Programs & Examples On #Winelib

ITextSharp HTML to PDF?

2020 UPDATE:

Converting HTML to PDF is very simple to do now. All you have to do is use NuGet to install itext7 and itext7.pdfhtml. You can do this in Visual Studio by going to "Project" > "Manage NuGet Packages..."

Make sure to include this dependency:

using iText.Html2pdf;

Now literally just paste this one liner and you're done:

HtmlConverter.ConvertToPdf(new FileInfo(@"temp.html"), new FileInfo(@"report.pdf"));

If you're running this example in visual studio, your html file should be in the /bin/Debug directory.

If you're interested, here's a good resource. Also, note that itext7 is licensed under AGPL.

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

In Windows 10 preview build with PowerShell 5, I can see that you can do:

$info = Get-Package -Name YourInstalledProduct
$info.Metadata["ProductCode"]

Not familiar with even not sure if all products has UpgradeCode, but according to this post you need to search UpgradeCode from this registry path:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UpgradeCodes

Unfortunately, the registry key values are the ProductCode and the registry keys are the UpgradeCode.

Split string and get first value only

These are the two options I managed to build, not having the luxury of working with var type, nor with additional variables on the line:

string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);

string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);

This is what it gets:

enter image description here

Getting an option text/value with JavaScript

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

What's the difference between import java.util.*; and import java.util.Date; ?

but what I got is something like this: Date@124bbbf  
while I change the import to: import java.util.Date;  
the code works perfectly, why? 

What do you mean by "works perfectly"? The output of printing a Date object is the same no matter whether you imported java.util.* or java.util.Date. The output that you get when printing objects is the representation of the object by the toString() method of the corresponding class.

Rails 3 execute custom sql query without a model

You could also use find_by_sql

# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

How to get the cookie value in asp.net website

FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;

and decrypt that.

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.

I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.

Could it be a mistake in my implementation that looks like this (PHP - server side):

$data = array();

$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);

$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);

$jsonString = "[" . implode(", ", $data) . "]";

The final step is that I store the JSON encoded string into an JS variable:

<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>

If I use "" instead of '' it still throws an error.

SOLUTION:

The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:

json_encode($tmp, JSON_HEX_APOS);

Is there another way of tackle this issue? Is my code wrong or poorly written?

Thanks

How to get status code from webclient?

There is a way to do it using reflection. It works with .NET 4.0. It accesses a private field and may not work in other versions of .NET without modifications.

I have no idea why Microsoft did not expose this field with a property.

private static int GetStatusCode(WebClient client, out string statusDescription)
{
    FieldInfo responseField = client.GetType().GetField("m_WebResponse", BindingFlags.Instance | BindingFlags.NonPublic);

    if (responseField != null)
    {
        HttpWebResponse response = responseField.GetValue(client) as HttpWebResponse;

        if (response != null)
        {
            statusDescription = response.StatusDescription;
            return (int)response.StatusCode;
        }
    }

    statusDescription = null;
    return 0;
}

What is a StackOverflowError?

If you have a function like:

int foo()
{
    // more stuff
    foo();
}

Then foo() will keep calling itself, getting deeper and deeper, and when the space used to keep track of what functions you're in is filled up, you get the stack overflow error.

.NET HttpClient. How to POST string value?

using System;
using System.Collections.Generic;
using System.Net.Http;

class Program
{
    static void Main(string[] args)
    {
        Task.Run(() => MainAsync());
        Console.ReadLine();
    }

    static async Task MainAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:6740");
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("", "login")
            });
            var result = await client.PostAsync("/api/Membership/exists", content);
            string resultContent = await result.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
        }
    }
}

How do you debug PHP scripts?

1) I use print_r(). In TextMate, I have a snippet for 'pre' which expands to this:

echo "<pre>";
print_r();
echo "</pre>";

2) I use Xdebug, but haven't been able to get the GUI to work right on my Mac. It at least prints out a readable version of the stack trace.

Is there a way to pass optional parameters to a function?

If you want give some default value to a parameter assign value in (). like (x =10). But important is first should compulsory argument then default value.

eg.

(y, x =10)

but

(x=10, y) is wrong

How to avoid soft keyboard pushing up my layout?

In my case, the reason the buttons got pushed up was because the view above them was a ScrollView, and it got collapsed with the buttons pushed up above the keyboard no matter what value of android:windowSoftInputMode I was setting.

I was able to avoid my bottom row of buttons getting pushed up by the soft keyboard by setting

android:isScrollContainer="false" 

on the ScrollView that sits above the buttons.

Time complexity of accessing a Python dict

To answer your specific questions:

Q1:
"Am I correct that python dicts suffer from linear access times with such inputs?"

A1: If you mean that average lookup time is O(N) where N is the number of entries in the dict, then it is highly likely that you are wrong. If you are correct, the Python community would very much like to know under what circumstances you are correct, so that the problem can be mitigated or at least warned about. Neither "sample" code nor "simplified" code are useful. Please show actual code and data that reproduce the problem. The code should be instrumented with things like number of dict items and number of dict accesses for each P where P is the number of points in the key (2 <= P <= 5)

Q2:
"As far as I know, sets have guaranteed logarithmic access times. How can I simulate dicts using sets(or something similar) in Python?"

A2: Sets have guaranteed logarithmic access times in what context? There is no such guarantee for Python implementations. Recent CPython versions in fact use a cut-down dict implementation (keys only, no values), so the expectation is average O(1) behaviour. How can you simulate dicts with sets or something similar in any language? Short answer: with extreme difficulty, if you want any functionality beyond dict.has_key(key).

How to form a correct MySQL connection string?

try creating connection string this way:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{    //watch out for this SQL injection vulnerability below
     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
                                    OSGconv.deciLat, OSGconv.deciLon);
     conn.Open();
     cmd.ExecuteNonQuery();
}

How to compare binary files to check if they are the same?

Use cmp command. This will either exit cleanly if they are binary equal, or it will print out where the first difference occurs and exit.

Can I limit the length of an array in JavaScript?

You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.

You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).

You should convert the shortened array back to a string with .join(",") and then use it for the new cookie instead of using old_cookie which is not shortened.

You may also not be using .splice() correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice() here.

How to disable Paste (Ctrl+V) with jQuery?

I tried this in my Angular project and it worked fine without jQuery.

<input type='text' ng-paste='preventPaste($event)'>

And in script part:

$scope.preventPaste = function(e){
   e.preventDefault();
   return false;
};

In non angular project, use 'onPaste' instead of 'ng-paste' and 'event' instesd of '$event'.

How to run an external program, e.g. notepad, using hyperlink?

The reasonable way how to launch apps from HTML is through url schemes. So you can launch email via mailto: links and irc through irc: links. Individual apps can implement these schemes, but I'm not sure WinMerge does this.

Prevent multiple instances of a given app in .NET?

Normally it's done with a named Mutex (use new Mutex( "your app name", true ) and check the return value), but there's also some support classes in Microsoft.VisualBasic.dll that can do it for you.

How to check if my string is equal to null?

I think that myString is not a string but an array of strings. Here is what you need to do:

String myNewString = join(myString, "")
if (!myNewString.equals(""))
{
    //Do something
}

Android, How to limit width of TextView (and add three dots at the end of text)?

Apart from

android:ellipsize="end" 
android:maxLines="1"

you should set

android:layout_width="0dp"

also know as "match constraint", because the wrap_content value just expands the box to fit the whole text, and the ellipsize property can't make its effect.

How to use a jQuery plugin inside Vue

Step 1 We place ourselves with the terminal in the folder of our project and install JQuery through npm or yarn.

npm install jquery --save

Step 2 Within our file where we want to use JQuery, for example app.js (resources/js/app.js), in the script section we include the following code.

// We import JQuery
const $ = require('jquery');
// We declare it globally
window.$ = $;

// You can use it now
$('body').css('background-color', 'orange');

// Here you can add the code for different plugins

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.

Use JSTL forEach loop's varStatus as an ID

The variable set by varStatus is a LoopTagStatus object, not an int. Use:

<div id="divIDNo${theCount.index}">

To clarify:

  • ${theCount.index} starts counting at 0 unless you've set the begin attribute
  • ${theCount.count} starts counting at 1

FFmpeg: How to split video efficiently?

In my experience, don't use ffmpeg for splitting/join. MP4Box, is faster and light than ffmpeg. Please tryit. Eg if you want to split a 1400mb MP4 file into two parts a 700mb you can use the following cmdl: MP4Box -splits 716800 input.mp4 eg for concatenating two files you can use:

MP4Box -cat file1.mp4 -cat file2.mp4 output.mp4

Or if you need split by time, use -splitx StartTime:EndTime:

MP4Box -add input.mp4 -splitx 0:15 -new split.mp4

Best C# API to create PDF

I used PdfSharp. It's free, open source and quite convenient to use, but I can't say whether it is the best or not, because I haven't really used anything else.

When to use RabbitMQ over Kafka?

I hear this question every week... While RabbitMQ (like IBM MQ or JMS or other messaging solutions in general) is used for traditional messaging, Apache Kafka is used as streaming platform (messaging + distributed storage + processing of data). Both are built for different use cases.

You can use Kafka for "traditional messaging", but not use MQ for Kafka-specific scenarios.

The article “Apache Kafka vs. Enterprise Service Bus (ESB)—Friends, Enemies, or Frenemies? (https://www.confluent.io/blog/apache-kafka-vs-enterprise-service-bus-esb-friends-enemies-or-frenemies/)” discusses why Kafka is not competitive but complementary to integration and messaging solutions (including RabbitMQ) and how to integrate both.

How can I get the sha1 hash of a string in node.js?

Tips to prevent issue (bad hash) :

I experienced that NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.

We can add binary argument to use the byte string.

const crypto = require("crypto");

function sha1(data) {
    return crypto.createHash("sha1").update(data, "binary").digest("hex");
}

sha1("Your text ;)");

You can try with : "\xac", "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...

Other languages (Python, PHP, ...):

sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47

Nodejs:

sha1 = crypto.createHash("sha1").update("\xac", "binary").digest("hex") //39527c59247a39d18ad48b9947ea738396a3bc47
//without:
sha1 = crypto.createHash("sha1").update("\xac").digest("hex") //f50eb35d94f1d75480496e54f4b4a472a9148752

Android: how to parse URL String with spaces to URI object?

URL url = Test.class.getResource(args[0]);  // reading demo file path from                                                   
                                            // same location where class                                    
File input=null;
try {
    input = new File(url.toURI());
} catch (URISyntaxException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

How do I terminate a thread in C++11?

Tips of using OS-dependent function to terminate C++ thread:

  1. std::thread::native_handle() only can get the thread’s valid native handle type before calling join() or detach(). After that, native_handle() returns 0 - pthread_cancel() will coredump.

  2. To effectively call native thread termination function(e.g. pthread_cancel()), you need to save the native handle before calling std::thread::join() or std::thread::detach(). So that your native terminator always has a valid native handle to use.

More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .

What is the difference between iterator and iterable and how to use them?

As explained here, The “Iterable” was introduced to be able to use in the foreach loop. A class implementing the Iterable interface can be iterated over.

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

When to use the !important property in CSS

You use !important to override a css property.

For example, you have a control in ASP.NET and it renders a control with a background blue (in the HTML). You want to change it, and you don't have the source control so you attach a new CSS file and write the same selector and change the color and after it add !important.

Best practices is when you are branding / redesigning SharePoint sites, you use it a lot to override the default styles.

Loop inside React JSX

You can create a new component like below:

Pass key and data to your ObjectRow component like this:

export const ObjectRow = ({key,data}) => {
    return (
      <div>
          ...
      </div>
    );
}

Create a new component ObjectRowList to act like a container for your data:

export const ObjectRowList = (objectRows) => {
    return (
      <tbody>
        {objectRows.map((row, index) => (
          <ObjectRow key={index} data={row} />
        ))}
      </tbody>
    );
}

Java: unparseable date exception

From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:

String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);

Next step is parse stringDate to Date:

Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);

