Programs & Examples On #Powerbuilder pfc

How to create an Explorer-like folder browser control?

It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.

What is &amp used for

& is HTML for "Start of a character reference".

& is the character reference for "An ampersand".

&current; is not a standard character reference and so is an error (browsers may try to perform error recovery but you should not depend on this).

If you used a character reference for a real character (e.g. ™) then it (™) would appear in the URL instead of the string you wanted.

(Note that depending on the version of HTML you use, you may have to end a character reference with a ;, which is why &trade= will be treated as ™. HTML 4 allows it to be ommited if the next character is a non-word character (such as =) but some browsers (Hello Internet Explorer) have issues with this).

Android AudioRecord example

Here I am posting you the some code example which record good quality of sound using AudioRecord API.

Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.

public class Audio_Record extends Activity {
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private AudioRecord recorder = null;
    private Thread recordingThread = null;
    private boolean isRecording = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setButtonHandlers();
        enableButtons(false);

        int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING); 
    }

    private void setButtonHandlers() {
        ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
        ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
    }

    private void enableButton(int id, boolean isEnable) {
        ((Button) findViewById(id)).setEnabled(isEnable);
    }

    private void enableButtons(boolean isRecording) {
        enableButton(R.id.btnStart, !isRecording);
        enableButton(R.id.btnStop, isRecording);
    }

    int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
    int BytesPerElement = 2; // 2 bytes in 16bit format

    private void startRecording() {

        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

        recorder.startRecording();
        isRecording = true;
        recordingThread = new Thread(new Runnable() {
            public void run() {
                writeAudioDataToFile();
            }
        }, "AudioRecorder Thread");
        recordingThread.start();
    }

        //convert short to byte
    private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

    private void writeAudioDataToFile() {
        // Write the output audio in byte

        String filePath = "/sdcard/voice8K16bitmono.pcm";
        short sData[] = new short[BufferElements2Rec];

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        while (isRecording) {
            // gets the voice output from microphone to byte format

            recorder.read(sData, 0, BufferElements2Rec);
            System.out.println("Short writing to file" + sData.toString());
            try {
                // // writes the data to file from buffer
                // // stores the voice buffer
                byte bData[] = short2byte(sData);
                os.write(bData, 0, BufferElements2Rec * BytesPerElement);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        // stops the recording activity
        if (null != recorder) {
            isRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;
            recordingThread = null;
        }
    }

    private View.OnClickListener btnClick = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnStart: {
                enableButtons(true);
                startRecording();
                break;
            }
            case R.id.btnStop: {
                enableButtons(false);
                stopRecording();
                break;
            }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

For more detail try this AUDIORECORD BLOG.

Happy Coding !!

How to capture a backspace on the onkeydown event

Try this:

document.addEventListener("keydown", KeyCheck);  //or however you are calling your method
function KeyCheck(event)
{
   var KeyID = event.keyCode;
   switch(KeyID)
   {
      case 8:
      alert("backspace");
      break; 
      case 46:
      alert("delete");
      break;
      default:
      break;
   }
}

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

How to go back (ctrl+z) in vi/vim

On a mac you can also use command Z and that will go undo. I'm not sure why, but sometimes it stops, and if your like me and vimtutor is on the bottom of that long list of things you need to learn, than u can just close the window and reopen it and should work fine.

Ajax Success and Error function failure

This may be an old post but I realized there is nothing to be returned from the php and your success function does not have input like as follows, success:function(e){}. I hope that helps you.

How to import existing *.sql files in PostgreSQL 8.4?

in command line first reach the directory where psql is present then write commands like this:

psql [database name] [username]

and then press enter psql asks for password give the user password:

then write

> \i [full path and file name with extension]

then press enter insertion done.

How to use JavaScript source maps (.map files)?

Just wanted to focus on the last part of the question; How source map files are created? by listing the build tools I know that can create source maps.

  1. Grunt: using plugin grunt-contrib-uglify
  2. Gulp: using plugin gulp-uglify
  3. Google closure: using parameter --create_source_map

Assigning more than one class for one event

Approach #1

function doSomething(){
    if ($(this).hasClass('clickedTag')){
        // code here
    }
    else {
         // and here
    }
}

$('.tag1').click(doSomething);
$('.tag2').click(doSomething);

// or, simplifying further
$(".tag1, .tag2").click(doSomething);

Approach #2

This will also work:

?$(".tag1, .tag2").click(function(){
   alert("clicked");    
});?

Fiddle

I prefer a separate function (approach #1) if there is a chance that logic will be reused.

See also How can I select an element with multiple classes? for handling multiple classes on the same item.

How can I represent an 'Enum' in Python?

This solution is a simple way of getting a class for the enumeration defined as a list (no more annoying integer assignments):

enumeration.py:

import new

def create(class_name, names):
    return new.classobj(
        class_name, (object,), dict((y, x) for x, y in enumerate(names))
    )

example.py:

import enumeration

Colors = enumeration.create('Colors', (
    'red',
    'orange',
    'yellow',
    'green',
    'blue',
    'violet',
))

Find the least number of coins required that can make any change from 1 to 99 cents

What you are looking for is Dynamic Programming.

You don't actually have to enumerate all the possible combinations for every possible values, because you can build it on top of previous answers.

You algorithm need to take 2 parameters:

  • The list of possible coin values, here [1, 5, 10, 25]
  • The range to cover, here [1, 99]

And the goal is to compute the minimal set of coins required for this range.

The simplest way is to proceed in a bottom-up fashion:

Range     Number of coins (in the minimal set)
          1   5   10   25
[1,1]     1
[1,2]     2
[1,3]     3
[1,4]     4
[1,5]     5
[1,5]*    4   1             * two solutions here
[1,6]     4   1
[1,9]     4   1
[1,10]    5   1             * experience tells us it's not the most viable one :p
[1,10]    4   2             * not so viable either
[1,10]    4   1   1
[1,11]    4   1   1
[1,19]    4   1   1
[1,20]    5   1   1         * not viable (in the long run)
[1,20]    4   2   1         * not viable (in the long run)
[1,20]    4   1   2

It is somewhat easy, at each step we can proceed by adding at most one coin, we just need to know where. This boils down to the fact that the range [x,y] is included in [x,y+1] thus the minimal set for [x,y+1] should include the minimal set for [x,y].

As you may have noticed though, sometimes there are indecisions, ie multiple sets have the same number of coins. In this case, it can only be decided later on which one should be discarded.

It should be possible to improve its running time, when noticing that adding a coin usually allows you to cover a far greater range that the one you added it for, I think.

For example, note that:

 [1,5]    4*1  1*5
 [1,9]    4*1  1*5

we add a nickel to cover [1,5] but this gives us up to [1,9] for free!

However, when dealing with outrageous input sets [2,3,5,10,25] to cover [2,99], I am unsure as how to check quickly the range covered by the new set, or it would be actually more efficient.

Detect click inside/outside of element with single event handler

For bootstrap 4 this works for me.

$(document).on('click', function(e) {
    $('[data-toggle="popover"],[data-original-title]').each(function() {
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide')
        }
    });
});

working demo on jsfiddle link: https://jsfiddle.net/LabibMuhammadJamal/jys10nez/9/

Configuring user and password with Git Bash

Try ssh-agent for installing the SSH key for use with Git. It should auto login after use of a passphrase.

How to avoid Number Format Exception in java?

I don't know about the runtime disadvantages about the following but you could run a regexp match on your string to make sure it is a number before trying to parse it, thus

cost.matches("-?\\d+\\.?\\d+")

for a float

and

cost.matches("-?\\d+")

for an integer

EDIT

please notices @Voo's comment about max int

Fast way to concatenate strings in nodeJS/JavaScript

You asked about performance. See this perf test comparing 'concat', '+' and 'join' - in short the + operator wins by far.

Upload files with FTP using PowerShell

I am not sure you can 100% bullet proof the script from not hanging or crashing, as there are things outside your control (what if the server loses power mid-upload?) - but this should provide a solid foundation for getting you started:

# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes("C:\me.png")
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()

How can I install an older version of a package via NuGet?

Try the following:

Uninstall-Package Newtonsoft.Json -Force

Followed by:

Install-Package Newtonsoft.Json -Version <press tab key for autocomplete>

foreach for JSON array , syntax

Try this:

$.each(result,function(index, value){
    console.log('My array has at position ' + index + ', this value: ' + value);
});

ImportError: No module named PIL

you have to install Image and pillow with your python package.

type

python -m pip install image 

or run command prompt (in windows), then navigate to the scripts folder

cd C:\Python27\Scripts

then run below command

pip install image

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

There is no difference until you compile to same target architecture. I suppose you are compiling for 32 bit architecture in both cases.

It's worth mentioning that OutOfMemoryException can also be raised if you get 2GB of memory allocated by a single collection in CLR (say List<T>) on both architectures 32 and 64 bit.

To be able to benefit from memory goodness on 64 bit architecture, you have to compile your code targeting 64 bit architecture. After that, naturally, your binary will run only on 64 bit, but will benefit from possibility having more space available in RAM.

jQuery `.is(":visible")` not working in Chrome

It seems jQuery's :visible selector does not work for some inline elements in Chrome. The solution is to add a display style, like "block" or "inline-block" to make it work.

Also note that jQuery has a somewhat different definition of what is visible than many developers:

Elements are considered visible if they consume space in the document.
Visible elements have a width or height that is greater than zero.

In other words, an element must have a non-zero width and height to consume space and be visible.

Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

On the other hand, even if its visibility is set to hidden or the opacity is zero, it's still :visible to jQuery as it consumes space, which can be confusing when the CSS explicitly says its visibility is hidden.

Elements that are not in a document are considered hidden; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.

All option elements are considered hidden, regardless of their selected state.

During animations that hide an element, the element is considered visible until the end of the animation. During animations to show an element, the element is considered visible at the start at the animation.

The easy way to look at it, is that if you can see the element on the screen, even if you can't see its content, it's transparent etc., it's visible, i.e. it takes up space.

I cleaned up your markup a little and added a display style (i.e. setting the elements display to "block" etc), and this works for me:

FIDDLE

Official API reference for :visible


As of jQuery 3, the definition of :visible has changed slightly

jQuery 3 slightly modifies the meaning of :visible (and therefore of :hidden).
Starting with this version, elements will be considered :visible if they have any layout boxes, including those of zero width and/or height. For example, br elements and inline elements with no content will be selected by the :visible selector.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

c++ string array initialization

With support for C++11 initializer lists it is very easy:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

using Strings = vector<string>;

void foo( Strings const& strings )
{
    for( string const& s : strings ) { cout << s << endl; }
}

auto main() -> int
{
    foo( Strings{ "hi", "there" } ); 
}

Lacking that (e.g. for Visual C++ 10.0) you can do things like this:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

typedef vector<string> Strings;

void foo( Strings const& strings )
{
    for( auto it = begin( strings );  it != end( strings );  ++it )
    {
        cout << *it << endl;
    }
}

template< class Elem >
vector<Elem>& r( vector<Elem>&& o ) { return o; }

template< class Elem, class Arg >
vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
{
    v.push_back( a );
    return v;
}

int main()
{
    foo( r( Strings() ) << "hi" << "there" ); 
}

Serializing a list to JSON

If you're doing this in the context of a asp.Net Core API action, the conversion to Json is done implicitly.

[HttpGet]
public ActionResult Get()
{
    return Ok(TheList);
}

How to calculate the bounding box for a given lat/lng location?

I wrote a JavaScript function that returns the four coordinates of a square bounding box, given a distance and a pair of coordinates:

'use strict';

/**
 * @param {number} distance - distance (km) from the point represented by centerPoint
 * @param {array} centerPoint - two-dimensional array containing center coords [latitude, longitude]
 * @description
 *   Computes the bounding coordinates of all points on the surface of a sphere
 *   that has a great circle distance to the point represented by the centerPoint
 *   argument that is less or equal to the distance argument.
 *   Technique from: Jan Matuschek <http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates>
 * @author Alex Salisbury
*/

getBoundingBox = function (centerPoint, distance) {
  var MIN_LAT, MAX_LAT, MIN_LON, MAX_LON, R, radDist, degLat, degLon, radLat, radLon, minLat, maxLat, minLon, maxLon, deltaLon;
  if (distance < 0) {
    return 'Illegal arguments';
  }
  // helper functions (degrees<–>radians)
  Number.prototype.degToRad = function () {
    return this * (Math.PI / 180);
  };
  Number.prototype.radToDeg = function () {
    return (180 * this) / Math.PI;
  };
  // coordinate limits
  MIN_LAT = (-90).degToRad();
  MAX_LAT = (90).degToRad();
  MIN_LON = (-180).degToRad();
  MAX_LON = (180).degToRad();
  // Earth's radius (km)
  R = 6378.1;
  // angular distance in radians on a great circle
  radDist = distance / R;
  // center point coordinates (deg)
  degLat = centerPoint[0];
  degLon = centerPoint[1];
  // center point coordinates (rad)
  radLat = degLat.degToRad();
  radLon = degLon.degToRad();
  // minimum and maximum latitudes for given distance
  minLat = radLat - radDist;
  maxLat = radLat + radDist;
  // minimum and maximum longitudes for given distance
  minLon = void 0;
  maxLon = void 0;
  // define deltaLon to help determine min and max longitudes
  deltaLon = Math.asin(Math.sin(radDist) / Math.cos(radLat));
  if (minLat > MIN_LAT && maxLat < MAX_LAT) {
    minLon = radLon - deltaLon;
    maxLon = radLon + deltaLon;
    if (minLon < MIN_LON) {
      minLon = minLon + 2 * Math.PI;
    }
    if (maxLon > MAX_LON) {
      maxLon = maxLon - 2 * Math.PI;
    }
  }
  // a pole is within the given distance
  else {
    minLat = Math.max(minLat, MIN_LAT);
    maxLat = Math.min(maxLat, MAX_LAT);
    minLon = MIN_LON;
    maxLon = MAX_LON;
  }
  return [
    minLon.radToDeg(),
    minLat.radToDeg(),
    maxLon.radToDeg(),
    maxLat.radToDeg()
  ];
};

How to remove padding around buttons in Android?

I had the same problem and it seems that it is because of the background color of the button. Try changing the background color to another color eg:

android:background="@color/colorActive"

and see if it works. You can then define a style if you want for the button to use.

How to mock location on device?

Use this permission in manifest file

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

android studio will recommend that "Mock location should only be requested in a test or debug-specific manifest file (typically src/debug/AndroidManifest.xml)" just disable the inspection

Now make sure you have checked the "Allow mock locations" in developer setting of your phone

Use LocationManager

locationManager.addTestProvider(mocLocationProvider, false, false,
                false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);

Now set the location wherever you want

Location mockLocation = new Location(mocLocationProvider); 
mockLocation.setLatitude(lat); 
mockLocation.setLongitude(lng); 
mockLocation.setAltitude(alt); 
mockLocation.setTime(System.currentTimeMillis()); 
locationManager.setTestProviderLocation( mocLocationProvider, mockLocation); 

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

How to set default values in Go structs

  1. Force a method to get the struct (the constructor way).

    From this post:

    A good design is to make your type unexported, but provide an exported constructor function like NewMyType() in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.

    This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.

  2. Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.

SQL: Combine Select count(*) from multiple tables

SELECT 
(select count(*) from foo1 where ID = '00123244552000258')
+
(select count(*) from foo2 where ID = '00123244552000258')
+
(select count(*) from foo3 where ID = '00123244552000258')

This is an easy way.

How to change the spinner background in Android?

Android Studio has a pre-defined code, you can directly use it. android:popupBackground="HEX COLOR CODE"

A potentially dangerous Request.Path value was detected from the client (*)

This exception occurred in my application and was rather misleading.

It was thrown when I was calling an .aspx page Web Method using an ajax method call, passing a JSON array object. The Web Page method signature contained an array of a strongly-typed .NET object, OrderDetails. The Actual_Qty property was defined as an int, and the JSON object Actual_Qty property contained "4 " (extra space character). After removing the extra space, the conversion was made possible, the Web Page method was successfully reached by the ajax call.

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

Browser (webapi):

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

Does React Native styles support gradients?

Here is a production ready pure JavaScript solution:

<View styles={{backgroundColor: `the main color you want`}}>
    <Image source={`A white to transparent gradient png`}>
</View>

Here is the source code of a npm package using this solution: https://github.com/flyskywhy/react-native-smooth-slider/blob/0f18a8bf02e2d436503b9a8ba241440247ef1c44/src/Slider.js#L329

Here is the gradient palette screenshot of saturation and brightness using this npm package: https://github.com/flyskywhy/react-native-slider-color-picker

react-native-slider-color-picker

Byte Array to Hex String

If you have a numpy array, you can do the following:

>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'

Pandas left outer join multiple dataframes on multiple columns

One can also do this with a compact version of @TomAugspurger's answer, like so:

df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])

