Programs & Examples On #Gesturedetector

Flutter: RenderBox was not laid out

Reading answers here, it seems that the error "RenderBox was not laid out" is caused when somehow the ListView size is limitless and this can happen in different scenarios.

Just aiming to help who may have the same case as mine. In my case, I was getting this error because my ListView was inside a a column whose parent was a SingleChildScrollView. I remove this parent and it worked.

Here is my working code:

 List _todoList = ["AAA", "BBB"];

 ...

    body: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    ));

Here how it was when I was getting the "not laid out" error:

     List _todoList = ["AAA", "BBB"];

     ...


     body: SingleChildScrollView(child: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    )));

I hope this may be useful for someone.

Flutter- wrapping text

Try Wrap widget to wrap text as text grows:

Example:

Wrap(
  direction: Axis.vertical, //Vertical || Horizontal
  children: <Widget>[
    Text(
      'Your Text',
      style: TextStyle(fontSize: 30),
    ),
    Text(
      'Your Text',
      style: TextStyle(fontSize: 30),
    ),
  ],
),

Handle Button click inside a row in RecyclerView

You need to return true inside onInterceptTouchEvent() when you handle click event.

Android Image View Pinch Zooming

Using a ScaleGestureDetector

When learning a new concept I don't like using libraries or code dumps. I found a good description here and in the documentation of how to resize an image by pinching. This answer is a slightly modified summary. You will probably want to add more functionality later, but it will help you get started.

Animated gif: Scale image example

Layout

The ImageView just uses the app logo since it is already available. You can replace it with any image you like, though.

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

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ic_launcher"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Activity

We use a ScaleGestureDetector on the activity to listen to touch events. When a scale (ie, pinch) gesture is detected, then the scale factor is used to resize the ImageView.

public class MainActivity extends AppCompatActivity {

    private ScaleGestureDetector mScaleGestureDetector;
    private float mScaleFactor = 1.0f;
    private ImageView mImageView;

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

        // initialize the view and the gesture detector
        mImageView = findViewById(R.id.imageView);
        mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
    }

    // this redirects all touch events in the activity to the gesture detector
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mScaleGestureDetector.onTouchEvent(event);
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        // when a scale gesture is detected, use it to resize the image
        @Override
        public boolean onScale(ScaleGestureDetector scaleGestureDetector){
            mScaleFactor *= scaleGestureDetector.getScaleFactor();
            mImageView.setScaleX(mScaleFactor);
            mImageView.setScaleY(mScaleFactor);
            return true;
        }
    }
}

Notes

  • Although the activity had the gesture detector in the example above, it could have also been set on the image view itself.
  • You can limit the size of the scaling with something like

    mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
    
  • Thanks again to Pinch-to-zoom with multi-touch gestures In Android

  • Documentation
  • Use Ctrl + mouse drag to simulate a pinch gesture in the emulator.

Going on

You will probably want to do other things like panning and scaling to some focus point. You can develop these things yourself, but if you would like to use a pre-made custom view, copy TouchImageView.java into your project and use it like a normal ImageView. It worked well for me and I only ran into one bug. I plan to further edit the code to remove the warning and the parts that I don't need. You can do the same.

How can I make a horizontal ListView in Android?

After reading this post, I have implemented my own horizontal ListView. You can find it here: http://dev-smart.com/horizontal-listview/ Let me know if this helps.

HorizontalScrollView within ScrollView Touch Handling

Update: I figured this out. On my ScrollView, I needed to override the onInterceptTouchEvent method to only intercept the touch event if the Y motion is > the X motion. It seems like the default behavior of a ScrollView is to intercept the touch event whenever there is ANY Y motion. So with the fix, the ScrollView will only intercept the event if the user is deliberately scrolling in the Y direction and in that case pass off the ACTION_CANCEL to the children.

Here is the code for my Scroll View class that contains the HorizontalScrollView:

public class CustomScrollView extends ScrollView {
    private GestureDetector mGestureDetector;

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mGestureDetector = new GestureDetector(context, new YScrollDetector());
        setFadingEdgeLength(0);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
    }

    // Return false if we're scrolling in the x direction  
    class YScrollDetector extends SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {             
            return Math.abs(distanceY) > Math.abs(distanceX);
        }
    }
}

Android: How to detect double-tap?

public class MyView extends View {

GestureDetector gestureDetector;

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
            // creating new gesture detector
    gestureDetector = new GestureDetector(context, new GestureListener());
}

// skipping measure calculation and drawing

    // delegate the event to the gesture detector
@Override
public boolean onTouchEvent(MotionEvent e) {
    return gestureDetector.onTouchEvent(e);
}


private class GestureListener extends GestureDetector.SimpleOnGestureListener {

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }
    // event when double tap occurs
    @Override
    public boolean onDoubleTap(MotionEvent e) {
        float x = e.getX();
        float y = e.getY();

        Log.d("Double Tap", "Tapped at: (" + x + "," + y + ")");

        return true;
    }
}
}

Fling gesture detection on grid layout

I know its too late to answer but Still I am posting Swipe Detection for ListView that How to use Swipe Touch Listener in ListView Item.

Refrence: Exterminator13(one of answer in this page)

Make one ActivitySwipeDetector.class

package com.example.wocketapp;

import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class ActivitySwipeDetector implements View.OnTouchListener 
{
    static final String logTag = "SwipeDetector";
    private SwipeInterface activity;
    private float downX, downY;
    private long timeDown;
    private final float MIN_DISTANCE;
    private final int VELOCITY;
    private final float MAX_OFF_PATH;

    public ActivitySwipeDetector(Context context, SwipeInterface activity)
    {
        this.activity = activity;
        final ViewConfiguration vc = ViewConfiguration.get(context);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        MIN_DISTANCE = vc.getScaledPagingTouchSlop() * dm.density;
        VELOCITY = vc.getScaledMinimumFlingVelocity();
        MAX_OFF_PATH = MIN_DISTANCE * 2;
    }

    public void onRightToLeftSwipe(View v) 
    {
        Log.i(logTag, "RightToLeftSwipe!");
        activity.onRightToLeft(v);
    }

    public void onLeftToRightSwipe(View v) 
    {
        Log.i(logTag, "LeftToRightSwipe!");
        activity.onLeftToRight(v);
    }

    public boolean onTouch(View v, MotionEvent event) 
    {
        switch (event.getAction()) 
        {
            case MotionEvent.ACTION_DOWN:
            {
                Log.d("onTouch", "ACTION_DOWN");
                timeDown = System.currentTimeMillis();
                downX = event.getX();
                downY = event.getY();
                v.getParent().requestDisallowInterceptTouchEvent(false);
                return true;
            }

        case MotionEvent.ACTION_MOVE:
            {
                float y_up = event.getY();
                float deltaY = y_up - downY;
                float absDeltaYMove = Math.abs(deltaY);

                if (absDeltaYMove > 60) 
                {
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                } 
                else
                {
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                }
            }

            break;

            case MotionEvent.ACTION_UP: 
            {
                Log.d("onTouch", "ACTION_UP");
                long timeUp = System.currentTimeMillis();
                float upX = event.getX();
                float upY = event.getY();

                float deltaX = downX - upX;
                float absDeltaX = Math.abs(deltaX);
                float deltaY = downY - upY;
                float absDeltaY = Math.abs(deltaY);

                long time = timeUp - timeDown;

                if (absDeltaY > MAX_OFF_PATH) 
                {
                    Log.e(logTag, String.format(
                            "absDeltaY=%.2f, MAX_OFF_PATH=%.2f", absDeltaY,
                            MAX_OFF_PATH));
                    return v.performClick();
                }

                final long M_SEC = 1000;
                if (absDeltaX > MIN_DISTANCE && absDeltaX > time * VELOCITY / M_SEC) 
                {
                     v.getParent().requestDisallowInterceptTouchEvent(true);
                    if (deltaX < 0) 
                    {
                        this.onLeftToRightSwipe(v);
                        return true;
                    }
                    if (deltaX > 0) 
                    {
                        this.onRightToLeftSwipe(v);
                        return true;
                    }
                }
                else 
                {
                    Log.i(logTag,
                            String.format(
                                    "absDeltaX=%.2f, MIN_DISTANCE=%.2f, absDeltaX > MIN_DISTANCE=%b",
                                    absDeltaX, MIN_DISTANCE,
                                    (absDeltaX > MIN_DISTANCE)));
                    Log.i(logTag,
                            String.format(
                                    "absDeltaX=%.2f, time=%d, VELOCITY=%d, time*VELOCITY/M_SEC=%d, absDeltaX > time * VELOCITY / M_SEC=%b",
                                    absDeltaX, time, VELOCITY, time * VELOCITY
                                            / M_SEC, (absDeltaX > time * VELOCITY
                                            / M_SEC)));
                }

                 v.getParent().requestDisallowInterceptTouchEvent(false);

            }
        }
        return false;
    }
    public interface SwipeInterface 
    {

        public void onLeftToRight(View v);

        public void onRightToLeft(View v);
    }

}

Call it from your activity class like this:

yourLayout.setOnTouchListener(new ActivitySwipeDetector(this, your_activity.this));

And Don't forget to implement SwipeInterface which will give you two @override methods:

    @Override
    public void onLeftToRight(View v) 
    {
        Log.e("TAG", "L to R");
    }

    @Override
    public void onRightToLeft(View v) 
    {
        Log.e("TAG", "R to L");
    }

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

Is this very likely to create a memory leak in Tomcat?

The key "Transactional Resources" looks like you are talking to the database without a proper transaction. Make sure transaction management is configured properly and no invocation path to the DAO exists that doesn't run under a @Transactional annotation. This can easily happen when you configured transaction management on the Controller level but are invoking DAOs in a timer or are using @PostConstruct annotations. I wrote it up here http://georgovassilis.blogspot.nl/2014/01/tomcat-spring-and-memory-leaks-when.html

Edit: It looks like this is (also?) a bug with spring-data-jpa which has been fixed with v1.4.3. I looked it up in the spring-data-jpa sources of LockModeRepositoryPostProcessor which sets the "Transactional Resources" key. In 1.4.3 it also clears the key again.

How to access accelerometer/gyroscope data from Javascript?

Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.

It is enough to register an event function for accelerometer like so:

if(window.DeviceMotionEvent){
  window.addEventListener("devicemotion", motion, false);
}else{
  console.log("DeviceMotionEvent is not supported");
}

with the handler:

function motion(event){
  console.log("Accelerometer: "
    + event.accelerationIncludingGravity.x + ", "
    + event.accelerationIncludingGravity.y + ", "
    + event.accelerationIncludingGravity.z
  );
}

And for magnetometer a following event handler has to be registered:

if(window.DeviceOrientationEvent){
  window.addEventListener("deviceorientation", orientation, false);
}else{
  console.log("DeviceOrientationEvent is not supported");
}

with a handler:

function orientation(event){
  console.log("Magnetometer: "
    + event.alpha + ", "
    + event.beta + ", "
    + event.gamma
  );
}

There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).

There is a simple working code on GitHub

jQuery find element by data attribute value

Use Attribute Equals Selector

$('.slide-link[data-slide="0"]').addClass('active');

Fiddle Demo

.find()

it works down the tree

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Return background color of selected cell

Maybe you can use this properties:

ActiveCell.Interior.ColorIndex - one of 56 preset colors

and

ActiveCell.Interior.Color - RGB color, used like that:

ActiveCell.Interior.Color = RGB(255,255,255)

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

data=np.genfromtxt(csv_file, delimiter=',', dtype='unicode')

It works fine for me.

Can't load AMD 64-bit .dll on a IA 32-bit platform

Try this:

  1. Download and install a 32-bit JDK.
  2. Go to eclipse click on your project (Run As ? Run Configurations...) under Java Application branch.
  3. Go to the JRE tab and select Alternate JRE. Click on Installed JRE button, add your 32-bit JRE and select.

how to parse xml to java object?

I find jackson fasterxml is one good choice to serializing/deserializing bean with XML.

Refer: How to use spring to marshal and unmarshal xml?

How do I execute a stored procedure once for each row returned by query?

I like the dynamic query way of Dave Rincon as it does not use cursors and is small and easy. Thank you Dave for sharing.

But for my needs on Azure SQL and with a "distinct" in the query, i had to modify the code like this:

Declare @SQL nvarchar(max);
-- Set SQL Variable
-- Prepare exec command for each distinctive tenantid found in Machines 
SELECT @SQL = (Select distinct 'exec dbo.sp_S2_Laser_to_cache ' + 
              convert(varchar(8),tenantid) + ';' 
              from Dim_Machine
              where iscurrent = 1
              FOR XML PATH(''))

--for debugging print the sql 
print @SQL;

--execute the generated sql script
exec sp_executesql @SQL;

I hope this helps someone...

creating a table in ionic

enter image description here

.html file

<ion-card-content>
<div class='summary_row'>
      <div  class='summarycell'>Header 1</div>
      <div  class='summarycell'>Header 2</div>
      <div  class='summarycell'>Header 3</div>
      <div  class='summarycell'>Header 4</div>
      <div  class='summarycell'>Header 5</div>
      <div  class='summarycell'>Header 6</div>
      <div  class='summarycell'>Header 7</div>

    </div>
    <div  class='summary_row'>
      <div  class='summarycell'>
        Cell1
      </div>
      <div  class='summarycell'>
          Cell2
      </div>
        <div  class='summarycell'>
            Cell3
          </div>

      <div  class='summarycell'>
        Cell5
      </div>
      <div  class='summarycell'>
          Cell6
        </div>
        <div  class='summarycell'>
            Cell7
          </div>
          <div  class='summarycell'>
              Cell8
            </div>
    </div>

.scss file

_x000D_
_x000D_
.row{_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    width: max-content;_x000D_
}_x000D_
.row:first-child .summarycell{_x000D_
    font-weight: bold;_x000D_
    text-align: center;_x000D_
}_x000D_
.cell{_x000D_
    overflow: auto;_x000D_
    word-wrap: break-word;_x000D_
    width: 27vw;_x000D_
    border: 1px solid #b3b3b3;_x000D_
    padding: 10px;_x000D_
    text-align: right;_x000D_
}_x000D_
.cell:nth-child(2){_x000D_
}_x000D_
.cell:first-child{_x000D_
    width:41vw;_x000D_
    text-align: left;_x000D_
}
_x000D_
_x000D_
_x000D_

Angular2 - Input Field To Accept Only Numbers

Casting because it works also with leading 0 like 00345

@Directive({
  selector: '[appOnlyDigits]'
})
export class AppOnlyDigitsDirective {
  @HostListener('input', ['$event'])
  onKeyDown(ev: KeyboardEvent) {
    const input = ev.target as HTMLInputElement;
    input.value = String(input.value.replace(/\D+/g, ''));
  }
}

Show all current locks from get_lock

From MySQL 5.7 onwards, this is possible, but requires first enabling the mdl instrument in the performance_schema.setup_instruments table. You can do this temporarily (until the server is next restarted) by running:

UPDATE performance_schema.setup_instruments
SET enabled = 'YES'
WHERE name = 'wait/lock/metadata/sql/mdl';

Or permanently, by adding the following incantation to the [mysqld] section of your my.cnf file (or whatever config files MySQL reads from on your installation):

[mysqld]
performance_schema_instrument = 'wait/lock/metadata/sql/mdl=ON'

(Naturally, MySQL will need to be restarted to make the config change take effect if you take the latter approach.)

Locks you take out after the mdl instrument has been enabled can be seen by running a SELECT against the performance_schema.metadata_locks table. As noted in the docs, GET_LOCK locks have an OBJECT_TYPE of 'USER LEVEL LOCK', so we can filter our query down to them with a WHERE clause:

mysql> SELECT GET_LOCK('foobarbaz', -1);
+---------------------------+
| GET_LOCK('foobarbaz', -1) |
+---------------------------+
|                         1 |
+---------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM performance_schema.metadata_locks 
    -> WHERE OBJECT_TYPE='USER LEVEL LOCK'
    -> \G
*************************** 1. row ***************************
          OBJECT_TYPE: USER LEVEL LOCK
        OBJECT_SCHEMA: NULL
          OBJECT_NAME: foobarbaz
OBJECT_INSTANCE_BEGIN: 139872119610944
            LOCK_TYPE: EXCLUSIVE
        LOCK_DURATION: EXPLICIT
          LOCK_STATUS: GRANTED
               SOURCE: item_func.cc:5482
      OWNER_THREAD_ID: 35
       OWNER_EVENT_ID: 3
1 row in set (0.00 sec)

mysql> 

The meanings of the columns in this result are mostly adequately documented at https://dev.mysql.com/doc/refman/en/metadata-locks-table.html, but one point of confusion is worth noting: the OWNER_THREAD_ID column does not contain the connection ID (like would be shown in the PROCESSLIST or returned by CONNECTION_ID()) of the thread that holds the lock. Confusingly, the term "thread ID" is sometimes used as a synonym of "connection ID" in the MySQL documentation, but this is not one of those times. If you want to determine the connection ID of the connection that holds a lock (for instance, in order to kill that connection with KILL), you'll need to look up the PROCESSLIST_ID that corresponds to the THREAD_ID in the performance_schema.threads table. For instance, to kill the connection that was holding my lock above...

mysql> SELECT OWNER_THREAD_ID FROM performance_schema.metadata_locks
    -> WHERE OBJECT_TYPE='USER LEVEL LOCK'
    -> AND OBJECT_NAME='foobarbaz';
+-----------------+
| OWNER_THREAD_ID |
+-----------------+
|              35 |
+-----------------+
1 row in set (0.00 sec)

mysql> SELECT PROCESSLIST_ID FROM performance_schema.threads
    -> WHERE THREAD_ID=35;
+----------------+
| PROCESSLIST_ID |
+----------------+
|             10 |
+----------------+
1 row in set (0.00 sec)

mysql> KILL 10;
Query OK, 0 rows affected (0.00 sec)

string encoding and decoding?

Aside from getting decode and encode backwards, I think part of the answer here is actually don't use the ascii encoding. It's probably not what you want.

To begin with, think of str like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.

Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.

The problem is that in practice, you run into both. Some libraries give you a str, and some expect a str. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.

Enter codecs: it's the translation library between these two data types. You use encode to generate a sequence of bytes (str) from a text string (unicode), and you use decode to get a text string (unicode) from a sequence of bytes (str).

For example:

>>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
>>> codecs.decode(s, 'utf-8')
u"I look like a string, but I'm actually a sequence of bytes. \u2764"

What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode version of this, given that this sequence of bytes is in 'utf-8'." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.

Let's go the other way around:

>>> u = u"I'm a string! Really! \u2764"
>>> codecs.encode(u, 'utf-8')
"I'm a string! Really! \xe2\x9d\xa4"

I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8' encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.

We can work with other encodings, too, of course:

>>> s = "I have a section \xa7"
>>> codecs.decode(s, 'latin1')
u'I have a section \xa7'
>>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
True

>>> u = u"I have a section \u00a7"
>>> u
u'I have a section \xa7'
>>> codecs.encode(u, 'latin1')
'I have a section \xa7'

('\xa7' is the section character, in both Unicode and Latin-1.)

So for your question, you first need to figure out what encoding your str is in.

  • Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode.

    s = [get from external source]
    u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
    
  • Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str. UTF-8 is a good choice for plain text documents; most things can read it.

    u = u'My string'
    s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
    [Write s out somewhere]
    
  • Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8' is probably the best choice for that:

    u = u'My string'
    s = codecs.encode(u, 'utf-8')
    newu = codecs.decode(s, 'utf-8')
    

In modern programming, you probably never want to use the 'ascii' encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.

Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str was replaced with bytes, and unicode was replaced with str.

TypeScript Objects as Dictionary types as in C#

You can also use the Record type in typescript :

export interface nameInterface { 
    propName : Record<string, otherComplexInterface> 
}

jQuery set radio button

In your selector you seem to be attempting to fetch some nested element of your radio button with a given id. If you want to check a radio button, you should select this radio button in the selector and not something else:

$('input:radio[name="cols"]').attr('checked', 'checked');

This assumes that you have the following radio button in your markup:

<input type="radio" name="cols" value="1" />

If your radio button had an id:

<input type="radio" name="cols" value="1" id="myradio" />

you could directly use an id selector:

$('#myradio').attr('checked', 'checked');

Removing time from a Date object?

What about this:

    Date today = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    today = sdf.parse(sdf.format(today));

Android Service needs to run always (Never pause or stop)

You can implement startForeground for the service and even if it dies you can restart it by using START_STICKY on startCommand(). Not sure though this is the right implementation.

What is the best way to test for an empty string with jquery-out-of-the-box?

To checks for all 'empties' like null, undefined, '', ' ', {}, [].

var isEmpty = function(data) {
    if(typeof(data) === 'object'){
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
            return true;
        }else if(!data){
            return true;
        }
        return false;
    }else if(typeof(data) === 'string'){
        if(!data.trim()){
            return true;
        }
        return false;
    }else if(typeof(data) === 'undefined'){
        return true;
    }else{
        return false;
    }
}

Use cases and results.

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false

How to display an image from a path in asp.net MVC 4 and Razor view?

Try this ,

<img src= "@Url.Content(Model.ImagePath)" alt="Sample Image" style="height:50px;width:100px;"/>

(or)

<img src="~/Content/img/@Url.Content(model =>model.ImagePath)" style="height:50px;width:100px;"/>

How to check if String value is Boolean type in Java?

Something you should also take into consideration is character casing...

Instead of:

return value.equals("false") || value.equals("true");

Do this:

return value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true");

How can I change the text inside my <span> with jQuery?

$('#abc span').text('baa baa black sheep');
$('#abc span').html('baa baa <strong>black sheep</strong>');

text() if just text content. html() if it contains, well, html content.

How to replace master branch in Git, entirely, from another branch?

I found this to be the best way of doing this (I had an issue with my server not letting me delete).

On the server that hosts the origin repository, type the following from a directory inside the repository:

git config receive.denyDeleteCurrent ignore

On your workstation:

git branch -m master vabandoned                 # Rename master on local
git branch -m newBranch master                  # Locally rename branch newBranch to master
git push origin :master                         # Delete the remote's master
git push origin master:refs/heads/master        # Push the new master to the remote
git push origin abandoned:refs/heads/abandoned  # Push the old master to the remote

Back on the server that hosts the origin repository:

git config receive.denyDeleteCurrent true

Credit to the author of blog post http://www.mslinn.com/blog/?p=772

Dynamically creating keys in a JavaScript associative array

JavaScript does not have associative arrays. It has objects.

The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

It looks like you have an associative array because an Array is also an Object - however you're not actually adding things into the array at all; you're setting fields on the object.

Now that that is cleared up, here is a working solution to your example:

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// Split into key and value
var kvp = cleaned.split('=');

// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.

Build android release apk on Phonegap 3.x CLI

i got this to work by copy pasting the signed app in the same dir as zipalign. It seems that aapt.exe could not find the source file even when given the path. i.e. this did not work zipalign -f -v 4 C:...\CordovaApp-release-unsigned.apk C:...\destination.apk it reached aapt.exeCordovaApp-release-unsigned.apk , froze and upon hitting return 'aapt.exeCordovaApp-release-unsigned.apk' is not recognized as an internal or external command, operable program or batch file. And this did zipalign -f -v 4 CordovaApp-release-unsigned.apk myappname.apk

Recursively look for files with a specific extension

find $directory -type f -name "*.in"

is a bit shorter than that whole thing (and safer - deals with whitespace in filenames and directory names).

Your script is probably failing for entries that don't have a . in their name, making $extension empty.

How to post a file from a form with Axios

How to post file using an object in memory (like a JSON object):

import axios from 'axios';
import * as FormData  from 'form-data'

async function sendData(jsonData){
    // const payload = JSON.stringify({ hello: 'world'});
    const payload = JSON.stringify(jsonData);
    const bufferObject = Buffer.from(payload, 'utf-8');
    const file = new FormData();

    file.append('upload_file', bufferObject, "b.json");

    const response = await axios.post(
        lovelyURL,
        file,
        headers: file.getHeaders()
    ).toPromise();


    console.log(response?.data);
}

How to execute a JavaScript function when I have its name as a string

Thanks for the very helpful answer. I'm using Jason Bunting's function in my projects.

I extended it to use it with an optional timeout, because the normal way to set a timeout wont work. See abhishekisnot's question

_x000D_
_x000D_
function executeFunctionByName(functionName, context, timeout /*, args */ ) {_x000D_
 var args = Array.prototype.slice.call(arguments, 3);_x000D_
 var namespaces = functionName.split(".");_x000D_
 var func = namespaces.pop();_x000D_
 for (var i = 0; i < namespaces.length; i++) {_x000D_
  context = context[namespaces[i]];_x000D_
 }_x000D_
 var timeoutID = setTimeout(_x000D_
  function(){ context[func].apply(context, args)},_x000D_
  timeout_x000D_
 );_x000D_
    return timeoutID;_x000D_
}_x000D_
_x000D_
var _very = {_x000D_
    _deeply: {_x000D_
        _defined: {_x000D_
            _function: function(num1, num2) {_x000D_
                console.log("Execution _very _deeply _defined _function : ", num1, num2);_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
console.log('now wait')_x000D_
executeFunctionByName("_very._deeply._defined._function", window, 2000, 40, 50 );
_x000D_
_x000D_
_x000D_

Rename Oracle Table or View

In order to rename a table in a different schema, try:

ALTER TABLE owner.mytable RENAME TO othertable;

The rename command (as in "rename mytable to othertable") only supports renaming a table in the same schema.

How do I make a textbox that only accepts numbers?

You can use the TextChanged event

private void textBox_BiggerThan_TextChanged(object sender, EventArgs e)
{
    long a;
    if (! long.TryParse(textBox_BiggerThan.Text, out a))
    {
        // If not int clear textbox text or Undo() last operation
        textBox_LessThan.Clear();
    }
}

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

How to place div side by side

If you're not tagetting IE6, then float the second <div> and give it a margin equal to (or maybe a little bigger than) the first <div>'s fixed width.

HTML:

<div id="main-wrapper">
    <div id="fixed-width"> lorem ipsum </div>
    <div id="rest-of-space"> dolor sit amet </div>
</div>

CSS:

#main-wrapper {
    100%;
    background:red;
}
#fixed-width {
    width:100px;
    float:left
}
#rest-of-space {
    margin-left:101px;
        /* May have to increase depending on borders and margin of the fixd width div*/
    background:blue;
}

The margin accounts for the possibility that the 'rest-of-space' <div> may contain more content than the 'fixed-width' <div>.

Don't give the fixed width one a background; if you need to visibly see these as different 'columns' then use the Faux Columns trick.

Can we convert a byte array into an InputStream in Java?

Use ByteArrayInputStream:

InputStream is = new ByteArrayInputStream(decodedBytes);

Get image data url in JavaScript?

In HTML5 better use this:

{
//...
canvas.width = img.naturalWidth; //img.width;
canvas.height = img.naturalHeight; //img.height;
//...
}

How can I trim beginning and ending double quotes from a string?

public String removeDoubleQuotes(String request) {
    return request.replace("\"", "");
}

Check time difference in Javascript

I like doing it via Epoch.

var now = new Date();
var future = new Date(now.setMinutes(15));

var futureEpoch = moment(future).unix();
var nowEpoch = moment(now).unix();
var differenceInEpoch = nowEpoch - scheduledEpoch ;

console.log("futureEpoch        : " + futureEpoch);
console.log("nowEpoch              : " + nowEpoch);
console.log("differenceInEpoch     : " + differenceInEpoch);

var diffTime = new Date(0); // The 0 there is the key, which sets the date to the epoch
diffTime.setUTCSeconds(differenceInEpoch);
console.log("new diffTime : " + diffTime);

EditorFor() and html properties

This is the cleanest and most elegant/simple way to get a solution here.

Brilliant blog post and no messy overkill in writing custom extension/helper methods like a mad professor.

http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx

What is the difference between require() and library()?

?library

and you will see:

library(package) and require(package) both load the package with name package and put it on the search list. require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist. Both functions check and update the list of currently loaded packages and do not reload a package which is already loaded. (If you want to reload such a package, call detach(unload = TRUE) or unloadNamespace first.) If you want to load a package without putting it on the search list, use requireNamespace.

Get started with Latex on Linux

If you use Ubuntu or Debian, I made a tutorial easy to follow: Install LaTeX on Ubuntu or Debian. This tutorial explains how to install LaTeX and how to create your first PDF.

Path.Combine for URLs?

There is a Todd Menier's comment above that Flurl includes a Url.Combine.

More details:

Url.Combine is basically a Path.Combine for URLs, ensuring one and only one separator character between parts:

var url = Url.Combine(
    "http://MyUrl.com/",
    "/too/", "/many/", "/slashes/",
    "too", "few?",
    "x=1", "y=2"
// result: "http://www.MyUrl.com/too/many/slashes/too/few?x=1&y=2" 

Get Flurl.Http on NuGet:

PM> Install-Package Flurl.Http

Or get the stand-alone URL builder without the HTTP features:

PM> Install-Package Flurl

How can I define colors as variables in CSS?

People keep upvoting my answer, but it's a terrible solution compared to the joy of sass or less, particularly given the number of easy to use gui's for both these days. If you have any sense ignore everything I suggest below.

You could put a comment in the css before each colour in order to serve as a sort of variable, which you can change the value of using find/replace, so...

At the top of the css file

/********************* Colour reference chart****************
*************************** comment ********* colour ******** 

box background colour       bbg              #567890
box border colour           bb               #abcdef
box text colour             bt               #123456

*/

Later in the CSS file

.contentBox {background: /*bbg*/#567890; border: 2px solid /*bb*/#abcdef; color:/*bt*/#123456}

Then to, for example, change the colour scheme for the box text you do a find/replace on

/*bt*/#123456

Timer Interval 1000 != 1 second?

The proper interval to get one second is 1000. The Interval property is the time between ticks in milliseconds:

MSDN: Timer.Interval Property

So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick event multiple times.

How to get the mouse position without events (without moving the mouse)?

You could try something similar to what Tim Down suggested - but instead of having elements for each pixel on the screen, create just 2-4 elements (boxes), and change their location, width, height dynamically to divide the yet possible locations on screen by 2-4 recursively, thus finding the mouse real location quickly.

For example - first elements take right and left half of screen, afterwards the upper and lower half. By now we already know in which quarter of screen the mouse is located, are able to repeat - discover which quarter of this space...

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

Accessing bash command line args $@ vs $*

The difference appears when the special parameters are quoted. Let me illustrate the differences:

$ set -- "arg  1" "arg  2" "arg  3"

$ for word in $*; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in $@; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in "$*"; do echo "$word"; done
arg  1 arg  2 arg  3

$ for word in "$@"; do echo "$word"; done
arg  1
arg  2
arg  3

one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:

$ for word in "$@"; do echo $word; done
arg 1
arg 2
arg 3

and in bash, "$@" is the "default" list to iterate over:

$ for word; do echo "$word"; done
arg  1
arg  2
arg  3

Time complexity of accessing a Python dict

My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.

I use a dictionary to memoize values. That seems to be a bottleneck.

This is evidence of a bug in your memoization method.

char initial value in Java

Either you initialize the variable to something

char retChar = 'x';

or you leave it automatically initialized, which is

char retChar = '\0';

an ascii 0, the same as

char retChar = (char) 0;

What can one initialize char values to?

Sounds undecided between automatic initialisation, which means, you have no influence, or explicit initialisation. But you cannot change the default.

Searching for file in directories recursively

You will want to move the loop for the files outside of the loop for the folders. In addition you will need to pass the data structure holding the collection of files to each call of the method. That way all files go into a single list.

public static List<string> DirSearch(string sDir, List<string> files)
{
  foreach (string f in Directory.GetFiles(sDir, "*.xml"))
  {
    string extension = Path.GetExtension(f);
    if (extension != null && (extension.Equals(".xml")))
    {
      files.Add(f);
    }
  }
  foreach (string d in Directory.GetDirectories(sDir))
  {
    DirSearch(d, files);
  }
  return files;
}

Then call it like this.

List<string> files = DirSearch("c:\foo", new List<string>());

Update:

Well unbeknownst to me, until I read the other answer anyway, there is already a builtin mechanism for doing this. I will leave my answer in case you are interested in seeing how your code needs to be modified to make it work.

Run parallel multiple commands at once in the same terminal

I am suggesting a much simpler utility I just wrote. It's currently called par, but will be renamed soon to either parl or pll, haven't decided yet.

https://github.com/k-bx/par

API is as simple as:

par "script1.sh" "script2.sh" "script3.sh"

Prefixing commands can be done via:

par "PARPREFIX=[script1] script1.sh" "script2.sh" "script3.sh"

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

Difference between binary semaphore and mutex

Mutexes have ownership, unlike semaphores. Although any thread, within the scope of a mutex, can get an unlocked mutex and lock access to the same critical section of code,only the thread that locked a mutex should unlock it.

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

NuGet Package Restore Not Working

Note you can force package restore to execute by running the following commands in the nuget package manager console

Update-Package -Reinstall

Forces re-installation of everything in the solution.


Update-Package -Reinstall -ProjectName myProj

Forces re-installation of everything in the myProj project.

Note: This is the nuclear option. When using this command you may not get the same versions of the packages you have installed and that could be lead to issues. This is less likely to occur at a project level as opposed to the solution level.

You can use the -safe commandline parameter option to constrain upgrades to newer versions with the same Major and Minor version component. This option was added later and resolves some of the issues mentioned in the comments.

Update-Package -Reinstall -Safe

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

This gist will do most of the work for you showing a menu when there are multiple devices connected:

$ adb $(android-select-device) shell
1) 02783201431feeee device 3) emulator-5554
2) 3832380FA5F30000 device 4) emulator-5556
Select the device to use, <Q> to quit:

To avoid typing you can just create an alias that included the device selection as explained here.

Log4j: How to configure simplest possible file logging?

I have one generic log4j.xml file for you:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">

    <appender name="default.console" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.out" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="default.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/mylogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="another.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/anotherlogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <logger name="com.yourcompany.SomeClass" additivity="false">
        <level value="debug" />
        <appender-ref ref="another.file" />
    </logger>

    <root>
        <priority value="info" />
        <appender-ref ref="default.console" />
        <appender-ref ref="default.file" />
    </root>
</log4j:configuration>

with one console, two file appender and one logger poiting to the second file appender instead of the first.

EDIT

In one of the older projects I have found a simple log4j.properties file:

# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.

# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with 
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless 
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file

# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n

log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n

For the description of all the layout arguments look here: log4j PatternLayout arguments

How can I display the current branch and folder path in terminal?

There are many PS1 generators but ezprompt has the git status (2nd tab 'Status Elements' ) also.

How does Git handle symbolic links?

You can find out what Git does with a file by seeing what it does when you add it to the index. The index is like a pre-commit. With the index committed, you can use git checkout to bring everything that was in the index back into the working directory. So, what does Git do when you add a symbolic link to the index?

To find out, first, make a symbolic link:

$ ln -s /path/referenced/by/symlink symlink

Git doesn't know about this file yet. git ls-files lets you inspect your index (-s prints stat-like output):

$ git ls-files -s ./symlink
[nothing]

Now, add the contents of the symbolic link to the Git object store by adding it to the index. When you add a file to the index, Git stores its contents in the Git object store.

$ git add ./symlink

So, what was added?

$ git ls-files -s ./symlink
120000 1596f9db1b9610f238b78dd168ae33faa2dec15c 0       symlink

The hash is a reference to the packed object that was created in the Git object store. You can examine this object if you look in .git/objects/15/96f9db1b9610f238b78dd168ae33faa2dec15c in the root of your repository. This is the file that Git stores in the repository, that you can later check out. If you examine this file, you'll see it is very small. It does not store the contents of the linked file. To confirm this, print the contents of the packed repository object with git cat-file:

$ git cat-file -p 1596f9db1b9610f238b78dd168ae33faa2dec15c
/path/referenced/by/symlink

(Note 120000 is the mode listed in ls-files output. It would be something like 100644 for a regular file.)

But what does Git do with this object when you check it out from the repository and into your filesystem? It depends on the core.symlinks config. From man git-config:

core.symlinks

If false, symbolic links are checked out as small plain files that contain the link text.

So, with a symbolic link in the repository, upon checkout you either get a text file with a reference to a full filesystem path, or a proper symbolic link, depending on the value of the core.symlinks config.

Either way, the data referenced by the symlink is not stored in the repository.

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

Converting JSON data to Java object

If you use any kind of special maps with keys or values also of special maps, you will find it's not contemplated by the implementation of google.

Conversion failed when converting the varchar value to data type int in sql

The line

SELECT  @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))

is wrong.

@Prefix is 'J' and LEN(...anything...) is an int, hence the type mismatch.


It seems to me, you actually want to do,

SELECT
        @maxCode = MAX(
            CAST(SUBSTRING(
                Voucher_No,
                @startFrom + 1,
                LEN(Voucher_No) - (@startFrom + 1)) AS INT)
    FROM
        dbo.Journal_Entry;

SELECT  @Prefix + CAST(@maxCode AS VARCHAR(10));

but, I couldn't say. If you illustrated before and after data, it would help.

default web page width - 1024px or 980px?

I use mostly 978px width for my designs. Adv. of 978px : can be divided by 2,3.

Why do I need to override the equals and hashCode methods in Java?

Java puts a rule that

"If two objects are equal using Object class equals method, then the hashcode method should give the same value for these two objects."

So, if in our class we override equals() we should override hashcode() method also to follow this rule. Both methods, equals() and hashcode(), are used in Hashtable, for example, to store values as key-value pairs. If we override one and not the other, there is a possibility that the Hashtable may not work as we want, if we use such object as a key.

How to implement the Android ActionBar back button?

I think onSupportNavigateUp() is simplest and best way to do so

check the code in this link Click here for complete code

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

%Like% Query in spring JpaRepository

I use this:

@Query("Select c from Registration c where lower(c.place) like lower(concat('%', concat(:place, '%')))")

lower() is like toLowerCase in String, so the result isn't case sensitive.

Homebrew: Could not symlink, /usr/local/bin is not writable

If you already have a directory in /usr/local for the package you're installing, you can try deleting this directory.

In my case I had previously installed the package I was trying to install without using brew, and had then uninstalled it. There was a directory /usr/local/<my_package>/ left over from that previous install. I deleted this folder (sudo rm -rf /usr/local/<my_package>/) and after that the brew link step was successful.

What is the default Precision and Scale for a Number in Oracle?

NUMBER (precision, scale)

If a precision is not specified, the column stores values as given. If no scale is specified, the scale is zero.

A lot more info at:

http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832

Remove all special characters from a string in R?

You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all from the stringr package, though gsub from base R works just as well.

The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.

x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")

(The base R equivalent is gsub("[[:punct:]]", " ", x).)

An alternative is to swap out all non-alphanumeric characters.

str_replace_all(x, "[^[:alnum:]]", " ")

Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.

Run bash command on jenkins pipeline

According to this document, you should be able to do it like so:

node {
    sh "#!/bin/bash \n" + 
       "echo \"Hello from \$SHELL\""
}

Delete default value of an input text on click

<input name="Email" type="text" id="Email" placeholder="enter your question" />

The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format).

The short hint is displayed in the input field before the user enters a value.

Note: The placeholder attribute works with the following input types: text, search, url, tel, email, and password.

I think this will help.

Android Horizontal RecyclerView scroll Direction

Just add two lines of code to make orientation of recyclerview as horizontal. So add these lines when Initializing Recyclerview.

  LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);

my_recycler.setLayoutManager(linearLayoutManager);

how to bold words within a paragraph in HTML/CSS?

Add <b> tag

<p> <b> I am in Bold </b></p>

For more text formatting tags click here

How to mark-up phone numbers?

The best bet is to start off with tel: which works on all mobiles

Then put in this code, which will only run when on a desktop, and only when a link is clicked.

I'm using http://detectmobilebrowsers.com/ to detect mobile browsers, you can use whatever method you prefer

if (!jQuery.browser.mobile) {
    jQuery('body').on('click', 'a[href^="tel:"]', function() {
            jQuery(this).attr('href', 
                jQuery(this).attr('href').replace(/^tel:/, 'callto:'));
    });
}

So basically you cover all your bases.

tel: works on all phones to open the dialer with the number

callto: works on your computer to connect to skype from firefox, chrome

Parsing JSON in Excel VBA

If you want to build on top of ScriptControl, you can add a few helper method to get at the required information. The JScriptTypeInfo object is a bit unfortunate: it contains all the relevant information (as you can see in the Watch window) but it seems impossible to get at it with VBA. However, the Javascript engine can help us:

Option Explicit

Private ScriptEngine As ScriptControl

Public Sub InitScriptEngine()
    Set ScriptEngine = New ScriptControl
    ScriptEngine.Language = "JScript"
    ScriptEngine.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
    ScriptEngine.AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
End Sub

Public Function DecodeJsonString(ByVal JsonString As String)
    Set DecodeJsonString = ScriptEngine.Eval("(" + JsonString + ")")
End Function

Public Function GetProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Variant
    GetProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function

Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
    Set GetObjectProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function

Public Function GetKeys(ByVal JsonObject As Object) As String()
    Dim Length As Integer
    Dim KeysArray() As String
    Dim KeysObject As Object
    Dim Index As Integer
    Dim Key As Variant

    Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
    Length = GetProperty(KeysObject, "length")
    ReDim KeysArray(Length - 1)
    Index = 0
    For Each Key In KeysObject
        KeysArray(Index) = Key
        Index = Index + 1
    Next
    GetKeys = KeysArray
End Function


Public Sub TestJsonAccess()
    Dim JsonString As String
    Dim JsonObject As Object
    Dim Keys() As String
    Dim Value As Variant
    Dim j As Variant

    InitScriptEngine

    JsonString = "{""key1"": ""val1"", ""key2"": { ""key3"": ""val3"" } }"
    Set JsonObject = DecodeJsonString(CStr(JsonString))
    Keys = GetKeys(JsonObject)

    Value = GetProperty(JsonObject, "key1")
    Set Value = GetObjectProperty(JsonObject, "key2")
End Sub

A few notes:

  • If the JScriptTypeInfo instance refers to a Javascript object, For Each ... Next won't work. However, it does work if it refers to a Javascript array (see GetKeys function).
  • The access properties whose name is only known at run-time, use the functions GetProperty and GetObjectProperty.
  • The Javascript array provides the properties length, 0, Item 0, 1, Item 1 etc. With the VBA dot notation (jsonObject.property), only the length property is accessible and only if you declare a variable called length with all lowercase letters. Otherwise the case doesn't match and it won't find it. The other properties are not valid in VBA. So better use the GetProperty function.
  • The code uses early binding. So you have to add a reference to "Microsoft Script Control 1.0".
  • You have to call InitScriptEngine once before using the other functions to do some basic initialization.

Responsive table handling in Twitter Bootstrap

If you are using Bootstrap 3 and Less you could apply the responsive tables to all resolutions by updatingthe file:

tables.less

or overwriting this part:

@media (max-width: @screen-xs) {
  .table-responsive {
    width: 100%;
    margin-bottom: 15px;
    overflow-y: hidden;
    overflow-x: scroll;
    border: 1px solid @table-border-color;

    // Tighten up spacing and give a background color
    > .table {
      margin-bottom: 0;
      background-color: #fff;

      // Ensure the content doesn't wrap
      > thead,
      > tbody,
      > tfoot {
        > tr {
          > th,
          > td {
            white-space: nowrap;
          }
        }
      }
    }

    // Special overrides for the bordered tables
    > .table-bordered {
      border: 0;

      // Nuke the appropriate borders so that the parent can handle them
      > thead,
      > tbody,
      > tfoot {
        > tr {
          > th:first-child,
          > td:first-child {
            border-left: 0;
          }
          > th:last-child,
          > td:last-child {
            border-right: 0;
          }
        }
        > tr:last-child {
          > th,
          > td {
            border-bottom: 0;
          }
        }
      }
    }
  }
}

With:

@media (max-width: @screen-lg) {
  .table-responsive {
    width: 100%;
...

Note how I changed the first line @screen-XX value.

I know making all tables responsive may not sound that good, but I found it extremely useful to have this enabled up to LG on large tables (lots of columns).

Hope it helps someone.

VirtualBox error "Failed to open a session for the virtual machine"

Killing VM process dint work in my case.

Right click on the VM and click on "Discard Saved State".

 Right click on the VM and click on "Discard Saved State".

This worked for me.

Manipulate a url string by adding GET parameters

another improved function version. Mix of existing answers with small improvements (port support) and bugfixes (checking keys properly).

/**
 * @param string $url original url to modify - can be relative, partial etc
 * @param array $paramsOverride associative array, can be empty
 * @return string modified url
 */
protected function overrideUrlQueryParams($url, $paramsOverride){
    if (!is_array($paramsOverride)){
        return $url;
    }

    $url_parts = parse_url($url);

    if (isset($url_parts['query'])) {
        parse_str($url_parts['query'], $params);
    } else {
        $params = [];
    }

    $params = array_merge($params, $paramsOverride);

    $res = '';

    if(isset($url_parts['scheme'])) {
        $res .= $url_parts['scheme'] . ':';
    }

    if(isset($url_parts['host'])) {
        $res .= '//' . $url_parts['host'];
    }

    if(isset($url_parts['port'])) {
        $res .= ':' . $url_parts['port'];
    }

    if (isset($url_parts['path'])) {
        $res .= $url_parts['path'];
    }

    if (count($params) > 0) {
        $res .= '?' . http_build_query($params);
    }

    return $res;
}

How do I conditionally apply CSS styles in AngularJS?

Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:

  • ng-class - use when the set of CSS styles is static/known ahead of time
  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.
  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)
  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)
  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)
  • ng-disabled and ng-readonly - use to restrict form element behavior
  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations

The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.

When the user changes the UI, Angular will automatically update the associated elements on the page.


Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.

ng-class accepts an "expression" that must evaluate to one of the following:

  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values

Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:

<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
   ... HTML to display the item ...
   <input type="checkbox" ng-model="item.checked">
</div>

Above, we used ng-class expression type #3 - a map/object of class names to boolean values.


Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.

ng-style accepts an "expression" that must evaluate to:

  1. an map/object of CSS style names to CSS values

For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):

<div class="main-body" ng-style="{color: myColor}">
   ...
   <input type="text" ng-model="myColor" placeholder="enter a color name">


Fiddle for both of the above.

The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.

C# Equivalent of SQL Server DataTypes