Note that, parse method throws ParseException

How do I finish the merge after resolving my merge conflicts?

The first thing I want to make clear is that branch names are just an alias to a specific commit. a commit is what git works off, when you pull, push merge and so forth. Each commit has a unique id.

When you do $ git merge , what is actually happening is git tries to fast forward your current branch to to the commit the referenced branch is on (in other words both branch names point to the same commit.) This scenario is the easiest for git to deal, since there's no new commit. Think of master jumping onto the lilipad your branch is chilling on. It's possible to set the --no-ff flag, in which case git will create a new commit regardless of whether there were any code conflicts.

In a situation where there are code conflicts between the two branches you are trying to merge (usually two branches whose commit history share a common commit in the past), the fast forward won't work. git may still be able to automatically merge the files, so long as the same line wasn't changed by both branches in a conflicting file. in this case, git will merge the conflicting files for you AND automatically commit them. You can preview how git did by doing $ git diff --cached. Or you can pass the --no-commit flag to the merge command, which will leave modified files in your index you'll need to add and commit. But you can $ git diff these files to review what the merge will change.

The third scenario is when there are conflicts git can't automatically resolve. In this case you'll need to manually merge them. In my opinion this is easiest to do with a merge took, like araxis merge or p4merge (free). Either way, you have to do each file one by one. If the merge ever seems to be stuck, use $ git merge --continue, to nudge it along. Git should tell you if it can't continue, and if so why not. If you feel you loused up the merge at some point, you can do $ git merge --abort, and any merging will undo and you can start over. When you're done, each file you merged will be a modified file that needs to be added and committed. You can verify where the files are with $ git status. If you haven't committed the merged files yet. You need to do that to complete the merge. You have to complete the merge or abort the merge before you can switch branches.

div background color, to change onhover

Set

display: block;

on a and give some height

Start index for iterating Python list

If you want to "wrap around" and effectively rotate the list to start with Monday (rather than just chop off the items prior to Monday):

dayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 
            'Friday', 'Saturday',  ]

startDayName = 'Monday'

startIndex = dayNames.index( startDayName )
print ( startIndex )

rotatedDayNames = dayNames[ startIndex: ] + dayNames [ :startIndex ]

for x in rotatedDayNames:
    print ( x )

How do I properly compare strings in C?

How do I properly compare strings?

char input[40];
char check[40];
strcpy(input, "Hello"); // input assigned somehow
strcpy(check, "Hello"); // check assigned somehow

// insufficient
while (check != input)

// good
while (strcmp(check, input) != 0)
// or 
while (strcmp(check, input))

Let us dig deeper to see why check != input is not sufficient.

In C, string is a standard library specification.

A string is a contiguous sequence of characters terminated by and including the first null character.
C11 §7.1.1 1

input above is not a string. input is array 40 of char.

The contents of input can become a string.

In most cases, when an array is used in an expression, it is converted to the address of its 1st element.

The below converts check and input to their respective addresses of the first element, then those addresses are compared.

check != input   // Compare addresses, not the contents of what addresses reference

To compare strings, we need to use those addresses and then look at the data they point to.
strcmp() does the job. §7.23.4.2

int strcmp(const char *s1, const char *s2);

The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

Not only can code find if the strings are of the same data, but which one is greater/less when they differ.

The below is true when the string differ.

strcmp(check, input) != 0

For insight, see Creating my own strcmp() function

How do I use HTML as the view engine in Express?

html is not a view engine , but ejs offers the possibility to write html code within it

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

Converting a String to a List of Words?

To do this properly is quite complex. For your research, it is known as word tokenization. You should look at NLTK if you want to see what others have done, rather than starting from scratch:

>>> import nltk
>>> paragraph = u"Hi, this is my first sentence. And this is my second."
>>> sentences = nltk.sent_tokenize(paragraph)
>>> for sentence in sentences:
...     nltk.word_tokenize(sentence)
[u'Hi', u',', u'this', u'is', u'my', u'first', u'sentence', u'.']
[u'And', u'this', u'is', u'my', u'second', u'.']

Python Turtle, draw text with on screen with larger font

You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..

But another question is this: How do you set the color of the text You write?

Answer: You use the turtle.color() method or turtle.fillcolor(), like this:

turtle.fillcolor("blue")

or just:

turtle.color("orange")

These calls must come before the turtle.write() command..

Adding a newline character within a cell (CSV)

I struggled with this as well but heres the solution. If you add " before and at the end of the csv string you are trying to display, it will consolidate them into 1 cell while honoring new line.

csvString += "\""+"Date Generated: \n" ; 
csvString += "Doctor: " + "\n"+"\"" + "\n"; 

C# - Making a Process.Start wait until the process has start-up

I also needed this once, and I did a check on the window title of the process. If it is the one you expect, you can be sure the application is running. The application I was checking needed some time for startup and this method worked fine for me.

var process = Process.Start("popup.exe");
while(process.MainWindowTitle != "Title")
{
    Thread.Sleep(10);
}

How to connect to a secure website using SSL in Java with a pkcs12 file?

I cannot comment because of the 50pts threshhold, but I don't think that the answer provided in https://stackoverflow.com/a/537344/1341220 is correct. What you are actually describing is how you insert server certificates into the systems default truststore:

$JAVA_HOME/jre/lib/security/cacerts, password: changeit)

This works, indeed, but it means that you did not really specify a trust store local to your project, but rather accepted the certificate universially in your system.

You actually never use your own truststore that you defined here:

System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Javascript: getFullyear() is not a function

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

Dissatisfied with the other answers. The top voted answer as of 2019/3/13 is factually wrong.

The short terse version of what => means is it's a shortcut writing a function AND for binding it to the current this

const foo = a => a * 2;

Is effectively a shortcut for

const foo = function(a) { return a * 2; }.bind(this);

You can see all the things that got shortened. We didn't need function, nor return nor .bind(this) nor even braces or parentheses

A slightly longer example of an arrow function might be

const foo = (width, height) => {
  const area = width * height;
  return area;
};

Showing that if we want multiple arguments to the function we need parentheses and if we want write more than a single expression we need braces and an explicit return.

It's important to understand the .bind part and it's a big topic. It has to do with what this means in JavaScript.

ALL functions have an implicit parameter called this. How this is set when calling a function depends on how that function is called.

Take

function foo() { console.log(this); }

If you call it normally

function foo() { console.log(this); }
foo();

this will be the global object.

If you're in strict mode

`use strict`;
function foo() { console.log(this); }
foo();

// or

function foo() {
   `use strict`;
   console.log(this);
 }
foo();

It will be undefined

You can set this directly using call or apply

function foo(msg) { console.log(msg, this); }

const obj1 = {abc: 123}
const obj2 = {def: 456}

foo.call(obj1, 'hello');  // prints Hello {abc: 123}
foo.apply(obj2, ['hi']);  // prints Hi {def: 456}

You can also set this implicitly using the dot operator .

function foo(msg) { console.log(msg, this); }
const obj = {
   abc: 123,
   bar: foo,
}
obj.bar('Hola');  // prints Hola {abc:123, bar: f}

A problem comes up when you want to use a function as a callback or a listener. You make class and want to assign a function as the callback that accesses an instance of the class.

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click', function() {
       console.log(this.name);  // won't work
    }); 
  }
}

The code above will not work because when the element fires the event and calls the function the this value will not be the instance of the class.

One common way to solve that problem is to use .bind

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click', function() {
       console.log(this.name); 
    }.bind(this); // <=========== ADDED! ===========
  }
}

Because the arrow syntax does the same thing we can write

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click',() => {
       console.log(this.name); 
    });
  }
}

bind effectively makes a new function. If bind did not exist you could basically make your own like this

function bind(functionToBind, valueToUseForThis) {
  return function(...args) {
    functionToBind.call(valueToUseForThis, ...args);
  };
}

In older JavaScript without the spread operator it would be

function bind(functionToBind, valueToUseForThis) {
  return function() {
    functionToBind.apply(valueToUseForThis, arguments);
  };
}

Understanding that code requires an understanding of closures but the short version is bind makes a new function that always calls the original function with the this value that was bound to it. Arrow functions do the same thing since they are a shortcut for bind(this)

Checking if a number is a prime number in Python

Here is my take on the problem:

from math import sqrt
from itertools import count, islice

def is_prime(n):
    return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1)))

This is a really simple and concise algorithm, and therefore it is not meant to be anything near the fastest or the most optimal primality check algorithm. It has a time complexity of O(sqrt(n)). Head over here to learn more about primality tests done right and their history.


Explanation

