Programs & Examples On #Fmj

FMJ is an open-source project with the goal of providing an alternative to Java Media Framework (JMF), while remaining API-compatible with JMF. It aims to produce a single API/Framework which can be used to capture, playback, process, and stream media across multiple platforms.

Can't perform a React state update on an unmounted component

If you are fetching data from axios and the error still occurs, just wrap the setter inside the condition

let isRendered = useRef(false);
useEffect(() => {
    isRendered = true;
    axios
        .get("/sample/api")
        .then(res => {
            if (isRendered) {
                setState(res.data);
            }
            return null;
        })
        .catch(err => console.log(err));
    return () => {
        isRendered = false;
    };
}, []);

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

Debugging in Maven?

Why not use the JPDA and attach to the launched process from a separate debugger process ? You should be able to specify the appropriate options in Maven to launch your process with the debugging hooks enabled. This article has more information.

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

For another instance of Glibc, download gcc 4.7.2, for instance from this github repo (although an official source would be better) and extract it to some folder, then update LD_LIBRARY_PATH with the path where you have extracted glib.

export LD_LIBRARY_PATH=$glibpath/glib-2.49.4-kgesagxmtbemim2denf65on4iixy3miy/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/libffi-3.2.1-wk2luzhfdpbievnqqtu24pi774esyqye/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/pcre-8.39-itdbuzevbtzqeqrvna47wstwczud67wx/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/gettext-0.19.8.1-aoweyaoufujdlobl7dphb2gdrhuhikil/lib:$LD_LIBRARY_PATH

This should keep you safe from bricking your CentOS*.

*Disclaimer: I just completed the thought it looks like the OP was trying to express, but I don't fully agree.

Android Support Design TabLayout: Gravity Center and Mode Scrollable

My final solution

class DynamicModeTabLayout : TabLayout {

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun setupWithViewPager(viewPager: ViewPager?) {
        super.setupWithViewPager(viewPager)

        val view = getChildAt(0) ?: return
        view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
        val size = view.measuredWidth

        if (size > measuredWidth) {
            tabMode = MODE_SCROLLABLE
            tabGravity = GRAVITY_CENTER
        } else {
            tabMode = MODE_FIXED
            tabGravity = GRAVITY_FILL
        }
    }
}

CSS selector for a checked radio button's label

If your input is a child element of the label and you have more than one labels, you can combine @Mike's trick with Flexbox + order.

enter image description here

_x000D_
_x000D_
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }



/* style the switch */

:root {
  --radio-size: 14px;
}

.switchLabel input.switch  {
  width: var(--radio-size);
  height: var(--radio-size);
  border-radius: 50%;
  border: 1px solid #999999;
  box-sizing: border-box;
  outline: none;
  -webkit-appearance: inherit;
  -moz-appearance: inherit;
  appearance: inherit;
  
  box-shadow: calc(var(--radio-size) / 2) 0 0 0 gray, calc(var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 calc(5px + var(--radio-size) / 2) 0 5px;
}

.switchLabel input.switch:checked {
  box-shadow: calc(-1 * var(--radio-size) / 2) 0 0 0 gray, calc(-1 * var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 5px 0 calc(5px + var(--radio-size) / 2);
}
_x000D_
<label class="switchLabel">
  <input type="checkbox" class="switch" />
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
_x000D_
_x000D_
_x000D_ asd

html
<label class="switchLabel">
  <input type="checkbox" class="switch"/>
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
css
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }

See it on JSFiddle.

note: Sibling selector only works within the same parent. To work around this, you can make the input hidden at top-level using @Nathan Blair hack.

How to connect to a docker container from outside the host (same network) [Windows]

  1. Open Oracle VM VirtualBox Manager
  2. Select the VM used by Docker
  3. Click Settings -> Network
  4. Adapter 1 should (default?) be "Attached to: NAT"
  5. Click Advanced -> Port Forwarding
  6. Add rule: Protocol TCP, Host Port 8080, Guest Port 8080 (leave Host IP and Guest IP empty)
  7. Guest is your docker container and Host is your machine

You should now be able to browse to your container via localhost:8080 and your-internal-ip:8080.

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

How to detect simple geometric shapes using OpenCV

The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.

Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:

double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer

Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.

Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.

In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis

Colspan all columns

Below is a concise es6 solution (similar to Rainbabba's answer but without the jQuery).

_x000D_
_x000D_
Array.from(document.querySelectorAll('[data-colspan-max]')).forEach(td => {_x000D_
    let table = td;_x000D_
    while (table && table.nodeName !== 'TABLE') table = table.parentNode;_x000D_
    td.colSpan = Array.from(table.querySelector('tr').children).reduce((acc, child) => acc + child.colSpan, 0);_x000D_
});
_x000D_
html {_x000D_
  font-family: Verdana;_x000D_
}_x000D_
tr > * {_x000D_
  padding: 1rem;_x000D_
  box-shadow: 0 0 8px gray inset;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
  <tr>_x000D_
    <th>Header 1</th>_x000D_
    <th>Header 2</th>_x000D_
    <th>Header 3</th>_x000D_
    <th>Header 4</th>_x000D_
    <th>Header 5</th>_x000D_
    <th>Header 6</th>_x000D_
  </tr>_x000D_
</thead>_x000D_
<tbod><tr>_x000D_
  <td data-colspan-max>td will be set to full width</td>_x000D_
</tr></tbod>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Scrollview vertical and horizontal in android

I found a better solution.

XML: (design.xml)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent">
  <FrameLayout android:layout_width="90px" android:layout_height="90px">
    <RelativeLayout android:id="@+id/container" android:layout_width="fill_parent" android:layout_height="fill_parent">        
    </RelativeLayout>
</FrameLayout>
</FrameLayout>

Java Code:

public class Example extends Activity {
  private RelativeLayout container;
  private int currentX;
  private int currentY;

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.design);

    container = (RelativeLayout)findViewById(R.id.container);

    int top = 0;
    int left = 0;

    ImageView image1 = ...
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image1, layoutParams);

    ImageView image2 = ...
    left+= 100;
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image2, layoutParams);

    ImageView image3 = ...
    left= 0;
    top+= 100;
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image3, layoutParams);

    ImageView image4 = ...
    left+= 100;     
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image4, layoutParams);
  }     

  @Override 
  public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            currentX = (int) event.getRawX();
            currentY = (int) event.getRawY();
            break;
        }

        case MotionEvent.ACTION_MOVE: {
            int x2 = (int) event.getRawX();
            int y2 = (int) event.getRawY();
            container.scrollBy(currentX - x2 , currentY - y2);
            currentX = x2;
            currentY = y2;
            break;
        }   
        case MotionEvent.ACTION_UP: {
            break;
        }
    }
      return true; 
  }
}

That's works!!!

If you want to load other layout or control, the structure is the same.

Database design for a survey

My design is shown below.

The latest create script is at https://gist.github.com/durrantm/1e618164fd4acf91e372

The script and the mysql workbench.mwb file are also available at
https://github.com/durrantm/survey enter image description here

jQuery: Handle fallback for failed AJAX Request

Dougs answer is correct, but you actually can use $.getJSON and catch errors (not having to use $.ajax). Just chain the getJSON call with a call to the fail function:

$.getJSON('/foo/bar.json')
    .done(function() { alert('request successful'); })
    .fail(function() { alert('request failed'); });

Live demo: http://jsfiddle.net/NLDYf/5/

This behavior is part of the jQuery.Deferred interface.
Basically it allows you to attach events to an asynchronous action after you call that action, which means you don't have to pass the event function to the action.

Read more about jQuery.Deferred here: http://api.jquery.com/category/deferred-object/

Mockito - difference between doReturn() and when()

The Mockito javadoc seems to tell why use doReturn() instead of when() Use doReturn() in those rare occasions when you cannot use Mockito.when(Object).

Beware that Mockito.when(Object) is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).

Here are those rare occasions when doReturn() comes handy:

1. When spying real objects and calling real methods on a spy brings side effects

List list = new LinkedList(); List spy = spy(list);

//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)

when(spy.get(0)).thenReturn("foo");

//You have to use doReturn() for stubbing: doReturn("foo").when(spy).get(0);

2. Overriding a previous exception-stubbing:

when(mock.foo()).thenThrow(new RuntimeException());

//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. when(mock.foo()).thenReturn("bar");

//You have to use doReturn() for stubbing:

doReturn("bar").when(mock).foo(); Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general overridding stubbing is a potential code smell that points out too much stubbing.

How to save a base64 image to user's disk using JavaScript?

This Works

function saveBase64AsFile(base64, fileName) {
    var link = document.createElement("a");
    document.body.appendChild(link);
    link.setAttribute("type", "hidden");
    link.href = "data:text/plain;base64," + base64;
    link.download = fileName;
    link.click();  
    document.body.removeChild(link);
}

Based on the answer above but with some changes

How to add dividers and spaces between items in RecyclerView?

Instead of create a shape xml for change the divider height and color. You can create programmatically like

val divider = DividerItemDecoration(context,
        DividerItemDecoration.VERTICAL)

divider.setDrawable(ShapeDrawable().apply {
    intrinsicHeight = resources.getDimensionPixelOffset(R.dimen.dp_15)
    paint.color = Color.RED // note: currently (support version 28.0.0), we can not use tranparent color here, if we use transparent, we still see a small divider line. So if we want to display transparent space, we can set color = background color or we can create a custom ItemDecoration instead of DividerItemDecoration. 
})

recycler_devices.addItemDecoration(divider)

Open Facebook page from Android app?

You can open the facebook app on button click as follows:-

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

    this.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            startNewActivity("com.facebook.katana");
        }
    });

}

