Programs & Examples On #Gwt rpc

Google Web Toolkit - Remote Procedure Calls

How to restart service using command prompt?

To restart a running service:

net stop "service name" && net start "service name"

However, if you don't know if the service is running in the first place and want to restart or start it, use this:

net stop "service name" & net start "service name"

This works if the service is already running or not.

For reference, here is the documentation on conditional processing symbols.

How do I use namespaces with TypeScript external modules?

Try this namespaces module

namespaceModuleFile.ts

export namespace Bookname{
export class Snows{
    name:any;
    constructor(bookname){
        console.log(bookname);
    }
}
export class Adventure{
    name:any;
    constructor(bookname){
        console.log(bookname);
    }
}
}





export namespace TreeList{
export class MangoTree{
    name:any;
    constructor(treeName){
        console.log(treeName);
    }
}
export class GuvavaTree{
    name:any;
    constructor(treeName){
        console.log(treeName);
    }
}
}

bookTreeCombine.ts

---compilation part---

import {Bookname , TreeList} from './namespaceModule';
import b = require('./namespaceModule');
let BooknameLists = new Bookname.Adventure('Pirate treasure');
BooknameLists = new Bookname.Snows('ways to write a book'); 
const TreeLis = new TreeList.MangoTree('trees present in nature');
const TreeLists = new TreeList.GuvavaTree('trees are the celebraties');

Android: How to handle right to left swipe gestures

OnSwipeTouchListener.java:

import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener (Context ctx){
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                        result = true;
                    }
                }
                else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom();
                    } else {
                        onSwipeTop();
                    }
                    result = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }
}

Usage:

imageView.setOnTouchListener(new OnSwipeTouchListener(MyActivity.this) {
    public void onSwipeTop() {
        Toast.makeText(MyActivity.this, "top", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeRight() {
        Toast.makeText(MyActivity.this, "right", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeLeft() {
        Toast.makeText(MyActivity.this, "left", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeBottom() {
        Toast.makeText(MyActivity.this, "bottom", Toast.LENGTH_SHORT).show();
    }

});

What is the syntax for Typescript arrow functions with generics?

This works for me

const Generic = <T> (value: T) => {
    return value;
} 

Can I use CASE statement in a JOIN condition?

I took your example and edited it:

SELECT  *
FROM    sys.indexes i
    JOIN sys.partitions p
        ON i.index_id = p.index_id 
    JOIN sys.allocation_units a
        ON a.container_id = (CASE
           WHEN a.type IN (1, 3)
               THEN p.hobt_id 
           WHEN a.type IN (2)
               THEN p.partition_id
           ELSE NULL
           END)

How to retrieve the hash for the current commit in Git?

Here is one-liner in Bash shell using direct read from git files:

(head=($(<.git/HEAD)); cat .git/${head[1]})

You need to run above command in your git root folder.

This method can be useful when you've repository files, but git command has been not installed.

If won't work, check in .git/refs/heads folder what kind of heads do you have present.

Execute a large SQL script (with GO commands)

use the following method to split the string and execute batch by batch

using System;
using System.IO;
using System.Text.RegularExpressions;
namespace RegExTrial
{
    class Program
    {
        static void Main(string[] args)
        {
            string sql = String.Empty;
            string path=@"D:\temp\sample.sql";
            using (StreamReader reader = new StreamReader(path)) {
                sql = reader.ReadToEnd();
            }            
            //Select any GO (ignore case) that starts with at least 
            //one white space such as tab, space,new line, verticle tab etc
            string pattern="[\\s](?i)GO(?-i)";

            Regex matcher = new Regex(pattern, RegexOptions.Compiled);
            int start = 0;
            int end = 0;
            Match batch=matcher.Match(sql);
            while (batch.Success) {
                end = batch.Index;
                string batchQuery = sql.Substring(start, end - start).Trim();
                //execute the batch
                ExecuteBatch(batchQuery);
                start = end + batch.Length;
                batch = matcher.Match(sql,start);
            }

        }

        private static void ExecuteBatch(string command)
        { 
            //execute your query here
        }

    }
}

How to replace a hash key with another key

rails Hash has standard method for it:

hash.transform_keys{ |key| key.to_s.upcase }

http://api.rubyonrails.org/classes/Hash.html#method-i-transform_keys

UPD: ruby 2.5 method

Is there a way to make npm install (the command) to work behind proxy?

npm config set proxy <http://...>:<port_number>
npm config set registry http://registry.npmjs.org/

This solved my problem.

PyCharm error: 'No Module' when trying to import own module (python script)

PyCharm Community/Professional 2018.2.1

I was having this problem just now and I was able to solve it in sort of a similar way that @Beatriz Fonseca and @Julie pointed out.

If you go to File -> Settings -> Project: YourProjectName -> Project Structure, you'll have a directory layout of the project you're currently working in. You'll have to go through your directories and label them as being either the Source directory for all your Source files, or as a Resource folder for files that are strictly for importing.

You'll also want to make sure that you place __init__.py files within your resource directories, or really anywhere that you want to import from, and it'll work perfectly fine.

I hope this answer helps someone, and hopefully JetBrains will fix this annoying bug.

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

I am using Chosen. Look at: http://harvesthq.github.io/chosen/

It works on Firefox, Chrome, IE and Safari with the same style. But not on Mobile Devices.

What’s the best way to get an HTTP response code from a URL?

Addressing @Niklas R's comment to @nickanor's answer:

from urllib.error import HTTPError
import urllib.request

def getResponseCode(url):
    try:
        conn = urllib.request.urlopen(url)
        return conn.getcode()
    except HTTPError as e:
        return e.code

How does one use glide to download an image into a bitmap?

Kotlin's way -

fun Context.bitMapFromImgUrl(imageUrl: String, callBack: (bitMap: Bitmap) -> Unit) {
    GlideApp.with(this)
        .asBitmap()
        .load(imageUrl)
        .into(object : CustomTarget<Bitmap>() {
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                callBack(resource)
            }

            override fun onLoadCleared(placeholder: Drawable?) {
                // this is called when imageView is cleared on lifecycle call or for
                // some other reason.
                // if you are referencing the bitmap somewhere else too other than this imageView
                // clear it here as you can no longer have the bitmap
            }
        })
}

Fixed height and width for bootstrap carousel

set style="height:300px !important;" and "imgBanner" for img tag.

<img src="/image/1.jpg" class="imgBanner" style="width:100%; height:300px !important;">

then if you want responsive image, so you can use jquery as:

$.(function(){
   $(window).resize(respWhenResize);
   respWhenResize();
 })



respWhenResize(){
 
       if (pagesize < 578) {
         $('.imgBanner').css('height','200px')
        } else if (pagesize > 578 ) {
            $('.imgBanner').css('height','300px')
        }
     }

Convert string to date then format the date

String start_dt = "2011-01-31";

DateFormat parser = new SimpleDateFormat("yyyy-MM-dd"); 
Date date = (Date) parser.parse(start_dt);

DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); 
System.out.println(formatter.format(date));

Prints: 01-31-2011

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

When using bindParam() you must pass in a variable, not a constant. So before that line you need to create a variable and set it to null

$myNull = null;
$stmt->bindParam(':v1', $myNull, PDO::PARAM_NULL);

You would get the same error message if you tried:

$stmt->bindParam(':v1', 5, PDO::PARAM_NULL);

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Since you're using PHP, you will probably need to use the CURLOPT_PORT option, like so:

curl_setopt($ch, CURLOPT_PORT, 11740);

Bear in mind, you may face problems with SELinux:

Unable to make php curl request with port number

exclude @Component from @ComponentScan

The configuration seem alright, except that you should use excludeFilters instead of excludes:

@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
  @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}

Fatal error: [] operator not supported for strings

Solved!

$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';

How can I plot a confusion matrix?

IF you want more data in you confusion matrix, including "totals column" and "totals line", and percents (%) in each cell, like matlab default (see image below)

enter image description here

including the Heatmap and other options...

You should have fun with the module above, shared in the github ; )

https://github.com/wcipriano/pretty-print-confusion-matrix


This module can do your task easily and produces the output above with a lot of params to customize your CM: enter image description here

iOS 7 UIBarButton back button arrow color

To change the back button chevron color for a specific navigation controller*:

self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

*If you are using an app with more than 1 navigation controller, and you want this chevron color to apply to each, you may want to use the appearance proxy to set the back button chevron for every navigation controller, as follows:

[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

And for good measure, in swift (thanks to Jay Mayu in the comments):

UINavigationBar.appearance().tintColor = UIColor.whiteColor()

ImportError: DLL load failed: The specified module could not be found

(I found this answer from a video: http://www.youtube.com/watch?v=xmvRF7koJ5E)

  1. Download msvcp71.dll and msvcr71.dll from the web.

  2. Save them to your C:\Windows\System32 folder.

  3. Save them to your C:\Windows\SysWOW64 folder as well (if you have a 64-bit operating system).

Now try running your code file in Python and it will load the graph in couple of seconds.

How to enable directory listing in apache web server

Once I changed Options -Index to Options +Index in my conf file, I removed the welcome page and restarted services.

$ sudo rm -f /etc/httpd/conf.d/welcome.conf
$ sudo service httpd restart

I was able to see directory listings after that.

Comparing two strings in C?

if(strcmp(sr1,str2)) // this returns 0 if strings r equal 
    flag=0;
else flag=1; // then last check the variable flag value and print the message 

                         OR

char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);

for(int i=0;str1[i]!='\0';i++)
{
    if(str[i]==str2[i])
         flag=0;
    else {flag=1; break;}
}

 //check the value of flag if it is 0 then strings r equal simple :)

How to get a key in a JavaScript object by its value?

Keep it simple!

You don't need to filter the object through sophisticated methods or libs, Javascript has a built in function called Object.values.

Example:

let myObj = {jhon: {age: 20, job: 'Developer'}, marie: {age: 20, job: 
'Developer'}};

function giveMeTheObjectData(object, property) {
   return Object.values(object[property]);
}

giveMeTheObjectData(myObj, 'marie'); // => returns marie: {}

This will return the object property data.

References

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/values

Why is synchronized block better than synchronized method?

Difference between synchronized block and synchronized method are following:

  1. synchronized block reduce scope of lock, but synchronized method's scope of lock is whole method.
  2. synchronized block has better performance as only the critical section is locked but synchronized method has poor performance than block.
  3. synchronized block provide granular control over lock but synchronized method lock either on current object represented by this or class level lock.
  4. synchronized block can throw NullPointerException but synchronized method doesn't throw.
  5. synchronized block: synchronized(this){}

    synchronized method: public synchronized void fun(){}

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

If you generate new public ssh key and inserted it to bitbucket or github and

it not helped - please try to restart your PC. It helped me!!

Bootstrap combining rows (rowspan)

Check this one. hope it will help full for you.

http://jsfiddle.net/j6amM/

.row-fix { margin-bottom:20px;}

.row-fix > [class*="span"]{ height:100px; background:#f1f1f1;}

.row-fix .two-col{ background:none;}

.two-col > [class*="col"]{ height:40px; background:#ccc;}

.two-col > .col1{margin-bottom:20px;}

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

How can I write output from a unit test?

Try using TestContext.WriteLine() which outputs text in test results.

Example:

[TestClass]
public class UnitTest1
{
    private TestContext testContextInstance;

    /// <summary>
    /// Gets or sets the test context which provides
    /// information about and functionality for the current test run.
    /// </summary>
    public TestContext TestContext
    {
        get { return testContextInstance; }
        set { testContextInstance = value; }
    }

    [TestMethod]
    public void TestMethod1()
    {
        TestContext.WriteLine("Message...");
    }
}

The "magic" is described in MSDN:

To use TestContext, create a member and property within your test class [...] The test framework automatically sets the property, which you can then use in unit tests.

ViewPager PagerAdapter not updating the View

1.First you have to set the getItemposition method in your Pageradapter class 2.You have to read the Exact position of your View Pager 3.then send that position as data location of your new one 4.Write update button onclick listener inside the setonPageChange listener

that program code is little bit i modified to set the particular position element only

public class MyActivity extends Activity {

private ViewPager myViewPager;
private List<String> data;
public int location=0;
public Button updateButton;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    data = new ArrayList<String>();
    data.add("A");
    data.add("B");
    data.add("C");
    data.add("D");
    data.add("E");
    data.add("F");

    myViewPager = (ViewPager) findViewById(R.id.pager);
    myViewPager.setAdapter(new MyViewPagerAdapter(this, data));

      updateButton = (Button) findViewById(R.id.update);

    myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
             //Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPageSelected( int i) {
          // here you will get the position of selected page
            final int k = i;
             updateViewPager(k);

        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });
}

private void updateViewPager(final int i) {  
    updateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
            data.set(i, "Replaced "+i);         
            myViewPager.getAdapter().notifyDataSetChanged();
        }
    });

}