I'm gonna give you some insides about that almost esoteric single line of code that will check for prime numbers:

  • First of all, using range() in Python 2 is really a bad idea, because it will create a list of numbers, which uses a lot of memory. Using xrange() is better, because it creates a generator, which only needs to memorize the initial arguments you provide, and generates every number on-the-fly. If you're using Python 3, range() has been converted to a generator by default. By the way, this is still not the best solution: trying to call xrange(n) for some n such that n > 231-1 (which is the maximum value for a C long) raises OverflowError. Therefore the best way to create a range generator is to use itertools:

     xrange(2147483647+1) # OverflowError
    
     from itertools import count, islice
    
     count(1)                        # Count from 1 to infinity with step=+1
     islice(count(1), 2147483648)    # Count from 1 to 2^31 with step=+1
     islice(count(1, 3), 2147483648) # Count from 1 to 3*2^31 with step=+3
    
  • You do not actually need to go all the way up to n if you want to check if n is a prime number. You can dramatically reduce the tests and only check from 2 to v(n) (square root of n). Here's an example:

    Let's find all the divisors of n = 100, and list them in a table:

     2  x  50 = 100
     4  x  25 = 100
     5  x  20 = 100
    10  x  10 = 100 <-- sqrt(100)
    20  x  5  = 100     
    25  x  4  = 100
    50  x  2  = 100
    

    You will easily notice that, after the square root of n, all the divisors we find were actually already found. For example 20 was already found doing 100/5. The square root of a number is the exact mid-point where the divisors we found begin being duplicated. Therefore, to check if a number is prime, you'll only need to check from 2 to sqrt(n).

  • Why sqrt(n)-1 then, and not just sqrt(n)? That's just because the second argument provided to itertools.islice() is the number of iterations to execute. islice(count(a), b) stops after b iterations. That's the reason why:

     for number in islice(count(10), 2):
         print number,
    
     # Will print: 10 11
    
     for number in islice(count(1, 3), 10):
         print number,
    
     # Will print: 1 4 7 10 13 16 19 22 25 28
    
  • The function all(...) is the same of the following:

     def all(iterable):
         for element in iterable:
             if not element:
                 return False
         return True
    

    It literally checks for all the elements in the iterable, returning False when any of them evaluates to False (which for an integer means only if it's zero). Why do we use it then? First of all, we don't need to use an additional index variable (like we would do using a loop), other than that: just for concision, there's no real need of it, but it looks way less bulky to work with only a single line of code instead of several nested lines.

Extended version

I'm including an "unpacked" version of the is_prime() function, to make it easier to understand and read:

from math import sqrt
from itertools import count, islice

def is_prime(n):
    if n < 2:
        return False

    for number in islice(count(2), int(sqrt(n) - 1)):
        if n % number == 0:
            return False

    return True

Difference between a virtual function and a pure virtual function

For a virtual function you need to provide implementation in the base class. However derived class can override this implementation with its own implementation. Normally , for pure virtual functions implementation is not provided. You can make a function pure virtual with =0 at the end of function declaration. Also, a class containing a pure virtual function is abstract i.e. you can not create a object of this class.

YAML Multi-Line Arrays

Following Works for me and its good from readability point of view when array element values are small:

key: [string1, string2, string3, string4, string5, string6]

Note:snakeyaml implementation used

Usage of \b and \r in C

The characters are exactly as documented - \b equates to a character code of 0x08 and \r equates to 0x0d. The thing that varies is how your OS reacts to those characters. Back when displays were trying to emulate an old teletype those actions were standardized, but they are less useful in modern environments and compatibility is not guaranteed.

How to prevent colliders from passing through each other?

  • Edit ---> Project Settings ---> Time ... decrease "Fixed Timestep" value .. This will solve the problem but it can affect performance negatively.

  • Another solution is could be calculate the coordinates (for example, you have a ball and wall. Ball will hit to wall. So calculate coordinates of wall and set hitting process according these cordinates )

Set focus on textbox in WPF

try FocusManager.SetFocusedElement

FocusManager.SetFocusedElement(parentElement, txtCompanyID)

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

Removing an element from an Array (Java)

I hope you use the java collection / java commons collections!

With an java.util.ArrayList you can do things like the following:

yourArrayList.remove(someObject);

yourArrayList.add(someObject);

Giving UIView rounded corners

You need to first import header file <QuartzCore/QuartzCore.h>

 #import QuartzCore/QuartzCore.h>

[yourView.layer setCornerRadius:8.0f];
yourView.layer.borderColor = [UIColor redColor].CGColor;
yourView.layer.borderWidth = 2.0f;
[yourView.layer setMasksToBounds:YES];

Don't miss to use -setMasksToBounds , otherwise the effect may not be shown.

How can I recursively find all files in current and subfolders based on wildcard matching?

This will search all the related files in current and sub directories, calculating their line count separately as well as totally:

find . -name "*.wanted" | xargs wc -l

how to find array size in angularjs

You can find the number of members in a Javascript array by using its length property:

var number = $scope.names.length;

Docs - Array.prototype.length

how to install python distutils

If you are in a scenario where you are using one of the latest versions of Ubuntu (or variants like Linux Mint), one which comes with Python 3.8, then you will NOT be able to have Python3.7 distutils, alias not be able to use pip or pipenv with Python 3.7, see: How to install python-distutils for old python versions

Obviously using Python3.8 is no problem.

Cannot add a project to a Tomcat server in Eclipse

After following the steps suggested by previous posters, do the following steps:

  • Right click on the project
  • Click Maven, then Update Project
  • Tick the checkbox "Force Update of Snapshots/Releases", then click OK

You should be good to go now.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

After reading your comment on my previous answer I thought I might put this as a separate answer.

Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.

That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with

WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/

This is the jQuery

$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();    
$('.active').show();

    $('#button-next').click(function(){

    $('.active').removeClass('active').addClass('oldActive');    
                   if ( $('.oldActive').is(':last-child')) {
        $('.sp').first().addClass('active');
        }
        else{
        $('.oldActive').next().addClass('active');
        }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();


    });

       $('#button-previous').click(function(){
    $('.active').removeClass('active').addClass('oldActive');    
           if ( $('.oldActive').is(':first-child')) {
        $('.sp').last().addClass('active');
        }
           else{
    $('.oldActive').prev().addClass('active');
           }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();
    });




});

So now the explanation.
Stage 1
1) Load the script on document ready.

2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.

3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;

Stage 2 Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.

2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.

3) We remove the class oldActive because it's no longer needed.

4) fadeOut all of the slides

5) fade In the active slides

Step 3

Same as in step two but using some reverse logic for traversing through the elements backwards.

It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.

One line if/else condition in linux shell scripting

To summarize the other answers, for general use:

Multi-line if...then statement

if [ foo ]; then
    a; b
elif [ bar ]; then
    c; d
else
    e; f
fi

Single-line version

if [ foo ]; then a && b; elif [ bar ]; c && d; else e && f; fi

Using the OR operator

( foo && a && b ) || ( bar && c && d ) || e && f;

Notes

Remember that the AND and OR operators evaluate whether or not the result code of the previous operation was equal to true/success (0). So if a custom function returns something else (or nothing at all), you may run into problems with the AND/OR shorthand. In such cases, you may want to replace something like ( a && b ) with ( [ a == 'EXPECTEDRESULT' ] && b ), etc.

Also note that ( and [ are technically commands, so whitespace is required around them.

Instead of a group of && statements like then a && b; else, you could also run statements in a subshell like then $( a; b ); else, though this is less efficient. The same is true for doing something like result1=$( foo; a; b ); result2=$( bar; c; d ); [ "$result1" -o "$result2" ] instead of ( foo && a && b ) || ( bar && c && d ). Though at that point you'd be getting more into less-compact, multi-line stuff anyway.

How to cast ArrayList<> from List<>

Try running the following code:

List<String> listOfString = Arrays.asList("Hello", "World");
ArrayList<String> arrayListOfString = new ArrayList(listOfString);
System.out.println(listOfString.getClass());
System.out.println(arrayListOfString.getClass());

You'll get the following result:

class java.util.Arrays$ArrayList
class java.util.ArrayList

So, that means they're 2 different classes that aren't extending each other. java.util.Arrays$ArrayList signifies the private class named ArrayList (inner class of Arrays class) and java.util.ArrayList signifies the public class named ArrayList. Thus, casting from java.util.Arrays$ArrayList to java.util.ArrayList and vice versa are irrelevant/not available.

ModalPopupExtender OK Button click event not firing?

Put into the Button-Control the Attribute "UseSubmitBehavior=false".

Convert from lowercase to uppercase all values in all character variables in dataframe

Another alternative is to use a combination of mutate_if() and str_to_uper() function, both from the tidyverse package:

df %>% mutate_if(is.character, str_to_upper) -> df

This will convert all string variables in the data frame to upper case. str_to_lower() do the opposite.

C++ STL Vectors: Get iterator from index?

Also; auto it = std::next(v.begin(), index);

Update: Needs a C++11x compliant compiler

Python 3 Float Decimal Points/Precision

The simple way to do this is by using the round buit-in.

round(2.6463636263,2) would be displayed as 2.65.

Sum all values in every column of a data.frame in R

You can use function colSums() to calculate sum of all values. [,-1] ensures that first column with names of people is excluded.

 colSums(people[,-1])
Height Weight 
   199    425

Assuming there could be multiple columns that are not numeric, or that your column order is not fixed, a more general approach would be:

colSums(Filter(is.numeric, people))

Returning Promises from Vuex actions

actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.

Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later - all asynchronously

actions: {
    myAction(context, data) {
        return new Promise((resolve, reject) => {
            // Do something here... lets say, a http call using vue-resource
            this.$http("/api/something").then(response => {
                // http success, call the mutator and change something in state
                resolve(response);  // Let the calling function know that http is done. You may send some data back
            }, error => {
                // http failed, let the calling function know that action did not work out
                reject(error);
            })
        })
    }
}

Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:

export default {
    mounted: function() {
        // This component just got created. Lets fetch some data here using an action
        this.$store.dispatch("myAction").then(response => {
            console.log("Got some data, now lets show something in this component")
        }, error => {
            console.error("Got nothing from server. Prompt user to check internet connection and try again")
        })
    }
}

As you can see above, it is highly beneficial for actions to return a Promise. Otherwise there is no way for the action initiator to know what is happening and when things are stable enough to show something on the user interface.

And a last note regarding mutators - as you rightly pointed out, they are synchronous. They change stuff in the state, and are usually called from actions. There is no need to mix Promises with mutators, as the actions handle that part.

Edit: My views on the Vuex cycle of uni-directional data flow:

If you access data like this.$store.state["your data key"] in your components, then the data flow is uni-directional.

The promise from action is only to let the component know that action is complete.

The component may either take data from promise resolve function in the above example (not uni-directional, therefore not recommended), or directly from $store.state["your data key"] which is unidirectional and follows the vuex data lifecycle.

The above paragraph assumes your mutator uses Vue.set(state, "your data key", http_data), once the http call is completed in your action.

Visual Studio Code Tab Key does not insert a tab

Try CTR + M it will work like before.

How many bytes is unsigned long long?

It must be at least 64 bits. Other than that it's implementation defined.

Strictly speaking, unsigned long long isn't standard in C++ until the C++0x standard. unsigned long long is a 'simple-type-specifier' for the type unsigned long long int (so they're synonyms).

The long long set of types is also in C99 and was a common extension to C++ compilers even before being standardized.

ReferenceError: document is not defined (in plain JavaScript)

This happened with me because I was using Next JS which has server side rendering. When you are using server side rendering there is no browser. Hence, there will not be any variable window or document. Hence this error shows up.

Work around :

If you are using Next JS you can use the dynamic rendering to prevent server side rendering for the component.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

export default () => <DynamicComponentWithNoSSR />

If you are using any other server side rendering library. Then add the code that you want to run at the client side in componentDidMount. If you are using React Hooks then use useEffects in the place of componentsDidMount.

import React, {useState, useEffects} from 'react';

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){

[a,setA] = useState();
useEffect(() => {
    setA(<DynamicComponentWithNoSSR/>)
  });


return (<>{a}<>)
}

References :

  1. https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
  2. https://reactjs.org/docs/hooks-effect.html

How can one use multi threading in PHP applications

You could simulate threading. PHP can run background processes via popen (or proc_open). Those processes can be communicated with via stdin and stdout. Of course those processes can themselves be a php program. That is probably as close as you'll get.

setTimeout in React Native

const getData = () => {
// some functionality
}

const that = this;
   setTimeout(() => {
   // write your functions    
   that.getData()
},6000);

Simple, Settimout function get triggered after 6000 milliseonds

gulp command not found - error after installing gulp

On my Windows 10 Enterprise, gulp was not installed in %AppData%, which is C:\Users\username\AppData\npm\node_modules on my machine, but in C:\Users\username\AppData\Local\npm\node_modules.

