Programs & Examples On #Setw

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

Having trouble setting working directory

Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

For me, I changed class='carousel-item' to class='item' like this

<div class="item">
    <img class="img-responsive" src="..." alt="...">
</div>

Bootstrap collapse animation not smooth

In case anybody else comes across this problem, as I just have, the answer is to wrap the content which you want to collapse inside a div and collapse the wrapper div rather than the content itself.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="form-group">_x000D_
    <a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne" class="btn btn-primary">+ addInfo</a>_x000D_
    <div id="collapseOne" class="collapse">_x000D_
        <textarea class="form-control" rows="4"></textarea>_x000D_
    </div>_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
    <a for="collapseTwo" data-toggle="collapse" href="#collapseTwo" aria-expanded="true" aria-controls="collapseOne" class="btn btn-info">+ subtitle</a>_x000D_
    <input type="text" class="form-control collapse" id="collapseTwo">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Unable to add window -- token null is not valid; is your activity running?

I had the same problem as you, it looks like you used the tutorial from http://www.piwai.info/chatheads-basics like I did. The problem is that you cannot reliably pass the current activity to the popup window, because you have no control over the current activity. It looks like there might be a unreliable way to get the current activity, but I don't recommend that.

The way I fixed it for my app was to not use the popup window, but instead make my own through the window manager.

private void showCustomPopupMenu()
    {
                windowManager2 = (WindowManager)getSystemService(WINDOW_SERVICE);
                LayoutInflater layoutInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View view=layoutInflater.inflate(R.layout.xxact_copy_popupmenu, null);
                params=new WindowManager.LayoutParams(
                        WindowManager.LayoutParams.WRAP_CONTENT,
                        WindowManager.LayoutParams.WRAP_CONTENT,
                        WindowManager.LayoutParams.TYPE_PHONE,
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                        PixelFormat.TRANSLUCENT);

                params.gravity=Gravity.CENTER|Gravity.CENTER;
                params.x=0;
                params.y=0;
                windowManager2.addView(view, params);  
    }

If you want this to look like a popup window, just add a transparent gray view as the background and add a onClickListener to it to remove the view from the windowManager object.

I know this isn't as convenient as a popup, but from my experience, it is the most reliable way.

and don't forget to add permission in your manifest file

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

What is offsetHeight, clientHeight, scrollHeight?

My descriptions for the three:

  • offsetHeight: How much of the parent's "relative positioning" space is taken up by the element. (ie. it ignores the element's position: absolute descendents)
  • clientHeight: Same as offset-height, except it excludes the element's own border, margin, and the height of its horizontal scroll-bar (if it has one).
  • scrollHeight: How much space is needed to see all of the element's content/descendents (including position: absolute ones) without scrolling.

Then there is also:

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

My personal cheatsheet, covering:

DOM element dimensions

  • .offsetWidth/.offsetHeight
  • .clientWidth/.clientHeight
  • .scrollWidth/.scrollHeight
  • .scrollLeft/.scrollTop
  • .getBoundingClientRect()

with small/simple/not-all-in-one diagrams :)


see full-size: https://docs.google.com/drawings/d/1bOOJnkN5G_lBs3Oz9NfQQH1I0aCrX5EZYPY3mu3_ROI/edit?usp=sharing

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'}); only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)

It could just be something that runs once the first time you initialize collapse with those parameters.

You will have more luck using the show and hide methods.

Here is an example:

$(function() {

  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('.collapse-init').on('click', function() {
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      $('.panel-collapse').collapse('show');
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
  });

});

http://bootply.com/98201

Update

Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.

I don't understand what's going on or why the show seemed to be toggling in some places.

But After messing around for a while.. Finally came with the following solution:

$(function() {
  var transition = false;
  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('#accordion').on('show.bs.collapse',function(){
    if($active){
        $('#accordion .in').collapse('hide');
    }
  });

  $('#accordion').on('hidden.bs.collapse',function(){
    if(transition){
        transition = false;
        $('.panel-collapse').collapse('show');
    }
  });

  $('.collapse-init').on('click', function() {
    $('.collapse-init').prop('disabled','true');
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      if($('.panel-collapse.in').length){
        transition = true;
        $('.panel-collapse.in').collapse('hide');       
      }
      else{
        $('.panel-collapse').collapse('show');
      }
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
    setTimeout(function(){
        $('.collapse-init').prop('disabled','');
    },800);
  });
});

http://bootply.com/98239

How to use BeanUtils.copyProperties?

There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.

One is

org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)

Another is

org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)

Pay attention to the opposite position of parameters.

Identifier is undefined

You may also be missing using namespace std;

Can not deserialize instance of java.lang.String out of START_OBJECT token

This way I solved my problem. Hope it helps others. In my case I created a class, a field, their getter & setter and then provide the object instead of string.

Use this

public static class EncryptedData {
    private String encryptedData;

    public String getEncryptedData() {
        return encryptedData;
    }

    public void setEncryptedData(String encryptedData) {
        this.encryptedData = encryptedData;
    }
}

@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
    try {
        Path path = Paths.get(PUBLIC_KEY);
        byte[] bytes = Files.readAllBytes(path);
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
        PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);

        Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
        cipher.init(Cipher.PRIVATE_KEY, privateKey);
        String decryptedData = new String(cipher.doFinal(encryptedData.getEncryptedData().getBytes()));
        String[] dataArray = decryptedData.split("|");


        Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
        updateIp.invoke(null, dataArray[0], dataArray[1]);

    } catch (Exception e) {
        LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
    }

    return null;

Instead of this

@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
    try {
        Path path = Paths.get(PUBLIC_KEY);
        byte[] bytes = Files.readAllBytes(path);
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
        PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);

        Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
        cipher.init(Cipher.PRIVATE_KEY, privateKey);
        String decryptedData = new String(cipher.doFinal(encryptedData.getBytes()));
        String[] dataArray = decryptedData.split("|");


        Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
        updateIp.invoke(null, dataArray[0], dataArray[1]);

    } catch (Exception e) {
        LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
    }

    return null;
}

Add Header and Footer for PDF using iTextsharp

The answers to this question, while they are correct, are very unnecessarily complicated. It doesn't take that much code for text to show up in the header/footer. Here is a simple example of adding text to the header/footer.

The current version of iTextSharp works by implementing a callback class which is defined by the IPdfPageEvent interface. From what I understand, it's not a good idea to add things during the OnStartPage method, so instead I will be using the OnEndPage page method. The events are triggered depending on what is happening to the PdfWriter

First, create a class which implements IPdfPageEvent. In the:

public void OnEndPage(PdfWriter writer, Document document)

function, obtain the PdfContentByte object by calling

PdfContentByte cb = writer.DirectContent;

Now you can add text very easily:

ColumnText ct = new ColumnText(cb);

cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
//Note, (0,0) in this case is at the bottom of the document
cb.SetTextMatrix(document.LeftMargin, document.BottomMargin); 
cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
cb.EndText();

So the full for the OnEndPage function will be:

public void OnEndPage(PdfWriter writer, Document document)
{
    PdfContentByte cb = writer.DirectContent;
    ColumnText ct = new ColumnText(cb);

    cb.BeginText();
    cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
    cb.SetTextMatrix(document.LeftMargin, document.BottomMargin);
    cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
    cb.EndText();

}

This will show up at the bottom of your document. One last thing. Don't forget to assign the IPdfPageEvent like this:

writter.PageEvent = new PDFEvents();

To the PdfWriter writter object

For the header it is very similar. Just flip the SetTextMatrix y coordinate:

cb.SetTextMatrix(document.LeftMargin, document.PageSize.Height - document.TopMargin);

how to get bounding box for div element in jquery

As this is specifically tagged for jQuery -

$("#myElement")[0].getBoundingClientRect();

or

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

Why I get 411 Length required error?

When you're using HttpWebRequest and POST method, you have to set a content (or a body if you prefer) via the RequestStream. But, according to your code, using authRequest.Method = "GET" should be enough.

In case you're wondering about POST format, here's what you have to do :

ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(serializedObject); // a json object, or xml, whatever...

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
request.Expect = "application/json";

request.GetRequestStream().Write(data, 0, data.Length);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Get width/height of SVG element

SVG has properties width and height. They return an object SVGAnimatedLength with two properties: animVal and baseVal. This interface is used for animation, where baseVal is the value before animation. From what I can see, this method returns consistent values in both Chrome and Firefox, so I think it can also be used to get calculated size of SVG.

How can I wait for 10 second without locking application UI in android

You never want to call thread.sleep() on the UI thread as it sounds like you have figured out. This freezes the UI and is always a bad thing to do. You can use a separate Thread and postDelayed

This SO answer shows how to do that as well as several other options

Handler

TimerTask

You can look at these and see which will work best for your particular situation

Embed Youtube video inside an Android app

The video quality depends upon the Connection speed using API

alternatively for other than API means without YouTube app you can follow this link

Android WebView not loading URL

Note : Make sure internet permission is given.

In android 9.0,

Webview or Imageloader can not load url or image because android 9 have network security issue which need to be enable by manifest file for all sub domain. so either you can add security config file.

  1. Add @xml/network_security_config into your resources:

_x000D_
_x000D_
<network-security-config>_x000D_
    <domain-config cleartextTrafficPermitted="true">_x000D_
    <domain includeSubdomains="true">www.google.com</domain>_x000D_
    </domain-config>_x000D_
</network-security-config>
_x000D_
_x000D_
_x000D_

  1. Add this security config to your Manifest like this:

_x000D_
_x000D_
<application_x000D_
   _x000D_
    android:networkSecurityConfig="@xml/network_security_config"_x000D_
    ...>_x000D_
</application>
_x000D_
_x000D_
_x000D_

if you want to allow all sub domain

_x000D_
_x000D_
<application_x000D_
   android:usesCleartextTraffic="true"_x000D_
    ...>_x000D_
</application>
_x000D_
_x000D_
_x000D_

Note: To solve the problem, don't use both of point 2 (android:networkSecurityConfig="@xml/network_security_config" and android:usesCleartextTraffic="true") choose one of them

C++ calling base class constructors

In c++, compiler always ensure that functions in object hierarchy are called successfully. These functions are constructors and destructors and object hierarchy means inheritance tree.

According to this rule we can guess compiler will call constructors and destructors for each object in inheritance hierarchy even if we don't implement it. To perform this operation compiler will synthesize the undefined constructors and destructors for us and we name them as a default constructors and destructors.Then, compiler will call default constructor of base class and then calls constructor of derived class.

In your case you don't call base class constructor but compiler does that for you by calling default constructor of base class because if compiler didn't do it your derived class which is Rectangle in your example will not be complete and it might cause disaster because maybe you will use some member function of base class in your derived class. So for the sake of safety compiler always need all constructor calls.

How to find the minimum value of a column in R?

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

google uses id="map_canvas" and id="map-canvas" in the samples, double-check and re-double-check the id :D

Why can't I define my workbook as an object?

It's actually a sensible question. Here's the answer from Excel 2010 help:

"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."

So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:

Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")

Very Simple, Very Smooth, JavaScript Marquee

I've made very simple function for marquee. See: http://jsfiddle.net/vivekw/pHNpk/2/ It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.

function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;

function scroll() {
    if (b.position().left <= -width) {
        b.css('left', start_pos);
        scroll();
    }
    else {
        time = (parseInt(b.position().left, 10) - end_pos) *
            (10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
        b.animate({
            'left': -width
        }, time, 'linear', function() {
            scroll();
        });
    }
}

b.css({
    'width': width,
    'left': start_pos
});
scroll(a, b);
b.mouseenter(function() {     // Remove these lines
    b.stop();                 //
    b.clearQueue();           // if you don't want
});                           //
b.mouseleave(function() {     // marquee to pause
    scroll(a, b);             //
});                           // on mouse over
}

$(document).ready(function() {
    marquee($('#display'), $('#text'));  //Enter name of container element & marquee element
});

How to convert image into byte array and byte array to base64 String in android?

Try this:

// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg), 
                       Base64.NO_WRAP);

Jetty: HTTP ERROR: 503/ Service Unavailable

None of these answers worked for me.

I had to remove all deployed java web app:

  • Windows/Show View/Other...
  • Go the the Server folder and select "Servers"
  • Right-click on the J2EE Preview at localhost
  • Click to Add and Remove... Click Remove all

Then run the project on the server

The Error is gone!

You will have to stop the server before deploying another project because it will not be found by the server. Otherwise you will get a 404 error

How to fix C++ error: expected unqualified-id

There should be no semicolon here:

class WordGame;

...but there should be one at the end of your class definition:

...
private:
    string theWord;
}; // <-- Semicolon should be at the end of your class definition

Download file inside WebView

webView.setDownloadListener(new DownloadListener()
        {
            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimeType,
                                        long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));
                request.setMimeType(mimeType);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading File...");
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(
                        Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
                                url, contentDisposition, mimeType));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
            }});

How to turn off Wifi via ADB?

Using "svc" through ADB (rooted required):

Enable:

adb shell su -c 'svc wifi enable'

Disable:

adb shell su -c 'svc wifi disable'

Using Key Events through ADB:

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell input keyevent 20 & adb shell input keyevent 23

The first line launch "wifi.WifiSettings" activity which open the WiFi Settings page. The second line simulate key presses.

I tested those two lines on a Droid X. But Key Events above probably need to edit in other devices because of different Settings layout.

More info about "keyevents" here.

How to pass html string to webview on android

i have successfully done by below line

 //data == html data which you want to load
 String data = "Your data which you want to load";

 WebView webview = (WebView)this.findViewById(R.id.webview);
 webview.getSettings().setJavaScriptEnabled(true);
 webview.loadData(data, "text/html; charset=utf-8", "UTF-8");

Or You can try

 webview.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

Use:

YourActivityName.this

Instead of:

getApplicationContext();

Format output string, right alignment

I really enjoy a new literal string interpolation in Python 3.6+:

line_new = f'{word[0]:>12}  {word[1]:>12}  {word[2]:>12}'

Reference: PEP 498 -- Literal String Interpolation

Android: how to draw a border to a LinearLayout

Extend LinearLayout/RelativeLayout and use it straight on the XML

package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        /*
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        fillPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(fillPaint) ;
        */

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(2);  
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;
    }

}

<?xml version="1.0" encoding="utf-8"?>

<com.pkg_name.LinearLayoutOutlined
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width=...
    android:layout_height=...
   >
   ... your widgets here ...

</com.pkg_name.LinearLayoutOutlined>

how to get html content from a webview?

I would suggest instead of trying to extract the HTML from the WebView, you extract the HTML from the URL. By this, I mean using a third party library such as JSoup to traverse the HTML for you. The following code will get the HTML from a specific URL for you

public static String getHtml(String url) throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";

        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                response.getEntity().getContent()
            )
        );

        String line = null;
        while ((line = reader.readLine()) != null){
            result += line + "\n";
        }
        return result;
    }

Attributes / member variables in interfaces?

Fields in interfaces are implicitly public static final. (Also methods are implicitly public, so you can drop the public keyword.) Even if you use an abstract class instead of an interface, I strongly suggest making all non-constant (public static final of a primitive or immutable object reference) private. More generally "prefer composition to inheritance" - a Tile is-not-a Rectangle (of course, you can play word games with "is-a" and "has-a").

How to switch activity without animation in Android?

This is not an example use or an explanation of how to use FLAG_ACTIVITY_NO_ANIMATION, however it does answer how to disable the Activity switching animation, as asked in the question title:

Android, how to disable the 'wipe' effect when starting a new activity?

android:layout_height 50% of the screen size

