Programs & Examples On #Webrequest

WebRequest is a abstract class in .NET Framework for making requests to URIs (including HTTP, HTTPS, FTP and FILE protocols).

Cannot set some HTTP headers when using System.Net.WebRequest

The above answers are all fine, but the essence of the issue is that some headers are set one way, and others are set other ways. See above for 'restricted header' lists. FOr these, you just set them as a property. For others, you actually add the header. See here.

    request.ContentType = "application/x-www-form-urlencoded";

    request.Accept = "application/json";

    request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + info.clientId + ":" + info.clientSecret);

How do you send an HTTP Get Web Request in Python?

In Python, you can use urllib2 (http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

Simply enough:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

To pass GET/POST parameters the urllib.urlencode() function can be used. For more information, you can refer to the Official Urllib2 Tutorial

Which versions of SSL/TLS does System.Net.WebRequest support?

This is an important question. The SSL 3 protocol (1996) is irreparably broken by the Poodle attack published 2014. The IETF have published "SSLv3 MUST NOT be used". Web browsers are ditching it. Mozilla Firefox and Google Chrome have already done so.

Two excellent tools for checking protocol support in browsers are SSL Lab's client test and https://www.howsmyssl.com/ . The latter does not require Javascript, so you can try it from .NET's HttpClient:

// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");

File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);

// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");

The result is damning:

Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.

That's concerning. It's comparable to 2006's Internet Explorer 7.

To list exactly which protocols a HTTP client supports, you can try the version-specific test servers below:

var test_servers = new Dictionary<string, string>();
test_servers["SSL 2"] = "https://www.ssllabs.com:10200";
test_servers["SSL 3"] = "https://www.ssllabs.com:10300";
test_servers["TLS 1.0"] = "https://www.ssllabs.com:10301";
test_servers["TLS 1.1"] = "https://www.ssllabs.com:10302";
test_servers["TLS 1.2"] = "https://www.ssllabs.com:10303";

var supported = new Func<string, bool>(url =>
{
    try { return new HttpClient().GetAsync(url).Result.IsSuccessStatusCode; }
    catch { return false; }
});

var supported_protocols = test_servers.Where(server => supported(server.Value));
Console.WriteLine(string.Join(", ", supported_protocols.Select(x => x.Key)));

I'm using .NET Framework 4.6.2. I found HttpClient supports only SSL 3 and TLS 1.0. That's concerning. This is comparable to 2006's Internet Explorer 7.


Update: It turns HttpClient does support TLS 1.1 and 1.2, but you have to turn them on manually at System.Net.ServicePointManager.SecurityProtocol. See https://stackoverflow.com/a/26392698/284795

I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?

How to use WebRequest to POST some data and read response?

From MSDN

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();

Take into account that the information must be sent in the format key1=value1&key2=value2

HttpWebRequest using Basic authentication

First thing, for me ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 worked instead of Ssl3.

Secondly, I had to send the Basic Auth request along with some data (form-urlencoded). Here is the complete sample which worked for me perfectly, after trying many solutions.

Disclaimer: The code below is a mixture of solutions found on this link and some other stackoverflow links, thanks for the useful information.

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        String username = "user_name";
        String password = "password";
        String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

        //Form Data
        var formData = "var1=val1&var2=val2";
        var encodedFormData = Encoding.ASCII.GetBytes(formData);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("THE_URL");
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        request.ContentLength = encodedFormData.Length;
        request.Headers.Add("Authorization", "Basic " + encoded);
        request.PreAuthenticate = true;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(encodedFormData, 0, encodedFormData.Length);
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Cannot send a content-body with this verb-type

I had the similar issue using Flurl.Http:

Flurl.Http.FlurlHttpException: Call failed. Cannot send a content-body with this verb-type. GET http://******:8301/api/v1/agents/**** ---> System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.

The problem was I used .WithHeader("Content-Type", "application/json") when creating IFlurlRequest.

How to get json response using system.net.webrequest in c#?

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place

How do I use WebRequest to access an SSL encrypted site using https?

This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

Since no answers were posted, I found the following here:

The Web server (running the Web site) thinks that the request submitted by the client (e.g. your Web browser or our CheckUpDown robot) can not be completed because it conflicts with some rule already established. For example, you may get a 409 error if you try to upload a file to the Web server which is older than the one already there - resulting in a version control conflict.

Someone on a similar question right here on stackoverflow, said the answer was:

I've had this issue when I was referencing the url of the document library and not the destination file itself.

i.e. try http://server name/document library name/new file name.doc

However I am 100% sure this was not my case, since I checked the WebRequest's URI property several times and the URI was complete with filename, and all the folders in the path existed on the sharepoint site.

Anyways, I hope this helps someone.

How to replace multiple white spaces with one white space

While the existing answers are fine, I'd like to point out one approach which doesn't work:

public static string DontUseThisToCollapseSpaces(string text)
{
    while (text.IndexOf("  ") != -1)
    {
        text = text.Replace("  ", " ");
    }
    return text;
}

This can loop forever. Anyone care to guess why? (I only came across this when it was asked as a newsgroup question a few years ago... someone actually ran into it as a problem.)

How to make a back-to-top button using CSS and HTML only?

To add to the existing answers, you can avoid affecting the URL by overriding the link with JavaScript. This will still take you to the top of the page without JavaScript, but will append # to the URL.

<a href="#" onclick="document.body.scrollTop=0;document.documentElement.scrollTop=0;event.preventDefault()">Back to top</a>

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

How to add elements of a string array to a string array list?

You should instantiate your ArrayList before trying to add items:

private List<String> species = new ArrayList<String>();

How do I determine file encoding in OS X?

Classic 8-bit LaTeX is very restricted in which UTF8 characters it can use; it's highly dependent on the encoding of the font you're using and which glyphs that font has available.

Since you don't give a specific example, it's hard to know exactly where the problem is — whether you're attempting to use a glyph that your font doesn't have or whether you're not using the correct font encoding in the first place.

Here's a minimal example showing how a few UTF8 characters can be used in a LaTeX document:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[utf8]{inputenc}
\begin{document}
‘Héllø—thêrè.’
\end{document}

You may have more luck with the [utf8x] encoding, but be slightly warned that it's no longer supported and has some idiosyncrasies compared with [utf8] (as far as I recall; it's been a while since I've looked at it). But if it does the trick, that's all that matters for you.

npm throws error without sudo

Other answers are suggesting to change ownerships or permissions of system directories to a specific user. I highly disadvise from doing so, this can become very awkward and might mess up the entire system!

Here is a more generic and safer approach that supports multi-user as well.

Create a new group for node-users and add the required users to this group. Then set the ownership of node-dependant files/directories to this group.

# Create new group
sudo groupadd nodegrp 

# Add user to group (logname is a variable and gets replaced by the currently logged in user)
sudo usermod -a -G nodegrp `logname`

# Instant access to group without re-login
newgrp nodegrp

# Check group - nodegrp should be listed as well now
groups

# Change group of node_modules, node, npm to new group 
sudo chgrp -R nodegrp /usr/lib/node_modules/
sudo chgrp nodegrp /usr/bin/node
sudo chgrp nodegrp /usr/bin/npm

# (You may want to change a couple of more files (like grunt etc) in your /usr/bin/ directory.)

Now you can easily install your modules as user

npm install -g generator-angular

Some modules (grunt, bower, yo etc.) will still need to be installed as root. This is because they create symlinks in /user/bin/.

Edit

3 years later I'd recommend to use Node Version Manager. It safes you a lot of time and trouble.

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

"Not ASCII (neither's ?/?)" needs qualification.

While these characters are not defined in the American Standard Code for Information Interchange as glyphs, their codes WERE commonly used to give a graphical presentation for ASCII codes 24 and 25 (hex 18 and 19, CANcel and EM:End of Medium). Code page 437 (called Extended ASCII by IBM, includes the numeric codes 128 to 255) defined the use of these glyphs as ASCII codes and the ubiquity of these conventions permeated the industry as seen by their deployment as standards by leading companies such as HP, particularly for printers, and IBM, particularly for microcomputers starting with the original PC.

Just as the use of the ASCII codes for CAN and EM was relatively obsolete at the time, justifying their use as glyphs, so has the passage of time made the use of the codes as glyphs obsolete by the current use of UNICODE conventions.


It should be emphasized that the extensions to ASCII made by IBM in Extended ASCII, included not only a larger numeric set for numeric codes 128 to 255, but also extended the use of some numeric control codes, in the ASCII range 0 to 32, from just media transmission control protocols to include glyphs. It is often assumed, incorrectly, that the first 0 to 128 were not "extended" and that IBM was using the glyphs of conventional ASCII for this range. This error is also perpetrated in one of the previous references. This error became so pervasive that it colloquially redefined ASCII subliminally.

How to clear/remove observable bindings in Knockout.js?

Have you tried calling knockout's clean node method on your DOM element to dispose of the in memory bound objects?

var element = $('#elementId')[0]; 
ko.cleanNode(element);

Then applying the knockout bindings again on just that element with your new view models would update your view binding.

How to find and restore a deleted file in a Git repository

To restore a deleted and commited file:

git reset HEAD some/path
git checkout -- some/path

It was tested on Git version 1.7.5.4.

Detecting TCP Client Disconnect

"""
tcp_disconnect.py
Echo network data test program in python. This easily translates to C & Java.

A server program might want to confirm that a tcp client is still connected 
before it sends a data. That is, detect if its connected without reading from socket.
This will demonstrate how to detect a TCP client disconnect without reading data.

The method to do this:
1) select on socket as poll (no wait)
2) if no recv data waiting, then client still connected
3) if recv data waiting, the read one char using PEEK flag 
4) if PEEK data len=0, then client has disconnected, otherwise its connected.
Note, the peek flag will read data without removing it from tcp queue.

To see it in action: 0) run this program on one computer 1) from another computer, 
connect via telnet port 12345, 2) type a line of data 3) wait to see it echo, 
4) type another line, 5) disconnect quickly, 6) watch the program will detect the 
disconnect and exit.

John Masinter, 17-Dec-2008
"""

import socket
import time
import select

HOST = ''       # all local interfaces
PORT = 12345    # port to listen

# listen for new TCP connections
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
# accept new conneciton
conn, addr = s.accept()
print 'Connected by', addr
# loop reading/echoing, until client disconnects
try:
    conn.send("Send me data, and I will echo it back after a short delay.\n")
    while 1:
        data = conn.recv(1024)                          # recv all data queued
        if not data: break                              # client disconnected
        time.sleep(3)                                   # simulate time consuming work
        # below will detect if client disconnects during sleep
        r, w, e = select.select([conn], [], [], 0)      # more data waiting?
        print "select: r=%s w=%s e=%s" % (r,w,e)        # debug output to command line
        if r:                                           # yes, data avail to read.
            t = conn.recv(1024, socket.MSG_PEEK)        # read without remove from queue
            print "peek: len=%d, data=%s" % (len(t),t)  # debug output
            if len(t)==0:                               # length of data peeked 0?
                print "Client disconnected."            # client disconnected
                break                                   # quit program
        conn.send("-->"+data)                           # echo only if still connected
finally:
    conn.close()

CSS Background Image Not Displaying

I am using embedded CSS on a local computer. I put the atom.jpg file in the same folder as my html file, then this code worked:

background-image:url(atom.jpg);

How do I print to the debug output window in a Win32 app?

If you want to print decimal variables:

wchar_t text_buffer[20] = { 0 }; //temporary buffer
swprintf(text_buffer, _countof(text_buffer), L"%d", your.variable); // convert
OutputDebugString(text_buffer); // print

How to make a hyperlink in telegram without using bots?

On Telegram Desktop for macOS, the shortcuts differ. You can right-click a highlighted text, then hover over Transformations to see the available options:

macOS Telegram Desktop Formatting Shortcuts

md-table - How to update the column width

You can also add the styling directly in the markup if you desire so:

<ng-container matColumnDef="Edit">
     <th mat-header-cell *matHeaderCellDef > Edit </th>
     <td mat-cell *matCellDef="let element" (click)="openModal()" style="width: 50px;"> <i class="fa fa-pencil" aria-hidden="true"></i> </td>
</ng-container>

Dialog to pick image from gallery or from camera

You can implement this code to select image from gallery or camera :-

private ImageView imageview;
private Button btnSelectImage;
private Bitmap bitmap;
private File destination = null;
private InputStream inputStreamImg;
private String imgPath = null;
private final int PICK_IMAGE_CAMERA = 1, PICK_IMAGE_GALLERY = 2;