private class MyViewPagerAdapter extends PagerAdapter {

    private List<String> data;
    private Context ctx;

    public MyViewPagerAdapter(Context ctx, List<String> data) {
        this.ctx = ctx;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public Object instantiateItem(View collection, int position) {          

        TextView view = new TextView(ctx);
        view.setText(data.get(position));
        ((ViewPager)collection).addView(view);            
        return view;
    }

    @Override
    public void destroyItem(View collection, int position, Object view) {
         ((ViewPager) collection).removeView((View) view);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {
    }

    @Override
    public void startUpdate(View arg0) {
    }

    @Override
    public void finishUpdate(View arg0) {
    }
}
}

Convert a string date into datetime in Oracle

You can use a cast to char to see the date results

_x000D_
_x000D_
 select to_char(to_date('17-MAR-17 06.04.54','dd-MON-yy hh24:mi:ss'), 'mm/dd/yyyy hh24:mi:ss') from dual;
_x000D_
_x000D_
_x000D_

iOS how to set app icon and launch images

To save a bit time:

1) You can mark your app icon images all in finder and drag them into your Assets catalog all at once by dragging into one of the empty slots of the app icon imageset. When you hold your drag over the slot, several of the other slots look selected and when you drop those all will be filled up at once. Note that this works in XCode 8 (I haven't tried XCode 7), but in XCode 9 beta not yet.

Dragging into app icon Asset catalog imageset

2) The "Technical Q&A QA1686" apple documentation site has the sizes per app icon slot already calculated for you in a nice image and also contains the correct image names conventions.

App icon sizes

How to turn off page breaks in Google Docs?

Just double click on the break and it will collaspe. However, it will still display the line where it will break but it's better than downloading add-ons etc.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I was able to get around this loading the headers before the HTML with php, and it worked very well.

<?php 
header( 'X-UA-Compatible: IE=edge,chrome=1' );
header( 'content: width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' );
include('ix.html');
?> 

ix.html is the content I wanted to load after sending the headers.

CodeIgniter - File upload required validation

check this form validation extension library can help you to validate files, with current form validation when you validate upload field it treat as input filed where value is empty have look on this really good extension for form validation library

MY_Formvalidation

How to determine device screen size category (small, normal, large, xlarge) using code?

Copy and paste this code into your Activity and when it is executed it will Toast the device's screen size category.

int screenSize = getResources().getConfiguration().screenLayout &
        Configuration.SCREENLAYOUT_SIZE_MASK;