This kind of worked for me. Though FAB doesn't float independently, but now it isn't getting pushed down.

Observe the weights given inside the LinearLayout

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/andsanddkasd">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/sharedResourcesRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="4"
                />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_gravity="bottom|right"
                android:src="@android:drawable/ic_input_add"
                android:layout_weight="1"/>

        </LinearLayout>

Hope this helps :)

Setting width of spreadsheet cell using PHPExcel

Tha is because getColumnDimensionByColumn receives the column index (an integer starting from 0), not a string.

The same goes for setCellValueByColumnAndRow

Split code over multiple lines in an R script

Dirk's method above will absolutely work, but if you're looking for a way to bring in a long string where whitespace/structure is important to preserve (example: a SQL query using RODBC) there is a two step solution.

1) Bring the text string in across multiple lines

long_string <- "this
is 
a 
long
string
with
whitespace"

2) R will introduce a bunch of \n characters. Strip those out with strwrap(), which destroys whitespace, per the documentation:

strwrap(long_string, width=10000, simplify=TRUE)

By telling strwrap to wrap your text to a very, very long row, you get a single character vector with no whitespace/newline characters.

Android: How to set password property in an edit text?

You need to use PasswordTransformationMethod.getInstance() instead of new PasswordTransformationMethod().

How to go back to previous page if back button is pressed in WebView?

Why not use onBackPressed()?

@Override
public void onBackPressed()
{
    // super.onBackPressed(); Do not call me!

    // Go to the previous web page.
}

Android webview & localStorage

If your app use multiple webview you will still have troubles : localStorage is not correctly shared accross all webviews.

If you want to share the same data in multiple webviews the only way is to repair it with a java database and a javascript interface.

This page on github shows how to do this.

hope this help!

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

In my WCF serive project this issue is due to Reference of System.Web.Mvc.dll 's different version. So it may be compatibility issue of DLL's different version

When I use

System.Web.Mvc.dll version 5.2.2.0 -> it thorows the Error The content type text/html; charset=utf-8 of the response message

but when I use System.Web.Mvc.dll version 4.0.0.0 or lower -> it works fine.

I don't know the reason of different version DLL's issue but by changing the DLL's verison it works for me.

This Error even generate when you add reference of other Project in your WCF Project and this reference project has different version of System.Web.Mvc DLL or could be any other DLL.

Imported a csv-dataset to R but the values becomes factors

None of these answers mention the colClasses argument which is another way to specify the variable classes in read.csv.

 stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "numeric") # all variables to numeric

or you can specify which columns to convert:

stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = c("PTS" = "numeric", "MP" = "numeric") # specific columns to numeric

Note that if a variable can't be converted to numeric then it will be converted to factor as default which makes it more difficult to convert to number. Therefore, it can be advisable just to read all variables in as 'character' colClasses = "character" and then convert the specific columns to numeric once the csv is read in:

stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "character")
point <- as.numeric(stuckey$PTS)
time <- as.numeric(stuckey$MP)

CSS position:fixed inside a positioned element

Seems, css transforms can be used

"‘transform’ property establishes a new local coordinate system at the element",

but ... this is not cross-browser, seems only Opera works correctly

Animate a custom Dialog

First, you have to create two animation resources in res/anim dir

slide_up.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="@android:integer/config_mediumAnimTime"
    android:fromYDelta="100%"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toXDelta="0">
</translate>
</set>

slide_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate 
    android:duration="@android:integer/config_mediumAnimTime" 
    android:fromYDelta="0%p" 
    android:interpolator="@android:anim/accelerate_interpolator" 
    android:toYDelta="100%p">
</translate>
</set>

then you have to create a style

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_bottom</item>
</style>

and add this line to your class

dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id

Based in http://www.devexchanges.info/2015/10/showing-dialog-with-animation-in-android.html

Add a Progress Bar in WebView

Here is the code that I am using:

Inside WebViewClient:

               @Override
             public void onPageStarted(WebView view, String url, Bitmap favicon) {

              super.onPageStarted(view, url, favicon);
              findViewById(R.id.progress1).setVisibility(View.VISIBLE);
             }

            @Override
            public void onPageFinished(WebView view, String url) {
                findViewById(R.id.progress1).setVisibility(View.GONE);
            }

Here is the XML :

<ProgressBar
    android:id="@+id/progress1"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Hope this helps..

Check existence of directory and create if doesn't exist

I know this question was asked a while ago, but in case useful, the here package is really helpful for not having to reference specific file paths and making code more portable. It will automatically define your working directory as the one that your .Rproj file resides in, so the following will often suffice without having to define the file path to your working directory:

library(here)

if (!dir.exists(here(outputDir))) {dir.create(here(outputDir))}

How to retrieve the dimensions of a view?

ViewTreeObserver and onWindowFocusChanged() are not so necessary at all.

If you inflate the TextView as layout and/or put some content in it and set LayoutParams then you can use getMeasuredHeight() and getMeasuredWidth().

BUT you have to be careful with LinearLayouts (maybe also other ViewGroups). The issue there is, that you can get the width and height after onWindowFocusChanged() but if you try to add some views in it, then you can't get that information until everything have been drawn. I was trying to add multiple TextViews to LinearLayouts to mimic a FlowLayout (wrapping style) and so couldn't use Listeners. Once the process is started, it should continue synchronously. So in such case, you might want to keep the width in a variable to use it later, as during adding views to layout, you might need it.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

FYI, another way this exception can occur is if:

  • Your transaction isolation is READ_COMMITTED
  • Transaction #1 queries for an entity, then deletes that entity
  • A simultaneous transaction #2 does the same thing

Then this can happen: TX #1 successfully commits before TX #2, then when TX #2 tries to delete the entity (again) it's not there any more - even though it was found by a query earlier in that same transaction. Note this anomaly is allowed with READ_COMMITTED isolation.

In my case the resulting exception looked like this:

HHH000315: Exception executing batch [org.hibernate.StaleStateException:
  Batch update returned unexpected row count from update [0]; actual row
  count: 0; expected: 1; statement executed: delete from Foobar where id=?],
  SQL: delete from Foobar where id=?

Is "delete this" allowed in C++?

Well, in Component Object Model (COM) delete this construction can be a part of Release method that is called whenever you want to release aquisited object:

void IMyInterface::Release()
{
    --instanceCount;
    if(instanceCount == 0)
        delete this;
}

How to get text in QlineEdit when QpushButton is pressed in a string?

Acepted solution implemented in PyQt5

import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect")
        self.pb.clicked.connect(self.button_click)

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)
        self.setLayout(layout)

        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print (shost)


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

What's the difference between setWebViewClient vs. setWebChromeClient?

From the source code:

// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;

// SOME OTHER SUTFFF.......

/**
 * Set the WebViewClient.
 * @param client An implementation of WebViewClient.
 */
public void setWebViewClient(WebViewClient client) {
    mWebViewClient = client;
}

/**
 * Set the WebChromeClient.
 * @param client An implementation of WebChromeClient.
 */
public void setWebChromeClient(WebChromeClient client) {
    mWebChromeClient = client;
}

Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress. Take a look of this example: Adding alert() support to a WebView

At first glance, there are too many differences WebViewClient & WebChromeClient. But, basically: if you are developing a WebView that won't require too many features but rendering HTML, you can just use a WebViewClient. On the other hand, if you want to (for instance) load the favicon of the page you are rendering, you should use a WebChromeClient object and override the onReceivedIcon(WebView view, Bitmap icon).

Most of the times, if you don't want to worry about those things... you can just do this:

webView= (WebView) findViewById(R.id.webview); 
webView.setWebChromeClient(new WebChromeClient()); 
webView.setWebViewClient(new WebViewClient()); 
webView.getSettings().setJavaScriptEnabled(true); 
webView.loadUrl(url); 

And your WebView will (in theory) have all features implemented (as the android native browser).

Android Webview - Completely Clear the Cache

I found the fix you were looking for:

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");

For some reason Android makes a bad cache of the url which it keeps returning by accident instead of the new data you need. Sure, you could just delete the entries from the DB but in my case I am only trying to access one URL so blowing away the whole DB is easier.

And don't worry, these DBs are just associated with your app so you aren't clearing the cache of the whole phone.

Why doesn't "System.out.println" work in Android?

Of course, to see the result in logcat, you should set the Log level at least to "Info" (Log level in logcat); otherwise, as it happened to me, you won't see your output.

IOException: Too many open files

As you are running on Linux I suspect you are running out of file descriptors. Check out ulimit. Here is an article that describes the problem: http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/

Android WebView Cookie Problem

Solution:Webview CookieSyncManager

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://xx.example.com","mid="+MySession.GetSession().sessionId+" ; Domain=.example.com");
cookieSyncManager.sync();

String cookie = cookieManager.getCookie("http://xx.example.com");

Log.d(LOGTAG, "cookie ------>"+cookie);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TuWebViewClient());
mWebView.loadUrl("http://xx.example.com");

How to get browser width using JavaScript code?

An important addition to Travis' answer; you need to put the getWidth() up in your document body to make sure that the scrollbar width is counted, else scrollbar width of the browser subtracted from getWidth(). What i did ;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
</body>

and call aWidth variable anywhere afterwards.

The best way to remove duplicate values from NSMutableArray in Objective-C?

just use this simple code :

NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];

since nsset doesn't allow duplicate values and all objects returns an array

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

How do I programmatically change file permissions?

simple java code  for change file permission in java  

   String path="D:\\file\\read.txt";
        File file=new File(path);
        if (file.exists()) {
            System.out.println("read="+file.canRead());
            System.out.println("write="+file.canWrite());
            System.out.println("Execute="+file.canExecute());
            file.setReadOnly();
        }     

Reference : how to change file permission in java

Bring a window to the front in WPF

I have had a similar problem with a WPF application that gets invoked from an Access application via the Shell object.

My solution is below - works in XP and Win7 x64 with app compiled to x86 target.

I'd much rather do this than simulate an alt-tab.

void Window_Loaded(object sender, RoutedEventArgs e)
{
    // make sure the window is normal or maximised
    // this was the core of the problem for me;
    // even though the default was "Normal", starting it via shell minimised it
    this.WindowState = WindowState.Normal;

    // only required for some scenarios
    this.Activate();
}

Use of Finalize/Dispose method in C#

Note that any IDisposable implementation should follow the below pattern (IMHO). I developed this pattern based on info from several excellent .NET "gods" the .NET Framework Design Guidelines (note that MSDN does not follow this for some reason!). The .NET Framework Design Guidelines were written by Krzysztof Cwalina (CLR Architect at the time) and Brad Abrams (I believe the CLR Program Manager at the time) and Bill Wagner ([Effective C#] and [More Effective C#] (just take a look for these on Amazon.com:

Note that you should NEVER implement a Finalizer unless your class directly contains (not inherits) UNmanaged resources. Once you implement a Finalizer in a class, even if it is never called, it is guaranteed to live for an extra collection. It is automatically placed on the Finalization Queue (which runs on a single thread). Also, one very important note...all code executed within a Finalizer (should you need to implement one) MUST be thread-safe AND exception-safe! BAD things will happen otherwise...(i.e. undetermined behavior and in the case of an exception, a fatal unrecoverable application crash).

The pattern I've put together (and written a code snippet for) follows:

#region IDisposable implementation

//TODO remember to make this class inherit from IDisposable -> $className$ : IDisposable

// Default initialization for a bool is 'false'
private bool IsDisposed { get; set; }

/// <summary>
/// Implementation of Dispose according to .NET Framework Design Guidelines.
/// </summary>
/// <remarks>Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </remarks>
public void Dispose()
{
    Dispose( true );

    // This object will be cleaned up by the Dispose method.
    // Therefore, you should call GC.SupressFinalize to
    // take this object off the finalization queue 
    // and prevent finalization code for this object
    // from executing a second time.

    // Always use SuppressFinalize() in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize( this );
}

/// <summary>
/// Overloaded Implementation of Dispose.
/// </summary>
/// <param name="isDisposing"></param>
/// <remarks>
/// <para><list type="bulleted">Dispose(bool isDisposing) executes in two distinct scenarios.
/// <item>If <paramref name="isDisposing"/> equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.</item>
/// <item>If <paramref name="isDisposing"/> equals false, the method has been called by the 
/// runtime from inside the finalizer and you should not reference 
/// other objects. Only unmanaged resources can be disposed.</item></list></para>
/// </remarks>
protected virtual void Dispose( bool isDisposing )
{
    // TODO If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    try
    {
        if( !this.IsDisposed )
        {
            if( isDisposing )
            {
                // TODO Release all managed resources here

                $end$
            }

            // TODO Release all unmanaged resources here



            // TODO explicitly set root references to null to expressly tell the GarbageCollector
            // that the resources have been disposed of and its ok to release the memory allocated for them.


        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );

        this.IsDisposed = true;
    }
}

//TODO Uncomment this code if this class will contain members which are UNmanaged
// 
///// <summary>Finalizer for $className$</summary>
///// <remarks>This finalizer will run only if the Dispose method does not get called.
///// It gives your base class the opportunity to finalize.
///// DO NOT provide finalizers in types derived from this class.
///// All code executed within a Finalizer MUST be thread-safe!</remarks>
//  ~$className$()
//  {
//     Dispose( false );
//  }
#endregion IDisposable implementation

Here is the code for implementing IDisposable in a derived class. Note that you do not need to explicitly list inheritance from IDisposable in the definition of the derived class.

public DerivedClass : BaseClass, IDisposable (remove the IDisposable because it is inherited from BaseClass)


protected override void Dispose( bool isDisposing )
{
    try
    {
        if ( !this.IsDisposed )
        {
            if ( isDisposing )
            {
                // Release all managed resources here

            }
        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );
    }
}

I've posted this implementation on my blog at: How to Properly Implement the Dispose Pattern

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I fixed mine by closing eclipse and deleting the whole .metadata folder inside my workspace folder.

AddRange to a Collection

No, this seems perfectly reasonable. There is a List<T>.AddRange() method that basically does just this, but requires your collection to be a concrete List<T>.

What's the best way to validate an XML file against an XSD file?

One more answer: since you said you need to validate files you are generating (writing), you might want to validate content while you are writing, instead of first writing, then reading back for validation. You can probably do that with JDK API for Xml validation, if you use SAX-based writer: if so, just link in validator by calling 'Validator.validate(source, result)', where source comes from your writer, and result is where output needs to go.

Alternatively if you use Stax for writing content (or a library that uses or can use stax), Woodstox can also directly support validation when using XMLStreamWriter. Here's a blog entry showing how that is done:

Setting attribute disabled on a SPAN element does not prevent click events

The disabled attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled) and check for that attribute when you handle the click event.

Sql query to insert datetime in SQL Server

No need to use convert. Simply list it as a quoted date in ISO 8601 format.
Like so:

select * from table1 where somedate between '2000/01/01' and '2099/12/31'

The separator needs to be a / and it needs to be surrounded by single ' quotes.

HTML: How to make a submit button with text + image in it?

Please refer to this link. You can have any button you want just use javascript to submit the form

http://www.w3schools.com/jsref/met_form_submit.asp

error: the details of the application error from being viewed remotely

In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.

Cheers

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Or you can just create your own MediaTypeFormatter. I use this for text/html. If you add text/plain to it, it'll work for you too:

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        using (var streamReader = new StreamReader(readStream))
        {
            return await streamReader.ReadToEndAsync();
        }
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}

Finally you have to assign this to the HttpMethodContext.ResponseFormatter property.