Now on button click event, you can able to call your method of select Image. This is inside activity's onCreate.

imageview = (ImageView) findViewById(R.id.imageview);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);

//OnbtnSelectImage click event...
btnSelectImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });

Outside of your activity's oncreate.

// Select image from camera and gallery
private void selectImage() {
    try {
        PackageManager pm = getPackageManager();
        int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
        if (hasPerm == PackageManager.PERMISSION_GRANTED) {
            final CharSequence[] options = {"Take Photo", "Choose From Gallery","Cancel"};
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
            builder.setTitle("Select Option");
            builder.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Take Photo")) {
                        dialog.dismiss();
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, PICK_IMAGE_CAMERA);
                    } else if (options[item].equals("Choose From Gallery")) {
                        dialog.dismiss();
                        Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);
                    } else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        } else
            Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    inputStreamImg = null;
    if (requestCode == PICK_IMAGE_CAMERA) {
        try {
            Uri selectedImage = data.getData();
            bitmap = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);

            Log.e("Activity", "Pick from Camera::>>> ");

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            destination = new File(Environment.getExternalStorageDirectory() + "/" +
                    getString(R.string.app_name), "IMG_" + timeStamp + ".jpg");
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            imgPath = destination.getAbsolutePath();
            imageview.setImageBitmap(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (requestCode == PICK_IMAGE_GALLERY) {
        Uri selectedImage = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
            Log.e("Activity", "Pick from Gallery::>>> ");

            imgPath = getRealPathFromURI(selectedImage);
            destination = new File(imgPath.toString());
            imageview.setImageBitmap(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = {MediaStore.Audio.Media.DATA};
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

Atlast, finally add the camera and write external storage permission to AndroidManifest.xml

It works for me greatly, hope it will also works for you.

TypeError: unsupported operand type(s) for /: 'str' and 'str'

By turning them into integers instead:

percent = (int(pyc) / int(tpy)) * 100;

In python 3, the input() function returns a string. Always. This is a change from Python 2; the raw_input() function was renamed to input().

Git push rejected "non-fast-forward"

  1. move the code to a new branch - git branch -b tmp_branchyouwantmergedin
  2. change to the branch you want to merge to - git checkout mycoolbranch
  3. reset the branch you want to merge to - git branch reset --hard HEAD
  4. merge the tmp branch into the desired branch - git branch merge tmp_branchyouwantmergedin
  5. push to origin

Adding an arbitrary line to a matplotlib plot in ipython notebook

Rather than abusing plot or annotate, which will be inefficient for many lines, you can use matplotlib.collections.LineCollection:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")

# Takes list of lines, where each line is a sequence of coordinates
l1 = [(70, 100), (70, 250)]
l2 = [(70, 90), (90, 200)]
lc = LineCollection([l1, l2], color=["k","blue"], lw=2)

plt.gca().add_collection(lc)

plt.show()

Figure with two lines plotted via LineCollection

It takes a list of lines [l1, l2, ...], where each line is a sequence of N coordinates (N can be more than two).

The standard formatting keywords are available, accepting either a single value, in which case the value applies to every line, or a sequence of M values, in which case the value for the ith line is values[i % M].

SQL Error with Order By in Subquery

On possible needs to order a subquery is when you have a UNION :

You generate a call book of all teachers and students.

SELECT name, phone FROM teachers
UNION
SELECT name, phone FROM students

You want to display it with all teachers first, followed by all students, both ordered by. So you cant apply a global order by.

One solution is to include a key to force a first order by, and then order the names :

SELECT name, phone, 1 AS orderkey FROM teachers
UNION
SELECT name, phone, 2 AS orderkey FROM students
ORDER BY orderkey, name

I think its way more clear than fake offsetting subquery result.

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

GLYPHICONS - bootstrap icon font hex value

If you want to use glyph icons with bootstrap 2.3.2, Add the font files from bootstrap 3 to your project folder then copy this to your css file

 @font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

pandas dataframe columns scaling with sklearn

As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el)) method will produce the following warning:

DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.

Converting your columns to numpy arrays should do the job (I prefer StandardScaler):

from sklearn.preprocessing import StandardScaler
scale = StandardScaler()

dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())

-- Edit Nov 2018 (Tested for pandas 0.23.4)--

As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix() returns FutureWarning. Therefore, it should be replaced by .values:

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()

scaler.fit_transform(dfTest[['A','B']].values)

-- Edit May 2019 (Tested for pandas 0.24.2)--

As joelostblom mentions in the comments, "Since 0.24.0, it is recommended to use .to_numpy() instead of .values."

Updated example:

import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
               'A':[14.00,90.20,90.95,96.27,91.21],
               'B':[103.02,107.26,110.35,114.23,114.68],
               'C':['big','small','big','small','small']
             })
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
      A         B      C
0 -1.995290 -1.571117    big
1  0.436356 -0.603995  small
2  0.460289  0.100818    big
3  0.630058  0.985826  small
4  0.468586  1.088469  small

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

MySQL: update a field only if condition is met

Another solution which, in my opinion, is easier to read would be:

UPDATE test 
    SET something = 1, field = IF(condition is true, 1, field) 
    WHERE id = 123

What this does is set 'field' to 1 (like OP used as example) if the condition is met and use the current value of 'field' if not met. Using the previous value is the same as not changing, so there you go.

Rounded table corners CSS only

The selected answer is terrible. I would implement this by targeting the corner table cells and applying the corresponding border radius.

To get the top corners, set the border radius on the first and last of type of the th elements, then finish by setting the border radius on the last and first of td type on the last of type tr to get the bottom corners.

th:first-of-type {
  border-top-left-radius: 10px;
}
th:last-of-type {
  border-top-right-radius: 10px;
}
tr:last-of-type td:first-of-type {
  border-bottom-left-radius: 10px;
}
tr:last-of-type td:last-of-type {
  border-bottom-right-radius: 10px;
}

How do I find the number of arguments passed to a Bash script?

that value is contained in the variable $#

How to uninstall Ruby from /usr/local?

It's not a good idea to uninstall 1.8.6 if it's in /usr/bin. That is owned by the OS and is expected to be there.

If you put /usr/local/bin in your PATH before /usr/bin then things you have installed in /usr/local/bin will be found before any with the same name in /usr/bin, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin in your #! interpreter invocation line at the top of your code.

@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.

Node update a specific package

Most of the time you can just npm update (or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).

npm update browser-sync
-------
yarn upgrade browser-sync
  • Use npm|yarn outdated to see which modules have newer versions
  • Use npm update|yarn upgrade (without a package name) to update all modules
  • Include --save-dev|--dev if you want to save the newer version numbers to your package.json. (NOTE: as of npm v5.0 this is only necessary for devDependencies).

Major version upgrades:

In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x by doing:

npm install browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev

...or the latest 2.1.x by doing:

npm install [email protected] --save-dev
-------
yarn add [email protected] --dev

...or the latest and greatest by doing:

npm install browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev

Note: the last one is no different than doing this:

npm uninstall browser-sync --save-dev
npm install browser-sync --save-dev
-------
yarn remove browser-sync --dev
yarn add browser-sync --dev

The --save-dev part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.

Convert string in base64 to image and save on filesystem in Python

Starting with

img_data = b'iVBORw0KGgoAAAANSUhEUgAABoIAAAaCCAYAAAABZu+EAAAqOElEQVR42uzBAQEAAACAkP6v7ggK\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAIcAeHkAAeLqlDIAAAAASUVORK5CYII='

Decoded the data using the base64 codec, and then write it to the filesystem.

# In Python 2.7
fh = open("imageToSave.png", "wb")
fh.write(img_data.decode('base64'))
fh.close()

# or, more concisely using with statement
with open("imageToSave.png", "wb") as fh:
    fh.write(img_data.decode('base64'))

Modernizing this example to Python 3, which removed arbitrary codec support from string/bytes .encode() and .decode() functions:

# For both Python 2.7 and Python 3.x
import base64
with open("imageToSave.png", "wb") as fh:
    fh.write(base64.decodebytes(img_data))

How to convert a Kotlin source file to a Java source file

you can go to Tools > Kotlin > Show kotlin bytecode

enter image description here

enter image description here

enter image description here

Execute command without keeping it in history

You might consider using a shell without history, like perhaps

/bin/sh << END
   your commands without history
END

(perhaps /bin/dash or /bin/sash could be more appropriate than /bin/sh)

or even better use the batch utility e.g

batch << EOB
   your commands
EOB

The history would then contain sh or batch which is not very meaningful

Can the :not() pseudo-class have multiple arguments?

Why :not just use two :not:

input:not([type="radio"]):not([type="checkbox"])

Yes, it is intentional

Cast IList to List

In my case I had to do this, because none of the suggested solutions were available:

List<SubProduct> subProducts = Model.subproduct.Cast<SubProduct>().ToList();

How do I skip a header from CSV files in Spark?

From Spark 2.0 onwards what you can do is use SparkSession to get this done as a one liner:

val spark = SparkSession.builder.config(conf).getOrCreate()

and then as @SandeepPurohit said:

val dataFrame = spark.read.format("CSV").option("header","true").load(csvfilePath)

I hope it solved your question !

P.S: SparkSession is the new entry point introduced in Spark 2.0 and can be found under spark_sql package

Laravel 5 Clear Views Cache

There is now a php artisan view:clear command for this task since Laravel 5.1

Can I force a page break in HTML printing?

Add a CSS class called "pagebreak" (or "pb"), like so:

@media print {
    .pagebreak { page-break-before: always; } /* page-break-after works, as well */
}

Then add an empty DIV tag (or any block element that generates a box) where you want the page break.

<div class="pagebreak"> </div>

It won't show up on the page, but will break up the page when printing.

P.S. Perhaps this only applies when using -after (and also what else you might be doing with other <div>s on the page), but I found that I had to augment the CSS class as follows:

@media print {
    .pagebreak {
        clear: both;
        page-break-after: always;
    }
}

Android Studio - Unable to find valid certification path to requested target

"Unable to find valid certification path to requested target"

If you are getting this message, you probably are behind a Proxy on your company, which probably is signing all request certificates with your company root CA certificate, this certificate is trusted only inside your company, so Android Studio cannot validate any certificate signed with your company certificate as valid, so, you need to tell Android Studio to trust your company certificate, you do that by adding your company certificate to Android Studio truststore.