To get gulp to be picked up at the command prompt or in powershell, I added to the user PATH the value C:\Users\username\AppData\Local\npm. After that it worked like a charm. Naturally I had to close the command prompt or powershell window and re-open for the above to take effect.

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

How do I get the App version and build number using Swift?

Updated for Swift 3.0

The NS-prefixes are now gone in Swift 3.0 and several properties/methods have changed names to be more Swifty. Here's what this looks like now:

extension Bundle {
    var releaseVersionNumber: String? {
        return infoDictionary?["CFBundleShortVersionString"] as? String
    }
    var buildVersionNumber: String? {
        return infoDictionary?["CFBundleVersion"] as? String
    }
}

Bundle.main.releaseVersionNumber
Bundle.main.buildVersionNumber

Old Updated Answer

I've been working with Frameworks a lot since my original answer, so I wanted to update my solution to something that is both simpler and much more useful in a multi-bundle environment:

extension NSBundle {

    var releaseVersionNumber: String? {
        return self.infoDictionary?["CFBundleShortVersionString"] as? String
    }

    var buildVersionNumber: String? {
        return self.infoDictionary?["CFBundleVersion"] as? String
    }

}

Now this extension will be useful in apps to identify both the main bundle and any other included bundles (such as a shared framework for extension programming or third frameworks like AFNetworking), like so:

NSBundle.mainBundle().releaseVersionNumber
NSBundle.mainBundle().buildVersionNumber

// or...

NSBundle(URL: someURL)?.releaseVersionNumber
NSBundle(URL: someURL)?.buildVersionNumber

Original Answer

I wanted to improve on some of the answers already posted. I wrote a class extension that can be added to your tool chain to handle this in a more logical fashion.

extension NSBundle {

class var applicationVersionNumber: String {
    if let version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"]

as? String { return version } return "Version Number Not Available" }

class var applicationBuildNumber: String {
    if let build = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String {
        return build
    }
    return "Build Number Not Available"
}

}

So now you can access this easily by:

let versionNumber = NSBundle.applicationVersionNumber

How do I get the directory that a program is running from?

Just my two cents, but doesn't the following code portably work in C++17?

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main(int argc, char* argv[])
{
    std::cout << "Path is " << fs::path(argv[0]).parent_path() << '\n';
}

Seems to work for me on Linux at least.

Based on the previous idea, I now have:

std::filesystem::path prepend_exe_path(const std::string& filename, const std::string& exe_path = "");

With implementation:

fs::path prepend_exe_path(const std::string& filename, const std::string& exe_path)
{
    static auto exe_parent_path = fs::path(exe_path).parent_path();
    return exe_parent_path / filename;
}

And initialization trick in main():

(void) prepend_exe_path("", argv[0]);

Thanks @Sam Redway for the argv[0] idea. And of course, I understand that C++17 was not around for many years when the OP asked the question.

How can I extract the folder path from file path in Python?

Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:

PathToContainingFolder =

"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])

so that

\Users\me\Desktop\New folder\file.txt

becomes

\Users\me\Desktop\New folder

Specifying maxlength for multiline textbox

Nearly all modern browsers now support the use of the maxlength attribute for textarea elements.(https://caniuse.com/#feat=maxlength)

To include the maxlength attribute on a multiline TextBox, you can simply modify the Attributes collection in the code behind like so:

txtTextBox.Attributes["maxlength"] = "100";

If you don't want to have to use the code behind to specify that, you can just create a custom control that derives from TextBox:

public class Textarea : TextBox
{
    public override TextBoxMode TextMode
    {
        get { return TextBoxMode.MultiLine; }
        set { }
    }

    protected override void OnPreRender(EventArgs e)
    {
        if (TextMode == TextBoxMode.MultiLine && MaxLength != 0)
        {
            Attributes["maxlength"] = MaxLength.ToString();
        }

        base.OnPreRender(e);
    }
}

Compiler error: memset was not declared in this scope

Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.

$ man memset

MEMSET(3)                BSD Library Functions Manual                MEMSET(3)

NAME
     memset -- fill a byte string with a byte value

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

     void *
     memset(void *b, int c, size_t len);

Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>/<cstdio>/<cstdlib>/etc, rather than C's <string.h>/<stdio.h>/<stdlib.h>/etc.

Removing a model in rails (reverse of "rails g model Title...")

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
    
  2. To remove Model

    rails d model name  #name => Your model name
    

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

Get push notification while App in foreground iOS

Xcode 10 Swift 4.2

To show Push Notification when your app is in the foreground -

Step 1 : add delegate UNUserNotificationCenterDelegate in AppDelegate class.

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

Step 2 : Set the UNUserNotificationCenter delegate

let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self

Step 3 : This step will allow your app to show Push Notification even when your app is in foreground

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])

    }

Step 4 : This step is optional. Check if your app is in the foreground and if it is in foreground then show Local PushNotification.

func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) {

        let state : UIApplicationState = application.applicationState
        if (state == .inactive || state == .background) {
            // go to screen relevant to Notification content
            print("background")
        } else {
            // App is in UIApplicationStateActive (running in foreground)
            print("foreground")
            showLocalNotification()
        }
    }

Local Notification function -

fileprivate func showLocalNotification() {

        //creating the notification content
        let content = UNMutableNotificationContent()

        //adding title, subtitle, body and badge
        content.title = "App Update"
        //content.subtitle = "local notification"
        content.body = "New version of app update is available."
        //content.badge = 1
        content.sound = UNNotificationSound.default()

        //getting the notification trigger
        //it will be called after 5 seconds
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)

        //getting the notification request
        let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)

        //adding the notification to notification center
        notificationCenter.add(request, withCompletionHandler: nil)
    }

Simple conversion between java.util.Date and XMLGregorianCalendar

Customizing the Calendar and Date while Marshaling

Step 1 : Prepare jaxb binding xml for custom properties, In this case i prepared for date and calendar

<jaxb:bindings version="2.1" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" 
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jaxb:globalBindings generateElementProperty="false">
<jaxb:serializable uid="1" />
<jaxb:javaType name="java.util.Date" xmlType="xs:date"
    parseMethod="org.apache.cxf.tools.common.DataTypeAdapter.parseDate"
    printMethod="com.stech.jaxb.util.CalendarTypeConverter.printDate" />
<jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
    parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
    printMethod="com.stech.jaxb.util.CalendarTypeConverter.printCalendar" />


Setp 2 : Add custom jaxb binding file to Apache or any related plugins at xsd option like mentioned below

<xsdOption>
  <xsd>${project.basedir}/src/main/resources/tutorial/xsd/yourxsdfile.xsd</xsd>
  <packagename>com.tutorial.xml.packagename</packagename>
  <bindingFile>${project.basedir}/src/main/resources/xsd/jaxbbindings.xml</bindingFile>
</xsdOption>

Setp 3 : write the code for CalendarConverter class

package com.stech.jaxb.util;

import java.text.SimpleDateFormat;

/**
 * To convert the calendar to JaxB customer format.
 * 
 */

public final class CalendarTypeConverter {

    /**
     * Calendar to custom format print to XML.
     * 
     * @param val
     * @return
     */
    public static String printCalendar(java.util.Calendar val) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
        return simpleDateFormat.format(val.getTime());
    }

    /**
     * Date to custom format print to XML.
     * 
     * @param val
     * @return
     */
    public static String printDate(java.util.Date val) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(val);
    }
}

Setp 4 : Output

  <xmlHeader>
   <creationTime>2014-09-25T07:23:05</creationTime> Calendar class formatted

   <fileDate>2014-09-25</fileDate> - Date class formatted
</xmlHeader>

How to create multiple output paths in Webpack config

I'm not sure if we have the same problem since webpack only support one output per configuration as of Jun 2016. I guess you already seen the issue on Github.

But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js).

var config = {
    // TODO: Add common Configuration
    module: {},
};

var fooConfig = Object.assign({}, config, {
    name: "a",
    entry: "./a/app",
    output: {
       path: "./a",
       filename: "bundle.js"
    },
});
var barConfig = Object.assign({}, config,{
    name: "b",
    entry: "./b/app",
    output: {
       path: "./b",
       filename: "bundle.js"
    },
});

// Return Array of Configurations
module.exports = [
    fooConfig, barConfig,       
];

If you have common configuration among them, you could use the extend library or Object.assign in ES6 or {...} spread operator in ES7.

Error: 'int' object is not subscriptable - Python

When you type x = 0 that is creating a new int variable (name) and assigning a zero to it.

When you type x[age1] that is trying to access the age1'th entry, as if x were an array.

Transfer data from one HTML file to another

you can simply send the data using window.location.href first store the value to send from testing.html in the script tag, variable say

<script> 
  var data = value_to_send
  window.loaction.href="next.htm?data="+data
</script>

this is sending through a get request

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

In VB:

from m in MyTable
take 10
select m.Foo

This assumes that MyTable implements IQueryable. You may have to access that through a DataContext or some other provider.

It also assumes that Foo is a column in MyTable that gets mapped to a property name.

See http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx for more detail.

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

You Could just use NSTimer to call a selector:

[NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(yourMethod:) userInfo:nil repeats:NO]

Open another page in php

Use something like header( 'Location: /my-other-page.html' ); to redirect. You can't have sent any other data on the page before you do this though.

How to run TypeScript files from command line?

None of the other answers discuss how to run a TypeScript script that uses modules, and especially modern ES Modules.

First off, ts-node doesn't work in that scenario, as of March 2020. So we'll settle for tsc followed by node.

Second, TypeScript still can't output .mjs files. So we'll settle for .js files and "type": "module" in package.json.

Third, you want clean import lines, without specifying the .js extension (which would be confusing in .ts files):

import { Lib } from './Lib';

Well, that's non-trivial. Node requires specifying extensions on imports, unless you use the experimental-specifier-resolution=node flag. In this case, it would enable Node to look for Lib.js or Lib/index.js when you only specify ./Lib on the import line.

Fourth, there's still a snag: if you have a different main filename than index.js in your package, Node won't find it.

Transpiling makes things a lot messier than running vanilla Node.

Here's a sample repo with a modern TypeScript project structure, generating ES Module code.

Right to Left support for Twitter Bootstrap 3

Bootstrap Persian version of the site http://rbootstrap.ir/ Ver.2.3.2

How to set Grid row and column positions programmatically

Try this:

                Grid grid = new Grid(); //Define the grid
                for (int i = 0; i < 36; i++) //Add 36 rows
                {
                    ColumnDefinition columna = new ColumnDefinition()
                    {
                        Name = "Col_" + i,
                        Width = new GridLength(32.5),
                    };
                    grid.ColumnDefinitions.Add(columna);
                }

                for (int i = 0; i < 36; i++) //Add 36 columns
                {
                    RowDefinition row = new RowDefinition();
                    row.Height = new GridLength(40, GridUnitType.Pixel);
                    grid.RowDefinitions.Add(row);
                }

                for (int i = 0; i < 36; i++)
                {
                    for (int j = 0; j < 36; j++)
                    {
                        Label t1 = new Label()
                        {
                            FontSize = 10,
                            FontFamily = new FontFamily("consolas"),
                            FontWeight = FontWeights.SemiBold,
                            BorderBrush = Brushes.LightGray,
                            BorderThickness = new Thickness(2),
                            HorizontalContentAlignment = HorizontalAlignment.Center,
                            VerticalContentAlignment = VerticalAlignment.Center,
                        };
                        Grid.SetRow(t1, i);
                        Grid.SetColumn(t1, j);
                        grid.Children.Add(t1); //Add the Label Control to the Grid created
                    }
                }