public void startNewActivity( String packageName)
{
    Intent intent = MainActivity.this.getPackageManager().getLaunchIntentForPackage(packageName);
    if (intent != null)
    {
        // we found the activity
        // now start the activity
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    else
    {
        // bring user to the market
        // or let them choose an app?
        intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id="+packageName));
        startActivity(intent);
    }
}

Invert colors of an image in CSS or JavaScript

For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I am posting my answer because I suspect there might be someone out there for whom the above solutions might not have worked.

So, you are getting a warning,

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server: (project name)' did not find a matching property.

Rather than disabling this warning by checking that option in Server configuration (I did try that) I would suggest you do this:

  1. First close all the existing projects by right clicking in Project explorer.
  2. Remove all the projects already synchronized with the server.
  3. Remove the server and redeploy it.
  4. Create a new dynamic project, do nothing yet just try running this on the server.
  5. Check the console, do you get the warning now. (My case I didn't get any).
    This means that something is wrong with your project not with eclipse or the server.
  6. Now restart the server. Don't run any app yet.
    You probably know that the Tomcat container loads up context of all the synchronized apps at the start.
  7. It will load context of any already synchronized app.
  8. Here is the catch, if there is really something wrong in your project it will show the stack trace of the exceptions.Look carefully and you will find where is the bug in your app.

Now if you successfully found that there is a bug in your app, the probable place would be look for a web.xml file which the container uses for loading the app. In my case I had misspelled a name in servlet mapping which made me debug meaninglessly for 3 hours. Your problem might be someplace else.

And another thing, if you have many apps synchronized with the server,there is a possibility some other app's context might be the source of problem. Try debugging one by one.

Detect if a Form Control option button is selected in VBA

If you are using a Form Control, you can get the same property as ActiveX by using OLEFormat.Object property of the Shape Object. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.

Dim opt As OptionButton

With Sheets("Sheet1") ' Try to be always explicit
    Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
    Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With

But then again, you really don't need to know the value.
If you use Form Control, you associate a Macro or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.

For example you have 2 Form Control Option Buttons.

Sub CheckOptions()
    Select Case Application.Caller
    Case "Option Button 1"
    ' Action for option button 1
    Case "Option Button 2"
    ' Action for option button 2
    End Select
End Sub

In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller.
This way, no need to check whether the option button value is true or false.

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:

#!/bin/sh

# POST-COMMIT HOOK

REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log

MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

exit 0

HTML button calling an MVC Controller and Action method

OK, you basically need to pass the action to the button and call it when click happens, it doesn't need to be inside a from, you can use HTML onclick on button to trigger it when the button get clicked...

<button id="my-button" onclick="location.href='@Url.Action("YourActionName", "YourControllerName")'">Submit</button>

Regular Expression Match to test for a valid year

You need to add a start anchor ^ as:

^\d{4}$

Your regex \d{4}$ will match strings that end with 4 digits. So input like -1234 will be accepted.

By adding the start anchor you match only those strings that begin and end with 4 digits, which effectively means they must contain only 4 digits.

Variable not accessible when initialized outside function

Declare systemStatus in an outer scope and assign it in an onload handler.

systemStatus = null;

function onloadHandler(evt) {
    systemStatus = document.getElementById("....");
}

Or if you don't want the onload handler, put your script tag at the bottom of your HTML.

Mod in Java produces negative numbers

Since Java 8 you can use the Math.floorMod() method:

Math.floorMod(-1, 2); //== 1

Note: If the modulo-value (here 2) is negative, all output values will be negative too. :)

Source: https://stackoverflow.com/a/25830153/2311557

jQuery send HTML data through POST

If you want to send an arbitrary amount of data to your server, POST is the only reliable method to do that. GET would also be possible but clients and servers allow just a limited URL length (something like 2048 characters).

How to stop IIS asking authentication for default website on localhost

It is easier to remove the "Default Web Site" and create a new one if you do not have any limitations.

I did it and my problem solved.

Inline style to act as :hover in CSS

A simple solution:

   <a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>

Or

<script>
 /** Change the style **/
 function overStyle(object){
    object.style.color = 'orange';
    // Change some other properties ...
 }

 /** Restores the style **/
 function outStyle(object){
    object.style.color = 'orange';
    // Restore the rest ...
 }
</script>

<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>

VBA Check if variable is empty

I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.

At first I just used a boolean var and IF statement:

Dim i as integer, bol as boolean
   If bol = false then
      i = ValueIWantToAssign
      bol = True
   End If

In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.

Like so:

Dim i as integer
ForLoopStart
   If ConditionIsMet Then
      i = ValueIWantToAssign
   Exit For
   End If
ForLoopEnd

Equivalent of "continue" in Ruby

Writing Ian Purton's answer in a slightly more idiomatic way:

(1..5).each do |x|
  next if x < 2
  puts x
end

Prints:

  2
  3
  4
  5

How do I convert array of Objects into one Object in JavaScript?

Trying to fix this answer in How do I convert array of Objects into one Object in JavaScript?,

this should do it:

_x000D_
_x000D_
var array = [_x000D_
    {key:'k1',value:'v1'},_x000D_
    {key:'k2',value:'v2'},_x000D_
    {key:'k3',value:'v3'}_x000D_
];_x000D_
var mapped = array .map(item => ({ [item.key]: item.value }) );_x000D_
var newObj = Object.assign({}, ...mapped );_x000D_
console.log(newObj );
_x000D_
_x000D_
_x000D_


One-liner:

var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));

Send password when using scp to copy files from one server to another

Firts as mentioned by David, we need to set up public/private key.

Then using below command had worked for me, means it didn't prompt me for password as we are passing private key in the command using -i option

scp -i path/to/private_key path/to/local/file remoteUserId@remoteHost:/path/to/remote/folder

Here path/to/private_key is private key file which we generated while setting up public/private key.

Is there a way to suppress JSHint warning for one given line?

Yes, there is a way. Two in fact. In October 2013 jshint added a way to ignore blocks of code like this:

// Code here will be linted with JSHint.
/* jshint ignore:start */
// Code here will be ignored by JSHint.
/* jshint ignore:end */
// Code here will be linted with JSHint.

You can also ignore a single line with a trailing comment like this:

ignoreThis(); // jshint ignore:line

MongoDB or CouchDB - fit for production?

We are using MongoDB in production in our mobile backend service namely Netmera. We are using it to store all user and content data.

JavaScript variable number of arguments to function

It is preferable to use rest parameter syntax as Ramast pointed out.

function (a, b, ...args) {}

I just want to add some nice property of the ...args argument

  1. It is an array, and not an object like arguments. This allows you to apply functions like map or sort directly.
  2. It does not include all parameters but only the one passed from it on. E.g. function (a, b, ...args) in this case args contains argument 3 to arguments.length

How to get a list of images on docker registry v2

We wrote a CLI tool for this purpose: docker-ls It allows you to browse a docker registry and supports authentication via token or basic auth.

How do I find an element position in std::vector?

In this case, it is safe to cast away the unsigned portion unless your vector can get REALLY big.

I would pull out the where.size() to a local variable since it won't change during the call. Something like this:

int find( const vector<type>& where, int searchParameter ){
    int size = static_cast<int>(where.size());
    for( int i = 0; i < size; i++ ) {
       if( conditionMet( where[i], searchParameter ) ) {
           return i;
       }
    }
    return -1;
}

Sending HTML mail using a shell script

So far I have found two quick ways in cmd linux

  1. Use old school mail

mail -s "$(echo -e "This is Subject\nContent-Type: text/html")" [email protected] < mytest.html

  1. Use mutt

mutt -e "my_hdr Content-Type: text/html" [email protected] -s "subject" < mytest.html

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

Best way to work with dates in Android SQLite

  1. As presumed in this comment, I'd always use integers to store dates.
  2. For storing, you could use a utility method

    public static Long persistDate(Date date) {
        if (date != null) {
            return date.getTime();
        }
        return null;
    }
    

    like so:

    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME, persistDate(entity.getDate()));
    long id = db.insertOrThrow(TABLE_NAME, null, values);
    
  3. Another utility method takes care of the loading

    public static Date loadDate(Cursor cursor, int index) {
        if (cursor.isNull(index)) {
            return null;
        }
        return new Date(cursor.getLong(index));
    }
    

    can be used like this:

    entity.setDate(loadDate(cursor, INDEX));
    
  4. Ordering by date is simple SQL ORDER clause (because we have a numeric column). The following will order descending (that is newest date goes first):

    public static final String QUERY = "SELECT table._id, table.dateCol FROM table ORDER BY table.dateCol DESC";
    
    //...
    
        Cursor cursor = rawQuery(QUERY, null);
        cursor.moveToFirst();
    
        while (!cursor.isAfterLast()) {
            // Process results
        }
    

Always make sure to store the UTC/GMT time, especially when working with java.util.Calendar and java.text.SimpleDateFormat that use the default (i.e. your device's) time zone. java.util.Date.Date() is safe to use as it creates a UTC value.

nginx- duplicate default server error

OS Debian 10 + nginx. In my case, i unlinked the "default" page as:

  1. cd/etc/nginx/sites-enabled
  2. unlink default
  3. service nginx restart

How do I remove repeated elements from ArrayList?

Although converting the ArrayList to a HashSet effectively removes duplicates, if you need to preserve insertion order, I'd rather suggest you to use this variant

// list is some List of Strings
Set<String> s = new LinkedHashSet<>(list);

Then, if you need to get back a List reference, you can use again the conversion constructor.

Using continue in a switch statement

It's syntactically correct and stylistically okay.

Good style requires every case: statement should end with one of the following:

 break;
 continue;
 return (x);
 exit (x);
 throw (x);
 //fallthrough

Additionally, following case (x): immediately with

 case (y):
 default:

is permissible - bundling several cases that have exactly the same effect.

Anything else is suspected to be a mistake, just like if(a=4){...} Of course you need enclosing loop (while, for, do...while) for continue to work. It won't loop back to case() alone. But a construct like:

while(record = getNewRecord())
{
    switch(record.type)
    {
        case RECORD_TYPE_...;
            ...
        break;
        default: //unknown type
            continue; //skip processing this record altogether.
    }
    //...more processing...
}

...is okay.

How can I use pointers in Java?

from the book named Decompiling Android by Godfrey Nolan

Security dictates that pointers aren’t used in Java so hackers can’t break out of an application and into the operating system. No pointers means that something else----in this case, the JVM----has to take care of the allocating and freeing memory. Memory leaks should also become a thing of the past, or so the theory goes. Some applications written in C and C++ are notorious for leaking memory like a sieve because programmers don’t pay attention to freeing up unwanted memory at the appropriate time----not that anybody reading this would be guilty of such a sin. Garbage collection should also make programmers more productive, with less time spent on debugging memory problems.

AngularJS multiple filter with custom filter function

Try this:

<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">

$scope.ageFilter = function (player) {
    return (player.age > $scope.min_age && player.age < $scope.max_age);
}

git: undo all working dir changes including new files

You can do this in two steps:

  1. Revert modified files: git checkout -f
  2. Remove untracked files: git clean -fd

sendKeys() in Selenium web driver

Try this code:

WebElement userName = pathfinderdriver.switchTo().activeElement();
userName.sendKeys(Keys.TAB);

TABLOCK vs TABLOCKX

This is more of an example where TABLOCK did not work for me and TABLOCKX did.

I have 2 sessions, that both use the default (READ COMMITTED) isolation level:

Session 1 is an explicit transaction that will copy data from a linked server to a set of tables in a database, and takes a few seconds to run. [Example, it deletes Questions] Session 2 is an insert statement, that simply inserts rows into a table that Session 1 doesn't make changes to. [Example, it inserts Answers].

(In practice there are multiple sessions inserting multiple records into the table, simultaneously, while Session 1 is running its transaction).

Session 1 has to query the table Session 2 inserts into because it can't delete records that depend on entries that were added by Session 2. [Example: Delete questions that have not been answered].

So, while Session 1 is executing and Session 2 tries to insert, Session 2 loses in a deadlock every time.

So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ LEFT JOIN tblX on ... LEFT JOIN tblA a ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...

The deadlock seems to be caused from contention between querying tblA while Session 2, [3, 4, 5, ..., n] try to insert into tblA.

In my case I could change the isolation level of Session 1's transaction to be SERIALIZABLE. When I did this: The transaction manager has disabled its support for remote/network transactions.

So, I could follow instructions in the accepted answer here to get around it: The transaction manager has disabled its support for remote/network transactions

But a) I wasn't comfortable with changing the isolation level to SERIALIZABLE in the first place- supposedly it degrades performance and may have other consequences I haven't considered, b) didn't understand why doing this suddenly caused the transaction to have a problem working across linked servers, and c) don't know what possible holes I might be opening up by enabling network access.

