Programs & Examples On #Punctuation

Punctuation's are the marks, such as full stop, comma, and brackets, used in writing to separate sentences and their elements and to clarify meaning.

Best way to strip punctuation from a string

Not necessarily simpler, but a different way, if you are more familiar with the re family.

import re, string
s = "string. With. Punctuation?" # Sample string 
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)

How do I add space between two variables after a print in Python

Alternatively you can use ljust/rjust to make the formatting nicer.

print "%s%s" % (str(count).rjust(10), conv)

or

print str(count).ljust(10), conv

How do I set up HttpContent for my HttpClient PostAsync second parameter?

To add to Preston's answer, here's the complete list of the HttpContent derived classes available in the standard library:

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

There's also a supposed ObjectContent but I was unable to find it in ASP.NET Core.

Of course, you could skip the whole HttpContent thing all together with Microsoft.AspNet.WebApi.Client extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:

var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
    Title = "New Article Title",
    Body = "New Article Body"
});

How to print (using cout) a number in binary form?

Is this what you're looking for?

std::cout << std::hex << val << std::endl;

Create directory if it does not exist

When you specify the -Force flag, PowerShell will not complain if the folder already exists.

One-liner:

Get-ChildItem D:\TopDirec\SubDirec\Project* | `
  %{ Get-ChildItem $_.FullName -Filter Revision* } | `
  %{ New-Item -ItemType Directory -Force -Path (Join-Path $_.FullName "Reports") }

BTW, for scheduling the task please check out this link: Scheduling Background Jobs.

Kill detached screen session

Alternatively, while in your screen session all you have to do is type exit

This will kill the shell session initiated by the screen, which effectively terminates the screen session you are on.

No need to bother with screen session id, etc.

Flexbox: center horizontally and vertically

RESULT: Code

CODE

HTML:

<div class="flex-container">
  <div class="rows">

    <div class="row">
      <span class="flex-item">1</span>
    </div>
    <div class="row">
      <span class="flex-item">2</span>
    </div>
    <div class="row">
      <span class="flex-item">3</span>
    </div>
    <div class="row">
      <span class="flex-item">4</span>
    </div>

  </div>  
</div>

CSS:

html, body {
  height: 100%;  
}

.flex-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.rows {
  display: flex;
  flex-direction: column;
}

where flex-container div is used to center vertically and horizontally your rows div, and rows div is used to group your "items" and ordering them in a column based one.

String.equals() with multiple conditions (and one action on result)

if (Arrays.asList("John", "Mary", "Peter").contains(name)) {
}
  • This is not as fast as using a prepared Set, but it performs no worse than using OR.
  • This doesn't crash when name is NULL (same with Set).
  • I like it because it looks clean

Run PostgreSQL queries from the command line

Open "SQL Shell (psql)" from your Applications (Mac).

enter image description here

Click enter for the default settings. Enter the password when prompted.

enter image description here

*) Type \? for help

*) Type \conninfo to see which user you are connected as.

*) Type \l to see the list of Databases.

enter image description here

*) Connect to a database by \c <Name of DB>, for example \c GeneDB1

enter image description here

You should see the key prompt change to the new DB, like so: enter image description here

*) Now that you're in a given DB, you want to know the Schemas for that DB. The best command to do this is \dn.

enter image description here

Other commands that also work (but not as good) are select schema_name from information_schema.schemata; and select nspname from pg_catalog.pg_namespace;:

enter image description here

-) Now that you have the Schemas, you want to know the tables in those Schemas. For that, you can use the dt command. For example \dt "GeneSchema1".*

enter image description here

*) Now you can do your queries. For example:

enter image description here

*) Here is what the above DB, Schema, and Tables look like in pgAdmin:

enter image description here

MassAssignmentException in Laravel

This is not a good way when you want to seeding database.
Use faker instead of hard coding, and before all this maybe it's better to truncate tables.

Consider this example :

    // Truncate table.  
    DB::table('users')->truncate();

    // Create an instance of faker.
    $faker = Faker::create();

    // define an array for fake data.
    $users = [];

    // Make an array of 500 users with faker.
    foreach (range(1, 500) as $index)
    {
        $users[] = [
            'group_id' => rand(1, 3),
            'name' => $faker->name,
            'company' => $faker->company,
            'email' => $faker->email,
            'phone' => $faker->phoneNumber,
            'address' => "{$faker->streetName} {$faker->postCode} {$faker->city}",
            'about' => $faker->sentence($nbWords = 20, $variableNbWords = true),
            'created_at' => new DateTime,
            'updated_at' => new DateTime,
        ];
    }

    // Insert into database.
    DB::table('users')->insert($users);

Tensorflow: how to save/restore a model?

For tensorflow 2.0, it is as simple as

# Save the model
model.save('path_to_my_model.h5')

To restore:

new_model = tensorflow.keras.models.load_model('path_to_my_model.h5')

jQuery textbox change event

You can achieve it:

 $(document).ready(function(){              
     $('#textBox').keyup(function () {alert('changed');});
 });

or with change (handle copy paste with right click):

 $(document).ready(function(){              
     $('#textBox2').change(function () {alert('changed');});
 });

Here is Demo

Where does Console.WriteLine go in ASP.NET?

If you use System.Diagnostics.Debug.WriteLine(...) instead of Console.WriteLine(), then you can see the results in the Output window of Visual Studio.

nodejs mysql Error: Connection lost The server closed the connection

Creating and destroying the connections in each query maybe complicated, i had some headaches with a server migration when i decided to install MariaDB instead MySQL. For some reason in the file etc/my.cnf the parameter wait_timeout had a default value of 10 sec (it causes that the persistence can't be implemented). Then, the solution was set it in 28800, that's 8 hours. Well, i hope help somebody with this "güevonada"... excuse me for my bad english.

Making a WinForms TextBox behave like your browser's address bar

This worked for a WPF/XAML TextBox.

    private bool initialEntry = true;
    private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
    {
        if (initialEntry)
        {
            e.Handled = true;
            initialEntry = false;
            TextBox.SelectAll();
        }
    }
    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox.SelectAll();
        initialEntry = true;      
    }

Enable/Disable a dropdownbox in jquery

try this

 <script type="text/javascript">
        $(document).ready(function () {
            $("#chkdwn2").click(function () {
                if (this.checked)
                    $('#dropdown').attr('disabled', 'disabled');
                else
                    $('#dropdown').removeAttr('disabled');
            });
        });
    </script>

Shell equality operators (=, ==, -eq)

It depends on the Test Construct around the operator. Your options are double parentheses, double brackets, single brackets, or test.

If you use (()), you are testing arithmetic equality with == as in C:

$ (( 1==1 )); echo $?
0
$ (( 1==2 )); echo $?
1

(Note: 0 means true in the Unix sense and a failed test results in a non-zero number.)

Using -eq inside of double parentheses is a syntax error.

If you are using [] (or single brackets) or [[]] (or double brackets), or test you can use one of -eq, -ne, -lt, -le, -gt, or -ge as an arithmetic comparison.

$ [ 1 -eq 1 ]; echo $?
0
$ [ 1 -eq 2 ]; echo $?
1
$ test 1 -eq 1; echo $?
0

The == inside of single or double brackets (or the test command) is one of the string comparison operators:

$ [[ "abc" == "abc" ]]; echo $?
0
$ [[ "abc" == "ABC" ]]; echo $?
1

As a string operator, = is equivalent to ==. Also, note the whitespace around = or ==: it’s required.

While you can do [[ 1 == 1 ]] or [[ $(( 1+1 )) == 2 ]] it is testing the string equality — not the arithmetic equality.

So -eq produces the result probably expected that the integer value of 1+1 is equal to 2 even though the right-hand side is a string and has a trailing space:

$ [[ $(( 1+1 )) -eq  "2 " ]]; echo $?
0

While a string comparison of the same picks up the trailing space and therefore the string comparison fails:

$ [[ $(( 1+1 )) == "2 " ]]; echo $?
1

And a mistaken string comparison can produce a completely wrong answer. 10 is lexicographically less than 2, so a string comparison returns true or 0. So many are bitten by this bug:

$ [[ 10 < 2 ]]; echo $?
0

The correct test for 10 being arithmetically less than 2 is this:

$ [[ 10 -lt 2 ]]; echo $?
1

In comments, there is a question about the technical reason why using the integer -eq on strings returns true for strings that are not the same:

$ [[ "yes" -eq "no" ]]; echo $?
0

The reason is that Bash is untyped. The -eq causes the strings to be interpreted as integers if possible including base conversion:

$ [[ "0x10" -eq 16 ]]; echo $?
0
$ [[ "010" -eq 8 ]]; echo $?
0
$ [[ "100" -eq 100 ]]; echo $?
0

And 0 if Bash thinks it is just a string:

$ [[ "yes" -eq 0 ]]; echo $?
0
$ [[ "yes" -eq 1 ]]; echo $?
1

So [[ "yes" -eq "no" ]] is equivalent to [[ 0 -eq 0 ]]


Last note: Many of the Bash specific extensions to the Test Constructs are not POSIX and therefore may fail in other shells. Other shells generally do not support [[...]] and ((...)) or ==.

Angular 6: saving data to local storage

you can use localStorage for storing the json data:

the example is given below:-

let JSONDatas = [
    {"id": "Open"},
    {"id": "OpenNew", "label": "Open New"},
    {"id": "ZoomIn", "label": "Zoom In"},
    {"id": "ZoomOut", "label": "Zoom Out"},
    {"id": "Find", "label": "Find..."},
    {"id": "FindAgain", "label": "Find Again"},
    {"id": "Copy"},
    {"id": "CopyAgain", "label": "Copy Again"},
    {"id": "CopySVG", "label": "Copy SVG"},
    {"id": "ViewSVG", "label": "View SVG"}
]

localStorage.setItem("datas", JSON.stringify(JSONDatas));

let data = JSON.parse(localStorage.getItem("datas"));

console.log(data);

How to install popper.js with Bootstrap 4?

I had problems installing it Bootstrap as well, so I did:

Install popper.js: npm install popper.js@^1.12.3 --save

Install jQuery: npm install [email protected] --save

Then I had a high severity vulnerability message when installing [email protected] and got this message:

run npm audit fix to fix them, or npm audit for details

So I did npm audit fix, and after another npm audit fix --force it successfully installed!

C# Dictionary get item by index

Your key is a string and your value is an int. Your code won't work because it cannot look up the random int you pass. Also, please provide full code

Git - remote: Repository not found

in my case, i cannot clone github due to user is wrong.

go to ~/.gitconfig then try to remove this line of code (just delete it then save file).

[user]
    name = youruser
    email = [email protected]

or try to use one liner in your cmd or terminal : git config --global --remove-section user

and try to do git clone again. hope it'll fix your day. ><

Calling another different view from the controller using ASP.NET MVC 4

Also, you can just set the ViewName:

return View("ViewName");

Full controller example:

public ActionResult SomeAction() {
    if (condition)
    {
        return View("CustomView");
    }else{
        return View();
    }
}

This works on MVC 5.

How can I convert String to Int?

int.TryParse()

It won't throw if the text is not numeric.

How to disable a particular checkstyle rule for a particular line of code?

Every answer refering to SuppressWarningsFilter is missing an important detail. You can only use the all-lowercase id if it's defined as such in your checkstyle-config.xml. If not you must use the original module name.

For instance, if in my checkstyle-config.xml I have:

<module name="NoWhitespaceBefore"/>

I cannot use:

@SuppressWarnings({"nowhitespacebefore"})

I must, however, use:

@SuppressWarnings({"NoWhitespaceBefore"})

In order for the first syntax to work, the checkstyle-config.xml should have:

<module name="NoWhitespaceBefore">
  <property name="id" value="nowhitespacebefore"/>
</module>

This is what worked for me, at least in the CheckStyle version 6.17.

Best way to test exceptions with Assert to ensure they will be thrown

As of v 2.5, NUnit has the following method-level Asserts for testing exceptions:

Assert.Throws, which will test for an exact exception type:

Assert.Throws<NullReferenceException>(() => someNullObject.ToString());

And Assert.Catch, which will test for an exception of a given type, or an exception type derived from this type:

Assert.Catch<Exception>(() => someNullObject.ToString());

As an aside, when debugging unit tests which throw exceptions, you may want to prevent VS from breaking on the exception.

Edit

Just to give an example of Matthew's comment below, the return of the generic Assert.Throws and Assert.Catch is the exception with the type of the exception, which you can then examine for further inspection:

// The type of ex is that of the generic type parameter (SqlException)
var ex = Assert.Throws<SqlException>(() => MethodWhichDeadlocks());
Assert.AreEqual(1205, ex.Number);

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

Simple mediaplayer play mp3 from file path?

2020 - NOV

This worked for me:

final File file = new File(getFilesDir(), "test.wav");//OR path to existing file
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));
mediaPlayer.start();

Table row and column number in jQuery

You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:

$('td').click(function(){
  var col = $(this).parent().children().index($(this));
  var row = $(this).parent().parent().children().index($(this).parent());
  alert('Row: ' + row + ', Column: ' + col);
});

Check a running example here.

Checking if sys.argv[x] is defined

I use this - it never fails:

startingpoint = 'blah'
if sys.argv[1:]:
   startingpoint = sys.argv[1]

How to make an anchor tag refer to nothing?

What do you mean by nothing?

<a href='about:blank'>blank page</a>

or

<a href='whatever' onclick='return false;'>won't navigate</a>

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

If you have Cygwin installed (which I strongly recommend for a variety of reasons), you could use the 'file' utility on the DLL

file <filename>

which would give an output like this:

icuuc36.dll: MS-DOS executable PE  for MS Windows (DLL) (GUI) Intel 80386 32-bit

FileNotFoundException..Classpath resource not found in spring?

Best way to handle such error-"Use Annotation". spring.xml-<context:component-scan base-package=com.SpringCollection.SpringCollection"/>

add annotation in that class for which you want to use Bean ID(i am using class "First")-

@Component