Adding rows to dataset

 DataSet ds = new DataSet();

 DataTable dt = new DataTable("MyTable");
 dt.Columns.Add(new DataColumn("id",typeof(int)));
 dt.Columns.Add(new DataColumn("name", typeof(string)));

 DataRow dr = dt.NewRow();
 dr["id"] = 123;
 dr["name"] = "John";
 dt.Rows.Add(dr);
 ds.Tables.Add(dt);

Is it possible to get a list of files under a directory of a website? How?

If a website's directory does NOT have an "index...." file, AND .htaccess has NOT been used to block access to the directory itself, then Apache will create an "index of" page for that directory. You can save that page, and its icons, using "Save page as..." along with the "Web page, complete" option (Firefox example). If you own the website, temporarily rename any "index...." file, and reference the directory locally. Then restore your "index...." file.

C#: Limit the length of a string?

You could extend the "string" class to let you return a limited string.

using System;

namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
         // since specified strings are treated on the fly as string objects...
         string limit5 = "The quick brown fox jumped over the lazy dog.".LimitLength(5);
         string limit10 = "The quick brown fox jumped over the lazy dog.".LimitLength(10);
         // this line should return us the entire contents of the test string
         string limit100 = "The quick brown fox jumped over the lazy dog.".LimitLength(100);

         Console.WriteLine("limit5   - {0}", limit5);
         Console.WriteLine("limit10  - {0}", limit10);
         Console.WriteLine("limit100 - {0}", limit100);

         Console.ReadLine();
      }
   }

   public static class StringExtensions
   {
      /// <summary>
      /// Method that limits the length of text to a defined length.
      /// </summary>
      /// <param name="source">The source text.</param>
      /// <param name="maxLength">The maximum limit of the string to return.</param>
      public static string LimitLength(this string source, int maxLength)
      {
         if (source.Length <= maxLength)
         {
            return source;
         }

         return source.Substring(0, maxLength);
      }
   }
}

Result:

limit5 - The q
limit10 - The quick
limit100 - The quick brown fox jumped over the lazy dog.

shared global variables in C

In one header file (shared.h):

extern int this_is_global;

In every file that you want to use this global symbol, include header containing the extern declaration:

#include "shared.h"

To avoid multiple linker definitions, just one declaration of your global symbol must be present across your compilation units (e.g: shared.cpp) :

/* shared.cpp */
#include "shared.h"
int this_is_global;

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.

Error C1083: Cannot open include file: 'stdafx.h'

You can fix this problem by adding "$(ProjectDir)" (or wherever the stdafx.h is) to list of directories under Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories.

Apache Spark: The number of cores vs. the number of executors

To hopefully make all of this a little more concrete, here’s a worked example of configuring a Spark app to use as much of the cluster as possible: Imagine a cluster with six nodes running NodeManagers, each equipped with 16 cores and 64GB of memory. The NodeManager capacities, yarn.nodemanager.resource.memory-mb and yarn.nodemanager.resource.cpu-vcores, should probably be set to 63 * 1024 = 64512 (megabytes) and 15 respectively. We avoid allocating 100% of the resources to YARN containers because the node needs some resources to run the OS and Hadoop daemons. In this case, we leave a gigabyte and a core for these system processes. Cloudera Manager helps by accounting for these and configuring these YARN properties automatically.

The likely first impulse would be to use --num-executors 6 --executor-cores 15 --executor-memory 63G. However, this is the wrong approach because:

63GB + the executor memory overhead won’t fit within the 63GB capacity of the NodeManagers. The application master will take up a core on one of the nodes, meaning that there won’t be room for a 15-core executor on that node. 15 cores per executor can lead to bad HDFS I/O throughput.

A better option would be to use --num-executors 17 --executor-cores 5 --executor-memory 19G. Why?

This config results in three executors on all nodes except for the one with the AM, which will have two executors. --executor-memory was derived as (63/3 executors per node) = 21. 21 * 0.07 = 1.47. 21 – 1.47 ~ 19.

The explanation was given in an article in Cloudera's blog, How-to: Tune Your Apache Spark Jobs (Part 2).

Git merge errors

as suggested in git status,

Unmerged paths:                                                                                                                                
(use "git add <file>..." to mark resolution)                                                                                                 

    both modified:   a.jl                                  
    both modified:   b.jl

I used git add to finish the merging, then git checkout works fine.

Java Ordered Map

LinkedHashMap maintains the order of the keys.

java.util.LinkedHashMap appears to work just like a normal HashMap otherwise.

How do I convert a list of ascii values to a string in python?

I've timed the existing answers. Code to reproduce is below. TLDR is that bytes(seq).decode() is by far the fastest. Results here:

 test_bytes_decode : 12.8046 µs/rep
     test_join_map : 62.1697 µs/rep
test_array_library : 63.7088 µs/rep
    test_join_list : 112.021 µs/rep
test_join_iterator : 171.331 µs/rep
    test_naive_add : 286.632 µs/rep

Setup was CPython 3.8.2 (32-bit), Windows 10, i7-2600 3.4GHz

Interesting observations:

  • The "official" fastest answer (as reposted by Toni Ruža) is now out of date for Python 3, but once fixed is still basically tied for second place
  • Joining a mapped sequence is almost twice as fast as a list comprehension
  • The list comprehension is faster than its non-list counterpart

Code to reproduce is here:

import array, string, timeit, random
from collections import namedtuple

# Thomas Wouters (https://stackoverflow.com/a/180615/13528444)
def test_join_iterator(seq):
    return ''.join(chr(c) for c in seq)

# community wiki (https://stackoverflow.com/a/181057/13528444)
def test_join_map(seq):
    return ''.join(map(chr, seq))

# Thomas Vander Stichele (https://stackoverflow.com/a/180617/13528444)
def test_join_list(seq):
    return ''.join([chr(c) for c in seq])

# Toni Ruža (https://stackoverflow.com/a/184708/13528444)
# Also from https://www.python.org/doc/essays/list2str/
def test_array_library(seq):
    return array.array('b', seq).tobytes().decode()  # Updated from tostring() for Python 3

# David White (https://stackoverflow.com/a/34246694/13528444)
def test_naive_add(seq):
    output = ''
    for c in seq:
        output += chr(c)
    return output

# Timo Herngreen (https://stackoverflow.com/a/55509509/13528444)
def test_bytes_decode(seq):
    return bytes(seq).decode()

RESULT = ''.join(random.choices(string.printable, None, k=1000))
INT_SEQ = [ord(c) for c in RESULT]
REPS=10000

if __name__ == '__main__':
    tests = {
        name: test
        for (name, test) in globals().items()
        if name.startswith('test_')
    }

    Result = namedtuple('Result', ['name', 'passed', 'time', 'reps'])
    results = [
        Result(
            name=name,
            passed=test(INT_SEQ) == RESULT,
            time=timeit.Timer(
                stmt=f'{name}(INT_SEQ)',
                setup=f'from __main__ import INT_SEQ, {name}'
                ).timeit(REPS) / REPS,
            reps=REPS)
        for name, test in tests.items()
    ]
    results.sort(key=lambda r: r.time if r.passed else float('inf'))

    def seconds_per_rep(secs):
        (unit, amount) = (
            ('s', secs) if secs > 1
            else ('ms', secs * 10 ** 3) if secs > (10 ** -3)
            else ('µs', secs * 10 ** 6) if secs > (10 ** -6)
            else ('ns', secs * 10 ** 9))
        return f'{amount:.6} {unit}/rep'

    max_name_length = max(len(name) for name in tests)
    for r in results:
        print(
            r.name.rjust(max_name_length),
            ':',
            'failed' if not r.passed else seconds_per_rep(r.time))

TypeError: Object of type 'bytes' is not JSON serializable

I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json). my_json_object in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.

The way I ended up solving it: the write_to_file.json will have everything up to the bytes object that is causing the issue.

In my particular case this was a line obtained through

for line in text:
    json_object['line'] = line.strip()

I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:

for line in text:
    json_object['line'] = line.strip().decode()

DisplayName attribute from Resources?

If you use MVC 3 and .NET 4, you can use the new Display attribute in the System.ComponentModel.DataAnnotations namespace. This attribute replaces the DisplayName attribute and provides much more functionality, including localization support.

In your case, you would use it like this:

public class MyModel
{
    [Required]
    [Display(Name = "labelForName", ResourceType = typeof(Resources.Resources))]
    public string name{ get; set; }
}

As a side note, this attribute will not work with resources inside App_GlobalResources or App_LocalResources. This has to do with the custom tool (GlobalResourceProxyGenerator) these resources use. Instead make sure your resource file is set to 'Embedded resource' and use the 'ResXFileCodeGenerator' custom tool.