There seemed to be just 6 queries within a very large transaction that are causing the trouble.

So, I read about TABLOCK and TabLOCKX.

I wasn't crystal clear on the differences, and didn't know if either would work. But it seemed like it would. First I tried TABLOCK and it didn't seem to make any difference. The competing sessions generated the same deadlocks. Then I tried TABLOCKX, and no more deadlocks.

So, in six places, all I needed to do was add a WITH (TABLOCKX).

So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ q LEFT JOIN tblX x on ... LEFT JOIN tblA a WITH (TABLOCKX) ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

How to execute a shell script in PHP?

Several possibilities:

  • You have safe mode enabled. That way, only exec() is working, and then only on executables in safe_mode_exec_dir
  • exec and shell_exec are disabled in php.ini
  • The path to the executable is wrong. If the script is in the same directory as the php file, try exec(dirname(__FILE__) . '/myscript.sh');

Javascript dynamic array of strings

Please check http://jsfiddle.net/GEBrW/ for live test.

You can use similar method for dynamic arrays creation.

var i = 0;
var a = new Array();

a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;

The result:

a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8

Toolbar overlapping below status bar

Just set this to v21/styles.xml file

 <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 <item name="android:statusBarColor">@color/colorPrimaryDark</item>

and be sure

 <item name="android:windowTranslucentStatus">false</item>

Java Generics With a Class & an Interface - Together

You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
    T t;
}

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

Change this dialog.cancel(); to dialog.dismiss();

The solution is to call dismiss() on the Dialog you created in NetErrorPage.java:114 before exiting the Activity, e.g. in onPause().

Views have a reference to their parent Context (taken from constructor argument). If you leave an Activity without destroying Dialogs and other dynamically created Views, they still hold this reference to your Activity (if you created with this as Context: like new ProgressDialog(this)), so it cannot be collected by the GC, causing a memory leak.

Create a tag in a GitHub repository

You just have to push the tag after you run the git tag 2.0 command.

So just do git push --tags now.

Set background color of WPF Textbox in C# code

Have you taken a look at Color.FromRgb?

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

For the most part, every C instruction corresponds to a very few assembler instructions. You are essentially writing higher level machine code, so you have control over almost everything the processor does. Many other compiled languages, such as C++, have a lot of simple looking instructions that can turn into much more code than you think it does (virtual functions, copy constructors, etc..) And interpreted languages like Java or Ruby have another layer of instructions that you never see - the Virtual Machine or Interpreter.

Using CSS to insert text

The answer using jQuery that everyone seems to like has a major flaw, which is it is not scalable (at least as it is written). I think Martin Hansen has the right idea, which is to use HTML5 data-* attributes. And you can even use the apostrophe correctly:

html:

<div class="task" data-task-owner="Joe">mop kitchen</div>
<div class="task" data-task-owner="Charles" data-apos="1">vacuum hallway</div>

css:

div.task:before { content: attr(data-task-owner)"'s task - " ; }
div.task[data-apos]:before { content: attr(data-task-owner)"' task - " ; }

output:

Joe's task - mop kitchen
Charles' task - vacuum hallway

Richtextbox wpf binding

Create a UserControl which has a RichTextBox named RTB. Now add the following dependency property:

    public FlowDocument Document
    {
        get { return (FlowDocument)GetValue(DocumentProperty); }
        set { SetValue(DocumentProperty, value); }
    }

    public static readonly DependencyProperty DocumentProperty =
        DependencyProperty.Register("Document", typeof(FlowDocument), typeof(RichTextBoxControl), new PropertyMetadata(OnDocumentChanged));

    private static void OnDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        RichTextBoxControl control = (RichTextBoxControl) d;
        FlowDocument document = e.NewValue as FlowDocument;
        if (document  == null)
        {
            control.RTB.Document = new FlowDocument(); //Document is not amused by null :)
        }
        else
        {
            control.RTB.Document = document;
        }
    }

This solution is probably that "proxy" solution you saw somewhere.. However.. RichTextBox simply does not have Document as DependencyProperty... So you have to do this in another way...

HTH

Is it possible to disable scrolling on a ViewPager

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;

public class NonSwipeableViewPager extends ViewPager {

public NonSwipeableViewPager(Context context) {
    super(context);
}

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

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    // stop swipe 
    return false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // stop switching pages
    return false;
}