Going through a text file line by line in C

In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).

Combine two columns of text in pandas dataframe

The method cat() of the .str accessor works really well for this:

>>> import pandas as pd
>>> df = pd.DataFrame([["2014", "q1"], 
...                    ["2015", "q3"]],
...                   columns=('Year', 'Quarter'))
>>> print(df)
   Year Quarter
0  2014      q1
1  2015      q3
>>> df['Period'] = df.Year.str.cat(df.Quarter)
>>> print(df)
   Year Quarter  Period
0  2014      q1  2014q1
1  2015      q3  2015q3

cat() even allows you to add a separator so, for example, suppose you only have integers for year and period, you can do this:

>>> import pandas as pd
>>> df = pd.DataFrame([[2014, 1],
...                    [2015, 3]],
...                   columns=('Year', 'Quarter'))
>>> print(df)
   Year Quarter
0  2014       1
1  2015       3
>>> df['Period'] = df.Year.astype(str).str.cat(df.Quarter.astype(str), sep='q')
>>> print(df)
   Year Quarter  Period
0  2014       1  2014q1
1  2015       3  2015q3

Joining multiple columns is just a matter of passing either a list of series or a dataframe containing all but the first column as a parameter to str.cat() invoked on the first column (Series):

>>> df = pd.DataFrame(
...     [['USA', 'Nevada', 'Las Vegas'],
...      ['Brazil', 'Pernambuco', 'Recife']],
...     columns=['Country', 'State', 'City'],
... )
>>> df['AllTogether'] = df['Country'].str.cat(df[['State', 'City']], sep=' - ')
>>> print(df)
  Country       State       City                   AllTogether
0     USA      Nevada  Las Vegas      USA - Nevada - Las Vegas
1  Brazil  Pernambuco     Recife  Brazil - Pernambuco - Recife

Do note that if your pandas dataframe/series has null values, you need to include the parameter na_rep to replace the NaN values with a string, otherwise the combined column will default to NaN.

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

I think the textbox you are trying to access is not yet loaded onto the page at the time your javascript is being executed.

ie., For the Javascript to be able to read the textbox from the DOM of the page, the textbox must be available as an element. If the javascript is getting called before the textbox is written onto the page, the textbox will not be visible and so NULL is returned.

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

I remember it this way:

  1. IEnumerable has one method GetEnumerator() which allows one to read through the values in a collection but not write to it. Most of the complexity of using the enumerator is taken care of for us by the for each statement in C#. IEnumerable has one property: Current, which returns the current element.

  2. ICollection implements IEnumerable and adds few additional properties the most use of which is Count. The generic version of ICollection implements the Add() and Remove() methods.

  3. IList implements both IEnumerable and ICollection, and add the integer indexing access to items (which is not usually required, as ordering is done in database).

Parsing JSON with Unix tools

On the basis that some of the recommendations here (esp in the comments) suggested the use of Python, I was disappointed not to find an example.

So, here's a one liner to get a single value from some JSON data. It assumes that you are piping the data in (from somewhere) and so should be useful in a scripting context.

echo '{"hostname":"test","domainname":"example.com"}' | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["hostname"]'

How to convert a plain object into an ES6 Map?

Do I really have to first convert it into an array of arrays of key-value pairs?

No, an iterator of key-value pair arrays is enough. You can use the following to avoid creating the intermediate array:

function* entries(obj) {
    for (let key in obj)
        yield [key, obj[key]];
}

const map = new Map(entries({foo: 'bar'}));
map.get('foo'); // 'bar'

Getting first value from map in C++

You can use the iterator that is returned by the begin() method of the map template:

std::map<K,V> myMap;
std::pair<K,V> firstEntry = *myMap.begin()

But remember that the std::map container stores its content in an ordered way. So the first entry is not always the first entry that has been added.

Set the value of an input field

if your form contains an input field like

<input type='text' id='id1' />

then you can write the code in javascript as given below to set its value as

document.getElementById('id1').value='text to be displayed' ; 

" netsh wlan start hostednetwork " command not working no matter what I try

At first simply uninstall wifi drivers and softwares just keep wifi drivers + from device manager....network adapters...remove all virtual connections

then

Press the Windows + R key combination to bring up a run box, type ncpa.cpl and hit enter.

netsh wlan set hostednetwork mode=allow ssid=”How-To Geek” key=”Pa$$w0rd”

netsh wlan start hostednetwork

netsh wlan show hostednetwork

its working for me and on others PC.

How to change the cursor into a hand when a user hovers over a list item?

Use

cursor: pointer;
cursor: hand;

if you want to have a crossbrowser result!

Django - "no module named django.core.management"

Are you using a Virtual Environment with Virtual Wrapper? Are you on a Mac?

If so try this:

Enter the following into your command line to start up the virtual environment and then work on it

1.)

source virtualenvwrapper.sh

or

source /usr/local/bin/virtualenvwrapper.sh

2.)

workon [environment name]

Note (from a newbie) - do not put brackets around your environment name

How do you kill a Thread in Java?

Generally you don't kill, stop, or interrupt a thread (or check wheter it is interrupted()), but let it terminate naturally.

It is simple. You can use any loop together with (volatile) boolean variable inside run() method to control thread's activity. You can also return from active thread to the main thread to stop it.

This way you gracefully kill a thread :) .

Difference between getAttribute() and getParameter()

Basic difference between getAttribute() and getParameter() is the return type.

java.lang.Object getAttribute(java.lang.String name)
java.lang.String getParameter(java.lang.String name)

How do I kill this tomcat process in Terminal?

kill -9 $(ps -ef | grep 8084 | awk 'NR==2{print $2}')

NR is for the number of records in the input file. awk can find or replaces text

Submit form using AJAX and jQuery

First give your form an id attribute, then use code like this:

$(document).ready( function() {
  var form = $('#my_awesome_form');

  form.find('select:first').change( function() {
    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
  } );

} );

So this code uses .serialize() to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.

For future reference, the jQuery docs are very, very good.

SQL: Select columns with NULL values only

If you need to list all rows where all the column values are NULL, then i'd use the COLLATE function. This takes a list of values and returns the first non-null value. If you add all the column names to the list, then use IS NULL, you should get all the rows containing only nulls.

SELECT * FROM MyTable WHERE COLLATE(Col1, Col2, Col3, Col4......) IS NULL

You shouldn't really have any tables with ALL the columns null, as this means you don't have a primary key (not allowed to be null). Not having a primary key is something to be avoided; this breaks the first normal form.

Make WPF Application Fullscreen (Cover startmenu)

If you want user to change between WindowStyle.SingleBorderWindow and WindowStyle.None at runtime you can bring this at code behind:

Make application fullscreen:

RootWindow.Visibility = Visibility.Collapsed;
RootWindow.WindowStyle = WindowStyle.None;
RootWindow.ResizeMode = ResizeMode.NoResize;
RootWindow.WindowState = WindowState.Maximized;
RootWindow.Topmost = true;
RootWindow.Visibility = Visibility.Visible;

Return to single border style:

RootWindow.WindowStyle = WindowStyle.SingleBorderWindow;
RootWindow.ResizeMode = ResizeMode.CanResize;
RootWindow.Topmost = false;

Note that without RootWindow.Visibility property your window will not cover start menu, however you can skip this step if you making application fullscreen once at startup.

Adding delay between execution of two following lines

You can use gcd to do this without having to create another method

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
  NSLog(@"Do some work");
});

You should still ask yourself "do I really need to add a delay" as it can often complicate code and cause race conditions

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Add the "code" folder to the project properties within Visual Studio

Project->Properties->Configuration Properties->C/C++->Additional Include Directories

Confused by python file mode "w+"

The file is truncated, so you can call read() (no exceptions raised, unlike when opened using 'w') but you'll get an empty string.

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

Use of #pragma in C

#pragma is used to do something implementation-specific in C, i.e. be pragmatic for the current context rather than ideologically dogmatic.

The one I regularly use is #pragma pack(1) where I'm trying to squeeze more out of my memory space on embedded solutions, with arrays of structures that would otherwise end up with 8 byte alignment.

Pity we don't have a #dogma yet. That would be fun ;)

Adding a new SQL column with a default value

Like this?

ALTER TABLE `tablename` ADD `new_col_name` INT NOT NULL DEFAULT 0;

Concat strings by & and + in VB.Net

From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.

    Dim s1 As String
    Dim i As Integer
    s1 = "Hello"
    i = 1
    String.Format("{0} {1}", s1, i)

It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?

How to get WooCommerce order details

You can get all details by order object.

   // Get $order object from order ID
      
    $order = wc_get_order( $order_id );
      
    // Now you have access to (see above)...
      
    if ( $order ) {
       // Get Order ID and Key
    $order->get_id();
    $order->get_order_key();
     
    // Get Order Totals $0.00
    $order->get_formatted_order_total();
    $order->get_cart_tax();
    $order->get_currency();
    $order->get_discount_tax();
    $order->get_discount_to_display();
    $order->get_discount_total();
    $order->get_fees();
    $order->get_formatted_line_subtotal();
    $order->get_shipping_tax();
    $order->get_shipping_total();
    $order->get_subtotal();
    $order->get_subtotal_to_display();
    $order->get_tax_location();
    $order->get_tax_totals();
    $order->get_taxes();
    $order->get_total();
    $order->get_total_discount();
    $order->get_total_tax();
    $order->get_total_refunded();
    $order->get_total_tax_refunded();
    $order->get_total_shipping_refunded();
    $order->get_item_count_refunded();
    $order->get_total_qty_refunded();
    $order->get_qty_refunded_for_item();
    $order->get_total_refunded_for_item();
    $order->get_tax_refunded_for_item();
    $order->get_total_tax_refunded_by_rate_id();
    $order->get_remaining_refund_amount();
    }

How to uninstall/upgrade Angular CLI?

I tried all the above things, and still ng as sticking around globally. So in powershell I ran Get-Command ng, and then it became clear what my problem was. I was using yarn heavily in the past, and all the old angular cli packages were also installed globally in the yarn cache location. I deleted my yarn cache for good measure, but probably could have just updated the global angular cli via yarn. In any case, I hope this helps remind some of you that if you use yarn, then global commands like ng can also live in another path than where npm puts them.

Vim multiline editing like in sublimetext?

There are several ways to accomplish that in Vim. I don't know which are most similar to Sublime Text's though.


The first one would be via multiline insert mode. Put your cursor to the second "a" in the first line, press Ctrl-V, select all lines, then press I, and put in a doublequote. Pressing <esc> will repeat the operation on every line.


The second one is via macros. Put the cursor on the first character, and start recording a macro with qa. Go the your right with llll, enter insert mode with a, put down a doublequote, exit insert mode, and go back to the beginning of your row with <home> (or equivalent). Press j to move down one row. Stop recording with q. And then replay the macro with @a. Several times.


Does any of the above approaches work for you?