(As a further side note, you shouldn't be using App_GlobalResources or App_LocalResources with MVC. You can read more about why this is the case here)

What does "request for member '*******' in something not a structure or union" mean?

You are trying to access a member of a structure, but in something that is not a structure. For example:

struct {
    int a;
    int b;
} foo;
int fum;
fum.d = 5;

Object of class mysqli_result could not be converted to string in

The mysqli_query() method returns an object resource to your $result variable, not a string.

You need to loop it up and then access the records. You just can't directly use it as your $result variable.

while ($row = $result->fetch_assoc()) {
    echo $row['classtype']."<br>";
}

How to check for a valid URL in Java?

My favorite approach, without external libraries:

try {
    URI uri = new URI(name);

    // perform checks for scheme, authority, host, etc., based on your requirements

    if ("mailto".equals(uri.getScheme()) {/*Code*/}
    if (uri.getHost() == null) {/*Code*/}

} catch (URISyntaxException e) {
}

How to replace list item in best way

I don't if it is best or not but you can use it also

List<string> data = new List<string>
(new string[]   { "Computer", "A", "B", "Computer", "B", "A" });
int[] indexes = Enumerable.Range(0, data.Count).Where
                 (i => data[i] == "Computer").ToArray();
Array.ForEach(indexes, i => data[i] = "Calculator");

How to define a variable in a Dockerfile?

You can use ARG - see https://docs.docker.com/engine/reference/builder/#arg

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.

Replace all whitespace with a line break/paragraph mark to make a word list

The portable way to do this is:

sed -e 's/[ \t][ \t]*/\
/g'

That's an actual newline between the backslash and the slash-g. Many sed implementations don't know about \n, so you need a literal newline. The backslash before the newline prevents sed from getting upset about the newline. (in sed scripts the commands are normally terminated by newlines)

With GNU sed you can use \n in the substitution, and \s in the regex:

sed -e 's/\s\s*/\n/g'

GNU sed also supports "extended" regular expressions (that's egrep style, not perl-style) if you give it the -r flag, so then you can use +:

sed -r -e 's/\s+/\n/g'

If this is for Linux only, you can probably go with the GNU command, but if you want this to work on systems with a non-GNU sed (eg: BSD, Mac OS-X), you might want to go with the more portable option.

How to change FontSize By JavaScript?

JavaScript is case sensitive.

So, if you want to change the font size, you have to go:

span.style.fontSize = "25px";

Understanding generators in Python

First of all, the term generator originally was somewhat ill-defined in Python, leading to lots of confusion. You probably mean iterators and iterables (see here). Then in Python there are also generator functions (which return a generator object), generator objects (which are iterators) and generator expressions (which are evaluated to a generator object).

According to the glossary entry for generator it seems that the official terminology is now that generator is short for "generator function". In the past the documentation defined the terms inconsistently, but fortunately this has been fixed.

It might still be a good idea to be precise and avoid the term "generator" without further specification.

What does "while True" mean in Python?

my question: while WHAT is True?

Everything inside the () of the while statement is going to be evaluated as a boolean. Meaning it gets converted into either true or false.

Consider in the statement while(6 > 5)

It first evaluates the expression 6 > 5 which is true so is the same as saying while(true)

Anything that is not FALSE, 0, an emptry string "", null, or undefined is likely to be evaluated to true.

When I first started programming I used to do things like if(foo == true), I didn't realise that was virtually the same thing as if(foo).

So when you say while(true) its like are saying while(true == true)

So to answer you question: While TRUE is True.

How Do I Make Glyphicons Bigger? (Change Size?)

For ex .. add class:

btn-lg - LARGE

btn-sm - SMALL

btn-xs - Very small

<button type=button class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button> 

<button type=button class="btn btn-default">
<span class="glyphicon glyphicon-star" aria-hidden=true></span>Star
</button>

 <button type=button class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button> 

<button type=button class="btn btn-default btn-xs">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button> 

Ref link Bootstrap : Glyphicons Bootstrap

I got error "The DELETE statement conflicted with the REFERENCE constraint"

To DELETE, without changing the references, you should first delete or otherwise alter (in a manner suitable for your purposes) all relevant rows in other tables.

To TRUNCATE you must remove the references. TRUNCATE is a DDL statement (comparable to CREATE and DROP) not a DML statement (like INSERT and DELETE) and doesn't cause triggers, whether explicit or those associated with references and other constraints, to be fired. Because of this, the database could be put into an inconsistent state if TRUNCATE was allowed on tables with references. This was a rule when TRUNCATE was an extension to the standard used by some systems, and is mandated by the the standard, now that it has been added.

python pip - install from local dir

You were looking for help on installations with pip. You can find it with the following command:

pip install --help

Running pip install -e /path/to/package installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.

How to get file extension from string in C++

Try to use strstr

char* lastSlash;
lastSlash = strstr(filename, ".");

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

I've put together what I hope is a pretty robust solution, including some of the techniques in other answers. It is a new class derived from ObservableCollection<>, which I'm calling FullyObservableCollection<>

It has the following features:

  • It adds a new event, ItemPropertyChanged. I've deliberately kept this separate from the existing CollectionChanged:
    • To aid backward compatibility.
    • So more relevant detail can be given in the new ItemPropertyChangedEventArgs that accompanies it: the original PropertyChangedEventArgs and the index within the collection.
  • It replicates all the constructors from ObservableCollection<>.
  • It correctly handles the list being reset (ObservableCollection<>.Clear()), avoiding a possible memory leak.
  • It overrides the base class's OnCollectionChanged(), rather than a more resource-intensive subscription to the CollectionChanged event.

Code

The complete .cs file follows. Note that a few features of C# 6 have been used, but it should be fairly simple to backport it:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;

namespace Utilities
{
    public class FullyObservableCollection<T> : ObservableCollection<T>
        where T : INotifyPropertyChanged
    {
        /// <summary>
        /// Occurs when a property is changed within an item.
        /// </summary>
        public event EventHandler<ItemPropertyChangedEventArgs> ItemPropertyChanged;

        public FullyObservableCollection() : base()
        { }

        public FullyObservableCollection(List<T> list) : base(list)
        {
            ObserveAll();
        }

        public FullyObservableCollection(IEnumerable<T> enumerable) : base(enumerable)
        {
            ObserveAll();
        }

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove ||
                e.Action == NotifyCollectionChangedAction.Replace)
            {
                foreach (T item in e.OldItems)
                    item.PropertyChanged -= ChildPropertyChanged;
            }

            if (e.Action == NotifyCollectionChangedAction.Add ||
                e.Action == NotifyCollectionChangedAction.Replace)
            {
                foreach (T item in e.NewItems)
                    item.PropertyChanged += ChildPropertyChanged;
            }

            base.OnCollectionChanged(e);
        }

        protected void OnItemPropertyChanged(ItemPropertyChangedEventArgs e)
        {
            ItemPropertyChanged?.Invoke(this, e);
        }

        protected void OnItemPropertyChanged(int index, PropertyChangedEventArgs e)
        {
            OnItemPropertyChanged(new ItemPropertyChangedEventArgs(index, e));
        }

        protected override void ClearItems()
        {
            foreach (T item in Items)
                item.PropertyChanged -= ChildPropertyChanged;

            base.ClearItems();
        }

        private void ObserveAll()
        {
            foreach (T item in Items)
                item.PropertyChanged += ChildPropertyChanged;
        }

        private void ChildPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            T typedSender = (T)sender;
            int i = Items.IndexOf(typedSender);

            if (i < 0)
                throw new ArgumentException("Received property notification from item not in collection");

            OnItemPropertyChanged(i, e);
        }
    }

    /// <summary>
    /// Provides data for the <see cref="FullyObservableCollection{T}.ItemPropertyChanged"/> event.
    /// </summary>
    public class ItemPropertyChangedEventArgs : PropertyChangedEventArgs
    {
        /// <summary>
        /// Gets the index in the collection for which the property change has occurred.
        /// </summary>
        /// <value>
        /// Index in parent collection.
        /// </value>
        public int CollectionIndex { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ItemPropertyChangedEventArgs"/> class.
        /// </summary>
        /// <param name="index">The index in the collection of changed item.</param>
        /// <param name="name">The name of the property that changed.</param>
        public ItemPropertyChangedEventArgs(int index, string name) : base(name)
        {
            CollectionIndex = index;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ItemPropertyChangedEventArgs"/> class.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="args">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
        public ItemPropertyChangedEventArgs(int index, PropertyChangedEventArgs args) : this(index, args.PropertyName)
        { }
    }
}

NUnit Tests

So you can check changes you might make (and see what I tested in the first place!), I've also included my NUnit test class. Obviously, the following code is not necessary just to use FullyObservableCollection<T> in your project.

NB The test class uses BindableBase from PRISM to implement INotifyPropertyChanged. There is no dependency on PRISM from the main code.

using NUnit.Framework;
using Utilities;
using Microsoft.Practices.Prism.Mvvm;
using System.Collections.Specialized;
using System.Collections.Generic;

namespace Test_Utilities
{
    [TestFixture]
    public class Test_FullyObservableCollection : AssertionHelper
    {
        public class NotifyingTestClass : BindableBase
        {
            public int Id
            {
                get { return _Id; }
                set { SetProperty(ref _Id, value); }
            }
            private int _Id;

            public string Name
            {
                get { return _Name; }
                set { SetProperty(ref _Name, value); }
            }
            private string _Name;

        }

        FullyObservableCollection<NotifyingTestClass> TestCollection;
        NotifyingTestClass Fred;
        NotifyingTestClass Betty;
        List<NotifyCollectionChangedEventArgs> CollectionEventList;
        List<ItemPropertyChangedEventArgs> ItemEventList;

        [SetUp]
        public void Init()
        {
            Fred = new NotifyingTestClass() { Id = 1, Name = "Fred" };
            Betty = new NotifyingTestClass() { Id = 4, Name = "Betty" };

            TestCollection = new FullyObservableCollection<NotifyingTestClass>()
                {
                    Fred,
                    new NotifyingTestClass() {Id = 2, Name = "Barney" },
                    new NotifyingTestClass() {Id = 3, Name = "Wilma" }
                };

            CollectionEventList = new List<NotifyCollectionChangedEventArgs>();
            ItemEventList = new List<ItemPropertyChangedEventArgs>();
            TestCollection.CollectionChanged += (o, e) => CollectionEventList.Add(e);
            TestCollection.ItemPropertyChanged += (o, e) => ItemEventList.Add(e);
        }

        // Change existing member property: just ItemPropertyChanged(IPC) should fire
        [Test]
        public void DetectMemberPropertyChange()
        {
            TestCollection[0].Id = 7;

            Expect(CollectionEventList.Count, Is.EqualTo(0));

            Expect(ItemEventList.Count, Is.EqualTo(1), "IPC count");
            Expect(ItemEventList[0].PropertyName, Is.EqualTo(nameof(Fred.Id)), "Field Name");
            Expect(ItemEventList[0].CollectionIndex, Is.EqualTo(0), "Collection Index");
        }


        // Add new member, change property: CollectionPropertyChanged (CPC) and IPC should fire
        [Test]
        public void DetectNewMemberPropertyChange()
        {
            TestCollection.Add(Betty);

            Expect(TestCollection.Count, Is.EqualTo(4));
            Expect(TestCollection[3].Name, Is.EqualTo("Betty"));

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Add), "Action (add)");
            Expect(CollectionEventList[0].OldItems, Is.Null, "OldItems count");
            Expect(CollectionEventList[0].NewItems.Count, Is.EqualTo(1), "NewItems count");
            Expect(CollectionEventList[0].NewItems[0], Is.EqualTo(Betty), "NewItems[0] dereference");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            TestCollection[3].Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count");

            Expect(ItemEventList.Count, Is.EqualTo(1), "Item Event count");
            Expect(TestCollection[ItemEventList[0].CollectionIndex], Is.EqualTo(Betty), "Collection Index dereference");
        }


        // Remove member, change property: CPC should fire for removel, neither CPC nor IPC should fire for change
        [Test]
        public void CeaseListentingWhenMemberRemoved()
        {
            TestCollection.Remove(Fred);

            Expect(TestCollection.Count, Is.EqualTo(2));
            Expect(TestCollection.IndexOf(Fred), Is.Negative);

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (pre change)");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count (pre change)");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Remove), "Action (remove)");
            Expect(CollectionEventList[0].OldItems.Count, Is.EqualTo(1), "OldItems count");
            Expect(CollectionEventList[0].NewItems, Is.Null, "NewItems count");
            Expect(CollectionEventList[0].OldItems[0], Is.EqualTo(Fred), "OldItems[0] dereference");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            Fred.Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count (post change)");
            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (post change)");
        }


        // Move member in list, change property: CPC should fire for move, IPC should fire for change
        [Test]
        public void MoveMember()
        {
            TestCollection.Move(0, 1);

            Expect(TestCollection.Count, Is.EqualTo(3));
            Expect(TestCollection.IndexOf(Fred), Is.GreaterThan(0));

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (pre change)");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count (pre change)");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Move), "Action (move)");
            Expect(CollectionEventList[0].OldItems.Count, Is.EqualTo(1), "OldItems count");
            Expect(CollectionEventList[0].NewItems.Count, Is.EqualTo(1), "NewItems count");
            Expect(CollectionEventList[0].OldItems[0], Is.EqualTo(Fred), "OldItems[0] dereference");
            Expect(CollectionEventList[0].NewItems[0], Is.EqualTo(Fred), "NewItems[0] dereference");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            Fred.Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count (post change)");

            Expect(ItemEventList.Count, Is.EqualTo(1), "Item Event count (post change)");
            Expect(TestCollection[ItemEventList[0].CollectionIndex], Is.EqualTo(Fred), "Collection Index dereference");
        }


        // Clear list, chnage property: only CPC should fire for clear and neither for property change
        [Test]
        public void ClearList()
        {
            TestCollection.Clear();

            Expect(TestCollection.Count, Is.EqualTo(0));

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (pre change)");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count (pre change)");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Reset), "Action (reset)");
            Expect(CollectionEventList[0].OldItems, Is.Null, "OldItems count");
            Expect(CollectionEventList[0].NewItems, Is.Null, "NewItems count");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            Fred.Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count (post change)");
            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (post change)");
        }
    }
}

Should a function have only one return statement?

In the interests of good standards and industry best practises, we must establish the correct number of return statements to appear in all functions. Obviously there is consensus against having one return statement. So I propose we set it at two.

I would appreciate it if everyone would look through their code right now, locate any functions with only one exit point, and add another one. It doesn't matter where.

The result of this change will undoubtedly be fewer bugs, greater readability and unimaginable wealth falling from the sky onto our heads.

Sql Server string to date conversion

You can easily achieve this by using this code.

SELECT Convert(datetime, Convert(varchar(30),'10/15/2008 10:06:32 PM',102),102)

Check whether a table contains rows or not sql server 2005

For what purpose?

  • Quickest for an IF would be IF EXISTS (SELECT * FROM Table)...
  • For a result set, SELECT TOP 1 1 FROM Table returns either zero or one rows
  • For exactly one row with a count (0 or non-zero), SELECT COUNT(*) FROM Table

How can I get zoom functionality for images?

You can try using the LayoutParams for this

public void zoom(boolean flag){
    if(flag){
        int width=40;
        int height=40;
    }
    else{
        int width=20;
        int height=20;
    }
    RelativeLayout.LayoutParams param=new RelativeLayout.LayoutParams(width,height); //use the parent layout of the ImageView;
    imageView.setLayoutParams(param); //imageView is the view which needs zooming.
}

ZoomIn = zoom(true); ZoomOut = zoom(false);

How to ignore ansible SSH authenticity checking?

Two options - the first, as you said in your own answer, is setting the environment variable ANSIBLE_HOST_KEY_CHECKING to False.

The second way to set it is to put it in an ansible.cfg file, and that's a really useful option because you can either set that globally (at system or user level, in /etc/ansible/ansible.cfg or ~/.ansible.cfg), or in an config file in the same directory as the playbook you are running.

To do that, make an ansible.cfg file in one of those locations, and include this:

[defaults]
host_key_checking = False

You can also set a lot of other handy defaults there, like whether or not to gather facts at the start of a play, whether to merge hashes declared in multiple places or replace one with another, and so on. There's a whole big list of options here in the Ansible docs.


Edit: a note on security.

SSH host key validation is a meaningful security layer for persistent hosts - if you are connecting to the same machine many times, it's valuable to accept the host key locally.

For longer-lived EC2 instances, it would make sense to accept the host key with a task run only once on initial creation of the instance:

  - name: Write the new ec2 instance host key to known hosts
    connection: local
    shell: "ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts"

There's no security value for checking host keys on instances that you stand up dynamically and remove right after playbook execution, but there is security value in checking host keys for persistent machines. So you should manage host key checking differently per logical environment.

  • Leave checking enabled by default (in ~/.ansible.cfg)
  • Disable host key checking in the working directory for playbooks you run against ephemeral instances (./ansible.cfg alongside the playbook for unit tests against vagrant VMs, automation for short-lived ec2 instances)

jQuery datepicker, onSelect won't work

I have downloaded the datepicker from jqueryui.com/download and I got 1.7.2 version but still onSelect function didn't work. Here is what i had -

$("#datepicker").datepicker();

$("#datepicker").datepicker({ 
      onSelect: function(value, date) { 
         alert('The chosen date is ' + value); 
      } 
});

I found the solution in this page -- problem with jquery datepicker onselect . Removed the $("#datepicker").datepicker(); once and it worked.

How do I get the total number of unique pairs of a set in the database?

This is how you can approach these problems in general on your own:

The first of the pair can be picked in N (=100) ways. You don't want to pick this item again, so the second of the pair can be picked in N-1 (=99) ways. In total you can pick 2 items out of N in N(N-1) (= 100*99=9900) different ways.

But hold on, this way you count also different orderings: AB and BA are both counted. Since every pair is counted twice you have to divide N(N-1) by two (the number of ways that you can order a list of two items). The number of subsets of two that you can make with a set of N is then N(N-1)/2 (= 9900/2 = 4950).

How can I output UTF-8 from Perl?

do in your shell: $ env |grep LANG

This will probably show that your shell is not using a utf-8 locale.

MySQL: How to add one day to datetime field in query

Have a go with this, as this is how I would do it :)

SELECT * 
FROM fab_scheduler
WHERE custid = '123456'
AND CURDATE() = DATE(DATE_ADD(eventdate, INTERVAL 1 DAY))

How to Access Hive via Python?

None of the answers demonstrate how to fetch and print the table headers. Modified the standard example from PyHive which is widely used and actively maintained.

from pyhive import hive
cursor = hive.connect(host="localhost", 
                      port=10000, 
                      username="shadan", 
                      auth="KERBEROS", 
                      kerberos_service_name="hive"
                      ).cursor()