String toastMsg;
switch(screenSize) {
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        toastMsg = "Large screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        toastMsg = "Normal screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        toastMsg = "Small screen";
        break;
    default:
        toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

You don't need to instantiate an object, because yau are going to use a static variable: Console.WriteLine(Book.myInt);

When is a CDATA section necessary within a script tag?

Basically it is to allow to write a document that is both XHTML and HTML. The problem is that within XHTML, the XML parser will interpret the &,<,> characters in the script tag and cause XML parsing error. So, you can write your JavaScript with entities, e.g.:

if (a &gt; b) alert('hello world');

But this is impractical. The bigger problem is that if you read the page in HTML, the tag script is considered CDATA 'by default', and such JavaScript will not run. Therefore, if you want the same page to be OK both using XHTML and HTML parsers, you need to enclose the script tag in CDATA element in XHTML, but NOT to enclose it in HTML.

This trick marks the start of a CDATA element as a JavaScript comment; in HTML the JavaScript parser ignores the CDATA tag (it's a comment). In XHTML, the XML parser (which is run before the JavaScript) detects it and treats the rest until end of CDATA as CDATA.

React - How to pass HTML tags in props?

@matagus answer is fine for me, Hope below snippet is helped those who wish to use a variable inside.

const myVar = 'not';
<MyComponent text={["This is ", <strong>{`${myVar}`}</strong>,  "working."]} />

Benefits of using the conditional ?: (ternary) operator

A really cool usage is:

x = foo ? 1 :
    bar ? 2 :
    baz ? 3 :
          4;

What is a clearfix?

The other (and perhaps simplest) option for acheiving a clearfix is to use overflow:hidden; on the containing element. For example

_x000D_
_x000D_
.parent {_x000D_
  background: red;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.segment-a {_x000D_
  float: left;_x000D_
}_x000D_
.segment-b {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="segment-a">_x000D_
    Float left_x000D_
  </div>_x000D_
  <div class="segment-b">_x000D_
    Float right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Of course this can only be used in instances where you never wish the content to overflow.

Syntax for async arrow function

My async function

const getAllRedis = async (key) => {
  let obj = [];

  await client.hgetall(key, (err, object) => {
    console.log(object);
    _.map(object, (ob)=>{
      obj.push(JSON.parse(ob));
    })
    return obj;
    // res.send(obj);
});
}

How to make flexbox items the same size?

Im no expert with flex but I got there by setting the basis to 50% for the two items i was dealing with. Grow to 1 and shrink to 0.

Inline styling: flex: '1 0 50%',

When should I use GET or POST method? What's the difference between them?

I use GET when I'm retrieving information from a URL and POST when I'm sending information to a URL.

How to print out all the elements of a List in Java?

I wrote a dump function, which basicly prints out the public members of an object if it has not overriden toString(). One could easily expand it to call getters. Javadoc:

Dumps an given Object to System.out, using the following rules:

  • If the Object is Iterable, all of its components are dumped.
  • If the Object or one of its superclasses overrides toString(), the "toString" is dumped
  • Else the method is called recursively for all public members of the Object

/**
 * Dumps an given Object to System.out, using the following rules:<br>
 * <ul>
 * <li> If the Object is {@link Iterable}, all of its components are dumped.</li>
 * <li> If the Object or one of its superclasses overrides {@link #toString()}, the "toString" is dumped</li>
 * <li> Else the method is called recursively for all public members of the Object </li>
 * </ul>
 * @param input
 * @throws Exception
 */
public static void dump(Object input) throws Exception{
    dump(input, 0);
}

private static void dump(Object input, int depth) throws Exception{
    if(input==null){
        System.out.print("null\n"+indent(depth));
        return;
    }

    Class<? extends Object> clazz = input.getClass();
    System.out.print(clazz.getSimpleName()+" ");
    if(input instanceof Iterable<?>){
        for(Object o: ((Iterable<?>)input)){
            System.out.print("\n"+indent(depth+1));
            dump(o, depth+1);
        }
    }else if(clazz.getMethod("toString").getDeclaringClass().equals(Object.class)){
        Field[] fields = clazz.getFields();
        if(fields.length == 0){
            System.out.print(input+"\n"+indent(depth));
        }
        System.out.print("\n"+indent(depth+1));
        for(Field field: fields){
            Object o = field.get(input);
            String s = "|- "+field.getName()+": ";
            System.out.print(s);
            dump(o, depth+1);
        }
    }else{

        System.out.print(input+"\n"+indent(depth));
    }
}

private static String indent(int depth) {
    StringBuilder sb = new StringBuilder();
    for(int i=0; i<depth; i++)
        sb.append("  ");
    return sb.toString();
}

Am I trying to connect to a TLS-enabled daemon without TLS?

TLDR: This got my Python meetup group past this problem when I was running a clinic on installing docker and most of the users were on OS X:

boot2docker init
boot2docker up

run the export commands the output gives you, then

docker info

should tell you it works.


The Context (what brought us to the problem)

I led a clinic on installing docker and most attendees had OS X, and we ran into this problem and I overcame it on several machines. Here's the steps we followed:

First, we installed homebrew (yes, some attendees didn't have it):

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then we got cask, which we used to install virtualbox, and then used brew to install docker and boot2docker (all required for OS X) Don't use sudo for brew.:

brew install caskroom/cask/brew-cask
brew cask install virtualbox
brew install docker
brew install boot2docker

The Solution

That was when we ran into the problem the asker here got. The following fixed it. I understand init was a one-time deal, but you'll probably have to run up every time you start docker:

boot2docker init
boot2docker up

Then when up has been run, it gives several export commands. Copy-paste and run those.

Finally docker info should tell you it's properly installed.

To Demo

The rest of the commands should demo it. (on Ubuntu linux I required sudo.)

docker run hello-world
docker run -it ubuntu bash

Then you should be on a root shell in the container:

apt-get install nano
exit

Back to your native user bash:

docker ps -l

Look for the about 12 digit hexadecimal (0-9 or a-f) identifier under "Container ID", e.g. 456789abcdef. You can then commit your change and name it some descriptive name, like descriptivename:

docker commit 456789abcdef descriptivename`

How do I close a tkinter window?

raise SystemExit

this worked on the first try, where

self.destroy()
root.destroy()

did not

Experimental decorators warning in TypeScript compilation

If you using Deno JavaScript and TypeScript runtime and you enable experimentalDecorators:true in tsconfig.json or the VSCode ide settings. It will not work. According to Deno requirement, you need to provide tsconfig as a flag when running a Deno file. See Custom TypeScript Compiler Options

In my particular case I was running a Deno test and used.

$ deno test -c tsconfig.json

If it is a file, you have something like

 $ deno run -c tsconfig.json mod.ts

my tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "esnext"
  }
}

Unable to connect with remote debugger

Make sure that the node server to provide the bundle is running in the background. To run start the server use npm start or react-native start and keep the tab open during development

Check if option is selected with jQuery, if not select a default

Here is my function changing the selected option. It works for jQuery 1.3.2

function selectOption(select_id, option_val) {
    $('#'+select_id+' option:selected').removeAttr('selected');
    $('#'+select_id+' option[value='+option_val+']').attr('selected','selected');   
}

Why is __init__() always called after __new__()?

I think the simple answer to this question is that, if __new__ returns a value that is the same type as the class, the __init__ function executes, otherwise it won't. In this case your code returns A._dict('key') which is the same class as cls, so __init__ will be executed.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

Java2D: Increase the line width

What is Stroke:

The BasicStroke class defines a basic set of rendering attributes for the outlines of graphics primitives, which are rendered with a Graphics2D object that has its Stroke attribute set to this BasicStroke.

https://docs.oracle.com/javase/7/docs/api/java/awt/BasicStroke.html

Note that the Stroke setting:

Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));

is setting the line width,since BasicStroke(float width):

Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.

And, it also effects other methods like Graphics2D.drawLine(int x1, int y1, int x2, int y2) and Graphics2D.drawRect(int x, int y, int width, int height):

The methods of the Graphics2D interface that use the outline Shape returned by a Stroke object include draw and any other methods that are implemented in terms of that method, such as drawLine, drawRect, drawRoundRect, drawOval, drawArc, drawPolyline, and drawPolygon.

How to upgrade scikit-learn package in anaconda

So to upgrade scikit-learn package, you have to follow below process

Step-1: Open your terminal(Ctrl+Alt+t)

Step-2: Now for checking currently installed packages along with the versions installed on your conda environment by typing conda list

Step-3: Now for upgrade type below command

conda update scikit-learn

Hope it helps!!

Convert DataTable to IEnumerable<T>

Nothing wrong with that implementation. You might give the yield keyword a shot, see how you like it:

private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
    {
        foreach (DataRow row in dataTable.Rows)
        {
            yield return new TankReading
                                  {
                                      TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
                                      TankID = Convert.ToInt32(row["TankID"]),
                                      ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
                                      ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
                                      ReadingInches = Convert.ToInt32(row["ReadingInches"]),
                                      MaterialNumber = row["MaterialNumber"].ToString(),
                                      EnteredBy = row["EnteredBy"].ToString(),
                                      ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
                                      MaterialID = Convert.ToInt32(row["MaterialID"]),
                                      Submitted = Convert.ToBoolean(row["Submitted"]),
                                  };
        }

    }

Also the AsEnumerable isn't necessary, as List<T> is already an IEnumerable<T>

Is there a way to iterate over a range of integers?

If you want to just iterate over a range w/o using and indices or anything else, this code sample worked just fine for me. No extra declaration needed, no _. Haven't checked the performance, though.

for range [N]int{} {
    // Body...
}

P.S. The very first day in GoLang. Please, do critique if it's a wrong approach.

Unable to import path from django.urls

My assumption you already have settings on your urls.py

from django.urls import path, include 
# and probably something like this 
    urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]

and on your app you should have something like this blog/urls.py

 from django.urls import path

 from .views import HomePageView, CreateBlogView

 urlpatterns = [
   path('', HomePageView.as_view(), name='home'),
   path('post/', CreateBlogView.as_view(), name='add_blog')
 ]

if it's the case then most likely you haven't activated your environment try the following to activate your environment first pipenv shell if you still get the same error try this methods below

make sure Django is installed?? any another packages? i.e pillow try the following

pipenv install django==2.1.5 pillow==5.4.1

then remember to activate your environment

pipenv shell

after the environment is activated try running

python3 manage.py makemigrations

python3 manage.py migrate

then you will need to run

python3 manage.py runserver

I hope this helps

SyntaxError: Unexpected token o in JSON at position 1

Unexpected 'O' error is thrown when JSON data or String happens to get parsed.

If it's string, it's already stringfied. Parsing ends up with Unexpected 'O' error.

I faced similar( although in different context), I solved the following error by removing JSON Producer.

    @POST
    @Produces({ **MediaType.APPLICATION_JSON**})
    public Response login(@QueryParam("agentID") String agentID , Officer aOffcr ) {
      return Response.status(200).entity("OK").build();

  }

The response contains "OK" string return. The annotation marked as @Produces({ **MediaType.APPLICATION_JSON})** tries to parse the string to JSON format which results in Unexpected 'O'.

Removing @Produces({ MediaType.APPLICATION_JSON}) works fine. Output : OK

Beware: Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'

O is the first letter of the string

JSON.parse(object) compares with jQuery.parseJSON(object);

JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine

Function to Calculate a CRC16 Checksum

for (pos = 0; pos < len; pos++) {
    crc ^= (uint16_t)buf[pos];     // XOR byte into least sig. byte of crc

    for (i = 8; i != 0; i--) {     // Loop over each bit
        if ((crc & 0x0001) != 0) { // If the LSB is set
            crc >>= 1;             // Shift right and XOR 0xA001
            crc ^= CRC16;
        } else {                   // Else LSB is not set
            crc >>= 1;             // Just shift right
        }
     }
}

return crc;

JAVA_HOME is set to an invalid directory:

I am using using Ubuntu.

Problem for me solved by using sudo in terminal with the command.

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

When to use self over $this?

self (not $self) refers to the type of class, where as $this refers to the current instance of the class. self is for use in static member functions to allow you to access static member variables. $this is used in non-static member functions, and is a reference to the instance of the class on which the member function was called.

Because this is an object, you use it like: $this->member

Because self is not an object, it's basically a type that automatically refers to the current class, you use it like: self::member

Upload artifacts to Nexus, without Maven

You can use curl instead.

version=1.2.3
artifact="artifact"
repoId=repositoryId
groupId=org/myorg
REPO_URL=http://localhost:8081/nexus

curl -u username:password --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artefact/$version/$artifact-$version.tgz

Using PHP with Socket.io

It may be a little late for this question to be answered, but here is what I found.

I don't want to debate on the fact that nodes does that better than php or not, this is not the point.

The solution is : I haven't found any implementation of socket.io for PHP.

But there are some ways to implement WebSockets. There is this jQuery plugin allowing you to use Websockets while gracefully degrading for non-supporting browsers. On the PHP side, there is this class which seems to be the most widely used for PHP WS servers.

What's the difference between 'git merge' and 'git rebase'?

While the accepted and most upvoted answer is great, I additionally find it useful trying to explain the difference only by words:

merge

  • “okay, we got two differently developed states of our repository. Let's merge them together. Two parents, one resulting child.”

rebase

  • “Give the changes of the main branch (whatever its name) to my feature branch. Do so by pretending my feature work started later, in fact on the current state of the main branch.”
  • “Rewrite the history of my changes to reflect that.” (need to force-push them, because normally versioning is all about not tampering with given history)
  • “Likely —if the changes I raked in have little to do with my work— history actually won't change much, if I look at my commits diff by diff (you may also think of ‘patches’).“

summary: When possible, rebase is almost always better. Making re-integration into the main branch easier.

Because? ? your feature work can be presented as one big ‘patch file’ (aka diff) in respect to the main branch, not having to ‘explain’ multiple parents: At least two, coming from one merge, but likely many more, if there were several merges. Unlike merges, multiple rebases do not add up. (another big plus)

Default values and initialization in Java

Read your reference more carefully:

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

The following chart summarizes the default values for the above data types.

. . .

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

How to pass variables from one php page to another without form?

If you are trying to access the variable from another PHP file directly, you can include that file with include() or include_once(), giving you access to that variable. Note that this will include the entire first file in the second file.

Unix: How to delete files listed in a file

You could use '\n' for define the new line character as delimiter.

xargs -d '\n' rm < 1.txt

Be careful with the -rf because it can delete what you don't want to if the 1.txt contains paths with spaces. That's why the new line delimiter a bit safer.

On BSD systems, you could use -0 option to use new line characters as delimiter like this:

xargs -0 rm < 1.txt

Verify host key with pysftp

If You try to connect by pysftp to "normal" FTP You have to set hostkey to None.

import pysftp

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None 
with pysftp.Connection(host='****',username='****',password='***',port=22,cnopts=cnopts) as sftp:
    print('DO SOMETHING')

iOS 7: UITableView shows under status bar

Please note: This worked for me for the following configuration:

  • No navigation bar at the top of the screen (table view meets status bar)
  • Table view is non-scrollable

If the above two requirements aren't met your milage may vary.

Original Post

I created my view programmatically and this ended up working for me:

- (void) viewDidLayoutSubviews {
    // only works for iOS 7+
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        CGRect viewBounds = self.view.bounds;
        CGFloat topBarOffset = self.topLayoutGuide.length;

        // snaps the view under the status bar (iOS 6 style)
        viewBounds.origin.y = topBarOffset * -1;

        // shrink the bounds of your view to compensate for the offset
        viewBounds.size.height = viewBounds.size.height + (topBarOffset * -1);
        self.view.bounds = viewBounds;
    }
}

Source (in topLayoutGuide section at bottom of pg.39).

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

You need to install these packages:

sudo apt-get install libpq-dev python-dev libxml2-dev libxslt1-dev libldap2-dev libsasl2-dev libffi-dev

Convert to absolute value in Objective-C

You can use this function to get the absolute value:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}

Check if SQL Connection is Open or Closed

You should be using SqlConnection.State

e.g,

using System.Data;

if (myConnection != null && myConnection.State == ConnectionState.Closed)
{
   // do something
   // ...
}

Failed to load ApplicationContext from Unit Test: FileNotFound

For me, I was missing @ActiveProfile at my test class

@ActiveProfiles("sandbox")
class MyTestClass...

Abstract variables in Java?

Define a constructor in the abstract class which sets the field so that the concrete implementations are per the specification required to call/override the constructor.

E.g.

public abstract class AbstractTable {
    protected String name;

    public AbstractTable(String name) {
        this.name = name;
    }
}

When you extend AbstractTable, the class won't compile until you add a constructor which calls super("somename").

public class ConcreteTable extends AbstractTable {
    private static final String NAME = "concreteTable";

    public ConcreteTable() {
        super(NAME);
    }
}

This way the implementors are required to set name. This way you can also do (null)checks in the constructor of the abstract class to make it more robust. E.g:

public AbstractTable(String name) {
    if (name == null) throw new NullPointerException("Name may not be null");
    this.name = name;
}

Getting full URL of action in ASP.NET MVC

As Paddy mentioned: if you use an overload of UrlHelper.Action() that explicitly specifies the protocol to use, the generated URL will be absolute and fully qualified instead of being relative.

I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I suggest to write a custom extension method for the sake of readability:

/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
    string actionName, string controllerName, object routeValues = null)
{
    string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;

    return url.Action(actionName, controllerName, routeValues, scheme);
}

You can then simply use it like that in your view:

@Url.AbsoluteAction("Action", "Controller")

Is it possible to make desktop GUI application in .NET Core?

If you are using .NET Core 3.0 and above, do the following steps and you are good to go: (I'm going to use .NET Core CLI, but you can use Visual Studio too):

  1. md MyWinFormsApp optional step
  2. cd MyWinFormsApp optional step
  3. dotnet new sln -n MyWinFormsApp optional step, but it's a good idea
  4. dotnet new winforms -n MyWinFormsApp I'm sorry, this is not optional
  5. dotnet sln add MyWinFormsApp do this if you did step #3

Okay, you can stop reading my answer and start adding code to the MyWinFormsApp project. But if you want to work with Form Designer, keep reading.

  1. Open up MyWinFormsApp.csproj file and change <TargetFramework>netcoreapp3.1<TargetFramework> to <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks> (if you are using netcoreapp3.0 don't worry. Change it to <TargetFrameworks>net472;netcoreapp3.0</TargetFrameworks>)
  2. Then add the following ItemGroup
  <ItemGroup Condition="'$(TargetFramework)' == 'net472'">
    <Compile Update="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Update="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
  </ItemGroup>

After doing these steps, this is what you should end up with:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net472'">
    <Compile Update="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Update="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
  </ItemGroup>

</Project>
  1. Open up file Program.cs and add the following preprocessor-if
#if NETCOREAPP3_1
    Application.SetHighDpiMode(HighDpiMode.SystemAware);
#endif

Now you can open the MyWinFormsApp project using Visual Studio 2019 (I think you can use Visual Studio 2017 too, but I'm not sure) and double click on Form1.cs and you should see this:

Enter image description here

Okay, open up Toolbox (Ctrl + W, X) and start adding controls to your application and make it pretty.

You can read more about designer at Windows Forms .NET Core Designer.

How To Change DataType of a DataColumn in a DataTable?

I combined the efficiency of Mark's solution - so I do not have to .Clone the entire DataTable - with generics and extensibility, so I can define my own conversion function. This is what I ended up with:

/// <summary>
///     Converts a column in a DataTable to another type using a user-defined converter function.
/// </summary>
/// <param name="dt">The source table.</param>
/// <param name="columnName">The name of the column to convert.</param>
/// <param name="valueConverter">Converter function that converts existing values to the new type.</param>
/// <typeparam name="TTargetType">The target column type.</typeparam>
public static void ConvertColumnTypeTo<TTargetType>(this DataTable dt, string columnName, Func<object, TTargetType> valueConverter)
{
    var newType = typeof(TTargetType);

    DataColumn dc = new DataColumn(columnName + "_new", newType);

    // Add the new column which has the new type, and move it to the ordinal of the old column
    int ordinal = dt.Columns[columnName].Ordinal;
    dt.Columns.Add(dc);
    dc.SetOrdinal(ordinal);

    // Get and convert the values of the old column, and insert them into the new
    foreach (DataRow dr in dt.Rows)
    {
        dr[dc.ColumnName] = valueConverter(dr[columnName]);
    }

    // Remove the old column
    dt.Columns.Remove(columnName);

    // Give the new column the old column's name
    dc.ColumnName = columnName;
}

This way, usage is a lot more straightforward, while also customizable:

DataTable someDt = CreateSomeDataTable();
// Assume ColumnName is an int column which we want to convert to a string one.
someDt.ConvertColumnTypeTo<string>('ColumnName', raw => raw.ToString());

std::wstring VS std::string

1) As mentioned by Greg, wstring is helpful for internationalization, that's when you will be releasing your product in languages other than english

4) Check this out for wide character http://en.wikipedia.org/wiki/Wide_character

Integer ASCII value to character in BASH using printf

this prints all the "printable" characters of your basic bash setup:

printf '%b\n' $(printf '\\%03o' {30..127})

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

How to drop rows from pandas data frame that contains a particular string in a particular column?

If your string constraint is not just one string you can drop those corresponding rows with:

df = df[~df['your column'].isin(['list of strings'])]

The above will drop all rows containing elements of your list

SMTP error 554

Just had this issue with an Outlook client going through a Exchange server to an external address on Windows XP. Clearing the temp files seemed to do the trick.

how to get domain name from URL

I know the question is seeking a regex solution but in every attempt it won't work to cover everything

I decided to write this method in Python which only works with urls that have a subdomain (i.e. www.mydomain.co.uk) and not multiple level subdomains like www.mail.yahoo.com

def urlextract(url):
  url_split=url.split(".")
  if len(url_split) <= 2:
      raise Exception("Full url required with subdomain:",url)
  return {'subdomain': url_split[0], 'domain': url_split[1], 'suffix': ".".join(url_split[2:])}

How to properly use the "choices" field option in Django

I think no one actually has answered to the first question:

Why did they create those variables?

Those variables aren't strictly necessary. It's true. You can perfectly do something like this:

MONTH_CHOICES = (
    ("JANUARY", "January"),
    ("FEBRUARY", "February"),
    ("MARCH", "March"),
    # ....
    ("DECEMBER", "December"),
)

month = models.CharField(max_length=9,
                  choices=MONTH_CHOICES,
                  default="JANUARY")

Why using variables is better? Error prevention and logic separation.

JAN = "JANUARY"
FEB = "FEBRUARY"
MAR = "MAR"
# (...)

MONTH_CHOICES = (
    (JAN, "January"),
    (FEB, "February"),
    (MAR, "March"),
    # ....
    (DEC, "December"),
)

Now, imagine you have a view where you create a new Model instance. Instead of doing this:

new_instance = MyModel(month='JANUARY')

You'll do this:

new_instance = MyModel(month=MyModel.JAN)

In the first option you are hardcoding the value. If there is a set of values you can input, you should limit those options when coding. Also, if you eventually need to change the code at the Model layer, now you don't need to make any change in the Views layer.

Styling the last td in a table with css

Javascript is the only viable way to do this client side (that is, CSS won't help you). In jQuery:

$("table td:last").css("border", "none");

What causes a java.lang.StackOverflowError

I created a program with hibernate, in which I created two POJO classes, both with an object of each other as data members. When in the main method I tried to save them in the database I also got this error.

This happens because both of the classes are referring each other, hence creating a loop which causes this error.

So, check whether any such kind of relationships exist in your program.

Create two blank lines in Markdown

Backtick quotes with a space inside and two spaces to follow. Repeat as needed for more lines:

text1 text1
`(space)`(space)(space)
`(space)`(space)(space)
text2 text2

It looks decent in Markdown source:

text1 text1
` `  
` `  
text2 text2

How to find the location of the Scheduled Tasks folder

Looks like TaskCache registry data is in ...

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache

... on my Windows 10 PC (i.e. add Schedule before TaskCache and TaskCache has an upper case C).

Converting a Uniform Distribution to a Normal Distribution

This is a Matlab implementation using the polar form of the Box-Muller transformation:

Function randn_box_muller.m:

function [values] = randn_box_muller(n, mean, std_dev)
    if nargin == 1
       mean = 0;
       std_dev = 1;
    end

    r = gaussRandomN(n);
    values = r.*std_dev - mean;
end

function [values] = gaussRandomN(n)
    [u, v, r] = gaussRandomNValid(n);

    c = sqrt(-2*log(r)./r);
    values = u.*c;
end

function [u, v, r] = gaussRandomNValid(n)
    r = zeros(n, 1);
    u = zeros(n, 1);
    v = zeros(n, 1);

    filter = r==0 | r>=1;

    % if outside interval [0,1] start over
    while n ~= 0
        u(filter) = 2*rand(n, 1)-1;
        v(filter) = 2*rand(n, 1)-1;
        r(filter) = u(filter).*u(filter) + v(filter).*v(filter);

        filter = r==0 | r>=1;
        n = size(r(filter),1);
    end
end

And invoking histfit(randn_box_muller(10000000),100); this is the result: Box-Muller Matlab Histfit

Obviously it is really inefficient compared with the Matlab built-in randn.

How do I list all tables in all databases in SQL Server in a single result set?

I posted an answer a while back here that you could use here. The outline is:

  • Create a temp table
  • Call sp_msForEachDb
  • The query run against each DB stores the data in the temp table
  • When done, query the temp table

Bootstrap 3 - How to load content in modal body via AJAX?

I guess you're searching for this custom function. It takes a data-toggle attribute and creates dynamically the necessary div to place the remote content. Just place the data-toggle="ajaxModal" on any link you want to load via AJAX.

The JS part:

$('[data-toggle="ajaxModal"]').on('click',
              function(e) {
                $('#ajaxModal').remove();
                e.preventDefault();
                var $this = $(this)
                  , $remote = $this.data('remote') || $this.attr('href')
                  , $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
                $('body').append($modal);
                $modal.modal({backdrop: 'static', keyboard: false});
                $modal.load($remote);
              }
            );

Finally, in the remote content, you need to put the entire structure to work.

<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
            <a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
            <a href="#" class="btn btn-primary">Button</a>
            <a href="#" class="btn btn-primary">Another button...</a>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

How do I remove javascript validation from my eclipse project?

Go to Windows->Preferences->Validation.

There would be a list of validators with checkbox options for Manual & Build, go and individually disable the javascript validator there.

If you select the Suspend All Validators checkbox on the top it doesn't necessarily take affect.

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

I think i understand what the reason of your error. First you click auto AUTO INCREMENT field then select it as a primary key.

The Right way is First You have to select it as a primary key then you have to click auto AUTO INCREMENT field.

Very easy. Thanks

Update multiple rows with different values in a single SQL query

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

You could do:

 UPDATE table SET posX=CASE
      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ...
      ELSE posX END, posY = CASE ... END
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

Otherwise, I'd try with indexing on id, or modifying the architecture.

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

How to implement a tree data-structure in Java?

Here:

public class Tree<T> {
    private Node<T> root;

    public Tree(T rootData) {
        root = new Node<T>();
        root.data = rootData;
        root.children = new ArrayList<Node<T>>();
    }

    public static class Node<T> {
        private T data;
        private Node<T> parent;
        private List<Node<T>> children;
    }
}

That is a basic tree structure that can be used for String or any other object. It is fairly easy to implement simple trees to do what you need.

All you need to add are methods for add to, removing from, traversing, and constructors. The Node is the basic building block of the Tree.

cURL POST command line on WINDOWS RESTful service

We can use below Curl command in Windows Command prompt to send the request. Use the Curl command below, replace single quote with double quotes, remove quotes where they are not there in below format and use the ^ symbol.

curl http://localhost:7101/module/url ^
  -d @D:/request.xml ^
  -H "Content-Type: text/xml" ^
  -H "SOAPAction: process" ^
  -H "Authorization: Basic xyz" ^
  -X POST

ImportError: No module named Image

On a system with both Python 2 and 3 installed and with pip2-installed Pillow failing to provide Image, it is possible to install PIL for Python 2 in a way that will solve ImportError: No module named Image:

easy_install-2.7 --user PIL

or

sudo easy_install-2.7 PIL

$location / switching between html5 and hashbang mode / link rewriting

The documentation is not very clear about AngularJS routing. It talks about Hashbang and HTML5 mode. In fact, AngularJS routing operates in three modes:

  • Hashbang Mode
  • HTML5 Mode
  • Hashbang in HTML5 Mode

For each mode there is a a respective LocationUrl class (LocationHashbangUrl, LocationUrl and LocationHashbangInHTML5Url).

In order to simulate URL rewriting you must actually set html5mode to true and decorate the $sniffer class as follows:

$provide.decorator('$sniffer', function($delegate) {
  $delegate.history = false;
  return $delegate;
});

I will now explain this in more detail:

Hashbang Mode

Configuration:

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
});
$locationProvider
  .html5Mode(false)
  .hashPrefix('!');

This is the case when you need to use URLs with hashes in your HTML files such as in

<a href="index.html#!/path">link</a>

In the Browser you must use the following Link: http://www.example.com/base/index.html#!/base/path

As you can see in pure Hashbang mode all links in the HTML files must begin with the base such as "index.html#!".

HTML5 Mode

Configuration:

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true);

You should set the base in HTML-file

<html>
  <head>
    <base href="/">
  </head>
</html>

In this mode you can use links without the # in HTML files

<a href="/path">link</a>

Link in Browser:

http://www.example.com/base/path

Hashbang in HTML5 Mode

This mode is activated when we actually use HTML5 mode but in an incompatible browser. We can simulate this mode in a compatible browser by decorating the $sniffer service and setting history to false.

Configuration:

$provide.decorator('$sniffer', function($delegate) {
  $delegate.history = false;
  return $delegate;
});
$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true)
  .hashPrefix('!');

Set the base in HTML-file:

<html>
  <head>
    <base href="/">
  </head>
</html>

In this case the links can also be written without the hash in the HTML file

<a href="/path">link</a>

Link in Browser:

http://www.example.com/index.html#!/base/path

Where to change the value of lower_case_table_names=2 on windows xampp

ADD following -

  • look up for: # The MySQL server [mysqld]
  • add this right below it: lower_case_table_names = 1 In file - /etc/mysql/mysql.conf.d/mysqld.cnf

It's works for me.

OperationalError, no such column. Django

You did every thing correct, I have been gone through same problem. First delete you db and migrations I solved my adding name of my app in makemigrations:

python manage.py makemigrations appname
python manage.py migrate

This will definitely work.

How can I extract audio from video with ffmpeg?

To extract the audio stream without re-encoding:

ffmpeg -i input-video.avi -vn -acodec copy output-audio.aac
  • -vn is no video.
  • -acodec copy says use the same audio stream that's already in there.

Read the output to see what codec it is, to set the right filename extension.

Pass react component as props

As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:

https://reactjs.org/docs/composition-vs-inheritance.html

Make sure you are actually passing a component and not an object (this tripped me up initially).

The code is simply this:

const Parent = () => { 
  return (
    <Child  componentToPassDown={<SomeComp />}  />
  )
}

const Child = ({ componentToPassDown }) => { 
  return (
    <>
     {componentToPassDown}  
    </>
  )
}

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Getting mouse position in c#

You must also have the following imports in order to import the DLL

using System.Runtime.InteropServices;
using System.Diagnostics;

What is a Subclass

A sub class is a small file of a program that extends from some other class. For example you make a class about cars in general and have basic information that holds true for all cars with your constructors and stuff then you have a class that extends from that on a more specific car or line of cars that would have new variables/methods. I see you already have plenty of examples of code from above by the time I get to post this but I hope this description helps.

Insert HTML from CSS

No you cannot. The only thing you can do is to insert content. Like so:

p:after {
    content: "yo";
}

How do I select which GPU to run a job on?

Set the following two environment variables:

NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0

where gpu_id is the ID of your selected GPU, as seen in the host system's nvidia-smi (a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).

You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id parameter in nvidia-smi run in a terminal in the guest system).

More info

This method based on NVIDIA_VISIBLE_DEVICES exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).

Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0 or env in Kubernetes or Openshift.

If you want GPU load-balancing, make gpu_id random at each guest system start.

If setting this with python, make sure you are using strings for all environment variables, including numerical ones.

You can verify that a different card is selected for each value of gpu_id by inspecting nvidia-smi's Bus-Id parameter (in a terminal run in the guest system).

The accepted solution based on CUDA_VISIBLE_DEVICES alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).

This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).

This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.

Disable form autofill in Chrome without disabling autocomplete

You better use disabled for your inputs, in order to prevent auto-completion.

<input type="password" ... disabled />

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

In VB.NET while trying to connect to Rackspace's SSL port on 465 I encountered the same issue (requires implicit SSL). I made use of https://www.nuget.org/packages/MailKit/ in order to successfully connect.

The following is an example of an HTML email message.

Imports MailKit.Net.Smtp
Imports MailKit
Imports MimeKit

Sub somesub()
    Dim builder As New BodyBuilder()
    Dim mail As MimeMessage
    mail = New MimeMessage()
    mail.From.Add(New MailboxAddress("", c_MailUser))
    mail.To.Add(New MailboxAddress("", c_ToUser))
    mail.Subject = "Mail Subject"
    builder.HtmlBody = "<html><body>Body Text"
    builder.HtmlBody += "</body></html>"
      mail.Body = builder.ToMessageBody()

      Using client As New SmtpClient
        client.Connect(c_MailServer, 465, True)
        client.AuthenticationMechanisms.Remove("XOAUTH2") ' Do not use OAUTH2
        client.Authenticate(c_MailUser, c_MailPassword) ' Use a username / password to authenticate.
        client.Send(mail)
        client.Disconnect(True)
    End Using 

End Sub

How do I get bit-by-bit data from an integer value in C?

If you want the k-th bit of n, then do

(n & ( 1 << k )) >> k

Here we create a mask, apply the mask to n, and then right shift the masked value to get just the bit we want. We could write it out more fully as:

    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;

You can read more about bit-masking here.

Here is a program:

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

int *get_bits(int n, int bitswanted){
  int *bits = malloc(sizeof(int) * bitswanted);

  int k;
  for(k=0; k<bitswanted; k++){
    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;
    bits[k] = thebit;
  }

  return bits;
}

int main(){
  int n=7;

  int  bitswanted = 5;

  int *bits = get_bits(n, bitswanted);

  printf("%d = ", n);

  int i;
  for(i=bitswanted-1; i>=0;i--){
    printf("%d ", bits[i]);
  }

  printf("\n");
}

How to concat two ArrayLists?

You can use .addAll() to add the elements of the second list to the first:

array1.addAll(array2);

Edit: Based on your clarification above ("i want a single String in the new Arraylist which has both name and number."), you would want to loop through the first list and append the item from the second list to it.

Something like this:

int length = array1.size();
if (length != array2.size()) { // Too many names, or too many numbers
    // Fail
}
ArrayList<String> array3 = new ArrayList<String>(length); // Make a new list
for (int i = 0; i < length; i++) { // Loop through every name/phone number combo
    array3.add(array1.get(i) + " " + array2.get(i)); // Concat the two, and add it
}

If you put in:

array1 : ["a", "b", "c"]
array2 : ["1", "2", "3"]

You will get:

array3 : ["a 1", "b 2", "c 3"]

How to get the first column of a pandas DataFrame as a Series?

This works great when you want to load a series from a csv file

x = pd.read_csv('x.csv', index_col=False, names=['x'],header=None).iloc[:,0]
print(type(x))
print(x.head(10))


<class 'pandas.core.series.Series'>
0    110.96
1    119.40
2    135.89
3    152.32
4    192.91
5    177.20
6    181.16
7    177.30
8    200.13
9    235.41
Name: x, dtype: float64

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

You can use general compound drawable implementation, but if you need to define a size of drawable use this library:

https://github.com/a-tolstykh/textview-rich-drawable

Here is a small example of usage:

<com.tolstykh.textviewrichdrawable.TextViewRichDrawable
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some text"
        app:compoundDrawableHeight="24dp"
        app:compoundDrawableWidth="24dp" />

Excel - match data from one range to another and get the value from the cell to the right of the matched data

I have added the following on my excel sheet

=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)

Still doesn't seem to work. I get an #N/A
BUT

=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)

Works

How do I remove a single breakpoint with GDB?

Use:

clear fileName:lineNum   // Removes all breakpoints at the specified line.
delete breakpoint number // Delete one breakpoint whose number is 'number'

How to sort by dates excel?

The problem in here is ms excel not recognizing the things which we entered as date, though is appears as date in menu bar. Select cell and type "=istext(cell ad)" then you can see it "TRUE" hence still your date ms excel thinks as a text that is why it aligns to left automatically. So we should change the type of text. There are many types of changing methods. but I think this too easy and lets do it now.

SELECT THE CELLS -> Go DATA in menu bar -> Then select "Text to Columns" object -> Select "Delimited" in first window then click next -> remove all ticks in the second window and hit next button -> last window select the "Date" and select your prefer date format then hit the finish button.(Then dates look like Wednesday, March 14, 2012) Then you can using previously used formula use and check whether our date is recognized in excel. Then you can Sort as you want. Thank you

getch and arrow codes

The keypad will allow the keyboard of the user's terminal to allow for function keys to be interpreted as a single value (i.e. no escape sequence).

As stated in the man page:

The keypad option enables the keypad of the user's terminal. If enabled (bf is TRUE), the user can press a function key (such as an arrow key) and wgetch returns a single value representing the function key, as in KEY_LEFT. If disabled (bf is FALSE), curses does not treat function keys specially and the program has to interpret the escape sequences itself. If the keypad in the terminal can be turned on (made to transmit) and off (made to work locally), turning on this option causes the terminal keypad to be turned on when wgetch is called. The default value for keypad is false.

What is the purpose and use of **kwargs?

You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

>>> def print_keyword_args(**kwargs):
...     # kwargs is a dict of the keyword args passed to the function
...     for key, value in kwargs.iteritems():
...         print "%s = %s" % (key, value)
... 
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe

You can also use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:

>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith

The Python Tutorial contains a good explanation of how it works, along with some nice examples.

<--Update-->

For people using Python 3, instead of iteritems(), use items()

How to resolve 'npm should be run outside of the node repl, in your normal shell'

For Windows users, run npm commands from the Command Prompt (cmd.exe), not Node.Js (node.exe). So your "normal shell" is cmd.exe. (I agree this message can be confusing for a Windows, Node newbie.)

By the way, the Node.js Command Prompt is actually just an easy shortcut to cmd.exe.

Below is an example screenshot for installing grunt from cmd.exe:

enter image description here

How to access single elements in a table in R

Maybe not so perfect as above ones, but I guess this is what you were looking for.

data[1:1,3:3]    #works with positive integers
data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
data[i:i,j:j]    #given that i and j are positive integers

Here indexing will work from 1, i.e,

data[1:1,1:1]    #means the top-leftmost element

Remove Identity from a column in a table

ALTER TABLE tablename add newcolumn int
update tablename set newcolumn=existingcolumnname
ALTER TABLE tablename DROP COLUMN existingcolumnname;
EXEC sp_RENAME 'tablename.oldcolumn' , 'newcolumnname', 'COLUMN'

However above code works only if no primary-foreign key relation

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

How to present UIAlertController when not in a view controller?

Swift 5

It's important to hide the window after showing the message.

func showErrorMessage(_ message: String) {
    let alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.rootViewController = UIViewController()

    let alertController = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertController.Style.alert)
    alertController.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.cancel, handler: { _ in
        alertWindow.isHidden = true
    }))
    
    alertWindow.windowLevel = UIWindow.Level.alert + 1;
    alertWindow.makeKeyAndVisible()
    alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)
}

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

How does OAuth 2 protect against things like replay attacks using the Security Token?

The other answer is very detailed and addresses the bulk of the questions raised by the OP.

To elaborate, and specifically to address the OP's question of "How does OAuth 2 protect against things like replay attacks using the Security Token?", there are two additional protections in the official recommendations for implementing OAuth 2:

1) Tokens will usually have a short expiration period (http://tools.ietf.org/html/rfc6819#section-5.1.5.3):

A short expiration time for tokens is a means of protection against the following threats:

  • replay...

2) When the token is used by Site A, the recommendation is that it will be presented not as URL parameters but in the Authorization request header field (http://tools.ietf.org/html/rfc6750):

Clients SHOULD make authenticated requests with a bearer token using the "Authorization" request header field with the "Bearer" HTTP authorization scheme. ...

The "application/x-www-form-urlencoded" method SHOULD NOT be used except in application contexts where participating browsers do not have access to the "Authorization" request header field. ...

URI Query Parameter... is included to document current use; its use is not recommended, due to its security deficiencies

Accessing last x characters of a string in Bash

Another workaround is to use grep -o with a little regex magic to get three chars followed by the end of line:

$ foo=1234567890
$ echo $foo | grep -o ...$
890

To make it optionally get the 1 to 3 last chars, in case of strings with less than 3 chars, you can use egrep with this regex:

$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd

You can also use different ranges, such as 5,10 to get the last five to ten chars.

Select data from "show tables" MySQL query

SELECT * FROM INFORMATION_SCHEMA.TABLES

That should be a good start. For more, check INFORMATION_SCHEMA Tables.

Oracle SQL - DATE greater than statement

As your query string is a literal, and assuming your dates are properly stored as DATE you should use date literals:

SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'

If you want to use TO_DATE (because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
                           'NLS_DATE_LANGUAGE = American');

JavaScript: Passing parameters to a callback function

Your question is unclear. If you're asking how you can do this in a simpler way, you should take a look at the ECMAScript 5th edition method .bind(), which is a member of Function.prototype. Using it, you can do something like this:

function tryMe (param1, param2) {
    alert (param1 + " and " + param2);
}

function callbackTester (callback) {
    callback();
}

callbackTester(tryMe.bind(null, "hello", "goodbye"));

You can also use the following code, which adds the method if it isn't available in the current browser:

// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
  Function.prototype.bind = function(){ 
    var fn = this, args = Array.prototype.slice.call(arguments),
        object = args.shift(); 
    return function(){ 
      return fn.apply(object, 
        args.concat(Array.prototype.slice.call(arguments))); 
    }; 
  };
}

Example

bind() - PrototypeJS Documentation

How to find the difference in days between two dates?

The bash way - convert the dates into %y%m%d format and then you can do this straight from the command line:

echo $(( ($(date --date="031122" +%s) - $(date --date="021020" +%s) )/(60*60*24) ))

Java Round up Any Number

Math.ceil() is the correct function to call. I'm guessing a is an int, which would make a / 100 perform integer arithmetic. Try Math.ceil(a / 100.0) instead.

int a = 142;
System.out.println(a / 100);
System.out.println(Math.ceil(a / 100));
System.out.println(a / 100.0);
System.out.println(Math.ceil(a / 100.0));
System.out.println((int) Math.ceil(a / 100.0));

Outputs:

1
1.0
1.42
2.0
2

See http://ideone.com/yhT0l

Delete last commit in bitbucket

Once changes has been committed it will not be able to delete. because commit's basic nature is not to delete.

Thing you can do (easy and safe method),

Interactive Rebase:

1) git rebase -i HEAD~2 #will show your recent 2 commits

2) Your commit will list like , Recent will appear at the bottom of the page LILO(last in Last Out)

enter image description here

Delete the last commit row entirely

3) save it by ctrl+X or ESC:wq

now your branch will updated without your last commit..

MongoDB distinct aggregation

SQL Query: (group by & count of distinct)

select city,count(distinct(emailId)) from TransactionDetails group by city;

Equivalent mongo query would look like this:

db.TransactionDetails.aggregate([ 
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} } 
]);

Does calling clone() on an array also clone its contents?

The clone is a shallow copy of the array.

This test code prints:

[1, 2] / [1, 2]
[100, 200] / [100, 2]

because the MutableInteger is shared in both arrays as objects[0] and objects2[0], but you can change the reference objects[1] independently from objects2[1].

import java.util.Arrays;                                                                                                                                 

public class CloneTest {                                                                                                                                 
    static class MutableInteger {                                                                                                                        
        int value;                                                                                                                                       
        MutableInteger(int value) {                                                                                                                      
            this.value = value;                                                                                                                          
        }                                                                                                                                                
        @Override                                                                                                                                        
        public String toString() {                                                                                                                       
            return Integer.toString(value);                                                                                                              
        }                                                                                                                                                
    }                                                                                                                                                    
    public static void main(String[] args) {                                                                                                             
        MutableInteger[] objects = new MutableInteger[] {
                new MutableInteger(1), new MutableInteger(2) };                                                
        MutableInteger[] objects2 = objects.clone();                                                                                                     
        System.out.println(Arrays.toString(objects) + " / " + 
                            Arrays.toString(objects2));                                                                
        objects[0].value = 100;                                                                                                                          
        objects[1] = new MutableInteger(200);                                                                                                            
        System.out.println(Arrays.toString(objects) + " / " + 
                            Arrays.toString(objects2));                                                               
    }                                                                                                                                                    
}                                                                                                                                                        

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

What is the size of a pointer?

Recently came upon a case where this was not true, TI C28x boards can have a sizeof pointer == 1, since a byte for those boards is 16-bits, and pointer size is 16 bits. To make matters more confusing, they also have far pointers which are 22-bits. I'm not really sure what sizeof far pointer would be.

In general, DSP boards can have weird integer sizes.

So pointer sizes can still be weird in 2020 if you are looking in weird places

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).

.carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
          transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
  z-index: 2;
}

Jackson serialization: ignore empty values (or null)

I was having similar problem recently with version 2.6.6.

@JsonInclude(JsonInclude.Include.NON_NULL)

Using above annotation either on filed or class level was not working as expected. The POJO was mutable where I was applying the annotation. When I changed the behaviour of the POJO to be immutable the annotation worked its magic.

I am not sure if its down to new version or previous versions of this lib had similar behaviour but for 2.6.6 certainly you need to have Immutable POJO for the annotation to work.

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Above option mentioned in various answers of setting serialisation inclusion in ObjectMapper directly at global level works as well but, I prefer controlling it at class or filed level.

So if you wanted all the null fields to be ignored while JSON serialisation then use the annotation at class level but if you want only few fields to ignored in a class then use it over those specific fields. This way its more readable & easy for maintenance if you wanted to change behaviour for specific response.

Is it possible to decompile an Android .apk file?

Decompilation of APK file is possible. But it might be difficult to understand the code if it is obfuscated.

ApkTool to view resources inside APK File

  • Extracts AndroidManifest.xml and everything in res folder(layout xml files, images, htmls used on webview etc..)
  • command : apktool.bat d sampleApp.apk
  • NOTE: You can achieve this by using zip utility like 7-zip. But, It also extracts the .smali file of all .class files.

Using dex2jar

  • Generates .jar file from .apk file, we need JD-GUI to view the source code from this .jar.
  • command : dex2jar sampleApp.apk

Decompiling .jar using JD-GUI

  • decompiles the .class files (obfuscated- in a case of the android app, but a readable original code is obtained in a case of other .jar file). i.e., we get .java back from the application.

How to find a string inside a entire database?

Here are couple more free tools that can be used for this. Both work as SSMS addins.

ApexSQL Search – 100% free - searches both schema and data in tables. Has couple more useful options such as dependency tracking…

SSMS Tools pack – free for all versions except SQL 2012 – doesn’t look as advanced as previous one but has a lot of other cool features.

PHP Pass variable to next page

Passing data in the request

You could either embed it as a hidden field in your form, or add it your forms action URL

 echo '<input type="hidden" name="myVariable" value="'.
     htmlentities($myVariable).'">';

or

echo '<form method="POST" action="Page2.php?myVariable='.
    urlencode($myVariable).'">";

Note this also illustrates the use of htmlentities and urlencode when passing data around.

Passing data in the session

If the data doesn't need to be passed to the client side, then sessions may be more appropriate. Simply call session_start() at the start of each page, and you can get and set data into the $_SESSION array.

Security

Since you state your value is actually a filename, you need to be aware of the security ramifications. If the filename has arrived from the client side, assume the user has tampered with the value. Check it for validity! What happens when the user passes the path to an important system file, or a file under their control? Can your script be used to "probe" the server for files that do or do not exist?

As you are clearly just getting started here, its worth reminding that this goes for any data which arrives in $_GET, $_POST or $_COOKIE - assume your worst enemy crafted the contents of those arrays, and code accordingly!

COALESCE with Hive SQL

Since 0.11 hive has a NVL function nvl(T value, T default_value)

which says Returns default value if value is null else returns value

Java split string to array

Consider this example:

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|")));
    // output : [Real, How, To]
  }
}

The result does not include the empty strings between the "|" separator. To keep the empty strings :

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|", -1)));
    // output : [Real, How, To, , , ]
  }
}

For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html

Should I use the Reply-To header when sending emails as a service to others?

You may want to consider placing the customer's name in the From header and your address in the Sender header:

From: Company A <[email protected]>
Sender: [email protected]

Most mailers will render this as "From [email protected] on behalf of Company A", which is accurate. And then a Reply-To of Company A's address won't seem out of sorts.

From RFC 5322:

The "From:" field specifies the author(s) of the message, that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. The "Sender:" field specifies the mailbox of the agent responsible for the actual transmission of the message. For example, if a secretary were to send a message for another person, the mailbox of the secretary would appear in the "Sender:" field and the mailbox of the actual author would appear in the "From:" field.

PySpark 2.0 The size or shape of a DataFrame

Use df.count() to get the number of rows.

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

A popular Linux library which has similar functionality would be ncurses.

How to get config parameters in Symfony2 Twig Templates

You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:

# app/config/parameters.yml
parameters:
    ga_tracking: UA-xxxxx-x

# app/config/config.yml
twig:
    globals:
        ga_tracking: "%ga_tracking%"

Now, the variable ga_tracking is available in all Twig templates:

<p>The google tracking code is: {{ ga_tracking }}</p>

The parameter is also available inside the controllers:

$this->container->getParameter('ga_tracking');

You can also define a service as a global Twig variable (Symfony2.2+):

# app/config/config.yml
twig:
    # ...
    globals:
        user_management: "@acme_user.user_management"

http://symfony.com/doc/current/templating/global_variables.html

If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.

Oracle query to identify columns having special characters

I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.

Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition

SELECT * FROM test WHERE REGEXP_LIKE(sampletext,  '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );

Embed website into my site

You might want to check HTML frames, which can do pretty much exactly what you are looking for. They are considered outdated however.

How to increase executionTimeout for a long-running query?

When a query takes that long, I would advice to run it asynchronously and use a callback function for when it's complete.

I don't have much experience with ASP.NET, but maybe you can use AJAX for this asynchronous behavior.

Typically a web page should load in mere seconds, not minutes. Don't keep your users waiting for so long!

IntelliJ does not show project folders

Select the module settings and do these changes, it will work

In File > Project Structure > Modules, click the "+" button,

add new module as per your project specific like Java or RUBY or something then apply and ok

A cycle was detected in the build path of project xxx - Build Path Problem

When I've had these problems it always has been a true cycle in the dependencies expressed in Manifest.mf

So open the manifest of the project in question, on the Dependencies Tab, look at the "Required Plugins" entry. Then follow from there to the next project(s), and repeat eventually the cycle will become clear.

You can simpify this task somewhat by using the Dependency Analysis links in the bottom right corner of the Dependencies Tab, this has cycle detection and easier navigation depdendencies.

I also don't know why Maven is more tolerant,

Postman: How to make multiple requests at the same time

Not sure if people are still looking for simple solutions to this, but you are able to run multiple instances of the "Collection Runner" in Postman. Just create a runner with some requests and click the "Run" button multiple times to bring up multiple instances.

Change WPF window background image in C# code

What about this:

new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "Images/icon.png")))

or alternatively, this:

this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/myapp;component/Images/icon.png")));

How to install easy_install in Python 2.7.1 on Windows 7

That tool is part of the setuptools (now called Distribute) package. Install Distribute. Of course you'll have to fetch that one manually.

http://pypi.python.org/pypi/distribute#installation-instructions

How can I open the interactive matplotlib window in IPython notebook?

I'm using ipython in "jupyter QTConsole" from Anaconda at www.continuum.io/downloads on 5/28/20117.

Here's an example to flip back and forth between a separate window and an inline plot mode using ipython magic.

>>> import matplotlib.pyplot as plt

# data to plot
>>> x1 = [x for x in range(20)]

# Show in separate window
>>> %matplotlib
>>> plt.plot(x1)
>>> plt.close() 

# Show in console window
>>> %matplotlib inline
>>> plt.plot(x1)
>>> plt.close() 

# Show in separate window
>>> %matplotlib
>>> plt.plot(x1)
>>> plt.close() 

# Show in console window
>>> %matplotlib inline
>>> plt.plot(x1)
>>> plt.close() 

# Note: the %matplotlib magic above causes:
#      plt.plot(...) 
# to implicitly include a:
#      plt.show()
# after the command.
#
# (Not sure how to turn off this behavior
# so that it matches behavior without using %matplotlib magic...)
# but its ok for interactive work...

Restoring MySQL database from physical files

I once copied these files to the database storage folder for a mysql database which was working, started the db and waited for it to "repair" the files, then extracted them with mysqldump.

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

Every ComboBoxItem instance has PreviewMouseDown event. If you will subscribe your custom handler on this event on every ComboBoxItem you will have opportunity to handle every click on the dropdown list.

// Subscribe on ComboBoxItem-s events.
comboBox.Items.Cast<ComboBoxItem>().ToList().ForEach(i => i.PreviewMouseDown += ComboBoxItem_PreviewMouseDown);

private void ComboBoxItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
     // your handler logic...         
}

Why is C so fast, and why aren't other languages as fast or faster?

There isn't much that's special about C. That's one of the reasons why it's fast.

Newer languages which have support for garbage collection, dynamic typing and other facilities which make it easier for the programmer to write programs.

The catch is, there is additional processing overhead which will degrade the performance of the application. C doesn't have any of that, which means that there is no overhead, but that means that the programmer needs to be able to allocate memory and free them to prevent memory leaks, and must deal with static typing of variables.

That said, many languages and platforms, such as Java (with its Java Virtual Machine) and .NET (with its Common Language Runtime) have improved performance over the years with advents such as just-in-time compilation which produces native machine code from bytecode to achieve higher performance.

Javascript Get Values from Multiple Select Option Box

Take a look at HTMLSelectElement.selectedOptions.

HTML

<select name="north-america" multiple>
  <option valud="ca" selected>Canada</a>
  <option value="mx" selected>Mexico</a>
  <option value="us">USA</a>
</select>

JavaScript

var elem = document.querySelector("select");

console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]

This would also work on non-multiple <select> elements


Warning: Support for this selectedOptions seems pretty unknown at this point

How do I remove a MySQL database?

From the MySQL prompt:

mysql> drop database <db_name>;

How do I Set Background image in Flutter?

We can use Container and mark its height as infinity

body: Container(
      height: double.infinity,
      width: double.infinity,
      child: FittedBox(
        fit: BoxFit.cover,
        child: Image.network(
          'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
        ),
      ),
    ));

Output:

enter image description here

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

multipart/form-data

Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.

Please consult the appendix for information about security issues for forms.

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.

A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.

application/x-www-form-urlencoded

This is the default content type. Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by=' and name/value pairs are separated from each other by `&'.

application/x-www-form-urlencoded the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

In Excel, sum all values in one column in each row where another column is a specific value

You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false). To add an extra column with only the non-reimbursed amounts, you would use something like:

=IF(B1="No", A1, 0)

and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.

How to change HTML Object element data attribute value in javascript

This works:

<html>
<head></head>
<body>

<object type="text/html" id="htmlFrame" style="border: none;" standby="loading" width="100%"></object> 

<script type="text/javascript">
  var element = document.getElementById("htmlFrame"); 
  element.setAttribute("data", "attributeValue"); 
</script>

</body>
</html>

If you put this in a file, open in it a web browser, the javascript will execute and and the "data" attribute + value will be added to the object element.

Note: If you simply look at the HTML source, you wil NOT see the attribute. This is because the browser is showing you the static source sent by the webserver, NOT the dynamically rendered DOM. To inspect the DOM, use a tool like Firebug. This will show you what DOM the browser has rendered, and you will be able to see the added attribute.

Using Firefox + Firebug or Google Chrome, you can right click on a part of a page and do "Inspect Element". This will bring up a view of the rendered DOM.

How can I time a code segment for testing performance with Pythons timeit?

The testing suite doesn't make an attempt at using the imported timeit so it's hard to tell what the intent was. Nonetheless, this is a canonical answer so a complete example of timeit seems in order, elaborating on Martijn's answer.

The docs for timeit offer many examples and flags worth checking out. The basic usage on the command line is:

$ python -mtimeit "all(True for _ in range(1000))"
2000 loops, best of 5: 161 usec per loop
$ python -mtimeit "all([True for _ in range(1000)])"
2000 loops, best of 5: 116 usec per loop

Run with -h to see all options. Python MOTW has a great section on timeit that shows how to run modules via import and multiline code strings from the command line.

In script form, I typically use it like this:

import argparse
import copy
import dis
import inspect
import random
import sys
import timeit

def test_slice(L):
    L[:]

def test_copy(L):
    L.copy()

def test_deepcopy(L):
    copy.deepcopy(L)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--n", type=int, default=10 ** 5)
    parser.add_argument("--trials", type=int, default=100)
    parser.add_argument("--dis", action="store_true")
    args = parser.parse_args()
    n = args.n
    trials = args.trials
    namespace = dict(L = random.sample(range(n), k=n))
    funcs_to_test = [x for x in locals().values() 
                     if callable(x) and x.__module__ == __name__]
    print(f"{'-' * 30}\nn = {n}, {trials} trials\n{'-' * 30}\n")

    for func in funcs_to_test:
        fname = func.__name__
        fargs = ", ".join(inspect.signature(func).parameters)
        stmt = f"{fname}({fargs})"
        setup = f"from __main__ import {fname}"
        time = timeit.timeit(stmt, setup, number=trials, globals=namespace)
        print(inspect.getsource(globals().get(fname)))

        if args.dis:
            dis.dis(globals().get(fname))

        print(f"time (s) => {time}\n{'-' * 30}\n")

You can pretty easily drop in the functions and arguments you need. Use caution when using impure functions and take care of state.

Sample output:

$ python benchmark.py --n 10000
------------------------------
n = 10000, 100 trials
------------------------------

def test_slice(L):
    L[:]

time (s) => 0.015502399999999972
------------------------------

def test_copy(L):
    L.copy()

time (s) => 0.01651419999999998
------------------------------

def test_deepcopy(L):
    copy.deepcopy(L)

time (s) => 2.136012
------------------------------

Redirect from a view to another view

That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

public ActionResult SomeAction()
{
    ...
    return RedirectToAction("SomeAction", "SomeController");
}

Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

[Authorize]
public ActionResult SomeProtectedAction()
{
    ...
}

Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

Android and Facebook share intent

Apparently Facebook no longer (as of 2014) allows you to customise the sharing screen, no matter if you are just opening sharer.php URL or using Android intents in more specialised ways. See for example these answers:

Anyway, using plain Intents, you can still share a URL, but not any default text with it, as billynomates commented. (Also, if you have no URL to share, just launching Facebook app with empty "Write Post" (i.e. status update) dialog is equally easy; use the code below but leave out EXTRA_TEXT.)

Here's the best solution I've found that does not involve using any Facebook SDKs.

This code opens the official Facebook app directly if it's installed, and otherwise falls back to opening sharer.php in a browser. (Most of the other solutions in this question bring up a huge "Complete action using…" dialog which isn't optimal at all!)

String urlToShare = "https://stackoverflow.com/questions/7545254";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "Foo bar"); // NB: has no effect!
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);

// See if official Facebook app is found
boolean facebookAppFound = false;
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
    if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) {
        intent.setPackage(info.activityInfo.packageName);
        facebookAppFound = true;
        break;
    }
}