private void setMyScroller() {
    try {
        Class<?> viewpager = ViewPager.class;
        Field scroller = viewpager.getDeclaredField("mScroller");
        scroller.setAccessible(true);
        scroller.set(this, new MyScroller(getContext()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public class MyScroller extends Scroller {
    public MyScroller(Context context) {
        super(context, new DecelerateInterpolator());
    }

    @Override
    public void startScroll(int startX, int startY, int dx, int dy, int 
duration) {
        super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
    }
}
}

Then in your Layout.XML file replace any --- com.android.support.V4.ViewPager --- tags with --- com.yourpackage.NonSwipeableViewPager --- tags.

jQuery Ajax POST example with PHP

Pure JS

In pure JS it will be much simpler

foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}

_x000D_
_x000D_
foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}
_x000D_
<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>
_x000D_
_x000D_
_x000D_

Difference between Inheritance and Composition

The answer given by @Michael Rodrigues is not correct (I apologize; I'm not able to comment directly), and could lead to some confusion.

Interface implementation is a form of inheritance... when you implement an interface, you're not only inheriting all the constants, you are committing your object to be of the type specified by the interface; it's still an "is-a" relationship. If a car implements Fillable, the car "is-a" Fillable, and can be used in your code wherever you would use a Fillable.

Composition is fundamentally different from inheritance. When you use composition, you are (as the other answers note) making a "has-a" relationship between two objects, as opposed to the "is-a" relationship that you make when you use inheritance.

So, from the car examples in the other questions, if I wanted to say that a car "has-a" gas tank, I would use composition, as follows:

public class Car {

private GasTank myCarsGasTank;

}

Hopefully that clears up any misunderstanding.

How to get file_get_contents() to work with HTTPS?

Try the following.

function getSslPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

Note: This disables SSL verification, meaning the security offered by HTTPS is lost. Only use this code for testing / local development, never on the internet or other public-facing networks. If this code works, it means the SSL certificate isn't trusted or can't be verified, which you should look into fixing as a separate issue.

Getting and removing the first character of a string

Use this function from stringi package

> x <- 'hello stackoverflow'
> stri_sub(x,2)
[1] "ello stackoverflow"

cartesian product in pandas

If you have a key that is repeated for each row, then you can produce a cartesian product using merge (like you would in SQL).

from pandas import DataFrame, merge
df1 = DataFrame({'key':[1,1], 'col1':[1,2],'col2':[3,4]})
df2 = DataFrame({'key':[1,1], 'col3':[5,6]})

merge(df1, df2,on='key')[['col1', 'col2', 'col3']]

Output:

   col1  col2  col3
0     1     3     5
1     1     3     6
2     2     4     5
3     2     4     6

See here for the documentation: http://pandas.pydata.org/pandas-docs/stable/merging.html#brief-primer-on-merge-methods-relational-algebra

How to disable Hyper-V in command line?

You can have a Windows 10 configuration with and without Hyper-V as follows in an Admin prompt:

bcdedit /copy {current} /d "Windows 10 no Hyper-V"

find the new id of the just created "Windows 10 no Hyper-V" bootentry, eg. {094a0b01-3350-11e7-99e1-bc5ec82bc470}

bcdedit /set {094a0b01-3350-11e7-99e1-bc5ec82bc470} hypervisorlaunchtype Off

After rebooting you can choose between Windows 10 with and without Hyper-V at startup

How to generate a range of numbers between two numbers?

Select non-persisted values with the VALUES keyword. Then use JOINs to generate lots and lots of combinations (can be extended to create hundreds of thousands of rows and beyond).

SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
     (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
     (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
     (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
WHERE ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n BETWEEN @userinput1 AND @userinput2
ORDER BY 1

Demo

A shorter alternative, that is not as easy to understand:

WITH x AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n
FROM x ones,     x tens,      x hundreds,       x thousands
ORDER BY 1

Demo

How do I close an open port from the terminal on the Mac?

very simple find port 5900:

sudo lsof -i :5900

then considering 59553 as PID

sudo kill 59553

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

How to run console application from Windows Service?

I have a Windows service, and I added the following line to the constructor for my service:

using System.Diagnostics;
try {
    Process p = Process.Start(@"C:\Windows\system32\calc.exe");
} catch {
    Debugger.Break();
}

When I tried to run this, the Process.Start() call was made, and no exception occurred. However, the calc.exe application did not show up. In order to make it work, I had edit the properties for my service in the Service Control Manager to enable interaction with the desktop. After doing that, the Process.Start() opened calc.exe as expected.

But as others have said, interaction with the desktop is frowned upon by Microsoft and has essentially been disabled in Vista. So even if you can get it to work in XP, I don't know that you'll be able to make it work in Vista.

How to enable authentication on MongoDB through Docker?

If you take a look at:

you will notice that there are two variables used in the docker-entrypoint.sh:

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

You can use them to setup root user. For example you can use following docker-compose.yml file:

mongo-container:
  image: mongo:3.4.2
  environment:
      # provide your credentials here
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=rootPassXXX
  ports:
    - "27017:27017"
  volumes:
      # if you wish to setup additional user accounts specific per DB or with different roles you can use following entry point
    - "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
  # no --auth is needed here as presence of username and password add this option automatically
  command: mongod

Now when starting the container by docker-compose up you should notice following entries:

...
I CONTROL  [initandlisten] options: { net: { bindIp: "127.0.0.1" }, processManagement: { fork: true }, security: { authorization: "enabled" }, systemLog: { destination: "file", path: "/proc/1/fd/1" } }
...
I ACCESS   [conn1] note: no users configured in admin.system.users, allowing localhost access
...
Successfully added user: {
    "user" : "root",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}

To add custom users apart of root use the entrypoint exectuable script (placed under $PWD/mongo-entrypoint dir as it is mounted in docker-compose to entrypoint):

#!/usr/bin/env bash
echo "Creating mongo users..."
mongo admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED --eval "db.createUser({user: 'ANOTHER_USER', pwd: 'PASS', roles: [{role: 'readWrite', db: 'xxx'}]}); db.createUser({user: 'admin', pwd: 'PASS', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]});"
echo "Mongo users created."

Entrypoint script will be executed and additional users will be created.

"The public type <<classname>> must be defined in its own file" error in Eclipse

I had two significant errors in my program. From the other answers, I learned in a single java program, one can not declare two classes as "public". So I changed the access specifier, but got another error as added to my question as "EDIT" that "Selection does not contain a main type". Finally I observed I forgot to add "String args[]" part in my main method. That's why the code was not working. After rectification, it worked as expected.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

I would do something like this:

;WITH x 
 AS (SELECT *, 
            Row_number() 
              OVER( 
                partition BY employeeid 
                ORDER BY datestart) rn 
     FROM   employeehistory) 
SELECT * 
FROM   x x1 
   LEFT OUTER JOIN x x2 
                ON x1.rn = x2.rn + 1 

Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.

C++ convert from 1 char to string?

All of

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.

How to Lock/Unlock screen programmatically?

The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.

Thanks all for this helpful question!

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.kns"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LockScreenActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyAdmin"
                android:permission="android.permission.BIND_DEVICE_ADMIN">
            <meta-data android:name="android.app.device_admin"
                       android:resource="@xml/policies" />
            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

policies.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <limit-password />
        <watch-login />
        <reset-password />
        <force-lock />
        <wipe-data />
    </uses-policies>
</device-admin>

How to get the background color of an HTML element?

This worked for me:

var backgroundColor = window.getComputedStyle ? window.getComputedStyle(myDiv, null).getPropertyValue("background-color") : myDiv.style.backgroundColor;

And, even better:

var getStyle = function(element, property) {
    return window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(property) : element.style[property.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); })];
};
var backgroundColor = getStyle(myDiv, "background-color");

What is the easiest way to push an element to the beginning of the array?

You can use insert:

a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]

Where the first argument is the index to insert at and the second is the value.

Top 1 with a left join

Use OUTER APPLY instead of LEFT JOIN:

SELECT u.id, mbg.marker_value 
FROM dps_user u
OUTER APPLY 
    (SELECT TOP 1 m.marker_value, um.profile_id
     FROM dps_usr_markers um (NOLOCK)
         INNER JOIN dps_markers m (NOLOCK) 
             ON m.marker_id= um.marker_id AND 
                m.marker_key = 'moneyBackGuaranteeLength'
     WHERE um.profile_id=u.id 
     ORDER BY m.creation_date
    ) AS MBG
WHERE u.id = 'u162231993';

Unlike JOIN, APPLY allows you to reference the u.id inside the inner query.

Fatal error: Class 'ZipArchive' not found in

For PHP 7.x

sudo apt-get install php-zip

For PHP 5.x

sudo apt-get install php5.x-zip
// (for example sudo apt-get install php5.6-zip)

And then restart the Apache server

sudo service apache2 restart

$('body').on('click', '.anything', function(){})

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

$(document).on('click','body *',function(){
    //  $(this) = your current element that clicked.
    // additional code
});

input() error - NameError: name '...' is not defined

Since you are writing for Python 3.x, you'll want to begin your script with:

#!/usr/bin/env python3

If you use:

#!/usr/bin/env python

It will default to Python 2.x. These go on the first line of your script, if there is nothing that starts with #! (aka the shebang).

If your scripts just start with:

#! python

Then you can change it to:

#! python3

Although this shorter formatting is only recognized by a few programs, such as the launcher, so it is not the best choice.

The first two examples are much more widely used and will help ensure your code will work on any machine that has Python installed.

Lambda function in list comprehensions

The other answers are correct, but if you are trying to make a list of functions, each with a different parameter, that can be executed later, the following code will do that:

import functools
a = [functools.partial(lambda x: x*x, x) for x in range(10)]

b = []
for i in a:
    b.append(i())

In [26]: b
Out[26]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

While the example is contrived, I found it useful when I wanted a list of functions that each print something different, i.e.

import functools
a = [functools.partial(lambda x: print(x), x) for x in range(10)]

for i in a:
    i()

Change IPython/Jupyter notebook working directory

In iPython Notebook on Windows, this worked for me:

cd d:\folder\

How correctly produce JSON by RESTful web service?

You could use a package like org.json http://www.json.org/java/

Because you will need to use JSONObjects more often.

There you can easily create JSONObjects and put some values in it:

 JSONObject json = new JSONObject();
 JSONArray array=new JSONArray();
    array.put("1");
    array.put("2");
    json.put("friends", array);

    System.out.println(json.toString(2));


    {"friends": [
      "1",
      "2"
    ]}

edit This has the advantage that you can build your responses in different layers and return them as an object

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

Count the frequency that a value occurs in a dataframe column

You can also do this with pandas by broadcasting your columns as categories first, e.g. dtype="category" e.g.

cats = ['client', 'hotel', 'currency', 'ota', 'user_country']

df[cats] = df[cats].astype('category')

and then calling describe:

df[cats].describe()

This will give you a nice table of value counts and a bit more :):

    client  hotel   currency    ota user_country
count   852845  852845  852845  852845  852845
unique  2554    17477   132 14  219
top 2198    13202   USD Hades   US
freq    102562  8847    516500  242734  340992

Convert base-2 binary number string to int

For large matrix (10**5 rows and up) it is better to use a vectorized matmult. Pass in all rows and cols in one shot. It is extremely fast. There is no looping in python here. I originally designed it for converting many binary columns like 0/1 for like 10 different genre columns in MovieLens into a single integer for each example row.

def BitsToIntAFast(bits):
  m,n = bits.shape
  a = 2**np.arange(n)[::-1]  # -1 reverses array of powers of 2 of same length as bits
  return bits @ a

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

To state the obvious, the cup represents outerScopeVar.

Asynchronous functions be like...

asynchronous call for coffee

How to make graphics with transparent background in R using ggplot2?

Just to improve YCR's answer:

1) I added black lines on x and y axis. Otherwise they are made transparent too.

2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.

Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.

MyTheme_transparent <- theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
    legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
    axis.line = element_line(colour = "black") # adding a black line for x and y axis
)

HTML/CSS: how to put text both right and left aligned in a paragraph

Ok what you probably want will be provide to you by result of:

  1. in CSS:

    div { column-count: 2; }

  2. in html:

    <div> some text, bla bla bla </div>

In CSS you make div to split your paragraph on to column, you can make them 3, 4...

If you want to have many differend paragraf like that, then put id or class in your div:

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?

var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone', 
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike 
v7.6 release 92', 'Pike v7.8 release 517'];

// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
    // Execute code
}
// If NOT on Apple device
else {
    // Execute code
}

Display exact matches only with grep

Recently I came across an issue in grep. I was trying to match the pattern x.y.z and grep returned x.y-z.Using some regular expression we may can overcome this, but with grep whole word matching did not help. Since the script I was writing is a generic one, I cannot restrict search for a specific way as in like x.y.z or x.y-z ..

Quick way I figured is to run a grep and then a condition check var="x.y.z" var1=grep -o x.y.z file.txt if [ $var1 == $var ] echo "Pattern match exact" else echo "Pattern does not match exact" fi

https://linuxacatalyst.blogspot.com/2019/12/grep-pattern-matching-issues.html

Javascript use variable as object name

Use square bracket around variable name.

var objname = 'myobject';
{[objname]}.value = 'value';

Java better way to delete file if exists

I was working on this type of function, maybe this will interests some of you ...

public boolean deleteFile(File file) throws IOException {
    if (file != null) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();

            for (File f: files) {
                deleteFile(f);
            }
        }
        return Files.deleteIfExists(file.toPath());
    }
    return false;
}

Selecting the first "n" items with jQuery

I found this note in the end of the lt() docs:

Additional Notes:
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead.

So use $("selector").slice(from, to) for better performances.

Using C++ filestreams (fstream), how can you determine the size of a file?

Don't use tellg to determine the exact size of the file. The length determined by tellg will be larger than the number of characters can be read from the file.

From stackoverflow question tellg() function give wrong size of file? tellg does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It's not even guaranteed that you can convert the type to an integral type.). For Windows (and most non-Unix systems), in text mode, there is no direct and immediate mapping between what tellg returns and the number of bytes you must read to get to that position.

If it is important to know exactly how many bytes you can read, the only way of reliably doing so is by reading. You should be able to do this with something like:

#include <fstream>
#include <limits>

ifstream file;
file.open(name,std::ios::in|std::ios::binary);
file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear();   //  Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );

Get IP address of an interface on Linux

In addition to the ioctl() method Filip demonstrated you can use getifaddrs(). There is an example program at the bottom of the man page.

How do I write a correct micro-benchmark in Java?

If you are trying to compare two algorithms, do at least two benchmarks for each, alternating the order. i.e.:

for(i=1..n)
  alg1();
for(i=1..n)
  alg2();
for(i=1..n)
  alg2();
for(i=1..n)
  alg1();

I have found some noticeable differences (5-10% sometimes) in the runtime of the same algorithm in different passes..

Also, make sure that n is very large, so that the runtime of each loop is at the very least 10 seconds or so. The more iterations, the more significant figures in your benchmark time and the more reliable that data is.

How do I run a docker instance from a DockerFile?

While other answers were usable, this really helped me, so I am putting it also here.

From the documentation:

Instead of specifying a context, you can pass a single Dockerfile in the URL or pipe the file in via STDIN. To pipe a Dockerfile from STDIN:

$ docker build - < Dockerfile

With Powershell on Windows, you can run:

Get-Content Dockerfile | docker build -

When the build is done, run command:

docker image ls

You will see something like this:

REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
<none>                     <none>              123456789        39 seconds ago      422MB

Copy your actual IMAGE ID and then run

docker run 123456789

Where the number at the end is the actual Image ID from previous step

If you do not want to remember the image id, you can tag your image by

docker tag 123456789 pavel/pavel-build

Which will tag your image as pavel/pavel-build

Using String Format to show decimal up to 2 places or simple integer

Simple one line code :

public static string DoFormat(double myNumber)
{
    return string.Format("{0:0.00}", myNumber).Replace(".00","");
}

Altering a column: null to not null

Let's take an example:

TABLE NAME=EMPLOYEE

And I want to change the column EMPLOYEE_NAME to NOT NULL. This query can be used for the task:

ALTER TABLE EMPLOYEE MODIFY EMPLOYEE.EMPLOYEE_NAME datatype NOT NULL;

How can I get a file's size in C++?

You need to seek to the end of the file and then ask for the position:

fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

You can then seek back, e.g.:

fseek(fp, 0L, SEEK_SET);

or (if seeking to go to the beginning)

rewind(fp);

Error: Cannot find module html

Install ejs if it is not.

npm install ejs

Then after just paste below two lines in your main file. (like app.js, main.js)

app.set('view engine', 'html');

app.engine('html', require('ejs').renderFile);

How to use ScrollView in Android?

Just make the top-level layout a ScrollView:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stretchColumns="1">

        <!-- everything you already have -->

    </TableLayout>
</ScrollView>

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

JSFiddle


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

_x000D_
_x000D_
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
  <sn:streetNumber>649</sn:streetNumber>_x000D_
  <p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
    xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
_x000D_
_x000D_

Table row and column number in jQuery

Off the top of my head, one way would be to grab all previous elements and count them.

$('td').click(function(){ 
    var colIndex = $(this).prevAll().length;
    var rowIndex = $(this).parent('tr').prevAll().length;
});

"Thinking in AngularJS" if I have a jQuery background?

jQuery

jQuery makes ridiculously long JavaScript commands like getElementByHerpDerp shorter and cross-browser.

AngularJS

AngularJS allows you to make your own HTML tags/attributes that do things which work well with dynamic web applications (since HTML was designed for static pages).

Edit:

Saying "I have a jQuery background how do I think in AngularJS?" is like saying "I have an HTML background how do I think in JavaScript?" The fact that you're asking the question shows you most likely don't understand the fundamental purposes of these two resources. This is why I chose to answer the question by simply pointing out the fundamental difference rather than going through the list saying "AngularJS makes use of directives whereas jQuery uses CSS selectors to make a jQuery object which does this and that etc....". This question does not require a lengthy answer.

jQuery is a way to make programming JavaScript in the browser easier. Shorter, cross-browser commands, etc.

AngularJS extends HTML, so you don't have to put <div> all over the place just to make an application. It makes HTML actually work for applications rather than what it was designed for, which is static, educational web pages. It accomplishes this in a roundabout way using JavaScript, but fundamentally it is an extension of HTML, not JavaScript.

What is the different between RESTful and RESTless

REST stands for REpresentational State Transfer and goes a little something like this:

We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.

the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.

For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/

RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful

Checking if a file is a directory or just a file

You can call the stat() function and use the S_ISREG() macro on the st_mode field of the stat structure in order to determine if your path points to a regular file:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int is_regular_file(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISREG(path_stat.st_mode);
}

Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.

npm install errors with Error: ENOENT, chmod

In Windows I had a similar error. Search paste App Data and search for the string npm.

I replaced the string 'npm' (including quotes) with 'npm.cmd' in both atlasboard\lib\package-dependency-manager.js and atlasboard\lib\cli\commands.js. That fixed the problem.

C# Telnet Library

I am currently evaluating two .NET (v2.0) C# Telnet libraries that may be of interest:

Hope this helps.

Regards, Andy.

Check if url contains string with JQuery

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf("?added-to-cart=555") > -1) {
    alert("found it");
}

android - setting LayoutParams programmatically

after creating the view we have to add layout parameters .

change like this

TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT));

llview.addView(tv);
tv.setTextColor(Color.WHITE);
tv.setTextSize(2,25);
tv.setText(chat);
if (mine) {
    leftMargin = 5;
    tv.setBackgroundColor(0x7C5B77);
}
else {
    leftMargin = 50;
    tv.setBackgroundColor(0x778F6E);
}
final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)tv.getLayoutParams();
lpt.setMargins(leftMargin,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin);

Java - Getting Data from MySQL database

  • First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].

  • Add the Jar file to your workspace [build path].

  • Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.

  • Define the database name, userName, and Password for your connection.

  • Use the resultSet to get the data based one the column name from your database table.

Sample code is here:

public class JdbcMySQLExample{

public static void main(String[] args) {

    String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
    String user = "root";
    String password = "root";
    
    String query = "SELECT * from YOUR_TABLE_NAME";

    try (Connection con = DriverManager.getConnection(url, user, password);
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(query)) {

        if (rs.next()) {
            
            System.out.println(rs.getString(1));
        }

    } catch (SQLException ex) {
          System.out.println(ex);
       
    } 
}

Pressing Ctrl + A in Selenium WebDriver

Java

The Robot class will work much more efficiently than sending the keys through Selenium sendkeys. Please try:

Example:

Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_A);

To use the above Robot class, you need to import java.awt.Robot;'.

Accessing localhost:port from Android emulator

I had the same issue when I was trying to connect to my IIS .NET Webservice from the Android emulator.

  1. install npm install -g iisexpress-proxy
  2. iisexpress-proxy 53990 to 9000 to proxy IIS express port to 9000 and access port 9000 from emulator like "http://10.0.2.2:9000"

the reason seems to be by default, IIS Express doesn't allow connections from network https://forums.asp.net/t/2125232.aspx?Bad+Request+Invalid+Hostname+when+accessing+localhost+Web+API+or+Web+App+from+across+LAN

Clean up a fork and restart it from the upstream

The simplest solution would be (using 'upstream' as the remote name referencing the original repo forked):

git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master  
git push origin master --force 

(Similar to this GitHub page, section "What should I do if I’m in a bad situation?")

Be aware that you can lose changes done on the master branch (both locally, because of the reset --hard, and on the remote side, because of the push --force).

An alternative would be, if you want to preserve your commits on master, to replay those commits on top of the current upstream/master.
Replace the reset part by a git rebase upstream/master. You will then still need to force push.
See also "What should I do if I’m in a bad situation?"


A more complete solution, backing up your current work (just in case) is detailed in "Cleanup git master branch and move some commit to new branch".

See also "Pull new updates from original GitHub repository into forked GitHub repository" for illustrating what "upstream" is.

upstream


Note: recent GitHub repos do protect the master branch against push --force.
So you will have to un-protect master first (see picture below), and then re-protect it after force-pushing).

enter image description here


Note: on GitHub specifically, there is now (February 2019) a shortcut to delete forked repos for pull requests that have been merged upstream.

Multiple SQL joins

It will be something like this:

SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
FROM
    Books b
    JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
    JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
    JOIN Publishers p ON p._PublisherID = b.PublisherID
    JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
    JOIN Writer w ON w._WritersID = wb._Writers_WriterID

You use the join statement to indicate which fields from table A map to table B. I'm using aliases here thats why you see Books b the Books table will be referred to as b in the rest of the query. This makes for less typing.

FYI your naming convention is very strange, I would expect it to be more like this:

Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID

How do I specify "close existing connections" in sql script

Go to management studio and do everything you describe, only instead of clicking OK, click on Script. It will show the code it will run which you can then incorporate in your scripts.

In this case, you want:

ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

How to fix "set SameSite cookie to none" warning?

>= PHP 7.3

setcookie('key', 'value', ['samesite' => 'None', 'secure' => true]);

< PHP 7.3

exploit the path
setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");

Emitting javascript

echo "<script>document.cookie('key=value; SameSite=None; Secure');</script>";