cursor.execute("SELECT * FROM my_dummy_table LIMIT 10")
columnList = [desc[0] for desc in cursor.description]
headerStr = ",".join(columnList)
headerTuple = tuple(headerStr.split (",")
print(headerTuple)
print(cursor.fetchone())
print(cursor.fetchall())

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

I will put a small comparison table here (just to have it somewhere):

Servlet is mapped as /test%3F/* and the application is deployed under /app.

http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a

Method              URL-Decoded Result           
----------------------------------------------------
getContextPath()        no      /app
getLocalAddr()                  127.0.0.1
getLocalName()                  30thh.loc
getLocalPort()                  8480
getMethod()                     GET
getPathInfo()           yes     /a?+b
getProtocol()                   HTTP/1.1
getQueryString()        no      p+1=c+d&p+2=e+f
getRequestedSessionId() no      S%3F+ID
getRequestURI()         no      /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL()         no      http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme()                     http
getServerName()                 30thh.loc
getServerPort()                 8480
getServletPath()        yes     /test?
getParameterNames()     yes     [p 2, p 1]
getParameter("p 1")     yes     c d

In the example above the server is running on the localhost:8480 and the name 30thh.loc was put into OS hosts file.

Comments

  • "+" is handled as space only in the query string

  • Anchor "#a" is not transferred to the server. Only the browser can work with it.

  • If the url-pattern in the servlet mapping does not end with * (for example /test or *.jsp), getPathInfo() returns null.

If Spring MVC is used

  • Method getPathInfo() returns null.

  • Method getServletPath() returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b

  • Be careful with URL encoded parts of @RequestMapping and @RequestParam in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.

How can I have grep not print out 'No such file or directory' errors?

Errors like that are usually sent to the "standard error" stream, which you can pipe to a file or just make disappear on most commands:

grep pattern * -R -n 2>/dev/null

Nginx: Job for nginx.service failed because the control process exited

In my case, nginx was not able to open the log file which is located here /var/log/nginx/error.log

This was because I had deleted the log directory to free up space in root (which turned out to be stupid)

I then created a log folder in var and an nginx folder in log.

Then simply run sudo service nginx start

Try-catch speeding up my code?

I'd have put this in as a comment as I'm really not certain that this is likely to be the case, but as I recall it doesn't a try/except statement involve a modification to the way the garbage disposal mechanism of the compiler works, in that it clears up object memory allocations in a recursive way off the stack. There may not be an object to be cleared up in this case or the for loop may constitute a closure that the garbage collection mechanism recognises sufficient to enforce a different collection method. Probably not, but I thought it worth a mention as I hadn't seen it discussed anywhere else.

'ls' is not recognized as an internal or external command, operable program or batch file

I'm fairly certain that the ls command is for Linux, not Windows (I'm assuming you're using Windows as you referred to cmd, which is the command line for the Windows OS).

You should use dir instead, which is the Windows equivalent of ls.

Edit (since this post seems to be getting so many views :) ):

You can't use ls on cmd as it's not shipped with Windows, but you can use it on other terminal programs (such as GitBash). Note, ls might work on some FTP servers if the servers are linux based and the FTP is being used from cmd.

dir on Windows is similar to ls. To find out the various options available, just do dir/?.

If you really want to use ls, you could install 3rd party tools to allow you to run unix commands on Windows. Such a program is Microsoft Windows Subsystem for Linux (link to docs).

How to prevent line-break in a column of a table cell (not a single cell)?

There are a few ways to do this; none of them are the easy, obvious way.

Applying white-space:nowrap to a <col> won't work; only four CSS properties work on <col> elements - background-color, width, border, and visibility. IE7 and earlier used to support all properties, but that's because they used a strange table model. IE8 now matches everyone else.

So, how do you solve this?

Well, if you can ignore IE (including IE8), you can use the :nth-child() pseudoclass to select particular <td>s from each row. You'd use td:nth-child(2) { white-space:nowrap; }. (This works for this example, but would break if you had any rowspans or colspans involved.)

If you have to support IE, then you've got to go the long way around and apply a class to every <td> that you want to affect. It sucks, but them's the breaks.

In the long run, there are proposals to fix this lack in CSS, so that you can more easily apply styles to all the cells in a column. You'll be able to do something like td:nth-col(2) { white-space:nowrap; } and it would do what you want.

Assign output of a program to a variable using a MS batch file

assuming that your application's output is a numeric return code, you can do the following

application arg0 arg1
set VAR=%errorlevel%

Error Message : Cannot find or open the PDB file

Working with VS 2013. Try the following Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off It will disable the display of modules loaded.

Add Foreign Key to existing table

Simple Steps...

ALTER TABLE t_name1 ADD FOREIGN KEY (column_name) REFERENCES t_name2(column_name)

What is an OS kernel ? How does it differ from an operating system?

Simple Answer

The Kernel is the core piece of the operating system. It is not necessarily an operating system in and of itself.

Everything else is built around it.

Ellaborate Definition

Kernel (computing) - Wikipedia

Java HTTPS client certificate authentication

For those of you who simply want to set up a two-way authentication (server and client certificates), a combination of these two links will get you there :

Two-way auth setup:

https://linuxconfig.org/apache-web-server-ssl-authentication

You don't need to use the openssl config file that they mention; just use

  • $ openssl genrsa -des3 -out ca.key 4096

  • $ openssl req -new -x509 -days 365 -key ca.key -out ca.crt

to generate your own CA certificate, and then generate and sign the server and client keys via:

  • $ openssl genrsa -des3 -out server.key 4096

  • $ openssl req -new -key server.key -out server.csr

  • $ openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 100 -out server.crt

and

  • $ openssl genrsa -des3 -out client.key 4096

  • $ openssl req -new -key client.key -out client.csr

  • $ openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 101 -out client.crt

For the rest follow the steps in the link. Managing the certificates for Chrome works the same as in the example for firefox that is mentioned.

Next, setup the server via:

https://www.digitalocean.com/community/tutorials/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-14-04

Note that you have already created the server .crt and .key so you don't have to do that step anymore.

How do you dismiss the keyboard when editing a UITextField

try this

- (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

I just tried with PHP 5.2, and that constant seems to exists :

var_dump(PDO::MYSQL_ATTR_INIT_COMMAND);

Gives me :

int 1002


But it seems there is a bug in PHP 5.3, that causes this constant to not exists anymore -- or, at least, not when the mysqlnd driver is used (and it's the one that's configured by default)

I suppose a temporary solution, as suggested on this bug report, could be to directly use the integer 1002 value, instead of the contant...

But note that you should go back to using the constant as soon as possible -- as this makes the code easier to understand.

List of IP addresses/hostnames from local network in Python

I have done following code to get the IP of MAC known device. This can be modified accordingly to obtain all IPs with some string manipulation. Hope this will help you.

#running windows cmd line  statement and put output into a string
cmd_out = os.popen("arp -a").read()
line_arr = cmd_out.split('\n')
line_count = len(line_arr)


#search in all lines for ip
for i in range(0, line_count):
    y = line_arr[i]
    z = y.find(mac_address)

    #if mac address is found then get the ip using regex matching
    if z > 0:
        ip_out= re.search('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', y, re.M | re.I)

Validate email with a regex in jQuery

Email: {
                      group: '.col-sm-3',
                      enabled: false,
                      validators: {
                          //emailAddress: {
                          //    message: 'Email not Valid'
                          //},
                          regexp: {
                              regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
                              message: 'Email not Valid'
                          },
                      }
                  },

Order Bars in ggplot2 bar graph

I found it very annoying that ggplot2 doesn't offer an 'automatic' solution for this. That's why I created the bar_chart() function in ggcharts.

ggcharts::bar_chart(theTable, Position)

enter image description here

By default bar_chart() sorts the bars and displays a horizontal plot. To change that set horizontal = FALSE. In addition, bar_chart() removes the unsightly 'gap' between the bars and the axis.

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

javascript variable reference/alias

in 2019 I need to write minified jquery plugins so I need it too this alias and so testing these examples and others ,from other sources,I found a way without copy in the memory of whe entire object ,but creating only a reference. I tested this already with firefox and watching task manager's tab memory on firefox before. The code is:

var {p: d} ={p: document};
console.log(d.body);

mongo - couldn't connect to server 127.0.0.1:27017

Resolved.

This problem could be solved by the below mentioned 4 steps

1) Remove .lock file

sudo rm /var/lib/mongodb/mongod.lock 

2) repair the mongodb

mongod -–repair

3) start the mongod server

sudo service mongod start 

4) start the mongo client

mongo

For more details take a look at http://shakthydoss.com/error-couldnt-connect-to-server-127-0-0-127017-srcmongoshellmongo-js-exception-connect-failed/

http://shakthydoss.com/technical/error-couldnt-connect-to-server-127-0-0-127017-srcmongoshellmongo-js-exception-connect-failed/

windows batch file rename

as Itsproinc said, the REN command works!

but if your file path/name has spaces, use quotes " "

example:

ren C:\Users\&username%\Desktop\my file.txt not my file.txt

add " "

ren "C:\Users\&username%\Desktop\my file.txt" "not my file.txt"

hope it helps

Simulate Keypress With jQuery

I believe this is what you're looking for:

var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);

From here.

Find where java class is loaded from

Edit just 1st line: Main.class

Class<?> c = Main.class;
String path = c.getResource(c.getSimpleName() + ".class").getPath().replace(c.getSimpleName() + ".class", "");

System.out.println(path);

Output:

/C:/Users/Test/bin/

Maybe bad style but works fine!

How to change the output color of echo in Linux

You may "combined" colours and text-mode.

#!/bin/bash

echo red text / black background \(Reverse\)
echo "\033[31;7mHello world\e[0m";
echo -e "\033[31;7mHello world\e[0m";
echo

echo yellow text / red background
echo "\033[32;41mHello world\e[0m";
echo -e "\033[32;41mHello world\e[0m";
echo "\033[0;32;41mHello world\e[0m";
echo -e "\033[0;32;41mHello world\e[0m";
echo

echo yellow BOLD text / red background
echo "\033[1;32;41mHello world\e[0m";
echo -e "\033[1;32;41mHello world\e[0m";
echo

echo yellow BOLD text underline / red background
echo "\033[1;4;32;41mHello world\e[0m";
echo -e "\033[1;4;32;41mHello world\e[0m";
echo "\033[1;32;4;41mHello world\e[0m";
echo -e "\033[1;32;4;41mHello world\e[0m";
echo "\033[4;32;41;1mHello world\e[0m";
echo -e "\033[4;32;41;1mHello world\e[0m";
echo

enter image description here

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

java: use StringBuilder to insert at the beginning

Maybe I'm missing something but you want to wind up with a String that looks like this, "999897969594...543210", correct?

StringBuilder sb = new StringBuilder();
for(int i=99;i>=0;i--){
    sb.append(String.valueOf(i));
}

Found 'OR 1=1/* sql injection in my newsletter database

Its better if you use validation code to the users input for making it restricted to use symbols and part of code in your input form. If you embeed php in html code your php code have to become on the top to make sure that it is not ignored as comment if a hacker edit the page and add /* in your html code

Error 'tunneling socket' while executing npm install

After looking at all of the answers, the one that helped me was providing proxy values in-line with the install command. One of my frustrations was adding the domain to my username. This is not needed. I used the following example to install a specific version of Angular:

npm install -g @angular/[email protected] --proxy "http://username:password@proxy_server:proxy_port" --registry http://registry.npmjs.org

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

Use grep to report back only line numbers

using only grep:

grep -n "text to find" file.ext | grep -Po '^[^:]+'

How can I configure Logback to log different levels for a logger to different destinations?

Example of how to output colored messages of level "INFO" or higher to console and messages of level "WARN" or higher to file.

Your logback.xml file:

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>

            <!--output messages of exact level only-->
            <!--<onMatch>ACCEPT</onMatch>-->
            <!--<onMismatch>DENY</onMismatch>-->
        </filter>
        <encoder>
            <pattern>%d{yyyy-MMM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n
            </pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>myfile.log</file>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>WARN</level>
        </filter>
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MMM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE"/>
    </root>
</configuration>

Twitter Bootstrap Datepicker within modal window

According to http://www.daterangepicker.com/ (options)

$('#dispatch_modal').on('shown.bs.modal', function() {
     $('input:text:visible:first').focus();
     // prepare datepicker
     $('.form_datepicker').daterangepicker({
          singleDatePicker: true,
          showDropdowns: true,
          parentEl: '#dispatch_modal'   
     });
});

`

parentEl solved my problem...

Phone: numeric keyboard for text input

I couldn't find a type that worked best for me in all situations: I needed to default to numeric entry (entry of "7.5" for example) but also at certain times allow text ("pass" for example). Users wanted a numeric keypad (entry of 7.5 for example) but occasional text entry was required ("pass" for example).

Rather what I did was to add a checkbox to the form and allow the user to toggle my input (id="inputSresult") between type="number" and type="text".

<input type="number" id="result"... >
<label><input id="cbAllowTextResults" type="checkbox" ...>Allow entry of text results.</label>

Then I wired a click handler to the checkbox that toggles the type between text and number based on whether the checkbox above is checked:

$(document).ready(function () {
    var cb = document.getElementById('cbAllowTextResults');
    cb.onclick = function (event) {
        if ($("#cbAllowTextResults").is(":checked"))
            $("#result").attr("type", "text");
        else
            $("#result").attr("type", "number");

    }
});

This worked out well for us.

NodeJS/express: Cache and 304 status code

  • Operating system: Windows
  • Browser: Chrome

I used Ctrl + F5 keyboard combination. By doing so, instead of reading from cache, I wanted to get a new response. The solution is to do hard refresh the page.

On MDN Web Docs:

"The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource."

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

-didSelectRowAtIndexPath: not being called

Another thing that might lead to the issue is not selected selection kind:

UITableView selection kind

Should be Single Selection for normal selection, should not be No Selection.

To do this programmatically, do:

tableView.allowsSelection = YES

How to detect Ctrl+V, Ctrl+C using JavaScript?

Short solution for preventing user from using context menu, copy and cut in jQuery:

jQuery(document).bind("cut copy contextmenu",function(e){
    e.preventDefault();
});

Also disabling text selection in CSS might come handy:

.noselect {  
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
     user-select: none;
}

What's the best practice to "git clone" into an existing folder?

if you are cloning the same repository, then run the following snippet through the existing repository

git pull origin master

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

How to make borders collapse (on a div)?

Use simple negative margin rather than using display table.

Updated in fiddle JS Fiddle

.container { 
    border-style: solid;
    border-color: red;
    border-width: 1px 0 0 1px;
    display: inline-block;
}
.column { 
    float: left; overflow: hidden; 
}
.cell { 
    border: 1px solid red; width: 120px; height: 20px; 
    margin:-1px 0 0 -1px;
}
.clearfix {
    clear:both;
}

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

I had to use the following command to start the build:

docker build .

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I know this is going to be a late answer, however here is the most correct answer.

In MySQL database, change your timestamp default value into CURRENT_TIMESTAMP. If you have old records with the fake value, you will have to manually fix them.

Basic Ajax send/receive with node.js

RESTful API (Route):

rtr.route('/testing')
.get((req, res)=>{
    res.render('test')
})
.post((req, res, next)=>{
       res.render('test')
})

AJAX Code:

$(function(){
$('#anyid').on('click', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'GET',
        contentType: 'application/json',
        success: function(res){
            console.log('GET Request')
        }
    })
})

$('#anyid').on('submit', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            info: "put data here to pass in JSON format."
        }),
        success: function(res){
            console.log('POST Request')
        }
    })
})
})

Maven artifact and groupId naming

Your convention seems to be reasonable. If I were searching for your framework in the Maven repo, I would look for awesome-inhouse-framework-x.y.jar in com.mycompany.awesomeinhouseframework group directory. And I would find it there according to your convention.

Two simple rules work for me:

  • reverse-domain-packages for groupId (since such are quite unique) with all the constrains regarding Java packages names
  • project name as artifactId (keeping in mind that it should be jar-name friendly i.e. not contain characters that maybe invalid for a file name or just look weird)

How to load a controller from another controller in codeigniter?

I came here because I needed to create a {{ render() }} function in Twig, to simulate Symfony2's behaviour. Rendering controllers from view is really cool to display independant widgets or ajax-reloadable stuffs.

Even if you're not a Twig user, you can still take this helper and use it as you want in your views to render a controller, using <?php echo twig_render('welcome/index', $param1, $param2, $_); ?>. This will echo everything your controller outputted.

Here it is:

helpers/twig_helper.php

<?php

if (!function_exists('twig_render'))
{

    function twig_render()
    {
        $args = func_get_args();
        $route = array_shift($args);
        $controller = APPPATH . 'controllers/' . substr($route, 0, strrpos($route, '/'));

        $explode = explode('/', $route);
        if (count($explode) < 2)
        {
            show_error("twig_render: A twig route is made from format: path/to/controller/action.");
        }

        if (!is_file($controller . '.php'))
        {
            show_error("twig_render: Controller not found: {$controller}");
        }
        if (!is_readable($controller . '.php'))
        {
            show_error("twig_render: Controller not readable: {$controller}");
        }
        require_once($controller . '.php');

        $class = ucfirst(reset(array_slice($explode, count($explode) - 2, 1)));
        if (!class_exists($class))
        {
            show_error("twig_render: Controller file exists, but class not found inside: {$class}");
        }

        $object = new $class();
        if (!($object instanceof CI_Controller))
        {
            show_error("twig_render: Class {$class} is not an instance of CI_Controller");
        }

        $method = $explode[count($explode) - 1];
        if (!method_exists($object, $method))
        {
            show_error("twig_render: Controller method not found: {$method}");
        }

        if (!is_callable(array($object, $method)))
        {
            show_error("twig_render: Controller method not visible: {$method}");
        }

        call_user_func_array(array($object, $method), $args);

        $ci = &get_instance();
        return $ci->output->get_output();
    }

}

Specific for Twig users (adapt this code to your Twig implementation):

libraries/Twig.php

$this->_twig_env->addFunction('render', new Twig_Function_Function('twig_render'));

Usage

{{ render('welcome/index', param1, param2, ...) }}

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

        // The newInstance() call is a work around for some
        // broken Java implementations
        Class.forName("com.mysql.cj.jdbc.Driver").newInstance();

Using LIMIT within GROUP BY to get N results per group?

Please try below stored procedure. I have already verified. I am getting proper result but without using groupby.

CREATE DEFINER=`ks_root`@`%` PROCEDURE `first_five_record_per_id`()
BEGIN
DECLARE query_string text;
DECLARE datasource1 varchar(24);
DECLARE done INT DEFAULT 0;
DECLARE tenants varchar(50);
DECLARE cur1 CURSOR FOR SELECT rid FROM demo1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    SET @query_string='';

      OPEN cur1;
      read_loop: LOOP

      FETCH cur1 INTO tenants ;

      IF done THEN
        LEAVE read_loop;
      END IF;

      SET @datasource1 = tenants;
      SET @query_string = concat(@query_string,'(select * from demo  where `id` = ''',@datasource1,''' order by rate desc LIMIT 5) UNION ALL ');

       END LOOP; 
      close cur1;

    SET @query_string  = TRIM(TRAILING 'UNION ALL' FROM TRIM(@query_string));  
  select @query_string;
PREPARE stmt FROM @query_string;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END

PHP Get name of current directory

Actually I found the best solution is the following:

$cur_dir = explode('\\', getcwd());
echo $cur_dir[count($cur_dir)-1];

if your dir is www\var\path\ Current_Path

then this returns Current_path

C# Creating an array of arrays

This loops vertically but might work for you.

int rtn = 0;    
foreach(int[] L in lists){
    for(int i = 0; i<L.Length;i++){
          rtn = L[i];
      //Do something with rtn
    }
}

Configuration System Failed to Initialize

After a long search I realised, this exception has an inner exception that tells you exactly what is wrong with your config file

How to check if a column is empty or null using SQL query select statement?

An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:

SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)

LEN becomes LENGTH and ISNULL becomes IFNULL.

MS Excel showing the formula in a cell instead of the resulting value

If you are using Excel 2013 Than do the following File > Option > Advanced > Under Display options for this worksheet: uncheck the checkbox before Show formulas in cells instead of their calculated results This should resolve the issue.

tr:hover not working

tr:hover doesn't work in old browsers.

You can use jQuery for this:

.tr-hover
{  
  background-color:#fefefe;
}
$('.list1 tr').hover(function()
{
    $(this).addClass('tr-hover');
},function()
{
    $(this).removeClass('tr-hover');
});

Set space between divs

Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.

#left{
    float: left;
    margin-right: 40px;
}
#right{
   float: left;
}

"Are you missing an assembly reference?" compile error - Visual Studio

Are you strong-naming your assemblies? In that case it is not a good idea to auto-increment your build number because with every new build number you will also have to update all your references.

HTTP Error 500.19 and error code : 0x80070021

Please <staticContent /> line and erased it from the web.config.

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

How to use BeginInvoke C#

I guess your code relates to Windows Forms.
You call BeginInvoke if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)

If BeginInvoke is called for Delegate type the delegate is just invoked asynchronously.
(Invoke for the sync version.)

If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task with the according context. (TaskScheduler.FromCurrentSynchronizationContext())

And to add a little to already said by others: Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var with lambdas: compiler needs a hint.

UPDATE:

this requires .Net v4.0 and higher

// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();

// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);

// also can be called anywhere. Task  will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked) 
task.Start(scheduler);

If you started the task from other thread and need to wait for its completition task.Wait() will block calling thread till the end of the task.

Read more about tasks here.

Jquery each - Stop loop and return object

here :

http://jsbin.com/ucuqot/3/edit

function findXX(word)
{  
  $.each(someArray, function(i,n)
  {
    $('body').append('-> '+i+'<br />');
    if(n == word)
    {
      return false;
    }   
  });  
}

Java JDBC - How to connect to Oracle using Service Name instead of SID

In case you are using eclipse to connect oracle without SID. There are two drivers to select i.e., Oracle thin driver and other is other driver. Select other drivers and enter service name in database column. Now you can connect directly using service name without SID.

Is there a limit to the length of a GET request?

The specification does not limit the length of an HTTP Get request but the different browsers implement their own limitations. For example Internet Explorer has a limitation implemented at 2083 characters.

Java regex to extract text between tags

You're on the right track. Now you just need to extract the desired group, as follows:

final Pattern pattern = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
final Matcher matcher = pattern.matcher("<tag>String I want to extract</tag>");
matcher.find();
System.out.println(matcher.group(1)); // Prints String I want to extract

If you want to extract multiple hits, try this:

public static void main(String[] args) {
    final String str = "<tag>apple</tag><b>hello</b><tag>orange</tag><tag>pear</tag>";
    System.out.println(Arrays.toString(getTagValues(str).toArray())); // Prints [apple, orange, pear]
}

private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);

private static List<String> getTagValues(final String str) {
    final List<String> tagValues = new ArrayList<String>();
    final Matcher matcher = TAG_REGEX.matcher(str);
    while (matcher.find()) {
        tagValues.add(matcher.group(1));
    }
    return tagValues;
}

However, I agree that regular expressions are not the best answer here. I'd use XPath to find elements I'm interested in. See The Java XPath API for more info.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.

@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    string cLayout = "";

    if (controller == "Webmaster")
        cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
    else
        cLayout = "~/Views/Shared/_Layout.cshtml";

    Layout = cLayout;
}

Read Complete Article here "How to Render different Layout in ASP.NET MVC"

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

By Changing The DbContext As Below;

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    }

Just adding in OnModelCreating method call to base.OnModelCreating(modelBuilder); and it becomes fine. I am using EF6.

Special Thanks To #The Senator

Error pushing to GitHub - insufficient permission for adding an object to repository database

you can using this

sudo chown -R $USER:$USER "$(git rev-parse --show-toplevel)/.git"

Best /Fastest way to read an Excel Sheet into a DataTable?

This seemed to work pretty well for me.

private DataTable ReadExcelFile(string sheetName, string path)
{

    using (OleDbConnection conn = new OleDbConnection())
    {
        DataTable dt = new DataTable();
        string Import_FileName = path;
        string fileExtension = Path.GetExtension(Import_FileName);
        if (fileExtension == ".xls")
            conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
        if (fileExtension == ".xlsx")
            conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
        using (OleDbCommand comm = new OleDbCommand())
        {
            comm.CommandText = "Select * from [" + sheetName + "$]";
            comm.Connection = conn;
            using (OleDbDataAdapter da = new OleDbDataAdapter())
            {
                da.SelectCommand = comm;
                da.Fill(dt);
                return dt;
            }
        }
    }
}

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

If you don't mind using Miniconda, the necessary external libraries and _ctypes are installed by default. It does take more space and may require using a moderately older version of Python (e.g. 3.7.6 instead of 3.8.2 as of this writing).

How to remove CocoaPods from a project?

There can be two aspects developer may face.

  • Either he wants to remove pods completely from project
  • developer wants to uninstall particular framework from project from pods.

In first case you have to use 'pod deintegrate' and follow several steps which are mentioned in the answers above.

For second case that is if you want to uninstall any particular framework which is installed there very simple way available in your pod file just comment the framework which you want to uninstall and run pod install command.

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
target 'ProjectName' do
  # Uncomment this line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

    pod 'iCarousel', '~> 1.8'
#    pod 'Facebook-iOS-SDK', '~> 4.1'
#    pod 'ParseFacebookUtilsV4', '~> 1.11'
#    pod 'Parse', '~> 1.14'


end

Here I want to uninstall facebook and parse frameworks (which were installed using pods) and not iCarousel that is why I have updated my pod file like above.

Now if I run pod install it will keep iCarousel as it is in my project and will remove facebook and parse.

How do I PHP-unserialize a jQuery-serialized form?

This is in reply to user1256561. Thanks for your idea.. however i have not taken care of the url decode stuff mentioned in step3.

so here is the php code that will decode the serialized form data, if anyone else needs it. By the way, use this code at your own discretion.

function xyz($strfromAjaxPOST)
{
    $array = "";
    $returndata = "";
    $strArray = explode("&", $strfromPOST);
    $i = 0;
    foreach ($strArray as $str)
    {
        $array = explode("=", $str);
        $returndata[$i] = $array[0];
        $i = $i + 1;
        $returndata[$i] = $array[1];
        $i = $i + 1;
    }
    print_r($returndata);
}

The url post data input will be like: attribute1=value1&attribute2=value2&attribute3=value3 and so on

Output of above code will still be in an array and you can modify it to get it assigned to any variable you want and it depends on how you want to use this data further.

Array
(
    [0] => attribute1
    [1] => value1
    [2] => attribute2
    [3] => value2
    [4] => attribute3
    [5] => value3
)

View the change history of a file using Git versioning

In Sourcetree UI (https://www.sourcetreeapp.com/), you can find history of a file by selecting 'Log Selected' option in right click context menu:

enter image description here

It would show the history of all the commits.

How do I do logging in C# without using 3rd party libraries?

I used to write my own error logging until I discovered ELMAH. I've never been able to get the emailing part down quite as perfectly as ELMAH does.

Opening PDF String in new window with javascript

window.open("data:application/pdf," + escape(pdfString)); 

The above one pasting the encoded content in URL. That makes restriction of the content length in URL and hence PDF file loading failed (because of incomplete content).

How to indent HTML tags in Notepad++

In Notepad++ v7.8.9 you can use the Tab key to increase the indention level, and use Shift + Tab to decrease the indentation level.

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

Manage toolbar's navigation and back button from fragment in android

The easiest solution I found was to simply put that in your fragment :

androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NavController navController = Navigation.findNavController(getActivity(), 
R.id.nav_host_fragment);
            navController.navigate(R.id.action_position_to_destination);
        }
    });

Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.

'router-outlet' is not a known element

In your app.module.ts file

import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
{
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full',
    component: DashboardComponent
},  
{
    path: 'dashboard',
    component: DashboardComponent
}
];

@NgModule({
imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    FormsModule               
],
declarations: [
    AppComponent,  
    DashboardComponent      
],
bootstrap: [AppComponent]
})
export class AppModule {

}

Add this code. Happy Coding.

Android RatingBar change star colors

Withou adding a new style you can use the tint color within the RatingBar

             <RatingBar
                    android:id="@+id/ratingBar"
                    style="@android:style/Widget.Holo.RatingBar.Small"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:numStars="5"
                    android:rating="4.5"
                    android:stepSize="0.5"
                    android:progressTint="@color/colorPrimary"/>

How do I cast a JSON Object to a TypeScript class?

You can cast json to property like this

class Jobs {
  constructor(JSONdata) {
    this.HEAT = JSONdata.HEAT;    
    this.HEAT_EAF = JSONdata.HEAT_EAF;    
  }
  
}

 var job = new Jobs({HEAT:'123',HEAT_EAF:'456'});

Execution failed app:processDebugResources Android Studio

In my case i had two declaration of

<?xml version="1.0" encoding="utf-8"?>

in my vector drawable icon

all i had to do was delete one

Where is GACUTIL for .net Framework 4.0 in windows 7?

VS 2012/13 Win 7 64 bit gacutil.exe is located in

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

CSS3 background image transition

Salam, this answer works only in Chrome, cause IE and FF support color transition.

There is no need to make your HTML elements opacity:0, cause some times they contain text, and no need to double your elements!.

The question with link to an example in jsfiddle needed a small change, that is to put an empty image in .title a like background:url(link to an empty image); same as you put it in .title a:hover but make it empty image, and the code will work.

.title a {
display: block;
width: 340px;
height: 338px;
color: black;
background: url(https://upload.wikimedia.org/wikipedia/commons/5/59/Empty.png) repeat;
/* TRANSISITION */
transition: background 1s;
-webkit-transition: background 1s;
-moz-transition: background 1s;
-o-transition: background 1s;
  }
  .title a:hover{   background: transparent;
   background: url(https://lh3.googleusercontent.com/-p1nr1fkWKUo/T0zUp5CLO3I/AAAAAAAAAWg/jDiQ0cUBuKA/s800/red-pattern.png) repeat;
/* TRANSISITION */
transition: background 1s;
-webkit-transition: background 1s;
-moz-transition: background 1s;
-o-transition: background 1s;
}

Check this out https://jsfiddle.net/Tobasi/vv8q9hum/

How can I insert into a BLOB column from an insert statement in sqldeveloper?

To insert a VARCHAR2 into a BLOB column you can rely on the function utl_raw.cast_to_raw as next:

insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));