(I'm doing this on macOS, but should be similar on Linux or Windows)

  • First, you need to save your company root CA certificate as a file: you can ask this certificate to your IT department, or download it yourself, here is how. Open your browser and open this url, for example, https://jcenter.bintray.com/ or https://search.maven.org/, click on the lock icon and then click on Show certificate

enter image description here

On the popup window, to save the root certificate as a file, make sure to select the top level of the certificates chain (the root cert) and drag the certificate image to a folder/directory on your disk drive. It should be saved as a file as, for example: my-root-ca-cert.cer, or my-root-ca-cert.pem

enter image description here

  • Second, let's add this certificate to the accepted Server Certificates of Android Studio:

On Android Studio open Preferences -> Tools -> Server Certificates, on the box Accepted certificates click the plus icon (+), search the certificate you saved previously and click Apply and OK

enter image description here

  • Third, you need to add the certificate to the Android Studio JDK truststore (Gradle use this JDK to build the project, so it's important):

In Android Studio open File -> Project Structure -> SDK Location -> JDK Location

enter image description here

Copy the path of JDK Location, and open the Terminal, and change your directory to that path, for example, execute:

cd /Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/

(don't forget to scape the whitespace, "\ ")

Now, to import the certificate to the truststore, execute:

./bin/keytool -importcert -file /path/to/your/certificate/my-root-ca-cert.cer -keystore ./jre/lib/security/cacerts -storepass changeit -noprompt
  • Finally, restart Android Studio, or better click File -> Invalidate Caches / Restart

Done, you should be able to build your project now.

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I configured the app.config with the tool for EntLib configuration and set up my LoggingConfiguration block. Then I copied this into the DotNetConfig.xsd. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.

<xs:element name="loggingConfiguration">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="listeners">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:attribute name="fileName" type="xs:string" use="required" />
                <xs:attribute name="footer" type="xs:string" use="required" />
                <xs:attribute name="formatter" type="xs:string" use="required" />
                <xs:attribute name="header" type="xs:string" use="required" />
                <xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
                <xs:attribute name="rollInterval" type="xs:string" use="required" />
                <xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
                <xs:attribute name="timeStampPattern" type="xs:string" use="required" />
                <xs:attribute name="listenerDataType" type="xs:string" use="required" />
                <xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
                <xs:attribute name="filter" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="formatters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="template" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="logFilters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="enabled" type="xs:boolean" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="categorySources">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="specialSources">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="allEvents">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="notProcessed">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="errors">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="name" type="xs:string" use="required" />
    <xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
    <xs:attribute name="defaultCategory" type="xs:string" use="required" />
    <xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
  </xs:complexType>
</xs:element>

How to delete last character from a string using jQuery?

You can also try this in plain javascript

"1234".slice(0,-1)

the negative second parameter is an offset from the last character, so you can use -2 to remove last 2 characters etc

console.log not working in Angular2 Component (Typescript)

It's not working because console.log() it's not in a "executable area" of the class "App".

A class is a structure composed by attributes and methods.

The only way to have your code executed is to place it inside a method that is going to be executed. For instance: constructor()

_x000D_
_x000D_
console.log('It works here')_x000D_
_x000D_
@Component({..)_x000D_
export class App {_x000D_
 s: string = "Hello2";_x000D_
            _x000D_
  constructor() {_x000D_
    console.log(this.s)            _x000D_
  }            _x000D_
}
_x000D_
_x000D_
_x000D_

Think of class like a plain javascript object.

Would it make sense to expect this to work?

_x000D_
_x000D_
class:  {_x000D_
  s: string,_x000D_
  console.log(s)_x000D_
 }
_x000D_
_x000D_
_x000D_

If you still unsure, try the typescript playground where you can see your typescript code generated into plain javascript.

https://www.typescriptlang.org/play/index.html

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

DATE: It is used for values with a date part but no time part. MySQL retrieves and displays DATE values in YYYY-MM-DD format. The supported range is 1000-01-01 to 9999-12-31.

DATETIME: It is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format. The supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59.

TIMESTAMP: It is also used for values that contain both date and time parts, and includes the time zone. TIMESTAMP has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC.

TIME: Its values are in HH:MM:SS format (or HHH:MM:SS format for large hours values). TIME values may range from -838:59:59 to 838:59:59. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).

PHP - Notice: Undefined index:

For starters,

mysql_connect() should not have a $ accompanying it; it is not a variable, it is a predefined function. Remove the $ to properly connect to the database.

Why do you have an XML tag at the top of this document? This is HTML/PHP - a HTML doctype should suffice.

From line 215, update:

if (isset($_POST)) {
    $Name = $_POST['Name'];
    $Surname = $_POST['Surname'];

    $Username = $_POST['Username'];

    $Email = $_POST['Email'];
    $C_Email = $_POST['C_Email'];

    $Password = $_POST['password'];
    $C_Password = $_POST['c_password'];

    $SecQ = $_POST['SecQ'];
    $SecA = $_POST['SecA'];
}

POST variables are coming from your form, and you have to check whether they exist or not, else PHP will give you a NOTICE error. You can disable these notices by placing error_reporting(0); at the top of your document. It's best to keep these visible for development purposes.

You should only be interacting with the database (inserting, checking) under the condition that the form has been submitted. If you do not, PHP will run all of these operations without any input from the user. Its best to use an IF statement, like so:

if (isset($_POST['submit']) {
// blah blah
// check if user exists, check if fields are blank
// insert the user if all of this stuff checks out..
} else {
// just display the form
}

Awesome form tutorial: http://php.about.com/od/learnphp/ss/php_forms.htm

PHP __get and __set magic methods

Intenta con:

__GET($k){
 return $this->$k;
}

_SET($k,$v){
 return $this->$k = $v;
}

Opening PDF String in new window with javascript

var byteCharacters = atob(response.data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
  byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new Blob([byteArray], { type: 'application/pdf;base64' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);

You return a base64 string from the API or another source. You can also download it.

Now() function with time trim

Paste this function in your Module and use it as like formula

Public Function format_date(t As String)
    format_date = Format(t, "YYYY-MM-DD")
End Function

for example in Cell A1 apply this formula

=format_date(now())

it will return in YYYY-MM-DD format. Change any format (year month date) as your wish.

NSDate get year/month/day

Try the following:

    NSString *birthday = @"06/15/1977";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSDate *date = [formatter dateFromString:birthday];
    if(date!=nil) {
        NSInteger age = [date timeIntervalSinceNow]/31556926;
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
        NSInteger day = [components day];
        NSInteger month = [components month];
        NSInteger year = [components year];

        NSLog(@"Day:%d Month:%d Year:%d Age:%d",day,month,year,age);
    }
    [formatter release];

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Git push existing repo to a new and different remote repo server?

If you have Existing Git repository:

cd existing_repo
git remote rename origin old-origin
git remote add origin https://gitlab.com/newproject
git push -u origin --all
git push -u origin --tags

JUnit tests pass in Eclipse but fail in Maven Surefire

It is most likely that your configuration files are in src/main/resources, while they must be under src/test/resources to work properly under maven.

https://cwiki.apache.org/UIMA/differences-between-running-unit-tests-in-eclipse-and-in-maven.html

I'm replying this after two years 'cause I couldn't find this answer here and I think it is the right one.

Getting unique items from a list

Use a HashSet<T>. For example:

var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
    Console.WriteLine(s);

prints

A
B
D
C

Is there a way to provide named parameters in a function call in JavaScript?

There is another way. If you're passing an object by reference, that object's properties will appear in the function's local scope. I know this works for Safari (haven't checked other browsers) and I don't know if this feature has a name, but the below example illustrates its use.

Although in practice I don't think that this offers any functional value beyond the technique you're already using, it's a little cleaner semantically. And it still requires passing a object reference or an object literal.

function sum({ a:a, b:b}) {
    console.log(a+'+'+b);
    if(a==undefined) a=0;
    if(b==undefined) b=0;
    return (a+b);
}

// will work (returns 9 and 3 respectively)
console.log(sum({a:4,b:5}));
console.log(sum({a:3}));

// will not work (returns 0)
console.log(sum(4,5));
console.log(sum(4));

Strangest language feature

In C#: a = cond ? b : c; If 'b' & 'c' are "assign incompatible", you'll never get result, even if 'a' is object. It's frequently used and most idiotically implemented operator from MS. For comparison see implementation in D language (note on type inference).

How do I bind to list of checkbox values with AngularJS?

<input type='checkbox' ng-repeat="fruit in fruits"
  ng-checked="checkedFruits.indexOf(fruit) != -1" ng-click="toggleCheck(fruit)">

.

function SomeCtrl ($scope) {
    $scope.fruits = ["apple, orange, pear, naartjie"];
    $scope.checkedFruits = [];
    $scope.toggleCheck = function (fruit) {
        if ($scope.checkedFruits.indexOf(fruit) === -1) {
            $scope.checkedFruits.push(fruit);
        } else {
            $scope.checkedFruits.splice($scope.checkedFruits.indexOf(fruit), 1);
        }
    };
}

What character represents a new line in a text area

It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:

The element's value is defined to be the element's raw value with the following transformation applied:

Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.

Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:

Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.

To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.

Driver executable must be set by the webdriver.ie.driver system property

You will need have to download InternetExplorer driver executable on your system, download it from the source (http://code.google.com/p/selenium/downloads/list) after download unzip it and put on the place of somewhere in your computer. In my example, I will place it to D:\iexploredriver.exe

Then you have write below code in your eclipse main class

   System.setProperty("webdriver.ie.driver", "D:/iexploredriver.exe");
   WebDriver driver = new InternetExplorerDriver();

Read files from a Folder present in project

I have a C# project (Windows Console Application). I have created a folder named Images inside project. There is one ico file called MyIcon.ico. I accessed MyIcon.ico inside Images folder like below.

this.Icon = new Icon(@"../../Images/MyIcon.ico");

Is it possible to use global variables in Rust?

Look at the const and static section of the Rust book.

You can use something as follows:

const N: i32 = 5; 

or

static N: i32 = 5;

in global space.

But these are not mutable. For mutability, you could use something like:

static mut N: i32 = 5;

Then reference them like:

unsafe {
    N += 1;

    println!("N: {}", N);
}

How to get PHP $_GET array?

When you don't want to change the link (e.g. foo.php?id=1&id=2&id=3) you could probably do something like this (although there might be a better way...):

$id_arr = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $tmp_arr_param) {
    $split_param = explode("=", $tmp_arr_param);
    if ($split_param[0] == "id") {
        $id_arr[] = urldecode($split_param[1]);
    }
}
print_r($id_arr);

ASP.NET MVC on IIS 7.5

The UI is a bit different in the newer versions of Windows Server. Here is where you have to enable ASP.Net in order to get it working on IIS

Fix IIS & Asp.net

Convert command line arguments into an array in Bash

Here is another usage :

#!/bin/bash
array=( "$@" )
arraylength=${#array[@]}
for (( i=0; i<${arraylength}; i++ ));
do
   echo "${array[$i]}"
done

Get yesterday's date using Date

Try this one:

private String toDate() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    // Create a calendar object with today date. Calendar is in java.util pakage.
    Calendar calendar = Calendar.getInstance();

    // Move calendar to yesterday
    calendar.add(Calendar.DATE, -1);

    // Get current date of calendar which point to the yesterday now
    Date yesterday = calendar.getTime();

    return dateFormat.format(yesterday).toString();
}

How to transform array to comma separated words string?

Make your array a variable and use implode.

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

http://php.net/manual/en/function.implode.php

JPA getSingleResult() or null

Here's a typed/generics version, based on Rodrigo IronMan's implementation:

 public static <T> T getSingleResultOrNull(TypedQuery<T> query) {
    query.setMaxResults(1);
    List<T> list = query.getResultList();
    if (list.isEmpty()) {
        return null;
    }
    return list.get(0);
}

What is the 'instanceof' operator used for in Java?

It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.

Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).

instanceof is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.

if (obj instanceof Checkbox)
{
    Checkbox cb = (Checkbox)obj;
    boolean state = cb.getState();
}

'^M' character at end of lines

C:\tmp\text>dos2unix hello.txt helloUNIX.txt

Sed is even more widely available and can do this kind of thing also if dos2unix is not installed

C:\tmp\text>sed s/\r// hello.txt > helloUNIX.txt  

You could also try tr:

cat hello.txt | tr -d \r > helloUNIX2.txt  

Here are the results:

C:\tmp\text>dumphex hello.txt  
00000000h: 48 61 68 61 0D 0A 68 61 68 61 0D 0A 68 61 68 61 Haha..haha..haha  
00000010h: 0D 0A 0D 0A 68 61 68 61 0D 0A                   ....haha..  

C:\tmp\text>dumphex helloUNIX.txt  
00000000h: 48 61 68 61 0A 68 61 68 61 0A 68 61 68 61 0A 0A Haha.haha.haha..  
00000010h: 68 61 68 61 0A                                  haha.  

C:\tmp\text>dumphex helloUNIX2.txt  
00000000h: 48 61 68 61 0A 68 61 68 61 0A 68 61 68 61 0A 0A Haha.haha.haha..  
00000010h: 68 61 68 61 0A                                  haha.  

How can I pass parameters to a partial view in mvc 4

Here is an extension method that will convert an object to a ViewDataDictionary.

public static ViewDataDictionary ToViewDataDictionary(this object values)
{
    var dictionary = new ViewDataDictionary();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(values))
    {
        dictionary.Add(property.Name, property.GetValue(values));
    }
    return dictionary;
}

You can then use it in your view like so:

@Html.Partial("_MyPartial", new
{
    Property1 = "Value1",
    Property2 = "Value2"
}.ToViewDataDictionary())

Which is much nicer than the new ViewDataDictionary { { "Property1", "Value1" } , { "Property2", "Value2" }} syntax.

Then in your partial view, you can use ViewBag to access the properties from a dynamic object rather than indexed properties, e.g.

<p>@ViewBag.Property1</p>
<p>@ViewBag.Property2</p>

CSS selector for "foo that contains bar"?

Is there any way you could programatically apply a class to the object?

<object class="hasparams">

then do

object.hasparams

Angular 2 - View not updating after model changes

Instead of dealing with zones and change detection — let AsyncPipe handle complexity. This will put observable subscription, unsubscription (to prevent memory leaks) and changes detection on Angular shoulders.

Change your class to make an observable, that will emit results of new requests:

export class RecentDetectionComponent implements OnInit {

    recentDetections$: Observable<Array<RecentDetection>>;

    constructor(private recentDetectionService: RecentDetectionService) {
    }

    ngOnInit() {
        this.recentDetections$ = Observable.interval(5000)
            .exhaustMap(() => this.recentDetectionService.getJsonFromApi())
            .do(recent => console.log(recent[0].macAddress));
    }
}

And update your view to use AsyncPipe:

<tr *ngFor="let detected of recentDetections$ | async">
    ...
</tr>

Want to add, that it's better to make a service with a method that will take interval argument, and:

  • create new requests (by using exhaustMap like in code above);
  • handle requests errors;
  • stop browser from making new requests while offline.

How can you program if you're blind?

What about inventing some kind of device that you plug in a usb port and that would be basically a "sheet of rubber" that would modify itself to show brail of your code, allowing blind people to read it instead to hear it?

how to open a url in python

You could also try:

import os
os.system("start \"\" http://example.com")

This, other than @aaronasterling ´s answer has the advantage that it opens the default web browser. Be sure not to forget the "http://".

How can I format a String number to have commas and round?

Here is the simplest way to get there:

String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result)); 

output: 10,987,655.88

How to allocate aligned memory only using the standard library?

If there are constraints that, you cannot waste a single byte, then this solution works: Note: There is a case where this may be executed infinitely :D

   void *mem;  
   void *ptr;
try:
   mem =  malloc(1024);  
   if (mem % 16 != 0) {  
       free(mem);  
       goto try;
   }  
   ptr = mem;  
   memset_16aligned(ptr, 0, 1024);

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

use a javascript array to fill up a drop down select box

This is a part from a REST-Service I´ve written recently.

var select = $("#productSelect")
for (var prop in data) {
    var option = document.createElement('option');
    option.innerHTML = data[prop].ProduktName
    option.value = data[prop].ProduktName;
    select.append(option)
}

The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

SELECT with LIMIT in Codeigniter

For further visitors:

// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);

// get_where sample, 
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);