Can I find events bound on an element with jQuery?

General case:

  • Hit F12 to open Dev Tools
  • Click the Sources tab
  • On right-hand side, scroll down to Event Listener Breakpoints, and expand tree
  • Click on the events you want to listen for.
  • Interact with the target element, if they fire you will get a break point in the debugger

Similarly, you can:

  • right click on the target element -> select "Inspect element"
  • Scroll down on the right side of the dev frame, at the bottom is 'event listeners'.
  • Expand the tree to see what events are attached to the element. Not sure if this works for events that are handled through bubbling (I'm guessing not)

ActionBar text color

For Android 5 (lollipop) you will have to use android:actionBarPopupTheme to set the textColor for the overflow menu.

How to "grep" out specific line ranges of a file

If you want lines instead of line ranges, you can do it with perl: eg. if you want to get line 1, 3 and 5 from a file, say /etc/passwd:

perl -e 'while(<>){if(++$l~~[1,3,5]){print}}' < /etc/passwd

How to center an element in the middle of the browser window?

Here is:

  • HTML+CSS only solution - no JavaScript needed
  • It does not require that you to know the content size in advance
  • The content stands centered on window resizing

And the example:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML centering</title>

        <style type="text/css">
        <!--
        html, body, #tbl_wrap { height: 100%; width: 100%; padding: 0; margin: 0; }
        #td_wrap { vertical-align: middle; text-align: center; }
        -->
        </style>
    </head>

    <body>
        <table id="tbl_wrap"><tbody><tr><td id="td_wrap">
        <!-- START: Anything between these wrapper comment lines will be centered -->


<div style="border: 1px solid black; display: inline-block;">
This content will be centered.
</div>

        <!-- END: Anything between these wrapper comment lines will be centered -->
        </td></tr></tbody></table>
    </body>
</html>

Take a look at the original URL for full info: http://krustev.net/html_center_content.html

You can do whatever you like with this code. The only condition is that any derived work must have a reference to the original author.

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

Not sure what is the difference between .cfg & .cnf In my server I couldn't find .cfg or .cnf I had created a new file for the same and placed it in the following folder /usr/local/ssl/bin

executed the

.\openssl genrsa -des3 -out <key name>.key 2048 

went great..

Absolute positioning ignoring padding of parent

I would set the child's width this way:

.child {position: absolute; width: calc(100% - padding);}

Padding, in the formula, is the sum of the left and right parent's padding. I admit it is probably not very elegant, but in my case, a div with the function of an overlay, it worked.

VB.Net: Dynamically Select Image from My.Resources

This works for me at runtime too:

UltraPictureBox1.Image = My.Resources.MyPicture

No strings involved and if I change the name it is automatically updated by refactoring.

.attr('checked','checked') does not work

With jQuery, never use inline onclick javascript. Keep it unobtrusive. Do this instead, and remove the onclick completely.

Also, note the use of the :checked pseudo selector in the last line. The reason for this is because once the page is loaded, the html and the actual state of the form element can be different. Open a web inspector and you can click on the other radio button and the HTML will still show the first one is checked. The :checked selector instead filters elements that are actually checked, regardless of what the html started as.

$('button').click(function() {
    alert($('input[name="myname"][value="b"]').length);
    $('input[name="myname"][value="b"]').attr('checked','checked');
    $('#b').attr('checked',true);
    alert($('input[name="myname"]:checked').val());
});

http://jsfiddle.net/uL545/1/

How to free memory from char array in C

Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc) as it's allocated on the heap:

char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);

More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

No module named setuptools

Install setuptools and try again.

try command:

sudo apt-get install -y python-setuptools

GridView sorting: SortDirection always Ascending

This is another way of solving the issue:

protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e)
{
    List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();
    items.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e);
    grdHeader.DataSource = items;
    grdHeader.DataBind();
}

private string ConvertSortDirectionToSql(GridViewSortEventArgs e)
{
    ViewState[e.SortExpression] = ViewState[e.SortExpression] ?? "ASC";
    ViewState[e.SortExpression] = (ViewState[e.SortExpression].ToString() == "ASC") ? "DESC" : "ASC";
    return ViewState[e.SortExpression].ToString();
}

TypeError: a bytes-like object is required, not 'str'

A bit of encoding can solve this:

Client Side:

message = input("->")
clientSocket.sendto(message.encode('utf-8'), (address, port))

Server Side:

data = s.recv(1024)
modifiedMessage, serverAddress = clientSocket.recvfrom(message.decode('utf-8'))

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

From this post:

To get the entire PC CPU and Memory usage:

using System.Diagnostics;

Then declare globally:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

Then to get the CPU time, simply call the NextValue() method:

this.theCPUCounter.NextValue();

This will get you the CPU usage

As for memory usage, same thing applies I believe:

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Memory", "Available MBytes");

Then to get the memory usage, simply call the NextValue() method:

this.theMemCounter.NextValue();

For a specific process CPU and Memory usage:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Process", "% Processor Time",              
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Process", "Working Set",
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?

To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters

The difference between Processor\% Processor Time and Process\% Processor Time is Processor is from the PC itself and Process is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters

An alternative to using the Performance Counter

Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):

CREATE OR REPLACE FUNCTION get_allitems
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems;
  RETURN my_cursor;
END get_allitems;

This will return the cursor.

Make sure not to put your SELECT-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.


If you really need to use dynamic SQL you can put your query in single quotes:

  OPEN my_cursor FOR 'SELECT * FROM allitems';

This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.

Make sure to use bind-variables where possible to avoid hard parses:

  OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;

Interface vs Abstract Class (general OO)

If you consider java as OOP language to answer this question, Java 8 release causes some of the content in above answers as obsolete. Now java interface can have default methods with concrete implementation.

Oracle website provides key differences between interface and abstract class.

Consider using abstract classes if :

  1. You want to share code among several closely related classes.
  2. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  3. You want to declare non-static or non-final fields.

Consider using interfaces if :

  1. You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
  2. You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
  3. You want to take advantage of multiple inheritance of type.

In simple terms, I would like to use

interface: To implement a contract by multiple unrelated objects