Best way to store data locally in .NET (C#)

My first inclination is an access database. The .mdb files are stored locally, and can be encrypted if that is deemed necessary. Though XML or JSON would also work for many scenarios. Flat files I would only use for read only, non-search (forward read only) information. I tend to prefer csv format to set width.

Angularjs loading screen on ajax request

You could add a condition and then change it via the rootscope. Before your ajax request, you simply call $rootScope.$emit('stopLoader');

angular.module('directive.loading', [])
        .directive('loading',   ['$http', '$rootScope',function ($http, $rootScope)
        {
            return {
                restrict: 'A',
                link: function (scope, elm, attrs)
                {
                    scope.isNoLoadingForced = false;
                    scope.isLoading = function () {
                        return $http.pendingRequests.length > 0 && scope.isNoLoadingForced;
                    };

                    $rootScope.$on('stopLoader', function(){
                        scope.isNoLoadingForced = true;
                    })

                    scope.$watch(scope.isLoading, function (v)
                    {
                        if(v){
                            elm.show();
                        }else{
                            elm.hide();
                        }
                    });
                }
            };

        }]);

This is definatly not the best solution but it would still works.

Is it possible to use Visual Studio on macOS?

I guess you can install it via Parallel or in any other Virtual machine with windows in it

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

As from PostgreSQL 9.0 you can use the aggregate function called string_agg. Your new SQL should look something like this:

SELECT company_id, string_agg(employee, ', ')
FROM mytable
GROUP BY company_id;

bash: pip: command not found

The updated command for installing pip3 is :

sudo apt-get install python3-pip

Substitute a comma with a line break in a cell

For some reason, none of the above worked for me. This DID however:

  1. Selected the range of cells I needed to replace.
  2. Go to Home > Find & Select > Replace or Ctrl + H
  3. Find what: ,
  4. Replace with: CTRL + SHIFT + J
  5. Click Replace All

Somehow CTRL + SHIFT + J is registered as a linebreak.

Get selected option text with JavaScript

There are two solutions, as far as I know.

both that just need using vanilla javascript

1 selectedOptions

live demo

_x000D_
_x000D_
const log = console.log;_x000D_
const areaSelect = document.querySelector(`[id="area"]`);_x000D_
_x000D_
areaSelect.addEventListener(`change`, (e) => {_x000D_
  // log(`e.target`, e.target);_x000D_
  const select = e.target;_x000D_
  const value = select.value;_x000D_
  const desc = select.selectedOptions[0].text;_x000D_
  log(`option desc`, desc);_x000D_
});
_x000D_
<div class="select-box clearfix">_x000D_
  <label for="area">Area</label>_x000D_
  <select id="area">_x000D_
    <option value="101">A1</option>_x000D_
    <option value="102">B2</option>_x000D_
    <option value="103">C3</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

2 options

live demo

_x000D_
_x000D_
const log = console.log;_x000D_
const areaSelect = document.querySelector(`[id="area"]`);_x000D_
_x000D_
areaSelect.addEventListener(`change`, (e) => {_x000D_
  // log(`e.target`, e.target);_x000D_
  const select = e.target;_x000D_
  const value = select.value;_x000D_
  const desc = select.options[select.selectedIndex].text;_x000D_
  log(`option desc`, desc);_x000D_
});
_x000D_
<div class="select-box clearfix">_x000D_
  <label for="area">Area</label>_x000D_
  <select id="area">_x000D_
    <option value="101">A1</option>_x000D_
    <option value="102">B2</option>_x000D_
    <option value="103">C3</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_


HTML input textbox with a width of 100% overflows table cells

I usually set the width of my inputs to 99% to fix this:

input {
    width: 99%;
}

You can also remove the default styles, but that will make it less obvious that it is a text box. However, I will show the code for that anyway:

input {
    width: 100%;
    border-width: 0;
    margin: 0;
    padding: 0;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}

Ad@m

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Get screenshot as Canvas or Jpeg Blob / ArrayBuffer using getDisplayMedia API:

FIX 1: Use the getUserMedia with chromeMediaSource only for Electron.js
FIX 2: Throw error instead return null object
FIX 3: Fix demo to prevent the error: getDisplayMedia must be called from a user gesture handler

// docs: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia
// see: https://www.webrtc-experiment.com/Pluginfree-Screen-Sharing/#20893521368186473
// see: https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Pluginfree-Screen-Sharing/conference.js

function getDisplayMedia(options) {
    if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
        return navigator.mediaDevices.getDisplayMedia(options)
    }
    if (navigator.getDisplayMedia) {
        return navigator.getDisplayMedia(options)
    }
    if (navigator.webkitGetDisplayMedia) {
        return navigator.webkitGetDisplayMedia(options)
    }
    if (navigator.mozGetDisplayMedia) {
        return navigator.mozGetDisplayMedia(options)
    }
    throw new Error('getDisplayMedia is not defined')
}

function getUserMedia(options) {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        return navigator.mediaDevices.getUserMedia(options)
    }
    if (navigator.getUserMedia) {
        return navigator.getUserMedia(options)
    }
    if (navigator.webkitGetUserMedia) {
        return navigator.webkitGetUserMedia(options)
    }
    if (navigator.mozGetUserMedia) {
        return navigator.mozGetUserMedia(options)
    }
    throw new Error('getUserMedia is not defined')
}

async function takeScreenshotStream() {
    // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/screen
    const width = screen.width * (window.devicePixelRatio || 1)
    const height = screen.height * (window.devicePixelRatio || 1)

    const errors = []
    let stream
    try {
        stream = await getDisplayMedia({
            audio: false,
            // see: https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints/video
            video: {
                width,
                height,
                frameRate: 1,
            },
        })
    } catch (ex) {
        errors.push(ex)
    }

    // for electron js
    if (navigator.userAgent.indexOf('Electron') >= 0) {
        try {
            stream = await getUserMedia({
                audio: false,
                video: {
                    mandatory: {
                        chromeMediaSource: 'desktop',
                        // chromeMediaSourceId: source.id,
                        minWidth         : width,
                        maxWidth         : width,
                        minHeight        : height,
                        maxHeight        : height,
                    },
                },
            })
        } catch (ex) {
            errors.push(ex)
        }
    }

    if (errors.length) {
        console.debug(...errors)
        if (!stream) {
            throw errors[errors.length - 1]
        }
    }

    return stream
}

async function takeScreenshotCanvas() {
    const stream = await takeScreenshotStream()

    // from: https://stackoverflow.com/a/57665309/5221762
    const video = document.createElement('video')
    const result = await new Promise((resolve, reject) => {
        video.onloadedmetadata = () => {
            video.play()
            video.pause()

            // from: https://github.com/kasprownik/electron-screencapture/blob/master/index.js
            const canvas = document.createElement('canvas')
            canvas.width = video.videoWidth
            canvas.height = video.videoHeight
            const context = canvas.getContext('2d')
            // see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement
            context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
            resolve(canvas)
        }
        video.srcObject = stream
    })

    stream.getTracks().forEach(function (track) {
        track.stop()
    })
    
    if (result == null) {
        throw new Error('Cannot take canvas screenshot')
    }

    return result
}

// from: https://stackoverflow.com/a/46182044/5221762
function getJpegBlob(canvas) {
    return new Promise((resolve, reject) => {
        // docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
        canvas.toBlob(blob => resolve(blob), 'image/jpeg', 0.95)
    })
}

async function getJpegBytes(canvas) {
    const blob = await getJpegBlob(canvas)
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader()

        fileReader.addEventListener('loadend', function () {
            if (this.error) {
                reject(this.error)
                return
            }
            resolve(this.result)
        })

        fileReader.readAsArrayBuffer(blob)
    })
}

async function takeScreenshotJpegBlob() {
    const canvas = await takeScreenshotCanvas()
    return getJpegBlob(canvas)
}

async function takeScreenshotJpegBytes() {
    const canvas = await takeScreenshotCanvas()
    return getJpegBytes(canvas)
}

function blobToCanvas(blob, maxWidth, maxHeight) {
    return new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = function () {
            const canvas = document.createElement('canvas')
            const scale = Math.min(
                1,
                maxWidth ? maxWidth / img.width : 1,
                maxHeight ? maxHeight / img.height : 1,
            )
            canvas.width = img.width * scale
            canvas.height = img.height * scale
            const ctx = canvas.getContext('2d')
            ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height)
            resolve(canvas)
        }
        img.onerror = () => {
            reject(new Error('Error load blob to Image'))
        }
        img.src = URL.createObjectURL(blob)
    })
}

DEMO:

document.body.onclick = async () => {
    // take the screenshot
    var screenshotJpegBlob = await takeScreenshotJpegBlob()

    // show preview with max size 300 x 300 px
    var previewCanvas = await blobToCanvas(screenshotJpegBlob, 300, 300)
    previewCanvas.style.position = 'fixed'
    document.body.appendChild(previewCanvas)

    // send it to the server
    var formdata = new FormData()
    formdata.append("screenshot", screenshotJpegBlob)
    await fetch('https://your-web-site.com/', {
        method: 'POST',
        body: formdata,
        'Content-Type' : "multipart/form-data",
    })
}

// and click on the page

Regular expression to extract text between square brackets

(?<=\[).+?(?=\])

Will capture content without brackets

  • (?<=\[) - positive lookbehind for [

  • .*? - non greedy match for the content

  • (?=\]) - positive lookahead for ]

EDIT: for nested brackets the below regex should work:

(\[(?:\[??[^\[]*?\]))

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

Month name as a string

As simple as this

mCalendar = Calendar.getInstance();    
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());

Calendar.LONG is to get the full name of the month and Calendar.SHORT gives the name in short. For eg: Calendar.LONG will return January Calendar.SHORT will return Jan

Is there any "font smoothing" in Google Chrome?

Ok you can use this simply

-webkit-text-stroke-width: .7px;
-webkit-text-stroke-color: #34343b;
-webkit-font-smoothing:antialiased;

Make sure your text color and upper text-stroke-width must me same and that's it.

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Here is another way you can change the selected option of a <select> element in javascript. You can use

document.getElementById('salesperson').selectedIndex=1;

Setting it to 1 will make the second element of the dropdown selected. The select element index start from 0.

Here is a sample code. Check if you can use this type of approach:

<html>
<head>
<script language="javascript">

function changeSelected() { 
document.getElementById('salesperson').selectedIndex=1;

} 

</script>
</head>
<body>
<form name="f1">

<select id="salesperson" > 
   <option value"">james</option>
   <option value"">john</option>  
</select> 
<input type="button" value="Change Selected" onClick="changeSelected();">

</form>
</body>
</html>

MySQL Daemon Failed to Start - centos 6

run this :

chown -R mysql:mysql /var/lib/mysql

and try again!

How to add certificate chain to keystore?

I solved the problem by cat'ing all the pems together:

cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD

(keytool didn't know what to do with a PKCS7 formatted key)

I got all the pems from letsencrypt

Trigger insert old values- values that was updated

Here's an example update trigger:

create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime, 
    OldName varchar(50))
go
create trigger Employees_Trigger_Update on Employees
after update
as
insert into Log (EmployeeId, LogDate, OldName) 
select id, getdate(), name
from deleted
go
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log

This will print:

id   EmployeeId   LogDate                   OldName
1    1            2010-07-05 20:11:54.127   Zaphoid

Get Substring between two characters using javascript

Try this to Get Substring between two characters using javascript.

        $("button").click(function(){
            var myStr = "MyLongString:StringIWant;";
            var subStr = myStr.match(":(.*);");
            alert(subStr[1]);
        });

Taken from @ Find substring between the two characters with jQuery

Handling Dialogs in WPF with MVVM

I had the same situation and wrapped up the MessageBox into a designer invisible control. The details are in my blog

http://geekswithblogs.net/mukapu/archive/2010/03/12/user-prompts-messagebox-with-mvvm.aspx

The same can be extended to any modal dialogs, file browse control etc.

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

What does bundle exec rake mean?

It should probably be mentioned, that there are ways to omit bundle exec (they are all stated in chapter 3.6.1 of Michael Hartls Ruby on Rails Tutorial book).

The simplest is to just use a sufficiently up-to-date version of RVM (>= 1.11.x).

If you're restricted to an earlier version of RVM, you can always use this method also mentioned by calasyr:

$ rvm get head && rvm reload
$ chmod +x $rvm_path/hooks/after_cd_bundler
$ bundle install --binstubs=./bundler_stubs

The bundler_stubs directory should then also be added to the .gitignore file.

A third option is to use the rubygems-bundler gem if you're not using RVM:

$ gem install rubygems-bundler
$ gem regenerate_binstubs

Code coverage for Jest built on top of Jasmine

If you are using the NestJS framework, you can get code coverage using this command:

npm run test:cov

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

What is the path that Django uses for locating and loading templates?

In django 3.1, go to setting of your project and import os

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

MySQL Removing Some Foreign keys

first need to get actual constrain name by this query

SHOW CREATE TABLE TABLE_NAME

This query will result constrain name of the foreign key, now below query will drop it.

ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1

last number in above constrain name depends how many foreign keys you have in table

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Improving upon @Ianl's answer,

It seems that if 2-step authentication is enabled, you have to use token instead of password. You could generate a token here.

If you want to disable the prompts for both the username and password then you can set the URL as follows -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

Note that the URL has both the username and password. Also the .git/config file should show your current settings.


Update 20200128:

If you don't want to store the password in the config file, then you can generate your personal token and replace the password with the token. Here are some details.

It would look like this -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

ElasticSearch - Return Unique Values

if you want to get the first document for each language field unique value, you can do this:

{
 "query": {
    "match_all": {
    }
  },
  "collapse": {
    "field": "language.keyword",
    "inner_hits": {
    "name": "latest",
      "size": 1
    }
  }
}

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)