It will cast your input VARCHAR2 into RAW datatype without modifying its content, then it will insert the result into your BLOB column.

More details about the function utl_raw.cast_to_raw

Prevent double submission of forms in jQuery

I can't believe the good old fashioned css trick of pointer-events: none hasn't been mentioned yet. I had the same issue by adding a disabled attribute but this doesn't post back. Try the below and replace #SubmitButton with the ID of your submit button.

$(document).on('click', '#SubmitButton', function () {
    $(this).css('pointer-events', 'none');
})

Strange Jackson exception being thrown when serializing Hibernate object

Similar to other answers, the problem for me was declaring a many-to-one column to do lazy fetching. Switching to eager fetching fixed the problem. Before:

@ManyToOne(targetEntity = StatusCode.class, fetch = FetchType.LAZY)

After:

@ManyToOne(targetEntity = StatusCode.class, fetch = FetchType.EAGER)

Can't start hostednetwork

First check if your wlan card support hosted network and if no update the card driver. Follow this steps

1) open cmd with administrative rights
2) on the black screen type: netsh wlan show driver | findstr Hosted
3) See Hosted network supported, if No then update drivers

enter image description here

How to resize images proportionally / keeping the aspect ratio?

I think this is a really cool method:

 /**
  * Conserve aspect ratio of the original region. Useful when shrinking/enlarging
  * images to fit into a certain area.
  *
  * @param {Number} srcWidth width of source image
  * @param {Number} srcHeight height of source image
  * @param {Number} maxWidth maximum available width
  * @param {Number} maxHeight maximum available height
  * @return {Object} { width, height }
  */
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return { width: srcWidth*ratio, height: srcHeight*ratio };
 }

display Java.util.Date in a specific format

How about:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));

> 31/05/2011

How to print a percentage value in python?

Then you'd want to do this instead:

print str(int(1.0/3.0*100))+'%'

The .0 denotes them as floats and int() rounds them to integers afterwards again.

Markdown: continue numbered list

If you don't want the lines in between the list items to be indented, like user Mars mentioned in his comment, you can use pandoc's example_lists feature. From their docs:

(@)  My first example will be numbered (1).
(@)  My second example will be numbered (2).

Explanation of examples.

(@)  My third example will be numbered (3).

How to convert Json array to list of objects in c#

Did you check this line works perfectly & your string have value in it ?

string jsonString = sr.ReadToEnd();

if yes, try this code for last line:

ValueSet items = JsonConvert.DeserializeObject<ValueSet>(jsonString);

or if you have an array of json you can use list like this :

List<ValueSet> items = JsonConvert.DeserializeObject<List<ValueSet>>(jsonString);

good luck

How to get the separate digits of an int number?

I haven't seen anybody use this method, but it worked for me and is short and sweet:

int num = 5542;
String number = String.valueOf(num);
for(int i = 0; i < number.length(); i++) {
    int j = Character.digit(number.charAt(i), 10);
    System.out.println("digit: " + j);
}

This will output:

digit: 5
digit: 5
digit: 4
digit: 2

Javascript callback when IFRAME is finished loading?

I have had to do this in cases where documents such as word docs and pdfs were being streamed to the iframe and found a solution that works pretty well. The key is handling the onreadystatechanged event on the iframe.

Lets say the name of your frame is "myIframe". First somewhere in your code startup (I do it inline any where after the iframe) add something like this to register the event handler:

document.getElementById('myIframe').onreadystatechange = MyIframeReadyStateChanged;

I was not able to use an onreadystatechage attribute on the iframe, I can't remember why, but the app had to work in IE 7 and Safari 3, so that may of been a factor.

Here is an example of a how to get the complete state:

function MyIframeReadyStateChanged()
{
    if(document.getElementById('myIframe').readyState == 'complete')
    {
        // Do your complete stuff here.
    }
}

Will iOS launch my app into the background if it was force-quit by the user?

Actually if you need to test background fetch you need to enable one option in scheme:

enabling bg fetch

Another way how you can test it: simulate bg fetch

Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html

Javascript - object key->value

I use the following syntax:

objTest = {"error": true, "message": "test message"};

get error:

 var name = "error"
 console.log(objTest[name]);

get message:

 name = "message"
 console.log(objTest[name]);

How to export html table to excel or pdf in php

If all you want is a simple excel worksheet try this:

header('Content-type: application/excel');
$filename = 'filename.xls';
header('Content-Disposition: attachment; filename='.$filename);

$data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
    <!--[if gte mso 9]>
    <xml>
        <x:ExcelWorkbook>
            <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                    <x:Name>Sheet 1</x:Name>
                    <x:WorksheetOptions>
                        <x:Print>
                            <x:ValidPrinterInfo/>
                        </x:Print>
                    </x:WorksheetOptions>
                </x:ExcelWorksheet>
            </x:ExcelWorksheets>
        </x:ExcelWorkbook>
    </xml>
    <![endif]-->
</head>

<body>
   <table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>
</body></html>';

echo $data;

The key here is the xml data. This will keep excel from complaining about the file.

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

This does not directly answer your question, but have you had a look at Litmus? We tend to use it mostly for testing HTML/CSS compatibility across multiple browsers (supported by Litmus).

How to sparsely checkout only one single file from a git repository?

If you need a specific file from a specific branch from a remote Git repository the command is:

git archive --remote=git://git.example.com/project.git refs/heads/mybranch path/to/myfile |tar xf -

The rest can be derived from @VonC's answer:

If you need a specific file from the master branch it is:

git archive --remote=git://git.example.com/project.git HEAD path/to/myfile |tar xf -

If you need a specific file from a tag it is:

git archive --remote=git://git.example.com/project.git mytag path/to/myfile |tar xf -

How to generate UL Li list from string array using jquery?

var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i)
{
    var li = $('<li/>')
        .addClass('ui-menu-item')
        .attr('role', 'menuitem')
        .appendTo(cList);
    var aaa = $('<a/>')
        .addClass('ui-all')
        .text(countries[i])
        .appendTo(li);
});

Fixed header table with horizontal scrollbar and vertical scrollbar on

If this is what you want only HTML and CSS solution

fiddle

Here's the HTML

<div class="outer-container"> <!-- absolute positioned container -->
<div class="inner-container">

    <div class="table-header">
        <table id="headertable" width="100%" cellpadding="0" cellspacing="0">
            <thead>
                <tr>
                    <th class="header-cell col1">One</th>
                    <th class="header-cell col2">Two</th>
                    <th class="header-cell col3">Three</th>
                    <th class="header-cell col4">Four</th>
                    <th class="header-cell col5">Five</th>
                </tr>
            </thead>
        </table>
    </div>

    <div class="table-body">
        <table id="bodytable" width="100%" cellpadding="0" cellspacing="0">
            <tbody>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
                <tr>
                    <td class="body-cell col1">body row1</td>
                    <td class="body-cell col2">body row2</td>
                    <td class="body-cell col3">body row2</td>
                    <td class="body-cell col4">body row2</td>
                    <td class="body-cell col5">body row2 en nog meer</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</div>

And this is the css

body {
margin:0;
padding:0;
height: 100%;
width: 100%;
}
table {
    border-collapse: collapse; /* make simple 1px lines borders if border defined */
}
tr {
    width: 100%;
}

.outer-container {
    background-color: #ccc;
    position: absolute;
    top:0;
    left: 0;
    right: 300px;
    bottom:40px;
    overflow: scroll;

}
.inner-container {
    width: 100%;
    height: 100%;
    position: relative;
    overflow-x: visible;
    overflow-y:visible;
}
.table-header {
    float:left;
    width: 100%;
}
.table-body {
    float:left;
    height: auto;
    width: auto;
    overflow: visible;
    background-color: red;
}
.header-cell {
    background-color: yellow;
    text-align: left;
    height: 40px;
}
.body-cell {
    background-color: transparent;
    text-align: left;
}
.col1, .col3, .col4, .col5 {
    width:120px;
    min-width: 120px;
}
.col2 {
    min-width: 300px;
}

Let me know if this is what you need. Or some thing is missing. I went through the other answers and found that jquery has been used . I took it on assumption that you need css solution . If I am missing any more point please mention :)

How to upload files to server using Putty (ssh)

You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.

What's HTML character code 8203?

ZERO WIDTH SPACE.

I've used it as content for "empty" table cells. No idea what it's doing in a <script> tag, though.

How to use boolean 'and' in Python

Try this:

i = 5
ii = 10
if i == 5 and ii == 10:
      print "i is 5 and ii is 10"

Edit: Oh, and you dont need that semicolon on the last line (edit to remove it from my code).

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

I had the same its because of version incompatibility check for version or remove version if using spring boot

How do I debug error ECONNRESET in Node.js?

Had the same problem today. After some research i found a very useful --abort-on-uncaught-exception node.js option. Not only it provides much more verbose and useful error stack trace, but also saves core file on application crash allowing further debug.

Reading CSV files using C#

I recommend CsvHelper from Nuget.

PS: Regarding other more upvoted answers, I'm sorry but adding a reference to Microsoft.VisualBasic is:

  • Ugly
  • Not cross-platform, because it's not available in .NETCore/.NET5 (and Mono never had very good support of Visual Basic, so it may be buggy).

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

'Incorrect SET Options' Error When Building Database Project

For me, just setting the compatibility level to higher level works fine. To see C.Level :

select compatibility_level from sys.databases where name = [your_database]

Postgres: check if array field contains value?

This worked for me:

select * from mytable
where array_to_string(pub_types, ',') like '%Journal%'

Depending on your normalization needs, it might be better to implement a separate table with a FK reference as you may get better performance and manageability.

Using JQuery to check if no radio button in a group has been checked

I think this is a simple example, how to check if a radio in a group of radios was checked.

if($('input[name=html_elements]:checked').length){
    //a radio button was checked
}else{
    //there was no radio button checked
} 

How to make CSS width to fill parent?

So after research the following is discovered:

For a div#bar setting display:block; width: auto; causes the equivalent of outerWidth:100%;

For a table#bar you need to wrap it in a div with the rules stated below. So your structure becomes:

<div id="foo">
 <div id="barWrap" style="border....">
  <table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">

This way the table takes up the parent div 100%, and #barWrap is used to add borders/margin/padding to the #bar table. Note that you will need to set the background of the whole thing in #barWrap and have #bar's background be transparent or the same as #barWrap.

For textarea#bar and input#bar you need to do the same thing as table#bar, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.

Npm Error - No matching version found for

Try removing "package-lock.json" and running "npm install && npm update", it'll install the latest version and clear all errors.

jQuery click events firing multiple times

.one()

A better option would be .one() :

The handler is executed at most once per element per event type.

$(".bet").one('click',function() {
    //Your function
});

In case of multiple classes and each class needs to be clicked once,

$(".bet").on('click',function() {
    //Your function
    $(this).off('click');   //or $(this).unbind()
});

how to assign a block of html code to a javascript variable

Modern Javascript implementations with the template syntax using backticks are also an easy way to assign an HTML block of code to a variable:

    const firstName = 'Sam';
    const fullName = 'Sam Smith';
    const htmlString = `<h1>Hello ${fullName}!</h1><p>This is some content \
        that will display. You can even inject your first name, ${firstName}, \
        in the code.</p><p><a href="http://www.google.com">Search</a> for \
        stuff on the Google website.</p>`;

Can I serve multiple clients using just Flask app.run() as standalone?

Using the simple app.run() from within Flask creates a single synchronous server on a single thread capable of serving only one client at a time. It is intended for use in controlled environments with low demand (i.e. development, debugging) for exactly this reason.

Spawning threads and managing them yourself is probably not going to get you very far either, because of the Python GIL.

That said, you do still have some good options. Gunicorn is a solid, easy-to-use WSGI server that will let you spawn multiple workers (separate processes, so no GIL worries), and even comes with asynchronous workers that will speed up your app (and make it more secure) with little to no work on your part (especially with Flask).

Still, even Gunicorn should probably not be directly publicly exposed. In production, it should be used behind a more robust HTTP server; nginx tends to go well with Gunicorn and Flask.

Print multiple arguments in Python

This was probably a casting issue. Casting syntax happens when you try to combine two different types of variables. Since we cannot convert a string to an integer or float always, we have to convert our integers into a string. This is how you do it.: str(x). To convert to a integer, it's: int(x), and a float is float(x). Our code will be:

print('Total score for ' + str(name) + ' is ' + str(score))

Also! Run this snippet to see a table of how to convert different types of variables!

_x000D_
_x000D_
<table style="border-collapse: collapse; width: 100%;background-color:maroon; color: #00b2b2;">
<tbody>
<tr>
<td style="width: 50%;font-family: serif; padding: 3px;">Booleans</td>
<td style="width: 50%;font-family: serif; padding: 3px;"><code>bool()</code></td>
  </tr>
 <tr>
<td style="width: 50%;font-family: serif;padding: 3px">Dictionaries</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>dict()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Floats</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>float()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding:3px">Integers</td>
<td style="width: 50%;font-family: serif;padding:3px;"><code>int()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Lists</td>
<td style="width: 50%font-family: serif;padding: 3px;"><code>list()</code></td>
</tr>
</tbody>
</table>
_x000D_
_x000D_
_x000D_

Sort an array of objects in React and render them

Try lodash sortBy

import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
    console.log("application")
    )
)

Read more : lodash.sortBy

Convert alphabet letters to number in Python

Here is my solution for a problem where you want to convert all the letters in a string with position of those letters in English alphabet and return a string of those nos.

https://gist.github.com/bondnotanymore/e0f1dcaacfb782348e74fac8b224769e

Let me know if you want to understand it in detail.I have used the following concepts - List comprehension - Dictionary comprehension

ByRef argument type mismatch in Excel VBA

I suspect you haven't set up last_name properly in the caller.

With the statement Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)

this will only work if last_name is a string, i.e.

Dim last_name as String

appears in the caller somewhere.

The reason for this is that VBA passes in variables by reference by default which means that the data types have to match exactly between caller and callee.

Two fixes:

1) Force ByVal -- Change your function to pass variable ByVal:
Public Function ProcessString(ByVal input_string As String) As String, or

2) Dim varname -- put Dim last_name As String in the caller before you use it.

(1) works because for ByVal, a copy of input_string is taken when passing to the function which will coerce it into the correct data type. It also leads to better program stability since the function cannot modify the variable in the caller.

How to obtain the total numbers of rows from a CSV file in Python?

Several of the above suggestions count the number of LINES in the csv file. But some CSV files will contain quoted strings which themselves contain newline characters. MS CSV files usually delimit records with \r\n, but use \n alone within quoted strings.

For a file like this, counting lines of text (as delimited by newline) in the file will give too large a result. So for an accurate count you need to use csv.reader to read the records.

JavaScript string newline character?

you can use <br/> and the document.write/, document.writeln one.

Find and kill a process in one line using bash and regex

The solution would be filtering the processes with exact pattern , parse the pid, and construct an argument list for executing kill processes:

ps -ef  | grep -e <serviceNameA> -e <serviceNameB> -e <serviceNameC> |
awk '{print $2}' | xargs sudo kill -9

Explanation from documenation:

ps utility displays a header line, followed by lines containing information about all of your processes that have controlling terminals.

-e Display information about other users' processes, including those

-f Display the uid, pid, parent pid, recent CPU usage, process start

The grep utility searches any given input files, selecting lines that