// As fallback, launch sharer.php in a browser
if (!facebookAppFound) {
    String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
}

startActivity(intent);

(Regarding the com.facebook.katana package name, see MatheusJardimB's comment.)

The result looks like this on my Nexus 7 (Android 4.4) with Facebook app installed:

enter image description here

The difference between Classes, Objects, and Instances

Any kind of data your computer stores and processes is in its most basic representation a row of bits. The way those bits are interpreted is done through data types. Data types can be primitive or complex. Primitive data types are - for instance - int or double. They have a specific length and a specific way of being interpreted. In the case of an integer, usually the first bit is used for the sign, the others are used for the value.

Complex data types can be combinations of primitive and other complex data types and are called "Class" in Java.

You can define the complex data type PeopleName consisting of two Strings called first and last name. Each String in Java is another complex data type. Strings in return are (probably) implemented using the primitive data type char for which Java knows how many bits they take to store and how to interpret them.

When you create an instance of a data type, you get an object and your computers reserves some memory for it and remembers its location and the name of that instance. An instance of PeopleName in memory will take up the space of the two String variables plus a bit more for bookkeeping. An integer takes up 32 bits in Java.

Complex data types can have methods assigned to them. Methods can perform actions on their arguments or on the instance of the data type you call this method from. If you have two instances of PeopleName called p1 and p2 and you call a method p1.getFirstName(), it usually returns the first name of the first person but not the second person's.

C: printf a float value

printf("%.<number>f", myFloat) //where <number> - digit after comma

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

Map enum in JPA with fixed values?

This is now possible with JPA 2.1:

@Column(name = "RIGHT")
@Enumerated(EnumType.STRING)
private Right right;

Further details:

How can I hide a checkbox in html?

This two classes are borrowed from the HTML Boilerplate main.css. Although the invisible checkbox will be focused and not the label.

/*
 * Hide only visually, but have it available for screenreaders: h5bp.com/v
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element to be focusable
 * when navigated to via the keyboard: h5bp.com/p
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

Can I override and overload static methods in Java?

Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.

What is difference between Errors and Exceptions?

An Error "indicates serious problems that a reasonable application should not try to catch."

while

An Exception "indicates conditions that a reasonable application might want to catch."

Error along with RuntimeException & their subclasses are unchecked exceptions. All other Exception classes are checked exceptions.

Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException, ParseException, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller

On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException, ClassCastException, etc. Many applications will use try-catch or throws clause for RuntimeExceptions & their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.

Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError, StackOverflowError, etc.

Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions(also unchecked exceptions) in code. Checked exceptions should be handled by the code.

Can you split a stream into two streams?

Not exactly. You can't get two Streams out of one; this doesn't make sense -- how would you iterate over one without needing to generate the other at the same time? A stream can only be operated over once.

However, if you want to dump them into a list or something, you could do

stream.forEach((x) -> ((x == 0) ? heads : tails).add(x));

support FragmentPagerAdapter holds reference to old fragments

Just so you know...

Adding to the litany of woes with these classes, there is a rather interesting bug that's worth sharing.

I'm using a ViewPager to navigate a tree of items (select an item and the view pager animates scrolling to the right, and the next branch appears, navigate back, and the ViewPager scrolls in the opposite direction to return to the previous node).

The problem arises when I push and pop fragments off the end of the FragmentStatePagerAdapter. It's smart enough to notice that the items change, and smart enough to create and replace a fragment when the item has changed. But not smart enough to discard the fragment state, or smart enough to trim the internally saved fragment states when the adapter size changes. So when you pop an item, and push a new one onto the end, the fragment for the new item gets the saved state of the fragment for the old item, which caused absolute havoc in my code. My fragments carry data that may require a lot of work to refetch from the internet, so not saving state really wasn't an option.

I don't have a clean workaround. I used something like this:

  public void onSaveInstanceState(Bundle outState) {
    IFragmentListener listener = (IFragmentListener)getActivity();
    if (listener!= null)
    {
        if (!listener.isStillInTheAdapter(this.getAdapterItem()))
        {
            return; // return empty state.
        }

    }
    super.onSaveInstanceState(outState);

    // normal saving of state for flips and 
    // paging out of the activity follows
    ....
  }

An imperfect solution because the new fragment instance still gets a savedState Bundle, but at least it doesn't carry stale data.

Check if a value exists in ArrayList

Just use .contains. For example, if you were checking if an ArrayList arr contains a value val, you would simply run arr.contains(val), which would return a boolean representing if the value is contained. For more information, see the docs for .contains.

Go to Matching Brace in Visual Studio?

I found this for you: Jump between braces in Visual Studio:

Put your cursor before or after the brace (your choice) and then press CTRL + ]. It works with parentheses ( ), brackets [ ] and braces { }. From now on you don’t need to play Where’s Waldo? to find that brace.

On MacOS, use CMD + SHIFT + \

No connection could be made because the target machine actively refused it?

In my case, some domains worked, while some did not. Adding a reference to my organization's proxy Url in my web.config fixed the issue.

<system.net>
    <defaultProxy useDefaultCredentials="true">
      <proxy proxyaddress="http://proxy.my-org.com/" usesystemdefault="True"/>
    </defaultProxy>
</system.net>

How to sort a list of lists by a specific index of the inner list?

multiple criteria can also be implemented through lambda function

sorted_list = sorted(list_to_sort, key=lambda x: (x[1], x[0]))

How to determine the number of days in a month in SQL Server?

--Last Day of Previous Month
SELECT DATEPART(day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)))

--Last Day of Current Month
SELECT DATEPART(day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)))

--Last Day of Next Month
SELECT DATEPART(day, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)))

Personally though, I would make a UDF for it if there is not a built in function...

iFrame Height Auto (CSS)

According to this post

You need to add the !important css modifier to your height percentages.

Hope this helps.

MySQL INSERT INTO ... VALUES and SELECT

Try this:

INSERT INTO table1 SELECT "A string", 5, idTable2 FROM table2 WHERE ...

How to ignore a particular directory or file for tslint?

Update for tslint v5.8.0

As mentioned by Saugat Acharya, you can now update tslint.json CLI Options:

{
  "extends": "tslint:latest",
  "linterOptions": {
      "exclude": [
          "bin",
          "lib/*generated.js"
      ]
  }
}

More information in this pull request.


This feature has been introduced with tslint 3.6

tslint \"src/**/*.ts\" -e \"**/__test__/**\"

You can now add --exclude (or -e) see PR here.

CLI

usage: tslint [options] file ...

Options:

-c, --config          configuration file
--force               return status code 0 even if there are lint errors
-h, --help            display detailed help
-i, --init            generate a tslint.json config file in the current working directory
-o, --out             output file
-r, --rules-dir       rules directory
-s, --formatters-dir  formatters directory
-e, --exclude         exclude globs from path expansion
-t, --format          output format (prose, json, verbose, pmd, msbuild, checkstyle)  [default: "prose"]
--test                test that tslint produces the correct output for the specified directory
-v, --version         current version

you are looking at using

-e, --exclude         exclude globs from path expansion

What is the difference between a 'closure' and a 'lambda'?

When most people think of functions, they think of named functions:

function foo() { return "This string is returned from the 'foo' function"; }

These are called by name, of course:

foo(); //returns the string above

With lambda expressions, you can have anonymous functions:

 @foo = lambda() {return "This is returned from a function without a name";}

With the above example, you can call the lambda through the variable it was assigned to:

foo();

More useful than assigning anonymous functions to variables, however, are passing them to or from higher-order functions, i.e., functions that accept/return other functions. In a lot of these cases, naming a function is unecessary:

function filter(list, predicate) 
 { @filteredList = [];
   for-each (@x in list) if (predicate(x)) filteredList.add(x);
   return filteredList;
 }

//filter for even numbers
filter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)}); 