SQL Server and .Net Data Type mapping

SQL Server and .Net Data Type mapping

"The Controls collection cannot be modified because the control contains code blocks"

The "<%#" databinding technique will not directly work inside <link> tags in the <head> tag:

<head runat="server">

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=<%# My.Constants.CSS_VERSION %>" />

</head>

The above code will evaluate to

<head>

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=&lt;%# My.Constants.CSS_VERSION %>" />

</head>

Instead, you should do the following (note the two double quotes inside):

<head runat="server">

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=<%# "" + My.Constants.CSS_VERSION %>" />

</head>

And you will get the desired result:

<head>

  <link rel="stylesheet" type="text/css" href="css/style.css?v=1.5" />

</head>

Convert month name to month number in SQL Server

You can use below code

DECLARE @T TABLE ([Month] VARCHAR(20))
INSERT INTO @T
SELECT 'January'
UNION
SELECT 'February'
UNION
SELECT 'March'`

SELECT MONTH('01-' + [Month] + '-2010') As MonthNumeric,[Month] FROM @T
ORDER BY MonthNumeric

Bower: ENOGIT Git is not installed or not in the PATH

I also got the same problem from cmd and resolved using the following steps.

First install the https://msysgit.github.io/ (if not alredy installed). Then set the Git path as suggested by skinneejoe:

set PATH=%PATH%;C:\Program Files\Git\bin;

Or this (notice the (x86)):

set PATH=%PATH%;C:\Program Files (x86)\Git\bin;

jQuery Validate - Enable validation for hidden fields

The plugin's author says you should use "square brackets without the quotes", []

http://bassistance.de/2011/10/07/release-validation-plugin-1-9-0/

Release: Validation Plugin 1.9.0: "...Another change should make the setup of forms with hidden elements easier, these are now ignored by default (option “ignore” has “:hidden” now as default). In theory, this could break an existing setup. In the unlikely case that it actually does, you can fix it by setting the ignore-option to “[]” (square brackets without the quotes)."

To change this setting for all forms:

$.validator.setDefaults({ 
    ignore: [],
    // any other default options and/or rules
});

(It is not required that .setDefaults() be within the document.ready function)

OR for one specific form:

$(document).ready(function() {

    $('#myform').validate({
        ignore: [],
        // any other options and/or rules
    });

});

EDIT:

See this answer for how to enable validation on some hidden fields but still ignore others.


EDIT 2:

Before leaving comments that "this does not work", keep in mind that the OP is simply asking about the jQuery Validate plugin and his question has nothing to do with how ASP.NET, MVC, or any other Microsoft framework can alter this plugin's normal expected behavior. If you're using a Microsoft framework, the default functioning of the jQuery Validate plugin is over-written by Microsoft's unobtrusive-validation plugin.

If you're struggling with the unobtrusive-validation plugin, then please refer to this answer instead: https://stackoverflow.com/a/11053251/594235

Set height of <div> = to height of another <div> through .css

If you're open to using javascript then you can get the property on an element like this: document.GetElementByID('rightdiv').style.getPropertyValue('max-height');

And you can set the attribute on an element like this: .setAttribute('style','max-height:'+heightVariable+';');

Note: if you're simply looking to set both element's max-height property in one line, you can do so like this:

#leftdiv,#rightdiv
{
    min-height: 600px;   
}

Search input with an icon Bootstrap 4

Update 2019

Why not use an input-group?

<div class="input-group col-md-4">
      <input class="form-control py-2" type="search" value="search" id="example-search-input">
      <span class="input-group-append">
        <button class="btn btn-outline-secondary" type="button">
            <i class="fa fa-search"></i>
        </button>
      </span>
</div>

And, you can make it appear inside the input using the border utils...

        <div class="input-group col-md-4">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
              <button class="btn btn-outline-secondary border-left-0 border" type="button">
                    <i class="fa fa-search"></i>
              </button>
            </span>
        </div>

Or, using a input-group-text w/o the gray background so the icon appears inside the input...

        <div class="input-group">
            <input class="form-control py-2 border-right-0 border" type="search" value="search" id="example-search-input">
            <span class="input-group-append">
                <div class="input-group-text bg-transparent"><i class="fa fa-search"></i></div>
            </span>
        </div>

Alternately, you can use the grid (row>col-) with no gutter spacing:

<div class="row no-gutters">
     <div class="col">
          <input class="form-control border-secondary border-right-0 rounded-0" type="search" value="search" id="example-search-input4">
     </div>
     <div class="col-auto">
          <button class="btn btn-outline-secondary border-left-0 rounded-0 rounded-right" type="button">
             <i class="fa fa-search"></i>
          </button>
     </div>
</div>

Or, prepend the icon like this...

<div class="input-group">
  <span class="input-group-prepend">
    <div class="input-group-text bg-transparent border-right-0">
      <i class="fa fa-search"></i>
    </div>
  </span>
  <input class="form-control py-2 border-left-0 border" type="search" value="..." id="example-search-input" />
  <span class="input-group-append">
    <button class="btn btn-outline-secondary border-left-0 border" type="button">
     Search
    </button>
  </span>
</div>

Demo of all Bootstrap 4 icon input options


enter image description here


Example with validation icons

matrix multiplication algorithm time complexity

In matrix multiplication there are 3 for loop, we are using since execution of each for loop requires time complexity O(n). So for three loops it becomes O(n^3)

Is there any way to start with a POST request using Selenium?

Selenium doesn't currently offer API for this, but there are several ways to initiate an HTTP request in your test. It just depends what language you are writing in.

In Java for example, it might look like this:

// setup the request
String request = "startpoint?stuff1=foo&stuff2=bar";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");

// get a response - maybe "success" or "true", XML or JSON etc.
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
    response.append(line);
    response.append('\r');
}
bufferedReader.close();

// continue with test
if (response.toString().equals("expected response"){
    // do selenium
}

how to display data values on Chart.js

From my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script> tag after the chart.js tag on your page), your charts begin to display values.

If you then choose you can customize it to fit your needs. The customization is clearly documented here but basically, the format is like this hypothetical example:

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: yourDataObject,
    options: {
        // other options
        plugins: {
            datalabels: {
                anchor :'end',
                align :'top',
                // and if you need to format how the value is displayed...
                formatter: function(value, context) {
                    return GetValueFormatted(value);
                }
            }
        }
    }
});

How can I get the current user's username in Bash?

Get the current task's user_struct

#define get_current_user()              \
({                                      \
    struct user_struct *__u;            \
    const struct cred *__cred;          \
    __cred = current_cred();            \
    __u = get_uid(__cred->user);        \
    __u;                                \
})

difference between throw and throw new Exception()

throw; rethrows the original exception and preserves its original stack trace.

throw ex; throws the original exception but resets the stack trace, destroying all stack trace information until your catch block.


NEVER write throw ex;


throw new Exception(ex.Message); is even worse. It creates a brand new Exception instance, losing the original stack trace of the exception, as well as its type. (eg, IOException).
In addition, some exceptions hold additional information (eg, ArgumentException.ParamName).
throw new Exception(ex.Message); will destroy this information too.

In certain cases, you may want to wrap all exceptions in a custom exception object, so that you can provide additional information about what the code was doing when the exception was thrown.

To do this, define a new class that inherits Exception, add all four exception constructors, and optionally an additional constructor that takes an InnerException as well as additional information, and throw your new exception class, passing ex as the InnerException parameter. By passing the original InnerException, you preserve all of the original exception's properties, including the stack trace.

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

$dbc is returning false. Your query has an error in it:

SELECT users.*, profile.* --You do not join with profile anywhere.
                                 FROM users 
                                 INNER JOIN contact_info 
                                 ON contact_info.user_id = users.user_id 
                                 WHERE users.user_id=3");

The fix for this in general has been described by Raveren.

sed one-liner to convert all uppercase to lowercase?

With tr:

# Converts upper to lower case 
$ tr '[:upper:]' '[:lower:]' < input.txt > output.txt

# Converts lower to upper case
$ tr '[:lower:]' '[:upper:]' < input.txt > output.txt

Or, sed on GNU (but not BSD or Mac as they don't support \L or \U):

# Converts upper to lower case
$ sed -e 's/\(.*\)/\L\1/' input.txt > output.txt

# Converts lower to upper case
$ sed -e 's/\(.*\)/\U\1/' input.txt > output.txt
 

Corrupt jar file

Try use the command jar -xvf fileName.jar and then do export the content of the decompressed file into a new Java project into Eclipse.

How to clear a textbox using javascript

just get element using

   function name()
   {  
   document.getElementById('elementid').value = "";
   }

you can call this function on onfocus event of textbox and clear the value

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

Where in an Eclipse workspace is the list of projects stored?

In Eclipse 3.3:

It's installed under your Eclipse workspace. Something like:

.metadata\.plugins\org.eclipse.core.resources\.projects\

within your workspace folder.

Under that folder is one folder per project. There's a file in there called .location, but it's binary.

So it looks like you can't do what you want, without interacting w/ Eclipse programmatically.

How to get all of the immediate subdirectories in Python

import glob
import os

def child_dirs(path):
     cd = os.getcwd()        # save the current working directory
     os.chdir(path)          # change directory 
     dirs = glob.glob("*/")  # get all the subdirectories
     os.chdir(cd)            # change directory to the script original location
     return dirs

The child_dirs function takes a path a directory and returns a list of the immediate subdirectories in it.

dir
 |
  -- dir_1
  -- dir_2

child_dirs('dir') -> ['dir_1', 'dir_2']

Playing a video in VideoView in Android

The code seems to be flawless! Simple and plain.
So it should work on the phone. The emulator is having hard time playing videos, it happened to me too.

Try increasing the required API level to the latest, it might help!

Right click on opened project, chose Properties > Android > check the latest version on the right side...

Igor

What does 'public static void' mean in Java?

It's three completely different things:

public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.

static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.

void means that the method has no return value. If the method returned an int you would write int instead of void.

The combination of all three of these is most commonly seen on the main method which most tutorials will include.

How do I link to part of a page? (hash?)

Here is how:

<a href="#go_middle">Go Middle</a>

<div id="go_middle">Hello There</div>

how to read a text file using scanner in Java?

This should help you..:

import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
    find(Recipe);
}
public void find(String Name){
    String newRecipe= Name+".txt";
    try{
        FileReader fr= new FileReader(newRecipe);
        BufferedReader br= new BufferedReader(fr);

        String str;


    while ((str=br.readLine()) != null){
            out.println(str + "\n");
        }
        br.close();

    }catch (IOException e){
        out.println("File Not Found!");
    }
}

}

Windows Batch: How to add Host-Entries?

Well I write a script which works very well.

> @echo off TITLE Modifying your HOSTS file COLOR F0 ECHO.
> 
> :LOOP SET Choice= SET /P Choice="Do you want to modify HOSTS file ?
> (Y/N)"
> 
> IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
> 
> ECHO. IF /I '%Choice%'=='Y' GOTO ACCEPTED IF /I '%Choice%'=='N' GOTO
> REJECTED ECHO Please type Y (for Yes) or N (for No) to proceed! ECHO.
> GOTO Loop
> 
> 
> :REJECTED ECHO Your HOSTS file was left
> unchanged>>%systemroot%\Temp\hostFileUpdate.log ECHO Finished. GOTO
> END
> 
> 
> :ACCEPTED SET NEWLINE=^& echo. ECHO Carrying out requested
> modifications to your HOSTS file FIND /C /I "www.youtube.com"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1    www.youtube.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "youtube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.facebook.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "facebook.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1    www.4everproxy.com
> >>%WINDIR%\system32\drivers\etc\hosts FIND /C /I "4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1    4everproxy.com >>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockvideos.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> unblockvideos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxyone.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxyone.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kuvia.eu" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    kuvia.eu>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "kuvia.eu/facebook-proxy"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> kuvia.eu/facebook-proxy>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "hidemytraxproxy.ca" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> hidemytraxproxy.ca>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "github.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> github.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "funproxy.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> funproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "en.wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> en.wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dronten.proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> dronten.proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zfreez.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> zfreez.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zendproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zendproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zalmos.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> zalmos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeunblockproxy.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubeunblockproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "youtubefreeproxy.net" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubefreeproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youliaoren.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youliaoren.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "xitenow.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> xitenow.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.vobas.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    vobas.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> www.unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.maddw.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    maddw.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND
> /C /I "facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.dolopo.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.dolopo.net>>%WINDIR%\system32\drivers\etc\hosts ECHO Finished GOTO
> END
> 
> 
> :END ECHO. ping -n 11 127.0.0.1 > nul EXIT

How to watch for a route change in AngularJS?

If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 
        // handle route changes     
    });
});

How to VueJS router-link active style

Let's make things simple, you don't need to read the document about a "custom tag" (as a 16 years web developer, I have enough this kind of tags, such as in struts, webwork, jsp, rails and now it's vuejs)

just press F12, and you will see the source code like:

    <div>
        <a href="#/topologies" class="luelue">page1</a> 
        <a href="#/" aria-current="page" class="router-link-exact-active router-link-active">page2</a> 
        <a href="#/databases" class="">page3</a>
    </div>

so just add styles for the .router-link-active or router-link-exact-active

if you want more details, check the router-link api:

https://router.vuejs.org/en/api/#router-link

mysql query result in php variable

Of course there is. Check out mysql_query, and mysql_fetch_row if you use MySQL.
Example from PHP manual:

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

Is there a code obfuscator for PHP?

Thicket™ Obfuscator for PHP

The PHP Obfuscator tool scrambles PHP source code to make it very difficult to understand or reverse-engineer (example). This provides significant protection for source code intellectual property that must be hosted on a website or shipped to a customer. It is a member of SD's family of Source Code Obfuscators.

Regular expression to allow spaces between words

Just add a space to end of your regex pattern as follows:

[a-zA-Z0-9_ ]

Replace negative values in an numpy array

Try numpy.clip:

>>> import numpy
>>> a = numpy.arange(-10, 10)
>>> a
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])
>>> a.clip(0, 10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

You can clip only the bottom half with clip(0).

>>> a = numpy.array([1, 2, 3, -4, 5])
>>> a.clip(0)
array([1, 2, 3, 0, 5])

You can clip only the top half with clip(max=n). (This is much better than my previous suggestion, which involved passing NaN to the first parameter and using out to coerce the type.):

>>> a.clip(max=2)
array([ 1,  2,  2, -4,  2])

Another interesting approach is to use where:

>>> numpy.where(a <= 2, a, 2)
array([ 1,  2,  2, -4,  2])

Finally, consider aix's answer. I prefer clip for simple operations because it's self-documenting, but his answer is preferable for more complex operations.

Left Join With Where Clause

When making OUTER JOINs (ANSI-89 or ANSI-92), filtration location matters because criteria specified in the ON clause is applied before the JOIN is made. Criteria against an OUTER JOINed table provided in the WHERE clause is applied after the JOIN is made. This can produce very different result sets. In comparison, it doesn't matter for INNER JOINs if the criteria is provided in the ON or WHERE clauses -- the result will be the same.

  SELECT  s.*, 
          cs.`value`
     FROM SETTINGS s
LEFT JOIN CHARACTER_SETTINGS cs ON cs.setting_id = s.id
                               AND cs.character_id = 1

extract digits in a simple way from a python string

This regular expression handles floats as well

import re
re_float = re.compile(r'\d*\.?\d+')

You could also add a group to the expression that catches your weight units.

re_banana = re.compile(r'(?P<number>\d*\.?\d+)\s?(?P<uni>[a-zA-Z]+)')

You can access the named groups like this re_banana.match("200 kgm").group('number').

I think this should help you getting started.

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

How do I install ASP.NET MVC 5 in Visual Studio 2012?

Microsoft has provided for you on their MSDN blogs: MVC 5 for VS2012. From that blog:

We have released ASP.NET and Web Tools 2013.1 for Visual Studio 2012. This release brings a ton of great improvements, and include some fantastic enhancements to ASP.NET MVC 5, Web API 2, Scaffolding and Entity Framework to users of Visual Studio 2012 and Visual Studio 2012 Express for Web.

You can download and start using these features now.

The download link is to a Web Platform Installer that will allow you to start a new MVC5 project from VS2012.

How to append new data onto a new line

import subprocess
subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)

Remove "Using default security password" on Spring Boot

If you are using Spring Boot version >= 2.0 try setting this bean in your configuration:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http.authorizeExchange().anyExchange().permitAll();
    return http.build();
}

Reference: https://stackoverflow.com/a/47292134/1195507

Calling a class function inside of __init__

You must declare parse_file like this; def parse_file(self). The "self" parameter is a hidden parameter in most languages, but not in python. You must add it to the definition of all that methods that belong to a class. Then you can call the function from any method inside the class using self.parse_file

your final program is going to look like this:

class MyClass():
  def __init__(self, filename):
      self.filename = filename 

      self.stat1 = None
      self.stat2 = None
      self.stat3 = None
      self.stat4 = None
      self.stat5 = None
      self.parse_file()

  def parse_file(self):
      #do some parsing
      self.stat1 = result_from_parse1
      self.stat2 = result_from_parse2
      self.stat3 = result_from_parse3
      self.stat4 = result_from_parse4
      self.stat5 = result_from_parse5

How to replace url parameter with javascript/jquery?

Editing a Parameter The set method of the URLSearchParams object sets the new value of the parameter.

After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.

The final new url can then be retrieved with the toString() method of the URL object.


var query_string = url.search;

var search_params = new URLSearchParams(query_string); 

// new value of "id" is set to "101"
search_params.set('id', '101');

// change the search property of the main url
url.search = search_params.toString();

// the new url string
var new_url = url.toString();

// output : http://demourl.com/path?id=101&topic=main
console.log(new_url);

Source - https://usefulangle.com/post/81/javascript-change-url-parameters

GSON - Date format

This is a bug. Currently you either have to set a timeStyle as well or use one of the alternatives described in the other answers.

Is it good practice to make the constructor throw an exception?

I've always considered throwing checked exceptions in the constructor to be bad practice, or at least something that should be avoided.

The reason for this is that you cannot do this :

private SomeObject foo = new SomeObject();

Instead you must do this :

private SomeObject foo;
public MyObject() {
    try {
        foo = new SomeObject()
    } Catch(PointlessCheckedException e) {
       throw new RuntimeException("ahhg",e);
    }
}

At the point when I'm constructing SomeObject I know what it's parameters are so why should I be expected to wrap it in a try catch? Ahh you say but if I'm constructing an object from dynamic parameters I don't know if they're valid or not. Well, you could... validate the parameters before passing them to the constructor. That would be good practice. And if all you're concerned about is whether the parameters are valid then you can use IllegalArgumentException.

So instead of throwing checked exceptions just do

public SomeObject(final String param) {
    if (param==null) throw new NullPointerException("please stop");
    if (param.length()==0) throw new IllegalArgumentException("no really, please stop");
}

Of course there are cases where it might just be reasonable to throw a checked exception

public SomeObject() {
    if (todayIsWednesday) throw new YouKnowYouCannotDoThisOnAWednesday();
}

But how often is that likely?

How to run a SQL query on an Excel table?

Microsoft Access and LibreOffice Base can open a spreadsheet as a source and run sql queries on it. That would be the easiest way to run all kinds of queries, and avoid the mess of running macros or writing code.

Excel also has autofilters and data sorting that will accomplish a lot of simple queries like your example. If you need help with those features, Google would be a better source for tutorials than me.

How can I combine hashes in Perl?

Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)


Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.

If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:

my %new_hash = %hash1; # make a copy; leave %hash1 alone

foreach my $key2 ( keys %hash2 )
    {
    if( exists $new_hash{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $new_hash{$key2} = $hash2{$key2};
        }
    }

If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.

foreach my $key2 ( keys %hash2 )
    {
    if( exists $hash1{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $hash1{$key2} = $hash2{$key2};
        }
    }

If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:

@hash1{ keys %hash2 } = values %hash2;

Enable UTF-8 encoding for JavaScript

thanks friends, after trying all and not getting desired result i think to use a hidden div with that arabic message and with jQuery fading affects solved the problem. Script I wrote is: .js file

$('#enterOpeningPrice').fadeIn();
$('#enterOpeningPrice').fadeOut(10000);

.html file

<div id="enterOpeningPrice">
    <p>???? ??? ????????</p>
</div>

Thanks to all..

How to ssh connect through python Paramiko with ppk public key

For me I doing this:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

works for me pretty ok

What is sys.maxint in Python 3?

An alternative is

import math

... math.inf ...

What is aria-label and how should I use it?

It's an attribute designed to help assistive technology (e.g. screen readers) attach a label to an otherwise anonymous HTML element.

So there's the <label> element:

<label for="fmUserName">Your name</label>
<input id="fmUserName">

The <label> explicitly tells the user to type their name into the input box where id="fmUserName".

aria-label does much the same thing, but it's for those cases where it isn't practical or desirable to have a label on screen. Take the MDN example:

<button aria-label="Close" onclick="myDialog.close()">X</button>`