Get battery level and state in Android

Here is a code sample that explains how to get battery information.

To sum it up, a broadcast receiver for the ACTION_BATTERY_CHANGED intent is set up dynamically, because it can not be received through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().

public class Main extends Activity {
  private TextView batteryTxt;
  private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context ctxt, Intent intent) {
      int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
      int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
      float batteryPct = level * 100 / (float)scale;
      batteryTxt.setText(String.valueOf(batteryPct) + "%");
    }
  };

  @Override
  public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.main);
    batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
    this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  }
}

How do I convert dmesg timestamp to custom date format?

So KevZero requested a less kludgy solution, so I came up with the following:

sed -r 's#^\[([0-9]+\.[0-9]+)\](.*)#echo -n "[";echo -n $(date --date="@$(echo "$(grep btime /proc/stat|cut -d " " -f 2)+\1" | bc)" +"%c");echo -n "]";echo -n "\2"#e'

Here's an example:

$ dmesg|tail | sed -r 's#^\[([0-9]+\.[0-9]+)\](.*)#echo -n "[";echo -n $(date --date="@$(echo "$(grep btime /proc/stat|cut -d " " -f 2)+\1" | bc)" +"%c");echo -n "]";echo -n "\2"#e'
[2015-12-09T04:29:20 COT] cfg80211:   (57240000 KHz - 63720000 KHz @ 2160000 KHz), (N/A, 0 mBm), (N/A)
[2015-12-09T04:29:23 COT] wlp3s0: authenticate with dc:9f:db:92:d3:07
[2015-12-09T04:29:23 COT] wlp3s0: send auth to dc:9f:db:92:d3:07 (try 1/3)
[2015-12-09T04:29:23 COT] wlp3s0: authenticated
[2015-12-09T04:29:23 COT] wlp3s0: associate with dc:9f:db:92:d3:07 (try 1/3)
[2015-12-09T04:29:23 COT] wlp3s0: RX AssocResp from dc:9f:db:92:d3:07 (capab=0x431 status=0 aid=6)
[2015-12-09T04:29:23 COT] wlp3s0: associated
[2015-12-09T04:29:56 COT] thinkpad_acpi: EC reports that Thermal Table has changed
[2015-12-09T04:29:59 COT] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment
[2015-12-09T05:00:52 COT] thinkpad_acpi: EC reports that Thermal Table has changed

If you want it to perform a bit better, put the timestamp from proc into a variable instead :)

What's the C++ version of Java's ArrayList

A couple of additional points re use of vector here.

Unlike ArrayList and Array in Java, you don't need to do anything special to treat a vector as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.

Unlike ArrayList, a vector can efficiently hold primitive types without encapsulation as a full-fledged object.

When removing items from a vector, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.

Make sure if you store complex objects in the vector that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.

Advice about reserve()ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.

Does Git Add have a verbose switch

I was debugging an issue with git and needed some very verbose output to figure out what was going wrong. I ended up setting the GIT_TRACE environment variable:

export GIT_TRACE=1
git add *.txt

You can also use these on the same line:

GIT_TRACE=1 git add *.txt

Output:

14:06:05.508517 git.c:415               trace: built-in: git add test.txt test2.txt
14:06:05.544890 git.c:415               trace: built-in: git config --get oh-my-zsh.hide-dirty

ALTER TABLE, set null in not null column, PostgreSQL 9.1

ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;

More details in the manual: http://www.postgresql.org/docs/9.1/static/sql-altertable.html

What does it mean if a Python object is "subscriptable" or not?

Off the top of my head, the following are the only built-ins that are subscriptable:

string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

But mipadi's answer is correct - any class that implements __getitem__ is subscriptable

How to get text and a variable in a messagebox

Why not use:

Dim msg as String = String.Format("Variable = {0}", variable)

More info on String.Format

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Ok, this is pretty weird. I have a couple of projects: one is a UI project (an ASP.NET MVC project) and the others are projects for stuff like repositories. The repositories project had a reference to EF, but the UI project didn't (because it didn't need one, it just needed to reference the other projects). After I installed EF for the UI project as well, everything started working. This is why, it added this piece of code to my Web.config:

<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
  </providers>
</entityFramework>

Limit to 2 decimal places with a simple pipe

Currency pipe uses the number one internally for number formatting. So you can use it like this:

{{ number | number : '1.2-2'}}

Enable PHP Apache2

You can use a2enmod or a2dismod to enable/disable modules by name.

From terminal, run: sudo a2enmod php5 to enable PHP5 (or some other module), then sudo service apache2 reload to reload the Apache2 configuration.

How can I declare a global variable in Angular 2 / Typescript?

I like the answer of @supercobra, but I would use the const keyword as it is in ES6 already available:

//
// ===== File globals.ts    
//
'use strict';

export const sep='/';
export const version: string="22.2.2"; 

Calculating number of full months between two dates in SQL

This answer follows T-SQL format. I conceptualize this problem as one of a linear-time distance between two date points in datetime format, call them Time1 and Time2; Time1 should be aligned to the 'older in time' value you are dealing with (say a Birth date or a widget Creation date or a journey Start date) and Time2 should be aligned with the 'newer in time' value (say a snapshot date or a widget completion date or a journey checkpoint-reached date).

DECLARE @Time1 DATETIME
SET @Time1 = '12/14/2015'

DECLARE @Time2 DATETIME
SET @Time2 = '12/15/2016'

The solution leverages simple measurement, conversion and calculations of the serial intersections of multiple cycles of different lengths; here: Century,Decade,Year,Month,Day (Thanks Mayan Calendar for the concept!). A quick note of thanks: I thank other contributors to Stack Overflow for showing me some of the component functions in this process that I've stitched together. I've positively rated these in my time on this forum.

First, construct a horizon that is the linear set of the intersections of the Century,Decade,Year,Month cycles, incremental by month. Use the cross join Cartesian function for this. (Think of this as creating the cloth from which we will cut a length between two 'yyyy-mm' points in order to measure distance):

SELECT 
Linear_YearMonths = (centuries.century + decades.decade + years.[year] + months.[Month]),
1 AS value
INTO #linear_months
FROM
(SELECT '18' [century] UNION ALL
SELECT '19' UNION ALL
SELECT '20') centuries 
CROSS JOIN 
(SELECT '0' [decade] UNION ALL
SELECT '1' UNION ALL
SELECT '2' UNION ALL
SELECT '3' UNION ALL
SELECT '4' UNION ALL
SELECT '5' UNION ALL
SELECT '6' UNION ALL
SELECT '7' UNION ALL
SELECT '8' UNION ALL
SELECT '9') decades 
CROSS JOIN 
(SELECT '1' [year] UNION ALL
SELECT '2' UNION ALL
SELECT '3' UNION ALL
SELECT '4' UNION ALL
SELECT '5' UNION ALL
SELECT '6' UNION ALL
SELECT '7' UNION ALL
SELECT '8' UNION ALL
SELECT '9' UNION ALL
SELECT '0') years 
CROSS JOIN  
(SELECT '-01' [month] UNION ALL
SELECT '-02' UNION ALL
SELECT '-03' UNION ALL
SELECT '-04' UNION ALL
SELECT '-05' UNION ALL
SELECT '-06' UNION ALL
SELECT '-07' UNION ALL
SELECT '-08' UNION ALL
SELECT '-09' UNION ALL
SELECT '-10' UNION ALL
SELECT '-11' UNION ALL
SELECT '-12') [months]
ORDER BY 1

Then, convert your Time1 and Time2 date points into the 'yyyy-mm' format (Think of these as the coordinate cut points on the whole cloth). Retain the original datetime versions of the points as well:

SELECT
Time1 = @Time1,
[YYYY-MM of Time1] = CASE
WHEN LEFT(MONTH(@Time1),1) <> '1' OR MONTH(@Time1) = '1'
    THEN (CAST(YEAR(@Time1) AS VARCHAR) + '-' + '0' + CAST(MONTH(@Time1) AS VARCHAR))
    ELSE (CAST(YEAR(@Time1) AS VARCHAR) + '-' + CAST(MONTH(@Time1) AS VARCHAR))
    END,
Time2 = @Time2,
[YYYY-MM of Time2] = CASE
WHEN LEFT(MONTH(@Time2),1) <> '1' OR MONTH(@Time2) = '1'
    THEN (CAST(YEAR(@Time2) AS VARCHAR) + '-' + '0' + CAST(MONTH(@Time2) AS VARCHAR))
    ELSE (CAST(YEAR(@Time2) AS VARCHAR) + '-' + CAST(MONTH(@Time2) AS VARCHAR))
    END
INTO #datepoints

Then, Select the ordinal distance of 'yyyy-mm' units, less one to convert to cardinal distance (i.e. cut a piece of cloth from the whole cloth at the identified cut points and get its raw measurement):

SELECT 
d.*,
Months_Between = (SELECT (SUM(l.value) - 1) FROM #linear_months l
            WHERE l.[Linear_YearMonths] BETWEEN d.[YYYY-MM of Time1] AND d.[YYYY-MM of Time2])
FROM #datepoints d

Raw Output: I call this a 'raw distance' because the month component of the 'yyyy-mm' cardinal distance may be one too many; the day cycle components within the month need to be compared to see if this last month value should count. In this example specifically, the raw output distance is '12'. But this wrong as 12/14 is before 12/15, so therefore only 11 full months have lapsed--its just one day shy of lapsing through the 12th month. We therefore have to bring in the intra-month day cycle to get to a final answer. Insert a 'month,day' position comparison between the to determine if the latest date point month counts nominally, or not:

SELECT 
d.*,
Months_Between = (SELECT (SUM(l.value) - 1) FROM AZ_VBP.[MY].[edg_Linear_YearMonths] l
            WHERE l.[Linear_YearMonths] BETWEEN d.[YYYY-MM of Time1] AND d.[YYYY-MM of Time2])
        + (CASE WHEN DAY(Time1) < DAY(Time2)
                THEN -1
                ELSE 0
                END)
FROM #datepoints d

Final Output: The correct answer of '11' is now our output. And so, I hope this helps. Thanks!

When to use React setState callback

this.setState({
    name:'value' 
},() => {
    console.log(this.state.name);
});

How to check if an element is off-screen

  • Get the distance from the top of the given element
  • Add the height of the same given element. This will tell you the total number from the top of the screen to the end of the given element.
  • Then all you have to do is subtract that from total document height

    jQuery(function () {
        var documentHeight = jQuery(document).height();
        var element = jQuery('#you-element');
        var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true));
        alert(distanceFromBottom)
    });
    

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

How to grey out a button?

Set Clickable as false and change the backgroung color as:

callButton.setClickable(false);
callButton.setBackgroundColor(Color.parseColor("#808080"));

400 BAD request HTTP error code meaning?

In neither case is the "syntax malformed". It's the semantics that are wrong. Hence, IMHO a 400 is inappropriate. Instead, it would be appropriate to return a 200 along with some kind of error object such as { "error": { "message": "Unknown request keyword" } } or whatever.

Consider the client processing path(s). An error in syntax (e.g. invalid JSON) is an error in the logic of the program, in other words a bug of some sort, and should be handled accordingly, in a way similar to a 403, say; in other words, something bad has gone wrong.