A closure may be a named or anonymous function, but is known as such when it "closes over" variables in the scope where the function is defined, i.e., the closure will still refer to the environment with any outer variables that are used in the closure itself. Here's a named closure:

@x = 0;

function incrementX() { x = x + 1;}

incrementX(); // x now equals 1

That doesn't seem like much but what if this was all in another function and you passed incrementX to an external function?

function foo()
 { @x = 0;

   function incrementX() 
    { x = x + 1;
      return x;
    }

   return incrementX;
 }

@y = foo(); // y = closure of incrementX over foo.x
y(); //returns 1 (y.x == 0 + 1)
y(); //returns 2 (y.x == 1 + 1)

This is how you get stateful objects in functional programming. Since naming "incrementX" isn't needed, you can use a lambda in this case:

function foo()
 { @x = 0;

   return lambda() 
           { x = x + 1;
             return x;
           };
 }

‘ant’ is not recognized as an internal or external command

Need to see whether you got ant folder moved by mistake or unknowingly. It is set in environment variables.I resolved this once as mentioned below.

I removed ant folder by mistake and placed in another folder.I went to command prompt and typed "path". It has given me path as "F:\apache-ant-1.9.4\". So I moved the ant back to F drive and it resolved the issue.

Codeigniter $this->db->order_by(' ','desc') result is not complete