Most people would be able to infer visually that this button will close the dialog. A blind person using assistive technology might just hear "X" read aloud, which doesn't mean much without the visual clues. aria-label explicitly tells them what the button will do.

What is the best way to remove a table row with jQuery?

id is not a good selector now. You can define some properties on the rows. And you can use them as selector.

<tr category="petshop" type="fish"><td>little fish</td></tr>
<tr category="petshop" type="dog"><td>little dog</td></tr>
<tr category="toys" type="lego"><td>lego starwars</td></tr>

and you can use a func to select the row like this (ES6):

const rowRemover = (category,type)=>{
   $(`tr[category=${category}][type=${type}]`).remove();
}

rowRemover('petshop','fish');

Sort tuples based on second parameter

    def findMaxSales(listoftuples):
        newlist = []
        tuple = ()
        for item in listoftuples:
             movie = item[0]
             value = (item[1])
             tuple = value, movie

             newlist += [tuple]
             newlist.sort()
             highest = newlist[-1]
             result = highest[1]
       return result

             movieList = [("Finding Dory", 486), ("Captain America: Civil                      

             War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The  Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
             print(findMaxSales(movieList))

output --> Rogue One

How can I connect to Android with ADB over TCP?

Assume you saved adb path into your Windows environment path

  1. Activate debug mode in Android

  2. Connect to PC via USB

  3. Open command prompt type: adb tcpip 5555

  4. Disconnect your tablet or smartphone from pc

  5. Open command prompt type: adb connect IPADDRESS (IPADDRESS is the DHCP/IP address of your tablet or smartphone, which you can find by Wi-Fi -> current connected network)

Now in command prompt you should see the result like: connected to xxx.xxx.xxx.xxx:5555

In Python, how do I create a string of n characters in one line of code?

Why "one line"? You can fit anything onto one line.

Assuming you want them to start with 'a', and increment by one character each time (with wrapping > 26), here's a line:

>>> mkstring = lambda(x): "".join(map(chr, (ord('a')+(y%26) for y in range(x))))
>>> mkstring(10)
'abcdefghij'
>>> mkstring(30)
'abcdefghijklmnopqrstuvwxyzabcd'

bash "if [ false ];" returns true instead of false -- why?

You are running the [ (aka test) command with the argument "false", not running the command false. Since "false" is a non-empty string, the test command always succeeds. To actually run the command, drop the [ command.

if false; then
   echo "True"
else
   echo "False"
fi

How do I change column default value in PostgreSQL?

If you want to remove the default value constraint, you can do:

ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;

Can you style an html radio button to look like a checkbox?

I don't think you can make a control look like anything other than a control with CSS.

Your best bet it to make a PRINT button goes to a new page with a graphic in place of the selected radio button, then do a window.print() from there.

Swapping pointers in C (char, int)

This example does not swap two int pointers. It swaps the value of the integers that pa and pb are pointing to. Here's an example of what's going on when you call this:

void Swap1 (int *pa, int *pb){
    int temp = *pa;
    *pa = *pb;
    *pb = temp;
}
int main()
{
    int a = 42;
    int b = 17;


    int *pa = &a;
    int *pb = &b;

    printf("--------Swap1---------\n");
    printf("a = %d\n b = %d\n", a, b);
    swap1(pa, pb);
    printf("a = %d\n = %d\n", a, a);
    printf("pb address =  %p\n", pa);
    printf("pa address =  %p\n", pb);
}

The output here is:

a = 42
b = 17
pa address =  0x7fffdf933228
pb address =  0x7fffdf93322c
--------Swap---------
pa = 17
pb = 42
a = 17
b = 42
pa address =  0x7fffdf933228
pb address =  0x7fffdf93322c

Note that the values swapped, but the pointer's addresses did not swap!

In order to swap addresses we need to do this:

void swap2 (int **pa, int **pb){
    int temp = *pa;
    *pa = *pb;
    *pb = temp;
}

and in main call the function like swap2(&pa, &pb);

Now the addresses are swapped, as well as the values for the pointers. a and b have the same values that the are initialized with The integers a and b did not swap because it swap2 swaps the addresses being being pointed to by the pointers!:

a = 42
b = 17
pa address =  0x7fffddaa9c98
pb address =  0x7fffddaa9c9c
--------Swap---------
pa = 17
pb = 42
a = 42
b = 17
pa address =  0x7fffddaa9c9c
pb address =  0x7fffddaa9c98

Since Strings in C are char pointers, and you want to swap Strings, you are really swapping a char pointer. As in the examples with an int, you need a double pointer to swap addresses.

The values of integers can be swapped even if the address isn't, but Strings are by definition a character pointer. You could swap one char with single pointers as the parameter, but a character pointer needs to be a double pointer in order to swap the strings.

IN Clause with NULL or IS NULL

The question as answered by Daniel is perfctly fine. I wanted to leave a note regarding NULLS. We should be carefull about using NOT IN operator when a column contains NULL values. You won't get any output if your column contains NULL values and you are using the NOT IN operator. This is how it's explained over here http://www.oraclebin.com/2013/01/beware-of-nulls.html , a very good article which I came across and thought of sharing it.

jQuery UI DatePicker to show month year only

for a monthpicker, using JQuery v 1.7.2, I have the following javascript which is doing just that

$l("[id$=txtDtPicker]").monthpicker({
showOn: "both",
buttonImage: "../../images/Calendar.png",
buttonImageOnly: true,
pattern: 'yyyymm', // Default is 'mm/yyyy' and separator char is not mandatory
monthNames: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez']
});

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

 function convertDatePickerTimeToMySQLTime(str) {
        var month, day, year, hours, minutes, seconds;
        var date = new Date(str),
            month = ("0" + (date.getMonth() + 1)).slice(-2),
            day = ("0" + date.getDate()).slice(-2);
        hours = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
        seconds = ("0" + date.getSeconds()).slice(-2);

        var mySQLDate = [date.getFullYear(), month, day].join("-");
        var mySQLTime = [hours, minutes, seconds].join(":");
        return [mySQLDate, mySQLTime].join(" ");
    }

Mockito, JUnit and Spring

The introduction of some new testing facilities in Spring 4.2.RC1 lets one write Spring integration tests that don't rely on the SpringJUnit4ClassRunner. Check out this part of the documentation.

In your case you could write your Spring integration test and still use mocks like this:

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration("test-app-ctx.xml")
public class FooTest {

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    @InjectMocks
    TestTarget sut;

    @Mock
    Foo mockFoo;

    @Test
    public void someTest() {
         // ....
    }
}

How to change the color of an svg element?

Only SVG with path information. you can't do that to the image.. as the path you can change stroke and fill information and you are done. like Illustrator

so: via CSS you can overwrite path fill value

path { fill: orange; }

but if you want more flexible way as you want to change it with a text when having some hovering effect going on.. use

path { fill: currentcolor; }

_x000D_
_x000D_
body {_x000D_
  background: #ddd;_x000D_
  text-align: center;_x000D_
  padding-top: 2em;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  width: 320px;_x000D_
  height: 50px;_x000D_
  display: block;_x000D_
  transition: all 0.3s;_x000D_
  cursor: pointer;_x000D_
  padding: 12px;_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
/***  desired colors for children  ***/_x000D_
.parent{_x000D_
  color: #000;_x000D_
  background: #def;_x000D_
}_x000D_
.parent:hover{_x000D_
  color: #fff;_x000D_
  background: #85c1fc;_x000D_
}_x000D_
_x000D_
.parent span{_x000D_
  font-size: 18px;_x000D_
  margin-right: 8px;_x000D_
  font-weight: bold;_x000D_
  font-family: 'Helvetica';_x000D_
  line-height: 26px;_x000D_
  vertical-align: top;_x000D_
}_x000D_
.parent svg{_x000D_
  max-height: 26px;_x000D_
  width: auto;_x000D_
  display: inline;_x000D_
}_x000D_
_x000D_
/****  magic trick  *****/_x000D_
.parent svg path{_x000D_
  fill: currentcolor;_x000D_
}
_x000D_
<div class='parent'>_x000D_
  <span>TEXT WITH SVG</span>_x000D_
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="128" height="128" viewBox="0 0 32 32">_x000D_
<path d="M30.148 5.588c-2.934-3.42-7.288-5.588-12.148-5.588-8.837 0-16 7.163-16 16s7.163 16 16 16c4.86 0 9.213-2.167 12.148-5.588l-10.148-10.412 10.148-10.412zM22 3.769c1.232 0 2.231 0.999 2.231 2.231s-0.999 2.231-2.231 2.231-2.231-0.999-2.231-2.231c0-1.232 0.999-2.231 2.231-2.231z"></path>_x000D_
</svg>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Writing a new line to file in PHP (line feed)

PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:

Using this will save you extra coding on cross platform developments.

IE.

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

If you looped through this twice you would see in 'somefile':

some data
some data

How to "git clone" including submodules?

[Quick Answer]

You can use this command to clone your repo with all the submodules:

git clone --recursive YOUR-GIT-REPO-URL

Or if you have already cloned the project, you can use:

git submodule init
git submodule update

How to get parameters from a URL string?

you can use below code to get email address after ? in the URL

_x000D_
_x000D_
<?php_x000D_
if (isset($_GET['email'])) {_x000D_
    echo $_GET['email'];_x000D_
}
_x000D_
_x000D_
_x000D_

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

OpenCV in Android Studio

Android Studio 3.4 + OpenCV 4.1

  1. Download the latest OpenCV zip file from here (current newest version is 4.1.0) and unzip it in your workspace or in another folder.

  2. Create new Android Studio project normally. Click File->New->Import Module, navigate to /path_to_unzipped_files/OpenCV-android-sdk/sdk/java, set Module name as opencv, click Next and uncheck all options in the screen.

  3. Enable Project file view mode (default mode is Android). In the opencv/build.gradle file change apply plugin: 'com.android.application' to apply plugin: 'com.android.library' and replace application ID "org.opencv" with

    minSdkVersion 21
    targetSdkVersion 28
    

    (according the values in app/build.gradle). Sync project with Gradle files.

  4. Add this string to the dependencies block in the app/build.gradle file

    dependencies {
        ...
        implementation project(path: ':opencv')
        ...
    }
    
  5. Select again Android file view mode. Right click on app module and goto New->Folder->JNI Folder. Select change folder location and set src/main/jniLibs/.

  6. Select again Project file view mode and copy all folders from /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/libs to app/src/main/jniLibs.

  7. Again in Android file view mode right click on app module and choose Link C++ Project with Gradle. Select Build System ndk-build and path to OpenCV.mk file /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/jni/OpenCV.mk.

    path_to_unzipped_files must not contain any spaces, or you will get error!

To check OpenCV initialization add Toast message in MainActivity onCreate() method:

Toast.makeText(MainActivity.this, String.valueOf(OpenCVLoader.initDebug()), Toast.LENGTH_LONG).show();

If initialization is successful you will see true in Toast message else you will see false.

How to delete multiple values from a vector?

The %in% operator tells you which elements are among the numers to remove:

> a <- sample (1 : 10)
> remove <- c (2, 3, 5)
> a
 [1] 10  5  2  7  1  6  3  4  8  9
> a %in% remove
 [1] FALSE  TRUE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
> a [! a %in% remove]
 [1] 10  7  1  6  4  8  9

Note that this will silently remove incomparables (stuff like NA or Inf) as well (while it will keep duplicate values in a as long as they are not listed in remove).

  • If a can contain incomparables, but remove will not, we can use match, telling it to return 0 for non-matches and incomparables (%in% is a conventient shortcut for match):

    > a <- c (a, NA, Inf)
    > a
     [1]  10   5   2   7   1   6   3   4   8   9  NA Inf
    > match (a, remove, nomatch = 0L, incomparables = 0L)
     [1] 0 3 1 0 0 0 2 0 0 0 0 0
    > a [match (a, remove, nomatch = 0L, incomparables = 0L) == 0L]
    [1]  10   7   1   6   4   8   9  NA Inf
    

    incomparables = 0 is not needed as incomparables will anyways not match, but I'd include it for the sake of readability.
    This is, btw., what setdiff does internally (but without the unique to throw away duplicates in a which are not in remove).

  • If remove contains incomparables, you'll have to check for them individually, e.g.

    if (any (is.na (remove))) 
      a <- a [! is.na (a)]
    

    (This does not distinguish NA from NaN but the R manual anyways warns that one should not rely on having a difference between them)

    For Inf/ -Inf you'll have to check both sign and is.finite

Tower of Hanoi: Recursive Algorithm

As a CS student, you might have heard about Mathematical induction. The recursive solution of Tower of Hanoi works analogously - only different part is to really get not lost with B and C as were the full tower ends up.

Setting a max height on a table

I had a coworker ask how to do this today, and this is what I came up with. I don't love it but it is a way to do it without js and have headers respected. The main drawback however is you lose some semantics due to not having a true table header anymore.

Basically I wrap a table within a table, and use a div as the scroll container by giving it a max-height. Since I wrap the table in a parent table "colspanning" the fake header rows it appears as if the table respects them, but in reality the child table just has the same number of rows.

One small issue due to the scroll bar taking up space the child table column widths wont match up exactly.

Live Demo

Markup

<table class="table-container">
    <tbody>
        <tr>
            <td>header col 1</td>
            <td>header col 2</td>
        </tr>
        <tr>
            <td colspan="2">
                <div class="scroll-container">
                    <table>
                        <tr>
                            <td>entry1</td>
                            <td>entry1</td>
                        </tr>
                       ........ all your entries
                    </table>
                </div>
            </td>
        </tr>
    </tbody>
</table>

CSS

.table-container {
    border:1px solid #ccc;
    border-radius: 3px;
    width:50%;
}
.table-container table {
    width: 100%;
}
.scroll-container{
    max-height: 150px;
    overflow-y: scroll;
}

href="file://" doesn't work

The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is because you specified http://file://

The http:// at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.

Note

If you link to something like

<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>

The above represents a link to a file called k:/yourfile.pdf on the k: drive on the machine on which you are viewing the URL.

You can do this, for example the below creates a link to C:\temp\test.pdf

<a href="file:///C:/Temp/test.pdf">test.pdf</a>

By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.

Most people do not have a K:/ drive.

But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).

You could try

<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>

Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is a malformed

Certificate is trusted by PC but not by Android

I had the same problem. Another way to generate the correct .crt file is like this:

Sometimes you get a .PEM file with an entire certificate chain inside. The file may look like this....

-----BEGIN RSA PRIVATE KEY-----
blablablabase64private...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
blablablabase64CRT1...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
blablablabase64CRT2...
-----END CERTIFICATE-----
...

If you remove the entire private key section, you will have a valid chained .crt

SELECT INTO Variable in MySQL DECLARE causes syntax error?

These answers don't cover very well MULTIPLE variables.

Doing the inline assignment in a stored procedure causes those results to ALSO be sent back in the resultset. That can be confusing. To using the SELECT...INTO syntax with multiple variables you do:

SELECT a, b INTO @a, @b FROM mytable LIMIT 1;

The SELECT must return only 1 row, hence LIMIT 1, although that isn't always necessary.

Powershell script does not run via Scheduled Tasks

I have another solution for this problem that might apply to some of you.

After I created my power shell (xyz.ps1) script, I opened it in notepad for subsequent editing. Hence Windows made an association between my xyz.ps1 file with notepad.exe and Scheduler was trying to run my power shell script (xyz.ps1) with notepad.exe in the background instead of executing it in Powershell. I found this problem by paying close attention to "Display all running tasks" section in the scheduler, which showed that notepad.exe was being used to run the xyz.ps1 script. To verify this, I right clicked on my xyz.ps1 file in windows explorer, went to "Properties", and it showed Notepad against the "Opens With" section. Then I changed the "Opens With" to %SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe. This did the trick. Now the scheduler would execute my xyz.ps1 using powershell.exe and gave me the desired results.

To locate your powershell.exe, refer to this article: https://www.powershelladmin.com/wiki/PowerShell_Executables_File_System_Locations

Iterate through <select> options

And the requisite, non-jquery way, for followers, since google seems to send everyone here:

  var select = document.getElementById("select_id");
  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    // now have option.text, option.value
  }

Check play state of AVPlayer

You can tell it's playing using:

AVPlayer *player = ...
if ((player.rate != 0) && (player.error == nil)) {
    // player is playing
}

Swift 3 extension:

extension AVPlayer {
    var isPlaying: Bool {
        return rate != 0 && error == nil
    }
}

Apache: client denied by server configuration

if you are having the

Allow from All

in httpd.conf then make sure us have

index.php

like in the below line in httpd.conf

DirectoryIndex index.html index.php

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

Look in HTML output for actual client ID

You need to look in the generated HTML output to find out the right client ID. Open the page in browser, do a rightclick and View Source. Locate the HTML representation of the JSF component of interest and take its id as client ID. You can use it in an absolute or relative way depending on the current naming container. See following chapter.

Note: if it happens to contain iteration index like :0:, :1:, etc (because it's inside an iterating component), then you need to realize that updating a specific iteration round is not always supported. See bottom of answer for more detail on that.

Memorize NamingContainer components and always give them a fixed ID

If a component which you'd like to reference by ajax process/execute/update/render is inside the same NamingContainer parent, then just reference its own ID.

<h:form id="form">
    <p:commandLink update="result"> <!-- OK! -->
    <h:panelGroup id="result" />
</h:form>

If it's not inside the same NamingContainer, then you need to reference it using an absolute client ID. An absolute client ID starts with the NamingContainer separator character, which is by default :.

<h:form id="form">
    <p:commandLink update="result"> <!-- FAIL! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- OK! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- FAIL! -->
</h:form>
<h:form id="otherform">
    <h:panelGroup id="result" />
</h:form>
<h:form id="form">
    <p:commandLink update=":otherform:result"> <!-- OK! -->
</h:form>
<h:form id="otherform">
    <h:panelGroup id="result" />
</h:form>

NamingContainer components are for example <h:form>, <h:dataTable>, <p:tabView>, <cc:implementation> (thus, all composite components), etc. You recognize them easily by looking at the generated HTML output, their ID will be prepended to the generated client ID of all child components. Note that when they don't have a fixed ID, then JSF will use an autogenerated ID in j_idXXX format. You should absolutely avoid that by giving them a fixed ID. The OmniFaces NoAutoGeneratedIdViewHandler may be helpful in this during development.

If you know to find the javadoc of the UIComponent in question, then you can also just check in there whether it implements the NamingContainer interface or not. For example, the HtmlForm (the UIComponent behind <h:form> tag) shows it implements NamingContainer, but the HtmlPanelGroup (the UIComponent behind <h:panelGroup> tag) does not show it, so it does not implement NamingContainer. Here is the javadoc of all standard components and here is the javadoc of PrimeFaces.

Solving your problem

So in your case of:

<p:tabView id="tabs"><!-- This is a NamingContainer -->
    <p:tab id="search"><!-- This is NOT a NamingContainer -->
        <h:form id="insTable"><!-- This is a NamingContainer -->
            <p:dialog id="dlg"><!-- This is NOT a NamingContainer -->
                <h:panelGrid id="display">

The generated HTML output of <h:panelGrid id="display"> looks like this:

<table id="tabs:insTable:display">

You need to take exactly that id as client ID and then prefix with : for usage in update:

<p:commandLink update=":tabs:insTable:display">

Referencing outside include/tagfile/composite

If this command link is inside an include/tagfile, and the target is outside it, and thus you don't necessarily know the ID of the naming container parent of the current naming container, then you can dynamically reference it via UIComponent#getNamingContainer() like so:

<p:commandLink update=":#{component.namingContainer.parent.namingContainer.clientId}:display">

Or, if this command link is inside a composite component and the target is outside it:

<p:commandLink update=":#{cc.parent.namingContainer.clientId}:display">

Or, if both the command link and target are inside same composite component:

<p:commandLink update=":#{cc.clientId}:display">

See also Get id of parent naming container in template for in render / update attribute

How does it work under the covers

This all is specified as "search expression" in the UIComponent#findComponent() javadoc:

A search expression consists of either an identifier (which is matched exactly against the id property of a UIComponent, or a series of such identifiers linked by the UINamingContainer#getSeparatorChar character value. The search algorithm should operates as follows, though alternate alogrithms may be used as long as the end result is the same:

  • Identify the UIComponent that will be the base for searching, by stopping as soon as one of the following conditions is met:
    • If the search expression begins with the the separator character (called an "absolute" search expression), the base will be the root UIComponent of the component tree. The leading separator character will be stripped off, and the remainder of the search expression will be treated as a "relative" search expression as described below.
    • Otherwise, if this UIComponent is a NamingContainer it will serve as the basis.
    • Otherwise, search up the parents of this component. If a NamingContainer is encountered, it will be the base.
    • Otherwise (if no NamingContainer is encountered) the root UIComponent will be the base.
  • The search expression (possibly modified in the previous step) is now a "relative" search expression that will be used to locate the component (if any) that has an id that matches, within the scope of the base component. The match is performed as follows:
    • If the search expression is a simple identifier, this value is compared to the id property, and then recursively through the facets and children of the base UIComponent (except that if a descendant NamingContainer is found, its own facets and children are not searched).
    • If the search expression includes more than one identifier separated by the separator character, the first identifier is used to locate a NamingContainer by the rules in the previous bullet point. Then, the findComponent() method of this NamingContainer will be called, passing the remainder of the search expression.

Note that PrimeFaces also adheres the JSF spec, but RichFaces uses "some additional exceptions".

"reRender" uses UIComponent.findComponent() algorithm (with some additional exceptions) to find the component in the component tree.

Those additional exceptions are nowhere in detail described, but it's known that relative component IDs (i.e. those not starting with :) are not only searched in the context of the closest parent NamingContainer, but also in all other NamingContainer components in the same view (which is a relatively expensive job by the way).

Never use prependId="false"

If this all still doesn't work, then verify if you aren't using <h:form prependId="false">. This will fail during processing the ajax submit and render. See also this related question: UIForm with prependId="false" breaks <f:ajax render>.

Referencing specific iteration round of iterating components

It was for long time not possible to reference a specific iterated item in iterating components like <ui:repeat> and <h:dataTable> like so:

<h:form id="form">
    <ui:repeat id="list" value="#{['one','two','three']}" var="item">
        <h:outputText id="item" value="#{item}" /><br/>
    </ui:repeat>

    <h:commandButton value="Update second item">
        <f:ajax render=":form:list:1:item" />
    </h:commandButton>
</h:form>

However, since Mojarra 2.2.5 the <f:ajax> started to support it (it simply stopped validating it; thus you would never face the in the question mentioned exception anymore; another enhancement fix is planned for that later).

This only doesn't work yet in current MyFaces 2.2.7 and PrimeFaces 5.2 versions. The support might come in the future versions. In the meanwhile, your best bet is to update the iterating component itself, or a parent in case it doesn't render HTML, like <ui:repeat>.

When using PrimeFaces, consider Search Expressions or Selectors

PrimeFaces Search Expressions allows you to reference components via JSF component tree search expressions. JSF has several builtin:

  • @this: current component
  • @form: parent UIForm
  • @all: entire document
  • @none: nothing

PrimeFaces has enhanced this with new keywords and composite expression support:

  • @parent: parent component
  • @namingcontainer: parent UINamingContainer
  • @widgetVar(name): component as identified by given widgetVar

You can also mix those keywords in composite expressions such as @form:@parent, @this:@parent:@parent, etc.

PrimeFaces Selectors (PFS) as in @(.someclass) allows you to reference components via jQuery CSS selector syntax. E.g. referencing components having all a common style class in the HTML output. This is particularly helpful in case you need to reference "a lot of" components. This only prerequires that the target components have all a client ID in the HTML output (fixed or autogenerated, doesn't matter). See also How do PrimeFaces Selectors as in update="@(.myClass)" work?

How to tell PowerShell to wait for each command to end before starting the next?

Besides using Start-Process -Wait, piping the output of an executable will make Powershell wait. Depending on the need, I will typically pipe to Out-Null, Out-Default, Out-String or Out-String -Stream. Here is a long list of some other output options.

# Saving output as a string to a variable.
$output = ping.exe example.com | Out-String

# Filtering the output.
ping stackoverflow.com | where { $_ -match '^reply' }

# Using Start-Process affords the most control.
Start-Process -Wait SomeExecutable.com

I do miss the CMD/Bash style operators that you referenced (&, &&, ||). It seems we have to be more verbose with Powershell.

Difference between application/x-javascript and text/javascript content types

According to RFC 4329 the correct MIME type for JavaScript should be application/javascript. Howerver, older IE versions choke on this since they expect text/javascript.

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

Moment JS start and end of given month

var d = new moment();
var startMonth = d.clone().startOf('month');
var endMonth = d.clone().endOf('month');
console.log(startMonth, endMonth);

doc

How unique is UUID?

Here's a testing snippet for you to test it's uniquenes. inspired by @scalabl3's comment

Funny thing is, you could generate 2 in a row that were identical, of course at mind-boggling levels of coincidence, luck and divine intervention, yet despite the unfathomable odds, it's still possible! :D Yes, it won't happen. just saying for the amusement of thinking about that moment when you created a duplicate! Screenshot video! – scalabl3 Oct 20 '15 at 19:11

If you feel lucky, check the checkbox, it only checks the currently generated id's. If you wish a history check, leave it unchecked. Please note, you might run out of ram at some point if you leave it unchecked. I tried to make it cpu friendly so you can abort quickly when needed, just hit the run snippet button again or leave the page.

_x000D_
_x000D_
Math.log2 = Math.log2 || function(n){ return Math.log(n) / Math.log(2); }_x000D_
  Math.trueRandom = (function() {_x000D_
  var crypt = window.crypto || window.msCrypto;_x000D_
_x000D_
  if (crypt && crypt.getRandomValues) {_x000D_
      // if we have a crypto library, use it_x000D_
      var random = function(min, max) {_x000D_
          var rval = 0;_x000D_
          var range = max - min;_x000D_
          if (range < 2) {_x000D_
              return min;_x000D_
          }_x000D_
_x000D_
          var bits_needed = Math.ceil(Math.log2(range));_x000D_
          if (bits_needed > 53) {_x000D_
            throw new Exception("We cannot generate numbers larger than 53 bits.");_x000D_
          }_x000D_
          var bytes_needed = Math.ceil(bits_needed / 8);_x000D_
          var mask = Math.pow(2, bits_needed) - 1;_x000D_
          // 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111_x000D_
_x000D_
          // Create byte array and fill with N random numbers_x000D_
          var byteArray = new Uint8Array(bytes_needed);_x000D_
          crypt.getRandomValues(byteArray);_x000D_
_x000D_
          var p = (bytes_needed - 1) * 8;_x000D_
          for(var i = 0; i < bytes_needed; i++ ) {_x000D_
              rval += byteArray[i] * Math.pow(2, p);_x000D_
              p -= 8;_x000D_
          }_x000D_
_x000D_
          // Use & to apply the mask and reduce the number of recursive lookups_x000D_
          rval = rval & mask;_x000D_
_x000D_
          if (rval >= range) {_x000D_
              // Integer out of acceptable range_x000D_
              return random(min, max);_x000D_
          }_x000D_
          // Return an integer that falls within the range_x000D_
          return min + rval;_x000D_
      }_x000D_
      return function() {_x000D_
          var r = random(0, 1000000000) / 1000000000;_x000D_
          return r;_x000D_
      };_x000D_
  } else {_x000D_
      // From http://baagoe.com/en/RandomMusings/javascript/_x000D_
      // Johannes Baagøe <[email protected]>, 2010_x000D_
      function Mash() {_x000D_
          var n = 0xefc8249d;_x000D_
_x000D_
          var mash = function(data) {_x000D_
              data = data.toString();_x000D_
              for (var i = 0; i < data.length; i++) {_x000D_
                  n += data.charCodeAt(i);_x000D_
                  var h = 0.02519603282416938 * n;_x000D_
                  n = h >>> 0;_x000D_
                  h -= n;_x000D_
                  h *= n;_x000D_
                  n = h >>> 0;_x000D_
                  h -= n;_x000D_
                  n += h * 0x100000000; // 2^32_x000D_
              }_x000D_
              return (n >>> 0) * 2.3283064365386963e-10; // 2^-32_x000D_
          };_x000D_
_x000D_
          mash.version = 'Mash 0.9';_x000D_
          return mash;_x000D_
      }_x000D_
_x000D_
      // From http://baagoe.com/en/RandomMusings/javascript/_x000D_
      function Alea() {_x000D_
          return (function(args) {_x000D_
              // Johannes Baagøe <[email protected]>, 2010_x000D_
              var s0 = 0;_x000D_
              var s1 = 0;_x000D_
              var s2 = 0;_x000D_
              var c = 1;_x000D_
_x000D_
              if (args.length == 0) {_x000D_
                  args = [+new Date()];_x000D_
              }_x000D_
              var mash = Mash();_x000D_
              s0 = mash(' ');_x000D_
              s1 = mash(' ');_x000D_
              s2 = mash(' ');_x000D_
_x000D_
              for (var i = 0; i < args.length; i++) {_x000D_
                  s0 -= mash(args[i]);_x000D_
                  if (s0 < 0) {_x000D_
                      s0 += 1;_x000D_
                  }_x000D_
                  s1 -= mash(args[i]);_x000D_
                  if (s1 < 0) {_x000D_
                      s1 += 1;_x000D_
                  }_x000D_
                  s2 -= mash(args[i]);_x000D_
                  if (s2 < 0) {_x000D_
                      s2 += 1;_x000D_
                  }_x000D_
              }_x000D_
              mash = null;_x000D_
_x000D_
              var random = function() {_x000D_
                  var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32_x000D_
                  s0 = s1;_x000D_
                  s1 = s2;_x000D_
                  return s2 = t - (c = t | 0);_x000D_
              };_x000D_
              random.uint32 = function() {_x000D_
                  return random() * 0x100000000; // 2^32_x000D_
              };_x000D_
              random.fract53 = function() {_x000D_
                  return random() +_x000D_
                      (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53_x000D_
              };_x000D_
              random.version = 'Alea 0.9';_x000D_
              random.args = args;_x000D_
              return random;_x000D_
_x000D_
          }(Array.prototype.slice.call(arguments)));_x000D_
      };_x000D_
      return Alea();_x000D_
  }_x000D_
}());_x000D_
_x000D_
Math.guid = function() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)    {_x000D_
      var r = Math.trueRandom() * 16 | 0,_x000D_
          v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
  });_x000D_
};_x000D_
function logit(item1, item2) {_x000D_
    console.log("Do "+item1+" and "+item2+" equal? "+(item1 == item2 ? "OMG! take a screenshot and you'll be epic on the world of cryptography, buy a lottery ticket now!":"No they do not. shame. no fame")+ ", runs: "+window.numberofRuns);_x000D_
}_x000D_
numberofRuns = 0;_x000D_
function test() {_x000D_
   window.numberofRuns++;_x000D_
   var x = Math.guid();_x000D_
   var y = Math.guid();_x000D_
   var test = x == y || historyTest(x,y);_x000D_
_x000D_
   logit(x,y);_x000D_
   return test;_x000D_
_x000D_
}_x000D_
historyArr = [];_x000D_
historyCount = 0;_x000D_
function historyTest(item1, item2) {_x000D_
    if(window.luckyDog) {_x000D_
       return false;_x000D_
    }_x000D_
    for(var i = historyCount; i > -1; i--) {_x000D_
        logit(item1,window.historyArr[i]);_x000D_
        if(item1 == history[i]) {_x000D_
            _x000D_
            return true;_x000D_
        }_x000D_
        logit(item2,window.historyArr[i]);_x000D_
        if(item2 == history[i]) {_x000D_
            _x000D_
            return true;_x000D_
        }_x000D_
_x000D_
    }_x000D_
    window.historyArr.push(item1);_x000D_
    window.historyArr.push(item2);_x000D_
    window.historyCount+=2;_x000D_
    return false;_x000D_
}_x000D_
luckyDog = false;_x000D_
document.body.onload = function() {_x000D_
document.getElementById('runit').onclick  = function() {_x000D_
window.luckyDog = document.getElementById('lucky').checked;_x000D_
var val = document.getElementById('input').value_x000D_
if(val.trim() == '0') {_x000D_
    var intervaltimer = window.setInterval(function() {_x000D_
         var test = window.test();_x000D_
         if(test) {_x000D_
            window.clearInterval(intervaltimer);_x000D_
         }_x000D_
    },0);_x000D_
}_x000D_
else {_x000D_
   var num = parseInt(val);_x000D_
   if(num > 0) {_x000D_
        var intervaltimer = window.setInterval(function() {_x000D_
         var test = window.test();_x000D_
         num--;_x000D_
         if(num < 0 || test) {_x000D_
    _x000D_
         window.clearInterval(intervaltimer);_x000D_
         }_x000D_
    },0);_x000D_
   }_x000D_
}_x000D_
};_x000D_
};
_x000D_
Please input how often the calulation should run. set to 0 for forever. Check the checkbox if you feel lucky.<BR/>_x000D_
<input type="text" value="0" id="input"><input type="checkbox" id="lucky"><button id="runit">Run</button><BR/>
_x000D_
_x000D_
_x000D_

How to count no of lines in text file and store the value into a variable using batch script?

In the below code, the variable name are SalaryCount and TaxCount

@ECHO OFF    
echo Process started, please wait...    
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Salary.txt"') do set SalaryCount=%%C    
echo Salary,%SalaryCount%
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Tax.txt"') do set TaxCount=%%C
echo Tax,%TaxCount%

Now if you need to output these values to a csv file, you could use the below code.

@ECHO OFF
cd "D:\CSVOutputPath\"
echo Process started, please wait...
echo FILENAME,FILECOUNT> SUMMARY.csv
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Salary.txt"') do set Count=%%C
echo Salary,%Count%>> SUMMARY.csv
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Tax.txt"') do set Count=%%C
echo Tax,%Count%>> SUMMARY.csv

The > will overwrite the existing content of the file and the >> will append the new data to existing data. The CSV will be generated in D:\CSVOutputPath

PHPUnit assert that an exception was thrown?

Code below will test exception message and exception code.

Important: It will fail if expected exception not thrown too.

try{
    $test->methodWhichWillThrowException();//if this method not throw exception it must be fail too.
    $this->fail("Expected exception 1162011 not thrown");
}catch(MySpecificException $e){ //Not catching a generic Exception or the fail function is also catched
    $this->assertEquals(1162011, $e->getCode());
    $this->assertEquals("Exception Message", $e->getMessage());
}

How can I select from list of values in Oracle

There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select '1,2,3,a,b,c,d' str from dual
  3  )
  4   select regexp_substr(str,'[^,]+',1,level) element
  5     from x
  6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /

ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d

7 rows selected.

Or in PL/SQL

SQL> create type str_tbl is table of varchar2(100);
  2  /

Type created.

SQL> create or replace function parse_list( p_list in varchar2 )
  2    return str_tbl
  3    pipelined
  4  is
  5  begin
  6    for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
  7                from dual
  8             connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
  9    loop
 10      pipe row( x.element );
 11    end loop
 12    return;
 13  end;
 14
 15  /

Function created.

SQL> select *
  2    from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));

COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f

9 rows selected.

Bootstrap 3: Offset isn't working?

If I get you right, you want something that seems to be the opposite of what is desired normally: you want a horizontal layout for small screens and vertically stacked elements on large screens. You may achieve this in a way like this:

<div class="container">
    <div class="row">
        <div class="hidden-md hidden-lg col-xs-3 col-xs-offset-6">a</div>
        <div class="hidden-md hidden-lg col-xs-3">b</div>
    </div>
    <div class="row">
        <div class="hidden-xs hidden-sm">c</div>

    </div>
</div>

On small screens, i.e. xs and sm, this generates one row with two columns with an offset of 6. On larger screens, i.e. md and lg, it generates two vertically stacked elements in full width (12 columns).

Space between border and content? / Border distance from content?

If you have background on that element, then, adding padding would be useless.

So, in this case, you can use background-clip: content-box; or outline-offset

Explanation: If you use wrapper, then it would be simple to separate the background from border. But if you want to style the same element, which has a background, no matter how much padding you would add, there would be no space between background and border, unless you use background-clip or outline-offset

Mapping list in Yaml to list of objects in Spring Boot

I had much issues with this one too. I finally found out what's the final deal.

Referring to @Gokhan Oner answer, once you've got your Service class and the POJO representing your object, your YAML config file nice and lean, if you use the annotation @ConfigurationProperties, you have to explicitly get the object for being able to use it. Like :

@ConfigurationProperties(prefix = "available-payment-channels-list")
//@Configuration  <-  you don't specificly need this, instead you're doing something else
public class AvailableChannelsConfiguration {

    private String xyz;
    //initialize arraylist
    private List<ChannelConfiguration> channelConfigurations = new ArrayList<>();

    public AvailableChannelsConfiguration() {
        for(ChannelConfiguration current : this.getChannelConfigurations()) {
            System.out.println(current.getName()); //TADAAA
        }
    }

    public List<ChannelConfiguration> getChannelConfigurations() {
        return this.channelConfigurations;
    }

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;
    }

}