abstract class: To implement the same or different behaviour among multiple related objects

Have a look at code example to understand things in clear way : How should I have explained the difference between an Interface and an Abstract class?

IF... OR IF... in a windows batch file

If %x%==1 (
If %y%==1 (
:: both are equal to 1.
)
)

That's for checking if multiple variables equal value. Here's for either variable.

If %x%==1 (
:: true
)
If %x%==0 (
If %y%==1 (
:: true
)
)
If %x%==0 (
If %y%==0 (
:: False
)
)

I just thought of that off the top if my head. I could compact it more.

How to loop an object in React?

The problem is the way you're using forEach(), as it will always return undefined. You're probably looking for the map() method, which returns a new array:

var tifOptions = Object.keys(tifs).map(function(key) {
    return <option value={key}>{tifs[key]}</option>
});

If you still want to use forEach(), you'd have to do something like this:

var tifOptions = [];

Object.keys(tifs).forEach(function(key) {
    tifOptions.push(<option value={key}>{tifs[key]}</option>);
});

Update:

If you're writing ES6, you can accomplish the same thing a bit neater using an arrow function:

const tifOptions = Object.keys(tifs).map(key => 
    <option value={key}>{tifs[key]}</option>
)

Here's a fiddle showing all options mentioned above: https://jsfiddle.net/fs7sagep/

Non-recursive depth first search algorithm

Suppose you want to execute a notification when each node in a graph is visited. The simple recursive implementation is:

void DFSRecursive(Node n, Set<Node> visited) {
  visited.add(n);
  for (Node x : neighbors_of(n)) {  // iterate over all neighbors
    if (!visited.contains(x)) {
      DFSRecursive(x, visited);
    }
  }
  OnVisit(n);  // callback to say node is finally visited, after all its non-visited neighbors
}

Ok, now you want a stack-based implementation because your example doesn't work. Complex graphs might for instance cause this to blow the stack of your program and you need to implement a non-recursive version. The biggest issue is to know when to issue a notification.

The following pseudo-code works (mix of Java and C++ for readability):

void DFS(Node root) {
  Set<Node> visited;
  Set<Node> toNotify;  // nodes we want to notify

  Stack<Node> stack;
  stack.add(root);
  toNotify.add(root);  // we won't pop nodes from this until DFS is done
  while (!stack.empty()) {
    Node current = stack.pop();
    visited.add(current);
    for (Node x : neighbors_of(current)) {
      if (!visited.contains(x)) {
        stack.add(x);
        toNotify.add(x);
      }
    }
  }
  // Now issue notifications. toNotifyStack might contain duplicates (will never
  // happen in a tree but easily happens in a graph)
  Set<Node> notified;
  while (!toNotify.empty()) {
  Node n = toNotify.pop();
  if (!toNotify.contains(n)) {
    OnVisit(n);  // issue callback
    toNotify.add(n);
  }
}

It looks complicated but the extra logic needed for issuing notifications exists because you need to notify in reverse order of visit - DFS starts at root but notifies it last, unlike BFS which is very simple to implement.

For kicks, try following graph: nodes are s, t, v and w. directed edges are: s->t, s->v, t->w, v->w, and v->t. Run your own implementation of DFS and the order in which nodes should be visited must be: w, t, v, s A clumsy implementation of DFS would maybe notify t first and that indicates a bug. A recursive implementation of DFS would always reach w last.

Excel Date to String conversion

Here is a VBA approach:

Sub change()
    toText Sheets(1).Range("A1:F20")
End Sub

Sub toText(target As Range)
Dim cell As Range
    For Each cell In target
        cell.Value = cell.Text
        cell.NumberFormat = "@"
    Next cell
End Sub

If you are looking for a solution without programming, the Question should be moved to SuperUser.

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

You need to either provide the absolute path to data.csv, or run your script in the same directory as data.csv.

How to center body on a page?

Also apply text-align: center; on the html element like so:

html {
  text-align: center;
}

A better approach though is to have an inner container div, which will be centralized, and not the body.

How to use ScrollView in Android?

As said above you can put it inside a ScrollView... and if you want the Scroll View to be horizontal put it inside HorizontalScrollView... and if you want your component (or layout) to support both put inside both of them like this:

  <HorizontalScrollView>
        <ScrollView>
            <!-- SOME THING -->
        </ScrollView>
    </HorizontalScrollView>

and with setting the layout_width and layout_height ofcourse.

Interactive shell using Docker Compose

In the official getting started example (https://docs.docker.com/compose/gettingstarted/) with the following docker-compose.yml:

version: '3'
services:
  web:
    build: .
    ports:
     - "5000:5000"
  redis:
    image: "redis:alpine"

After you start this with docker-compose up, you can easily shell into either your redis container or your web container with:

docker-compose exec redis sh
docker-compose exec web sh 

batch file to list folders within a folder to one level

I tried this command to display the list of files in the directory.

dir /s /b > List.txt

In the file it displays the list below.

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll

What is want to do is only to display sub-directory not the full directory path.

Just like this:

Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll

Cisco Jabber\accessories\JabraJabberPlugin.dll

Cisco Jabber\accessories\Logitech

Cisco Jabber\accessories\Plantronics

Cisco Jabber\accessories\SennheiserJabberPlugin.dll

Call PHP function from jQuery?

AJAX does the magic:

$(document).ready(function(

    $.ajax({ url: 'script.php?argument=value&foo=bar' });

));

error: Your local changes to the following files would be overwritten by checkout

This error happens when the branch you are switching to, has changes that your current branch doesn't have.

If you are seeing this error when you try to switch to a new branch, then your current branch is probably behind one or more commits. If so, run:

git fetch

You should also remove dependencies which may also conflict with the destination branch.

For example, for iOS developers:

pod deintegrate

then try checking out a branch again.

If the desired branch isn't new you can either cherry pick a commit and fix the conflicts or stash the changes and then fix the conflicts.

1. Git Stash (recommended)

git stash
git checkout <desiredBranch>
git stash apply

2. Cherry pick (more work)

git add <your file>
git commit -m "Your message"
git log

Copy the sha of your commit. Then discard unwanted changes:

git checkout .
git checkout -- . 
git clean -f -fd -fx

Make sure your branch is up to date:

git fetch

Then checkout to the desired branch

git checkout <desiredBranch>

Then cherry pick the other commit:

git cherry-pick <theSha>

Now fix the conflict.

  1. Otherwise, your other option is to abandon your current branches changes with:
git checkout -f branch

Oracle 'Partition By' and 'Row_Number' keyword

PARTITION BY segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.

In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER

But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency

newid() produces GUID, so what shall you expect by this expression?

select
   hi,ho,
   row_number() over(partition by newid() order by hi,ho)
from tbl;

...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1

Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1

An example, this is your data:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');

Then this is analogous to your query:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho)
from tbl;

What will be the output of that?

HI  HO  COLUMN_2
A   X   1
A   Y   1
A   Z   1
B   W   1
B   W   2
C   L   1
C   L   2

You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.

Now, why is the ORDER BY needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY; whereas in Postgresql, ORDER BY on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1

select
   hi,ho,
   row_number() over(partition by hi,ho)
from tbl;

Your ORDER BY on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION with no ORDER BY, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:

SELECT cdt.*,
        ROW_NUMBER ()
        OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
              ORDER BY newid())
           seq_no
   FROM CUSTOMER_DETAILS cdt

You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid() for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION with no ORDER BY

Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table

It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.

Live test: http://www.sqlfiddle.com/#!3/27821/6


But as dbaseman have noticed also, it's useless to partition and order on same columns.

You have a set of data like this:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');

Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

Output:

HI  HO  ROW_QUERY_A
A   X   1
A   X   2
A   X   3
B   Y   1
B   Y   2
C   Z   1
C   Z   2

See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)


You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:

create table tbl(hi varchar, ho varchar);

insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');

select
   hi,ho,
   row_number() over(partition by hi order by ho) as nr
from tbl;

PARTITION BY hi operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho

Output:

HI  HO  NR
A   D   1
A   E   2
A   F   3
B   E   1
B   F   2
C   D   1
C   E   2

That data set makes more sense

Live test: http://www.sqlfiddle.com/#!3/d0b44/1

And this is similar to your query with same columns on both PARTITION BY and ORDER BY:

select
   hi,ho,
   row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;

And this is the ouput:

HI  HO  NR
A   D   1
A   E   1
A   F   1
B   E   1
B   F   1
C   D   1
C   E   1

See? no sense?

Live test: http://www.sqlfiddle.com/#!3/d0b44/3


Finally this might be the right query:

SELECT cdt.*,
     ROW_NUMBER ()
     OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
           ORDER BY 
               -- removed: cdt.country_code, cdt.account, 
               cdt.currency) -- keep
        seq_no
FROM CUSTOMER_DETAILS cdt

What is the use of hashCode in Java?

The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.

By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

This answer is from the java SE 8 official tutorial documentation

Set title background color

Try with the following code

View titleView = getWindow().findViewById(android.R.id.title);
    if (titleView != null) {
      ViewParent parent = titleView.getParent();
      if (parent != null && (parent instanceof View)) {
        View parentView = (View)parent;
        parentView.setBackgroundColor(Color.RED);
      }
    }

also use this link its very useful : http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/

PHP - Extracting a property from an array of objects

You can do it easily with ouzo goodies

$result = array_map(Functions::extract()->id, $arr);

or with Arrays (from ouzo goodies)

$result = Arrays::map($arr, Functions::extract()->id);

Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract

See also functional programming with ouzo (I cannot post a link).

How to keep one variable constant with other one changing with row in excel

You put it as =(B0+4)/($A$0)

You can also go across WorkSheets with Sheet1!$a$0

How to use a variable for a key in a JavaScript object literal?

With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation: 

var obj = {
  [key]: value
}

Where key can be any sort of expression (e.g. a variable) returning a value.

So here your code would look like:

<something>.stop().animate({
  [thetop]: 10
}, 10)

Where thetop will be evaluated before being used as key.

Dealing with commas in a CSV file

There is a library available through nuget for dealing with pretty much any well formed CSV (.net) - CsvHelper

Example to map to a class:

var csv = new CsvReader( textReader );
var records = csv.GetRecords<MyClass>();

Example to read individual fields:

var csv = new CsvReader( textReader );
while( csv.Read() )
{
    var intField = csv.GetField<int>( 0 );
    var stringField = csv.GetField<string>( 1 );
    var boolField = csv.GetField<bool>( "HeaderName" );
}

Letting the client drive the file format:
, is the standard field delimiter, " is the standard value used to escape fields that contain a delimiter, quote, or line ending.

To use (for example) # for fields and ' for escaping:

var csv = new CsvReader( textReader );
csv.Configuration.Delimiter = "#";
csv.Configuration.Quote = ''';
// read the file however meets your needs

More Documentation

Build error, This project references NuGet

Why should you need manipulations with packages.config or .csproj files?
The error explicitly says: Use NuGet Package Restore to download them.
Use it accordingly this instruction: https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore-troubleshooting:

Quick solution for Visual Studio users
1.Select the Tools > NuGet Package Manager > Package Manager Settings menu command.
2.Set both options under Package Restore.
3.Select OK.
4.Build your project again.

How to use the "required" attribute with a "radio" input field

Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:

_x000D_
_x000D_
fieldset { 
  display: block;
  margin-left: 0;
  margin-right: 0;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 0;
  padding-right: 0;
  border: none;
}
body {font-size: 15px; font-family: serif;}
input {
  background: transparent;
  border-radius: 0px;
  border: 1px solid black;
  padding: 5px;
  box-shadow: none!important;
  font-size: 15px; font-family: serif;
}
input[type="submit"] {padding: 5px 10px; margin-top: 5px;}
label {display: block; padding: 0 0 5px 0;}
form > div {margin-bottom: 1em; overflow: auto;}
.hidden {
  opacity: 0; 
  position: absolute; 
  pointer-events: none;
}
.checkboxes label {display: block; float: left;}
input[type="radio"] + span {
  display: block;
  border: 1px solid black;
  border-left: 0;
  padding: 5px 10px;
}
label:first-child input[type="radio"] + span {border-left: 1px solid black;}
input[type="radio"]:checked + span {background: silver;}
_x000D_
<form>
  <div>
    <label for="name">Name (optional)</label>
    <input id="name" type="text" name="name">
  </div>
  <fieldset>
  <legend>Gender</legend>
  <div class="checkboxes">
    <label for="male"><input id="male" type="radio" name="gender" value="male" class="hidden" required="required"><span>Male</span></label>
    <label for="female"><input id="female" type="radio" name="gender" value="female" class="hidden" required="required"><span>Female </span></label>
    <label for="other"><input id="other" type="radio" name="gender" value="other" class="hidden" required="required"><span>Other</span></label>
  </div>
  </fieldset>
  <input type="submit" value="Send" />
</form>
_x000D_
_x000D_
_x000D_

Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.

android - how to convert int to string and place it in a EditText?

Use +, the string concatenation operator:

ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);

or use String.valueOf(int):

ed.setText(String.valueOf(x));

or use Integer.toString(int):

ed.setText(Integer.toString(x));

Passing parameters on button action:@selector

I think the correct method should be : - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

UIControl Reference

Where do you get your method from?

I see that your selector has an argument, that argument will be filled by the runtime system. It will send you back the button through that argument.

Your method should look like:

- (void)buttonPressed:(id)BUTTON_HERE { }

Return HTTP status code 201 in flask

You can use Response to return any http status code.

> from flask import Response
> return Response("{'a':'b'}", status=201, mimetype='application/json')

How to wait until an element is present in Selenium?

Let me recommend you using Selenide library. It allows writing much more concise and readable tests. It can wait for presence of elements with much shorter syntax:

$("#elementId").shouldBe(visible);

Here is a sample project for testing Google search: https://github.com/selenide-examples/google

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

ASP.net vs PHP (What to choose)

You can have great success and great performance either way. MSDN runs off of ASP.NET so you know it can perform well. PHP runs a lot of the top websites in the world. The same can be said of the databases as well. You really need to choose based upon your skills, the skills of your team, possible specific features that you need/want that one does better than the other, and even the servers that you want to run this site.

If I were building it, I would lean towards PHP because probably everything you want to do has been done before (with code examples how) and because hosting is so much easier to get (and cheaper because you don't have the licensing issues to deal with compared to Windows hosting). For the same reason, I would choose MySQL as well. It is a great database platform and the price is right.

PHP is not recognized as an internal or external command in command prompt

Extra info:

If you are using PhpStorm as IDE, after updating the path variable you need to restart PhpStorm so that it takes effect.

Restarting terminal window was not enough for me. (PhpStorm 2020.3.2)

Failure [INSTALL_FAILED_INVALID_APK]

Your package name should include words combined by dots like com.example or prashant.mydairy..... it should work fine now

files where you must update ur package name are as below: 1)Manifest file 2)Gradle file(module appp): applicationId "package.name"

How to make use of ng-if , ng-else in angularJS

I am adding some of the important concern about ng directives:-

  1. Directives will respond the same place where it's execute.
  2. ng-else concept is not there, you can with only if, or other flavor like switch statement.

Check out the below example:-

<div ng-if="data.type == 'FirstValue' ">

//different template with hoot data

</div>

<div ng-if="data.type == 'SecondValue' ">

  //different template with story data

</div>

<div ng-if="data.type == 'ThirdValue' ">

 //different template with article data

</div>

As per datatype it is going to render any one of the div.

How to get the size of a range in Excel

The Range object has both width and height properties, which are measured in points.

What is the command to exit a Console application in C#?

You can use Environment.Exit(0) and Application.Exit.

Environment.Exit(): terminates this process and gives the underlying operating system the specified exit code.

How to change color in markdown cells ipython/jupyter notebook?

You can simply use raw html tags like

foo <font color='red'>bar</font> foo

Be aware that this will not survive a conversion of the notebook to latex.

As there are some complaints about the deprecation of the proposed solution. They are totally valid and Scott has already answered the question with a more recent, i.e. CSS based approach. Nevertheless, this answer shows some general approach to use html tags within IPython to style markdown cell content beyond the available pure markdown capabilities.

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Plug it in, and run this from the command line:

system_profiler SPUSBDataType

Look for:

Serial Number: xxxx

How to move an element into another element?

If you want a quick demo and more details about how you move elements, try this link:

http://html-tuts.com/move-div-in-another-div-with-jquery


Here is a short example:

To move ABOVE an element:

$('.whatToMove').insertBefore('.whereToMove');

To move AFTER an element:

$('.whatToMove').insertAfter('.whereToMove');

To move inside an element, ABOVE ALL elements inside that container:

$('.whatToMove').prependTo('.whereToMove');

To move inside an element, AFTER ALL elements inside that container:

$('.whatToMove').appendTo('.whereToMove');

resize2fs: Bad magic number in super-block while trying to open

On centos and fedora work with fsadm

fsadm resize /dev/vg_name/root

Is there a way to list open transactions on SQL Server 2000 database?

DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.

An informational message is displayed if there are no active transactions in the log.

DBCC OPENTRAN

Generate a unique id

Why can't we make a unique id as below.

We can use DateTime.Now.Ticks and Guid.NewGuid().ToString() to combine together and make a unique id.

As the DateTime.Now.Ticks is added, we can find out the Date and Time in seconds at which the unique id is created.

Please see the code.

var ticks = DateTime.Now.Ticks;
var guid = Guid.NewGuid().ToString();
var uniqueSessionId = ticks.ToString() +'-'+ guid; //guid created by combining ticks and guid

var datetime = new DateTime(ticks);//for checking purpose
var datetimenow = DateTime.Now;    //both these date times are different.

We can even take the part of ticks in unique id and check for the date and time later for future reference.

NPM global install "cannot find module"

For Windows, from Nodejs cannot find installed module on Windows? what worked for me is running npm link as in

npm link wisp

How to convert JTextField to String and String to JTextField?

// to string
String text = textField.getText();

// to JTextField
textField.setText(text);

You can also create a new text field: new JTextField(text)

Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.

Reference: javadocs of JTextField

Mocking static methods with Mockito

There is an easy solution by using java FunctionalInterface and then add that interface as dependency for the class you are trying to unit test.

Redirect echo output in shell script to logfile

You can add this line on top of your script:

#!/bin/bash
# redirect stdout/stderr to a file
exec &> logfile.txt

OR else to redirect only stdout use:

exec > logfile.txt

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

Wait Until File Is Completely Written

You're actually in luck - the program writing the file locks it, so you can't open it. If it hadn't locked it, you would have copied a partial file, without having any idea there's a problem.

When you can't access a file, you can assume it's still in use (better yet - try to open it in exclusive mode, and see if someone else is currently opening it, instead of guessing from the failure of File.Copy). If the file is locked, you'll have to copy it at some other time. If it's not locked, you can copy it (there's slight potential for a race condition here).

When is that 'other time'? I don't rememeber when FileSystemWatcher sends multiple events per file - check it out, it might be enough for you to simply ignore the event and wait for another one. If not, you can always set up a time and recheck the file in 5 seconds.

Troubleshooting BadImageFormatException

What I found worked was checking the "Use the 64 bit version of IIS Express for Web Sites and Projects" option under the Projects and Solutions => Web Projects section under the Tools=>Options menu.

Java error: Only a type can be imported. XYZ resolves to a package

Well, you are not really providing enough details on your webapp but my guess is that you have a JSP with something like that:

<%@ page import="java.util.*,x.y.Z"%> 

And x.y.Z can't be found on the classpath (i.e. is not present under WEB-INF/classes nor in a JAR of WEB-INF/lib).

Double check that the WAR you deploy on Tomcat has the following structure:

my-webapp
|-- META-INF
|   `-- MANIFEST.MF
|-- WEB-INF
|   |-- classes
|   |   |-- x
|   |   |   `-- y
|   |   |       `-- Z.class
|   |   `-- another
|   |       `-- packagename
|   |           `-- AnotherClass.class
|   |-- lib
|   |   |-- ajar.jar
|   |   |-- bjar.jar
|   |   `-- zjar.jar
|   `-- web.xml
|-- a.jsp
|-- b.jsp
`-- index.jsp

Or that the JAR that bundles x.y.Z.class is present under WEB-INF/lib.

SHOW PROCESSLIST in MySQL command: sleep

"Sleep" state connections are most often created by code that maintains persistent connections to the database.

This could include either connection pools created by application frameworks, or client-side database administration tools.

As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.

(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)

how to align all my li on one line?

I think the NOBR tag might be overkill, and as you said, unreliable.

There are 2 options available depending on how you are displaying the text.

If you are displaying text in a table cell you would do Long Text Here. If you are using a div or a span, you can use the style="white-space: nowrap;"

Way to go from recursion to iteration

Generally the technique to avoid stack overflow is for recursive functions is called trampoline technique which is widely adopted by Java devs.

However, for C# there is a little helper method here that turns your recursive function to iterative without requiring to change logic or make the code in-comprehensible. C# is such a nice language that amazing stuff is possible with it.

It works by wrapping parts of the method by a helper method. For example the following recursive function:

int Sum(int index, int[] array)
{
 //This is the termination condition
 if (int >= array.Length)
 //This is the returning value when termination condition is true
 return 0;

//This is the recursive call
 var sumofrest = Sum(index+1, array);

//This is the work to do with the current item and the
 //result of recursive call
 return array[index]+sumofrest;
}

Turns into:

int Sum(int[] ar)
{
 return RecursionHelper<int>.CreateSingular(i => i >= ar.Length, i => 0)
 .RecursiveCall((i, rv) => i + 1)
 .Do((i, rv) => ar[i] + rv)
 .Execute(0);
}

Edit line thickness of CSS 'underline' attribute

Thanks to the magic of new css options this is now possible natively:

a {
  text-decoration: underline;
  text-decoration-thickness: 5px;
  text-decoration-skip-ink: auto;
  text-underline-offset: 3px;
}

As of yet support is relatively poor. But it'll land in other browsers than ff eventually.

CentOS 7 and Puppet unable to install nc

yum install nmap-ncat.x86_64

resolved my problem

Show DialogFragment with animation growing from a point

Have you looked at Android Developers Training on Zooming a View? Might be a good starting point.

You probably want to create a custom class extending DialogFragment to get this working.

Also, take a look at Jake Whartons NineOldAndroids for Honeycomb Animation API compatibility all the way back to API Level 1.

Get difference between two lists

The difference between two lists (say list1 and list2) can be found using the following simple function.

def diff(list1, list2):
    c = set(list1).union(set(list2))  # or c = set(list1) | set(list2)
    d = set(list1).intersection(set(list2))  # or d = set(list1) & set(list2)
    return list(c - d)

or

def diff(list1, list2):
    return list(set(list1).symmetric_difference(set(list2)))  # or return list(set(list1) ^ set(list2))

By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2). Both will give the result ['Four', 'Three']. You don't have to worry about the order of the list or which list is to be given first.

Python doc reference

JavaScript hide/show element

I recommend Javascript, because its relatively fast and more malleable.

    <script>
function showStuff(id, text, btn) {
document.getElementById(id).style.display = 'block';
// hide the lorem ipsum text
document.getElementById(text).style.display = 'none';
// hide the link
btn.style.display = 'none';
}
</script>


<td class="post">

<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>
<span id="answer1" style="display: none;">
<textarea rows="10" cols="115"></textarea>
</span>

<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>
</td>

UITextField border color

Import QuartzCore framework in you class:

#import <QuartzCore/QuartzCore.h>

and for changing the border color use the following code snippet (I'm setting it to redColor),

    textField.layer.cornerRadius=8.0f;
    textField.layer.masksToBounds=YES;
    textField.layer.borderColor=[[UIColor redColor]CGColor];
    textField.layer.borderWidth= 1.0f;

For reverting back to the original layout just set border color to clear color,

    serverField.layer.borderColor=[[UIColor clearColor]CGColor];

in swift code

    textField.layer.borderWidth = 1
    textField.layer.borderColor = UIColor.whiteColor().CGColor

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

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

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

Conditional logic in AngularJS template

You could use the ngSwitch directive:

  <div ng-switch on="selection" >
    <div ng-switch-when="settings">Settings Div</div>
    <span ng-switch-when="home">Home Span</span>
    <span ng-switch-default>default</span>
  </div>

If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.

This is just an (untested) example. It can and should be optimized:

HTML:

<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>

Directive:

app.directive('conditionalTemplate', function($http, $compile) {
   return {
      restrict: 'E',
      require: '^ngModel',
      link: function(sope, element, attrs, ctrl) {
        // get template with $http
        // check model via ctrl.$viewValue
        // compile with $compile
        // replace element with element.replaceWith()
      }
   };
});

How to print an exception in Python 3?

I'm guessing that you need to assign the Exception to a variable. As shown in the Python 3 tutorial:

def fails():
    x = 1 / 0

try:
    fails()
except Exception as ex:
    print(ex)

To give a brief explanation, as is a pseudo-assignment keyword used in certain compound statements to assign or alias the preceding statement to a variable.

In this case, as assigns the caught exception to a variable allowing for information about the exception to stored and used later, instead of needing to be dealt with immediately. (This is discussed in detail in the Python 3 Language Reference: The try Statement.)


The other compound statement using as is the with statement:

@contextmanager
def opening(filename):
    f = open(filename)
    try:
        yield f
    finally:
        f.close()

with opening(filename) as f:
    # ...read data from f...

Here, with statements are used to wrap the execution of a block with methods defined by context managers. This functions like an extended try...except...finally statement in a neat generator package, and the as statement assigns the generator-produced result from the context manager to a variable for extended use. (This is discussed in detail in the Python 3 Language Reference: The with Statement.)


Finally, as can be used when importing modules, to alias a module to a different (usually shorter) name:

import foo.bar.baz as fbb

This is discussed in detail in the Python 3 Language Reference: The import Statement.

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

I haven't figure out the reason but reinstalling the .pfx certificate(both in current user and local machine) works for me.

how to concat two columns into one with the existing column name in mysql?

Remove the * from your query and use individual column names, like this:

SELECT SOME_OTHER_COLUMN, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`;

Using * means, in your results you want all the columns of the table. In your case * will also include FIRSTNAME. You are then concatenating some columns and using alias of FIRSTNAME. This creates 2 columns with same name.

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

How to upload a project to Github

Follow these steps to upload your project to Github

1) git init

2) git add .

3) git commit -m "Add all my files"

4) git remote add origin https://github.com/yourusername/your-repo-name.git

Upload of project from scratch require git pull origin master.

5) git pull origin master

6) git push origin master

If any problem occurs in pushing use git push --force origin master

How to create a database from shell command?

mysqladmin -u$USER -p$PASSWORD create $DB_NAME

Replace above variables and you are good to go with this oneliner. $USER is the username, $PASSWORD is the password and $DB_NAME is the name of the database.

How can I read user input from the console?

string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
    Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);

The main reason of different input/output you're facing is that Console.Read() returns char code, not a number you typed! Learn how to use MSDN.

Execute a shell function with timeout

I have a slight modification of @Tiago Lopo's answer that can handle commands with multiple arguments. I've also tested TauPan's solution, but it does not work if you use it multiple times in a script, while Tiago's does.

function timeout_cmd { 
  local arr
  local cmd
  local timeout

  arr=( "$@" )

  # timeout: first arg
  # cmd: the other args
  timeout="${arr[0]}"
  cmd=( "${arr[@]:1}" )

  ( 
    eval "${cmd[@]}" &
    child=$!

    echo "child: $child"
    trap -- "" SIGTERM 
    (       
      sleep "$timeout"
      kill "$child" 2> /dev/null 
    ) &     
    wait "$child"
  )
}

Here's a fully functional script thant you can use to test the function above:

$ ./test_timeout.sh -h
Usage:
  test_timeout.sh [-n] [-r REPEAT] [-s SLEEP_TIME] [-t TIMEOUT]
  test_timeout.sh -h

Test timeout_cmd function.

Options:
  -n              Dry run, do not actually sleep. 
  -r REPEAT       Reapeat everything multiple times [default: 1].
  -s SLEEP_TIME   Sleep for SLEEP_TIME seconds [default: 5].
  -t TIMEOUT      Timeout after TIMEOUT seconds [default: no timeout].

For example you cnal launch like this:

$ ./test_timeout.sh -r 2 -s 5 -t 3
Try no: 1
  - Set timeout to: 3
child: 2540
    -> retval: 143
    -> The command timed out
Try no: 2
  - Set timeout to: 3
child: 2593
    -> retval: 143
    -> The command timed out
Done!
#!/usr/bin/env bash

#shellcheck disable=SC2128
SOURCED=false && [ "$0" = "$BASH_SOURCE" ] || SOURCED=true

if ! $SOURCED; then
  set -euo pipefail
  IFS=$'\n\t'
fi

#################### helpers
function check_posint() {
  local re='^[0-9]+$'
  local mynum="$1"
  local option="$2"

  if ! [[ "$mynum" =~ $re ]] ; then
     (echo -n "Error in option '$option': " >&2)
     (echo "must be a positive integer, got $mynum." >&2)
     exit 1
  fi

  if ! [ "$mynum" -gt 0 ] ; then
     (echo "Error in option '$option': must be positive, got $mynum." >&2)
     exit 1
  fi
}
#################### end: helpers

#################### usage
function short_usage() {
  (>&2 echo \
"Usage:
  test_timeout.sh [-n] [-r REPEAT] [-s SLEEP_TIME] [-t TIMEOUT]
  test_timeout.sh -h"
  )
}

function usage() {
  (>&2 short_usage )
  (>&2 echo \
"
Test timeout_cmd function.

Options:
  -n              Dry run, do not actually sleep. 
  -r REPEAT       Reapeat everything multiple times [default: 1].
  -s SLEEP_TIME   Sleep for SLEEP_TIME seconds [default: 5].
  -t TIMEOUT      Timeout after TIMEOUT seconds [default: no timeout].
")
}
#################### end: usage

help_flag=false
dryrun_flag=false
SLEEP_TIME=5
TIMEOUT=-1
REPEAT=1

while getopts ":hnr:s:t:" opt; do
  case $opt in
    h)
      help_flag=true
      ;;    
    n)
      dryrun_flag=true
      ;;
    r)
      check_posint "$OPTARG" '-r'

      REPEAT="$OPTARG"
      ;;
    s)
      check_posint "$OPTARG" '-s'

      SLEEP_TIME="$OPTARG"
      ;;
    t)
      check_posint "$OPTARG" '-t'

      TIMEOUT="$OPTARG"
      ;;
    \?)
      (>&2 echo "Error. Invalid option: -$OPTARG.")
      (>&2 echo "Try -h to get help")
      short_usage
      exit 1
      ;;
    :)
      (>&2 echo "Error.Option -$OPTARG requires an argument.")
      (>&2 echo "Try -h to get help")
      short_usage
      exit 1
      ;;
  esac
done

if $help_flag; then
  usage
  exit 0
fi

#################### utils
if $dryrun_flag; then
  function wrap_run() {
    ( echo -en "[dry run]\\t" )
    ( echo "$@" )
  }
else
  function wrap_run() { "$@"; }
fi

# Execute a shell function with timeout
# https://stackoverflow.com/a/24416732/2377454
function timeout_cmd { 
  local arr
  local cmd
  local timeout

  arr=( "$@" )

  # timeout: first arg
  # cmd: the other args
  timeout="${arr[0]}"
  cmd=( "${arr[@]:1}" )

  ( 
    eval "${cmd[@]}" &
    child=$!

    echo "child: $child"
    trap -- "" SIGTERM 
    (       
      sleep "$timeout"
      kill "$child" 2> /dev/null 
    ) &     
    wait "$child"
  )
}
####################

function sleep_func() {
  local secs
  local waitsec

  waitsec=1
  secs=$(($1))
  while [ "$secs" -gt 0 ]; do
   echo -ne "$secs\033[0K\r"
   sleep "$waitsec"
   secs=$((secs-waitsec))
  done

}

command=("wrap_run" \
         "sleep_func" "${SLEEP_TIME}"
         )

for i in $(seq 1 "$REPEAT"); do
  echo "Try no: $i"

  if [ "$TIMEOUT" -gt 0 ]; then
    echo "  - Set timeout to: $TIMEOUT"
    set +e
    timeout_cmd "$TIMEOUT" "${command[@]}"
    retval="$?"
    set -e

    echo "    -> retval: $retval"
    # check if (retval % 128) == SIGTERM (== 15)
    if [[ "$((retval % 128))" -eq 15 ]]; then
      echo "    -> The command timed out"
    fi
  else
    echo "  - No timeout"
    "${command[@]}"
    retval="$?"
  fi
done

echo "Done!"

exit 0

msvcr110.dll is missing from computer error while installing PHP

I was missing the MSVCR110.dll. Which I corrected. I could run php from the command line but not the web server. Then I clicked on php-cgi.exe and it gave me the answer. The php5.dll was missing (I downloaded the wrong copy). So for my 2012 IIS box I re-installed using php's x86 non thread safe zip.

Android Imagebutton change Image OnClick

You have assing button to your imgButton variable:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imgButton = (Button) findViewById(R.id.imgButton);
    imgButton.setOnClickListener(imgButtonHandler);
}

what is the difference between ajax and jquery and which one is better?

Ajax is a technology / paradigm, whereas jquery is a library (which provides - besides other nice functionality - a convenient wrapper around ajax) - thus you can't compare them.

Bundling data files with PyInstaller (--onefile)

I found the existing answers confusing, and took a long time to work out where the problem is. Here's a compilation of everything I found.

When I run my app, I get an error Failed to execute script foo (if foo.py is the main file). To troubleshoot this, don't run PyInstaller with --noconsole (or edit main.spec to change console=False => console=True). With this, run the executable from a command-line, and you'll see the failure.

The first thing to check is that it's packaging up your extra files correctly. You should add tuples like ('x', 'x') if you want the folder x to be included.

After it crashes, don't click OK. If you're on Windows, you can use Search Everything. Look for one of your files (eg. sword.png). You should find the temporary path where it unpacked the files (eg. C:\Users\ashes999\AppData\Local\Temp\_MEI157682\images\sword.png). You can browse this directory and make sure it included everything. If you can't find it this way, look for something like main.exe.manifest (Windows) or python35.dll (if you're using Python 3.5).

If the installer includes everything, the next likely problem is file I/O: your Python code is looking in the executable's directory, instead of the temp directory, for files.

To fix that, any of the answers on this question work. Personally, I found a mixture of them all to work: change directory conditionally first thing in your main entry-point file, and everything else works as-is:

if hasattr(sys, '_MEIPASS'): os.chdir(sys._MEIPASS)

Make sure that the controller has a parameterless public constructor error

I had the same issue and I resolved it by making changes in the UnityConfig.cs file In order to resolve the dependency issue in the UnityConfig.cs file you have to add:

public static void RegisterComponents()    
{
    var container = new UnityContainer();
    container.RegisterType<ITestService, TestService>();
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

Get Enum from Description attribute

rather than extension methods, just try a couple of static methods

public static class Utility
{
    public static string GetDescriptionFromEnumValue(Enum value)
    {
        DescriptionAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof (DescriptionAttribute), false)
            .SingleOrDefault() as DescriptionAttribute;
        return attribute == null ? value.ToString() : attribute.Description;
    }

    public static T GetEnumValueFromDescription<T>(string description)
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException();
        FieldInfo[] fields = type.GetFields();
        var field = fields
                        .SelectMany(f => f.GetCustomAttributes(
                            typeof(DescriptionAttribute), false), (
                                f, a) => new { Field = f, Att = a })
                        .Where(a => ((DescriptionAttribute)a.Att)
                            .Description == description).SingleOrDefault();
        return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
    }
}

and use here

var result1 = Utility.GetDescriptionFromEnumValue(
    Animal.GiantPanda);
var result2 = Utility.GetEnumValueFromDescription<Animal>(
    "Lesser Spotted Anteater");

Cannot connect to repo with TortoiseSVN

Run ipconfig /flushdns from a command prompt. Apparently some people seem to think I posted this answer for sheer fun. That's why they down voted my answer. Perhaps an explanation would help them. When I used "SVN Update" it said it can't connect to the SVN repository although I could ping the server. After running ipconfig /flushdns the issue was fixed.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

How do you auto format code in Visual Studio?

For Visual Studio 2010/2013/2015/2017/2019

  • Format Document (Ctrl+K,Ctrl+D) so type Ctrl+K, AND THEN Ctrl+D as it is a sequence
  • Format Selection (Ctrl+K,Ctrl+F)

Toolbar Edit -> Advanced (If you can't see Advanced, select a code file in solution explorer and try again)

Your shortcuts might display differently to mine as I am set up for C# coding but navigating via the toolbar will get you to your ones.

If it isn't working, look for errors in your code, like missing brackets which stop auto format from working

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

Assigning out/ref parameters in Moq

EDIT: In Moq 4.10, you can now pass a delegate that has an out or ref parameter directly to the Callback function:

mock
  .Setup(x=>x.Method(out d))
  .Callback(myDelegate)
  .Returns(...); 

You will have to define a delegate and instantiate it:

...
.Callback(new MyDelegate((out decimal v)=>v=12m))
...

For Moq version before 4.10:

Avner Kashtan provides an extension method in his blog which allows setting the out parameter from a callback: Moq, Callbacks and Out parameters: a particularly tricky edge case

The solution is both elegant and hacky. Elegant in that it provides a fluent syntax that feels at-home with other Moq callbacks. And hacky because it relies on calling some internal Moq APIs via reflection.

The extension method provided at the above link didn't compile for me, so I've provided an edited version below. You'll need to create a signature for each number of input parameters you have; I've provided 0 and 1, but extending it further should be simple:

public static class MoqExtensions
{
    public delegate void OutAction<TOut>(out TOut outVal);
    public delegate void OutAction<in T1,TOut>(T1 arg1, out TOut outVal);

    public static IReturnsThrows<TMock, TReturn> OutCallback<TMock, TReturn, TOut>(this ICallback<TMock, TReturn> mock, OutAction<TOut> action)
        where TMock : class
    {
        return OutCallbackInternal(mock, action);
    }

    public static IReturnsThrows<TMock, TReturn> OutCallback<TMock, TReturn, T1, TOut>(this ICallback<TMock, TReturn> mock, OutAction<T1, TOut> action)
        where TMock : class
    {
        return OutCallbackInternal(mock, action);
    }

    private static IReturnsThrows<TMock, TReturn> OutCallbackInternal<TMock, TReturn>(ICallback<TMock, TReturn> mock, object action)
        where TMock : class
    {
        mock.GetType()
            .Assembly.GetType("Moq.MethodCall")
            .InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock,
                new[] { action });
        return mock as IReturnsThrows<TMock, TReturn>;
    }
}

With the above extension method, you can test an interface with out parameters such as:

public interface IParser
{
    bool TryParse(string token, out int value);
}

.. with the following Moq setup:

    [TestMethod]
    public void ParserTest()
    {
        Mock<IParser> parserMock = new Mock<IParser>();

        int outVal;
        parserMock
            .Setup(p => p.TryParse("6", out outVal))
            .OutCallback((string t, out int v) => v = 6)
            .Returns(true);

        int actualValue;
        bool ret = parserMock.Object.TryParse("6", out actualValue);

        Assert.IsTrue(ret);
        Assert.AreEqual(6, actualValue);
    }



Edit: To support void-return methods, you simply need to add new overload methods:

public static ICallbackResult OutCallback<TOut>(this ICallback mock, OutAction<TOut> action)
{
    return OutCallbackInternal(mock, action);
}

public static ICallbackResult OutCallback<T1, TOut>(this ICallback mock, OutAction<T1, TOut> action)
{
    return OutCallbackInternal(mock, action);
}

private static ICallbackResult OutCallbackInternal(ICallback mock, object action)
{
    mock.GetType().Assembly.GetType("Moq.MethodCall")
        .InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock, new[] { action });
    return (ICallbackResult)mock;
}

This allows testing interfaces such as:

public interface IValidationRule
{
    void Validate(string input, out string message);
}

[TestMethod]
public void ValidatorTest()
{
    Mock<IValidationRule> validatorMock = new Mock<IValidationRule>();

    string outMessage;
    validatorMock
        .Setup(v => v.Validate("input", out outMessage))
        .OutCallback((string i, out string m) => m  = "success");

    string actualMessage;
    validatorMock.Object.Validate("input", out actualMessage);

    Assert.AreEqual("success", actualMessage);
}

Why does cURL return error "(23) Failed writing body"?

For completeness and future searches:

It's a matter of how cURL manages the buffer, the buffer disables the output stream with the -N option.

Example: curl -s -N "URL" | grep -q Welcome

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

What's the difference between a Python module and a Python package?

A module is a single file (or files) that are imported under one import and used. e.g.

import my_module

A package is a collection of modules in directories that give a package hierarchy.

from my_package.timing.danger.internets import function_of_love

Documentation for modules

Introduction to packages

Getting cursor position in Python

win32gui.GetCursorPos(point)

This retrieves the cursor's position, in screen coordinates - point = (x,y)

flags, hcursor, (x,y) = win32gui.GetCursorInfo()

Retrieves information about the global cursor.

Links:

I am assuming that you would be using python win32 API bindings or pywin32.

After submitting a POST form open a new window showing the result

If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");

var hiddenField = document.createElement("input");              
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);

// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

form.submit();

C++ pass an array by reference

As you are using C++, the obligatory suggestion that's still missing here, is to use std::vector<double>.

You can easily pass it by reference:

void foo(std::vector<double>& bar) {}

And if you have C++11 support, also have a look at std::array.

For reference:

How to get all subsets of a set? (powerset)

Perhaps the question is getting old, but I hope my code will help someone.

def powSet(set):
    if len(set) == 0:
       return [[]]
    return addtoAll(set[0],powSet(set[1:])) + powSet(set[1:])

def addtoAll(e, set):
   for c in set:
       c.append(e)
   return set

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

These are usually to make sure that the browser gets a new version when the site gets updated with a new version, e.g. as part of our build process we'd have something like this:

/Resources/Combined.css?v=x.x.x.buildnumber

Since this changes with every new code push, the client's forced to grab a new version, just because of the querystring. Look at this page (at the time of this answer) for example:

<link ... href="http://sstatic.net/stackoverflow/all.css?v=c298c7f8233d">

I think instead of a revision number the SO team went with a file hash, which is an even better approach, even with a new release, the browsers only forced to grab a new version when the file actually changes.

Both of these approaches allow you to set the cache header to something ridiculously long, say 20 years...yet when it changes, you don't have to worry about that cache header, the browser sees a different querystring and treats it as a different, new file.

'str' object has no attribute 'decode'. Python 3 error?

If you land here using jwt authentication after the PyJWT v2.0.0 release (22/12/2020), you might want to freeze your version of PyJWT to the previous release in your requirements.txt file.

PyJWT==1.7.1

Get latest from Git branch

If you have forked a repository fro Delete your forked copy and fork it again from master.

pycharm running way slow

It is super easy by changing the heap size as it was mentioned. Just easily by going to Pycharm HELP -> Edit custom VM option ... and change it to:

-Xms2048m
-Xmx2048m

The system cannot find the file specified. in Visual Studio

I resolved this issue after deleting folder where I was trying to add the file in Visual Studio. Deleted folder from window explorer also. After doing all this, successfully able to add folder and file.

close vs shutdown socket?

This may be platform specific, I somehow doubt it, but anyway, the best explanation I've seen is here on this msdn page where they explain about shutdown, linger options, socket closure and general connection termination sequences.

In summary, use shutdown to send a shutdown sequence at the TCP level and use close to free up the resources used by the socket data structures in your process. If you haven't issued an explicit shutdown sequence by the time you call close then one is initiated for you.

Using os.walk() to recursively traverse directories in Python

Would be the best way

def traverse_dir_recur(dir):
    import os
    l = os.listdir(dir)
    for d in l:
        if os.path.isdir(dir + d):
            traverse_dir_recur(dir+  d +"/")
        else:
            print(dir + d)

Passing arguments to require (when loading module)

Based on your comments in this answer, I do what you're trying to do like this:

module.exports = function (app, db) {
    var module = {};

    module.auth = function (req, res) {
        // This will be available 'outside'.
        // Authy stuff that can be used outside...
    };

    // Other stuff...
    module.pickle = function(cucumber, herbs, vinegar) {
        // This will be available 'outside'.
        // Pickling stuff...
    };

    function jarThemPickles(pickle, jar) {
        // This will be NOT available 'outside'.
        // Pickling stuff...

        return pickleJar;
    };

    return module;
};

I structure pretty much all my modules like that. Seems to work well for me.

sqlalchemy: how to join several tables by one query?

A good style would be to setup some relations and a primary key for permissions (actually, usually it is good style to setup integer primary keys for everything, but whatever):

class User(Base):
    __tablename__ = 'users'
    email = Column(String, primary_key=True)
    name = Column(String)

class Document(Base):
    __tablename__ = "documents"
    name = Column(String, primary_key=True)
    author_email = Column(String, ForeignKey("users.email"))
    author = relation(User, backref='documents')

class DocumentsPermissions(Base):
    __tablename__ = "documents_permissions"
    id = Column(Integer, primary_key=True)
    readAllowed = Column(Boolean)
    writeAllowed = Column(Boolean)
    document_name = Column(String, ForeignKey("documents.name"))
    document = relation(Document, backref = 'permissions')

Then do a simple query with joins:

query = session.query(User, Document, DocumentsPermissions).join(Document).join(DocumentsPermissions)

if arguments is equal to this string, define a variable like this string

You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets. The proper method is for brackets to contain spacing within, and operators to contain spacing around. In some instances different combinations work; however, the following is intended to be a universal example.

if [ "$1" == "something" ]; then     ## GOOD

if [ "$1" = "something" ]; then      ## GOOD

if [ "$1"="something" ]; then        ## BAD (operator spacing)

if ["$1" == "something"]; then       ## BAD (bracket spacing)

Also, note double brackets are handled slightly differently compared to single brackets ...

if [[ $a == z* ]]; then   # True if $a starts with a "z" (pattern matching).
if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching).

if [ $a == z* ]; then     # File globbing and word splitting take place.
if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching).

I hope that helps!

Installing Python 3 on RHEL

I was having the same issue using the python 2.7. Follow the below steps to upgrade successfully to 3.6. You can also try this one-

  1. See before upgrading version is 2.x

    python --version
    Python 2.7.5
    
  2. Use below command to upgrade your python to 3.x version-

    yum install python3x

    replace x with the version number you want.

    i.e. for installing python 3.6 execute

    yum install python36
    
  3. After that if you want to set this python for your default version then in bashrc file add

    vi ~/.bashrc

    alias python='python3.6'
    
  4. execute bash command to apply the settings

    bash 
    
  5. Now you can see the version below

    python --version
    Python 3.6.3
    

How to create dispatch queue in Swift 3

it is now simply:

let serialQueue = DispatchQueue(label: "my serial queue")

the default is serial, to get concurrent, you use the optional attributes argument .concurrent

Base64 Java encode and decode a string

Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes: java.util.Base64, java.util.Base64.Encoder and java.util.Base64.Decoder.

Example usage:

// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);

// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);

// decode a String
byte [] barr = Base64.getDecoder().decode(encoded); 

Any way to exit bash script, but not quitting the terminal

Yes; you can use return instead of exit. Its main purpose is to return from a shell function, but if you use it within a source-d script, it returns from that script.

As §4.1 "Bourne Shell Builtins" of the Bash Reference Manual puts it:

     return [n]

Cause a shell function to exit with the return value n. If n is not supplied, the return value is the exit status of the last command executed in the function. This may also be used to terminate execution of a script being executed with the . (or source) builtin, returning either n or the exit status of the last command executed within the script as the exit status of the script. Any command associated with the RETURN trap is executed before execution resumes after the function or script. The return status is non-zero if return is used outside a function and not during the execution of a script by . or source.

Eclipse will not start and I haven't changed anything

Removing workbench.xmi under workspace/.metadata/.plugins/org.eclipse.e4.workbench/ worked for me. It did not remove the existing projects.

How can I use async/await at the top level?

The actual solution to this problem is to approach it differently.

Probably your goal is some sort of initialization which typically happens at the top level of an application.

The solution is to ensure that there is only ever one single JavaScript statement at the top level of your application. If you have only one statement at the top of your application, then you are free to use async/await at every other point everwhere (subject of course to normal syntax rules)

Put another way, wrap your entire top level in a function so that it is no longer the top level and that solves the question of how to run async/await at the top level of an application - you don't.

This is what the top level of your application should look like:

import {application} from './server'

application();

CSS selector (id contains part of text)

<div id='element_123_wrapper_text'>My sample DIV</div>

The Operator ^ - Match elements that starts with given value

div[id^="element_123"] {

}

The Operator $ - Match elements that ends with given value

div[id$="wrapper_text"] {

}

The Operator * - Match elements that have an attribute containing a given value

div[id*="wrapper_text"] {

}

How to force maven update?

You can do effectively from Eclipse IDE. Of course if you are using it.

Project_Name->Maven->Update Project Configuration->Force Update of Snapshots/Releases

Calculate percentage saved between two numbers?

I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:

(1 - (oldNumber / newNumber)) * 100

So, the percentage difference from 30 to 40 is:

(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)

The percentage difference from 40 to 30 is:

(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)

In php, I use a function like this:

function calculatePercentage($oldFigure, $newFigure) {
        if (($oldFigure != 0) && ($newFigure != 0)) {
            $percentChange = (1 - $oldFigure / $newFigure) * 100;
        }
        else {
            $percentChange = null;
        }
        return $percentChange;
}

Why am I getting an OPTIONS request instead of a GET request?

It's looking like Firefox and Opera (tested on mac as well) don't like the cross domainness of this (but Safari is fine with it).

You might have to call a local server side code to curl the remote page.

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I had this error that wasn't solved by brew update && brew upgrade. For some reason I needed to install it from scratch:

$ brew install libpng

Pointer to incomplete class type is not allowed

You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:

namespace X
{
  namespace Y
  {
    class A;

    void func(A* a) { ... } // incomplete type here!
  }
}

...but, in class A was defined like this:

namespace X
{
  class A { ... };
}

Thus, A was defined as X::A, but I was using it as X::Y::A.

The fix obviously is to move the forward reference to its proper place like so:

namespace X
{
  class A;
  namespace Y
  {
    void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
  }
}

rails generate model

The code is okay but you are in the wrong directory. You must run these commands inside your rails project-directory.

The normal way to get there from scratch is:

$ rails new PROJECT_NAME
$ cd PROJECT_NAME
$ rails generate model ad \
    name:string \ 
    description:text \
    price:decimal \
    seller_id:integer \
    email:string img_url:string

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

You can browse package folder below method.

  1. Use Sublime Text 2 menu : Preferences\Browse Packages
  2. In Windows 7 : C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages (equals %appdata%\Sublime Text 2\Packages)

Changing text of UIButton programmatically swift

To set a title for a button in Xcode using swift - 04: first create a method called setTitle with parameter title and UIController state like below ;

func setTitle(_ title : String?, for state : UIControl.State)   {

}

and recall this method in your button action method like ;

yourButtonName.setTitle("String", for: .state)

How to disable Hyper-V in command line?

In an elevated Command Prompt write this :

To disable:

bcdedit /set hypervisorlaunchtype off

To enable:

bcdedit /set hypervisorlaunchtype auto 

(From comments - restart to take effect)

Detecting real time window size changes in Angular 4

This is an example of service which I use.

You can get the screen width by subscribing to screenWidth$, or via screenWidth$.value.

The same is for mediaBreakpoint$ ( or mediaBreakpoint$.value)

import {
  Injectable,
  OnDestroy,
} from '@angular/core';
import {
  Subject,
  BehaviorSubject,
  fromEvent,
} from 'rxjs';
import {
  takeUntil,
  debounceTime,
} from 'rxjs/operators';

@Injectable()
export class ResponsiveService implements OnDestroy {
  private _unsubscriber$: Subject<any> = new Subject();
  public screenWidth$: BehaviorSubject<number> = new BehaviorSubject(null);
  public mediaBreakpoint$: BehaviorSubject<string> = new BehaviorSubject(null);

  constructor() {
    this.init();
  }

  init() {
    this._setScreenWidth(window.innerWidth);
    this._setMediaBreakpoint(window.innerWidth);
    fromEvent(window, 'resize')
      .pipe(
        debounceTime(1000),
        takeUntil(this._unsubscriber$)
      ).subscribe((evt: any) => {
        this._setScreenWidth(evt.target.innerWidth);
        this._setMediaBreakpoint(evt.target.innerWidth);
      });
  }

  ngOnDestroy() {
    this._unsubscriber$.next();
    this._unsubscriber$.complete();
  }

  private _setScreenWidth(width: number): void {
    this.screenWidth$.next(width);
  }

  private _setMediaBreakpoint(width: number): void {
    if (width < 576) {
      this.mediaBreakpoint$.next('xs');
    } else if (width >= 576 && width < 768) {
      this.mediaBreakpoint$.next('sm');
    } else if (width >= 768 && width < 992) {
      this.mediaBreakpoint$.next('md');
    } else if (width >= 992 && width < 1200) {
      this.mediaBreakpoint$.next('lg');
    } else if (width >= 1200 && width < 1600) {
      this.mediaBreakpoint$.next('xl');
    } else {
      this.mediaBreakpoint$.next('xxl');
    }
  }

}

Hope this helps someone

how to implement Pagination in reactJs

Give you a pagination component, which is maybe a little difficult to understand for newbie to react:

https://www.npmjs.com/package/pagination

file_get_contents behind a proxy?

Use stream_context_set_default function. It is much easier to use as you can directly use file_get_contents or similar functions without passing any additional parameters

This blog post explains how to use it. Here is the code from that page.

<?php
// Edit the four values below
$PROXY_HOST = "proxy.example.com"; // Proxy server address
$PROXY_PORT = "1234";    // Proxy server port
$PROXY_USER = "LOGIN";    // Username
$PROXY_PASS = "PASSWORD";   // Password
// Username and Password are required only if your proxy server needs basic authentication

$auth = base64_encode("$PROXY_USER:$PROXY_PASS");
stream_context_set_default(
 array(
  'http' => array(
   'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT",
   'request_fulluri' => true,
   'header' => "Proxy-Authorization: Basic $auth"
   // Remove the 'header' option if proxy authentication is not required
  )
 )
);

$url = "http://www.pirob.com/";

print_r( get_headers($url) );

echo file_get_contents($url);
?>

Getting reference to child component in parent component

You need to leverage the @ViewChild decorator to reference the child component from the parent one by injection:

import { Component, ViewChild } from 'angular2/core';  

(...)

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <child></child>
    <button (click)="submit()">Submit</button>
  `,
  directives:[App]
})
export class AppComponent { 
  @ViewChild(Child) child:Child;

  (...)

  someOtherMethod() {
    this.searchBar.someMethod();
  }
}

Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.

You can notice that the @Query parameter decorator could also be used:

export class AppComponent { 
  constructor(@Query(Child) children:QueryList<Child>) {
    this.childcmp = children.first();
  }

  (...)
}

Check if a property exists in a class

If you are binding like I was:

<%# Container.DataItem.GetType().GetProperty("Property1") != null ? DataBinder.Eval(Container.DataItem, "Property1") : DataBinder.Eval(Container.DataItem, "Property2")  %>

What happens when a duplicate key is put into a HashMap?

Maps from JDK are not meant for storing data under duplicated keys.

  • At best new value will override the previous ones.

  • Worse scenario is exception (e.g when you try to collect it as a stream):

No duplicates:

Stream.of("one").collect(Collectors.toMap(x -> x, x -> x))

Ok. You will get: $2 ==> {one=one}

Duplicated stream:

Stream.of("one", "not one", "surely not one").collect(Collectors.toMap(x -> 1, x -> x))

Exception java.lang.IllegalStateException: Duplicate key 1 (attempted merging values one and not one) | at Collectors.duplicateKeyException (Collectors.java:133) | at Collectors.lambda$uniqKeysMapAccumulator$1 (Collectors.java:180) | at ReduceOps$3ReducingSink.accept (ReduceOps.java:169) | at Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948) | at AbstractPipeline.copyInto (AbstractPipeline.java:484) | at AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:474) | at ReduceOps$ReduceOp.evaluateSequential (ReduceOps.java:913) | at AbstractPipeline.evaluate (AbstractPipeline.java:234) | at ReferencePipeline.collect (ReferencePipeline.java:578) | at (#4:1)

To deal with duplicated keys - use other package, e.g: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html

There is a lot of other implementations dealing with duplicated keys. Those are needed for web (e.g. duplicated cookie keys, Http headers can have same fields, ...)

Good luck! :)

Convert generic List/Enumerable to DataTable?

This is a simple mix of the solutions. It work with Nullable types.

public static DataTable ToDataTable<T>(this IList<T> list)
{
  PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
  DataTable table = new DataTable();
  for (int i = 0; i < props.Count; i++)
  {
    PropertyDescriptor prop = props[i];
    table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
  }
  object[] values = new object[props.Count];
  foreach (T item in list)
  {
    for (int i = 0; i < values.Length; i++)
      values[i] = props[i].GetValue(item) ?? DBNull.Value;
    table.Rows.Add(values);
  }
  return table;
}

Pipe subprocess standard output to a variable

If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output() command. Here is an example:

output = subprocess.check_output('ls')

To also redirect stderr you can use the following:

output = subprocess.check_output('ls', stderr=subprocess.STDOUT)



In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.

output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)

JavaFX open new window

If you just want a button to open up a new window, then something like this works:

btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent event) {
        Parent root;
        try {
            root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
            Stage stage = new Stage();
            stage.setTitle("My New Stage Title");
            stage.setScene(new Scene(root, 450, 450));
            stage.show();
            // Hide this current window (if this is what you want)
            ((Node)(event.getSource())).getScene().getWindow().hide();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Lowercase and Uppercase with jQuery

Try this:

var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();

Possible duplicate with: How do I use jQuery to ignore case when selecting

PHP include relative path

You could always include it using __DIR__:

include(dirname(__DIR__).'/config.php');

__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.

include(ROOT_PATH.'config.php');

Should then work to include the config file from where you want.

How to configure encoding in Maven?

If you combine the answers above, finally a pom.xml that configured for UTF-8 should seem like that.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>YOUR_COMPANY</groupId>
    <artifactId>YOUR_APP</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <project.java.version>1.8</project.java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <!-- Your dependencies -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${project.java.version}</source>
                    <target>${project.java.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Question mark characters displaying within text, why is this?

Your browser hasn't interpretted the encoding of the page correctly (either because you've forced it to a particular setting, or the page is set incorrectly), and thus cannot display some of the characters.

How can one change the timestamp of an old commit in Git?

To change both the author date and the commit date:

GIT_COMMITTER_DATE="Wed Sep 23 9:40 2015 +0200" git commit --amend --date "Wed Sep 23 9:40 2015 +0200"

How to install JQ on Mac by command-line?

For most it is a breeze, however like you I had a difficult time installing jq

The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/

However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system

What worked for me was removing all previous installs then pip install jq

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

Have a div cling to top of screen if scrolled down past it

The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.

Derived from the code viixii.com uses I ended up using this:

function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top)
        $('#sticky-element').addClass('sticky');
    else
        $('#sticky-element').removeClass('sticky');
}

$(function() {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.

Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.

Just place an empty div with a class acting like an anchor just above the element you want to have fixed.

Like so:

<div id="sticky-anchor"></div>
<div id="sticky-element">Your sticky content</div>

All credit for the code goes to viixii.com

Check if my SSL Certificate is SHA1 or SHA2

openssl s_client -connect api.cscglobal.com:443 < /dev/null 2>/dev/null  | openssl x509 -text -in /dev/stdin | grep "Signature Algorithm" | cut -d ":" -f2 | uniq | sed '/^$/d' | sed -e 's/^[ \t]*//'

remove / reset inherited css from an element

You could try overwriting the CSS and use auto

I don't think this will work with color specifically, but I ran into an issue where i had a parent property such as

.parent {
   left: 0px;
}

and then I was able to just define my child with something like

.child {
   left: auto;
}

and it effectively "reset" the property.

How to store Java Date to Mysql datetime with JPA

it works for me !!

in mysql table

DATETIME

in entity:

private Date startDate;

in process:

objectEntity.setStartDate(new Date());

in preparedStatement:

pstm.setDate(9, new java.sql.Date(objEntity.getStartDate().getTime()));

Remove blank attributes from an Object in Javascript

If someone needs to remove undefined values from an object with deep search using lodash then here is the code that I'm using. It's quite simple to modify it to remove all empty values (null/undefined).

function omitUndefinedDeep(obj) {
  return _.reduce(obj, function(result, value, key) {
    if (_.isObject(value)) {
      result[key] = omitUndefinedDeep(value);
    }
    else if (!_.isUndefined(value)) {
      result[key] = value;
    }
    return result;
  }, {});
}

How to get the Parent's parent directory in Powershell?

You can split it at the backslashes, and take the next-to-last one with negative array indexing to get just the grandparent directory name.

($scriptpath -split '\\')[-2]

You have to double the backslash to escape it in the regex.

To get the entire path:

($path -split '\\')[0..(($path -split '\\').count -2)] -join '\'

And, looking at the parameters for split-path, it takes the path as pipeline input, so:

$rootpath = $scriptpath | split-path -parent | split-path -parent

Regex Until But Not Including

The explicit way of saying "search until X but not including X" is:

(?:(?!X).)*

where X can be any regular expression.

In your case, though, this might be overkill - here the easiest way would be

[^z]*

This will match anything except z and therefore stop right before the next z.

So .*?quick[^z]* will match The quick fox jumps over the la.

However, as soon as you have more than one simple letter to look out for, (?:(?!X).)* comes into play, for example

(?:(?!lazy).)* - match anything until the start of the word lazy.

This is using a lookahead assertion, more specifically a negative lookahead.

.*?quick(?:(?!lazy).)* will match The quick fox jumps over the.

Explanation:

(?:        # Match the following but do not capture it:
 (?!lazy)  # (first assert that it's not possible to match "lazy" here
 .         # then match any character
)*         # end of group, zero or more repetitions.

Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b will only match the complete word fox but not the fox in foxy.

Note

If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s) to the regex, but that doesn't work in all regex engines (notably JavaScript).

Alternative solution:

In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ? to the * quantifier, it will try to match as few characters as possible from the current position:

.*?(?=(?:X)|$)

will match any number of characters, stopping right before X (which can be any regex) or the end of the string (if X doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X in order to reliably isolate it from the alternation)

How to import a JSON file in ECMAScript 6?

Simply do this:

import * as importedConfig from '../config.json';

Then use it like the following:

const config = importedConfig.default;

How to use setInterval and clearInterval?

I used angular with electron,

In my case, setInterval returns a Nodejs Timer object. which when I called clearInterval(timerobject) it did not work.

I had to get the id first and call to clearInterval

clearInterval(timerobject._id)

I have struggled many hours with this. hope this helps.

Content Type text/xml; charset=utf-8 was not supported by service

I saw this problem today when trying to create a WCF service proxy, both using VS2010 and svcutil.

Everything I'm doing is with basicHttpBinding (so no issue with wsHttpBinding).

For the first time in my recollection MSDN actually provided me with the solution, at the following link How to: Publish Metadata for a Service Using a Configuration File. The line I needed to change was inside the behavior element inside the MEX service behavior element inside my service app.config file. I changed it from

&lt;serviceMetadata httpGetEnabled="true"/>  
to  
&lt;serviceMetadata httpGetEnabled="true" policyVersion="Policy15"/>

and like magic the error went away and I was able to create the service proxy. Note that there is a corresponding MSDN entry for using code instead of a config file: How to: Publish Metadata for a Service Using Code.

(Of course, Policy15 - how could I possibly have overlooked that???)

One more "gotcha": my service needs to expose 3 different endpoints, each supporting a different contract. For each proxy that I needed to build, I had to comment out the other 2 endpoints, otherwise svcutil would complain that it could not resolve the base URL address.

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

Read specific columns with pandas or other python module

Above answers are in python2. So for python 3 users I am giving this answer. You can use the bellow code:

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
print(df.star_name)

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

UICollectionView - dynamic cell height?

Swift 4 answer based on helpful answer from @mbm29414.

Unfortunately, it requires the use of a XIB file. There doesn't appear to be an alternative.

The key parts are using a sizing cell (created only once) and registering the XIB when initializing the collection view.

Then you size each cell dynamically within the sizeForItemAt function.

// UICollectionView Vars and Constants
let CellXIBName = YouViewCell.XIBName
let CellReuseID = YouViewCell.ReuseID
var sizingCell = YouViewCell()


fileprivate func initCollectionView() {
    // Connect to view controller
    collectionView.dataSource = self
    collectionView.delegate = self

    // Register XIB
    collectionView.register(UINib(nibName: CellXIBName, bundle: nil), forCellWithReuseIdentifier: CellReuseID)

    // Create sizing cell for dynamically sizing cells
    sizingCell = Bundle.main.loadNibNamed(CellXIBName, owner: self, options: nil)?.first as! YourViewCell

    // Set scroll direction
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical
    collectionView.collectionViewLayout = layout

    // Set properties
    collectionView.alwaysBounceVertical = true
    collectionView.alwaysBounceHorizontal = false

    // Set top/bottom padding
    collectionView.contentInset = UIEdgeInsets(top: collectionViewTopPadding, left: collectionViewSidePadding, bottom: collectionViewBottomPadding, right: collectionViewSidePadding)

    // Hide scrollers
    collectionView.showsVerticalScrollIndicator = false
    collectionView.showsHorizontalScrollIndicator = false
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // Get cell data and render post
    let data = YourData[indexPath.row]
    sizingCell.renderCell(data: data)

    // Get cell size
    sizingCell.setNeedsLayout()
    sizingCell.layoutIfNeeded()
    let cellSize = sizingCell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)

    // Return cell size
    return cellSize
}

Leap year calculation

The length of a year is (more or less) 365.242196 days. So we have to subtract, more or less, a quarter of a day to make it fit :

365.242196 - 0.25 = 364.992196 (by adding 1 day in 4 years) : but oops, now it's too small!! lets add a hundreth of a day (by not adding that day once in a hundred year :-))

364.992196 + 0,01 = 365.002196 (oops, a bit too big, let's add that day anyway one time in about 400 years)

365.002196 - 1/400 = 364.999696

Almost there now, just play with leapseconds now and then, and you're set.

(Note : the reason no more corrections are applied after this step is because a year also CHANGES IN LENGTH!!, that's why leapseconds are the most flexible solution, see for examlple here)

That's why i guess

Regex doesn't work in String.matches()

[a-z] matches a single char between a and z. So, if your string was just "d", for example, then it would have matched and been printed out.

You need to change your regex to [a-z]+ to match one or more chars.

How to test if a double is an integer

Guava: DoubleMath.isMathematicalInteger. (Disclosure: I wrote it.) Or, if you aren't already importing Guava, x == Math.rint(x) is the fastest way to do it; rint is measurably faster than floor or ceil.

Renaming files in a folder to sequential numbers

Try to use a loop, let, and printf for the padding:

a=1
for i in *.jpg; do
  new=$(printf "%04d.jpg" "$a") #04 pad to length of 4
  mv -i -- "$i" "$new"
  let a=a+1
done

using the -i flag prevents automatically overwriting existing files.

How to permanently set $PATH on Linux/Unix?

You can add that line to your console config file (e.g. .bashrc) , or to .profile

How can I read and parse CSV files in C++?

If you don't want to deal with including boost in your project (it is considerably large if all you are going to use it for is CSV parsing...)

I have had luck with the CSV parsing here:

http://www.zedwood.com/article/112/cpp-csv-parser

It handles quoted fields - but does not handle inline \n characters (which is probably fine for most uses).

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

The configuration here is working for me:

configurations {
    customProvidedRuntime
}

dependencies {
    compile(
        // Spring Boot dependencies
    )

    customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}

war {
    classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}

springBoot {
    providedConfiguration = "customProvidedRuntime"
}