Put from before where, and order_by on last:

$this->db->select('*');
$this->db->from('courses');
$this->db->where('tennant_id',$tennant_id);
$this->db->order_by("UPPER(course_name)","desc");

Or try BINARY:

ORDER BY BINARY course_name DESC;

You should add manually on codeigniter for binary sorting.

And set "course_name" character column.

If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.

What type of structure data in courses table?

If you frustrated you can put into array and return using PHP:

Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)

Your array from database as example: $array_db = $result_from_db:

$final_result = natcasesort($array_db);

print_r($final_result);

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

I was getting the same warning i did this:

  1. unload project
  2. edit project properties i.e .csproj
  3. add the following tag:

    <PropertyGroup>
        <ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>
            None
        </ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>
    </PropertyGroup>
    
  4. Reload the project

writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}\n')

file.close()

css h1 - only as wide as the text

An easy fix for this is to float your H1 element left:

.centercol h1{
    background: #F2EFE9;
    border-left: 3px solid #C6C1B8;
    color: #006BB6;
    display: block;
    float: left;
    font-weight: normal;
    font-size: 18px;
    padding: 3px 3px 3px 6px;
}

I have put together a simple jsfiddle example that shows the effect of the "float: left" style on the width of your H1 element for anyone looking for a more generic answer:

http://jsfiddle.net/zmEBt/1/