// Produces: LIMIT 10
$this->db->limit(10);  

// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);

Limiting double to 3 decimal places

Multiply by 1000 then use Truncate then divide by 1000.

Create a string and append text to it

Another way to do this is to add the new characters to the string as follows:

Dim str As String

str = ""

To append text to your string this way:

str = str & "and this is more text"

How do I pass JavaScript values to Scriptlet in JSP?

Its not possible as you are expecting. But you can do something like this. Pass the your java script value to the servlet/controller, do your processing and then pass this value to the jsp page by putting it into some object's as your requirement. Then you can use this value as you want.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

The reason why there are so many different answers is because the exception probably doesn't have anything to do with the SECRET_KEY. It is probably an earlier exception that is being swallowed. Turn on debugging using DEBUG=True to see the real exception.

PHP and MySQL Select a Single Value

It is quite evident that there is only a single id corresponding to a single username because username is unique.

But the actual problem lies in the query itself-

$sql = "SELECT 'id' FROM Users WHERE username='$name'";

O/P

+----+
| id |
+----+
| id |
+----+

i.e. 'id' actually is treated as a string not as the id attribute.

Correct synatx:

$sql = "SELECT `id` FROM Users WHERE username='$name'";

i.e. use grave accent(`) instead of single quote(').

or

$sql = "SELECT id FROM Users WHERE username='$name'";

Complete code

session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;

Jackson Vs. Gson

Gson 1.6 now includes a low-level streaming API and a new parser which is actually faster than Jackson.

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

you have to add the missing local lang helper: for me the missing ones where de_LU de_LU.UTF-8 . Mongo 2.6.4 worked wihtout mongo 2.6.5 throw an error on this

Is it possible to preview stash contents in git?

I like how gitk can show you exactly what was untracked or sitting in the index, but by default it will show those stash "commits" in the middle of all your other commits on the current branch.

The trick is to run gitk as follows:

gitk "stash@{0}^!"

(The quoting is there to make it work in Powershell but this way it should still work in other shells as well.)

If you look up this syntax in the gitrevisions help page you'll find the following:

The r1^! notation includes commit r1 but excludes all of its parents. By itself, this notation denotes the single commit r1.

This will apparently put gitk in such a mode that only the immediate parents of the selected commit are shown, which is exactly what I like.


If you want to take this further and list all stashes then you can run this:

gitk `git stash list '--pretty=format:%gd^!'`

(Those single quotes inside the backticks are necessary to appease Bash, otherwise it complains about the exclamation mark)

If you are on Windows and using cmd or Powershell:

gitk "--argscmd=git stash list --pretty=format:%gd^!"

How can I rename a project folder from within Visual Studio?

The simplest way is to go to the property of the window, change the name of the default namespaces, and then the rename is done.

How to insert logo with the title of a HTML page?

Put this in the <head> section:

<link rel="icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />

Keep the picture file named "favicon.ico". You'll have to look online to get a .ico file generator.

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

Moment.js get day name from date

With moment you can parse the date string you have:

var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")

That's for UTC, you'll have to convert the time zone from that point if you so desire.

Then you can get the day of the week:

dt.format('dddd');

What does the ??!??! operator do in C?

As already stated ??!??! is essentially two trigraphs (??! and ??! again) mushed together that get replaced-translated to ||, i.e the logical OR, by the preprocessor.

The following table containing every trigraph should help disambiguate alternate trigraph combinations:

Trigraph   Replaces

??(        [
??)        ]
??<        {
??>        }
??/        \
??'        ^
??=        #
??!        |
??-        ~

Source: C: A Reference Manual 5th Edition

So a trigraph that looks like ??(??) will eventually map to [], ??(??)??(??) will get replaced by [][] and so on, you get the idea.

Since trigraphs are substituted during preprocessing you could use cpp to get a view of the output yourself, using a silly trigr.c program:

void main(){ const char *s = "??!??!"; } 

and processing it with:

cpp -trigraphs trigr.c 

You'll get a console output of

void main(){ const char *s = "||"; }

As you can notice, the option -trigraphs must be specified or else cpp will issue a warning; this indicates how trigraphs are a thing of the past and of no modern value other than confusing people who might bump into them.


As for the rationale behind the introduction of trigraphs, it is better understood when looking at the history section of ISO/IEC 646:

ISO/IEC 646 and its predecessor ASCII (ANSI X3.4) largely endorsed existing practice regarding character encodings in the telecommunications industry.

As ASCII did not provide a number of characters needed for languages other than English, a number of national variants were made that substituted some less-used characters with needed ones.

(emphasis mine)

So, in essence, some needed characters (those for which a trigraph exists) were replaced in certain national variants. This leads to the alternate representation using trigraphs comprised of characters that other variants still had around.

Replace single quotes in SQL Server

If escaping your single quote with another single quote isn't working for you (like it didn't for one of my recent REPLACE() queries), you can use SET QUOTED_IDENTIFIER OFF before your query, then SET QUOTED_IDENTIFIER ON after.

For example

SET QUOTED_IDENTIFIER OFF;

UPDATE TABLE SET NAME = REPLACE(NAME, "'S", "S");

SET QUOTED_IDENTIFIER OFF;

Copy folder recursively in Node.js

Use shelljs

npm i -D shelljs

const bash = require('shelljs');
bash.cp("-rf", "/path/to/source/folder", "/path/to/destination/folder");

momentJS date string add 5 days

You can reduce what they said in a few lines of code:

var nowPlusOneDay = moment().add('days', 1);
var nowPlusOneDayStr = nowPlusOneDay.format('YYYY-MM-DD');

alert('nowPlusOneDay Without Format(Unix Date):'+nowPlusOneDay);
alert('nowPlusOneDay Formatted(String):'+nowPlusOneDayStr);

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

This worked for me :

EDITOR="/usr/bin/vim"
export EDITOR

Add this to ~/.bash_profile or ~/.bashrc to enable this for current user.

Better way to get type of a Javascript variable?

You can apply Object.prototype.toString to any object:

var toString = Object.prototype.toString;

console.log(toString.call([]));
//-> [object Array]

console.log(toString.call(/reg/g));
//-> [object RegExp]

console.log(toString.call({}));
//-> [object Object]

This works well in all browsers, with the exception of IE - when calling this on a variable obtained from another window it will just spit out [object Object].

UIScrollView scroll to bottom programmatically

valdyr, hope this will help you:

CGPoint bottomOffset = CGPointMake(0, [textView contentSize].height - textView.frame.size.height);

if (bottomOffset.y > 0)
 [textView setContentOffset: bottomOffset animated: YES];

Make Div Draggable using CSS

You can do it now by using the CSS property -webkit-user-drag:

_x000D_
_x000D_
#drag_me {_x000D_
  -webkit-user-drag: element;_x000D_
}
_x000D_
<div draggable="true" id="drag_me">_x000D_
  Your draggable content here_x000D_
</div>
_x000D_
_x000D_
_x000D_

This property is only supported by webkit browsers, such as Safari or Chrome, but it is a nice approach to get it working using only CSS.

The HTML5 draggable attribute is only set to ensure dragging works for other browsers.

You can find more information here: http://help.dottoro.com/lcbixvwm.php

How to download a file from my server using SSH (using PuTTY on Windows)

if you install git with git bash, you get SCP available on windows.

PHP: maximum execution time when importing .SQL data file

you must change php_admin_value max_execution_time in your Alias config (\XAMPP\alias\phpmyadmin.conf)

answer is here: WAMPServer phpMyadmin Maximum execution time of 360 seconds exceeded

Get top 1 row of each group

SELECT o.*
FROM `DocumentStatusLogs` o                   
  LEFT JOIN `DocumentStatusLogs` b                   
  ON o.DocumentID = b.DocumentID AND o.DateCreated < b.DateCreated
 WHERE b.DocumentID is NULL ;

If you want to return only recent document order by DateCreated, it will return only top 1 document by DocumentID

When should I use git pull --rebase?

I don't think there's ever a reason not to use pull --rebase -- I added code to Git specifically to allow my git pull command to always rebase against upstream commits.

When looking through history, it is just never interesting to know when the guy/gal working on the feature stopped to synchronise up. It might be useful for the guy/gal while he/she is doing it, but that's what reflog is for. It's just adding noise for everyone else.

Why do I need an IoC container as opposed to straightforward DI code?

Honestly I don't find there to be many cases where IoC containers are needed, and most of the time, they just add unneeded complexity.

If you are using it just for making construction of an object simpler, I'd have to ask, are you instantiating this object in more than one location? Would a singleton not suit your needs? Are you changing the configuration at runtime? (Switching data source types, etc).

If yes, then you might need an IoC container. If not, then you're just moving the initialization away from where the developer can easily see it.

Who said that an interface is better than inheritance anyway? Say you're testing a Service. Why not use constructor DI, and create mocks of the dependencies using inheritance? Most services I use only have a few dependencies. Doing unit testing this way prevents maintaining a ton of useless interfaces and means you don't have to use Resharper to quickly find the declaration of a method.

I believe that for most implementations, saying that IoC Containers remove unneeded code is a myth.

First, there's setting up the container in the first place. Then you still have to define each object that needs to be initialized. So you don't save code in initialization, you move it (unless your object is used more than once. Is it better as a Singleton?). Then, for each object you've initialized in this way, you have to create and maintain an interface.

Anyone have any thoughts on this?

Differences between Ant and Maven

Maven acts as both a dependency management tool - it can be used to retrieve jars from a central repository or from a repository you set up - and as a declarative build tool. The difference between a "declarative" build tool and a more traditional one like ant or make is you configure what needs to get done, not how it gets done. For example, you can say in a maven script that a project should be packaged as a WAR file, and maven knows how to handle that.

Maven relies on conventions about how project directories are laid out in order to achieve its "declarativeness." For example, it has a convention for where to put your main code, where to put your web.xml, your unit tests, and so on, but also gives the ability to change them if you need to.

You should also keep in mind that there is a plugin for running ant commands from within maven:

http://maven.apache.org/plugins/maven-ant-plugin/

Also, maven's archetypes make getting started with a project really fast. For example, there is a Wicket archetype, which provides a maven command you run to get a whole, ready-to-run hello world-type project.

https://wicket.apache.org/start/quickstart.html

How to increment a pointer address and pointer's value?

With regards to "How to increment a pointer address and pointer's value?" I think that ++(*p++); is actually well defined and does what you're asking for, e.g.:

#include <stdio.h>

int main() {
  int a = 100;
  int *p = &a;
  printf("%p\n",(void*)p);
  ++(*p++);
  printf("%p\n",(void*)p);
  printf("%d\n",a);
  return 0;
}

It's not modifying the same thing twice before a sequence point. I don't think it's good style though for most uses - it's a little too cryptic for my liking.

WCF gives an unsecured or incorrectly secured fault error

In my case, I was getting this error on the same machine, in my test client-server application. But this problem was resolved by "Update Service Reference".

  • Tushar G. Walavalkar

Problems with entering Git commit message with Vim

Typically, git commit brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR environment variable) for you to edit your commit message in. When you save and exit, the commit completes.

You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

for converting dd/mm/yyyy to mm/dd/yyyy

=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))

Execute curl command within a Python script

You can use below code snippet

import shlex
import subprocess
import json

def call_curl(curl):
    args = shlex.split(curl)
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return json.loads(stdout.decode('utf-8'))


if __name__ == '__main__':
    curl = '''curl - X
    POST - d
    '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
    http: // localhost: 8080 / firewall / rules / 0000000000000001 '''
    output = call_curl(curl)
    print(output)

Assembly Language - How to do Modulo?

If your modulus / divisor is a known constant, and you care about performance, see this and this. A multiplicative inverse is even possible for loop-invariant values that aren't known until runtime, e.g. see https://libdivide.com/ (But without JIT code-gen, that's less efficient than hard-coding just the steps necessary for one constant.)

Never use div for known powers of 2: it's much slower than and for remainder, or right-shift for divide. Look at C compiler output for examples of unsigned or signed division by powers of 2, e.g. on the Godbolt compiler explorer. If you know a runtime input is a power of 2, use lea eax, [esi-1] ; and eax, edi or something like that to do x & (y-1). Modulo 256 is even more efficient: movzx eax, cl has zero latency on recent Intel CPUs (mov-elimination), as long as the two registers are separate.


In the simple/general case: unknown value at runtime

The DIV instruction (and its counterpart IDIV for signed numbers) gives both the quotient and remainder. For unsigned, remainder and modulus are the same thing. For signed idiv, it gives you the remainder (not modulus) which can be negative:
e.g. -5 / 2 = -2 rem -1. x86 division semantics exactly match C99's % operator.

DIV r32 divides a 64-bit number in EDX:EAX by a 32-bit operand (in any register or memory) and stores the quotient in EAX and the remainder in EDX. It faults on overflow of the quotient.

Unsigned 32-bit example (works in any mode)

mov eax, 1234          ; dividend low half
mov edx, 0             ; dividend high half = 0.  prefer  xor edx,edx

mov ebx, 10            ; divisor can be any register or memory

div ebx       ; Divides 1234 by 10.
        ; EDX =   4 = 1234 % 10  remainder
        ; EAX = 123 = 1234 / 10  quotient

In 16-bit assembly you can do div bx to divide a 32-bit operand in DX:AX by BX. See Intel's Architectures Software Developer’s Manuals for more information.

Normally always use xor edx,edx before unsigned div to zero-extend EAX into EDX:EAX. This is how you do "normal" 32-bit / 32-bit => 32-bit division.

For signed division, use cdq before idiv to sign-extend EAX into EDX:EAX. See also Why should EDX be 0 before using the DIV instruction?. For other operand-sizes, use cbw (AL->AX), cwd (AX->DX:AX), cdq (EAX->EDX:EAX), or cqo (RAX->RDX:RAX) to set the top half to 0 or -1 according to the sign bit of the low half.

div / idiv are available in operand-sizes of 8, 16, 32, and (in 64-bit mode) 64-bit. 64-bit operand-size is much slower than 32-bit or smaller on current Intel CPUs, but AMD CPUs only care about the actual magnitude of the numbers, regardless of operand-size.

Note that 8-bit operand-size is special: the implicit inputs/outputs are in AH:AL (aka AX), not DL:AL. See 8086 assembly on DOSBox: Bug with idiv instruction? for an example.

Signed 64-bit division example (requires 64-bit mode)

   mov    rax,  0x8000000000000000   ; INT64_MIN = -9223372036854775808
   mov    ecx,  10           ; implicit zero-extension is fine for positive numbers

   cqo                       ; sign-extend into RDX, in this case = -1 = 0xFF...FF
   idiv   rcx
       ; quotient  = RAX = -922337203685477580 = 0xf333333333333334
       ; remainder = RDX = -8                  = 0xfffffffffffffff8

Limitations / common mistakes

div dword 10 is not encodeable into machine code (so your assembler will report an error about invalid operands).

Unlike with mul/imul (where you should normally use faster 2-operand imul r32, r/m32 or 3-operand imul r32, r/m32, imm8/32 instead that don't waste time writing a high-half result), there is no newer opcode for division by an immediate, or 32-bit/32-bit => 32-bit division or remainder without the high-half dividend input.

Division is so slow and (hopefully) rare that they didn't bother to add a way to let you avoid EAX and EDX, or to use an immediate directly.


div and idiv will fault if the quotient doesn't fit into one register (AL / AX / EAX / RAX, the same width as the dividend). This includes division by zero, but will also happen with a non-zero EDX and a smaller divisor. This is why C compilers just zero-extend or sign-extend instead of splitting up a 32-bit value into DX:AX.

And also why INT_MIN / -1 is C undefined behaviour: it overflows the signed quotient on 2's complement systems like x86. See Why does integer division by -1 (negative one) result in FPE? for an example of x86 vs. ARM. x86 idiv does indeed fault in this case.

The x86 exception is #DE - divide exception. On Unix/Linux systems, the kernel delivers a SIGFPE arithmetic exception signal to processes that cause a #DE exception. (On which platforms does integer divide by zero trigger a floating point exception?)

For div, using a dividend with high_half < divisor is safe. e.g. 0x11:23 / 0x12 is less than 0xff so it fits in an 8-bit quotient.

Extended-precision division of a huge number by a small number can be implemented by using the remainder from one chunk as the high-half dividend (EDX) for the next chunk. This is probably why they chose remainder=EDX quotient=EAX instead of the other way around.

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

I got the same error {AttributeError: 'bytes' object has no attribute 'read'} in python3. This worked for me later without using json:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://someurl/'
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html)
print(soup.prettify('latin-1'))

Column count doesn't match value count at row 1

You can resolve the error by providing the column names you are affecting.

> INSERT INTO table_name (column1,column2,column3)
 `VALUES(50,'Jon Snow','Eye');`

please note that the semi colon should be added only after the statement providing values

How can I convert a zero-terminated byte array to string?

Only use for performance tuning.

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func BytesToString(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}

func StringToBytes(s string) []byte {
    return *(*[]byte)(unsafe.Pointer(&s))
}

func main() {
    b := []byte{'b', 'y', 't', 'e'}
    s := BytesToString(b)
    fmt.Println(s)
    b = StringToBytes(s)
    fmt.Println(string(b))
}

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Example using Hyperlink in WPF

IMHO the simplest way is to use new control inherited from Hyperlink:

/// <summary>
/// Opens <see cref="Hyperlink.NavigateUri"/> in a default system browser
/// </summary>
public class ExternalBrowserHyperlink : Hyperlink
{
    public ExternalBrowserHyperlink()
    {
        RequestNavigate += OnRequestNavigate;
    }

    private void OnRequestNavigate(object sender, RequestNavigateEventArgs e)
    {
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
        e.Handled = true;
    }
}

How to drop all tables in a SQL Server database?

It doesn't work for me either when there are multiple foreign key tables.
I found that code that works and does everything you try (delete all tables from your database):

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR

SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_SCHEMA + '].[' +  tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + '];'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME

OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql

WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec sp_executesql @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END

CLOSE @Cursor DEALLOCATE @Cursor
GO

EXEC sp_MSforeachtable 'DROP TABLE ?'
GO

You can find the post here. It is the post by Groker.

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

Storing C++ template function definitions in a .CPP file

This code is well-formed. You only have to pay attention that the definition of the template is visible at the point of instantiation. To quote the standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

No route matches "/users/sign_out" devise rails 3

See if your routes.rb has a "resource :users" before a "devise_for :users" then try swapping them:

  1. Works

    • devise_for :users
    • resources :users
  2. Fails

    • resources :users
    • devise_for :users

Fill username and password using selenium in python

In some cases when the element is not interactable, sendKeys() doesn't work and you're likely to encounter an ElementNotInteractableException.

In such cases, you can opt to execute javascript that sets the values and then can post back.

Example:

url = 'https://www.your_url.com/'

driver = Chrome(executable_path="./chromedriver")
driver.get(url)

username = 'your_username'
password = 'your_password'

#Setting the value of email input field
driver.execute_script(f'var element = document.getElementById("email"); element.value = "{username}";')

#Setting the value of password input field
driver.execute_script(f'var element = document.getElementById("password"); element.value = "{password}";')

#Submitting the form or click the login button also
driver.execute_script(f'document.getElementsByClassName("login_form")[0].submit();')

print(driver.page_source)

Reference:

https://www.quora.com/How-do-I-resolve-the-ElementNotInteractableException-in-Selenium-WebDriver

Generate 'n' unique random numbers within a range

You could use the random.sample function from the standard library to select k elements from a population:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islice with an infinite random generator:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need n distinct (unique) numbers.

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
    items.add(x)

Run Jquery function on window events: load, resize, and scroll?

just call your function inside the events.

load:

$(document).ready(function(){  // or  $(window).load(function(){
    topInViewport($(mydivname));
});

resize:

$(window).resize(function () {
    topInViewport($(mydivname));
});

scroll:

$(window).scroll(function () {
    topInViewport($(mydivname));
});

or bind all event in one function

$(window).on("load scroll resize",function(e){

What are FTL files

'ftl' stands for freemarker. It combines server side objects and view side (HTML/JQuery) contents into a single viewable template on the client browser.
Some documentation which might help:

http://freemarker.org/docs/

Tutorials:

http://www.vogella.com/tutorials/FreeMarker/article.html

http://viralpatel.net/blogs/freemaker-template-hello-world-tutorial/

How can I create a progress bar in Excel VBA?

About the progressbar control in a userform, it won't show any progress if you don't use the repaint event. You have to code this event inside the looping (and obviously increment the progressbar value).

Example of use:

userFormName.repaint

How to convert base64 string to image?

Return converted image without saving:

from PIL import Image
import cv2

# Take in base64 string and return cv image
def stringToRGB(base64_string):
    imgdata = base64.b64decode(str(base64_string))
    image = Image.open(io.BytesIO(imgdata))
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

Align Div at bottom on main Div

Please try this:

#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;

-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;

-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}

Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.

php mail setup in xampp

My favorite smtp server is hMailServer.

It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.

It can proxy through your gmail/yahoo/etc account or send email directly.

Once it is installed, email in xampp just works with no config changes.

Remove quotes from String in Python

Just use string methods .replace() if they occur throughout, or .strip() if they only occur at the start and/or finish:

a = '"sajdkasjdsak" "asdasdasds"' 

a = a.replace('"', '')
'sajdkasjdsak asdasdasds'

# or, if they only occur at start and end...
a = a.strip('\"')
'sajdkasjdsak" "asdasdasds'

# or, if they only occur at start...
a = a.lstrip('\"')

# or, if they only occur at end...
a = a.rstrip('\"')

Producer/Consumer threads using a Queue

  1. Java code "BlockingQueue" which has synchronized put and get method.
  2. Java code "Producer" , producer thread to produce data.
  3. Java code "Consumer" , consumer thread to consume the data produced.
  4. Java code "ProducerConsumer_Main", main function to start the producer and consumer thread.

BlockingQueue.java

public class BlockingQueue 
{
    int item;
    boolean available = false;

    public synchronized void put(int value) 
    {
        while (available == true)
        {
            try 
            {
                wait();
            } catch (InterruptedException e) { 
            } 
        }

        item = value;
        available = true;
        notifyAll();
    }

    public synchronized int get()
    {
        while(available == false)
        {
            try
            {
                wait();
            }
            catch(InterruptedException e){
            }
        }

        available = false;
        notifyAll();
        return item;
    }
}

Consumer.java

package com.sukanya.producer_Consumer;

public class Consumer extends Thread
{
    blockingQueue queue;
    private int number;
    Consumer(BlockingQueue queue,int number)
    {
        this.queue = queue;
        this.number = number;
    }

    public void run()
    {
        int value = 0;

        for (int i = 0; i < 10; i++) 
        {
            value = queue.get();
            System.out.println("Consumer #" + this.number+ " got: " + value);
        }
    }
}

ProducerConsumer_Main.java

package com.sukanya.producer_Consumer;

public class ProducerConsumer_Main 
{
    public static void main(String args[])
    {
        BlockingQueue queue = new BlockingQueue();
        Producer producer1 = new Producer(queue,1);
        Consumer consumer1 = new Consumer(queue,1);
        producer1.start();
        consumer1.start();
    }
}

Bash: Syntax error: redirection unexpected

Does your script reference /bin/bash or /bin/sh in its hash bang line? The default system shell in Ubuntu is dash, not bash, so if you have #!/bin/sh then your script will be using a different shell than you expect. Dash does not have the <<< redirection operator.

Generate table relationship diagram from existing schema (SQL Server)

Visio Professional has a database reverse-engineering feature if yiu create a database diagram. It's not free but is fairly ubiquitous in most companies and should be fairly easy to get.

Note that Visio 2003 does not play nicely with SQL2005 or SQL2008 for reverse engineering - you will need to get 2007.

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

How do I iterate over an NSArray?

Do this :-

for (id object in array) 
{
        // statement
}

How to create a DB for MongoDB container on start up?

Here another cleaner solution by using docker-compose and a js script.

This example assumes that both files (docker-compose.yml and mongo-init.js) lay in the same folder.

docker-compose.yml

version: '3.7'

services:
    mongodb:
        image: mongo:latest
        container_name: mongodb
        restart: always
        environment:
            MONGO_INITDB_ROOT_USERNAME: <admin-user>
            MONGO_INITDB_ROOT_PASSWORD: <admin-password>
            MONGO_INITDB_DATABASE: <database to create>
        ports:
            - 27017:27017
        volumes:
            - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro

mongo-init.js

db.createUser(
        {
            user: "<user for database which shall be created>",
            pwd: "<password of user>",
            roles: [
                {
                    role: "readWrite",
                    db: "<database to create>"
                }
            ]
        }
);

Then simply start the service by running the following docker-compose command

docker-compose up --build -d mongodb 

Note: The code in the docker-entrypoint-init.d folder is only executed if the database has never been initialized before.

Delete files older than 15 days using PowerShell

#----- Define parameters -----#
#----- Get current date ----#
$Now = Get-Date
$Days = "15" #----- define amount of days ----#
$Targetfolder = "C:\Logs" #----- define folder where files are located ----#
$Extension = "*.log" #----- define extension ----#
$Lastwrite = $Now.AddDays(-$Days)

#----- Get files based on lastwrite filter and specified folder ---#
$Files = Get-Children $Targetfolder -include $Extension -Recurse | where {$_.LastwriteTime -le "$Lastwrite"}

foreach ($File in $Files)
{
    if ($File -ne $Null)
    {
        write-host "Deleting File $File" backgroundcolor "DarkRed"
        Remove-item $File.Fullname | out-null
    }
    else
        write-host "No more files to delete" -forgroundcolor "Green"
    }
}

Edit a commit message in SourceTree Windows (already pushed to remote)

If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)

So I have to use the following method.

CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.

Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.

Step2:

[Situation A]: target commit is the latest one.

1) In the git command console, input

git commit --amend -m "new comment message"

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force

[Situation B]: target commit is not the latest one.

1) In the git command console, input

git rebase -i HEAD~n

It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2. This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq to save&quit.

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force


Finally: In the sourcetree main window, Press F5 to refresh.

How to use onClick() or onSelect() on option tag in a JSP page?

You can change selection in the function

_x000D_
_x000D_
window.onload = function () {_x000D_
  var selectBox = document.getElementById("selectBox");_x000D_
  selectBox.addEventListener('change', changeFunc);_x000D_
  function changeFunc() {_x000D_
    alert(this.value);_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Selection</title>_x000D_
  </head>_x000D_
  <body>_x000D_
    <select id="selectBox" onChange="changeFunc();">_x000D_
      <option> select</option>_x000D_
      <option value="1">Option #1</option>_x000D_
      <option value="2">Option #2</option>_x000D_
   </select>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

PHP send mail to multiple email addresses

It is very bad practice to send all email addresses to all recipients; you should use Bcc (blind carbon copies).

    $from = "[email protected]";
    $recipList = "mailaddress1,mailaddress2,etc";
    $headers = "MIME-Version: 1.0\nContent-type: text/html; charset=utf-8\nFrom: {$from}\nBcc: {$recipList}\nDate: ".date(DATE_RFC2822);
    mail(null,$subject,$message,$headers); //send the eail

Building a fat jar using maven

You can use the maven-shade-plugin.

After configuring the shade plugin in your build the command mvn package will create one single jar with all dependencies merged into it.

How do I make a text input non-editable?

You can use readonly attribute, if you want your input only to be read. And you can use disabled attribute, if you want input to be shown, but totally disabled (even processing languages like PHP wont be able to read those).

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

EDIT: actually, Chromium docs also indicate how to do it for other OS.

Using HttpClient and HttpPost in Android with post parameters

I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

 params.add(new BasicNameValuePair("apikey", apikey);

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?

Find the most common element in a list

Here:

def most_common(l):
    max = 0
    maxitem = None
    for x in set(l):
        count =  l.count(x)
        if count > max:
            max = count
            maxitem = x
    return maxitem

I have a vague feeling there is a method somewhere in the standard library that will give you the count of each element, but I can't find it.

BigDecimal equals() versus compareTo()

You can also compare with double value

BigDecimal a= new BigDecimal("1.1"); BigDecimal b =new BigDecimal("1.1");
System.out.println(a.doubleValue()==b.doubleValue());

Turning off auto indent when pasting text into vim

Native paste / bracketed paste is the best and simplest way since vim 8 (released in 2016). It even works over ssh! (Bracketed paste works on Linux and Mac, but not Windows Git Bash)

  1. Make sure you have vim 8+ (you don't need the +clipboard or +xterm_clipboard options).

    vim --version | head -1

  2. Simply use the OS native paste command (e.g. ctrl+shift+V or cmd+V) in Normal Mode. Do not press i for Insert Mode.


Test

  1. Copy (ctrl+shift+C or cmd+C) the output of this (2 lines with a tab indent) to the system clipboard:

    echo -e '\ta\n\tb'

  2. Launch a clean vim 8+ with autoindent:

    vim -u NONE --noplugin -c 'set autoindent'

  3. Paste from the system clipboard (ctrl+shift+V or cmd+V) in Normal Mode. Do not press i for Insert Mode. The a and b should be aligned with a single tab indent. You can even do this while ssh-ing to a remote machine (the remote machine will need vim 8+).

  4. Now try the old way, which will autoindent the second line with an extra tab: Press i for Insert Mode. Then paste using ctrl+shift+V or cmd+V. The a and b are misaligned now.


Installing Vim 8

Add new element to an existing object

You can use Extend to add new objects to an existing one.

intl extension: installing php_intl.dll

There is a better way of doing this.

I was having same kind of problem with ldap, intl, curl php extensions. I've solved those issues by the following ways:

At first you've to check whether these extensions have been enabled in the php.ini file by removing semicolon (;) in front of the following lines:

;extension=php_intl.dll
;extension=php_ldap.dll
;extension=php_curl.dll

Now you can directly load those necessary dll files (ie libeay32, libssh2, ssleay32, icu**.dll ) from your httpd.conf (apache configuratio file) file. You don't have to do any other things like copying them to the apache's bin directory or php's ext directory. Just add them directly in you apache's httpd.conf file.

Please note that the followng example is for php version 5.5.x.

LoadFile  "C:/php/icudt51.dll"
LoadFile  "C:/php/icuin51.dll"
LoadFile  "C:/php/icuio51.dll"
LoadFile  "C:/php/icule51.dll"
LoadFile  "C:/php/iculx51.dll"
LoadFile  "C:/php/icutest51.dll"
LoadFile  "C:/php/icutu51.dll"
LoadFile  "C:/php/icuuc51.dll"

LoadFile  "C:/php/libeay32.dll"
LoadFile  "C:/php/libssh2.dll"
LoadFile  "C:/php/ssleay32.dll"

That's it. Now, restart your apache or wamp and you're good to go.

How can I pretty-print JSON using node.js?

I know this is old question. But maybe this can help you

JSON string

var jsonStr = '{ "bool": true, "number": 123, "string": "foo bar" }';

Pretty Print JSON

JSON.stringify(JSON.parse(jsonStr), null, 2);

Minify JSON

JSON.stringify(JSON.parse(jsonStr));

OTP (token) should be automatically read from the message

With the SMS Retriever API, one can Read OTP without declaring android.permission.READ_SMS.

  1. Start the SMS retriever
    private fun startSMSRetriever() {
        // Get an instance of SmsRetrieverClient, used to start listening for a matching SMS message.
        val client = SmsRetriever.getClient(this /* context */);

        // Starts SmsRetriever, which waits for ONE matching SMS message until timeout
        // (5 minutes). The matching SMS message will be sent via a Broadcast Intent with
        // action SmsRetriever#SMS_RETRIEVED_ACTION.
        val task: Task<Void> = client.startSmsRetriever();

        // Listen for success/failure of the start Task. If in a background thread, this
        // can be made blocking using Tasks.await(task, [timeout]);
        task.addOnSuccessListener {
            Log.d("SmsRetriever", "SmsRetriever Start Success")
        }

        task.addOnFailureListener {
            Log.d("SmsRetriever", "SmsRetriever Start Failed")
        }
    }
  1. Receive messages via Broadcast
    public class MySMSBroadcastReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent?) {
            if (SmsRetriever.SMS_RETRIEVED_ACTION == intent?.action && intent.extras!=null) {
                val extras = intent.extras
                val status = extras.get(SmsRetriever.EXTRA_STATUS) as Status

                when (status.statusCode) {
                    CommonStatusCodes.SUCCESS -> {
                        // Get SMS message contents
                        val message = extras.get(SmsRetriever.EXTRA_SMS_MESSAGE) as String
                        Log.e("Message", message);
                        // Extract one-time code from the message and complete verification
                        // by sending the code back to your server.
                    }
                    CommonStatusCodes.TIMEOUT -> {
                        // Waiting for SMS timed out (5 minutes)
                        // Handle the error ...
                    }
                }
            }
        }

    }   


    /**Don't forgot to define BroadcastReceiver in AndroidManifest.xml.*/       
    <receiver android:name=".MySMSBroadcastReceiver" android:exported="true">
        <intent-filter>
            <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
        </intent-filter>
    </receiver>
  1. Send the one-time code from the verification message to your server

Make sure your SMS format is exactly as below:

<#> Your ExampleApp code is: 123ABC78
fBzOyyp9h6L
  1. Be no longer than 140 bytes
  2. Begin with the prefix <#>
  3. End with an 11-character hash string that identifies your app

    You can compute app hash with following code:

    import android.content.Context
    import android.content.ContextWrapper
    import android.content.pm.PackageManager
    import android.util.Base64
    import android.util.Log
    import java.nio.charset.StandardCharsets
    import java.security.MessageDigest
    import java.security.NoSuchAlgorithmException
    import java.util.*
    
    /**
     * This is a helper class to generate your message hash to be included in your SMS message.
     *
     * Without the correct hash, your app won't recieve the message callback. This only needs to be
     * generated once per app and stored. Then you can remove this helper class from your code.
     *
     * For More Detail: https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string
     *
     */
    public class AppSignatureHelper(private val context: Context) : ContextWrapper(context) {
    
        companion object {
            val TAG = AppSignatureHelper::class.java.simpleName;
    
            private const val HASH_TYPE = "SHA-256";
            const val NUM_HASHED_BYTES = 9;
            const val NUM_BASE64_CHAR = 11;
        }
    
        /**
         * Get all the app signatures for the current package
         * @return
         */
        public fun getAppSignatures(): ArrayList<String> {
            val appCodes = ArrayList<String>();
    
            try {
                // Get all package signatures for the current package
                val signatures = packageManager.getPackageInfo(
                    packageName,
                    PackageManager.GET_SIGNATURES
                ).signatures;
    
                // For each signature create a compatible hash
                for (signature in signatures) {
                    val hash = hash(packageName, signature.toCharsString());
                    if (hash != null) {
                        appCodes.add(String.format("%s", hash));
                    }
                }
            } catch (e: PackageManager.NameNotFoundException) {
                Log.e(TAG, "Unable to find package to obtain hash.", e);
            }
            return appCodes;
        }
    
        private fun hash(packageName: String, signature: String): String? {
            val appInfo = "$packageName $signature";
            try {
                val messageDigest = MessageDigest.getInstance(HASH_TYPE);
                messageDigest.update(appInfo.toByteArray(StandardCharsets.UTF_8));
                var hashSignature = messageDigest.digest();
    
                // truncated into NUM_HASHED_BYTES
                hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES);
                // encode into Base64
                var base64Hash = Base64.encodeToString(hashSignature, Base64.NO_PADDING or Base64.NO_WRAP);
                base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR);
    
                Log.e(TAG, String.format("pkg: %s -- hash: %s", packageName, base64Hash));
                return base64Hash;
            } catch (e: NoSuchAlgorithmException) {
                Log.e(TAG, "hash:NoSuchAlgorithm", e);
            }
            return null;
        }
    }       
    

Required Gradle :

implementation "com.google.android.gms:play-services-auth-api-phone:16.0.0"

References:
https://developers.google.com/identity/sms-retriever/overview
https://developers.google.com/identity/sms-retriever/request
https://developers.google.com/identity/sms-retriever/verify

Where do I put image files, css, js, etc. in Codeigniter?

(I am new to Codeigniter, so I don't know if this is the best advice)

I keep publicly available files in my public folder. It is logical for them to be there, and I don't want to use Codeigniter for something I don't need to use it for.

The directory tree looks likes this:

  • /application/
  • /public/
  • /public/css/
  • /public/img/
  • /public/js/
  • /system/

The only files I keep in /public/ are Codeigniter's index.php, and my .htaccess file:

RewriteEngine On
RewriteBase /

RewriteRule ^css/ - [L]
RewriteRule ^img/ - [L]
RewriteRule ^js/ - [L]

RewriteRule ^index.php(.*)$ - [L]
RewriteRule ^(.*)$ /index.php?/$1 [L]

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

The number of possible binary search tree with n nodes (elements,items) is

=(2n C n) / (n+1) = ( factorial (2n) / factorial (n) * factorial (2n - n) ) / ( n + 1 ) 

where 'n' is number of nodes  (elements,items ) 

Example :

for 
n=1 BST=1,
n=2 BST 2,
n=3 BST=5,
n=4 BST=14 etc

How do I write a Python dictionary to a csv file?

You are using DictWriter.writerows() which expects a list of dicts, not a dict. You want DictWriter.writerow() to write a single row.

You will also want to use DictWriter.writeheader() if you want a header for you csv file.

You also might want to check out the with statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.

Example with these changes made:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:  # You will need 'wb' mode in Python 2.x
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

Which produces:

test,testing
1,2

How to change option menu icon in the action bar?

The following lines should be updated in app -> main -> res -> values -> Styles.xml

 <!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>
</style>

<!-- Style to replace actionbar overflow icon. set item 'android:actionOverflowButtonStyle' in AppTheme -->
<style name="MyActionButtonOverflow" parent="android:style/Widget.Holo.Light.ActionButton.Overflow">
    <item name="android:src">@drawable/ic_launcher</item>
    <item name="android:background">?android:attr/actionBarItemBackground</item>
    <item name="android:contentDescription">"Lala"</item>
</style>

This is how it can be done. If you want to change the overflow icon in action bar

Pass object to javascript function

when you pass an object within curly braces as an argument to a function with one parameter , you're assigning this object to a variable which is the parameter in this case

Winforms issue - Error creating window handle

Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns... Then run your app and take a look at those columns for that app and see if one of those is growing really large.

It might be that you've got UI components that you think are cleaned up but haven't been Disposed.

Here's a link about this that might be helpful.

Good Luck!

When to use async false and async true in ajax function in jquery

  1. When async setting is set to false, a Synchronous call is made instead of an Asynchronous call.
  2. When the async setting of the jQuery AJAX function is set to true then a jQuery Asynchronous call is made. AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.
  3. for more information please refer this link

Import MySQL database into a MS SQL Server

I found a way for this on the net

It demands a little bit of work, because it has to be done table by table. But anyway, I could copy the tables, data and constraints into a MS SQL database.

Here is the link

http://www.codeproject.com/KB/database/migrate-mysql-to-mssql.aspx

Error handling in AngularJS http get then construct

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })

Visual Studio Code compile on save

I implemented compile on save with gulp task using gulp-typescript and incremental build. This allows to control compilation whatever you want. Notice my variable tsServerProject, in my real project I also have tsClientProject because I want to compile my client code with no module specified. As I know you can't do it with vs code.

var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    sourcemaps = require('gulp-sourcemaps');

var tsServerProject = ts.createProject({
   declarationFiles: false,
   noExternalResolve: false,
   module: 'commonjs',
   target: 'ES5'
});

var srcServer = 'src/server/**/*.ts'

gulp.task('watch-server', ['compile-server'], watchServer);
gulp.task('compile-server', compileServer);

function watchServer(params) {
   gulp.watch(srcServer, ['compile-server']);
}

function compileServer(params) {
   var tsResult = gulp.src(srcServer)
      .pipe(sourcemaps.init())
      .pipe(ts(tsServerProject));

   return tsResult.js
      .pipe(sourcemaps.write('./source-maps'))
      .pipe(gulp.dest('src/server/'));

}

How can I use NSError in my iPhone App?

I would like to add some more suggestions based on my most recent implementation. I've looked at some code from Apple and I think my code behaves in much the same way.

The posts above already explain how to create NSError objects and return them, so I won't bother with that part. I'll just try to suggest a good way to integrate errors (codes, messages) in your own app.


I recommend creating 1 header that will be an overview of all the errors of your domain (i.e. app, library, etc..). My current header looks like this:

FSError.h

FOUNDATION_EXPORT NSString *const FSMyAppErrorDomain;

enum {
    FSUserNotLoggedInError = 1000,
    FSUserLogoutFailedError,
    FSProfileParsingFailedError,
    FSProfileBadLoginError,
    FSFNIDParsingFailedError,
};

FSError.m

#import "FSError.h" 

NSString *const FSMyAppErrorDomain = @"com.felis.myapp";

Now when using the above values for errors, Apple will create some basic standard error message for your app. An error could be created like the following:

+ (FSProfileInfo *)profileInfoWithData:(NSData *)data error:(NSError **)error
{
    FSProfileInfo *profileInfo = [[FSProfileInfo alloc] init];
    if (profileInfo)
    {
        /* ... lots of parsing code here ... */

        if (profileInfo.username == nil)
        {
            *error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSProfileParsingFailedError userInfo:nil];            
            return nil;
        }
    }
    return profileInfo;
}

The standard Apple-generated error message (error.localizedDescription) for the above code will look like the following:

Error Domain=com.felis.myapp Code=1002 "The operation couldn’t be completed. (com.felis.myapp error 1002.)"

The above is already quite helpful for a developer, since the message displays the domain where the error occured and the corresponding error code. End users will have no clue what error code 1002 means though, so now we need to implement some nice messages for each code.

For the error messages we have to keep localisation in mind (even if we don't implement localized messages right away). I've used the following approach in my current project:


1) create a strings file that will contain the errors. Strings files are easily localizable. The file could look like the following:

FSError.strings

"1000" = "User not logged in.";
"1001" = "Logout failed.";
"1002" = "Parser failed.";
"1003" = "Incorrect username or password.";
"1004" = "Failed to parse FNID."

2) Add macros to convert integer codes to localized error messages. I've used 2 macros in my Constants+Macros.h file. I always include this file in the prefix header (MyApp-Prefix.pch) for convenience.

Constants+Macros.h

// error handling ...

#define FS_ERROR_KEY(code)                    [NSString stringWithFormat:@"%d", code]
#define FS_ERROR_LOCALIZED_DESCRIPTION(code)  NSLocalizedStringFromTable(FS_ERROR_KEY(code), @"FSError", nil)

3) Now it's easy to show a user friendly error message based on an error code. An example:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
            message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code) 
            delegate:nil 
            cancelButtonTitle:@"OK" 
            otherButtonTitles:nil];
[alert show];

Pass a JavaScript function as parameter

You can also use eval() to do the same thing.

//A function to call
function needToBeCalled(p1, p2)
{
    alert(p1+"="+p2);
}

//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
    eval(aFunction + "("+params+")");
}

//A function Call
callAnotherFunction("needToBeCalled", "10,20");

That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

I have also encountered this error . Just i opened the new window ie Window -> New Window in eclipse .Then , I closed my old window. This solved my problem.

Cluster analysis in R: determine the optimal number of clusters

The answers are great. If you want to give a chance to another clustering method you can use hierarchical clustering and see how data is splitting.

> set.seed(2)
> x=matrix(rnorm(50*2), ncol=2)
> hc.complete = hclust(dist(x), method="complete")
> plot(hc.complete)

enter image description here

Depending on how many classes you need you can cut your dendrogram as;

> cutree(hc.complete,k = 2)
 [1] 1 1 1 2 1 1 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 2 1 1 1
[26] 2 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 2 1 1 1 1 1 1 1 2

If you type ?cutree you will see the definitions. If your data set has three classes it will be simply cutree(hc.complete, k = 3). The equivalent for cutree(hc.complete,k = 2) is cutree(hc.complete,h = 4.9).

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

It turns out that the solution is to stop all the related services and solve the “Another daemon is already running” issue.

The commands i used to solve the issue are as follows:

sudo /opt/lampp/lampp stop              
sudo /etc/init.d/apache2 stop    
sudo /etc/init.d/mysql stop

Or, you can also type instead:

sudo service apache2 stop
sudo service mysql stop

After that, we again start the lampp services:

sudo /opt/lampp/lampp start

Now, there must be no problems while opening:

http://localhost                  
http://localhost/phpmyadmin

WCF error: The caller was not authenticated by the service

Have you tried using basicHttpBinding instead of wsHttpBinding? If do not need any authentication and the Ws-* implementations are not required, you'd probably be better off with plain old basicHttpBinding. WsHttpBinding implements WS-Security for message security and authentication.

Highcharts - redraw() vs. new Highcharts.chart

you have to call set and add functions on chart object before calling redraw.

chart.xAxis[0].setCategories([2,4,5,6,7], false);

chart.addSeries({
    name: "acx",
    data: [4,5,6,7,8]
}, false);

chart.redraw();

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

Put your url here Facebook Login -> Settings -> Valid OAuth redirect URIs AND you'll also get that error if your APP ID is wrong

Table column sizing

Another option is to apply flex styling at the table row, and add the col-classes to the table header / table data elements:

<table>
  <thead>
    <tr class="d-flex">
      <th class="col-3">3 columns wide header</th>
      <th class="col-sm-5">5 columns wide header</th>
      <th class="col-sm-4">4 columns wide header</th>
    </tr>
  </thead>
  <tbody>
    <tr class="d-flex">
      <td class="col-3">3 columns wide content</th>
      <td class="col-sm-5">5 columns wide content</th>
      <td class="col-sm-4">4 columns wide content</th>
    </tr>
  </tbody>
</table>

What is the right way to populate a DropDownList from a database?

((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;

React Native add bold or italics to single words in <Text> field

enter image description here

I am a maintainer of react-native-spannable-string

Nested <Text/> component with custom style works well but maintainability is low.

I suggest you build spannable string like this with this library.

SpannableBuilder.getInstance({ fontSize: 24 })
    .append('Using ')
    .appendItalic('Italic')
    .append(' in Text')
    .build()

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

Padding is invalid and cannot be removed?

If the same key and initialization vector are used for encoding and decoding, this issue does not come from data decoding but from data encoding.

After you called Write method on a CryptoStream object, you must ALWAYS call FlushFinalBlock method before Close method.

MSDN documentation on CryptoStream.FlushFinalBlock method says:
"Calling the Close method will call FlushFinalBlock ..."
https://msdn.microsoft.com/en-US/library/system.security.cryptography.cryptostream.flushfinalblock(v=vs.110).aspx
This is wrong. Calling Close method just closes the CryptoStream and the output Stream.
If you do not call FlushFinalBlock before Close after you wrote data to be encrypted, when decrypting data, a call to Read or CopyTo method on your CryptoStream object will raise a CryptographicException exception (message: "Padding is invalid and cannot be removed").

This is probably true for all encryption algorithms derived from SymmetricAlgorithm (Aes, DES, RC2, Rijndael, TripleDES), although I just verified that for AesManaged and a MemoryStream as output Stream.

So, if you receive this CryptographicException exception on decryption, read your output Stream Length property value after you wrote your data to be encrypted, then call FlushFinalBlock and read its value again. If it has changed, you know that calling FlushFinalBlock is NOT optional.

And you do not need to perform any padding programmatically, or choose another Padding property value. Padding is FlushFinalBlock method job.

.........

Additional remark for Kevin:

Yes, CryptoStream calls FlushFinalBlock before calling Close, but it is too late: when CryptoStream Close method is called, the output stream is also closed.

If your output stream is a MemoryStream, you cannot read its data after it is closed. So you need to call FlushFinalBlock on your CryptoStream before using the encrypted data written on the MemoryStream.

If your output stream is a FileStream, things are worse because writing is buffered. The consequence is last written bytes may not be written to the file if you close the output stream before calling Flush on FileStream. So before calling Close on CryptoStream you first need to call FlushFinalBlock on your CryptoStream then call Flush on your FileStream.

What is a constant reference? (not a reference to a constant)

What is a constant reference (not a reference to a constant)
A Constant Reference is actually a Reference to a Constant.

A constant reference/ Reference to a constant is denoted by:

int const &i = j; //or Alternatively
const int &i = j;
i = 1;            //Compilation Error

It basically means, you cannot modify the value of type object to which the Reference Refers.
For Example:
Trying to modify value(assign 1) of variable j through const reference, i will results in error:

assignment of read-only reference ‘i’


icr=y;          // Can change the object it is pointing to so it's not like a const pointer...
icr=99;

Doesn't change the reference, it assigns the value of the type to which the reference refers. References cannot be made to refer any other variable than the one they are bound to at Initialization.

First statement assigns the value y to i
Second statement assigns the value 99 to i

Creating an Array from a Range in VBA

Using Value2 gives a performance benefit. As per Charles Williams blog

Range.Value2 works the same way as Range.Value, except that it does not check the cell format and convert to Date or Currency. And thats probably why its faster than .Value when retrieving numbers.

So

DirArray = [a1:a5].Value2

Bonus Reading

  • Range.Value: Returns or sets a Variant value that represents the value of the specified range.
  • Range.Value2: The only difference between this property and the Value property is that the Value2 property doesn't use the Currency and Date data types.

Getting the last revision number in SVN?

nickh@SCLLNHENRY:~/Work/standingcloud/svn/main/trunk/dev/scripts$ svnversion
12354

Or

nickh@SCLLNHENRY:~/Work/standingcloud/svn/main/trunk/dev/scripts$ svn info --xml |     xmlstarlet sel -t --value-of "//entry/@revision"
12354

Or

nickh@SCLLNHENRY:~/Work/standingcloud/svn/main/trunk/dev/scripts$ svn info --xml | xmlstarlet sel -t --value-of "//commit/@revision"
12335

Span inside anchor or anchor inside span or doesn't matter?

SPAN is a GENERIC inline container. It does not matter whether an a is inside span or span is inside a as both are inline elements. Feel free to do whatever seems logically correct to you.

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

I have to modify the following files

$CATALINA_BASE/conf/Catalina/localhost/manager.xml and add following line

  <Context privileged="true" antiResourceLocking="false" 
     docBase="${catalina.home}/webapps/manager">
        <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^.*$" />
  </Context>

This will allow tomcat to be accessed from any machine, if you want to grant access to specific IP then use the below value instead of allow="^.*$"

    <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="192\.168\.11\.234" />

Add a custom attribute to a Laravel / Eloquent model on load?

in my case, creating an empty column and setting its accessor worked fine. my accessor filling user's age from dob column. toArray() function worked too.

public function getAgeAttribute()
{
  return Carbon::createFromFormat('Y-m-d', $this->attributes['dateofbirth'])->age;
}

How to recover closed output window in netbeans?

in Netbeans 7.4 try Window -> Output OR Ctrl + 4

Checking for NULL pointer in C/C++

if (foo) is clear enough. Use it.

Visual c++ can't open include file 'iostream'

    // first.cpp -- displays a message


#include <iostream>   // a PREPROCESSOR directive
using namesapce std;
int main()        // function header
{             // start of a function body
  ///using namespace std;
  cout << "Come up and C++ me sometime.\n";  // message
  // start a new line
  cout << "Here is the total: 1000.00\n";
  cout << "Here we go!\n";
  return 0;
}

C# how to change data in DataTable?

dt.Rows[1].ItemArray gives you a copy of item arrays. When you modify it, you're not modifying the original.

You can simply do this:

dt.Rows[1][3] = "Value";

ItemArray property is used when you want to modify all row values.

ex.:

dt.Rows[1].ItemArray = newItemArray;

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

Heap space out of memory

No. The heap is cleared by the garbage collector whenever it feels like it. You can ask it to run (with System.gc()) but it is not guaranteed to run.

First try increasing the memory by setting -Xmx256m

XDocument or XmlDocument

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument. If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

I've just started using LINQ to XML, and I love the way you create an XML document using functional construction. It's really nice. DOM is clunky in comparison.

Doctrine 2: Update query with query builder

With a small change, it worked fine for me

$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
               ->update()
               ->field('status')->set($status)
               ->field('id')->equals($instrumentId)
               ->getQuery()
               ->execute();

Include headers when using SELECT INTO OUTFILE?

MySQL alone isn't enough to do this simply. Below is a PHP script that will output columns and data to CSV.

Enter your database name and tables near the top.

<?php

set_time_limit( 24192000 );
ini_set( 'memory_limit', '-1' );
setlocale( LC_CTYPE, 'en_US.UTF-8' );
mb_regex_encoding( 'UTF-8' );

$dbn = 'DB_NAME';
$tbls = array(
'TABLE1',
'TABLE2',
'TABLE3'
);

$db = new PDO( 'mysql:host=localhost;dbname=' . $dbn . ';charset=UTF8', 'root', 'pass' );

foreach( $tbls as $tbl )
{
    echo $tbl . "\n";
    $path = '/var/lib/mysql/' . $tbl . '.csv';

    $colStr = '';
    $cols = $db->query( 'SELECT COLUMN_NAME AS `column` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $tbl . '" AND TABLE_SCHEMA = "' . $dbn . '"' )->fetchAll( PDO::FETCH_COLUMN );
    foreach( $cols as $col )
    {
        if( $colStr ) $colStr .= ', ';
        $colStr .= '"' . $col . '"';
    }

    $db->query(
    'SELECT *
    FROM
    (
        SELECT ' . $colStr . '
        UNION ALL
        SELECT * FROM ' . $tbl . '
    ) AS sub
    INTO OUTFILE "' . $path . '"
    FIELDS TERMINATED BY ","
    ENCLOSED BY "\""
    LINES TERMINATED BY "\n"'
    );

    exec( 'gzip ' . $path );

    print_r( $db->errorInfo() );
}

?>

You'll need this to be the directory you'd like to output to. MySQL needs to have the ability to write to the directory.

$path = '/var/lib/mysql/' . $tbl . '.csv';

You can edit the CSV export options in the query:

INTO OUTFILE "' . $path . '"
FIELDS TERMINATED BY ","
ENCLOSED BY "\""
LINES TERMINATED BY "\n"'

At the end there is an exec call to GZip the CSV.

How to include libraries in Visual Studio 2012?

Typically you need to do 5 things to include a library in your project:

1) Add #include statements necessary files with declarations/interfaces, e.g.:

#include "library.h"

2) Add an include directory for the compiler to look into

-> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)

3) Add a library directory for *.lib files:

-> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)

4) Link the lib's *.lib files

-> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;

5) Place *.dll files either:

-> in the directory you'll be opening your final executable from or into Windows/system32

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

Having that:

public interface ITerm
{
    string Name { get; }
}

public class Value : ITerm...

public class Variable : ITerm...

public class Query
{
   public IList<ITerm> Terms { get; }
...
}

I managed conversion trick implementing that:

public class TermConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var field = value.GetType().Name;
        writer.WriteStartObject();
        writer.WritePropertyName(field);
        writer.WriteValue((value as ITerm)?.Name);
        writer.WriteEndObject();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        var jsonObject = JObject.Load(reader);
        var properties = jsonObject.Properties().ToList();
        var value = (string) properties[0].Value;
        return properties[0].Name.Equals("Value") ? (ITerm) new Value(value) : new Variable(value);
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof (ITerm) == objectType || typeof (Value) == objectType || typeof (Variable) == objectType;
    }
}

It allows me to serialize and deserialize in JSON like:

string JsonQuery = "{\"Terms\":[{\"Value\":\"This is \"},{\"Variable\":\"X\"},{\"Value\":\"!\"}]}";
...
var query = new Query(new Value("This is "), new Variable("X"), new Value("!"));
var serializeObject = JsonConvert.SerializeObject(query, new TermConverter());
Assert.AreEqual(JsonQuery, serializeObject);
...
var queryDeserialized = JsonConvert.DeserializeObject<Query>(JsonQuery, new TermConverter());

Is module __file__ attribute absolute or relative?

Late simple example:

from os import path, getcwd, chdir

def print_my_path():
    print('cwd:     {}'.format(getcwd()))
    print('__file__:{}'.format(__file__))
    print('abspath: {}'.format(path.abspath(__file__)))

print_my_path()

chdir('..')

print_my_path()

Under Python-2.*, the second call incorrectly determines the path.abspath(__file__) based on the current directory:

cwd:     C:\codes\py
__file__:cwd_mayhem.py
abspath: C:\codes\py\cwd_mayhem.py
cwd:     C:\codes
__file__:cwd_mayhem.py
abspath: C:\codes\cwd_mayhem.py

As noted by @techtonik, in Python 3.4+, this will work fine since __file__ returns an absolute path.

Swift addsubview and remove it

Tested this code using XCode 8 and Swift 3

To Add Custom View to SuperView use:

self.view.addSubview(myView)

To Remove Custom View from Superview use:

self.view.willRemoveSubview(myView)

How can I get browser to prompt to save password?

The browser might not be able to detect that your form is a login form. According to some of the discussion in this previous question, a browser looks for form fields that look like <input type="password">. Is your password form field implemented similar to that?

Edit: To answer your questions below, I think Firefox detects passwords by form.elements[n].type == "password" (iterating through all form elements) and then detects the username field by searching backwards through form elements for the text field immediately before the password field (more info here). From what I can tell, your login form needs to be part of a <form> or Firefox won't detect it.

complex if statement in python

if
  ...
  # several checks
  ...
elif not (1024<=var<=65535 or var == 80 or var == 443)
  # fail
else
  ...

Multiple Inheritance in C#

Consider just using composition instead of trying to simulate Multiple Inheritance. You can use Interfaces to define what classes make up the composition, eg: ISteerable implies a property of type SteeringWheel, IBrakable implies a property of type BrakePedal, etc.

Once you've done that, you could use the Extension Methods feature added to C# 3.0 to further simplify calling methods on those implied properties, eg:

public interface ISteerable { SteeringWheel wheel { get; set; } }

public interface IBrakable { BrakePedal brake { get; set; } }

public class Vehicle : ISteerable, IBrakable
{
    public SteeringWheel wheel { get; set; }

    public BrakePedal brake { get; set; }

    public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }
}

public static class SteeringExtensions
{
    public static void SteerLeft(this ISteerable vehicle)
    {
        vehicle.wheel.SteerLeft();
    }
}

public static class BrakeExtensions
{
    public static void Stop(this IBrakable vehicle)
    {
        vehicle.brake.ApplyUntilStop();
    }
}


public class Main
{
    Vehicle myCar = new Vehicle();

    public void main()
    {
        myCar.SteerLeft();
        myCar.Stop();
    }
}

Converting between strings and ArrayBuffers

In case you have binary data in a string (obtained from nodejs + readFile(..., 'binary'), or cypress + cy.fixture(..., 'binary'), etc), you can't use TextEncoder. It supports only utf8. Bytes with values >= 128 are each turned into 2 bytes.

ES2015:

a = Uint8Array.from(s, x => x.charCodeAt(0))

Uint8Array(33) [2, 134, 140, 186, 82, 70, 108, 182, 233, 40, 143, 247, 29, 76, 245, 206, 29, 87, 48, 160, 78, 225, 242, 56, 236, 201, 80, 80, 152, 118, 92, 144, 48

s = String.fromCharCode.apply(null, a)

"ºRFl¶é(÷LõÎW0 Náò8ìÉPPv\0"

jQuery ajax success error

I had the same problem;

textStatus = 'error'
errorThrown = (empty)
xhr.status = 0

That fits my problem exactly. It turns out that when I was loading the HTML-page from my own computer this problem existed, but when I loaded the HTML-page from my webserver it went alright. Then I tried to upload it to another domain, and again the same error occoured. Seems to be a cross-domain problem. (in my case at least)

I have tried calling it this way also:

var request = $.ajax({
url: "http://crossdomain.url.net/somefile.php", dataType: "text",
crossDomain: true,
xhrFields: {
withCredentials: true
}
});

but without success.

This post solved it for me: jQuery AJAX cross domain

What is output buffering?

Output Buffering for Web Developers, a Beginner’s Guide:

Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.

Advantages of output buffering for Web developers

  • Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
  • All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
  • If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.