And then here you go. It's simple as hell, but we have to know that we must call the object getter. I was waiting at initialization, wishing the object was being built with the value but no. Hope it helps :)

What is the purpose of meshgrid in Python / NumPy?

Suppose you have a function:

def sinus2d(x, y):
    return np.sin(x) + np.sin(y)

and you want, for example, to see what it looks like in the range 0 to 2*pi. How would you do it? There np.meshgrid comes in:

xx, yy = np.meshgrid(np.linspace(0,2*np.pi,100), np.linspace(0,2*np.pi,100))
z = sinus2d(xx, yy) # Create the image on this grid

and such a plot would look like:

import matplotlib.pyplot as plt
plt.imshow(z, origin='lower', interpolation='none')
plt.show()

enter image description here

So np.meshgrid is just a convenience. In principle the same could be done by:

z2 = sinus2d(np.linspace(0,2*np.pi,100)[:,None], np.linspace(0,2*np.pi,100)[None,:])

but there you need to be aware of your dimensions (suppose you have more than two ...) and the right broadcasting. np.meshgrid does all of this for you.

Also meshgrid allows you to delete coordinates together with the data if you, for example, want to do an interpolation but exclude certain values:

condition = z>0.6
z_new = z[condition] # This will make your array 1D

so how would you do the interpolation now? You can give x and y to an interpolation function like scipy.interpolate.interp2d so you need a way to know which coordinates were deleted:

x_new = xx[condition]
y_new = yy[condition]

and then you can still interpolate with the "right" coordinates (try it without the meshgrid and you will have a lot of extra code):

from scipy.interpolate import interp2d
interpolated = interp2d(x_new, y_new, z_new)

and the original meshgrid allows you to get the interpolation on the original grid again:

interpolated_grid = interpolated(xx[0], yy[:, 0]).reshape(xx.shape)

These are just some examples where I used the meshgrid there might be a lot more.

How to set the image from drawable dynamically in android?

Try this Dynamic code

String fnm = "cat"; //  this is image file name
String PACKAGE_NAME = getApplicationContext().getPackageName();
int imgId = getResources().getIdentifier(PACKAGE_NAME+":drawable/"+fnm , null, null);
System.out.println("IMG ID :: "+imgId);
System.out.println("PACKAGE_NAME :: "+PACKAGE_NAME);
//    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),imgId);
your_image_view.setImageBitmap(BitmapFactory.decodeResource(getResources(),imgId));

In above code you will need Image-file-Name and Image-View object which both you are having.

What exactly is RESTful programming?

Old question, newish way of answering. There's a lot of misconception out there about this concept. I always try to remember:

  1. Structured URLs and Http Methods/Verbs are not the definition of restful programming.
  2. JSON is not restful programming
  3. RESTful programming is not for APIs

I define restful programming as

An application is restful if it provides resources (being the combination of data + state transitions controls) in a media type the client understands

To be a restful programmer you must be trying to build applications that allow actors to do things. Not just exposing the database.

State transition controls only make sense if the client and server agree upon a media type representation of the resource. Otherwise there's no way to know what's a control and what isn't and how to execute a control. IE if browsers didn't know <form> tags in html then there'd be nothing for you to submit to transition state in your browser.

I'm not looking to self promote, but i expand on these ideas to great depth in my talk http://techblog.bodybuilding.com/2016/01/video-what-is-restful-200.html .

An excerpt from my talk is about the often referred to richardson maturity model, i don't believe in the levels, you either are RESTful (level 3) or you are not, but what i like to call out about it is what each level does for you on your way to RESTful

annotated richardson maturity model

Hive load CSV with commas in quoted fields

Add a backward slash in FIELDS TERMINATED BY '\;'

For Example:

CREATE  TABLE demo_table_1_csv
COMMENT 'my_csv_table 1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\;'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 'your_hdfs_path'
AS 
select a.tran_uuid,a.cust_id,a.risk_flag,a.lookback_start_date,a.lookback_end_date,b.scn_name,b.alerted_risk_category,
CASE WHEN (b.activity_id is not null ) THEN 1 ELSE 0 END as Alert_Flag 
FROM scn1_rcc1_agg as a LEFT OUTER JOIN scenario_activity_alert as b ON a.tran_uuid = b.activity_id;