How can I convert a string to an int in Python?

>>> a = "123"
>>> int(a)
123

Here's some freebie code:

def getTwoNumbers():
    numberA = raw_input("Enter your first number: ")
    numberB = raw_input("Enter your second number: ")
    return int(numberA), int(numberB)

How to define a two-dimensional array?

In case if you need a matrix with predefined numbers you can use the following code:

def matrix(rows, cols, start=0):
    return [[c + start + r * cols for c in range(cols)] for r in range(rows)]


assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]

TensorFlow: "Attempting to use uninitialized value" in variable initialization

There is another the error happening which related to the order when calling initializing global variables. I've had the sample of code has similar error FailedPreconditionError (see above for traceback): Attempting to use uninitialized value W

def linear(X, n_input, n_output, activation = None):
    W = tf.Variable(tf.random_normal([n_input, n_output], stddev=0.1), name='W')
    b = tf.Variable(tf.constant(0, dtype=tf.float32, shape=[n_output]), name='b')
    if activation != None:
        h = tf.nn.tanh(tf.add(tf.matmul(X, W),b), name='h')
    else:
        h = tf.add(tf.matmul(X, W),b, name='h')
    return h

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as sess:
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    # But W hasn't in the graph yet so not know to initialize 
    # EVAL then error
    print(linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3).eval())