public class First {

Changes In Main Class**-

ApplicationContext context = new AnnotationConfigApplicationContext(First.class); use this.

Dynamically create Bootstrap alerts box through JavaScript

You can also create a HTML alert template like this:

<div class="alert alert-info" id="alert_template" style="display: none;">
    <button type="button" class="close">×</button>
</div>

And so you can do in JavaScript this here:

$("#alert_template button").after('<span>Some text</span>');
$('#alert_template').fadeIn('slow');

Which is in my opinion cleaner and faster. In addition you stick to Twitter Bootstrap standards when calling fadeIn().

To guarantee that this alert template works also with multiple calls (so it doesn't add the new message to the old one), add this here to your JavaScript:

$('#alert_template .close').click(function(e) {
    $("#alert_template span").remove();
});

So this call removes the span element every time you close the alert via the x-button.

What is log4j's default log file dumping path

By default, Log4j logs to standard output and that means you should be able to see log messages on your Eclipse's console view. To log to a file you need to use a FileAppender explicitly by defining it in a log4j.properties file in your classpath.

Create the following log4j.properties file in your classpath. This allows you to log your message to both a file as well as your console.

log4j.rootLogger=debug, stdout, file

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=example.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%p %t %c - %m%n

Note: The above creates an example.log in your current working directory (i.e. Eclipse's project directory) so that the same log4j.properties could work with different projects without overwriting each other's logs.

References:
Apache log4j 1.2 - Short introduction to log4j

What's the difference between git reset --mixed, --soft, and --hard?

There are a number of answers here with a misconception about git reset --soft. While there is a specific condition in which git reset --soft will only change HEAD (starting from a detached head state), typically (and for the intended use), it moves the branch reference you currently have checked out. Of course it can't do this if you don't have a branch checked out (hence the specific condition where git reset --soft will only change HEAD).

I've found this to be the best way to think about git reset. You're not just moving HEAD (everything does that), you're also moving the branch ref, e.g., master. This is similar to what happens when you run git commit (the current branch moves along with HEAD), except instead of creating (and moving to) a new commit, you move to a prior commit.

This is the point of reset, changing a branch to something other than a new commit, not changing HEAD. You can see this in the documentation example:

Undo a commit, making it a topic branch

          $ git branch topic/wip     (1)
          $ git reset --hard HEAD~3  (2)
          $ git checkout topic/wip   (3)
  1. You have made some commits, but realize they were premature to be in the "master" branch. You want to continue polishing them in a topic branch, so create "topic/wip" branch off of the current HEAD.
  2. Rewind the master branch to get rid of those three commits.
  3. Switch to "topic/wip" branch and keep working.

What's the point of this series of commands? You want to move a branch, here master, so while you have master checked out, you run git reset.

The top voted answer here is generally good, but I thought I'd add this to correct the several answers with misconceptions.

Change your branch

git reset --soft <ref>: resets the branch pointer for the currently checked out branch to the commit at the specified reference, <ref>. Files in your working directory and index are not changed. Committing from this stage will take you right back to where you were before the git reset command.

Change your index too

git reset --mixed <ref>

or equivalently

git reset <ref>:

Does what --soft does AND also resets the index to the match the commit at the specified reference. While git reset --soft HEAD does nothing (because it says move the checked out branch to the checked out branch), git reset --mixed HEAD, or equivalently git reset HEAD, is a common and useful command because it resets the index to the state of your last commit.

Change your working directory too

git reset --hard <ref>: does what --mixed does AND also overwrites your working directory. This command is similar to git checkout <ref>, except that (and this is the crucial point about reset) all forms of git reset move the branch ref HEAD is pointing to.

A note about "such and such command moves the HEAD":

It is not useful to say a command moves the HEAD. Any command that changes where you are in your commit history moves the HEAD. That's what the HEAD is, a pointer to wherever you are. HEADis you, and so will move whenever you do.

How do I give PHP write access to a directory?

You can set selinux to permissive in order to analyze.

    # setenforce 0

Selinux will log but permit acesses. So you can check the /var/log/audit/audit.log for details. Maybe you will need change selinux context. Fot this, you will use chcon command. If you need, show us your audit.log to more detailed answer.

Don't forget to enable selinux after you solved the problem. It better keep selinux enforced.

    # setenforce 1

GitHub README.md center image

TLDR:
Just jump straight down to look at the 4 examples (1.1, 1.2, 1.3, and 1.4) in the section below called "1. Centering and aligning images in GitHub readmes using the deprecated HTML align attribute"!

Also, view actual examples of this on GitHub in a couple readme markdown files in my repositories here:

  1. https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/markdown/github_readme_center_and_align_images.md
  2. and https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world#3-markdown
    1. enter image description here

Background on how to center and align images in markdown:

So, it turns out that GitHub explicitly blocks/filters out all attempts at editing any form of CSS (Cascading Style Sheets) styles (including external, internal, and inline) inside GitHub *.md markdown files, such as readmes. See here (emphasis added):

  1. Custom css file for readme.md in a Github repo

    GitHub does not allow for CSS to affect README.md files through CSS for security reasons...

  2. https://github.community/t/github-flavored-markdown-doesnt-render-css-styles-inside-a-html-block/126258/2?u=electricrcaircraftguy

    Unfortunately you cannot use CSS in GitHub markdown as it is a part of the sanitization process.

    The HTML is sanitized, aggressively removing things that could harm you and your kin—such as script tags, inline-styles, and class or id attributes.

    source: https://github.com/github/markup

So, that means to center or align images in GitHub readmes, your only solution is to use the deprecated HTML align attribute (that happens to still function), as this answer shows.

I should also point out that although that solution does indeed work, it is causing a lot of confusion for that answer to claim to use inline css to solve the problem, since, like @Poikilos points out in the comments, that answer has no CSS in it whatsoever. Rather, the align="center" part of the <p> element is a deprecated HTML attribute (that happens to still function) and is NOT CSS. All CSS, whether external, internal, or inline is banned from GitHub readmes and explicitly removed, as indicated through trial-and-error and in the two references above.

This leads me to split my answer into two answers here:

  1. "Centering and aligning images in GitHub readmes using the deprecated HTML align attribute", and
  2. "Centering and aligning images using modern CSS in any markdown document where you also have control over CSS styles".

Option 2 only works in places where you have full control over CSS styles, such as in a custom GitHub Pages website you make maybe?


1. Centering and aligning images in GitHub readmes using the deprecated HTML align attribute:

This works in any GitHub *.md markdown file, such as a GitHub readme.md file. It relies on the deprecated HTML align attribute, but still works fine. You can see a full demo of this in an actual GitHub readme in my eRCaGuy_hello_world repo here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/markdown/github_readme_center_and_align_images.md.

Notes:

  1. Be sure to set width="100%" inside each of your <p> paragraph elements below, or else the entire paragraph tries to allow word wrap around it, causing weird and less-predicable effects.
  2. To resize your image, simly set width="30%", or whatever percent you'd like between 0% and 100%, to get the desired effect! This is much easier than trying to set a pixel size, such as width="200" height="150", as using a width percent automatically adjusts to your viewer's screen and to the page display width, and it automatically resizes the image as you resize your browser window as well. It also avoids skewing the image into unnatural proportions. It's a great feature!
  3. Options for the (deprecated) HTML align attribute include left, center, right, and justify.

1.1. Align images left, right, or centered, with NO WORD WRAP:

This:

**Align left:**
<p align="left" width="100%">
    <img width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 
</p>

**Align center:**
<p align="center" width="100%">
    <img width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 
</p>

**Align right:**
<p align="right" width="100%">
    <img width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 
</p>

Produces this:

enter image description here

If you'd like to set the text itself to left, center, or right, you can include the text inside the <p> element as well, as regular HTML, like this:

<p align="right" width="100%">
    This text is also aligned to the right.<br>
    <img width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 
</p>

To produce this:

enter image description here

1.2. Align images left, right, or centered, WITH word wrap:

This:

**Align left (works fine):**

<img align="left" width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 

[Arduino](https://en.wikipedia.org/wiki/Arduino) (/??r'dwi?no?/) is an open-source hardware and software company, project and user community that designs and manufactures single-board microcontrollers and microcontroller kits for building digital devices. Its hardware products are licensed under a CC-BY-SA license, while software is licensed under the GNU Lesser General Public License (LGPL) or the GNU General Public License (GPL),[1] permitting the manufacture of Arduino boards and software distribution by anyone. Arduino boards are available commercially from the official website or through authorized distributors. Arduino board designs use a variety of microprocessors and controllers. The boards are equipped with sets of digital and analog input/output (I/O) pins that may be interfaced to various expansion boards ('shields') or breadboards (for prototyping) and other circuits.


**Align center (doesn't really work):**

<img align="center" width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 

[Arduino](https://en.wikipedia.org/wiki/Arduino) (/??r'dwi?no?/) is an open-source hardware and software company, project and user community that designs and manufactures single-board microcontrollers and microcontroller kits for building digital devices. Its hardware products are licensed under a CC-BY-SA license, while software is licensed under the GNU Lesser General Public License (LGPL) or the GNU General Public License (GPL),[1] permitting the manufacture of Arduino boards and software distribution by anyone. Arduino boards are available commercially from the official website or through authorized distributors. Arduino board designs use a variety of microprocessors and controllers. The boards are equipped with sets of digital and analog input/output (I/O) pins that may be interfaced to various expansion boards ('shields') or breadboards (for prototyping) and other circuits.


**Align right (works fine):**

<img align="right" width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 

[Arduino](https://en.wikipedia.org/wiki/Arduino) (/??r'dwi?no?/) is an open-source hardware and software company, project and user community that designs and manufactures single-board microcontrollers and microcontroller kits for building digital devices. Its hardware products are licensed under a CC-BY-SA license, while software is licensed under the GNU Lesser General Public License (LGPL) or the GNU General Public License (GPL),[1] permitting the manufacture of Arduino boards and software distribution by anyone. Arduino boards are available commercially from the official website or through authorized distributors. Arduino board designs use a variety of microprocessors and controllers. The boards are equipped with sets of digital and analog input/output (I/O) pins that may be interfaced to various expansion boards ('shields') or breadboards (for prototyping) and other circuits.

Produces this:

enter image description here

1.3. Align images side-by-side:

Reminder: MAKE SURE TO GIVE THE entire <p> paragraph element the full 100% column width (width="100%", as shown below) or else text gets word-wrapped around it, botching your vertical alignment and vertical spacing/formatting you may be trying to maintain!

This:

33% width each (_possibly_ a little too wide to fit all 3 images side-by-side, depending on your markdown viewer):
<p align="center" width="100%">
    <img width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="33%" src="https://i.stack.imgur.com/RJj4x.png"> 
</p>

32% width each (perfect size to just barely fit all 3 images side-by-side):
<p align="center" width="100%">
    <img width="32%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="32%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="32%" src="https://i.stack.imgur.com/RJj4x.png"> 
</p>

31% width each:
<p align="center" width="100%">
    <img width="31%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="31%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="31%" src="https://i.stack.imgur.com/RJj4x.png"> 
</p>

30% width each:
<p align="center" width="100%">
    <img width="30%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="30%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="30%" src="https://i.stack.imgur.com/RJj4x.png"> 
</p>

Produces this:

enter image description here

I am aligning all paragraph <p> elements above to the center, but you can also align left or right, as shown in previous examples, to force the row of images to get aligned that way too. Example:

This:

Align the whole row of images to the right this time:
<p align="right" width="100%">
    <img width="25%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="25%" src="https://i.stack.imgur.com/RJj4x.png"> 
    <img width="25%" src="https://i.stack.imgur.com/RJj4x.png"> 
</p>

Produces this (aligning the whole row of images according to the align attribute set above, or to the right in this case). Generally, center is preferred, as done in the examples above.

enter image description here

1.4. Use a markdown table to improve vertical spacing of odd-sized/odd-shaped images:

Sometimes, with odd-sized or different-shaped images, using just the "row of images" methods above produces slightly awkward-looking results.

This code produces two rows of images which have good horizontal spacing, but bad vertical spacing. This code:

<p align="center" width="100%">
    <img width="32%" src="photos/pranksta1.jpg"> 
    <img width="32%" src="photos/pranksta2.jpg"> 
    <img width="32%" src="photos/pranksta3.jpg"> 
</p>
<p align="center" width="100%">
    <img width="32%" src="photos/pranksta4.jpg"> 
    <img width="32%" src="photos/pranksta5.jpg"> 
    <img width="32%" src="photos/pranksta6.jpg"> 
</p>

Produces this, since the last image in row 1 ("pranksta3.jpg") is a very tall image with 2x the height as the other images:

enter image description here

So, placing those two rows of images inside a markdown table forces nice-looking vertical spacing. Notice in the markdown table below that each image is set to have an HTML width attribute set to 100%. This is because it is relative to the table cell the image sits in, NOT relative to the page column width anymore. Since we want each image to fill the entire width of each cell, we set their widths all to width="100%".

This markdown table with images in it:

|                                               |                                               |                                               |
|-----------------------------------------------|-----------------------------------------------|-----------------------------------------------|
| <img width="100%" src="photos/pranksta1.jpg"> | <img width="100%" src="photos/pranksta2.jpg"> | <img width="100%" src="photos/pranksta3.jpg"> |
| <img width="100%" src="photos/pranksta4.jpg"> | <img width="100%" src="photos/pranksta5.jpg"> | <img width="100%" src="photos/pranksta6.jpg"> |

Produces this, which looks much nicer and more well-spaced in my opinion, since vertical spacing is also centered for each row of images:

enter image description here


2. Centering and aligning images using modern CSS in any markdown document where you also have control over CSS styles:

This works in any markdown file, such as a GitHub Pages website maybe?, where you do have full control over CSS styles. This does NOT work in any GitHub *.md markdown file, such as a readme.md, therefore, because GitHub expliclty scans for and disables all custom CSS styling you attempt to use. See above.

TLDR;

Use this HTML/CSS to add and center an image and set its size to 60% of the screen space width inside your markdown file, which is usually a good starting value:

<img src="https://i.stack.imgur.com/RJj4x.png" 
     style="display:block;float:none;margin-left:auto;margin-right:auto;width:60%"> 

Change the width CSS value to whatever percent you want, or remove it altogether to use the markdown default size, which I think is 100% of the screen width if the image is larger than the screen, or it is the actual image width otherwise.

Done!

Or, keep reading for a lot more information.

Here are various HTML and CSS options which work perfectly inside markdown files, so long as CSS is not explicitly forbidden:

1. Center and configure (resize) ALL images in your markdown file:

Just copy and paste this to the top of your markdown file to center and resize all images in the file (then just insert any images you want with normal markdown syntax):

<style>
img
{
    display:block; 
    float:none; 
    margin-left:auto;
    margin-right:auto;
    width:60%;
}
</style> 

Or, here is the same code as above but with detailed HTML and CSS comments to explain exactly what is going on:

<!-- (This is an HTML comment). Copy and paste this entire HTML `<style>...</style>` element (block)
to the top of your markdown file -->
<style>
/* (This is a CSS comment). The below `img` style sets the default CSS styling for all images
hereafter in this markdown file. */
img
{
    /* Default display value is `inline-block`. Set it to `block` to prevent surrounding text from
    wrapping around the image. Instead, `block` format will force the text to be above or below the
    image, but never to the sides. */
    display:block; 
    /* Common float options are `left`, `right`, and `none`. Set to `none` to override any previous
    settings which might have been `left` or `right`. `left` causes the image to be to the left,
    with text wrapped to the right of the image, and `right` causes the image to be to the right,
    with text wrapped to its left, so long as `display:inline-block` is also used. */
    float:none; 
    /* Set both the left and right margins to `auto` to cause the image to be centered. */
    margin-left:auto;
    margin-right:auto;
    /* You may also set the size of the image, in percent of width of the screen on which the image
    is being viewed, for example. A good starting point is 60%. It will auto-scale and auto-size
    the image no matter what screen or device it is being viewed on, maintaining proporptions and 
    not distorting it. */
    width:60%;
    /* You may optionally force a fixed size, or intentionally skew/distort an image by also 
    setting the height. Values for `width` and `height` are commonly set in either percent (%) 
    or pixels (px). Ex: `width:100%;` or `height:600px;`. */
    /* height:400px; */
}
</style> 

Now, whether you insert an image using markdown:

![](https://i.stack.imgur.com/RJj4x.png)

Or HTML in your markdown file:

<img src="https://i.stack.imgur.com/RJj4x.png"> 

...it will be automatically centered and sized to 60% of the screenview width, as described in the comments within the HTML and CSS above. (Of course the 60% size is really easily changeable too, and I present simple ways below to do it on an image-by-image basis as well).

2. Center and configure images on a case-by-case basis, one at a time:

Whether or not you have copied and pasted the above <style> block into the top of your markdown file, this will also work, as it overrides and takes precedence over any file-scope style settings you may have set above:

<img src="https://i.stack.imgur.com/RJj4x.png" style="display:block;float:none;margin-left:auto;margin-right:auto;width:60%"> 

You can also format it on multiple lines, like this, and it will still work:

<img src="https://i.stack.imgur.com/RJj4x.png" 
     alt="this is an optional description of the image to help the blind and show up in case the 
          image won't load" 
     style="display:block; /* override the default display setting of `inline-block` */ 
            float:none; /* override any prior settings of `left` or `right` */ 
            /* set both the left and right margins to `auto` to center the image */
            margin-left:auto; 
            margin-right:auto;
            width:60%; /* optionally resize the image to a screen percentage width if you want too */
            "> 

3. In addition to all of the above, you can also create CSS style classes to help stylize individual images:

Add this whole thing to the top of your markdown file.

<style>

/* By default, make all images center-aligned, and 60% of the width 
of the screen in size */
img
{
    display:block; 
    float:none; 
    margin-left:auto;
    margin-right:auto;
    width:60%;
}

/* Create a CSS class to style images to left-align, or "float left" */
.leftAlign
{
    display:inline-block;
    float:left;
    /* provide a 15 pixel gap between the image and the text to its right */
    margin-right:15px; 
}

/* Create a CSS class to style images to right-align, or "float right" */
.rightAlign
{
    display:inline-block;
    float:right;
    /* provide a 15 pixel gap between the image and the text to its left */
    margin-left:15px;
}

</style> 

Now, your img CSS block has set the default setting for images to be centered and 60% of the width of the screen space in size, but you can use the leftAlign and rightAlign CSS classes to override those settings on an image-by-image basis.

For example, this image will be center-aligned and 60% in size (the default I set above):

<img src="https://i.stack.imgur.com/RJj4x.png"> 

This image will be left-aligned, however, with text wrapping to its right, using the leftAlign CSS class we just created above!

<img src="https://i.stack.imgur.com/RJj4x.png" class="leftAlign">

It might look like this:

enter image description here

You can still override any of its CSS properties via the style attribute, however, such as width, like this:

<img src="https://i.stack.imgur.com/RJj4x.png" class="leftAlign" style="width:20%">

And now you'll get this:

enter image description here

4. Create 3 CSS classes, but don't change the img markdown defaults

Another option to what we just showed above, where we modified the default img property:value settings and created 2 classes, is to just leave all the default markdown img properties alone, but create 3 custom CSS classes, like this:

<style>

/* Create a CSS class to style images to center-align */
.centerAlign
{
    display:block;
    float:none;
    /* Set both the left and right margins to `auto` to cause the image to be centered. */
    margin-left:auto;
    margin-right:auto;
    width:60%;
}

/* Create a CSS class to style images to left-align, or "float left" */
.leftAlign
{
    display:inline-block;
    float:left;
    /* provide a 15 pixel gap between the image and the text to its right */
    margin-right:15px; 
    width:60%;
}

/* Create a CSS class to style images to right-align, or "float right" */
.rightAlign
{
    display:inline-block;
    float:right;
    /* provide a 15 pixel gap between the image and the text to its left */
    margin-left:15px;
    width:60%;
}

</style> 

Use them, of course, like this:

<img src="https://i.stack.imgur.com/RJj4x.png" class="centerAlign" style="width:20%">

Notice how I manually set the width property using the CSS style attribute above, but if I had something more complicated I wanted to do, I could also create some additional classes like this, adding them inside the <style>...</style> block above:

/* custom CSS class to set a predefined "small" size for an image */
.small
{
    width:20%;
    /* set any other properties, as desired, inside this class too */
}

Now you can assign multiple classes to the same object, like this. Simply [separate class names by a space, NOT a comma][11]. In the event of conflicting settings, I believe whichever setting comes last will be the one that takes effect, overriding any previously-set settings. This should also be the case in the event you set the same CSS properties multiple times in the same CSS class or inside the same HTML style attribute.

<img src="https://i.stack.imgur.com/RJj4x.png" class="centerAlign small">

5. Consolidate Common Settings in CSS Classes:

The last trick is one I learned in this answer here: How can I use CSS to style multiple images differently?. As you can see above, all 3 of the CSS align classes set the image width to 60%. Therefore, this common setting can be set all at once like this if you wish, then you can set the specific settings for each class afterwards:

<style>

/* set common properties for multiple CSS classes all at once */
.centerAlign, .leftAlign, .rightAlign {
    width:60%;
}

/* Now set the specific properties for each class individually */

/* Create a CSS class to style images to center-align */
.centerAlign
{
    display:block;
    float:none;
    /* Set both the left and right margins to `auto` to cause the image to be centered. */
    margin-left:auto;
    margin-right:auto;
}

/* Create a CSS class to style images to left-align, or "float left" */
.leftAlign
{
    display:inline-block;
    float:left;
    /* provide a 15 pixel gap between the image and the text to its right */
    margin-right:15px; 
}

/* Create a CSS class to style images to right-align, or "float right" */
.rightAlign
{
    display:inline-block;
    float:right;
    /* provide a 15 pixel gap between the image and the text to its left */
    margin-left:15px;
}

/* custom CSS class to set a predefined "small" size for an image */
.small
{
    width:20%;
    /* set any other properties, as desired, inside this class too */
}

</style> 

More Details:

1. My thoughts on HTML and CSS in Markdown

As far as I'm concerned, anything which can be written in a markdown document and get the desired result is all we are after, not some "pure markdown" syntax.

In C and C++, the compiler compiles down to assembly code, and the assembly is then assembled down to binary. Sometimes, however, you need the low-level control that only assembly can provide, and so you can write inline assembly right inside of a C or C++ source file. Assembly is the "lower level" language and it can be written right inside C and C++.

So it is with markdown. Markdown is the high-level language which is interpreted down to HTML and CSS. However, where we need extra control, we can just "inline" the lower-level HTML and CSS right inside of our markdown file, and it will still be interpreted correctly. In a sense, therefore, HTML and CSS are valid "markdown" syntax.

So, to center an image in markdown, use HTML and CSS.

2. Standard image insertion in markdown:

How to add a basic image in markdown with default "behind-the-scenes" HTML and CSS formatting:

This markdown:

![](https://i.stack.imgur.com/RJj4x.png)

Will produce this output:

This is my fire-shooting hexacopter I made.

You can also optionally add a description in the opening square brackets. Honestly I'm not even sure what that does, but perhaps it gets converted into an [HTML <img> element alt attribute][12], which gets displayed in case the image can't load, and may be read by screen readers for the blind. So, this markdown:

![this is my hexacopter I built](https://i.stack.imgur.com/RJj4x.png)

will also produce this output:

this is my hexacopter I built

3. More details on what's happening in the HTML/CSS when centering and resizing an image in markdown:

Centering the image in markdown requires that we use the extra control that HTML and CSS can give us directly. You can insert and center an individual image like this:

<img src="https://i.stack.imgur.com/RJj4x.png" 
     alt="this is my hexacopter I built" 
     style="display:block; 
            float:none; 
            margin-left:auto;
                  

css padding is not working in outlook

Do this instead:

<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
      <td bgcolor="#7d9aaa" width="40%" style="color: #ffffff; font-size:15px; font-family:Arial, Helvetica, sans-serif; font-weight: bold; padding:12px;">
        Order Confirmation
      </td>
      <td bgcolor="#7d9aaa" align="right" width="60%" style="color: #ffffff; font-size:15px; font-family:Arial, Helvetica, sans-serif; font-weight: bold; padding:12px;">
        Your Confirmation number is {{var order.increment_id}}
      </td>
  </tr>
</table>

It is better to use two cells and align the content, than using large padding and &nbsp;'s.

How to set downloading file name in ASP.NET Web API

You need to add the content-disposition header to the response:

 response.StatusCode = HttpStatusCode.OK;
 response.Content = new StreamContent(result);
 response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
 return response;

How to get the Android Emulator's IP address?

Like this:

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

Check the docs for more info: NetworkInterface.

Replacing NULL with 0 in a SQL server query

UPDATE TableName SET ColumnName= ISNULL(ColumnName, 0 ) WHERE Id = 10

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

I faced the same problem when import C++ Dll in .Net Framework +4, I unchecked Project->Properties->Build->Prefer 32-bit and it solved for me.

How do I use Assert to verify that an exception has been thrown?

This is going to depend on what test framework are you using?

In MbUnit, for example, you can specify the expected exception with an attribute to ensure that you are getting the exception you really expect.

[ExpectedException(typeof(ArgumentException))]

How do I set a textbox's text to bold at run time?

Here is an example for toggling bold, underline, and italics.

   protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
   {
      if ( ActiveControl is RichTextBox r )
      {
         if ( keyData == ( Keys.Control | Keys.B ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Bold ); // XOR will toggle
            return true;
         }
         if ( keyData == ( Keys.Control | Keys.U ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Underline ); // XOR will toggle
            return true;
         }
         if ( keyData == ( Keys.Control | Keys.I ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Italic ); // XOR will toggle
            return true;
         }
      }
      return base.ProcessCmdKey( ref msg, keyData );
   }

Check if a property exists in a class

I got this error: "Type does not contain a definition for GetProperty" when tying the accepted answer.

This is what i ended up with:

using System.Reflection;

if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{

}

How do I calculate a point on a circle’s circumference?

Calculating point around circumference of circle given distance travelled.
For comparison... This may be useful in Game AI when moving around a solid object in a direct path.

enter image description here

public static Point DestinationCoordinatesArc(Int32 startingPointX, Int32 startingPointY,
    Int32 circleOriginX, Int32 circleOriginY, float distanceToMove,
    ClockDirection clockDirection, float radius)
{
    // Note: distanceToMove and radius parameters are float type to avoid integer division
    // which will discard remainder

    var theta = (distanceToMove / radius) * (clockDirection == ClockDirection.Clockwise ? 1 : -1);
    var destinationX = circleOriginX + (startingPointX - circleOriginX) * Math.Cos(theta) - (startingPointY - circleOriginY) * Math.Sin(theta);
    var destinationY = circleOriginY + (startingPointX - circleOriginX) * Math.Sin(theta) + (startingPointY - circleOriginY) * Math.Cos(theta);

    // Round to avoid integer conversion truncation
    return new Point((Int32)Math.Round(destinationX), (Int32)Math.Round(destinationY));
}

/// <summary>
/// Possible clock directions.
/// </summary>
public enum ClockDirection
{
    [Description("Time moving forwards.")]
    Clockwise,
    [Description("Time moving moving backwards.")]
    CounterClockwise
}

private void ButtonArcDemo_Click(object sender, EventArgs e)
{
    Brush aBrush = (Brush)Brushes.Black;
    Graphics g = this.CreateGraphics();

    var startingPointX = 125;
    var startingPointY = 75;
    for (var count = 0; count < 62; count++)
    {
        var point = DestinationCoordinatesArc(
            startingPointX: startingPointX, startingPointY: startingPointY,
            circleOriginX: 75, circleOriginY: 75,
            distanceToMove: 5,
            clockDirection: ClockDirection.Clockwise, radius: 50);
        g.FillRectangle(aBrush, point.X, point.Y, 1, 1);

        startingPointX = point.X;
        startingPointY = point.Y;

        // Pause to visually observe/confirm clock direction
        System.Threading.Thread.Sleep(35);

        Debug.WriteLine($"DestinationCoordinatesArc({point.X}, {point.Y}");
    }
}

How do you check "if not null" with Eloquent?

Eloquent has a method for that (Laravel 4.*/5.*);

Model::whereNotNull('sent_at')

Laravel 3:

Model::where_not_null('sent_at')

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

Getting the parent of a directory in Bash

if for whatever reason you are interested in navigating up a specific number of directories you could also do: nth_path=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && cd ../../../ && pwd). This would give 3 parents directories up

Jquery get form field value

You can try these lines:

$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value

How can I position my div at the bottom of its container?

CodePen link here.

_x000D_
_x000D_
html, body {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.overlay {_x000D_
    min-height: 100%;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.container {_x000D_
    width: 900px;_x000D_
    position: relative;_x000D_
    padding-bottom: 50px;_x000D_
}_x000D_
_x000D_
.height {_x000D_
    width: 900px;_x000D_
    height: 50px;_x000D_
}_x000D_
_x000D_
.footer {_x000D_
    width: 900px;_x000D_
    height: 50px;_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
}
_x000D_
<div class="overlay">_x000D_
    <div class="container">_x000D_
        <div class="height">_x000D_
            content_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="footer">_x000D_
        footer_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

Just install and load Lodash:

import { capitalize } from "lodash";

capitalize('test') // Test

How to disassemble a memory range with GDB?

Do you only want to disassemble your actual main? If so try this:

(gdb) info line main 
(gdb) disas STARTADDRESS ENDADDRESS

Like so:

USER@MACHINE /cygdrive/c/prog/dsa
$ gcc-3.exe -g main.c

USER@MACHINE /cygdrive/c/prog/dsa
$ gdb a.exe
GNU gdb 6.8.0.20080328-cvs (cygwin-special)
...
(gdb) info line main
Line 3 of "main.c" starts at address 0x401050 <main> and ends at 0x401075 <main+
(gdb) disas 0x401050 0x401075
Dump of assembler code from 0x401050 to 0x401075:
0x00401050 <main+0>:    push   %ebp
0x00401051 <main+1>:    mov    %esp,%ebp
0x00401053 <main+3>:    sub    $0x18,%esp
0x00401056 <main+6>:    and    $0xfffffff0,%esp
0x00401059 <main+9>:    mov    $0x0,%eax
0x0040105e <main+14>:   add    $0xf,%eax
0x00401061 <main+17>:   add    $0xf,%eax
0x00401064 <main+20>:   shr    $0x4,%eax
0x00401067 <main+23>:   shl    $0x4,%eax
0x0040106a <main+26>:   mov    %eax,-0xc(%ebp)
0x0040106d <main+29>:   mov    -0xc(%ebp),%eax
0x00401070 <main+32>:   call   0x4010c4 <_alloca>
End of assembler dump.

I don't see your system interrupt call however. (its been a while since I last tried to make a system call in assembly. INT 21h though, last I recall

Server Client send/receive simple text

   public partial class Form1 : Form
    {
        private Thread n_server;
        private Thread n_client;
        private Thread n_send_server;
        private TcpClient client;
        private TcpListener listener;
        private int port = 2222;
        private string IP = " ";
        private Socket socket;
        byte[] bufferReceive = new byte[4096];
        byte[] bufferSend = new byte[4096];
        public Form1()
        {
            InitializeComponent();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        public void Server()
        {
            listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            try
            {
                socket = listener.AcceptSocket();
                if (socket.Connected)
                {
                    textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Client        : " + socket.RemoteEndPoint.ToString(); });
                }
                while (true)
                {
                    int length = socket.Receive(bufferReceive);
                    if (length > 0)
                    {
                        label2.Invoke((MethodInvoker)delegate { label2.Text = Encoding.Unicode.GetString(bufferReceive); });
                    }
                }
            }
            catch
            {
            }
        }

        public void Client()
        {
            IP = "localhost";
            client = new TcpClient();
            try
            {
                client.Connect(IP, port);
                while (true)
                {
                    NetworkStream nts = client.GetStream();
                    int length;
                    while ((length = nts.Read(bufferReceive, 0, bufferReceive.Length)) != 0)
                    {
                       label3.Invoke((MethodInvoker)delegate { label3.Text = Encoding.Unicode.GetString(bufferReceive); });
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

            if (client.Connected)
            {
                textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            n_server = new Thread(new ThreadStart(Server));
            n_server.IsBackground = true;
            n_server.Start();
            textBox1.Text = "Server up";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            n_client = new Thread(new ThreadStart(Client));
            n_client.IsBackground = true;
            n_client.Start();
        }

        private void send()
        {
            if (socket!=null)
            {
                bufferSend = Encoding.Unicode.GetBytes(textBox2.Text);
                socket.Send(bufferSend);
            }
            else
            {
                if (client.Connected)
                {
                    bufferSend = Encoding.Unicode.GetBytes(textBox3.Text);
                    NetworkStream nts = client.GetStream();
                    if (nts.CanWrite)
                    {
                        nts.Write(bufferSend,0,bufferSend.Length);
                    }

                }
            }
        }



        private void button3_Click(object sender, EventArgs e)
        {
            n_send_server = new Thread(new ThreadStart(send));
            n_send_server.IsBackground = true;
            n_send_server.Start();
        }
    }

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

In Visual Studio 2010 the key sequence CTRL+E, S will also toggle display of whitespace characters.

Padding a table row

You could simply add this style to the table.

table {
    border-spacing: 15px;
}

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

Firefox and SSL: sec_error_unknown_issuer

I know this thread is a little old but we ran into this too and will archive our eventual solution here for others.

We had the same problem with a Comodo wildcard "positive ssl" cert. We are running our website using a squid-reverse SSL proxy and Firefox would keep complaining "sec_error_unknown_issuer" as you stated, yet every other browser was OK.

I found that this is a problem of the certificate chain being incomplete. Firefox apparently does not have one of the intermediary certificates build in, though Firefox does trust the root CA. Therefore you have to provide the whole chain of certificates to Firefox. Comodo's support states:

An intermediate certificate is the certificate, or certificates, that go between your site (server) certificate and a root certificate. The intermediate certificate, or certificates, completes the chain to a root certificate trusted by the browser.

Using an intermediate certificate means that you must complete an additional step in the installation process to enable your site certificate to be chained to the trusted root, and not show errors in the browser when someone visits your web site.

This was already touched on earlier in this thread but it did not resove how you do this.

First you have to make a chained certificate bundle and you do that by using your favorite text editor and just paste them in, in the correct (reverse) order i.e.

  • Intermediate CA Certificate 2 - IntermediateCA2.crt - on top of the file
  • Intermediate CA Certificate 1 - IntermediateCA1.crt
  • Root CA Certificate - root.crt - at the end of the file

The exact order you can get from your ssl provider if its not obvious from the names.

Then save the file as whatever name you like. E.g. yourdomain-chain-bundle.crt

In this example I have not included the actual domain certificate and as long as your server can be configured to take a separate chained certificate bundle this is what you use.

More data can be found here:

https://support.comodo.com/index.php?/Knowledgebase/Article/View/643/0/how-do-i-make-my-own-bundle-file-from-crt-files

If for some reason you can't configure your server to use a separate chained bundle, then you just paste your server certificate in the beginning (on the top) of the bundle and use the resulting file as your server cert. This is what needs to be done in the E.g Squid case. See below from the squid mailing list on this subject.

http://www.squid-cache.org/mail-archive/squid-users/201109/0037.html

This resolved it for us.

What's the difference between fill_parent and wrap_content?

Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.

fill_parent (deprecated and renamed MATCH_PARENT in API Level 8 and higher)

Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dockstyle of a Windows Form Control to Fill.

Setting a top level layout or control to fill_parent will force it to take up the whole screen.

wrap_content

Setting a View's size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.

It's roughly the equivalent of setting a Windows Form Control's Autosize property to True.

Online Documentation

There's some details in the Android code documentation here.

Proper way to concatenate variable strings

As simple as joining lists in python itself.

ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost

localhost | SUCCESS => {
  "msg": "list-joined-together" }

Works the same way using variables:

ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost

Git merge with force overwrite

This merge approach will add one commit on top of master which pastes in whatever is in feature, without complaining about conflicts or other crap.

enter image description here

Before you touch anything

git stash
git status # if anything shows up here, move it to your desktop

Now prepare master

git checkout master
git pull # if there is a problem in this step, it is outside the scope of this answer

Get feature all dressed up

git checkout feature
git merge --strategy=ours master

Go for the kill

git checkout master
git merge --no-ff feature

What is Android's file system?

When analysing a Galaxy Ace 2.2 in a hex editor. The hex seemed to point to the device using FAT16 as its file system. I thought this unusual. However Fat 16 is compatible with the Linux kernel.

Seaborn Barplot - Displaying Values

A simple way to do so is to add the below code (for Seaborn):

for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points') 

Example :

splot = sns.barplot(df['X'], df['Y'])
# Annotate the bars in plot
for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points')    
plt.show()

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}

or

${string:(-3)}

(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:

${parameter:offset}
${parameter:offset:length}

Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:

${string:${#string}<3?0:-3}

This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.


Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

I know I told babay in 2012 that I thought it was unlikely that someone wouldn't realize that they weren't on a branch and commit. This just happened to me, so I guess I have to admit that I was wrong, but considering that it took until 2016 for this to happen to me, you could argue that it is in fact unlikely.

Anyway, creating a new branch is overkill in my opinion. All you have to do is:

git checkout some-branch
git merge commit-sha

If you didn't copy the commit-sha before checking out the other branch, you can easily find it by running:

git reflog

MySQL: View with Subquery in the FROM Clause Limitation

I had the same problem. I wanted to create a view to show information of the most recent year, from a table with records from 2009 to 2011. Here's the original query:

SELECT a.* 
FROM a 
JOIN ( 
  SELECT a.alias, MAX(a.year) as max_year 
  FROM a 
  GROUP BY a.alias
) b 
ON a.alias=b.alias and a.year=b.max_year

Outline of solution:

  1. create a view for each subquery
  2. replace subqueries with those views

Here's the solution query:

CREATE VIEW v_max_year AS 
  SELECT alias, MAX(year) as max_year 
  FROM a 
  GROUP BY a.alias;

CREATE VIEW v_latest_info AS 
  SELECT a.* 
  FROM a 
  JOIN v_max_year b 
  ON a.alias=b.alias and a.year=b.max_year;

It works fine on mysql 5.0.45, without much of a speed penalty (compared to executing the original sub-query select without any views).

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

I followed @Viktor Kerkez's answer and have had mixed success. I found that sometimes this recipe of

conda skeleton pypi PACKAGE

conda build PACKAGE

would look like everything worked but I could not successfully import PACKAGE. Recently I asked about this on the Anaconda user group and heard from @Travis Oliphant himself on the best way to use conda to build and manage packages that do not ship with Anaconda. You can read this thread here, but I'll describe the approach below to hopefully make the answers to the OP's question more complete...

Example: I am going to install the excellent prettyplotlib package on Windows using conda 2.2.5.

1a) conda build --build-recipe prettyplotlib

You'll see the build messages all look good until the final TEST section of the build. I saw this error

File "C:\Anaconda\conda-bld\test-tmp_dir\run_test.py", line 23 import None SyntaxError: cannot assign to None TESTS FAILED: prettyplotlib-0.1.3-py27_0

1b) Go into /conda-recipes/prettyplotlib and edit the meta.yaml file. Presently, the packages being set up like in step 1a result in yaml files that have an error in the test section. For example, here is how mine looked for prettyplotlib

test:   # Python imports   imports:
    - 
    - prettyplotlib
    - prettyplotlib

Edit this section to remove the blank line preceded by the - and also remove the redundant prettyplotlib line. At the time of this writing I have found that I need to edit most meta.yaml files like this for external packages I am installing with conda, meaning that there is a blank import line causing the error along with a redundant import of the given package.

1c) Rerun the command from 1a, which should complete with out error this time. At the end of the build you'll be asked if you want to upload the build to binstar. I entered No and then saw this message:

If you want to upload this package to binstar.org later, type:

$ binstar upload C:\Anaconda\conda-bld\win-64\prettyplotlib-0.1.3-py27_0.tar.bz2

That tar.bz2 file is the build that you now need to actually install.

2) conda install C:\Anaconda\conda-bld\win-64\prettyplotlib-0.1.3-py27_0.tar.bz2

Following these steps I have successfully used conda to install a number of packages that do not come with Anaconda. Previously, I had installed some of these using pip, so I did pip uninstall PACKAGE prior to installing PACKAGE with conda. Using conda, I can now manage (almost) all of my packages with a single approach rather than having a mix of stuff installed with conda, pip, easy_install, and python setup.py install.

For context, I think this recent blog post by @Travis Oliphant will be helpful for people like me who do not appreciate everything that goes into robust Python packaging but certainly appreciate when stuff "just works". conda seems like a great way forward...

How do I replace all the spaces with %20 in C#?

I found useful System.Web.HttpUtility.UrlPathEncode(string str);

It replaces spaces with %20 and not with +.

Python:Efficient way to check if dictionary is empty or not

I would say that way is more pythonic and fits on line:

If you need to check value only with the use of your function:

if filter( your_function, dictionary.values() ): ...

When you need to know if your dict contains any keys:

if dictionary: ...

Anyway, using loops here is not Python-way.

How to make a cross-module variable?

I wondered if it would be possible to avoid some of the disadvantages of using global variables (see e.g. http://wiki.c2.com/?GlobalVariablesAreBad) by using a class namespace rather than a global/module namespace to pass values of variables. The following code indicates that the two methods are essentially identical. There is a slight advantage in using class namespaces as explained below.

The following code fragments also show that attributes or variables may be dynamically created and deleted in both global/module namespaces and class namespaces.

wall.py

# Note no definition of global variables

class router:
    """ Empty class """

I call this module 'wall' since it is used to bounce variables off of. It will act as a space to temporarily define global variables and class-wide attributes of the empty class 'router'.

source.py

import wall
def sourcefn():
    msg = 'Hello world!'
    wall.msg = msg
    wall.router.msg = msg

This module imports wall and defines a single function sourcefn which defines a message and emits it by two different mechanisms, one via globals and one via the router function. Note that the variables wall.msg and wall.router.message are defined here for the first time in their respective namespaces.

dest.py

import wall
def destfn():

    if hasattr(wall, 'msg'):
        print 'global: ' + wall.msg
        del wall.msg
    else:
        print 'global: ' + 'no message'

    if hasattr(wall.router, 'msg'):
        print 'router: ' + wall.router.msg
        del wall.router.msg
    else:
        print 'router: ' + 'no message'

This module defines a function destfn which uses the two different mechanisms to receive the messages emitted by source. It allows for the possibility that the variable 'msg' may not exist. destfn also deletes the variables once they have been displayed.

main.py

import source, dest

source.sourcefn()

dest.destfn() # variables deleted after this call
dest.destfn()

This module calls the previously defined functions in sequence. After the first call to dest.destfn the variables wall.msg and wall.router.msg no longer exist.

The output from the program is:

global: Hello world!
router: Hello world!
global: no message
router: no message

The above code fragments show that the module/global and the class/class variable mechanisms are essentially identical.

If a lot of variables are to be shared, namespace pollution can be managed either by using several wall-type modules, e.g. wall1, wall2 etc. or by defining several router-type classes in a single file. The latter is slightly tidier, so perhaps represents a marginal advantage for use of the class-variable mechanism.

Class not registered Error

In 64 bit windows machines the COM components need to register itself in HKEY_CLASSES_ROOT\CLSID (64 bit component) OR HKEY_CLASSES_ROOT\Wow6432Node\CLSID (32 bit component) . If your application is a 32 bit application running on 64-bit machine the COM library would typically look for the GUID under Wow64 node and if your application is a 64 bit application, the COM library would try to load from HKEY_CLASSES_ROOT\CLSID. Make sure you are targeting the correct platform and ensure you have installed the correct version of library(32/64 bit).

How to default to other directory instead of home directory

This may help you.

image description

  1. Right click on git bash -> properties
  2. In Shorcut tab -> Start in field -> enter your user defined path
  3. Make sure the Target field does not include --go-to-home or it will continue to start in the directory specified in your HOME variable

Thats it.

jQuery check if <input> exists and has a value

I would do something like this: $('input[value]').something . This finds all inputs that have value and operates something onto them.

How do I get values from a SQL database into textboxes using C#?

Make a connection and open it.

con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<database_name>)));User Id =<userid>; Password =<password>");
con.Open();

Write the select query:

string sql = "select * from Pending_Tasks";

Create a command object:

OracleCommand cmd = new OracleCommand(sql, con);

Execute the command and put the result in a object to read it.

OracleDataReader r = cmd.ExecuteReader();

now start reading from it.

while (read.Read())
{
 CustID.Text = (read["Customer_ID"].ToString());
 CustName.Text = (read["Customer_Name"].ToString());
 Add1.Text = (read["Address_1"].ToString());
 Add2.Text = (read["Address_2"].ToString());
 PostBox.Text = (read["Postcode"].ToString());
 PassBox.Text = (read["Password"].ToString());
 DatBox.Text = (read["Data_Important"].ToString());
 LanNumb.Text = (read["Landline"].ToString());
 MobNumber.Text = (read["Mobile"].ToString());
 FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();

Add this too using Oracle.ManagedDataAccess.Client;

What are some great online database modeling tools?

I've used DBDesigner before. It is an open source tool. You might check that out. Not sure if it fits your needs.

Best of luck!

SQL Server using wildcard within IN

This might me the most simple solution use like any

select *
from jobdetails
where job_no like any ('0711%', '0712%')

In Teradata this works fine.

Is there a way to create interfaces in ES6 / Node 4?

Interfaces are not part of the ES6 but classes are.

If you really need them, you should look at TypeScript which support them.

how to drop database in sqlite?

You can drop tables by issuing an SQL Command as you would normally. If you want to drop the whole database you'll have to delete the file. You can delete the file located under

data/data/com.your.app.name/database/[databasefilename]

you can do this from the eclipse view called "FileBrowser" out of the "Android" Category for example. Or directly on your emulator or phone.

How do you import classes in JSP?

FYI - if you are importing a List into a JSP, chances are pretty good that you are violating MVC principles. Take a few hours now to read up on the MVC approach to web app development (including use of taglibs) - do some more googling on the subject, it's fascinating and will definitely help you write better apps.

If you are doing anything more complicated than a single JSP displaying some database results, please consider using a framework like Spring, Grails, etc... It will absolutely take you a bit more effort to get going, but it will save you so much time and effort down the road that I really recommend it. Besides, it's cool stuff :-)

Lightweight workflow engine for Java

CamundaBPM is one option. You can check here: https://camunda.com/

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1 https://github.com/user/repo.git

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git

Iterating each character in a string using Python

Several answers here use range. xrange is generally better as it returns a generator, rather than a fully-instantiated list. Where memory and or iterables of widely-varying lengths can be an issue, xrange is superior.

Transpose a data frame

df.aree <- as.data.frame(t(df.aree))
colnames(df.aree) <- df.aree[1, ]
df.aree <- df.aree[-1, ]
df.aree$myfactor <- factor(row.names(df.aree))

Is there any way to debug chrome in any IOS device

Old Answer (July 2016):

You can't directly debug Chrome for iOS due to restrictions on the published WKWebView apps, but there are a few options already discussed in other SO threads:

  1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

  2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

  3. You could try and create a simple WKWebView browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

Truncating all tables in a Postgres database

If I have to do this, I will simply create a schema sql of current db, then drop & create db, then load db with schema sql.

Below are the steps involved:

1) Create Schema dump of database (--schema-only)

pg_dump mydb -s > schema.sql

2) Drop database

drop database mydb;

3) Create Database

create database mydb;

4) Import Schema

psql mydb < schema.sql

How to get elements with multiple classes

actually @bazzlebrush 's answer and @filoxo 's comment helped me a lot.

I needed to find the elements where the class could be "zA yO" OR "zA zE"

Using jquery I first select the parent of the desired elements:

(a div with class starting with 'abc' and style != 'display:none')

var tom = $('div[class^="abc"][style!="display: none;"]')[0];                   

then the desired children of that element:

var ax = tom.querySelectorAll('.zA.yO, .zA.zE');

works perfectly! note you don't have to do document.querySelector you can as above pass in a pre-selected object.

How do I execute a file in Cygwin?

To execute a file in the current directory, the syntax to use is: ./foo

As mentioned by allain, ./a.exe is the correct way to execute a.exe in the working directory using Cygwin.

Note: You may wish to use the -o parameter to cc to specify your own output filename. An example of this would be: cc helloworld.c -o helloworld.exe.

static linking only some libraries

gcc objectfiles -o program -Wl,-Bstatic -ls1 -ls2 -Wl,-Bdynamic -ld1 -ld2

you can also use: -static-libgcc -static-libstdc++ flags for gcc libraries

keep in mind that if libs1.so and libs1.a both exists, the linker will pick libs1.so if it's before -Wl,-Bstatic or after -Wl,-Bdynamic. Don't forget to pass -L/libs1-library-location/ before calling -ls1.

how to pass value from one php page to another using session

Use something like this:

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

Any other PHP page:

<?php
session_start();
echo $_SESSION['myValue'];
?>

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}

Angular 2 - Setting selected value on dropdown list

This works for me.

<select formControlName="preferredBankAccountId" class="form-control" value="">
    <option value="">Please select</option>    
    <option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >{{item.nickName}}</option>
</select>

Not sure this is valid or not, correct me if it's wrong.
Correct me if this should not be like this.

force Maven to copy dependencies into target/lib

mvn install dependency:copy-dependencies 

Works for me with dependencies directory created in target folder. Like it!

How to Maximize window in chrome using webDriver (python)

Try

ChromeOptions options = new ChromeOptions();
options.addArguments("--start-fullscreen");

How can I use goto in Javascript?

Actually, I see that ECMAScript (JavaScript) DOES INDEED have a goto statement. However, the JavaScript goto has two flavors!

The two JavaScript flavors of goto are called labeled continue and labeled break. There is no keyword "goto" in JavaScript. The goto is accomplished in JavaScript using the break and continue keywords.

And this is more or less explicitly stated on the w3schools website here http://www.w3schools.com/js/js_switch.asp.

I find the documentation of the labeled continue and labeled break somewhat awkwardly expressed.

The difference between the labeled continue and labeled break is where they may be used. The labeled continue can only be used inside a while loop. See w3schools for some more information.

===========

Another approach that will work is to have a giant while statement with a giant switch statement inside:

while (true)
{
    switch (goto_variable)
    {
        case 1:
            // some code
            goto_variable = 2
            break;
        case 2:
            goto_variable = 5   // case in etc. below
            break;
        case 3:
            goto_variable = 1
            break;

         etc. ...
    }

}

Swift: Convert enum value to String?

It couldn't get simpler than this in Swift 2 and the latest Xcode 7 (no need to specify enum type, or .rawValue, descriptors etc...)

Updated for Swift 3 and Xcode 8:

    enum Audience {
        case Public
        case Friends
        case Private
    }

    let audience: Audience = .Public  // or, let audience = Audience.Public
    print(audience) // "Public"

How to use MySQLdb with Python and Django in OSX 10.6?

mysql_config must be on the path. On Mac, do

export PATH=$PATH:/usr/local/mysql/bin/
pip install MySQL-python

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

How to compare two double values in Java?

Instead of using doubles for decimal arithemetic, please use java.math.BigDecimal. It would produce the expected results.

For reference take a look at this stackoverflow question

MySQL Update Column +1?

update TABLENAME
set COLUMNNAME = COLUMNNAME + 1
where id = 'YOURID'

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

For a one-page web application where I add scrollable sections dynamically, I trigger OSX's scrollbars by programmatically scrolling one pixel down and back up:

// Plain JS:
var el = document.getElementById('scrollable-section');
el.scrollTop = 1;
el.scrollTop = 0;

// jQuery:
$('#scrollable-section').scrollTop(1).scrollTop(0);

This triggers the visual cue fading in and out.

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

_x000D_
_x000D_
function textbox()_x000D_
{_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
_x000D_
_x000D_

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

Instead, you could git CtrlZ and retry the commit but this time add " -m " with a message in quotes after it, then it will commit without prompting you with that page.

HttpURLConnection timeout settings

If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period

public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
    AsyncTask<Params, Progress, Result> {

private static final int HTTP_REQUEST_TIMEOUT = 30000;

@Override
protected Result doInBackground(Params... params) {
    createTimeoutListener();
    return doInBackgroundImpl(params);
}

private void createTimeoutListener() {
    Thread timeout = new Thread() {
        public void run() {
            Looper.prepare();

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    if (AsyncTaskWithTimer.this != null
                            && AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
                        AsyncTaskWithTimer.this.cancel(true);
                    handler.removeCallbacks(this);
                    Looper.myLooper().quit();
                }
            }, HTTP_REQUEST_TIMEOUT);

            Looper.loop();
        }
    };
    timeout.start();
}

abstract protected Result doInBackgroundImpl(Params... params);
}

A Sample for this

public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {

    @Override
    protected void onCancelled(Void void) {
        Log.d(TAG, "Async Task onCancelled With Result");
        super.onCancelled(result);
    }

    @Override
    protected void onCancelled() {
        Log.d(TAG, "Async Task onCancelled");
        super.onCancelled();
    }

    @Override
    protected Void doInBackgroundImpl(Void... params) {
        // Do background work
        return null;
    };
 }

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

pip installing in global site-packages instead of virtualenv

I stumbled upon the same problem running Manjaro. I created the virtual environment using python3 -m ven venv and then activated using source venv/bin/actiave. which python and which pip both pointed towards the correct binaries in the virtualenv, however I was not able to install to the virtualenv, even when using the full path of the binaries. Turned out that when I uninstalled the python-pip package with sudo pacman -R python-pip python-reportlab (had to include reportlab to satisfy dependencies) everything started to work as expected. Not sure why, but this is probably due to a double install where the system package is taking precedence.

print memory address of Python variable

id is the method you want to use: to convert it to hex:

hex(id(variable_here))

For instance:

x = 4
print hex(id(x))

Gave me:

0x9cf10c

Which is what you want, right?

(Fun fact, binding two variables to the same int may result in the same memory address being used.)
Try:

x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))

This gave me identical pairs, even for the large integers.

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

what innerHTML is doing in javascript?

The innerHTML property is part of the Document Object Model (DOM) that allows Javascript code to manipulate a website being displayed. Specifically, it allows reading and replacing everything within a given DOM element (HTML tag).

However, DOM manipulations using innerHTML are slower and more failure-prone than manipulations based on individual DOM objects.

How to delete directory content in Java?

Use FileUtils with FileUtils.deleteDirectory();

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

What does ON [PRIMARY] mean?

To add a very important note on what Mark S. has mentioned in his post. In the specific SQL Script that has been mentioned in the question you can NEVER mention two different file groups for storing your data rows and the index data structure.

The reason why is due to the fact that the index being created in this case is a clustered Index on your primary key column. The clustered index data and the data rows of your table can NEVER be on different file groups.

So in case you have two file groups on your database e.g. PRIMARY and SECONDARY then below mentioned script will store your row data and clustered index data both on PRIMARY file group itself even though I've mentioned a different file group ([SECONDARY]) for the table data. More interestingly the script runs successfully as well (when I was expecting it to give an error as I had given two different file groups :P). SQL Server does the trick behind the scene silently and smartly.

CREATE TABLE [dbo].[be_Categories](
    [CategoryID] [uniqueidentifier] ROWGUIDCOL  NOT NULL CONSTRAINT [DF_be_Categories_CategoryID]  DEFAULT (newid()),
    [CategoryName] [nvarchar](50) NULL,
    [Description] [nvarchar](200) NULL,
    [ParentID] [uniqueidentifier] NULL,
 CONSTRAINT [PK_be_Categories] PRIMARY KEY CLUSTERED 
(
    [CategoryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [SECONDARY]
GO

NOTE: Your index can reside on a different file group ONLY if the index being created is non-clustered in nature.

The below script which creates a non-clustered index will get created on [SECONDARY] file group instead when the table data already resides on [PRIMARY] file group:

CREATE NONCLUSTERED INDEX [IX_Categories] ON [dbo].[be_Categories]
(
    [CategoryName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Secondary]
GO

You can get more information on how storing non-clustered indexes on a different file group can help your queries perform better. Here is one such link.

How do I get a file's last modified time in Perl?

You need the stat call, and the file name:

my $last_mod_time = (stat ($file))[9];

Perl also has a different version:

my $last_mod_time = -M $file;

but that value is relative to when the program started. This is useful for things like sorting, but you probably want the first version.

Difference between Activity and FragmentActivity

FragmentActivity is part of the support library, while Activity is the framework's default class. They are functionally equivalent.

You should always use FragmentActivity and android.support.v4.app.Fragment instead of the platform default Activity and android.app.Fragment classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.

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

If all else fails, Ctrl-H (search and replace) with "=" in both boxes (in other words, search on = and replace it with the same =). Seems to do the trick.

Format Date/Time in XAML in Silverlight

In SL5 I found this to work:

<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat=dd-MMMM-yy hh:mm}">
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat='Justification Date: \{0:dd-MMMM-yy hh:mm\}'}">

Why do Sublime Text 3 Themes not affect the sidebar?

The most recent version of Sublime has fixed this issue, click on Preferences, click on Theme select Adaptive.sublime-theme. This will change the sidebar to a dark colored background.

Removing page title and date when printing web page (with CSS?)

Its simple. Just use css.

<style>
@page { size: auto;  margin: 0mm; }
</style>

Should URL be case sensitive?

Depends on the hosting os. Sites that are hosted on Windows tend to be case insensitive as the underlying file system is case insensitive. Sites hosted on Unix type systems tend to be case sensitive as their underlying file systems are typically case sensitive. The host name part of the URL is always case insensitive, it's the rest of the path that varies.

Transactions in .net

You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.

opening html from google drive

I don't think it is necessary to "host" the content using the way from the accepted answer. It is too complicated for a normal user with limited developing skills.

Google actually has provided hosting feature without using Drive SDK/API, what you need is just few clicks. Check this out:

http://support.google.com/drive/bin/answer.py?hl=en&answer=2881970

It is the same to the answer of user1557669. However, in step 4, the URL is not correct, it is like:

https://drive.google.com/#folders/...

To get the correct host URL. Right click on the html file (you have to finish 1-3 steps first and put the html in the public shared folder), and select "Details" from the context menu. You will find the hosting URL right close to the bottom of the details panel. It should look like:

https://googledrive.com/host/.../abc.html

Then you can share the link to anyone. Happy sharing.

ArrayList - How to modify a member of an object?

Fixed. I was wrong: this only applies on element reassignment. I thought that the returned object wasn't referencing the new one.

It can be done.

Q: Why?
A: The get() method returns an object referencing the original one.

So, if you write myArrayList.get(15).itsVariable = 7
or
myArrayList.get(15).myMethod("My Value"),
you are actually assigning a value / using a method from the object referenced by the returned one (this means, the change is applied to the original object)

The only thing you can't do is myArrayList.get(15) = myNewElement. To do this you have to use list.set() method.

Share data between AngularJS controllers

A simple solution is to have your factory return an object and let your controllers work with a reference to the same object:

JS:

// declare the app with no dependencies
var myApp = angular.module('myApp', []);

// Create the factory that share the Fact
myApp.factory('Fact', function(){
  return { Field: '' };
});

// Two controllers sharing an object that has a string in it
myApp.controller('FirstCtrl', function( $scope, Fact ){
  $scope.Alpha = Fact;
});

myApp.controller('SecondCtrl', function( $scope, Fact ){
  $scope.Beta = Fact;
});

HTML:

<div ng-controller="FirstCtrl">
    <input type="text" ng-model="Alpha.Field">
    First {{Alpha.Field}}
</div>

<div ng-controller="SecondCtrl">
<input type="text" ng-model="Beta.Field">
    Second {{Beta.Field}}
</div>

Demo: http://jsfiddle.net/HEdJF/

When applications get larger, more complex and harder to test you might not want to expose the entire object from the factory this way, but instead give limited access for example via getters and setters:

myApp.factory('Data', function () {

    var data = {
        FirstName: ''
    };

    return {
        getFirstName: function () {
            return data.FirstName;
        },
        setFirstName: function (firstName) {
            data.FirstName = firstName;
        }
    };
});

With this approach it is up to the consuming controllers to update the factory with new values, and to watch for changes to get them:

myApp.controller('FirstCtrl', function ($scope, Data) {

    $scope.firstName = '';

    $scope.$watch('firstName', function (newValue, oldValue) {
        if (newValue !== oldValue) Data.setFirstName(newValue);
    });
});

myApp.controller('SecondCtrl', function ($scope, Data) {

    $scope.$watch(function () { return Data.getFirstName(); }, function (newValue, oldValue) {
        if (newValue !== oldValue) $scope.firstName = newValue;
    });
});

HTML:

<div ng-controller="FirstCtrl">
  <input type="text" ng-model="firstName">
  <br>Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
  Input should also be here: {{firstName}}
</div>

Demo: http://jsfiddle.net/27mk1n1o/

How do I get the current timezone name in Postgres 9.3?

This may or may not help you address your problem, OP, but to get the timezone of the current server relative to UTC (UT1, technically), do:

SELECT EXTRACT(TIMEZONE FROM now())/3600.0;

The above works by extracting the UT1-relative offset in minutes, and then converting it to hours using the factor of 3600 secs/hour.

Example:

SET SESSION timezone TO 'Asia/Kabul';
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
-- output: 4.5 (as of the writing of this post)

(docs).

How to make an introduction page with Doxygen

Following syntax may help for adding a main page and related subpages for doxygen:

/*! \mainpage Drawing Shapes
 *
 * This project helps user to draw shapes.
 * Currently two types of shapes can be drawn:
 * - \subpage drawingRectanglePage "How to draw rectangle?"
 *
 * - \subpage drawingCirclePage "How to draw circle?"
 *
 */ 

/*! \page drawingRectanglePage How to draw rectangle?
 *
 * Lorem ipsum dolor sit amet
 *
 */

/*! \page drawingCirclePage How to draw circle?
 *
 * This page is about how to draw a circle.
 * Following sections describe circle:
 * - \ref groupCircleDefinition "Definition of Circle"
 * - \ref groupCircleClass "Circle Class"
 */

Creating groups as following also help for designing pages:

/** \defgroup groupCircleDefinition Circle Definition
 * A circle is a simple shape in Euclidean geometry.
 * It is the set of all points in a plane that are at a given distance from a given point, the centre;
 * equivalently it is the curve traced out by a point that moves so that its distance from a given point is constant.
 * The distance between any of the points and the centre is called the radius.
 */

An example can be found here

await vs Task.Wait - Deadlock?

Wait and await - while similar conceptually - are actually completely different.

Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. As a general rule, you should use "async all the way down"; that is, don't block on async code. On my blog, I go into the details of how blocking in asynchronous code causes deadlock.

await will asynchronously wait until the task completes. This means the current method is "paused" (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation.

You also mentioned a "cooperative block", by which I assume you mean a task that you're Waiting on may execute on the waiting thread. There are situations where this can happen, but it's an optimization. There are many situations where it can't happen, like if the task is for another scheduler, or if it's already started or if it's a non-code task (such as in your code example: Wait cannot execute the Delay task inline because there's no code for it).

You may find my async / await intro helpful.

TypeScript Objects as Dictionary types as in C#

Lodash has a simple Dictionary implementation and has good TypeScript support

Install Lodash:

npm install lodash @types/lodash --save

Import and usage:

import { Dictionary } from "lodash";
let properties : Dictionary<string> = {
    "key": "value"        
}
console.log(properties["key"])

How to send redirect to JSP page in Servlet

    String u = request.getParameter("username");
    String p = request.getParameter("password");

    try {
        st = con.createStatement();
        String sql;
        sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
                + p + "'";
        ResultSet rs = st.executeQuery(sql);
        if (rs.next()) {
            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/home.jsp");
            requestDispatcher.forward(request, response);
        } else {

            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/invalidLogin.jsp");
            requestDispatcher.forward(request, response);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    finally{
        try {
            rs.close();
            ps.close();
            con.close();
            st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

UPDATE multiple tables in MySQL using LEFT JOIN

Table A 
+--------+-----------+
| A-num  | text      | 
|    1   |           |
|    2   |           |
|    3   |           |
|    4   |           |
|    5   |           |
+--------+-----------+

Table B
+------+------+--------------+
| B-num|  date        |  A-num | 
|  22  |  01.08.2003  |     2  |
|  23  |  02.08.2003  |     2  | 
|  24  |  03.08.2003  |     1  |
|  25  |  04.08.2003  |     4  |
|  26  |  05.03.2003  |     4  |

I will update field text in table A with

UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from                                           
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`

and come to this result:

Table A 
+--------+------------------------+
| A-num  | text                   | 
|    1   |  24 from 03 08 2003 /  |
|    2   |  22 from 01 08 2003 /  |       
|    3   |                        |
|    4   |  25 from 04 08 2003 /  |
|    5   |                        |
--------+-------------------------+

where only one field from Table B is accepted, but I will come to this result:

Table A 
+--------+--------------------------------------------+
| A-num  | text                                       | 
|    1   |  24 from 03 08 2003                        |
|    2   |  22 from 01 08 2003 / 23 from 02 08 2003 / |       
|    3   |                                            |
|    4   |  25 from 04 08 2003 / 26 from 05 03 2003 / |
|    5   |                                            |
+--------+--------------------------------------------+

Best Timer for using in a Windows service

Don't use a service for this. Create a normal application and create a scheduled task to run it.

This is the commonly held best practice. Jon Galloway agrees with me. Or maybe its the other way around. Either way, the fact is that it is not best practices to create a windows service to perform an intermittent task run off a timer.

"If you're writing a Windows Service that runs a timer, you should re-evaluate your solution."

–Jon Galloway, ASP.NET MVC community program manager, author, part time superhero

How do you change the launcher logo of an app in Android Studio?

In the manifest file, under the tag, there will be a similar line:

android:icon="drawable_resource_path"

Place the launcher icon you want in drawable folder and write its resource path.

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

How to get size of mysql database?

Run this query and you'll probably get what you're looking for:

SELECT table_schema "DB Name",
        ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" 
FROM information_schema.tables 
GROUP BY table_schema; 

This query comes from the mysql forums, where there are more comprehensive instructions available.

The entity type <type> is not part of the model for the current context

map of the entity (even an empty one) added to the configuration will lead to having the entity type be part of the context. We had an entity with no relationship to other entities that was fixed with an empty map.

React Native Border Radius with background color

Never give borderRadius to your <Text /> always wrap that <Text /> inside your <View /> or in your <TouchableOpacity/>.

borderRadius on <Text /> will work perfectly on Android devices. But on IOS devices it won't work.

So keep this in your practice to wrap your <Text/> inside your <View/> or on <TouchableOpacity/> and then give the borderRadius to that <View /> or <TouchableOpacity /> so that it will work on both Android as well as on IOS devices.

For example:-

<TouchableOpacity style={{borderRadius: 15}}>
   <Text>Button Text</Text>
</TouchableOpacity>

-Thanks

Using sed and grep/egrep to search and replace

Use this command:

egrep -lRZ "\.jpg|\.png|\.gif" . \
    | xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
  • egrep: find matching lines using extended regular expressions

    • -l: only list matching filenames

    • -R: search recursively through all given directories

    • -Z: use \0 as record separator

    • "\.jpg|\.png|\.gif": match one of the strings ".jpg", ".gif" or ".png"

    • .: start the search in the current directory

  • xargs: execute a command with the stdin as argument

    • -0: use \0 as record separator. This is important to match the -Z of egrep and to avoid being fooled by spaces and newlines in input filenames.

    • -l: use one line per command as parameter

  • sed: the stream editor

    • -i: replace the input file with the output without making a backup

    • -e: use the following argument as expression

    • 's/\.jpg\|\.gif\|\.png/.bmp/g': replace all occurrences of the strings ".jpg", ".gif" or ".png" with ".bmp"

Eliminate space before \begin{itemize}

I'm very happy with the paralist package. Besides adding the option to eliminate the space it also adds other nice things like compact versions of the itemize, enumerate and describe environments.

Convert an image to grayscale in HTML/CSS

be An alternative for older browser could be to use mask produced by pseudo-elements or inline tags.

Absolute positionning hover an img (or text area wich needs no click nor selection) can closely mimic effects of color scale , via rgba() or translucide png .

It will not give one single color scale, but will shades color out of range.

test on code pen with 10 different colors via pseudo-element, last is gray . http://codepen.io/gcyrillus/pen/nqpDd (reload to switch to another image)

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

Converting a UNIX Timestamp to Formatted Date String

You can do like as.....

$originalDate = "1585876500";

echo $newDate = date("Y-m-d h:i:sa", date($originalDate));

mvn clean install vs. deploy vs. release

The clean, install and deploy phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.

mvn clean install

This command invokes the clean phase and then the install phase sequentially:

  • clean: removes files generated at build-time in a project's directory (target by default)
  • install: installs the package into the local repository, for use as a dependency in other projects locally.

mvn deploy

This command invokes the deploy phase:

  • deploy: copies the final package to the remote repository for sharing with other developers and projects.

mvn release

This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare and perform. As documented:

Preparing a release goes through the following release phases:

  • Check that there are no uncommitted changes in the sources
  • Check that there are no SNAPSHOT dependencies
  • Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
  • Transform the SCM information in the POM to include the final destination of the tag
  • Run the project tests against the modified POMs to confirm everything is in working order
  • Commit the modified POMs
  • Tag the code in the SCM with a version name (this will be prompted for)
  • Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
  • Commit the modified POMs

And then:

Performing a release runs the following release phases:

  • Checkout from an SCM URL with optional tag
  • Run the predefined Maven goals to release the project (by default, deploy site-deploy)

See also

Return a value if no rows are found in Microsoft tSQL

I read all the answers here, and it took a while to figure out what was going on. The following is based on the answer by Moe Sisko and some related research

If your SQL query does not return any data there is not a field with a null value so neither ISNULL nor COALESCE will work as you want them to. By using a sub query, the top level query gets a field with a null value, and both ISNULL and COALESCE will work as you want/expect them to.

My query

select isnull(
 (select ASSIGNMENTM1.NAME
 from dbo.ASSIGNMENTM1
 where ASSIGNMENTM1.NAME = ?)
, 'Nothing Found') as 'ASSIGNMENTM1.NAME'

My query with comments

select isnull(
--sub query either returns a value or returns nothing (no value)
 (select ASSIGNMENTM1.NAME
 from dbo.ASSIGNMENTM1
 where ASSIGNMENTM1.NAME = ?)
 --If there is a value it is displayed 
 --If no value, it is perceived as a field with a null value, 
 --so the isnull function can give the desired results
, 'Nothing Found') as 'ASSIGNMENTM1.NAME'

How to use Elasticsearch with MongoDB?

Using river can present issues when your operation scales up. River will use a ton of memory when under heavy operation. I recommend implementing your own elasticsearch models, or if you're using mongoose you can build your elasticsearch models right into that or use mongoosastic which essentially does this for you.

Another disadvantage to Mongodb River is that you'll be stuck using mongodb 2.4.x branch, and ElasticSearch 0.90.x. You'll start to find that you're missing out on a lot of really nice features, and the mongodb river project just doesn't produce a usable product fast enough to keep stable. That said Mongodb River is definitely not something I'd go into production with. It's posed more problems than its worth. It will randomly drop write under heavy load, it will consume lots of memory, and there's no setting to cap that. Additionally, river doesn't update in realtime, it reads oplogs from mongodb, and this can delay updates for as long as 5 minutes in my experience.

We recently had to rewrite a large portion of our project, because its a weekly occurrence that something goes wrong with ElasticSearch. We had even gone as far as to hire a Dev Ops consultant, who also agrees that its best to move away from River.

UPDATE: Elasticsearch-mongodb-river now supports ES v1.4.0 and mongodb v2.6.x. However, you'll still likely run into performance problems on heavy insert/update operations as this plugin will try to read mongodb's oplogs to sync. If there are a lot of operations since the lock(or latch rather) unlocks, you'll notice extremely high memory usage on your elasticsearch server. If you plan on having a large operation, river is not a good option. The developers of ElasticSearch still recommend you to manage your own indexes by communicating directly with their API using the client library for your language, rather than using river. This isn't really the purpose of river. Twitter-river is a great example of how river should be used. Its essentially a great way to source data from outside sources, but not very reliable for high traffic or internal use.

Also consider that mongodb-river falls behind in version, as its not maintained by ElasticSearch Organization, its maintained by a thirdparty. Development was stuck on v0.90 branch for a long time after the release of v1.0, and when a version for v1.0 was released it wasn't stable until elasticsearch released v1.3.0. Mongodb versions also fall behind. You may find yourself in a tight spot when you're looking to move to a later version of each, especially with ElasticSearch under such heavy development, with many very anticipated features on the way. Staying up on the latest ElasticSearch has been very important as we rely heavily on constantly improving our search functionality as its a core part of our product.

All in all you'll likely get a better product if you do it yourself. Its not that difficult. Its just another database to manage in your code, and it can easily be dropped in to your existing models without major refactoring.

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

PreparedStatement with Statement.RETURN_GENERATED_KEYS

Not having a compiler by me right now, I'll answer by asking a question:

Have you tried this? Does it work?

long key = -1L;
PreparedStatement statement = connection.prepareStatement();
statement.executeUpdate(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
    key = rs.getLong(1);
}

Disclaimer: Obviously, I haven't compiled this, but you get the idea.

PreparedStatement is a subinterface of Statement, so I don't see a reason why this wouldn't work, unless some JDBC drivers are buggy.

AngularJs: Reload page

If using Angulars more advanced ui-router which I'd definitely recommend then you can now simply use:

$state.reload();

Which is essentially doing the same as Dunc's answer.

Change directory in Node.js command prompt

  1. Open file nodevars.bat
  2. Just add your path to the end, "%HOMEDRIVE%%HOMEPATH% /file1/file2/file3
  3. Save file nodevars.bat

This work even with Swedish words

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

Check play state of AVPlayer

You can tell it's playing using:

AVPlayer *player = ...
if ((player.rate != 0) && (player.error == nil)) {
    // player is playing
}

Swift 3 extension:

extension AVPlayer {
    var isPlaying: Bool {
        return rate != 0 && error == nil
    }
}

Twitter bootstrap 3 two columns full height

If there will be no content after the row (whole screen height is taken), the trick with using position: fixed; height: 100% for .col:before element may work well:

_x000D_
_x000D_
header {_x000D_
  background: green;_x000D_
  height: 50px;_x000D_
}_x000D_
.col-xs-3 {_x000D_
  background: pink;_x000D_
}_x000D_
.col-xs-3:before {_x000D_
  background: pink;_x000D_
  content: ' ';_x000D_
  height: 100%;_x000D_
  margin-left: -15px; /* compensates column's padding */_x000D_
  position: fixed;_x000D_
  width: inherit; /* bootstrap column's width */_x000D_
  z-index: -1; /* puts behind content */_x000D_
}_x000D_
.col-xs-9 {_x000D_
  background: yellow;_x000D_
}_x000D_
.col-xs-9:before {_x000D_
  background: yellow;_x000D_
  content: ' ';_x000D_
  height: 100%;_x000D_
  margin-left: -15px; /* compensates column's padding */_x000D_
  position: fixed;_x000D_
  width: inherit; /* bootstrap column's width */_x000D_
  z-index: -1; /* puts behind content */_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<header>Header</header>_x000D_
<div class="container-fluid">_x000D_
    <div class="row">_x000D_
        <div class="col-xs-3">Navigation</div>_x000D_
        <div class="col-xs-9">Content</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between AF_INET and PF_INET in socket programming?

In fact, AF_ and PF_ are the same thing. There are some words on Wikipedia will clear your confusion

The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.

Getting multiple keys of specified value of a generic Dictionary?

Can't you create a subclass of Dictionary which has that functionality?


    public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
    {
        private Dictionary < TValue, TKey > _keys;

        public TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set 
            { 
                base[key] = value;
                _keys[value] = key;
            }
        }

        public MyDict()
        {
            _keys = new Dictionary < TValue, TKey >();
        }

        public TKey GetKeyFromValue(TValue value)
        {
            return _keys[value];
        }
    }

EDIT: Sorry, didn't get code right first time.

Customizing Bootstrap CSS template

Use LESS with Bootstrap...

Here are the Bootstrap docs for how to use LESS

(they have moved since previous answers)

How to remove duplicate values from a multi-dimensional array in PHP

The user comments on the array_unique() documentation have many solutions to this. Here is one of them:

kenrbnsn at rbnsn dot com
27-Sep-2005 12:09

Yet another Array_Unique for multi-demensioned arrays. I've only tested this on two-demensioned arrays, but it could probably be generalized for more, or made to use recursion.

This function uses the serialize, array_unique, and unserialize functions to do the work.


function multi_unique($array) {
    foreach ($array as $k=>$na)
        $new[$k] = serialize($na);
    $uniq = array_unique($new);
    foreach($uniq as $k=>$ser)
        $new1[$k] = unserialize($ser);
    return ($new1);
}

This is from http://ca3.php.net/manual/en/function.array-unique.php#57202.

form action with javascript

It has been almost 8 years since the question was asked, but I will venture an answer not previously given. The OP said this doesn't work:

action="javascript:simpleCart.checkout()"

And the OP said that this code continued to fail despite trying all the good advice he got. So I will venture a guess. The action is calling checkout() as a static method of the simpleCart class; but maybe checkout() is actually an instance member, and not static. It depends how he defined checkout().

By the way, simpleCart is presumably a class name, and by convention class names have an initial capital letter, so let's use that convention, here. Let's use the name SimpleCart.

Here is some sample code that illustrates defining checkout() as an instance member. This was the correct way to do it, prior to ECMA-6:

function SimpleCart() {
    ...
}
SimpleCart.prototype.checkout = function() { ... };

Many people have used a different technique, as illustrated in the following. This was popular, and it worked, but I advocate against it, because instances are supposed to be defined on the prototype, just once, while the following technique defines the member on this and does so repeatedly, with every instantiation.

function SimpleCart() {
    ...
    this.checkout = function() { ... };
}

And here is an instance definition in ECMA-6, using an official class:

class SimpleCart {
    constructor() { ... }
    ...
    checkout()    { ... }
}

Compare to a static definition in ECMA-6. The difference is just one word:

class SimpleCart {
    constructor() { ... }
    ...
    static checkout()    { ... }
}

And here is a static definition the old way, pre-ECMA-6. Note that the checkout() method is defined outside of the function. It is a member of the function object, not the prototype object, and that's what makes it static.

function SimpleCart() {
    ...
}
SimpleCart.checkout = function() { ... };

Because of the way it is defined, a static function will have a different concept of what the keyword this references. Note that instance member functions are called using the this keyword:

this.checkout();

Static member functions are called using the class name:

SimpleCart.checkout();

The problem is that the OP wants to put the call into HTML, where it will be in global scope. He can't use the keyword this because this would refer to the global scope (which is window).

action="javascript:this.checkout()" // not as intended
action="javascript:window.checkout()" // same thing

There is no easy way to use an instance member function in HTML. You can do stuff in combination with JavaScript, creating a registry in the static scope of the Class, and then calling a surrogate static method, while passing an argument to that surrogate that gives the index into the registry of your instance, and then having the surrogate call the actual instance member function. Something like this:

// In Javascript:
SimpleCart.registry[1234] = new SimpleCart();

// In HTML
action="javascript:SimpleCart.checkout(1234);"

// In Javascript
SimpleCart.checkout = function(myIndex) {
    var myThis = SimpleCart.registry[myIndex];
    myThis.checkout();
}

You could also store the index as an attribute on the element.

But usually it is easier to just do nothing in HTML and do everything in JavaScript with .addEventListener() and use the .bind() capability.

ECMAScript 6 arrow function that returns an object

You can always check this out for more custom solutions:

x => ({}[x.name] = x);

XML Schema minOccurs / maxOccurs default values

Short answer:

As written in xsd:

<xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/>
<xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/>

If you provide an attribute with number, then the number is boundary. Otherwise attribute should appear exactly once.

How can I set selected option selected in vue.js 2?

You simply need to remove v-bind (:) from selected and required attributes. Like this :-

_x000D_
_x000D_
<template>_x000D_
    <select class="form-control" v-model="selected" required @change="changeLocation">_x000D_
        <option selected>Choose Province</option>_x000D_
        <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>_x000D_
    </select>_x000D_
</template>
_x000D_
_x000D_
_x000D_

You are not binding anything to the vue instance through these attributes thats why it is giving error.

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

Yes it does. If you're using the emulator, it will show in the Logcat view under the System.out tag. Write something and try it in your emulator.

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

Explanation without any code

Summary Example:

The Hat is "loosely coupled" to the body. This means you can easily take the hat off without making any changes to the person/body. When you can do that then you have "loose coupling". See below for elaboration.

The Hat is "loosely coupled" to the body. This means you can easily take then hat off without making any changes to the the person/body. Picture Attribution: https://pixabay.com/en/greeting-cylinder-chapeau-dignity-317250/

Tight coupling (Detailed Example)

Skin - tight coupling

Think of your skin. It's stuck to your body. It fits like a glove. But what if you wanted to change your skin colour from say white to black? Can you imagine just how painful it would be to peel off your skin, dye it, and then to paste it back on etc? Changing your skin is difficult because it is tightly coupled to your body. You just can't make changes easily. You would have to fundamentally redesign a human being in order to make this possible.

  • Key Point #1: In other words, if you want to change the skin, you would also HAVE TO change the design of your body as well because the two are joined together - they are tightly coupled.

God was not a good object oriented programmer.

Loose coupling (Detailed Example)

Now think of getting dressed in the morning. You don't like blue? No problems: you can put a red shirt on instead. You can do this easily and effortlessly because the shirt is not really connected to your body the same way as your skin. The shirt doesn't know or care about what body it is going on. In other words, you can change your clothes, without really changing your body.

  • That's key point #2. If you change your shirt, then you are not forced to change your body - when you can do that, then you have loose coupling. When you can't do that, then you have tight coupling.

That's the basic concept in a nutshell.

Why is all of this important?

It's important because software changes all the time. Generally speaking you want to be able to easily modify your code, without changing your code. I know that sounds like an oxymoron, but please bear with me.

Practical Examples of Coupling when Designing Software

  • CSV/JSON/DB Examples: If somebody wants their output in a CSV file rather than JSON etc., or if you want to switch from MySQL to PostGreSQL you should be able to make those changes extremely easily in your code, without having to rewrite the entire class etc. In other words, you do not want to tightly couple your application with a specific database implementation (e.g. Mysql) or to a particular output (e.g. CSV files). Because, as is inevitable in software, changes will come. When they do come, it's much easier if your parts of your code are loosely coupled. Or if you're using AWS and they start charging too much because of market dominance, you should be able to somewhat easily switch to Google or Azure etc.

Practical Example in Manufacturing - Car Parts:

Another example to reinforce coupling:

If somebody wants their car in black, you shouldn't have to redesign the entire car in order to do that. A car and its spare parts would be a perfect example of a loosely coupled architecture. If you want to replace your engine with a better one, you should be able to simply remove your engine without too much effort and swap it for a better one. If your car only works with Rolls Royce 1234 Engines and no other engines - then your car will is tightly coupled to that engine (Rolls Royce 1234).

Some amount of coupling is going to happen, but you should work to minimise it as much as you can. Why? Because when requirements change we should still be able to deliver good quality software, very quickly and we are aided in that goal by loose coupling.

Summary

In short, loose coupling makes code easier to change. The answers above provide some code which is worth reading at this point.

Picture Attribution.

href around input type submit

Why would you want to put a submit button inside an anchor? You are either trying to submit a form or go to a different page. Which one is it?

Either submit the form:

<input type="submit" class="button_active" value="1" />

Or go to another page:

<input type="button" class="button_active" onclick="location.href='1.html';" />

Using CSS to align a button bottom of the screen using relative positions

This will work for any resolution,

button{
    position:absolute;
    bottom: 5%;
    right:20%;
}

http://jsfiddle.net/BUuSr/

Which tool to build a simple web front-end to my database

I think PHP is a good solution. It's simple to set up, free and there is plenty of documentation on how to create a database management app. Ruby on Rails is faster to code but a bit more difficult to set up.

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

How to insert Records in Database using C# language?

Use a parameterized query to prevent Sql injections (secutity problem)

Use the using statement so the connection will be closed and resources will be disposed.

using(var connection = new SqlConnection("connectionString"))
{
    connection.Open();
    var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
    using(var cmd = new SqlCommand(sql, connection))
    {
        cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
        cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);

        cmd.ExecuteNonQuery();
    }
}

Python executable not finding libpython shared library

I installed Python 3.5 by Software Collections on CentOS 7 minimal. It all worked fine on its own, but I saw the shared library error mentioned in this question when I tried running a simple CGI script:

tail /var/log/httpd/error_log
AH01215: /opt/rh/rh-python35/root/usr/bin/python: error while loading shared libraries: libpython3.5m.so.rh-python35-1.0: cannot open shared object file: No such file or directory

I wanted a systemwide permanent solution that works for all users, so that excluded adding export statements to .profile or .bashrc files. There is a one-line solution, based on the Red Hat solutions page. Thanks for the comment that points it out:

echo 'source scl_source enable rh-python35' | sudo tee --append /etc/profile.d/python35.sh

After a restart, it's all good on the shell, but sometimes my web server still complains. There's another approach that always worked for both the shell and the server, and is more generic. I saw the solution here and then realized it's actually mentioned in one of the answers here as well! Anyway, on CentOS 7, these are the steps:

 vim /etc/ld.so.conf

Which on my machine just had:

include ld.so.conf.d/*.conf

So I created a new file:

vim /etc/ld.so.conf.d/rh-python35.conf

And added:

/opt/rh/rh-python35/root/usr/lib64/

And to manually rebuild the cache:

sudo ldconfig

That's it, scripts work fine!

This was a temporary solution, which didn't work across reboots:

sudo ldconfig /opt/rh/rh-python35/root/usr/lib64/ -v

The -v (verbose) option was just to see what was going on. I saw that it did: /opt/rh/rh-python35/root/usr/lib64: libpython3.so.rh-python35 -> libpython3.so.rh-python35 libpython3.5m.so.rh-python35-1.0 -> libpython3.5m.so.rh-python35-1.0

This particular error went away. Incidentally, I had to chown the user to apache to get rid of a permission error after that.

Note that I used find to locate the directory for the library. You could also do:

sudo yum install mlocate
sudo updatedb
locate libpython3.5m.so.rh-python35-1.0

Which on my VM returns:

/opt/rh/rh-python35/root/usr/lib64/libpython3.5m.so.rh-python35-1.0

Which is the path I need to give to ldconfig, as shown above.

How to add a line to a multiline TextBox?

Just put a line break into your text.

You don't add lines as a method. Multiline just supports the use of line breaks.

Why do you need to put #!/bin/bash at the beginning of a script file?

It is called a shebang. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash. All scripts under UNIX and Linux execute using the interpreter specified on a first line.

Parallel foreach with asynchronous lambda

My lightweight implementation of ParallelForEach async.

Features:

  1. Throttling (max degree of parallelism).
  2. Exception handling (aggregation exception will be thrown at completion).
  3. Memory efficient (no need to store the list of tasks).

public static class AsyncEx
{
    public static async Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> asyncAction, int maxDegreeOfParallelism = 10)
    {
        var semaphoreSlim = new SemaphoreSlim(maxDegreeOfParallelism);
        var tcs = new TaskCompletionSource<object>();
        var exceptions = new ConcurrentBag<Exception>();
        bool addingCompleted = false;

        foreach (T item in source)
        {
            await semaphoreSlim.WaitAsync();
            asyncAction(item).ContinueWith(t =>
            {
                semaphoreSlim.Release();

                if (t.Exception != null)
                {
                    exceptions.Add(t.Exception);
                }

                if (Volatile.Read(ref addingCompleted) && semaphoreSlim.CurrentCount == maxDegreeOfParallelism)
                {
                    tcs.TrySetResult(null);
                }
            });
        }

        Volatile.Write(ref addingCompleted, true);
        await tcs.Task;
        if (exceptions.Count > 0)
        {
            throw new AggregateException(exceptions);
        }
    }
}

Usage example:

await Enumerable.Range(1, 10000).ParallelForEachAsync(async (i) =>
{
    var data = await GetData(i);
}, maxDegreeOfParallelism: 100);

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

Begining with Python 3, all strings are unicode objects.

  a = 'Happy New Year' # Python 3
  b = unicode('Happy New Year') # Python 2

The instructions above are the same. So I think you should remove the .decode('utf-8') part because you already have a unicode object.

Adding external library into Qt Creator project

LIBS += C:\Program Files\OpenCV\lib

won't work because you're using white-spaces in Program Files. In this case you have to add quotes, so the result will look like this: LIBS += "C:\Program Files\OpenCV\lib". I recommend placing libraries in non white-space locations ;-)

How to draw lines in Java

You need to create a class that extends Component. There you can override the paint method and put your painting code in:

package blah.whatever;

import java.awt.Component;
import java.awt.Graphics;

public class TestAWT extends Component {

/** @see java.awt.Component#paint(java.awt.Graphics) */
@Override
public void paint(Graphics g) {
    super.paint(g);
    g.drawLine(0,0,100,100);
    g.drawLine(10, 10, 20, 300);
    // more drawing code here...
}

}

Put this component into the GUI of your application. If you're using Swing, you need to extend JComponent and override paintComponent, instead.

As Helios mentioned, the painting code actually tells the system how your component looks like. The system will ask for this information (call your painting code) when it thinks it needs to be (re)painted, for example, if a window is moved in front of your component.

How to search for a string in cell array in MATLAB?

The strcmp and strcmpi functions are the most direct way to do this. They search through arrays.

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ix = find(strcmp(strs, 'KU'))

How to get HttpContext.Current in ASP.NET Core?

As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.

HttpContext.Current was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.

HttpContext property

You can access the current HTTP context via the HttpContext property on any controller. The closest thing to your original code sample would be to pass HttpContext into the method you are calling:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        MyMethod(HttpContext);

        // Other code
    }
}

public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
    var host = $"{context.Request.Scheme}://{context.Request.Host}";

    // Other code
}

HttpContext parameter in middleware

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically:

public Task Invoke(HttpContext context)
{
    // Do something with the current HTTP context...
}

HTTP context accessor

Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.

Request this interface in your constructor:

public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

You can then access the current HTTP context in a safe way:

var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...

IHttpContextAccessor isn't always added to the service container by default, so register it in ConfigureServices just to be safe:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    // if < .NET Core 2.2 use this
    //services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other code...
}

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Python 2,3 Convert Integer to "bytes" Cleanly

Answer 1:

To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string's encode method. If you don't supply an encoding parameter 'ascii' is used, which will always be good enough for numeric digits.

s = str(n).encode()

In Python 2 str(n) already produces bytes; the encode will do a double conversion as this string is implicitly converted to Unicode and back again to bytes. It's unnecessary work, but it's harmless and is completely compatible with Python 3.


Answer 2:

Above is the answer to the question that was actually asked, which was to produce a string of ASCII bytes in human-readable form. But since people keep coming here trying to get the answer to a different question, I'll answer that question too. If you want to convert 10 to b'10' use the answer above, but if you want to convert 10 to b'\x0a\x00\x00\x00' then keep reading.

The struct module was specifically provided for converting between various types and their binary representation as a sequence of bytes. The conversion from a type to bytes is done with struct.pack. There's a format parameter fmt that determines which conversion it should perform. For a 4-byte integer, that would be i for signed numbers or I for unsigned numbers. For more possibilities see the format character table, and see the byte order, size, and alignment table for options when the output is more than a single byte.

import struct
s = struct.pack('<i', 5) # b'\x05\x00\x00\x00'

Why is the Android emulator so slow? How can we speed up the Android emulator?

To reduce your emulator start-up time you need to check the "Disable Boot Animation" before starting the emulator. Refer to the Android documentation.

If in case you don't know, you do not need to close the emulator every-time you run/debug your app. If you click run/debug when it's already open, your APK file will get uploaded to the emulator and start pretty much immediately. Emulator takes annoyingly long time only when it started the first time.

Here are some tips to speed up the Android emulator: How to speed up the Android Emulator by up to 400%.

How to do HTTP authentication in android?

I've not met that particular package before, but it says it's for client-side HTTP authentication, which I've been able to do on Android using the java.net APIs, like so:

Authenticator.setDefault(new Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("myuser","mypass".toCharArray());
    }});
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setUseCaches(false);
c.connect();

Obviously your getPasswordAuthentication() should probably do something more intelligent than returning a constant.

If you're trying to make a request with a body (e.g. POST) with authentication, beware of Android issue 4326. I've linked a suggested fix to the platform there, but there's a simple workaround if you only want Basic auth: don't bother with Authenticator, and instead do this:

c.setRequestProperty("Authorization", "basic " +
        Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));

How to stop C# console applications from closing automatically?

Alternatively, you can delay the closing using the following code:

System.Threading.Thread.Sleep(1000);

Note the Sleep is using milliseconds.

Undo scaffolding in Rails

To generate the scaffold:

rails generate scaffold abc

To revert this scaffold:

rails destroy scaffold abc

If you have run the migration for it just rollback

rake db:rollback STEP=1

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

There are two ways for specifying parameters in C. One is using an identifier list, and the other is using a parameter type list. The identifier list can be omitted, but the type list can not. So, to say that one function takes no arguments in a function definition you do this with an (omitted) identifier list

void f() {
    /* do something ... */
}

And this with a parameter type list:

void f(void) {
    /* do something ... */
}

If in a parameter type list the only one parameter type is void (it must have no name then), then that means the function takes no arguments. But those two ways of defining a function have a difference regarding what they declare.

Identifier lists

The first defines that the function takes a specific number of arguments, but neither the count is communicated nor the types of what is needed - as with all function declarations that use identifier lists. So the caller has to know the types and the count precisely before-hand. So if the caller calls the function giving it some argument, the behavior is undefined. The stack could become corrupted for example, because the called function expects a different layout when it gains control.

Using identifier lists in function parameters is deprecated. It was used in old days and is still present in lots of production code. They can cause severe danger because of those argument promotions (if the promoted argument type do not match the parameter type of the function definition, behavior is undefined either!) and are much less safe, of course. So always use the void thingy for functions without parameters, in both only-declarations and definitions of functions.

Parameter type list

The second one defines that the function takes zero arguments and also communicates that - like with all cases where the function is declared using a parameter type list, which is called a prototype. If the caller calls the function and gives it some argument, that is an error and the compiler spits out an appropriate error.

The second way of declaring a function has plenty of benefits. One of course is that amount and types of parameters are checked. Another difference is that because the compiler knows the parameter types, it can apply implicit conversions of the arguments to the type of the parameters. If no parameter type list is present, that can't be done, and arguments are converted to promoted types (that is called the default argument promotion). char will become int, for example, while float will become double.

Composite type for functions

By the way, if a file contains both an omitted identifier list and a parameter type list, the parameter type list "wins". The type of the function at the end contains a prototype:

void f();
void f(int a) {
    printf("%d", a);
}

// f has now a prototype. 

That is because both declarations do not say anything contradictory. The second, however, had something to say in addition. Which is that one argument is accepted. The same can be done in reverse

void f(a) 
  int a;
{ 
    printf("%d", a);
}

void f(int);

The first defines a function using an identifier list, while the second then provides a prototype for it, using a declaration containing a parameter type list.

How do I get the absolute directory of a file in bash?

I have been using readlink -f works on linux

so

FULL_PATH=$(readlink -f filename)
DIR=$(dirname $FULL_PATH)

PWD=$(pwd)

cd $DIR

#<do more work>

cd $PWD

SLF4J: Class path contains multiple SLF4J bindings

<!--<dependency>-->
     <!--<groupId>org.springframework.boot</groupId>-->
     <!--<artifactId>spring-boot-starter-log4j2</artifactId>-->
<!--</dependency>-->

I solved by delete this:spring-boot-starter-log4j2

Download a file with Android, and showing the progress in a ProgressDialog

There are many ways to download files. Following I will post most common ways; it is up to you to decide which method is better for your app.

1. Use AsyncTask and show the download progress in a dialog

This method will allow you to execute some background processes and update the UI at the same time (in this case, we'll update a progress bar).

Imports:

import android.os.PowerManager;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;

This is an example code:

// declare the dialog as a member field of your activity
ProgressDialog mProgressDialog;

// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);

// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");

mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

    @Override
    public void onCancel(DialogInterface dialog) {
        downloadTask.cancel(true); //cancel the task
    }
});

The AsyncTask will look like this:

// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;
    private PowerManager.WakeLock mWakeLock;

    public DownloadTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/file_name.extension");

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }

The method above (doInBackground) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate and onPreExecute run on the UI thread, so there you can change the progress bar:

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user 
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
             getClass().getName());
        mWakeLock.acquire();
        mProgressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
    }

For this to run, you need the WAKE_LOCK permission.

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

2. Download from Service

The big question here is: how do I update my activity from a service?. In the next example we are going to use two classes you may not be aware of: ResultReceiver and IntentService. ResultReceiver is the one that will allow us to update our thread from a service; IntentService is a subclass of Service which spawns a thread to do background work from there (you should know that a Service runs actually in the same thread of your app; when you extends Service, you must manually spawn new threads to run CPU blocking operations).

Download service can look like this:

public class DownloadService extends IntentService {
    public static final int UPDATE_PROGRESS = 8344;

    public DownloadService() {
        super("DownloadService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {

        String urlToDownload = intent.getStringExtra("url");
        ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
        try {

            //create url and connect
            URL url = new URL(urlToDownload);
            URLConnection connection = url.openConnection();
            connection.connect();

            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(connection.getInputStream());

            String path = "/sdcard/BarcodeScanner-debug.apk" ;
            OutputStream output = new FileOutputStream(path);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;

                // publishing the progress....
                Bundle resultData = new Bundle();
                resultData.putInt("progress" ,(int) (total * 100 / fileLength));
                receiver.send(UPDATE_PROGRESS, resultData);
                output.write(data, 0, count);
            }

            // close streams 
            output.flush();
            output.close();
            input.close();

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

        Bundle resultData = new Bundle();
        resultData.putInt("progress" ,100);

        receiver.send(UPDATE_PROGRESS, resultData);
    }
}

Add the service to your manifest:

<service android:name=".DownloadService"/>

And the activity will look like this:

// initialize the progress dialog like in the first example

// this is how you fire the downloader
mProgressDialog.show();
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("url", "url of the file to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);

Here is were ResultReceiver comes to play:

private class DownloadReceiver extends ResultReceiver{

    public DownloadReceiver(Handler handler) {
        super(handler);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {

        super.onReceiveResult(resultCode, resultData);

        if (resultCode == DownloadService.UPDATE_PROGRESS) {

            int progress = resultData.getInt("progress"); //get the progress
            dialog.setProgress(progress);

            if (progress == 100) {
                dialog.dismiss();
            }
        }
    }
}

2.1 Use Groundy library

Groundy is a library that basically helps you run pieces of code in a background service, and it is based on the ResultReceiver concept shown above. This library is deprecated at the moment. This is how the whole code would look like:

The activity where you are showing the dialog...

public class MainActivity extends Activity {

    private ProgressDialog mProgressDialog;

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

        findViewById(R.id.btn_download).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String url = ((EditText) findViewById(R.id.edit_url)).getText().toString().trim();
                Bundle extras = new Bundler().add(DownloadTask.PARAM_URL, url).build();
                Groundy.create(DownloadExample.this, DownloadTask.class)
                        .receiver(mReceiver)
                        .params(extras)
                        .queue();

                mProgressDialog = new ProgressDialog(MainActivity.this);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
            }
        });
    }

    private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            super.onReceiveResult(resultCode, resultData);
            switch (resultCode) {
                case Groundy.STATUS_PROGRESS:
                    mProgressDialog.setProgress(resultData.getInt(Groundy.KEY_PROGRESS));
                    break;
                case Groundy.STATUS_FINISHED:
                    Toast.makeText(DownloadExample.this, R.string.file_downloaded, Toast.LENGTH_LONG);
                    mProgressDialog.dismiss();
                    break;
                case Groundy.STATUS_ERROR:
                    Toast.makeText(DownloadExample.this, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();
                    mProgressDialog.dismiss();
                    break;
            }
        }
    };
}

A GroundyTask implementation used by Groundy to download the file and show the progress:

public class DownloadTask extends GroundyTask {    
    public static final String PARAM_URL = "com.groundy.sample.param.url";

    @Override
    protected boolean doInBackground() {
        try {
            String url = getParameters().getString(PARAM_URL);
            File dest = new File(getContext().getFilesDir(), new File(url).getName());
            DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));
            return true;
        } catch (Exception pokemon) {
            return false;
        }
    }
}

And just add this to the manifest:

<service android:name="com.codeslap.groundy.GroundyService"/>

It couldn't be easier I think. Just grab the latest jar from Github and you are ready to go. Keep in mind that Groundy's main purpose is to make calls to external REST apis in a background service and post results to the UI with easily. If you are doing something like that in your app, it could be really useful.

2.2 Use https://github.com/koush/ion

3. Use DownloadManager class (GingerBread and newer only)

GingerBread brought a new feature, DownloadManager, which allows you to download files easily and delegate the hard work of handling threads, streams, etc. to the system.

First, let's see a utility method:

/**
 * @param context used to check the device version and DownloadManager information
 * @return true if the download manager is available
 */
public static boolean isDownloadManagerAvailable(Context context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        return true;
    }
    return false;
}

Method's name explains it all. Once you are sure DownloadManager is available, you can do something like this:

String url = "url you want to download";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");

// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

Download progress will be showing in the notification bar.

Final thoughts

First and second methods are just the tip of the iceberg. There are lots of things you have to keep in mind if you want your app to be robust. Here is a brief list:

  • You must check whether user has an internet connection available
  • Make sure you have the right permissions (INTERNET and WRITE_EXTERNAL_STORAGE); also ACCESS_NETWORK_STATE if you want to check internet availability.
  • Make sure the directory were you are going to download files exist and has write permissions.
  • If download is too big you may want to implement a way to resume the download if previous attempts failed.
  • Users will be grateful if you allow them to interrupt the download.

Unless you need detailed control of the download process, then consider using DownloadManager (3) because it already handles most of the items listed above.

But also consider that your needs may change. For example, DownloadManager does no response caching. It will blindly download the same big file multiple times. There's no easy way to fix it after the fact. Where if you start with a basic HttpURLConnection (1, 2), then all you need is to add an HttpResponseCache. So the initial effort of learning the basic, standard tools can be a good investment.

This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress. For more details Link

react-native :app:installDebug FAILED

As you add more modules to Android, there is an incredible demand placed on the Android build system, and the default memory settings will not work. To avoid OutOfMemory errors during Android builds, you should uncomment the alternate Gradle memory setting present in /android/gradle.properties:

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

MVC If statement in View

You only need to prefix an if statement with @ if you're not already inside a razor code block.

Edit: You have a couple of things wrong with your code right now.

You're declaring nmb, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:

@if (ViewBag.Articles != null)
{
    int nmb = 0;
    foreach (var item in ViewBag.Articles)
    {
        if (nmb % 3 == 0)
        {
            @:<div class="row"> 
        }

        <a href="@Url.Action("Article", "Programming", new { id = item.id })">
            <div class="tasks">
                <div class="col-md-4">
                    <div class="task important">
                        <h4>@item.Title</h4>
                        <div class="tmeta">
                            <i class="icon-calendar"></i>
                                @item.DateAdded - Pregleda:@item.Click
                            <i class="icon-pushpin"></i> Authorrr
                        </div>
                    </div>
                </div>
            </div>
        </a>
        if (nmb % 3 == 0)
        {
            @:</div>
        }
    }
}

The important part here is the @:. It's a short-hand of <text></text>, which is used to force the razor engine to render text.

One other thing, the HTML standard specifies that a tags can only contain inline elements, and right now, you're putting a div, which is a block-level element, inside an a.

What is the difference between Scrum and Agile Development?

At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".

In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.

So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.

How to define a relative path in java

Example for Spring Boot. My WSDL-file is in Resources in "wsdl" folder. The path to the WSDL-file is:

resources/wsdl/WebServiceFile.wsdl

To get the path from some method to this file you can do the following:

String pathToWsdl = this.getClass().getClassLoader().
                    getResource("wsdl\\WebServiceFile.wsdl").toString();

How to create a user in Django?

Bulk user creation with set_password

I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

set_password is another way to generate the hashed passwords:

def users_iterator():
    for i in range(nusers):
        is_superuser = (i == 0)
        user = User(
            first_name='First' + str(i),
            is_staff=is_superuser,
            is_superuser=is_superuser,
            last_name='Last' + str(i),
            username='user' + str(i),
        )
        user.set_password('asdfqwer')
        yield user

class Command(BaseCommand):
    def handle(self, **options):
        User.objects.bulk_create(iter(users_iterator()))

Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django

Tested in Django 1.9.

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

Assuming the parent has a fixed width, e.g #page { width: 1000px; } and is centered #page { margin: auto; }, you want the child to fit the width of browser viewport you could simply do:

#page {
    margin: auto;
    width: 1000px;
}

.fullwidth {
    margin-left: calc(500px - 50vw); /* 500px is half of the parent's 1000px */
    width: 100vw;
}

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I had this problem, and on a hunch I removed the Qt Configs from my environment. I.e.,

rm -rf ~/.config/Qt*

Then I started qtcreator and it reconfigured itself with the existing state of the machine. It no longer remembered where my projects were, but that just meant I had to browse to them "for the first time" again.

But more importantly it built itself a coherent set of library paths, so I could rebuild and run my project executables again without the xcb or qxcb libraries going missing.

What is copy-on-write?

Copy-on-write is a technique to reduce the memory usage of resource copies using deferred copy. The resource copies are initially virtual (i.e. they share memory) and only become real (i.e. they have their own memory) on the first write operation, hence the name ‘copy-on-write’.

Here after is a Python implementation of the copy-on-write technique using the proxy design pattern. A ValueProxy object (the proxy) implements the copy-on-write technique by:

  • having an attribute bound to an immutable Value object (the subject);
  • translating copy requests to the creation of a new ValueProxy object sharing the same subject attribute as the original ValueProxy object;
  • forwarding read requests to the subject attribute;
  • translating write requests to the creation of a new immutable Value object with the new state and the rebinding of the subject attribute to this new immutable Value object.
import abc

class BaseValue(abc.ABC):
    @abc.abstractmethod
    def read(self):
        raise NotImplementedError
    @abc.abstractmethod
    def write(self, data):
        raise NotImplementedError

class Value(BaseValue):
    def __init__(self, data):
        self.data = data
    def read(self):
        return self.data
    def write(self, data):
        pass

class ValueProxy(BaseValue):
    def __init__(self, subject):
        self.subject = subject
    def read(self):
        return self.subject.read()
    def write(self, data):
        self.subject = Value(data)
    def clone(self):
        return ValueProxy(self.subject)

v1 = ValueProxy(Value('foo'))
v2 = v1.clone()  # shares the immutable Value object between the copies
assert v1.subject is v2.subject
v2.write('bar')  # creates a new immutable Value object with the new state
assert v1.subject is not v2.subject

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

MATLAB is a fantastic tool for

  • prototyping
  • engineering simulation and
  • fast visualization of data

You can really play with, visualize and test your ideas on a data set very effectively. It should not be regarded as an alternative to other software languages used for product development. I highly recommend it for the above tasks, though it is expensive - free alternatives like Octave and Python are catching up.

Define static method in source-file with declaration in header-file in C++

Static member functions must refer to static variables of that class. So in your case,

static void CP_StringToPString( std::string& inString, unsigned char *outString);

Since your member function CP_StringToPstring is static, the parameters in that function, inString and outString should be declared as static too.

The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.

You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.

Where can I find error log files?

This will defiantly help you,

https://davidwinter.me/enable-php-error-logging/

OR

In php.ini: (vim /etc/php.ini Or Sudo vim /usr/local/etc/php/7.1/php.ini)

display_errors = Off

log_errors = On

error_log = /var/log/php-errors.log

Make the log file, and writable by www-data:

sudo touch /var/log/php-errors.log

/var/log/php-errors.log

sudo chown :www

Thanks,

Basic text editor in command prompt?

notepad filename.extension will open notepad editor

How to implement 2D vector array?

I use this piece of code . works fine for me .copy it and run on your computer. you'll understand by yourself .

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector <vector <int> > matrix;
    size_t row=3 , col=3 ;
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            vector <int> colVector ;
            matrix.push_back(colVector) ;
            matrix.at(i).push_back(cnt++) ;
        }
    }
    matrix.at(1).at(1) = 0;     //matrix.at(columns).at(rows) = intValue 
    //printing all elements
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            cout<<matrix[i][j] <<" " ;
        }
        cout<<endl ;
    }
}

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

MySQL makes a difference between "localhost" and "127.0.0.1".

It might be possible that 'root'@'localhost' is not allowed because there is an entry in the user table that will only allow root login from 127.0.0.1.

This could also explain why some application on your server can connect to the database and some not because there are different ways of connecting to the database. And you currently do not allow it through "localhost".

Oracle database: How to read a BLOB?

If you're interested to get the plaintext (body part) from a BLOB, you could use the CTX_DOC package.

For example, the CTX_DOC.FILTER procedure can "generate either a plain text or a HTML version of a document". Be aware that CTX_DOC.FILTER requires an index on the BLOB column. If you don't want that, you could use the CTX_DOC.POLICY_FILTER procedure instead, which doesn't require an index.

Git: How do I list only local branches?

One of the most straightforward ways to do it is

git for-each-ref --format='%(refname:short)' refs/heads/

This works perfectly for scripts as well.

How many values can be represented with n bits?

There's an easier way to think about this. Start with 1 bit. This can obviously represent 2 values (0 or 1). What happens when we add a bit? We can now represent twice as many values: the values we could represent before with a 0 appended and the values we could represent before with a 1 appended.

So the the number of values we can represent with n bits is just 2^n (2 to the power n)