-e pattern, --regexp=pattern Specify a pattern used during the search of the input: an input line is selected if it matches any of the specified patterns. This option is most useful when multiple -e options are used to specify multiple patterns, or when a pattern begins with a dash (`-').

xargs - construct argument list(s) and execute utility

kill - terminate or signal a process

number 9 signal - KILL (non-catchable, non-ignorable kill)

Example:

ps -ef  | grep -e node -e loggerUploadService.sh - -e applicationService.js |
awk '{print $2}' | xargs sudo kill -9

jQuery datepicker set selected date, on the fly

This example shows of how to use default value in the dropdown calendar and value in the text box. It also shows how to set default value to previous date.

selectedDate is another variable that holds current selected date of the calendar control

    var date = new Date();
    date.setDate(date.getDate() - 1);

    $("#datepicker").datepicker({
        dateFormat: "yy-mm-dd",
        defaultDate: date,
        onSelect: function () {
            selectedDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
        }
    });

    $("#datepicker").datepicker("setDate", date);

Copy table to a different database on a different SQL Server

Create the database, with Script Database as... CREATE To

Within SSMS on the source server, use the export wizard with the destination server database as the destination.

  • Source instance > YourDatabase > Tasks > Export data
  • Data Soure = SQL Server Native Client
    • Validate/enter Server & Database
  • Destination = SQL Server Native Client
    • Validate/enter Server & Database
  • Follow through wizard

how to make a div to wrap two float divs inside?

Here i show you a snippet where your problem is solved (i know, it's been too long since you posted it, but i think this is cleaner than de "clear" fix)

_x000D_
_x000D_
#nav_x000D_
        {_x000D_
            float: left;_x000D_
            width: 25%;_x000D_
            height: 150px;_x000D_
            background-color: #999;_x000D_
            margin-bottom: 10px;_x000D_
        }_x000D_
_x000D_
        #content_x000D_
        {_x000D_
            float: left;_x000D_
            margin-left: 1%;_x000D_
            width: 65%;_x000D_
            height: 150px;_x000D_
            background-color: #999;_x000D_
            margin-bottom: 10px;_x000D_
        }       _x000D_
        #wrap_x000D_
        {_x000D_
          background-color:#DDD;_x000D_
          overflow: hidden_x000D_
        }
_x000D_
    <div id="wrap">_x000D_
    <h1>wrap1 </h1>_x000D_
    <div id="nav"></div>_x000D_
    <div id="content"><a href="index.htm">&lt; Back to article</a></div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How To Add An "a href" Link To A "div"?

In this case, it doesn't matter as there is no content between the two divs.

Either one will get the browser to scroll down to it.

The a element will look like:

<a href="mypageName.html#buttonOne">buttonOne</a>

Or:

<a href="mypageName.html#linkedinB">linkedinB</a>

How can I extract substrings from a string in Perl?

Well, a one liner here:

perl -lne 'm|Scheme ID:\s+(.*?)\s+\((.*?)\)\s?(\*)?|g&&print "$1:$2:$3"' file.txt

Expanded to a simple script to explain things a bit better:

#!/usr/bin/perl -ln              

#-w : warnings                   
#-l : print newline after every print                               
#-n : apply script body to stdin or files listed at commandline, dont print $_           

use strict; #always do this.     

my $regex = qr{  # precompile regex                                 
  Scheme\ ID:      # to match beginning of line.                      
  \s+              # 1 or more whitespace                             
  (.*?)            # Non greedy match of all characters up to         
  \s+              # 1 or more whitespace                             
  \(               # parenthesis literal                              
    (.*?)            # non-greedy match to the next                     
  \)               # closing literal parenthesis                      
  \s*              # 0 or more whitespace (trailing * is optional)    
  (\*)?            # 0 or 1 literal *s                                
}x;  #x switch allows whitespace in regex to allow documentation.   

#values trapped in $1 $2 $3, so do whatever you need to:            
#Perl lets you use any characters as delimiters, i like pipes because                    
#they reduce the amount of escaping when using file paths           
m|$regex| && print "$1 : $2 : $3";

#alternatively if(m|$regex|) {doOne($1); doTwo($2) ... }     

Though if it were anything other than formatting, I would implement a main loop to handle files and flesh out the body of the script rather than rely ing on the commandline switches for the looping.

What is the use of the @ symbol in PHP?

It suppresses error messages — see Error Control Operators in the PHP manual.

How to check if string input is a number?

EDITED: You could also use this below code to find out if its a number or also a negative

import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
    print "given string is number"

you could also change your format to your specific requirement. I am seeing this post a little too late.but hope this helps other persons who are looking for answers :) . let me know if anythings wrong in the given code.

Rails formatting date

Use

Model.created_at.strftime("%FT%T")

where,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method:

Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)

For the complete list of formats for strftime method please visit APIDock

Making a PowerShell POST request if a body param starts with '@'

You should be able to do the following:

$params = @{"@type"="login";
 "username"="[email protected]";
 "password"="yyy";
}

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params

This will send the post as the body. However - if you want to post this as a Json you might want to be explicit. To post this as a JSON you can specify the ContentType and convert the body to Json by using

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

Extra: You can also use the Invoke-RestMethod for dealing with JSON and REST apis (which will save you some extra lines for de-serializing)

jQuery issue in Internet Explorer 8

I had the same problems.

I solved it verifying that IE8 was not configured correctly to reach the SRC URL.

I changed this, it works right.

How do I find out what version of Sybase is running

Try running below command (Works on both windows and linux)

isql -v

How to export table as CSV with headings on Postgresql?

instead of just table name, you can also write a query for getting only selected column data.

COPY (select id,name from tablename) TO 'filepath/aa.csv' DELIMITER ',' CSV HEADER;

with admin privilege

\COPY (select id,name from tablename) TO 'filepath/aa.csv' DELIMITER ',' CSV HEADER;

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

How can I print variable and string on same line in Python?

Python is a very versatile language. You may print variables by different methods. I have listed below five methods. You may use them according to your convenience.

Example:

a = 1
b = 'ball'

Method 1:

print('I have %d %s' % (a, b))

Method 2:

print('I have', a, b)

Method 3:

print('I have {} {}'.format(a, b))

Method 4:

print('I have ' + str(a) + ' ' + b)

Method 5:

print(f'I have {a} {b}')

The output would be:

I have 1 ball

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

"location" directive should be inside a 'server' directive, e.g.

server {
    listen       8765;

    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$uri$is_args$args;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Algorithm: efficient way to remove duplicate integers from an array

Use bloom filter for hashing. This will reduce the memory overhead very significantly.

Getting value from appsettings.json in .net core

In my case it was simple as using the Bind() method on the Configuration object. And then add the object as singleton in the DI.

var instructionSettings = new InstructionSettings();
Configuration.Bind("InstructionSettings", instructionSettings);
services.AddSingleton(typeof(IInstructionSettings), (serviceProvider) => instructionSettings);

The Instruction object can be as complex as you want.

{  
 "InstructionSettings": {
    "Header": "uat_TEST",
    "SVSCode": "FICA",
    "CallBackUrl": "https://UATEnviro.companyName.co.za/suite/webapi/receiveCallback",
    "Username": "s_integrat",
    "Password": "X@nkmail6",
    "Defaults": {
    "Language": "ENG",
    "ContactDetails":{
       "StreetNumber": "9",
       "StreetName": "Nano Drive",
       "City": "Johannesburg",
       "Suburb": "Sandton",
       "Province": "Gauteng",
       "PostCode": "2196",
       "Email": "[email protected]",
       "CellNumber": "0833 468 378",
       "HomeNumber": "0833 468 378",
      }
      "CountryOfBirth": "710"
    }
  }

Spark java.lang.OutOfMemoryError: Java heap space

I have few suggession for the above mentioned error.

? Check executor memory assigned as an executor might have to deal with partitions requiring more memory than what is assigned.

? Try to see if more shuffles are live as shuffles are expensive operations since they involve disk I/O, data serialization, and network I/O

? Use Broadcast Joins

? Avoid using groupByKeys and try to replace with ReduceByKey

? Avoid using huge Java Objects wherever shuffling happens

@AspectJ pointcut for all methods of a class with specific annotation

I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.

@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
    /**
     * It is the parameter is to show arguments in the method or the class.
     */
    boolean showArguments() default false;
}


@Aspect
@Component
public class AnnotationLoggerAspect {
    
    @Autowired 
    private Logger logger;  
    
    private static final String METHOD_NAME   = "METHOD NAME: {} ";
    private static final String ARGUMENTS     = "ARGS: {} ";
    
    @Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
    public void logAdviceExecutionBefore(JoinPoint joinPoint){  
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
        AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
        if(annotationLogger!= null) {
            StringBuilder annotationLoggerFormat = new StringBuilder();
            List<Object> annotationLoggerArguments = new ArrayList<>();
            annotationLoggerFormat.append(METHOD_NAME);
            annotationLoggerArguments.add(codeSignature.getName());
            
            if (annotationLogger.showArguments()) {
                annotationLoggerFormat.append(ARGUMENTS);
                List<?> argumentList = Arrays.asList(joinPoint.getArgs());
                annotationLoggerArguments.add(argumentList.toString());
            }
            logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
        }
    }
    
    private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
        AnnotationLogger annotationLogger = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = joinPoint.getTarget().getClass().
                    getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());
            
            if (method.isAnnotationPresent(AnnotationLogger.class)){
                annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
            }else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
                annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
            }
            return annotationLogger;
        }catch(Exception e) {
            return annotationLogger;
        }
    }
}

Android Studio with Google Play Services

I've got this working after doing the following:

  • Have the google-play-services-lib as a module (note difference between module and project), then add the google-play-services.jar to your models "libs" directory.
  • After that add the jar to your build path through making a library or add the jar to another library. I generally have a single IDEA library which I add all my /libs/*.jar files to.
  • Add the library to your modules build path through Module Settings (F4).
  • Add the google-play-services-lib as a module dependency to your project.
  • Done!

Note: This doesn't give me the runtime exceptions either, it works.

difference between System.out.println() and System.err.println()

It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:

public class PrintQueue {
    public static void main(String[] args) {
        for(int i = 0; i < 100; i++) {
            System.out.println("out");
            System.err.println("err");
        }
    }
}

If you compile and run the program, you will see that the order of outputs in console is mixed up.

An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.

Even in this code snippet you can see that the order is mixed up sometimes:

public class PrintQueue {
    public static void main(String[] args) {
        System.out.println("out");
        System.err.println("err");
    }
}

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

Append an empty row in dataframe using pandas

You can add it by appending a Series to the dataframe as follows. I am assuming by blank you mean you want to add a row containing only "Nan". You can first create a Series object with Nan. Make sure you specify the columns while defining 'Series' object in the -Index parameter. The you can append it to the DF. Hope it helps!

from numpy import nan as Nan
import pandas as pd

>>> df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
...                     'B': ['B0', 'B1', 'B2', 'B3'],
...                     'C': ['C0', 'C1', 'C2', 'C3'],
...                     'D': ['D0', 'D1', 'D2', 'D3']},
...                     index=[0, 1, 2, 3])

>>> s2 = pd.Series([Nan,Nan,Nan,Nan], index=['A', 'B', 'C', 'D'])
>>> result = df1.append(s2)
>>> result
     A    B    C    D
0   A0   B0   C0   D0
1   A1   B1   C1   D1
2   A2   B2   C2   D2
3   A3   B3   C3   D3
4  NaN  NaN  NaN  NaN

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Two ways to do it...

GROUP BY

SELECT RES.[CUSTOMER ID], RES,NAME, SUM(INV.AMOUNT) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
GROUP BY RES.[CUSTOMER ID], RES,NAME

OVER

SELECT RES.[CUSTOMER ID], RES,NAME, 
       SUM(INV.AMOUNT) OVER (PARTITION RES.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]

vb.net get file names in directory?

You will need to use the IO.Directory.GetFiles function.

Dim files() As String = IO.Directory.GetFiles("c:\")

For Each file As String In files
  ' Do work, example
  Dim text As String = IO.File.ReadAllText(file)
Next

How can we dynamically allocate and grow an array

Lets take a case when you have an array of 1 element, and you want to extend the size to accommodate 1 million elements dynamically.

Case 1:

String [] wordList = new String[1];
String [] tmp = new String[wordList.length + 1];
for(int i = 0; i < wordList.length ; i++){
    tmp[i] = wordList[i];
}
wordList = tmp;

Case 2 (increasing size by a addition factor):

String [] wordList = new String[1];
String [] tmp = new String[wordList.length + 10];
for(int i = 0; i < wordList.length ; i++){
    tmp[i] = wordList[i];
}
wordList = tmp;

Case 3 (increasing size by a multiplication factor):

String [] wordList = new String[1];
String [] tmp = new String[wordList.length * 2];
for(int i = 0; i < wordList.length ; i++){
    tmp[i] = wordList[i];
}
wordList = tmp;

When extending the size of an Array dynamically, using Array.copy or iterating over the array and copying the elements to a new array using the for loop, actually iterates over each element of the array. This is a costly operation. Array.copy would be clean and optimized, still costly. So, I'd suggest increasing the array length by a multiplication factor.

How it helps is,

In case 1, to accommodate 1 million elements you have to increase the size of array 1 million - 1 times i.e. 999,999 times.

In case 2, you have to increase the size of array 1 million / 10 - 1 times i.e. 99,999 times.

In case 3, you have to increase the size of array by log21 million - 1 time i.e. 18.9 (hypothetically).

Is an HTTPS query string secure?

SSL first connects to the host, so the host name and port number are transferred as clear text. When the host responds and the challenge succeeds, the client will encrypt the HTTP request with the actual URL (i.e. anything after the third slash) and and send it to the server.

There are several ways to break this security.

It is possible to configure a proxy to act as a "man in the middle". Basically, the browser sends the request to connect to the real server to the proxy. If the proxy is configured this way, it will connect via SSL to the real server but the browser will still talk to the proxy. So if an attacker can gain access of the proxy, he can see all the data that flows through it in clear text.

Your requests will also be visible in the browser history. Users might be tempted to bookmark the site. Some users have bookmark sync tools installed, so the password could end up on deli.ci.us or some other place.

Lastly, someone might have hacked your computer and installed a keyboard logger or a screen scraper (and a lot of Trojan Horse type viruses do). Since the password is visible directly on the screen (as opposed to "*" in a password dialog), this is another security hole.

Conclusion: When it comes to security, always rely on the beaten path. There is just too much that you don't know, won't think of and which will break your neck.

How do I read image data from a URL in Python?

Python 3

from urllib.request import urlopen
from PIL import Image

img = Image.open(urlopen(url))
img

Jupyter Notebook and IPython

import IPython
url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
IPython.display.Image(url, width = 250)

Unlike other methods, this method also works in a for loop!

Min and max value of input in angular4 application

You can write a directive to listen the change event on the input and reset the value to the min value if it is too low. StackBlitz

@HostListener('change') onChange() {
  const min = +this.elementRef.nativeElement.getAttribute('min');

  if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
    this.renderer2.setProperty(
      this.elementRef.nativeElement,
      'value',
      min + ''
    );
  }
}

Also listen for the ngModelChange event to do the same when the form value is set.

@HostListener('ngModelChange', ['$event'])
onModelChange(value: number) {
  const min = +this.elementRef.nativeElement.getAttribute('min');
  if (this.valueIsLessThanMin(min, value)) {
    const formControl = this.formControlName
      ? this.formControlName.control
      : this.formControlDirective.control;

    if (formControl) {
      if (formControl.updateOn === 'change') {
        console.warn(
          `minValueDirective: form control ${this.formControlName.name} is set to update on change
          this can cause issues with min update values.`
        );
      }
      formControl.reset(min);
    }
  }
}

Full code:

import {
  Directive,
  ElementRef,
  HostListener,
  Optional,
  Renderer2,
  Self
} from "@angular/core";
import { FormControlDirective, FormControlName } from "@angular/forms";

@Directive({
  // tslint:disable-next-line: directive-selector
  selector: "input[minValue][min][type=number]"
})
export class MinValueDirective {
  @HostListener("change") onChange() {
    const min = +this.elementRef.nativeElement.getAttribute("min");

    if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
      this.renderer2.setProperty(
        this.elementRef.nativeElement,
        "value",
        min + ""
      );
    }
  }

  // if input is a form control validate on model change
  @HostListener("ngModelChange", ["$event"])
  onModelChange(value: number) {
    const min = +this.elementRef.nativeElement.getAttribute("min");
    if (this.valueIsLessThanMin(min, value)) {
      const formControl = this.formControlName
        ? this.formControlName.control
        : this.formControlDirective.control;

      if (formControl) {
        if (formControl.updateOn === "change") {
          console.warn(
            `minValueDirective: form control ${
              this.formControlName.name
            } is set to update on change
              this can cause issues with min update values.`
          );
        }
        formControl.reset(min);
      }
    }
  }

  constructor(
    private elementRef: ElementRef<HTMLInputElement>,
    private renderer2: Renderer2,
    @Optional() @Self() private formControlName: FormControlName,
    @Optional() @Self() private formControlDirective: FormControlDirective
  ) {}

  private valueIsLessThanMin(min: any, value: number): boolean {
    return typeof min === "number" && value && value < min;
  }
}

Make sure to use this with the form control set to updateOn blur or the user won't be able to enter a +1 digit number if the first digit is below the min value.

 this.formGroup = this.formBuilder.group({
    test: [
      null,
      {
        updateOn: 'blur',
        validators: [Validators.min(5)]
      }
    ]
  });

How to change an application icon programmatically in Android?

Programatically, you may want to publish the application launcher yourself :

Note: this method no longer works starting with Android 8.0 - Oreo

In your AndroidManifest.xml, add :

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

Then you need create your app launcher intent:

Intent myLauncherIntent = new Intent();
myLauncherIntent.setClassName("your.package.name", "YourLauncherActivityName");
myLauncherIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Create an install shortcut intent with your app launcher and custom icon:

Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myLauncherIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Application Name");
intent.putExtra
       (
        Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
        Intent.ShortcutIconResource.fromContext
                                    (
                                         getApplicationContext(), 
                                         R.drawable.app_icon
                                    )
       );
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");

And finally launch the broadcast intent:

getApplicationContext().sendBroadcast(intent);

XAMPP Apache won't start

I experienced this issue and I preferred to free up the port .80 and my XAMPP/Apache restarted again. This is how I made the port .80 free. First: -Open a command prompt and type this :

netstat -aon | findstr :80

You'll get this display:enter image description here

Then type this command:

tasklist /fi "pid eq 4"

You'll get the name of the process using the is displayed. Now, press: Win+R services.msc in the invite, then press Ok. Now you can start stopping all services which can use the port .80.

Find some of them here: W3SVC,WAS,SSRS,PeerDistSvc,NcbService.

How can I set a custom baud rate on Linux?

There is an serial I/O chip on your motherboard's CPU (16650 UART). This chip uses 8-bit port as control and data bus, and thus you can issue a command to it through writing to this chip through the control and data bus.

Usually, an application did the following steps on the serial port

  1. Set baud rate, parity, encoding, flow control, and starting / ending sequence length during program start. This setup can be done via ioctl to the serial device or 'stty' command. In fact, the stty command uses ioctl to that serial device.
  2. Write characters of data to the serial device and the driver will be writing data charaters to the UART chip through its 8-bit data bus.

In short, you can specify the baud rate only in the STTY command, and then all other options would be kept as default, and it should enough to connect to ohter devices.

Python: Find index of minimum item in list of floats

I would use:

val, idx = min((val, idx) for (idx, val) in enumerate(my_list))

Then val will be the minimum value and idx will be its index.