You should change to following

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as 
    # NOT RUNNING BUT ASSIGN
    l = linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3)
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    print([op.name for op in g.get_operations()])
    # ONLY EVAL AFTER INIT
    print(l.eval(session=sess))

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I have just faced with similar issue building LLVM 3.7 version. first check whether you have installed the required library on your system:

$locate libstdc++.so.6.*

Then add the found location to your $LD_LIBRARY_PATH environment variable.

Apache: Restrict access to specific source IP inside virtual host

The mod_authz_host directives need to be inside a <Location> or <Directory> block but I've used the former within <VirtualHost> like so for Apache 2.2:

<VirtualHost *:8080>
    <Location />
    Order deny,allow
    Deny from all
    Allow from 127.0.0.1
    </Location>

    ...
</VirtualHost>

Reference: https://askubuntu.com/questions/262981/how-to-install-mod-authz-host-in-apache

Escaping ampersand character in SQL string

--SUBSTITUTION VARIABLES
-- these variables are used to store values TEMPorarily.
-- The values can be stored temporarily through
-- Single Ampersand (&)
-- Double Ampersand(&&)
-- The single ampersand substitution variable applies for each instance when the
--SQL statement is created or executed.
-- The double ampersand substitution variable is applied for all instances until
--that SQL statement is existing.
INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Fees, Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &fees, '&Gender');
--Using double ampersand substitution variable
INSERT INTO Student (Stud_id,First_Name, Last_Name,Dob,Fees,Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &&fees,'&gender');