Duration column = End - Start

  1. Once done, plot your stacked bar chart using the entire data.
  2. Mark start and end range to no fill.
  3. Right click on the X Axis and change Axis options manually. (This did cause me some issues, till I realized I couldn't manipulate them to enter dates, :) yeah I am newbie, excel masters! :))

enter image description here

How do I make the first letter of a string uppercase in JavaScript?

yourString.replace(/\w/, c => c.toUpperCase())

I found this arrow function easiest. Replace matches the first letter character (\w) of your string and converts it to uppercase. Nothing fancier is necessary.

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

How do I convert an integer to string as part of a PostgreSQL query?

You could do this:

SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'

PHP check file extension

pathinfo is what you're looking for

PHP.net

$file_parts = pathinfo($filename);

switch($file_parts['extension'])
{
    case "jpg":
    break;

    case "exe":
    break;

    case "": // Handle file extension for files ending in '.'
    case NULL: // Handle no file extension
    break;
}

ASP.NET page life cycle explanation

Partial Class _Default
    Inherits System.Web.UI.Page
    Dim str As String

    Protected Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed

        str += "PAGE DISPOSED" & "<br />"
    End Sub

    Protected Sub Page_Error(sender As Object, e As System.EventArgs) Handles Me.Error
        str += "PAGE ERROR " & "<br />"
    End Sub

    Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
        str += "PAGE INIT " & "<br />"
    End Sub

    Protected Sub Page_InitComplete(sender As Object, e As System.EventArgs) Handles Me.InitComplete
        str += "INIT Complte " & "<br />"
    End Sub

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        str += "PAGE LOAD " & "<br />"

    End Sub

    Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
        str += "PAGE LOAD Complete " & "<br />"
    End Sub

    Protected Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
        str = ""
        str += "PAGE PRE INIT" & "<br />"
    End Sub

    Protected Sub Page_PreLoad(sender As Object, e As System.EventArgs) Handles Me.PreLoad
        str += "PAGE PRE LOAD " & "<br />"
    End Sub

    Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
        str += "PAGE PRE RENDER " & "<br />"
    End Sub

    Protected Sub Page_PreRenderComplete(sender As Object, e As System.EventArgs) Handles Me.PreRenderComplete
        str += "PAGE PRE RENDER COMPLETE " & "<br />"
    End Sub

    Protected Sub Page_SaveStateComplete(sender As Object, e As System.EventArgs) Handles Me.SaveStateComplete
        str += "PAGE SAVE STATE COMPLTE  " & "<br />"
        lbl.Text = str
    End Sub

    Protected Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
        'Response.Write("PAGE UN LOAD\n")
    End Sub
End Class

Convert XLS to CSV on command line

Create a TXT file on your desktop named "xls2csv.vbs" and paste the code:

Dim vExcel
Dim vCSV
Set vExcel = CreateObject("Excel.Application")
Set vCSV = vExcel.Workbooks.Open(Wscript.Arguments.Item(0))
vCSV.SaveAs WScript.Arguments.Item(0) & ".csv", 6
vCSV.Close False
vExcel.Quit

Drag a XLS file to it (like "test.xls"). It will create a converted CSV file named "test.xls.csv". Then, rename it to "test.csv". Done.

Angular 5 Service to read local .json file

You have an alternative solution, importing directly your json.

To compile, declare this module in your typings.d.ts file

declare module "*.json" {
    const value: any;
    export default value;
}

In your code

import { data_json } from '../../path_of_your.json';

console.log(data_json)

Can scripts be inserted with innerHTML?

You could do it like this:

var mydiv = document.getElementById("mydiv");
var content = "<script>alert(\"hi\");<\/script>";

mydiv.innerHTML = content;
var scripts = mydiv.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
    eval(scripts[i].innerText);
}

addEventListener not working in IE8

If you use jQuery you can write:

$( _checkbox ).click( function( e ){ /*process event here*/ } )

Replace non-numeric with empty string

I'm sure there's a more efficient way to do it, but I would probably do this:

string getTenDigitNumber(string input)
{    
    StringBuilder sb = new StringBuilder();
    for(int i - 0; i < input.Length; i++)
    {
        int junk;
        if(int.TryParse(input[i], ref junk))
            sb.Append(input[i]);
    }
    return sb.ToString();
}

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

I finally figured out the right answer to this question today.

<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>${cxf.version}</version>
    <executions>
        <execution>
            <id>generate-sources</id>
            <phase>generate-sources</phase>
            <configuration> 
                <sourceRoot>${project.build.directory}/generated-sources/cxf</sourceRoot>
                <wsdlOptions>
                    <wsdlOption>
                        <wsdl>${project.basedir}/src/main/resources/wsdl/FooService.wsdl</wsdl>
                        <wsdlLocation>classpath:wsdl/FooService.wsdl</wsdlLocation>
                    </wsdlOption>
                </wsdlOptions>
            </configuration>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Notice that I have prefixed the value in wsdlLocation with classpath:. This tells the plugin that the wsdl will be on the classpath instead of an absolute path. Then it will generate code similar to this:

@WebServiceClient(name = "FooService", 
                  wsdlLocation = "classpath:wsdl/FooService.wsdl",
                  targetNamespace = "http://org/example/foo") 
public class Foo_Service extends Service {

    public final static URL WSDL_LOCATION;

    public final static QName SERVICE = new QName("http://org/example/foo", "Foo");
    public final static QName FooSOAPOverHTTP = new QName("http://org/example/foo", "Foo_SOAPOverHTTP");
    static {
        URL url = Foo_Service.class.getClassLoader().getResource("wsdl/FooService.wsdl");
        if (url == null) {
            java.util.logging.Logger.getLogger(Foo_Service.class.getName())
                .log(java.util.logging.Level.INFO, 
                     "Can not initialize the default wsdl from {0}", "classpath:wsdl/FooService.wsdl");
        }       
        WSDL_LOCATION = url;
    }

Note that this only works with version 2.4.1 or newer of the cxf-codegen-plugin.

How can I run a PHP script in the background after a form is submitted?

If you can access the server over ssh and can run your own scripts you can make a simple fifo server using php (although you will have to recompile php with posix support for fork).

The server can be written in anything really, you probably can easily do it in python.

Or the simplest solution would be sending an HttpRequest and not reading the return data but the server might destroy the script before it finish processing.

Example server :

<?php
define('FIFO_PATH', '/home/user/input.queue');
define('FORK_COUNT', 10);

if(file_exists(FIFO_PATH)) {
    die(FIFO_PATH . ' exists, please delete it and try again.' . "\n");
}

if(!file_exists(FIFO_PATH) && !posix_mkfifo(FIFO_PATH, 0666)){
    die('Couldn\'t create the listening fifo.' . "\n");
}

$pids = array();
$fp = fopen(FIFO_PATH, 'r+');
for($i = 0; $i < FORK_COUNT; ++$i) {
    $pids[$i] = pcntl_fork();
    if(!$pids[$i]) {
        echo "process(" . posix_getpid() . ", id=$i)\n";
        while(true) {
            $line = chop(fgets($fp));
            if($line == 'quit' || $line === false) break;
            echo "processing (" . posix_getpid() . ", id=$i) :: $line\n";
        //  $data = json_decode($line);
        //  processData($data);
        }
        exit();
    }
}
fclose($fp);
foreach($pids as $pid){
    pcntl_waitpid($pid, $status);
}
unlink(FIFO_PATH);
?>

Example client :

<?php
define('FIFO_PATH', '/home/user/input.queue');
if(!file_exists(FIFO_PATH)) {
    die(FIFO_PATH . ' doesn\'t exist, please make sure the fifo server is running.' . "\n");
}

function postToQueue($data) {
    $fp = fopen(FIFO_PATH, 'w+');
    stream_set_blocking($fp, false); //don't block
    $data = json_encode($data) . "\n";
    if(fwrite($fp, $data) != strlen($data)) {
        echo "Couldn't the server might be dead or there's a bug somewhere\n";
    }
    fclose($fp);
}
$i = 1000;
while(--$i) {
    postToQueue(array('xx'=>21, 'yy' => array(1,2,3)));
}
?>

PHP date() format when inserting into datetime in MySQL

This has been driving me mad looking for a simple answer. Finally I made this function that seems to catch all input and give a good SQL string that is correct or at least valid and checkable. If it's 1999-12-31 it's probably wrong but won't throw a bad error in MySQL.

function MakeSQLDate($date) {
    if (is_null($date)) {
        //use 1999-12-31 as a valid date or as an alert
        return date('Y-m-d', strtotime('1999-12-31'));
    }

    if (($t = strtotime($date)) === false) {
        //use 1999-12-31 as a valid date or as an alert
        return date('Y-m-d', strtotime('1999-12-31'));
    } else {
        return date('Y-m-d H:i:s', strtotime($date));
    }
}

How can I find the link URL by link text with XPath?

//a[text()='programming quesions site']/@href 

which basically identifies an anchor node <a> that has the text you want, and extracts the href attribute.

Can we have multiple "WITH AS" in single sql - Oracle SQL

Aditya or others, can you join or match up t2 with t1 in your example, i.e. translated to my code,

with t1 as (select * from AA where FIRSTNAME like 'Kermit'),
     t2 as (select * from BB B join t1 on t1.FIELD1 = B.FIELD1)

I am not clear whether only WHERE is supported for joining, or what joining approach is supported within the 2nd WITH entity. Some of the examples have the WHERE A=B down in the body of the select "below" the WITH clauses.

The error I'm getting following these WITH declarations is the identifiers (field names) in B are not recognized, down in the body of the rest of the SQL. So the WITH syntax seems to run OK, but cannot access the results from t2.

Python integer incrementing with ++

Python doesn't support ++, but you can do:

number += 1

Matplotlib discrete colorbar

I have been investigating these ideas and here is my five cents worth. It avoids calling BoundaryNorm as well as specifying norm as an argument to scatter and colorbar. However I have found no way of eliminating the rather long-winded call to matplotlib.colors.LinearSegmentedColormap.from_list.

Some background is that matplotlib provides so-called qualitative colormaps, intended to use with discrete data. Set1, e.g., has 9 easily distinguishable colors, and tab20 could be used for 20 colors. With these maps it could be natural to use their first n colors to color scatter plots with n categories, as the following example does. The example also produces a colorbar with n discrete colors approprately labelled.

import matplotlib, numpy as np, matplotlib.pyplot as plt
n = 5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x % 11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)