An error in a parameter value, on the other hand, is an error of semantics, perhaps due to say poorly validated user input. It is not an HTTP error (although I suppose it could be a 422). The processing path would be different.

For instance, in jQuery, I would prefer not to have to write a single error handler that deals with both things like 500 and some app-specific semantic error. Other frameworks, Ember for one, also treat HTTP errors like 400s and 500s identically as big fat failures, requiring the programmer to detect what's going on and branch depending on whether it's a "real" error or not.

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

How to listen state changes in react.js?

I haven't used Angular, but reading the link above, it seems that you're trying to code for something that you don't need to handle. You make changes to state in your React component hierarchy (via this.setState()) and React will cause your component to be re-rendered (effectively 'listening' for changes). If you want to 'listen' from another component in your hierarchy then you have two options:

  1. Pass handlers down (via props) from a common parent and have them update the parent's state, causing the hierarchy below the parent to be re-rendered.
  2. Alternatively, to avoid an explosion of handlers cascading down the hierarchy, you should look at the flux pattern, which moves your state into data stores and allows components to watch them for changes. The Fluxxor plugin is very useful for managing this.

How do I import an SQL file using the command line in MySQL?

If you are using MAMP on Mac OS X, this may be helpful:

/applications/MAMP/library/bin/mysql -u MYSQL_USER -p DATABASE_NAME < path/to/database_sql/FILE.sql

MYSQL_USER is root by default.

T-SQL: Deleting all duplicate rows but keeping one

Example query:

DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)

Here fields are column on which you want to group the duplicate rows.

Python: Total sum of a list of numbers with the for loop

x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
   sum=sum+x[s]
print sum   

How do you manually execute SQL commands in Ruby On Rails using NuoDB

Reposting the answer from our forum to help others with a similar issue:

@connection = ActiveRecord::Base.connection
result = @connection.exec_query('select tablename from system.tables')
result.each do |row|
puts row
end

Resolve absolute path from relative path and/or file name

SET CD=%~DP0

SET REL_PATH=%CD%..\..\build\

call :ABSOLUTE_PATH    ABS_PATH   %REL_PATH%

ECHO %REL_PATH%

ECHO %ABS_PATH%

pause

exit /b

:ABSOLUTE_PATH

SET %1=%~f2

exit /b

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Remove the newline character in a list read from a file

str.strip() returns a string with leading+trailing whitespace removed, .lstrip and .rstrip for only leading and trailing respectively.

grades.append(lists[i].rstrip('\n').split(','))

How to convert a full date to a short date in javascript?

Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY we can use something like:

new Date(dateString).toLocaleDateString('en-US', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
})

How to concatenate strings in a Windows batch file?

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

An "and" operator for an "if" statement in Bash

Try this:

if [ ${STATUS} -ne 100 -a "${STRING}" = "${VALUE}" ]

or

if [ ${STATUS} -ne 100 ] && [ "${STRING}" = "${VALUE}" ]

NSRange to Range<String.Index>

You need to use Range<String.Index> instead of the classic NSRange. The way I do it (maybe there is a better way) is by taking the string's String.Index a moving it with advance.

I don't know what range you are trying to replace, but let's pretend you want to replace the first 2 characters.

var start = textField.text.startIndex // Start at the string's start index
var end = advance(textField.text.startIndex, 2) // Take start index and advance 2 characters forward
var range: Range<String.Index> = Range<String.Index>(start: start,end: end)

textField.text.stringByReplacingCharactersInRange(range, withString: string)

Stylesheet not updating

Easiest way to see if the file is being cached is to append a query string to the <link /> element so that the browser will re-load it.

To do this you can change your stylesheet reference to something like

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

Note the v=1 part. You can update this each time you make a new version to see if it is indeed being cached.

Eloquent Collection: Counting and Detect Empty

I agree the above approved answer. But usually I use $results->isNotEmpty() method as given below.

if($results->isNotEmpty())
{
//do something
}

It's more verbose than if(!results->isEmpty()) because sometimes we forget to add '!' in front which may result in unwanted error.

Note that this method exists from version 5.3 onwards.

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

You are not creating datetime index properly,

format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))

How to set the current working directory?

import os
print os.getcwd()  # Prints the current working directory

To set the working directory:

os.chdir('c:\\Users\\uname\\desktop\\python')  # Provide the new path here

How to activate "Share" button in android app?

Add a Button and on click of the Button add this code:

Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));

Useful links:

For basic sharing

For customization

"fatal: Not a git repository (or any of the parent directories)" from git status

Sometimes its because of ssh. So you can use this:

git clone https://cfdem.git.sourceforge.net/gitroot/cfdem/liggghts

instead of:

git clone git://cfdem.git.sourceforge.net/gitroot/cfdem/liggghts

How do I debug jquery AJAX calls?

2020 answer with Chrome dev tools

To debug any XHR request:

  1. Open Chrome DEV tools (F12)
  2. Right-click your Ajax url in the console

Chrome console Ajax request

for a GET request:

  • click Open in new tab

for a POST request:

  1. click Reveal in Network panel

  2. In the Network panel:

    1. click on your request

    2. click on the response tab to see the details Chrome Network panel's response tab

Get a list of dates between two dates

Create a stored procedure which takes two parameters a_begin and a_end. Create a temporary table within it called t, declare a variable d, assign a_begin to d, and run a WHILE loop INSERTing d into t and calling ADDDATE function to increment the value d. Finally SELECT * FROM t.

How to calculate md5 hash of a file using javascript

While there are JS implementations of the MD5 algorithm, older browsers are generally unable to read files from the local filesystem.

I wrote that in 2009. So what about new browsers?

With a browser that supports the FileAPI, you *can * read the contents of a file - the user has to have selected it, either with an <input> element or drag-and-drop. As of Jan 2013, here's how the major browsers stack up:

How to tell if a connection is dead in python

Short answer:

use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.

Long answer:

The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.

TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.

Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.

Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.

So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.

Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().

Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.

I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".

In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.

What you can do is:

  • set the socket to non-blocking mode, but than you get a system-depended error to indicate the receive buffer is empty, or the send buffer is full
  • stick to blocking mode but set a very short socket timeout. This will allow you to "ping" or "check" the socket with recv(), pretty much what you want to do
  • use select() call or asyncore module with a very short timeout. Error reporting is still system-specific.

For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.

I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:

  • receive a proper response on the same socket for the exact message that you sent. Basically you are using the higher level protocol to provide confirmation.
  • perform a successful shutdow() and close() on the socket

The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)

Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.

Cross-Origin Request Blocked

@Egidius, when creating an XMLHttpRequest, you should use

var xhr = new XMLHttpRequest({mozSystem: true});

What is mozSystem?

mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.

Changes to your Manifest

On your manifest, do not forget to include this line on your permissions:

"permissions": {
       "systemXHR" : {},
}

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

Just to add to the other answers, the documentation gives this explanation:

  • KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

  • A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.

  • A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL declares them so implicitly (and silently). A table can have only one PRIMARY KEY. The name of a PRIMARY KEY is always PRIMARY, which thus cannot be used as the name for any other kind of index.

Checking Value of Radio Button Group via JavaScript?

Try:


var selectedVal;

for( i = 0; i < document.form_name.gender.length; i++ )
{
  if(document.form_name.gender[i].checked)
    selectedVal = document.form_name.gender[i].value; //male or female
    break;
  }
}

Checking for empty or null List<string>

This is able to solve your problem `if(list.Length > 0){

}`

Java: JSON -> Protobuf & back conversion

Adding to Ophirs answer, JsonFormat is available even before protobuf 3.0. However, the way to do it differs a little bit.

In Protobuf 3.0+, the JsonFormat class is a singleton and therefore do something like the below

String jsonString = "";
JsonFormat.parser().ignoringUnknownFields().merge(jsonString,yourObjectBuilder);

In Protobuf 2.5+, the below should work

String jsonString = "";
JsonFormat jsonFormat = new JsonFormat();
jsonString = jsonFormat.printToString(yourProtobufMessage);

Here is a link to a tutorial I wrote that uses the JsonFormat class in a TypeAdapter that can be registered to a GsonBuilder object. You can then use Gson's toJson and fromJson methods to convert the proto data to Java and back.

Replying to jean . If we have the protobuf data in a file and want to parse it into a protobuf message object, use the merge method TextFormat class. See the below snippet:

// Let your proto text data be in a file MessageDataAsProto.prototxt
// Read it into string  
String protoDataAsString = FileUtils.readFileToString(new File("MessageDataAsProto.prototxt"));

// Create an object of the message builder
MyMessage.Builder myMsgBuilder = MyMessage.newBuilder();

// Use text format to parse the data into the message builder
TextFormat.merge(protoDataAsString, ExtensionRegistry.getEmptyRegistry(), myMsgBuilder);

// Build the message and return
return myMsgBuilder.build();

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

I had copied and renamed the page (aspx/cs). The page name was "mainpage" so the class name at the top of the cs file as follows:

enter image description here

After renaming the class to match this error was resolved.

How to install Visual C++ Build tools?

The current version (2019/03/07) is Build Tools for Visual Studio 2017. It's an online installer, you need to include at least the individual components:

  • VC++ 2017 version xx.x tools
  • Windows SDK to use standard libraries.

How do I drag and drop files into an application?

You can implement Drag&Drop in WinForms and WPF.

  • WinForm (Drag from app window)

You should add mousemove event:

private void YourElementControl_MouseMove(object sender, MouseEventArgs e)

    {
     ...
         if (e.Button == MouseButtons.Left)
         {
                 DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move);
         }
     ...
    }
  • WinForm (Drag to app window)

You should add DragDrop event:

private void YourElementControl_DragDrop(object sender, DragEventArgs e)

    {
       ...
       foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop))
            {
                File.Copy(path, DirPath + Path.GetFileName(path));
            }
       ...
    }

Source with full code.

Is it possible to assign numeric value to an enum in Java?

Assuming that EXIT_CODE is referring to System . exit ( exit_code ) then you could do

enum ExitCode
{
      NORMAL_SHUTDOWN ( 0 ) , EMERGENCY_SHUTDOWN ( 10 ) , OUT_OF_MEMORY ( 20 ) , WHATEVER ( 30 ) ;

      private int value ;

      ExitCode ( int value )
      {
           this . value = value ;
      }

      public void exit ( )
      {
            System . exit ( value ) ;
      }
}

Then you can put the following at appropriate spots in your code

ExitCode . NORMAL_SHUTDOWN . exit ( ) '

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

Apart from what Andy mentioned, there is another difference which could be important - write-host directly writes to the host and return nothing, meaning that you can't redirect the output, e.g., to a file.

---- script a.ps1 ----
write-host "hello"

Now run in PowerShell:

PS> .\a.ps1 > someFile.txt
hello
PS> type someFile.txt
PS>

As seen, you can't redirect them into a file. This maybe surprising for someone who are not careful.

But if switched to use write-output instead, you'll get redirection working as expected.

C multi-line macro: do/while(0) vs scope block

Andrey Tarasevich provides the following explanation:

  1. On Google Groups
  2. On bytes.com

[Minor changes to formatting made. Parenthetical annotations added in square brackets []].