I have tested it, and it worked.

Is there a way to get rid of accents and convert a whole string to regular letters?

I think the best solution is converting each char to HEX and replace it with another HEX. It's because there are 2 Unicode typing:

Composite Unicode
Precomposed Unicode

For example "Ô`" written by Composite Unicode is different from "?" written by Precomposed Unicode. You can copy my sample chars and convert them to see the difference.

In Composite Unicode, "Ô`" is combined from 2 char: Ô (U+00d4) and ` (U+0300)
In Precomposed Unicode, "?" is single char (U+1ED2)

I have developed this feature for some banks to convert the info before sending it to core-bank (usually don't support Unicode) and faced this issue when the end-users use multiple Unicode typing to input the data. So I think, converting to HEX and replace it is the most reliable way.

Why does ++[[]][+[]]+[+[]] return the string "10"?

Perhaps the shortest possible ways to evaluate an expression into "10" without digits are:

+!+[] + [+[]] // "10"

-~[] + [+[]] // "10"

//========== Explanation ==========\\

+!+[] : +[] Converts to 0. !0 converts to true. +true converts to 1. -~[] = -(-1) which is 1

[+[]] : +[] Converts to 0. [0] is an array with a single element 0.

Then JS evaluates the 1 + [0], thus Number + Array expression. Then the ECMA specification works: + operator converts both operands to a string by calling the toString()/valueOf() functions from the base Object prototype. It operates as an additive function if both operands of an expression are numbers only. The trick is that arrays easily convert their elements into a concatenated string representation.

Some examples:

1 + {} //    "1[object Object]"
1 + [] //    "1"
1 + new Date() //    "1Wed Jun 19 2013 12:13:25 GMT+0400 (Caucasus Standard Time)"

There's a nice exception that two Objects addition results in NaN:

[] + []   //    ""
[1] + [2] //    "12"
{} + {}   //    NaN
{a:1} + {b:2}     //    NaN
[1, {}] + [2, {}] //    "1,[object Object]2,[object Object]"

Flutter - Layout a Grid

Please visit this repo.

Widget _gridView() {
    return GridView.count(
      crossAxisCount: 4,
      padding: EdgeInsets.all(4.0),
      childAspectRatio: 8.0 / 9.0,
      children: itemList
          .map(
            (Item) => ItemList(item: Item),
          )
          .toList(),
    );
  }

Below screenshot contains crossAxisCount: 2 this screenshot is for grid count 2

Carousel with Thumbnails in Bootstrap 3.0

Bootstrap 4 (update 2019)

A multi-item carousel can be accomplished in several ways as explained here. Another option is to use separate thumbnails to navigate the carousel slides.

Bootstrap 3 (original answer)

This can be done using the grid inside each carousel item.

       <div id="myCarousel" class="carousel slide">
                <div class="carousel-inner">
                    <div class="item active">
                        <div class="row">
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                        </div>
                        <!--/row-->
                    </div>
                    ...add more item(s)
                 </div>
        </div>

Demo example thumbnail slider using the carousel:
http://www.bootply.com/81478

Another example with carousel indicators as thumbnails: http://www.bootply.com/79859

Copying the cell value preserving the formatting from one cell to another in excel using VBA

Using Excel 2010 ? Try

Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Error message "Strict standards: Only variables should be passed by reference"

$instance->find() returns a reference to a variable.

You get the report when you are trying to use this reference as an argument to a function, without storing it in a variable first.

This helps preventing memory leaks and will probably become an error in the next PHP versions.

Your second code block would throw an error if it wrote like (note the & in the function signature):

function &get_arr(){
    return array(1, 2);
}
$el = array_shift(get_arr());

So a quick (and not so nice) fix would be:

$el = array_shift($tmp = $instance->find(..));

Basically, you do an assignment to a temporary variable first and send the variable as an argument.

How to remove focus from input field in jQuery?

For all textbox :

$(':text').blur()

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

How do you get total amount of RAM the computer has?

Compatible with .Net and Mono (tested with Win10/FreeBSD/CentOS)

Using ComputerInfo source code and PerformanceCounters for Mono and as backup for .Net:

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

public class SystemMemoryInfo
{
    private readonly PerformanceCounter _monoAvailableMemoryCounter;
    private readonly PerformanceCounter _monoTotalMemoryCounter;
    private readonly PerformanceCounter _netAvailableMemoryCounter;

    private ulong _availablePhysicalMemory;
    private ulong _totalPhysicalMemory;

    public SystemMemoryInfo()
    {
        try
        {
            if (PerformanceCounterCategory.Exists("Mono Memory"))
            {
                _monoAvailableMemoryCounter = new PerformanceCounter("Mono Memory", "Available Physical Memory");
                _monoTotalMemoryCounter = new PerformanceCounter("Mono Memory", "Total Physical Memory");
            }
            else if (PerformanceCounterCategory.Exists("Memory"))
            {
                _netAvailableMemoryCounter = new PerformanceCounter("Memory", "Available Bytes");
            }
        }
        catch
        {
            // ignored
        }
    }

    public ulong AvailablePhysicalMemory
    {
        [SecurityCritical]
        get
        {
            Refresh();

            return _availablePhysicalMemory;
        }
    }

    public ulong TotalPhysicalMemory
    {
        [SecurityCritical]
        get
        {
            Refresh();

            return _totalPhysicalMemory;
        }
    }

    [SecurityCritical]
    [DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);

    [SecurityCritical]
    [DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);

    [SecurityCritical]
    private void Refresh()
    {
        try
        {
            if (_monoTotalMemoryCounter != null && _monoAvailableMemoryCounter != null)
            {
                _totalPhysicalMemory = (ulong) _monoTotalMemoryCounter.NextValue();
                _availablePhysicalMemory = (ulong) _monoAvailableMemoryCounter.NextValue();
            }
            else if (Environment.OSVersion.Version.Major < 5)
            {
                var memoryStatus = MEMORYSTATUS.Init();
                GlobalMemoryStatus(ref memoryStatus);

                if (memoryStatus.dwTotalPhys > 0)
                {
                    _availablePhysicalMemory = memoryStatus.dwAvailPhys;
                    _totalPhysicalMemory = memoryStatus.dwTotalPhys;
                }
                else if (_netAvailableMemoryCounter != null)
                {
                    _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();
                }
            }
            else
            {
                var memoryStatusEx = MEMORYSTATUSEX.Init();

                if (GlobalMemoryStatusEx(ref memoryStatusEx))
                {
                    _availablePhysicalMemory = memoryStatusEx.ullAvailPhys;
                    _totalPhysicalMemory = memoryStatusEx.ullTotalPhys;
                }
                else if (_netAvailableMemoryCounter != null)
                {
                    _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();
                }
            }
        }
        catch
        {
            // ignored
        }
    }

    private struct MEMORYSTATUS
    {
        private uint dwLength;
        internal uint dwMemoryLoad;
        internal uint dwTotalPhys;
        internal uint dwAvailPhys;
        internal uint dwTotalPageFile;
        internal uint dwAvailPageFile;
        internal uint dwTotalVirtual;
        internal uint dwAvailVirtual;

        public static MEMORYSTATUS Init()
        {
            return new MEMORYSTATUS
            {
                dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUS)))
            };
        }
    }

    private struct MEMORYSTATUSEX
    {
        private uint dwLength;
        internal uint dwMemoryLoad;
        internal ulong ullTotalPhys;
        internal ulong ullAvailPhys;
        internal ulong ullTotalPageFile;
        internal ulong ullAvailPageFile;
        internal ulong ullTotalVirtual;
        internal ulong ullAvailVirtual;
        internal ulong ullAvailExtendedVirtual;

        public static MEMORYSTATUSEX Init()
        {
            return new MEMORYSTATUSEX
            {
                dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUSEX)))
            };
        }
    }
}

How to properly apply a lambda function into a pandas data frame column

You need mask:

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)

Another solution with loc and boolean indexing:

sample.loc[sample['PR'] < 90, 'PR'] = np.nan

Sample:

import pandas as pd
import numpy as np

sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
    PR
0   10
1  100
2   40

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
      PR
0    NaN
1  100.0
2    NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
      PR
0    NaN
1  100.0
2    NaN

EDIT:

Solution with apply:

sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)

Timings len(df)=300k:

sample = pd.concat([sample]*100000).reset_index(drop=True)

In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop

In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop

Waiting until two async blocks are executed before starting another block

Another GCD alternative is a barrier:

dispatch_queue_t queue = dispatch_queue_create("com.company.app.queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{ 
    NSLog(@"start one!\n");  
    sleep(4);  
    NSLog(@"end one!\n");
});

dispatch_async(queue, ^{  
    NSLog(@"start two!\n");  
    sleep(2);  
    NSLog(@"end two!\n"); 
});

dispatch_barrier_async(queue, ^{  
    NSLog(@"Hi, I'm the final block!\n");  
});

Just create a concurrent queue, dispatch your two blocks, and then dispatch the final block with barrier, which will make it wait for the other two to finish.

How to calculate the inverse of the normal cumulative distribution function in python?

# given random variable X (house price) with population muy = 60, sigma = 40
import scipy as sc
import scipy.stats as sct
sc.version.full_version # 0.15.1

#a. Find P(X<50)
sct.norm.cdf(x=50,loc=60,scale=40) # 0.4012936743170763

#b. Find P(X>=50)
sct.norm.sf(x=50,loc=60,scale=40) # 0.5987063256829237

#c. Find P(60<=X<=80)
sct.norm.cdf(x=80,loc=60,scale=40) - sct.norm.cdf(x=60,loc=60,scale=40)

#d. how much top most 5% expensive house cost at least? or find x where P(X>=x) = 0.05
sct.norm.isf(q=0.05,loc=60,scale=40)

#e. how much top most 5% cheapest house cost at least? or find x where P(X<=x) = 0.05
sct.norm.ppf(q=0.05,loc=60,scale=40)

Test if number is odd or even

Try this one with #Input field

<?php
    //checking even and odd
    echo '<form action="" method="post">';
    echo "<input type='text' name='num'>\n";
    echo "<button type='submit' name='submit'>Check</button>\n";
    echo "</form>";

    $num = 0;
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["num"])) {
        $numErr = "<span style ='color: red;'>Number is required.</span>";
        echo $numErr;
        die();
      } else {
          $num = $_POST["num"];
      }


    $even = ($num % 2 == 0);
    $odd = ($num % 2 != 0);
    if ($num > 0){
        if($even){
            echo "Number is even.";
        } else {
            echo "Number is odd.";
        }
    } else {
        echo "Not a number.";
    }
    }
?>

jQuery override default validation error message display (Css) Popup/Tooltip like

Add following css to your .validate method to change the css or functionality

 errorElement: "div",
    wrapper: "div",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertAfter(element)
        error.css('color','red');
    }

Changing datagridview cell color based on condition

private void dataGridView1_DataBindingComplete(object sender DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (Convert.ToInt32(row.Cells["balaceAmount"].Value) == 0)
        {
            row.DefaultCellStyle.BackColor = Color.Yellow;
        }
        else
        {
            row.DefaultCellStyle.BackColor = Color.White;
        }
    }
}

Get values from an object in JavaScript

If you want to do this in a single line, try:

Object.keys(a).map(function(key){return a[key]})

Chmod 777 to a folder and all contents

for mac, should be a ‘superuser do’;

so first :

sudo -s 
password:

and then

chmod -R 777 directory_path

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

Find out time it took for a python script to complete execution

use the time and datetime packages.

if anybody want to execute this script and also find out how much time it took to execute in minutes

import time
from time import strftime
from datetime import datetime 
from time import gmtime

def start_time_():    
    #import time
    start_time = time.time()
    return(start_time)

def end_time_():
    #import time
    end_time = time.time()
    return(end_time)

def Execution_time(start_time_,end_time_):
   #import time
   #from time import strftime
   #from datetime import datetime 
   #from time import gmtime
   return(strftime("%H:%M:%S",gmtime(int('{:.0f}'.format(float(str((end_time-start_time))))))))

start_time = start_time_()
# your code here #
[i for i in range(0,100000000)]
# your code here #
end_time = end_time_()
print("Execution_time is :", Execution_time(start_time,end_time))

The above code works for me. I hope this helps.

How to start an application using android ADB tools?

Step 1: First get all the package name of the apps installed in your Device, by using:

adb shell pm list packages

Step 2: You will get all the package names, copy the one you want to start using adb.

Step 3: Add your desired package name in the below command.

adb shell monkey -p 'your package name' -v 500

For Example:
adb shell monkey -p com.estrongs.android.pop -v 500 to start the Es explorer.

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

I had the same issue while working with web services. Here Microsoft has a (long) walk-thru showing you how to install stuff on the client to basically say that your self-signed cert is ok. In the end, I just spent the $30 and bought a full certificate from Godaddy.com.

P.S. I know that you can code around the error message but we didn't want to do that for testing reasons.

Could not load file or assembly for Oracle.DataAccess in .NET

please register your Oracle.DataAccess to GAC

raProvCfg.exe /action:gac /providerpath:C:\oracle\product\11.2.0\x32\ODP.NET\bin\4\Oracle.DataAccess.dll

OraProvCfg.exe /action:gac /providerpath:C:\oracle\product\11.2.0\x64\ODP.NET\bin\4\Oracle.DataAccess.dll

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

You could also do what I do and by a commercial control like this one: http://www.syncfusion.com/products/reporting-edition/xlsio

I have been struging for years before ending with a commercial solution. I first tried the OLEDB approach that is very easy to use in my development environment but can be a knightmare to deploy. Then I tried the open source solutions but most of the are outdated and have bad support.

The xlsio controls from syncfusion are just the ones I use and are happy with but others exists. If you can affort it, do not hesitate, it's the best solution. Why? Because it has no dependencies with the system and supports all version of office right away. Among other advantages like, it's really fast.

And no, I do not work for synfusion ;)

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the formatter specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s).

Validating IPv4 addresses with regexp

-bash-3.2$ echo "191.191.191.39" | egrep 
  '(^|[^0-9])((2([6-9]|5[0-5]?|[0-4][0-9]?)?|1([0-9][0-9]?)?|[3-9][0-9]?|0)\.{3}
     (2([6-9]|5[0-5]?|[0-4][0-9]?)?|1([0-9][0-9]?)?|[3-9][0-9]?|0)($|[^0-9])'

>> 191.191.191.39

(This is a DFA that matches the entire addr space (including broadcasts, etc.) an nothing else.

How to vertically center a container in Bootstrap?

Vertically align center with bootstrap 4

Add this class: d-flex align-items-center to the element

Example

If you had this:

<div class="col-3">

change it to this:

<div class="col-3 d-flex align-items-center>

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

Sample settings.xml

The reference for the user-specific configuration for Maven is available on-line and it doesn't make much sense to share a settings.xml with you since these settings are user specific.

If you need to configure a proxy, have a look at the section about Proxies.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.somewhere.com</host>
      <port>8080</port>
      <username>proxyuser</username>
      <password>somepassword</password>
      <nonProxyHosts>*.google.com|ibiblio.org</nonProxyHosts>
    </proxy>
  </proxies>
  ...
</settings>
  • id: The unique identifier for this proxy. This is used to differentiate between proxy elements.
  • active: true if this proxy is active. This is useful for declaring a set of proxies, but only one may be active at a time.
  • protocol, host, port: The protocol://host:port of the proxy, seperated into discrete elements.
  • username, password: These elements appear as a pair denoting the login and password required to authenticate to this proxy server.
  • nonProxyHosts: This is a list of hosts which should not be proxied. The delimiter of the list is the expected type of the proxy server; the example above is pipe delimited - comma delimited is also common