which produces the image below. The n in the call to Set1 specifies the first n colors of that colormap, and the last n in the call to from_list specifies to construct a map with n colors (the default being 256). In order to set cm as the default colormap with plt.set_cmap, I found it to be necessary to give it a name and register it, viz:

cm = from_list('Set15', plt.cm.Set1(range(0,n)), n)
plt.cm.register_cmap(None, cm)
plt.set_cmap(cm)
...
plt.scatter(x, y, c=z)

scatterplot with disrete colors

Add horizontal scrollbar to html table

I was running into the same issue. I discovered the following solution, which has only been tested in Chrome v31:

table {
    table-layout: fixed;
}

tbody {
    display: block;
    overflow: scroll;
}

Increase number of axis ticks

Additionally,

ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))

Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).

How to obtain the location of cacerts of the default java installation?

If you need to access those certs programmatically it is best to not use the file at all, but access it via the trust manager. The following code is from a OpenJDK Test case (which makes sure the built cacerts collection is not empty):

TrustManagerFactory trustManagerFactory =
    TrustManagerFactory.getInstance("PKIX");
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers =
    trustManagerFactory.getTrustManagers();
X509TrustManager trustManager =
    (X509TrustManager) trustManagers[0];
X509Certificate[] acceptedIssuers =
    trustManager.getAcceptedIssuers();

So you don’t have to deal with file location or keystore password.

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

I'm not quite sure what you're asking, but maybe this can help:

window.onload = function(){
    // Code. . .

}

Or:

window.onload = main;

function main(){
    // Code. . .

}

How can I copy a Python string?

You don't need to copy a Python string. They are immutable, and the copy module always returns the original in such cases, as do str(), the whole string slice, and concatenating with an empty string.

Moreover, your 'hello' string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.

One way you could work around this is to actually create a new string, then slice that string back to the original content:

>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)

But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.

If all you wanted to know is how much memory a Python object requires, use sys.getsizeof(); it gives you the memory footprint of any Python object.

For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:

>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360

You can then choose to use id() tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.

Why can't I use Docker CMD multiple times to run multiple services?

Even though CMD is written down in the Dockerfile, it really is runtime information. Just like EXPOSE, but contrary to e.g. RUN and ADD. By this, I mean that you can override it later, in an extending Dockerfile, or simple in your run command, which is what you are experiencing. At all times, there can be only one CMD.

If you want to run multiple services, I indeed would use supervisor. You can make a supervisor configuration file for each service, ADD these in a directory, and run the supervisor with supervisord -c /etc/supervisor to point to a supervisor configuration file which loads all your services and looks like

[supervisord]
nodaemon=true

[include]
files = /etc/supervisor/conf.d/*.conf

If you would like more details, I wrote a blog on this subject here: http://blog.trifork.com/2014/03/11/using-supervisor-with-docker-to-manage-processes-supporting-image-inheritance/

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

Split page vertically using CSS

you can use..

<div style="width: 100%;">
   <div style="float:left; width: 80%">
   </div>
   <div style="float:right;">
   </div>
</div>
<div style="clear:both"></div>

now element below this will not be affected.

What is perm space?

It stands for permanent generation:

The permanent generation is special because it holds meta-data describing user classes (classes that are not part of the Java language). Examples of such meta-data are objects describing classes and methods and they are stored in the Permanent Generation. Applications with large code-base can quickly fill up this segment of the heap which will cause java.lang.OutOfMemoryError: PermGen no matter how high your -Xmx and how much memory you have on the machine.

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Why aren't variable-length arrays part of the C++ standard?

If you know the value at compile time you can do the following:

template <int X>
void foo(void)
{
   int values[X];

}

Edit: You can create an a vector that uses a stack allocator (alloca), since the allocator is a template parameter.

Detect and exclude outliers in Pandas data frame

Get the 98th and 2nd percentile as the limits of our outliers

upper_limit = np.percentile(X_train.logerror.values, 98) 
lower_limit = np.percentile(X_train.logerror.values, 2) # Filter the outliers from the dataframe
data[‘target’].loc[X_train[‘target’]>upper_limit] = upper_limit data[‘target’].loc[X_train[‘target’]<lower_limit] = lower_limit

@Cacheable key on multiple method arguments

Use this

@Cacheable(value="bookCache", key="#isbn + '_' + #checkWarehouse + '_' + #includeUsed")

Formatting Phone Numbers in PHP

this takes 7, 10 and 11 digit, removes additional characters and adds dashes by going right to left through the string. change the dash to a space or dot.

$raw_phone = preg_replace('/\D/', '', $raw_phone);
$temp = str_split($raw_phone);
$phone_number = "";
for ($x=count($temp)-1;$x>=0;$x--) {
    if ($x === count($temp) - 5 || $x === count($temp) - 8 || $x === count($temp) - 11) {
        $phone_number = "-" . $phone_number;
    }
    $phone_number = $temp[$x] . $phone_number;
}
echo $phone_number;

Git asks for username every time I push

To avoid entering username, but still be prompted to enter a password, then you can simply clone your repository including the username:

git clone [email protected]/my_repo.git

How to get child element by class name?

You could try:

notes = doc.querySelectorAll('.4');

or

notes = doc.getElementsByTagName('*');
for (var i = 0; i < notes.length; i++) { 
    if (notes[i].getAttribute('class') == '4') {
    }
}

Text size of android design TabLayout tabs

Work on api 22 & 23 Make this style :

<style name="TabLayoutStyle" parent="Base.Widget.Design.TabLayout">
    <item name="android:textSize">12sp</item>
    <item name="android:textAllCaps">true</item>
</style>

And apply it to your tablayout :

<android.support.design.widget.TabLayout
    android:id="@+id/contentTabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:background="@drawable/list_gray_border"
    app:tabTextAppearance="@style/TabLayoutStyle"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    app:tabTextColor="@color/colorGrey"
    app:tabMode="fixed"
    app:tabGravity="fill"/>

MySQL check if a table exists without throwing an exception

I don't know the PDO syntax for it, but this seems pretty straight-forward:

$result = mysql_query("SHOW TABLES LIKE 'myTable'");
$tableExists = mysql_num_rows($result) > 0;

How to set specific Java version to Maven

I've used the base idea from @Jonathan. I've set the windows with: set JAVA_HOME=C:\Program Files\java\AdoptOpenJDK-11.0.8+10 call mvn clean package -DskipTests

VB.NET - How to move to next item a For Each Loop?

I'd use the Continue statement instead:

For Each I As Item In Items

    If I = x Then
        Continue For
    End If

    ' Do something

Next

Note that this is slightly different to moving the iterator itself on - anything before the If will be executed again. Usually this is what you want, but if not you'll have to use GetEnumerator() and then MoveNext()/Current explicitly rather than using a For Each loop.

Clicking URLs opens default browser

Official documentation says, click on a link in a WebView will launch application that handles URLs. You need to override this default behavior

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    });

or if there is no conditional logic in the method simply do this

myWebView.setWebViewClient(new WebViewClient());

How to install beautiful soup 4 with python 2.7 on windows

easy_install BeautifulSoup4

or

easy_install BeautifulSoup 

to install easy_install

http://pypi.python.org/pypi/setuptools#files

Android - running a method periodically using postDelayed() call

I think you could experiment with different activity flags, as it sounds like multiple instances.

"singleTop" "singleTask" "singleInstance"

Are the ones I would try, they can be defined inside the manifest.

http://developer.android.com/guide/topics/manifest/activity-element.html

What does "&" at the end of a linux command mean?

The & makes the command run in the background.

From man bash:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

django change default runserver port

If you wish to change the default configurations then follow this steps:

  1. Open terminal type command

     $ /usr/local/lib/python<2/3>.x/dist-packages/django/core/management/commands
    
  2. Now open runserver.py file in nano editor as superuser

     $ sudo nano runserver.py
    
  3. find the 'default_port' variable then you will see the default port no is '8000'. Now you can change it to whatever you want.

  4. Now exit and save the file using "CTRL + X and Y to save the file"

Note: Replace <2/3>.x with your usable version of python

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

I had the same problem and I solved it installing both crystal Report Runtime 32 and 64 bit both version

display data from SQL database into php/ html table

Look in the manual http://www.php.net/manual/en/mysqli.query.php

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

Winforms TableLayoutPanel adding rows programmatically

I just had a related problem (which is how I found this thread), where my dynamically added row and column styles were not taking effect. I usually consider SuspendLayout()/ResumeLayout() as optimizations, but in this case, wrapping my code in them made the rows and columns behave correctly.

How to manually include external aar package using new Gradle Android Build System

UPDATE ANDROID STUDIO 3.4

  1. Go to File -> Project Structure

enter image description here

  1. Modules and click on +

enter image description here

  1. Select Import .aar Package

enter image description here

  1. Find the .aar route

enter image description here

  1. Finish and Apply, then verify if package is added

enter image description here

  1. Now in the app module, click on + and Module Dependency

enter image description here

  1. Check the library package and Ok

enter image description here

  1. Verify the added dependency

enter image description here

  1. And the project structure like this

enter image description here

What is the difference between encode/decode?

The decode method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.

unicode().decode() will perform an implicit encoding of s using the default (ascii) codec. Verify this like so:

>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

>>> s.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

The error messages are exactly the same.

For str().encode() it's the other way around -- it attempts an implicit decoding of s with the default encoding:

>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)

Used like this, str().encode() is also superfluous.

But there is another application of the latter method that is useful: there are encodings that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:

>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'

You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate byte and string types in Python 3, this is no longer an issue.

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

How to specify font attributes for all elements on an html web page?

If you want to set styles of all elements in body you should use next code^

  body{
    color: green;
    }