The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.

Consider the following code sketch:

if (<condition>)
  foo(a);
else
  bar(a);

where foo and bar are ordinary functions. Now imagine that you'd like to replace function foo with a macro of the above nature [named CALL_FUNCS]:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

Now, if your macro is defined in accordance with the second approach (just { and }) the code will no longer compile, because the 'true' branch of if is now represented by a compound statement. And when you put a ; after this compound statement, you finished the whole if statement, thus orphaning the else branch (hence the compilation error).

One way to correct this problem is to remember not to put ; after macro "invocations":

if (<condition>)
  CALL_FUNCS(a)
else
  bar(a);

This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:

#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

Now this code:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

will compile without any problems.

However, note the small but important difference between my definition of CALL_FUNCS and the first version in your message. I didn't put a ; after } while (0). Putting a ; at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.

I don't know why the author of the code you quoted in your original message put this ; after while (0). In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final ; into the macro (for the reasons that I explained above).

Difference between $.ajax() and $.get() and $.load()

The methods provide different layers of abstraction.

  • $.ajax() gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.

  • $.get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler.

  • $(selector).load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).

It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax().

E.g. you won't use $.load(), if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax() or $.get().

div with dynamic min-height based on browser window height

If #top and #bottom have fixed heights, you can use:

#top {
    position: absolute;
    top: 0;
    height: 200px;
}
#bottom {
    position: absolute;
    bottom: 0;
    height: 100px;
}
#central {
    margin-top: 200px;
    margin-bot: 100px;
}

update

If you want #central to stretch down, you could:

  • Fake it with a background on parent;
  • Use CSS3's (not widely supported, most likely) calc();
  • Or maybe use javascript to dynamically add min-height.

With calc():

#central {
    min-height: calc(100% - 300px);
}

With jQuery it could be something like:

$(document).ready(function() {
  var desiredHeight = $("body").height() - $("top").height() - $("bot").height();
  $("#central").css("min-height", desiredHeight );
});

Import PEM into Java Key Store

If you need an easy way to load PEM files in Java without having to deal with external tools (opensll, keytool), here is my code I use in production :

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.xml.bind.DatatypeConverter;

public class PEMImporter {

    public static SSLServerSocketFactory createSSLFactory(File privateKeyPem, File certificatePem, String password) throws Exception {
        final SSLContext context = SSLContext.getInstance("TLS");
        final KeyStore keystore = createKeyStore(privateKeyPem, certificatePem, password);
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keystore, password.toCharArray());
        final KeyManager[] km = kmf.getKeyManagers();
        context.init(km, null, null);
        return context.getServerSocketFactory();
    }

    /**
     * Create a KeyStore from standard PEM files
     * 
     * @param privateKeyPem the private key PEM file
     * @param certificatePem the certificate(s) PEM file
     * @param the password to set to protect the private key
     */
    public static KeyStore createKeyStore(File privateKeyPem, File certificatePem, final String password)
            throws Exception, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
        final X509Certificate[] cert = createCertificates(certificatePem);
        final KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(null);
        // Import private key
        final PrivateKey key = createPrivateKey(privateKeyPem);
        keystore.setKeyEntry(privateKeyPem.getName(), key, password.toCharArray(), cert);
        return keystore;
    }

    private static PrivateKey createPrivateKey(File privateKeyPem) throws Exception {
        final BufferedReader r = new BufferedReader(new FileReader(privateKeyPem));
        String s = r.readLine();
        if (s == null || !s.contains("BEGIN PRIVATE KEY")) {
            r.close();
            throw new IllegalArgumentException("No PRIVATE KEY found");
        }
        final StringBuilder b = new StringBuilder();
        s = "";
        while (s != null) {
            if (s.contains("END PRIVATE KEY")) {
                break;
            }
            b.append(s);
            s = r.readLine();
        }
        r.close();
        final String hexString = b.toString();
        final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
        return generatePrivateKeyFromDER(bytes);
    }

    private static X509Certificate[] createCertificates(File certificatePem) throws Exception {
        final List<X509Certificate> result = new ArrayList<X509Certificate>();
        final BufferedReader r = new BufferedReader(new FileReader(certificatePem));
        String s = r.readLine();
        if (s == null || !s.contains("BEGIN CERTIFICATE")) {
            r.close();
            throw new IllegalArgumentException("No CERTIFICATE found");
        }
        StringBuilder b = new StringBuilder();
        while (s != null) {
            if (s.contains("END CERTIFICATE")) {
                String hexString = b.toString();
                final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
                X509Certificate cert = generateCertificateFromDER(bytes);
                result.add(cert);
                b = new StringBuilder();
            } else {
                if (!s.startsWith("----")) {
                    b.append(s);
                }
            }
            s = r.readLine();
        }
        r.close();

        return result.toArray(new X509Certificate[result.size()]);
    }

    private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        final KeyFactory factory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) factory.generatePrivate(spec);
    }

    private static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes));
    }

}

Have fun.

Javascript (+) sign concatenates instead of giving sum of variables

Since you are concatenating numbers on to a string, the whole thing is treated as a string. When you want to add numbers together, you either need to do it separately and assign it to a var and use that var, like this:

i = i + 1;
divID = "question-" + i;

Or you need to specify the number addition like this:

divID = "question-" + Number(i+1);

EDIT

I should have added this long ago, but based on the comments, this works as well:

divID = "question-" + (i+1);

"continue" in cursor.forEach()

Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed returns true, doSomeLengthyOperation

elementsCollection.forEach( el => 
  el.shouldBeProcessed && doSomeLengthyOperation()
);

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

<ng-container> vs <template>

The documentation (https://angular.io/guide/template-syntax#!#star-template) gives the following example. Say we have template code like this:

<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>

Before it will be rendered, it will be "de-sugared". That is, the asterix notation will be transcribed to the notation:

<template [ngIf]="currentHero">
  <hero-detail [hero]="currentHero"></hero-detail>
</template>

If 'currentHero' is truthy this will be rendered as

<hero-detail> [...] </hero-detail>

But what if you want an conditional output like this:

<h1>Title</h1><br>
<p>text</p>

.. and you don't want the output be wrapped in a container.

You could write the de-sugared version directly like so:

<template [ngIf]="showContent">
  <h1>Title</h1>
  <p>text</p><br>
</template>

And this will work fine. However, now we need ngIf to have brackets [] instead of an asterix *, and this is confusing (https://github.com/angular/angular.io/issues/2303)

For that reason a different notation was created, like so:

<ng-container *ngIf="showContent"><br>
  <h1>Title</h1><br>
  <p>text</p><br>
</ng-container>

Both versions will produce the same results (only the h1 and p tag will be rendered). The second one is preferred because you can use *ngIf like always.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Python - Module Not Found

I had same error. For those who run python scripts on different servers, please check if the python path is correctly specified in shebang. For me on each server it was located in different dirs.

Delete dynamically-generated table row using jQuery

You should use Event Delegation, because of the fact that you are creating dynamic rows.

$(document).on('click','button.removebutton', function() {
    alert("aa");
  $(this).closest('tr').remove();
  return false;
});

Live Demo

How do I fix MSB3073 error in my post-build event?

The specified error is related to the post built event. Somehow VS tool is not able to copy the files to the destination folder. There can be many reasons for it. To check the exact error cause go to Tools > Option> Project and Solution > Built and run, and change "MsBuild project build output verbosity" to "Diagnostic". It will give you enough information to detect the actual problem.

Easiest way to loop through a filtered list with VBA?

Suppose I have numbers 1 to 10 in cells A2:A11 with my autofilter in A1. I now filter to only show numbers greater then 5 (i.e. 6, 7, 8, 9, 10).

This code will only print visible cells:

Sub SpecialLoop()
    Dim cl As Range, rng As Range

    Set rng = Range("A2:A11")

    For Each cl In rng
        If cl.EntireRow.Hidden = False Then //Use Hidden property to check if filtered or not
            Debug.Print cl
        End If
    Next

End Sub

Perhaps there is a better way with SpecialCells but the above worked for me in Excel 2003.

EDIT

Just found a better way with SpecialCells:

Sub SpecialLoop()
    Dim cl As Range, rng As Range

    Set rng = Range("A2:A11")

    For Each cl In rng.SpecialCells(xlCellTypeVisible)
        Debug.Print cl
    Next cl

End Sub

Hibernate Annotations - Which is better, field or property access?

That really depends on a specific case -- both options are available for a reason. IMO it boils down to three cases:

  1. setter has some logic that should not be executed at the time of loading an instance from a database; for example, some value validation happens in the setter, however the data coming from db should be valid (otherwise it would not get there (: ); in this case field access is most appropriate;
  2. setter has some logic that should always be invoked, even during loading of an instance from db; for example, the property being initialised is used in computation of some calculated field (e.g. property -- a monetary amount, calculated property -- a total of several monetary properties of the same instance); in this case property access is required.
  3. None of the above cases -- then both options are applicable, just stay consistent (e.i. if field access is the choice in this situation then use it all the time in similar situation).

How to pass parameters on onChange of html select

jQuery solution

How do I get the text value of a selected option

Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:

$( "#myselect" ).val();
// => 1

The second is the text value of the select.
For example, using the following select box:

<select id="myselect">
  <option value="1">Mr</option>
  <option value="2">Mrs</option>
  <option value="3">Ms</option>
  <option value="4">Dr</option>
  <option value="5">Prof</option>
</select>

If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:

$( "#myselect option:selected" ).text();
// => "Mr"  

See also

How to Completely Uninstall Xcode and Clear All Settings

  1. Open Storage Management

    • Go to ? > About This Mac > Window > Storage Management
    • Or, hit ? + Space to open Spotlight and search for Storage Management.
  2. Select Applications on left pane.

  3. Right click on Xcode on the right pane and select delete.

This will remove XCode from the installed applications list of your Mac's App Store.

Update: This worked for me on macOS Sierra 10.12.1.

HTML img tag: title attribute vs. alt attribute?

The ALT attribute is for the visually impaired user that would use a screen reader. If the ALT is missing from ANY image tag, the entire url for the image will be read. If the images are for part of the design of the site, they should still have the ALT but they can be left empty so the url doesn't have to be read for every part of the site.

CURL and HTTPS, "Cannot resolve host"

add yourlocalhost
ex. 127.0.0.1 cards.localhost in the /etc/hosts directory. Now restart apache server

How to multiply all integers inside list

Try a list comprehension:

l = [x * 2 for x in l]

This goes through l, multiplying each element by two.

Of course, there's more than one way to do it. If you're into lambda functions and map, you can even do

l = map(lambda x: x * 2, l)

to apply the function lambda x: x * 2 to each element in l. This is equivalent to:

def timesTwo(x):
    return x * 2

l = map(timesTwo, l)

Note that map() returns a map object, not a list, so if you really need a list afterwards you can use the list() function afterwards, for instance:

l = list(map(timesTwo, l))

Thanks to Minyc510 in the comments for this clarification.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

For chat applications or any other application that is in constant conversation with the server, WebSockets are the best option. However, you can only use WebSockets with a server that supports them, so that may limit your ability to use them if you cannot install the required libraries. In which case, you would need to use Long Polling to obtain similar functionality.