Programs & Examples On #Memory layout

Struct memory layout in C

It's implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is:

  • Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.)
  • If necessary, padding is added before each struct member, to ensure correct alignment.
  • Each primitive type T requires an alignment of sizeof(T) bytes.

So, given the following struct:

struct ST
{
   char ch1;
   short s;
   char ch2;
   long long ll;
   int i;
};
  • ch1 is at offset 0
  • a padding byte is inserted to align...
  • s at offset 2
  • ch2 is at offset 4, immediately after s
  • 3 padding bytes are inserted to align...
  • ll at offset 8
  • i is at offset 16, right after ll
  • 4 padding bytes are added at the end so that the overall struct is a multiple of 8 bytes. I checked this on a 64-bit system: 32-bit systems may allow structs to have 4-byte alignment.

So sizeof(ST) is 24.

It can be reduced to 16 bytes by rearranging the members to avoid padding:

struct ST
{
   long long ll; // @ 0
   int i;        // @ 8
   short s;      // @ 12
   char ch1;     // @ 14
   char ch2;     // @ 15
} ST;

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

For camera access use:

<key>NSCameraUsageDescription</key>
<string>Camera Access Warning</string>

Full-screen iframe with a height of 100%

You can can call a function which will calculate the iframe's body hieght when the iframe is loaded:

<script type="text/javascript">
    function iframeloaded(){
       var lastHeight = 0, curHeight = 0, $frame = $('iframe:eq(0)');
       curHeight = $frame.contents().find('body').height();
       if ( curHeight != lastHeight ) {
           $frame.css('height', (lastHeight = curHeight) + 'px' );
       }
    }
</script>

<iframe onload="iframeloaded()" src=...>

How to pass argument to Makefile from command line?

Much easier aproach. Consider a task:

provision:
        ansible-playbook -vvvv \
        -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory \
        --private-key=.vagrant/machines/default/virtualbox/private_key \
        --start-at-task="$(AT)" \
        -u vagrant playbook.yml

Now when I want to call it I just run something like:

AT="build assets" make provision

or just:

make provision in this case AT is an empty string

javascript remove "disabled" attribute from html input

method 1 <input type="text" onclick="this.disabled=false;" disabled>
<hr>
method 2 <input type="text" onclick="this.removeAttribute('disabled');" disabled>
<hr>
method 3 <input type="text" onclick="this.removeAttribute('readonly');" readonly>

code of the previous answers don't seem to work in inline mode, but there is a workaround: method 3.

see demo https://jsfiddle.net/eliz82/xqzccdfg/

Android ADB stop application command like "force-stop" for non rooted device

If you have a rooted device you can use kill command

Connect to your device with adb:

adb shell

Once the session is established, you have to escalade privileges:

su

Then

ps

will list running processes. Note down the PID of the process you want to terminate. Then get rid of it

kill PID

Replace \n with actual new line in Sublime Text

Fool proof method (no RegEx and Ctrl+Enter didn't work for me as it was just jumping to next Find):

First, select an occurrence of \n and hit Ctrl+H (brings up the Replace... dialogue, also accessible through Find -> Replace... menu). This populates the Find what field.

Go to the end of any line of your file (press End if your keyboard has it) and select the end of line by holding down Shift and pressing ? (right arrow) EXACTLY once. Then copy-paste this into the Replace with field.

(the animation is for finding true new lines; works the same for replacing them)

enter image description here

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

How can I disable inherited css styles?

Give the div you don't want him inheriting the property background too.

Save modifications in place with awk

In case you want an awk-only solution without creating a temporary file and usable with version!=(gawk 4.1.0):

awk '{a[b++]=$0} END {for(c=0;c<=b;c++)print a[c]>ARGV[1]}' file

Compile Views in ASP.NET MVC

Build > Run Code Analysis

Hotkey : Alt+F11

Helped me catch Razor errors.

How can I turn a DataTable to a CSV?

To write to a file, I think the following method is the most efficient and straightforward: (You can add quotes if you want)

public static void WriteCsv(DataTable dt, string path)
{
    using (var writer = new StreamWriter(path)) {
        writer.WriteLine(string.Join(",", dt.Columns.Cast<DataColumn>().Select(dc => dc.ColumnName)));
        foreach (DataRow row in dt.Rows) {
            writer.WriteLine(string.Join(",", row.ItemArray));
        }
    }
}

Rename multiple files in a folder, add a prefix (Windows)

This worked for me, first cd in the directory that you would like to change the filenames to and then run the following command:

Get-ChildItem | rename-item -NewName { "house chores-" + $_.Name }

Class has been compiled by a more recent version of the Java Environment

You can try this way

javac --release 8 yourClass.java

How do I get the SharedPreferences from a PreferenceActivity in Android?

import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);

Update

According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,

Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.

Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.

  1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.

  2. Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.

Shared Preferences:

The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.

(1) The recommended way is to use by the default mode, without specifying the file name

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

(2) Here is how you get the instance when you specify the file name

public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.

Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:

int storedPreference = preferences.getInt("storedInt", 0);

To store values in the preference file SharedPreference.Editor object has to be used. Editor is a nested interface in the SharedPreference class.

SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

Editor also supports methods like remove() and clear() to delete the preference values from the file.

Activity Preferences:

The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.

Following is the code to get preferences

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);

The code to store values is also the same as in case of shared preferences.

SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.

To see some more examples check Android's Data Storage post on developers site.

How to convert int to float in C?

You are doing integer arithmetic, so there the result is correct. Try

percentage=((double)number/total)*100;

BTW the %f expects a double not a float. By pure luck that is converted here, so it works out well. But generally you'd mostly use double as floating point type in C nowadays.

Batch Script to Run as Administrator

Following is a work-around:

  1. Create a shortcut of the .bat file
  2. Open the properties of the shortcut. Under the shortcut tab, click on advanced.
  3. Tick "Run as administrator"

Running the shortcut will execute your batch script as administrator.

Relative paths in Python

What worked for me is using sys.path.insert. Then I specified the directory I needed to go. For example I just needed to go up one directory.

import sys
sys.path.insert(0, '../')

Printing chars and their ASCII-code in C

This prints out all ASCII values:

int main()
{
    int i;
    i=0;
    do
    {
        printf("%d %c \n",i,i);
        i++;
    }
    while(i<=255);
    return 0;
}

and this prints out the ASCII value for a given character:

int main()
{
    int e;
    char ch;
    clrscr();
    printf("\n Enter a character : ");
    scanf("%c",&ch);
    e=ch;
    printf("\n The ASCII value of the character is : %d",e);
    getch();
    return 0;
}

video as site background? HTML 5

First, your HTML markup looks like this:

<video id="awesome_video" src="first_video.mp4" autoplay />

Second, your JavaScript code will look like this:

<script type="text/javascript">
  var index = 1,
      playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
      video = document.getElementById('awesome_video');

  video.addEventListener('ended', rotate_video, false);

  function rotate_video() {
    video.setAttribute('src', playlist[index]);
    video.load();
    index++;
    if (index >= playlist.length) { index = 0; }
  }
</script>

And last but not least, your CSS:

#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

Replace string within file contents

with open('Stud.txt','r') as f:
    newlines = []
    for line in f.readlines():
        newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
    for line in newlines:
        f.write(line)

How to detect the physical connected state of a network cable/connector?

There exists two daemons that detect these events:

ifplugd and netplugd

What is the difference between localStorage, sessionStorage, session and cookies?

LocalStorage:

  • Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie.

  • The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.

  • The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

  • It works on same-origin policy. So, data stored will only be available on the same origin.

Cookies:

  • We can set the expiration time for each cookie

  • The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

  • The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

sessionStorage:

  • It is similar to localStorage.
  • Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted The data is available only inside the window/tab in which it was set.

  • The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Regular expression for address field validation

Here is the approach I have taken to finding addresses using regular expressions:

A set of patterns is useful to find many forms that we might expect from an address starting with simply a number followed by set of strings (ex. 1 Basic Road) and then getting more specific such as looking for "P.O. Box", "c/o", "attn:", etc.

Below is a simple test in python. The test will find all the addresses but not the last 4 items which are company names. This example is not comprehensive, but can be altered to suit your needs and catch examples you find in your data.

import re
strings = [
    '701 FIFTH AVE',
    '2157 Henderson Highway',
    'Attn: Patent Docketing',
    'HOLLYWOOD, FL 33022-2480',
    '1940 DUKE STREET',
    '111 MONUMENT CIRCLE, SUITE 3700',
    'c/o Armstrong Teasdale LLP',
    '1 Almaden Boulevard',
    '999 Peachtree Street NE',
    'P.O. BOX 2903',
    '2040 MAIN STREET',
    '300 North Meridian Street',
    '465 Columbus Avenue',
    '1441 SEAMIST DR.',
    '2000 PENNSYLVANIA AVENUE, N.W.',
    '465 Columbus Avenue',
    '28 STATE STREET',
    'P.O, Drawer 800889.',
    '2200 CLARENDON BLVD.',
    '840 NORTH PLANKINTON AVENUE',
    '1025 Connecticut Avenue, NW',
    '340 Commercial Street',
    '799 Ninth Street, NW',
    '11318 Lazarro Ln',
    'P.O, Box 65745',
    'c/o Ballard Spahr LLP',
    '8210 SOUTHPARK TERRACE',
    '1130 Connecticut Ave., NW, Suite 420',
    '465 Columbus Avenue',
    "BANNER & WITCOFF , LTD",
    "CHIP LAW GROUP",
    "HAMMER & ASSOCIATES, P.C.",
    "MH2 TECHNOLOGY LAW GROUP, LLP",
]

patterns = [
    "c\/o [\w ]{2,}",
    "C\/O [\w ]{2,}",
    "P.O\. [\w ]{2,}",
    "P.O\, [\w ]{2,}",
    "[\w\.]{2,5} BOX [\d]{2,8}",
    "^[#\d]{1,7} [\w ]{2,}",
    "[A-Z]{2,2} [\d]{5,5}",
    "Attn: [\w]{2,}",
    "ATTN: [\w]{2,}",
    "Attention: [\w]{2,}",
    "ATTENTION: [\w]{2,}"
]
contact_list = []
total_count = len(strings)
found_count = 0
for string in strings:
    pat_no = 1
    for pattern in patterns:
        match = re.search(pattern, string.strip())
        if match:
            print("Item found: " + match.group(0) + " | Pattern no: " + str(pat_no))
            found_count += 1
        pat_no += 1

print("-- Total: " + str(total_count) + " Found: " + str(found_count)) 

Vertically aligning text next to a radio button

I think this is what you might be asking for

http://jsbin.com/ixowuw/2/

CSS

label{
  font-size:18px;
  vertical-align: middle;
}

input[type="radio"]{
  vertical-align: middle;
}

HTML

<span>
  <input type="radio" id="oddsPref" name="oddsPref" value="decimal" />
  <label>Decimal</label>
</span>

How to assign an exec result to a sql variable?

From the documentation (assuming that you use SQL-Server):

USE AdventureWorks;
GO
DECLARE @returnstatus nvarchar(15);
SET @returnstatus = NULL;
EXEC @returnstatus = dbo.ufnGetSalesOrderStatusText @Status = 2;
PRINT @returnstatus;
GO

So yes, it should work that way.

How do I get the Session Object in Spring?

Since you're using Spring, stick with Spring, don't hack it yourself like the other post posits.

The Spring manual says:

You shouldn't interact directly with the HttpSession for security purposes. There is simply no justification for doing so - always use the SecurityContextHolder instead.

The suggested best practice for accessing the session is:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
  String username = ((UserDetails)principal).getUsername();
} else {
  String username = principal.toString();
}

The key here is that Spring and Spring Security do all sorts of great stuff for you like Session Fixation Prevention. These things assume that you're using the Spring framework as it was designed to be used. So, in your servlet, make it context aware and access the session like the above example.

If you just need to stash some data in the session scope, try creating some session scoped bean like this example and let autowire do its magic. :)

How to detect DataGridView CheckBox event change?

following Killercam'answer, My code

private void dgvProducts_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        dgvProducts.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }

and :

private void dgvProducts_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (dgvProducts.DataSource != null)
        {
            if (dgvProducts.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "True")
            {
                //do something
            }
            else
            {
               //do something
            }
        }
    }

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

Using pattern and check validate:

var input = '33/15/2000';

var pattern = /^((0[1-9]|[12][0-9]|3[01])(\/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(\/)(02))|((0[1-9]|[12][0-9]|3[0])(\/)(0[469]|11))(\/)\d{4}$/;

alert(pattern.test(input));

Make JQuery UI Dialog automatically grow or shrink to fit its contents

If you need it to work in IE7, you can't use the undocumented, buggy, and unsupported {'width':'auto'} option. Instead, add the following to your .dialog():

'open': function(){ $(this).dialog('option', 'width', this.scrollWidth) }

Whether .scrollWidth includes the right-side padding depends on the browser (Firefox differs from Chrome), so you can either add a subjective "good enough" number of pixels to .scrollWidth, or replace it with your own width-calculation function.

You might want to include width: 0 among your .dialog() options, since this method will never decrease the width, only increase it.

Tested to work in IE7, IE8, IE9, IE10, IE11, Firefox 30, Chrome 35, and Opera 22.

Java HTTPS client certificate authentication

Other answers show how to globally configure client certificates. However if you want to programmatically define the client key for one particular connection, rather than globally define it across every application running on your JVM, then you can configure your own SSLContext like so:

String keyPassphrase = "";

KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("cert-key-pair.pfx"), keyPassphrase.toCharArray());

SSLContext sslContext = SSLContexts.custom()
        .loadKeyMaterial(keyStore, null)
        .build();

HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
HttpResponse response = httpClient.execute(new HttpGet("https://example.com"));

SQL Server equivalent of MySQL's NOW()?

You can also use CURRENT_TIMESTAMP, if you feel like being more ANSI compliant (though if you're porting code between database vendors, that'll be the least of your worries). It's exactly the same as GetDate() under the covers (see this question for more on that).

There's no ANSI equivalent for GetUTCDate(), however, which is probably the one you should be using if your app operates in more than a single time zone ...

TortoiseSVN icons not showing up under Windows 7

I had the same issue as the OP: Win 7 (x64), TortoiseSVN (x64), and DropBox (x86). The info from some of the other answers gave me all the info. I've only ever had the x64 version of TSVN installed on this machine.

In my case TSVN and DropBox were installed the same day I did the OS install and the overlays worked fine until a couple of days ago. I did nothing involving changing settings for either app to cause them to stop working.

Here is what I had in the icon overlay registry section after the problem started (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\ShellIconOverlayIdentifiers):

  1. DropboxExt1
  2. DropboxExt2
  3. DropboxExt3
  4. EnhancedStorageShell
  5. Offline Files
  6. SharingPrivate
  7. TortoiseAdded
  8. TortoiseConflict
  9. TortoiseDeleted
  10. TortoiseIgnored
  11. TortoiseLocked
  12. TortoiseModified
  13. TortoiseNormal
  14. TortoiseReadOnly
  15. TortoiseUnversioned

I verified that only the overlays corresponding to the first 11 entries display in Explorer. When I modified the order of above entries by adding 'z' to the start of some of them, again only the first 11 overlays (under the updated order) would display.

With the above I had everything I needed to solve the problem (either rename or or delete entries so that the TSVN entries I want working are <= #11 on the list). Below deals with wondering why this suddenly happened.

I know that based on the overlays that worked prior to a couple of days ago, keys 1-3, 7-9, 12-13 were all <= 11 in the list (not sure if overlay #14 ever worked since I never had files w/ read-only status. #15 never worked on this machine so i know it was never in the top 11). I also assume the block of TSVN keys move up/down in unison, therefore they were bumped down either two or three places (* see below). This implies that 2-3 items were added between the DropBox & TSVN blocks. The three that are there now are added by Windows and I would assume they'd be there as soon as the OS installed.

Is the list of 15 overlays determined at run-time? Seems like the overlay handlers might sometimes tell the windows shell that there are no icons to add to the list. Possibly some settings I messed with a couple of days ago related to file sharing and file encryption caused some of those items at the 4-6 spots to become "activated" and push the SVN ones down.

In the end I deleted a couple of entries and moved some, so my final list looks like this:

  1. DropboxExt1
  2. DropboxExt2
  3. DropboxExt3
  4. SharingPrivate (i want this to show up)
  5. TortoiseAdded
  6. TortoiseConflict
  7. TortoiseDeleted
  8. TortoiseModified
  9. TortoiseNormal
  10. TortoiseReadOnly
  11. TortoiseUnversioned
  12. zOffline Files (i don't use Sync Center, or "Offline Files" so I don't care about this)
  13. zEnhancedStorageShell (don't really know what Enhanced Storage is, don't think I need this)

Time in milliseconds in C

Here is what I write to get the timestamp in millionseconds.

#include<sys/time.h>

long long timeInMilliseconds(void) {
    struct timeval tv;

    gettimeofday(&tv,NULL);
    return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}

Left Join without duplicate rows from left table

Try an OUTER APPLY

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    OUTER APPLY
    (
        SELECT TOP 1 *
        FROM tbl_Media M 
        WHERE M.Content_Id = C.Content_Id 
    ) m
ORDER BY 
    C.Content_DatePublished ASC

Alternatively, you could GROUP BY the results

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
GROUP BY
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
ORDER BY
    C.Content_DatePublished ASC

The OUTER APPLY selects a single row (or none) that matches each row from the left table.

The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

JPA entity without id

If there is a one to one mapping between entity and entity_property you can use entity_id as the identifier.

GetElementByID - Multiple IDs

Dunno if something like this works in js, in PHP and Python which i use quite often it is possible. Maybe just use for loop like:

function doStuff(){
    for(i=1; i<=4; i++){
        var i = document.getElementById("myCiricle"+i);
    }
}

Why is setState in reactjs Async instead of Sync?

You can call a function after the state value has updated:

this.setState({foo: 'bar'}, () => { 
    // Do something here. 
});

Also, if you have lots of states to update at once, group them all within the same setState:

Instead of:

this.setState({foo: "one"}, () => {
    this.setState({bar: "two"});
});

Just do this:

this.setState({
    foo: "one",
    bar: "two"
});

Mocking HttpClient in unit tests

You could use RichardSzalay MockHttp library which mocks the HttpMessageHandler and can return an HttpClient object to be used during tests.

GitHub MockHttp

PM> Install-Package RichardSzalay.MockHttp

From the GitHub documentation

MockHttp defines a replacement HttpMessageHandler, the engine that drives HttpClient, that provides a fluent configuration API and provides a canned response. The caller (eg. your application's service layer) remains unaware of its presence.

Example from GitHub

 var mockHttp = new MockHttpMessageHandler();

// Setup a respond for the user api (including a wildcard in the URL)
mockHttp.When("http://localhost/api/user/*")
        .Respond("application/json", "{'name' : 'Test McGee'}"); // Respond with JSON

// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();

var response = await client.GetAsync("http://localhost/api/user/1234");
// or without async: var response = client.GetAsync("http://localhost/api/user/1234").Result;

var json = await response.Content.ReadAsStringAsync();

// No network connection required
Console.Write(json); // {'name' : 'Test McGee'}

How to swap String characters in Java?

'In' a string, you cant. Strings are immutable. You can easily create a second string with:

 String second = first.replaceFirst("(.)(.)", "$2$1");

How to make correct date format when writing data to Excel

This worked for me:

hoja_trabajo.Cells[i + 2, j + 1] = fecha.ToString("dd-MMM-yyyy").Replace(".", "");

Button Width Match Parent

The Following code work for me

       ButtonTheme(
            minWidth: double.infinity,
            child: RaisedButton(child: Text("Click!!", style: TextStyle(color: Colors.white),), color: Colors.pink, onPressed: () {}))

A free tool to check C/C++ source code against a set of coding standards?

The only tool I know is Vera. Haven't used it, though, so can't comment how viable it is. Demo looks promising.

PostgreSQL psql terminal command

Use \x Example from postgres manual:

    postgres=# \x
    postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
    -[ RECORD 1 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
    calls      | 3000
    total_time | 20.716706
    rows       | 3000
    -[ RECORD 2 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
    calls      | 3000
    total_time | 17.1107649999999
    rows       | 3000
    -[ RECORD 3 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
    calls      | 3000
    total_time | 0.645601
    rows       | 3000

Flask - Calling python function on button OnClick event

Easiest solution

<button type="button" onclick="window.location.href='{{ url_for( 'move_forward') }}';">Forward</button>

New line character in VB.Net?

In asp.net for giving new line character in string you should use <br> .

For window base application Environment.NewLine will work fine.

How can I explicitly free memory in Python?

The del statement might be of use, but IIRC it isn't guaranteed to free the memory. The docs are here ... and a why it isn't released is here.

I have heard people on Linux and Unix-type systems forking a python process to do some work, getting results and then killing it.

This article has notes on the Python garbage collector, but I think lack of memory control is the downside to managed memory

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

Memory errors and list limits?

There is no memory limit imposed by Python. However, you will get a MemoryError if you run out of RAM. You say you have 20301 elements in the list. This seems too small to cause a memory error for simple data types (e.g. int), but if each element itself is an object that takes up a lot of memory, you may well be running out of memory.

The IndexError however is probably caused because your ListTemp has got only 19767 elements (indexed 0 to 19766), and you are trying to access past the last element.

It is hard to say what you can do to avoid hitting the limit without knowing exactly what it is that you are trying to do. Using numpy might help. It looks like you are storing a huge amount of data. It may be that you don't need to store all of it at every stage. But it is impossible to say without knowing.

Getting 404 Not Found error while trying to use ErrorDocument

When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,

 ErrorDocument 404 /yourfoldernames/errors/404.html

How do I get a background location update every n minutes in my iOS application?

I did write an app using Location services, app must send location every 10s. And it worked very well.

Just use the "allowDeferredLocationUpdatesUntilTraveled:timeout" method, following Apple's doc.

What I did are:

Required: Register background mode for update Location.

1. Create LocationManger and startUpdatingLocation, with accuracy and filteredDistance as whatever you want:

-(void) initLocationManager    
{
    // Create the manager object
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    _locationManager.delegate = self;
    // This is the most important property to set for the manager. It ultimately determines how the manager will
    // attempt to acquire location and thus, the amount of power that will be consumed.
    _locationManager.desiredAccuracy = 45;
    _locationManager.distanceFilter = 100;
    // Once configured, the location manager must be "started".
    [_locationManager startUpdatingLocation];
}

2. To keep app run forever using allowDeferredLocationUpdatesUntilTraveled:timeout method in background, you must restart updatingLocation with new parameter when app moves to background, like this:

- (void)applicationWillResignActive:(UIApplication *)application {
     _isBackgroundMode = YES;

    [_locationManager stopUpdatingLocation];
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [_locationManager setDistanceFilter:kCLDistanceFilterNone];
    _locationManager.pausesLocationUpdatesAutomatically = NO;
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
    [_locationManager startUpdatingLocation];
 }

3. App gets updatedLocations as normal with locationManager:didUpdateLocations: callback:

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//  store data
    CLLocation *newLocation = [locations lastObject];
    self.userLocation = newLocation;

   //tell the centralManager that you want to deferred this updatedLocation
    if (_isBackgroundMode && !_deferringUpdates)
    {
        _deferringUpdates = YES;
        [self.locationManager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:10];
    }
}

4. But you should handle the data in then locationManager:didFinishDeferredUpdatesWithError: callback for your purpose

- (void) locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error {

     _deferringUpdates = NO;

     //do something 
}

5. NOTE: I think we should reset parameters of LocationManager each time app switches between background/forground mode.

localhost refused to connect Error in visual studio

I was having this issue and solved it by closing all open instances of Visual Studio.

How can I make a CSS table fit the screen width?

CSS:

table { 
    table-layout:fixed;
}

Update with CSS from the comments:

td { 
    overflow: hidden; 
    text-overflow: ellipsis; 
    word-wrap: break-word;
}

For mobile phones I leave the table width but assign an additional CSS class to the table to enable horizontal scrolling (table will not go over the mobile screen anymore):

@media only screen and (max-width: 480px) {
    /* horizontal scrollbar for tables if mobile screen */
    .tablemobile {
        overflow-x: auto;
        display: block;
    }
}

Sufficient enough.

How to calculate age in T-SQL with years, months, and days

There is an easy way, based on the hours between the two days BUT with the end date truncated.

SELECT CAST(DATEDIFF(hour,Birthdate,CAST(GETDATE() as Date))/8766.0 as INT) AS Age FROM <YourTable>

This one has proven to be extremely accurate and reliable. If it weren't for the inner CAST on the GETDATE() it might flip the birthday a few hours before midnight but, with the CAST, it is dead on with the age changing over at exactly midnight.

Simplest way to download and unzip files in Node.js cross-platform?

Node has builtin support for gzip and deflate via the zlib module:

var zlib = require('zlib');

zlib.gunzip(gzipBuffer, function(err, result) {
    if(err) return console.error(err);

    console.log(result);
});

Edit: You can even pipe the data directly through e.g. Gunzip (using request):

var request = require('request'),
    zlib = require('zlib'),
    fs = require('fs'),
    out = fs.createWriteStream('out');

// Fetch http://example.com/foo.gz, gunzip it and store the results in 'out'
request('http://example.com/foo.gz').pipe(zlib.createGunzip()).pipe(out);

For tar archives, there is Isaacs' tar module, which is used by npm.

Edit 2: Updated answer as zlib doesn't support the zip format. This will only work for gzip.

JPA Query selecting only specific columns without using Criteria Query?

You can use something like this:

List<Object[]> list = em.createQuery("SELECT p.field1, p.field2 FROM Entity p").getResultList();

then you can iterate over it:

for (Object[] obj : list){
    System.out.println(obj[0]);
    System.out.println(obj[1]);
}

BUT if you have only one field in query, you get a list of the type not from Object[]

What is the difference between And and AndAlso in VB.NET?

If Bool1 And Bool2 Then

Evaluates both Bool1 and Bool2

If Bool1 AndAlso Bool2 Then

Evaluates Bool2 if and only if Bool1 is true.

Sending mail from Python using SMTP

The example code which i did for send mail using SMTP.

import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "sender@email"
receiver_email = "receiver@email"
password = "<your password here>"
message = """ Subject: Hi there

This message is sent from Python."""


# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
server = smtplib.SMTP(smtp_server,port)

try:
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit()

How to trigger button click in MVC 4

yo can try this code

@using (Html.BeginForm("SignUp", "Account", FormMethod.Post)){<fieldset>
    <legend>Sign Up</legend>
    <table>
        <tr>
            <td>
                @Html.Label("User Name")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Username)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Email")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Email)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Password")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Password)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Confirm Password")
            </td>
            <td>
                @Html.Password("txtPassword")
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" name="btnSubmit" value="Sign Up" />
            </td>
        </tr>
    </table>
</fieldset>}

How to check task status in Celery?

I found helpful information in the

Celery Project Workers Guide inspecting-workers

For my case, I am checking to see if Celery is running.

inspect_workers = task.app.control.inspect()
if inspect_workers.registered() is None:
    state = 'FAILURE'
else:
    state = str(task.state) 

You can play with inspect to get your needs.

How to go from one page to another page using javascript?

To simply redirect a browser using javascript:

window.location.href = "http://example.com/new_url";

To redirect AND submit a form (i.e. login details), requires no javascript:

<form action="/new_url" method="POST">
   <input name="username">
   <input type="password" name="password">
   <button type="submit">Submit</button>
</form>

Validate phone number with JavaScript

Try this js function. Returns true if it matches and false if it fails Ref

_x000D_
_x000D_
function ValidatePhoneNumber(phone) {_x000D_
        return /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/.test(phone);_x000D_
}
_x000D_
_x000D_
_x000D_

PostgreSQL - max number of parameters in "IN" clause?

This is not really an answer to the present question, however it might help others too.

At least I can tell there is a technical limit of 32767 values (=Short.MAX_VALUE) passable to the PostgreSQL backend, using Posgresql's JDBC driver 9.1.

This is a test of "delete from x where id in (... 100k values...)" with the postgresql jdbc driver:

Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 100000
    at org.postgresql.core.PGStream.SendInteger2(PGStream.java:201)

Git command to display HEAD commit id?

You can use

git log -g branchname

to see git reflog information formatted like the git log output

How to view method information in Android Studio?

I'm using Visual Studio too much and I want to see params when I click on Ctrl+Space that's why I'm using Visual Studio keys. To change keymap to VS keymap: enter image description here enter image description here

UL list style not applying

All I can think of is that something is over-riding this afterwards.

You are including the reset styles first, right?

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Insert an element at a specific index in a list and return the updated list

The shortest I got: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

How can I clear the input text after clicking

function submitForm()
{
    if (testSubmit())
    {
        document.forms["myForm"].submit(); //first submit
        document.forms["myForm"].reset(); //and then reset the form values
    }
} </script> <body>
<form method="get" name="myForm">

    First Name: <input type="text" name="input1"/>
    <br/>
    Last Name: <input type="text" name="input2"/>
    <br/>
    <input type="button" value="Submit" onclick="submitForm()"/>
</form>

How do I crop an image in Java?

The solution I found most useful for cropping a buffered image uses the getSubImage(x,y,w,h);

My cropping routine ended up looking like this:

  private BufferedImage cropImage(BufferedImage src, Rectangle rect) {
      BufferedImage dest = src.getSubimage(0, 0, rect.width, rect.height);
      return dest; 
   }

What port number does SOAP use?

SOAP (communication protocol) for communication between applications. Uses HTTP (port 80) or SMTP ( port 25 or 2525 ), for message negotiation and transmission.

PostgreSQL delete with inner join

This worked for me:

DELETE from m_productprice
WHERE  m_pricelist_version_id='1000020'
       AND m_product_id IN (SELECT m_product_id
                            FROM   m_product
                            WHERE  upc = '7094'); 

Spring 3 MVC accessing HttpRequest from controller

Spring MVC will give you the HttpRequest if you just add it to your controller method signature:

For instance:

/**
 * Generate a PDF report...
 */
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
        @PathVariable("objectId") Long objectId, 
        HttpServletRequest request, 
        HttpServletResponse response) {

    // ...
    // Here you can use the request and response objects like:
    // response.setContentType("application/pdf");
    // response.getOutputStream().write(...);

}

As you see, simply adding the HttpServletRequest and HttpServletResponse objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession object too.

EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.

I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.

How do I choose grid and block dimensions for CUDA kernels?

There are two parts to that answer (I wrote it). One part is easy to quantify, the other is more empirical.

Hardware Constraints:

This is the easy to quantify part. Appendix F of the current CUDA programming guide lists a number of hard limits which limit how many threads per block a kernel launch can have. If you exceed any of these, your kernel will never run. They can be roughly summarized as:

  1. Each block cannot have more than 512/1024 threads in total (Compute Capability 1.x or 2.x and later respectively)
  2. The maximum dimensions of each block are limited to [512,512,64]/[1024,1024,64] (Compute 1.x/2.x or later)
  3. Each block cannot consume more than 8k/16k/32k/64k/32k/64k/32k/64k/32k/64k registers total (Compute 1.0,1.1/1.2,1.3/2.x-/3.0/3.2/3.5-5.2/5.3/6-6.1/6.2/7.0)
  4. Each block cannot consume more than 16kb/48kb/96kb of shared memory (Compute 1.x/2.x-6.2/7.0)

If you stay within those limits, any kernel you can successfully compile will launch without error.

Performance Tuning:

This is the empirical part. The number of threads per block you choose within the hardware constraints outlined above can and does effect the performance of code running on the hardware. How each code behaves will be different and the only real way to quantify it is by careful benchmarking and profiling. But again, very roughly summarized:

  1. The number of threads per block should be a round multiple of the warp size, which is 32 on all current hardware.
  2. Each streaming multiprocessor unit on the GPU must have enough active warps to sufficiently hide all of the different memory and instruction pipeline latency of the architecture and achieve maximum throughput. The orthodox approach here is to try achieving optimal hardware occupancy (what Roger Dahl's answer is referring to).

The second point is a huge topic which I doubt anyone is going to try and cover it in a single StackOverflow answer. There are people writing PhD theses around the quantitative analysis of aspects of the problem (see this presentation by Vasily Volkov from UC Berkley and this paper by Henry Wong from the University of Toronto for examples of how complex the question really is).

At the entry level, you should mostly be aware that the block size you choose (within the range of legal block sizes defined by the constraints above) can and does have a impact on how fast your code will run, but it depends on the hardware you have and the code you are running. By benchmarking, you will probably find that most non-trivial code has a "sweet spot" in the 128-512 threads per block range, but it will require some analysis on your part to find where that is. The good news is that because you are working in multiples of the warp size, the search space is very finite and the best configuration for a given piece of code relatively easy to find.

How to determine an interface{} value's "real" type?

Type switches can also be used with reflection stuff:

var str = "hello!"
var obj = reflect.ValueOf(&str)

switch obj.Elem().Interface().(type) {
case string:
    log.Println("obj contains a pointer to a string")
default:
    log.Println("obj contains something else")
}

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

In absence of a white-list feature you have to make the "all" or "nothing" Choice. You can disable mixed content blocking completely.


The Nothing Choice

You will need to permanently disable mixed content blocking for the current active profile.

In the "Awesome Bar," type "about:config". If this is your first time you will get the "This might void your warranty!" message.

Yes you will be careful. Yes you promise!

Find security.mixed_content.block_active_content. Set its value to false.


The All Choice

iDevelApp's answer is awesome.

MySQL timezone change?

The easiest way to do this, as noted by Umar is, for example

mysql> SET GLOBAL time_zone = 'America/New_York';

Using the named timezone is important for timezone that has a daylights saving adjustment. However, for some linux builds you may get the following response:

#1298 - Unknown or incorrect time zone

If you're seeing this, you may need to run a tzinfo_to_sql translation... it's easy to do, but not obvious. From the linux command line type in:

mysql_tzinfo_to_sql /usr/share/zoneinfo/|mysql -u root mysql -p

Provide your root password (MySQL root, not Linux root) and it will load any definitions in your zoneinfo into mysql. You can then go back and run your

mysql> SET GLOBAL time_zone = timezone;

good example of Javadoc

Download the sources of Lucene and see how they do it. They have good JavaDocs.

jquery beforeunload when closing (not leaving) the page?

Try javascript into your Ajax

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Reference link

Example 2:

document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){
    window.btn_clicked = true;
};
window.onbeforeunload = function(){
    if(!window.btn_clicked){
        return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
    }
};

Here it will alert the user every time he leaves the page, until he clicks on the button.

DEMO: http://jsfiddle.net/DerekL/GSWbB/show/

How to set a timeout on a http.request() in Node?

There is simpler method.

Instead of using setTimeout or working with socket directly,
We can use 'timeout' in the 'options' in client uses

Below is code of both server and client, in 3 parts.

Module and options part:

'use strict';

// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js

const assert = require('assert');
const http = require('http');

const options = {
    host: '127.0.0.1', // server uses this
    port: 3000, // server uses this

    method: 'GET', // client uses this
    path: '/', // client uses this
    timeout: 2000 // client uses this, timesout in 2 seconds if server does not respond in time
};

Server part:

function startServer() {
    console.log('startServer');

    const server = http.createServer();
    server
            .listen(options.port, options.host, function () {
                console.log('Server listening on http://' + options.host + ':' + options.port);
                console.log('');

                // server is listening now
                // so, let's start the client

                startClient();
            });
}

Client part:

function startClient() {
    console.log('startClient');

    const req = http.request(options);

    req.on('close', function () {
        console.log("got closed!");
    });

    req.on('timeout', function () {
        console.log("timeout! " + (options.timeout / 1000) + " seconds expired");

        // Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js#L27
        req.destroy();
    });

    req.on('error', function (e) {
        // Source: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js#L248
        if (req.connection.destroyed) {
            console.log("got error, req.destroy() was called!");
            return;
        }

        console.log("got error! ", e);
    });

    // Finish sending the request
    req.end();
}


startServer();

If you put all the above 3 parts in one file, "a.js", and then run:

node a.js

then, output will be:

startServer
Server listening on http://127.0.0.1:3000

startClient
timeout! 2 seconds expired
got closed!
got error, req.destroy() was called!

Hope that helps.

How to select the rows with maximum values in each group with dplyr?

More generally, I think you might want to get "top" of the rows that are sorted within a given group.

For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).

# Answering the question of getting row with max "value".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in descending order by "value" column.
  arrange( desc(value) ) %>% 
  # Pick the top 1 value
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

# Answering an extension of the question of 
# getting row with the max value of the lowest "C".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in ascending order by C, and then within that by 
  # descending order by "value" column.
  arrange( C, desc(value) ) %>% 
  # Pick the one top row based on the sort
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

Java parsing XML document gives "Content not allowed in prolog." error

Check any syntax problem in the XMl file. I've found this error when working on xsl/xsp with Cocoon and I define a variable using a non-existing node or something like that. Check the whole XML.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

You can't add reference to table that have already data inside.
Change:

user = models.OneToOneField(User)

to:

user = models.OneToOneField(User, default = "")

do:

python manage.py makemigrations
python manage.py migrate

change again:

user = models.OneToOneField(User)

do migration again:

python manage.py makemigrations
python manage.py migrate

Why do I get a "permission denied" error while installing a gem?

I had the same problem using rvm on Ubuntu, was fixed by setting the source on my terminal as a short-term solution:

source $HOME/.rvm/scripts/rvm

or

source /home/$USER/.rvm/scripts/rvm

and configure a default Ruby Version, 2.3.3 in my case.

rvm use 2.3.3 --default


And a long-term Solution is to add your source to your .bashrc file to permanently make Ubuntu look in .rvm for all the Ruby files.

Add:

source .rvm/scripts/rvm

into

$HOME/.bashrc file.

Windows command prompt log to a file

First method

For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.

Steps:

  1. type PowerShell in search area and click on "Windows PowerShell"

  2. If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)

  3. run the .bat file with following command

    PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt

This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.

Second method

You can use file redirection (>, >>) as suggest by Bali C above.

I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.

Elegant way to check for missing packages and install them?

Yes. If you have your list of packages, compare it to the output from installed.packages()[,"Package"] and install the missing packages. Something like this:

list.of.packages <- c("ggplot2", "Rcpp")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)

Otherwise:

If you put your code in a package and make them dependencies, then they will automatically be installed when you install your package.

Convert pandas Series to DataFrame

probably graded as a non-pythonic way to do this but this'll give the result you want in a line:

new_df = pd.DataFrame(zip(email,list))

Result:

               email               list
0   [email protected]    [1.0, 0.0, 0.0]
1   [email protected]    [2.0, 0.0, 0.0]
2   [email protected]    [1.0, 0.0, 0.0]
3   [email protected]    [4.0, 0.0, 3.0]
4   [email protected]    [1.0, 5.0, 0.0]

How to copy JavaScript object to new variable NOT by reference?

I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).

JSON.parse(JSON.stringify(json_original));

Documentation

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

string comparison in batch file

While @ajv-jsy's answer works most of the time, I had the same problem as @MarioVilas. If one of the strings to be compared contains a double quote ("), the variable expansion throws an error.

Example:

@echo off
SetLocal

set Lhs="
set Rhs="

if "%Lhs%" == "%Rhs%" echo Equal

Error:

echo was unexpected at this time.

Solution:

Enable delayed expansion and use ! instead of %.

@echo off
SetLocal EnableDelayedExpansion

set Lhs="
set Rhs="

if !Lhs! == !Rhs! echo Equal

:: Surrounding with double quotes also works but appears (is?) unnecessary.
if "!Lhs!" == "!Rhs!" echo Equal

I have not been able to break it so far using this technique. It works with empty strings and all the symbols I threw at it.

Test:

@echo off
SetLocal EnableDelayedExpansion

:: Test empty string
set Lhs=
set Rhs=
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

:: Test symbols
set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

How to Configure SSL for Amazon S3 bucket

Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/

Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.

@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.

Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

sql select with column name like

This will show you the table name and column name

select table_name,column_name from information_schema.columns
where column_name like '%breakfast%'

Convert character to ASCII code in JavaScript

str.charCodeAt(index)

Using charCodeAt() The following example returns 65, the Unicode value for A.

'ABC'.charCodeAt(0) // returns 65

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

Spark Dynamic allocation gives flexibility and allocates resources dynamically. In this number of min and max executors can be given. Also the number of executors that has to be launched at the starting of the application can also be given.

Read below on the same:

http://spark.apache.org/docs/latest/configuration.html#dynamic-allocation

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

In TorpedoQuery it look like this

Entity from = from(Entity.class);
where(from.getCode()).in("Joe", "Bob");
Query<Entity> select = select(from);

Callback functions in C++

There isn't an explicit concept of a callback function in C++. Callback mechanisms are often implemented via function pointers, functor objects, or callback objects. The programmers have to explicitly design and implement callback functionality.

Edit based on feedback:

In spite of the negative feedback this answer has received, it is not wrong. I'll try to do a better job of explaining where I'm coming from.

C and C++ have everything you need to implement callback functions. The most common and trivial way to implement a callback function is to pass a function pointer as a function argument.

However, callback functions and function pointers are not synonymous. A function pointer is a language mechanism, while a callback function is a semantic concept. Function pointers are not the only way to implement a callback function - you can also use functors and even garden variety virtual functions. What makes a function call a callback is not the mechanism used to identify and call the function, but the context and semantics of the call. Saying something is a callback function implies a greater than normal separation between the calling function and the specific function being called, a looser conceptual coupling between the caller and the callee, with the caller having explicit control over what gets called. It is that fuzzy notion of looser conceptual coupling and caller-driven function selection that makes something a callback function, not the use of a function pointer.

For example, the .NET documentation for IFormatProvider says that "GetFormat is a callback method", even though it is just a run-of-the-mill interface method. I don't think anyone would argue that all virtual method calls are callback functions. What makes GetFormat a callback method is not the mechanics of how it is passed or invoked, but the semantics of the caller picking which object's GetFormat method will be called.

Some languages include features with explicit callback semantics, typically related to events and event handling. For example, C# has the event type with syntax and semantics explicitly designed around the concept of callbacks. Visual Basic has its Handles clause, which explicitly declares a method to be a callback function while abstracting away the concept of delegates or function pointers. In these cases, the semantic concept of a callback is integrated into the language itself.

C and C++, on the other hand, does not embed the semantic concept of callback functions nearly as explicitly. The mechanisms are there, the integrated semantics are not. You can implement callback functions just fine, but to get something more sophisticated which includes explicit callback semantics you have to build it on top of what C++ provides, such as what Qt did with their Signals and Slots.

In a nutshell, C++ has what you need to implement callbacks, often quite easily and trivially using function pointers. What it does not have is keywords and features whose semantics are specific to callbacks, such as raise, emit, Handles, event +=, etc. If you're coming from a language with those types of elements, the native callback support in C++ will feel neutered.

Java String new line

Try:

System.out.println("I\nam\na\nboy");

How do I pipe or redirect the output of curl -v?

Your URL probably has ampersands in it. I had this problem, too, and I realized that my URL was full of ampersands (from CGI variables being passed) and so everything was getting sent to background in a weird way and thus not redirecting properly. If you put quotes around the URL it will fix it.

Why aren't programs written in Assembly more often?

ASM has poor legibility and isn't really maintainable compared to higher-level languages.

Also, there are many fewer ASM developers than for other more popular languages, such as C.

Furthermore, if you use a higher-level language and new ASM instructions become available (SSE for example), you just need to update your compiler and your old code can easily make use of the new instructions.

What if the next CPU has twice as many registers?

The converse of this question would be: What functionality do compilers provide?

I doubt you can/want to/should optimize your ASM better than gcc -O3 can.

Round number to nearest integer

For positives, try

int(x + 0.5)

To make it work for negatives too, try

int(x + (0.5 if x > 0 else -0.5))

int() works like a floor function and hence you can exploit this property. This is definitely the fastest way.

How to update Identity Column in SQL Server?

If got your question right you want to do something like

update table
set identity_column_name = some value

Let me tell you, it is not an easy process and it is not advisable to use it, as there may be some foreign key associated on it.

But here are steps to do it, Please take a back-up of table

Step 1- Select design view of the table

enter image description here

Step 2- Turn off the identity column

enter image description here

Now you can use the update query.

Now redo the step 1 and step 2 and Turn on the identity column

Reference

How can I get all the request headers in Django?

According to the documentation request.META is a "standard Python dictionary containing all available HTTP headers". If you want to get all the headers you can simply iterate through the dictionary.

Which part of your code to do this depends on your exact requirement. Anyplace that has access to request should do.

Update

I need to access it in a Middleware class but when i iterate over it, I get a lot of values apart from HTTP headers.

From the documentation:

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name.

(Emphasis added)

To get the HTTP headers alone, just filter by keys prefixed with HTTP_.

Update 2

could you show me how I could build a dictionary of headers by filtering out all the keys from the request.META variable which begin with a HTTP_ and strip out the leading HTTP_ part.

Sure. Here is one way to do it.

import re
regex = re.compile('^HTTP_')
dict((regex.sub('', header), value) for (header, value) 
       in request.META.items() if header.startswith('HTTP_'))

bash string compare to multiple correct values

Maybe you should better use a case for such lists:

case "$cms" in
  wordpress|meganto|typo3)
    do_your_else_case
    ;;
  *)
    do_your_then_case
    ;;
esac

I think for long such lists this is better readable.

If you still prefer the if you can do it with single brackets in two ways:

if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then

or

if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then

get size of json object

use this one

//for getting length of object
 int length = jsonObject.length();

or

//for getting length of array
 int length = jsonArray.length();

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

UPDATE will not do anything if the row does not exist.

Where as the INSERT OR REPLACE would insert if the row does not exist, or replace the values if it does.

UTF-8 text is garbled when form is posted as multipart/form-data

You do not use UTF-8 to encode text data for HTML forms. The html standard defines two encodings, and the relevant part of that standard is here. The "old" encoding, than handles ascii, is application/x-www-form-urlencoded. The new one, that works properly, is multipart/form-data.

Specifically, the form declaration looks like this:

 <FORM action="http://server.com/cgi/handle"
       enctype="multipart/form-data"
       method="post">
   <P>
   What is your name? <INPUT type="text" name="submit-name"><BR>
   What files are you sending? <INPUT type="file" name="files"><BR>
   <INPUT type="submit" value="Send"> <INPUT type="reset">
 </FORM>

And I think that's all you have to worry about - the webserver should handle it. If you are writing something that directly reads the InputStream from the web client, then you will need to read RFC 2045 and RFC 2046.

What is the JavaScript equivalent of var_dump or print_r in PHP?

I wrote this JS function dump() to work like PHP's var_dump(). To show the contents of the variable in an alert window: dump(variable) To show the contents of the variable in the web page: dump(variable, 'body') To just get a string of the variable: dump(variable, 'none')

/* repeatString() returns a string which has been repeated a set number of times */
function repeatString(str, num) {
    out = '';
    for (var i = 0; i < num; i++) {
        out += str;
    }
    return out;
}

/*
dump() displays the contents of a variable like var_dump() does in PHP. dump() is
better than typeof, because it can distinguish between array, null and object.
Parameters:
    v:              The variable
    howDisplay:     "none", "body", "alert" (default)
    recursionLevel: Number of times the function has recursed when entering nested
                    objects or arrays. Each level of recursion adds extra space to the
                    output to indicate level. Set to 0 by default.
Return Value:
    A string of the variable's contents
Limitations:
    Can't pass an undefined variable to dump(). 
    dump() can't distinguish between int and float.
    dump() can't tell the original variable type of a member variable of an object.
    These limitations can't be fixed because these are *features* of JS. However, dump()
*/
function dump(v, howDisplay, recursionLevel) {
    howDisplay = (typeof howDisplay === 'undefined') ? "alert" : howDisplay;
    recursionLevel = (typeof recursionLevel !== 'number') ? 0 : recursionLevel;

    var vType = typeof v;
    var out = vType;

    switch (vType) {
        case "number":
        /* there is absolutely no way in JS to distinguish 2 from 2.0
           so 'number' is the best that you can do. The following doesn't work:
           var er = /^[0-9]+$/;
           if (!isNaN(v) && v % 1 === 0 && er.test(3.0)) {
               out = 'int';
           }
        */
        break;
    case "boolean":
        out += ": " + v;
        break;
    case "string":
        out += "(" + v.length + '): "' + v + '"';
        break;
    case "object":
        //check if null
        if (v === null) {
            out = "null";
        }
        //If using jQuery: if ($.isArray(v))
        //If using IE: if (isArray(v))
        //this should work for all browsers according to the ECMAScript standard:
        else if (Object.prototype.toString.call(v) === '[object Array]') {
            out = 'array(' + v.length + '): {\n';
            for (var i = 0; i < v.length; i++) {
                out += repeatString('   ', recursionLevel) + "   [" + i + "]:  " +
                    dump(v[i], "none", recursionLevel + 1) + "\n";
            }
            out += repeatString('   ', recursionLevel) + "}";
        }
        else {
            //if object
            let sContents = "{\n";
            let cnt = 0;
            for (var member in v) {
                //No way to know the original data type of member, since JS
                //always converts it to a string and no other way to parse objects.
                sContents += repeatString('   ', recursionLevel) + "   " + member +
                    ":  " + dump(v[member], "none", recursionLevel + 1) + "\n";
                cnt++;
            }
            sContents += repeatString('   ', recursionLevel) + "}";
            out += "(" + cnt + "): " + sContents;
        }
        break;
    default:
        out = v;
        break;
    }

    if (howDisplay == 'body') {
        var pre = document.createElement('pre');
        pre.innerHTML = out;
        document.body.appendChild(pre);
    }
    else if (howDisplay == 'alert') {
        alert(out);
    }

    return out;
}

Export P7b file with all the certificate chain into CER file

-print_certs is the option you want to use to list all of the certificates in the p7b file, you may need to specify the format of the p7b file you are reading.

You can then redirect the output to a new file to build the concatenated list of certificates.

Open the file in a text editor, you will either see Base64 (PEM) or binary data (DER).

openssl pkcs7 -inform DER -outform PEM -in certificate.p7b -print_certs > certificate_bundle.cer

http://www.openssl.org/docs/apps/pkcs7.html

How to delete a module in Android Studio

In Android studio v1.0.2

Method 1

Go to project structure, File -> Project Structure..., as the following picture show, click - icon to remove the module.enter image description here

Method 2

Edit the file settings.gradle and remove the entry you are going to delete. e.g. edit the file from include ':app', ':apple' to include ':app'.

That will work in most of the situation, however finally you have to delete the module from disk manually if you don't need it anymore.

Refresh a page using PHP

One trick is to add a random number to the end of the URL. That way you don't have to rename the file every time. E.g.:

echo "<img src='temp.jpg?r=3892384947438'>"

The browser will not cache it as long as the random number is different, but the web server will ignore it.

Default values for Vue component props & how to check if a user did not set the prop?

Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:

propE: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: function () {
        return { message: 'hello' }
      }
    },

Change a Django form field to a hidden field

If you have a custom template and view you may exclude the field and use {{ modelform.instance.field }} to get the value.

also you may prefer to use in the view:

form.fields['field_name'].widget = forms.HiddenInput()

but I'm not sure it will protect save method on post.

Hope it helps.

C# Double - ToString() formatting with two decimal places but no rounding

Solution:

var d = 0.123345678; 
var stringD = d.ToString(); 
int indexOfP = stringD.IndexOf("."); 
var result = stringD.Remove((indexOfP+1)+2);

(indexOfP+1)+2(this number depend on how many number you want to preserve. I give it two because the question owner want.)

jQuery/JavaScript: accessing contents of an iframe

I think what you are doing is subject to the same origin policy. This should be the reason why you are getting permission denied type errors.

ValueError: math domain error

You are trying to do a logarithm of something that is not positive.

Logarithms figure out the base after being given a number and the power it was raised to. log(0) means that something raised to the power of 2 is 0. An exponent can never result in 0*, which means that log(0) has no answer, thus throwing the math domain error

*Note: 0^0 can result in 0, but can also result in 1 at the same time. This problem is heavily argued over.

How to properly ignore exceptions

How to properly ignore Exceptions?

There are several ways of doing this.

However, the choice of example has a simple solution that does not cover the general case.

Specific to the example:

Instead of

try:
    shutil.rmtree(path)
except:
    pass

Do this:

shutil.rmtree(path, ignore_errors=True)

This is an argument specific to shutil.rmtree. You can see the help on it by doing the following, and you'll see it can also allow for functionality on errors as well.

>>> import shutil
>>> help(shutil.rmtree)

Since this only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

General approach

Since the above only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

New in Python 3.4:

You can import the suppress context manager:

from contextlib import suppress

But only suppress the most specific exception:

with suppress(FileNotFoundError):
    shutil.rmtree(path)

You will silently ignore a FileNotFoundError:

>>> with suppress(FileNotFoundError):
...     shutil.rmtree('bajkjbkdlsjfljsf')
... 
>>> 

From the docs:

As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.

Note that suppress and FileNotFoundError are only available in Python 3.

If you want your code to work in Python 2 as well, see the next section:

Python 2 & 3:

When you just want to do a try/except without handling the exception, how do you do it in Python?

Is the following the right way to do it?

try :
    shutil.rmtree ( path )
except :
    pass

For Python 2 compatible code, pass is the correct way to have a statement that's a no-op. But when you do a bare except:, that's the same as doing except BaseException: which includes GeneratorExit, KeyboardInterrupt, and SystemExit, and in general, you don't want to catch those things.

In fact, you should be as specific in naming the exception as you can.

Here's part of the Python (2) exception hierarchy, and as you can see, if you catch more general Exceptions, you can hide problems you did not expect:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
... and so on

You probably want to catch an OSError here, and maybe the exception you don't care about is if there is no directory.

We can get that specific error number from the errno library, and reraise if we don't have that:

import errno

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno == errno.ENOENT: # no such file or directory
        pass
    else: # we had an OSError we didn't expect, so reraise it
        raise 

Note, a bare raise raises the original exception, which is probably what you want in this case. Written more concisely, as we don't really need to explicitly pass with code in the exception handling:

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno != errno.ENOENT: # no such file or directory
        raise 

Assigning a variable NaN in python without numpy

Use float("nan"):

>>> float("nan")
nan

Using if-else in JSP

Instead of if-else condition use if in both conditions. it will work that way but not sure why.

How to pretty print XML from Java?

The solutions I have found here for Java 1.6+ do not reformat the code if it is already formatted. The one that worked for me (and re-formatted already formatted code) was the following.

import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
import org.w3c.dom.Element;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.StringReader;

public class XmlUtils {
    public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {
        Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
        byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());
        return new String(canonXmlBytes);
    }

    public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        InputSource src = new InputSource(new StringReader(input));
        Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
        Boolean keepDeclaration = input.startsWith("<?xml");
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
        return writer.writeToString(document);
    }
}

It is a good tool to use in your unit tests for full-string xml comparison.

private void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
    String canonicalExpected = prettyFormat(toCanonicalXml(expected));
    String canonicalActual = prettyFormat(toCanonicalXml(actual));
    assertEquals(canonicalExpected, canonicalActual);
}

Access denied for root user in MySQL command-line

You mustn't have a space character between -u and the username:

mysql -uroot -p
# or
mysql --user=root --password

Programmatically Install Certificate into Mozilla

I have an update of this awesome answer (just not working any more with last Firefox updates), in this same thread, made by H.-Dirk Schmitt, also thanks to the answer in this other thread made by BecarioEstrella.

I just adapted the script to recent changes.

Tested in 2021 just in Firefox 85.0.1 (64bit) in Ubuntu 20.04 and 18.04.

#!/usr/bin/env bash

function usage {
  echo "Error: no certificate filename or name supplied."
  echo "Usage: $ ./installcerts.sh <certname>.pem <Cert-DB-Name>"
  exit 1

}

if [ -z "$1" ] || [ -z "$2" ]
  then
    usage
fi

certificate_file="$1"
certificate_name="$2"
for certDB in $(find  ~/.mozilla* ~/.thunderbird -name "cert9.db")
do
  cert_dir=$(dirname ${certDB});
  echo "Mozilla Firefox certificate" "install '${certificate_name}' in ${cert_dir}"
  certutil -A -n "${certificate_name}" -t "TCu,Cuw,Tuw" -i ${certificate_file} -d sql:"${cert_dir}"
done

If you want it just for Firefox, replace the line:

for certDB in $(find  ~/.mozilla* ~/.thunderbird -name "cert9.db")

By

for certDB in $(find  ~/.mozilla* -name "cert9.db")

Further readings:

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

What does 'low in coupling and high in cohesion' mean

Do you have a smart phone? Is there one big app or lots of little ones? Does one app reply upon another? Can you use one app while installing, updating, and/or uninstalling another? That each app is self-contained is high cohesion. That each app is independent of the others is low coupling. DevOps favours this architecture because it means you can do discrete continuous deployment without disrupting the system entire.

How to solve error: "Clock skew detected"?

please try to do

make clean

(instead of make), then

make

again.

How can I get an HTTP response body as a string?

This is relatively simple in the specific case, but quite tricky in the general case.

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://stackoverflow.com/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.getContentMimeType(entity));
System.out.println(EntityUtils.getContentCharSet(entity));

The answer depends on the Content-Type HTTP response header.

This header contains information about the payload and might define the encoding of textual data. Even if you assume text types, you may need to inspect the content itself in order to determine the correct character encoding. E.g. see the HTML 4 spec for details on how to do that for that particular format.

Once the encoding is known, an InputStreamReader can be used to decode the data.

This answer depends on the server doing the right thing - if you want to handle cases where the response headers don't match the document, or the document declarations don't match the encoding used, that's another kettle of fish.

What is the difference between MacVim and regular Vim?

The one reason I have which made switching to MacVim worth it: Yank uses the system clipboard.

I can finally copy paste between MacVim on my terminal and the rest of my applications.

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

JavaScript has replace() method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example of replace() method having both string arguments is shown below.

var text = 'one, two, three, one, five, one';
var new_text = text.replace('one', 'ten');
console.log(new_text)  //ten, two, three, one, five, one

Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a g (global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences of one in the above example.

var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, 'ten');
console.log(new_text)  //ten, two, three, ten, five, ten

Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag i which makes the pattern case-insensitive. In that case the above regular expression will be /one/gi. Notice the i flag added here.

If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,

var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, function(match, pos, text){
return 'ten';
});
console.log(new_text) //ten, two, three, ten, five, ten

You can have more control over the replacement text using a function as the second argument.

Add jars to a Spark Job - spark-submit

When using spark-submit with --master yarn-cluster, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. URLs supplied after --jars must be separated by commas. That list is included in the driver and executor classpaths

Example :

spark-submit --master yarn-cluster --jars ../lib/misc.jar, ../lib/test.jar --class MainClass MainApp.jar

https://spark.apache.org/docs/latest/submitting-applications.html

Converting NSString to NSDictionary / JSON

I believe you are misinterpreting the JSON format for key values. You should store your string as

NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

Now if you do following NSLog statement

NSLog(@"%@",[json objectForKey:@"ID"]);

Result would be another NSDictionary.

{
    Content = 268;
    type = text;
}

Hope this helps to get clear understanding.

What are the true benefits of ExpandoObject?

It's all about programmer convenience. I can imagine writing quick and dirty programs with this object.

What are the parameters for the number Pipe - Angular 2

'1.0-0' will give you zero decimal places i.e. no decimals. e.g.$500

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

This can be caused by a bum applicationhost.config entry.

Stop IIS Express if it's running (right-click the light-blue scroll-thingy icon in the Windows System Tray; Exit).

Go to your project's Properties > Web, and check that the Project Url is correct. In case of an https url, make sure it includes a port number in the valid range. A correct URL could be: https://localhost:44300/. Now press the "Create Virtual Directory"-button next to the URL. This adds a new entry to applicationhost.config.

Start the project again and hopefully you will no longer get the error.

error running apache after xampp install

Try those methods, it should work:

  • quit/exit Skype (make sure it's not running) because it reserves localhost:80
  • disable Anti-virus (Try first to disable skype and running again, if it didn't work do this step)
  • Right click on xampp control panel and run as administrator

Update Jenkins from a war file

#on ubuntu, in /usr/share/jenkins:

sudo service jenkins stop
sudo mv jenkins.war jenkins.war.old
sudo wget https://updates.jenkins-ci.org/latest/jenkins.war
sudo service jenkins start

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

Generate random integers between 0 and 9

The secrets module is new in Python 3.6. This is better than the random module for cryptography or security uses.

To randomly print an integer in the inclusive range 0-9:

from secrets import randbelow
print(randbelow(10))

For details, see PEP 506.

How to fix Cannot find module 'typescript' in Angular 4?

If you have cloned your project from git or somewhere then first, you should type npm install.

How can I initialize a String array with length 0 in Java?

Ok I actually found the answer but thought I would 'import' the question into SO anyway

String[] files = new String[0];
or
int[] files = new int[0];

Sort columns of a dataframe by column name

test = data.frame(C=c(0,2,4, 7, 8), A=c(4,2,4, 7, 8), B=c(1, 3, 8,3,2))

Using the simple following function replacement can be performed (but only if data frame does not have many columns):

test <- test[, c("A", "B", "C")]

for others:

test <- test[, c("B", "A", "C")]

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

If you're using Spring Data JPA then addition @Transactional annotation to your service implementation would solve the issue.

Java method to sum any number of ints

public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
    int sum = 0; //start with 0
    for(int n : nums) { //this won't execute if no argument is passed
        sum += n; // this will repeat for all the arguments
    }
    return sum; //return the sum
} 

Explanation of "ClassCastException" in Java

Straight from the API Specifications for the ClassCastException:

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.

Object i = Integer.valueOf(42);
String s = (String)i;            // ClassCastException thrown here.

How to check for null in a single statement in scala?

Although I'm sure @Ben Jackson's asnwer with Option(getObject).foreach is the preferred way of doing it, I like to use an AnyRef pimp that allows me to write:

getObject ifNotNull ( QueueManager.add(_) )

I find it reads better.

And, in a more general way, I sometimes write

val returnVal = getObject ifNotNull { obj =>
  returnSomethingFrom(obj)
} otherwise {
  returnSomethingElse
}

... replacing ifNotNull with ifSome if I'm dealing with an Option. I find it clearer than first wrapping in an option and then pattern-matching it.

(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matching and the Otherwise0/Otherwise1 classes.)

Know relationships between all the tables of database in SQL Server

Just another way to retrieve the same data using INFORMATION_SCHEMA

The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.

sqlauthority way

SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
---- optional:
ORDER BY
1,2,3,4
WHERE PK.TABLE_NAME='something'WHERE FK.TABLE_NAME='something'
WHERE PK.TABLE_NAME IN ('one_thing', 'another')
WHERE FK.TABLE_NAME IN ('one_thing', 'another')

How to save a bitmap on internal storage

To save file into directory

  public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){

    String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());

    String mImageName = "snap_"+mTimeStamp+".jpg";

    ContextWrapper wrapper = new ContextWrapper(mContext);

    File file = wrapper.getDir("Images",MODE_PRIVATE);

    file = new File(file, "snap_"+ mImageName+".jpg");

    try{

        OutputStream stream = null;

        stream = new FileOutputStream(file);

        bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);

        stream.flush();

        stream.close();

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

    Uri mImageUri = Uri.parse(file.getAbsolutePath());

    return mImageUri;
}

required permission

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

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Just add Attribute routing if it is not present in appconfig or webconfig

config.MapHttpAttributeRoutes()

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:

<location path="YourWebservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

How to reload .bash_profile from the command line?

  1. Save .bash_profile file
  2. Goto user's home directory by typing cd
  3. Reload the profile with . .bash_profile

How to check if JavaScript object is JSON

I know this is a very old question with good answers. However, it seems that it's still possible to add my 2¢ to it.

Assuming that you're trying to test not a JSON object itself but a String that is formatted as a JSON (which seems to be the case in your var data), you could use the following function that returns a boolean (is or is not a 'JSON'):

function isJsonString( jsonString ) {

  // This function below ('printError') can be used to print details about the error, if any.
  // Please, refer to the original article (see the end of this post)
  // for more details. I suppressed details to keep the code clean.
  //
  let printError = function(error, explicit) {
  console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
  }


  try {
      JSON.parse( jsonString );
      return true; // It's a valid JSON format
  } catch (e) {
      return false; // It's not a valid JSON format
  }

}

Here are some examples of using the function above:

console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );

console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );

console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );

console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );

console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );

console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );

console.log('\n7 -----------------');
j = '[{"a":1, "b":   2}, {"c":3}]';
console.log( j, isJsonString(j) );

When you run the code above, you will get the following results:

1 -----------------
abc false

2 -----------------
{"abc": "def"} true

3 -----------------
{"abc": "def} false

4 -----------------
{} true

5 -----------------
[{}] true

6 -----------------
[{},] false

7 -----------------
[{"a":1, "b":   2}, {"c":3}] true

Please, try the snippet below and let us know if this works for you. :)

IMPORTANT: the function presented in this post was adapted from https://airbrake.io/blog/javascript-error-handling/syntaxerror-json-parse-bad-parsing where you can find more and interesting details about the JSON.parse() function.

_x000D_
_x000D_
function isJsonString( jsonString ) {_x000D_
_x000D_
  let printError = function(error, explicit) {_x000D_
  console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);_x000D_
  }_x000D_
_x000D_
_x000D_
  try {_x000D_
      JSON.parse( jsonString );_x000D_
      return true; // It's a valid JSON format_x000D_
  } catch (e) {_x000D_
      return false; // It's not a valid JSON format_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
console.log('\n1 -----------------');_x000D_
let j = "abc";_x000D_
console.log( j, isJsonString(j) );_x000D_
_x000D_
console.log('\n2 -----------------');_x000D_
j = `{"abc": "def"}`;_x000D_
console.log( j, isJsonString(j) );_x000D_
_x000D_
console.log('\n3 -----------------');_x000D_
j = '{"abc": "def}';_x000D_
console.log( j, isJsonString(j) );_x000D_
_x000D_
console.log('\n4 -----------------');_x000D_
j = '{}';_x000D_
console.log( j, isJsonString(j) );_x000D_
_x000D_
console.log('\n5 -----------------');_x000D_
j = '[{}]';_x000D_
console.log( j, isJsonString(j) );_x000D_
_x000D_
console.log('\n6 -----------------');_x000D_
j = '[{},]';_x000D_
console.log( j, isJsonString(j) );_x000D_
_x000D_
console.log('\n7 -----------------');_x000D_
j = '[{"a":1, "b":   2}, {"c":3}]';_x000D_
console.log( j, isJsonString(j) );
_x000D_
_x000D_
_x000D_

Cannot execute RUN mkdir in a Dockerfile

The problem is that /var/www doesn't exist either, and mkdir isn't recursive by default -- it expects the immediate parent directory to exist.

Use:

mkdir -p /var/www/app

...or install a package that creates a /var/www prior to reaching this point in your Dockerfile.

How do I use Comparator to define a custom sort order?

I think this can be done as follows:

class ColorComparator implements Comparator<CarSort>
{
    private List<String> sortOrder;
    public ColorComparator (List<String> sortOrder){
        this.sortOrder = sortOrder;
    }

    public int compare(CarSort c1, CarSort c2)
    {
        String a1 = c1.getColor();
        String a2 = c2.getColor();
        return sortOrder.indexOf(a1) - sortOrder.indexOf(a2);
     }
 }

For sorting use this:

Collections.sort(carList, new ColorComparator(sortOrder));

Qt. get part of QString

If you do not need to modify the substring, then you can use QStringRef. The QStringRef class is a read only wrapper around an existing QString that references a substring within the existing string. This gives much better performance than creating a new QString object to contain the sub-string. E.g.

QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"

If you do need to modify the substring, then left(), mid() and right() will do what you need...

QString myString("This is a string");
QString subString = myString.mid(5,2); // subString contains "is"
subString.append("n't"); // subString contains "isn't"

Computational complexity of Fibonacci Sequence

The naive recursion version of Fibonacci is exponential by design due to repetition in the computation:

At the root you are computing:

F(n) depends on F(n-1) and F(n-2)

F(n-1) depends on F(n-2) again and F(n-3)

F(n-2) depends on F(n-3) again and F(n-4)

then you are having at each level 2 recursive calls that are wasting a lot of data in the calculation, the time function will look like this:

T(n) = T(n-1) + T(n-2) + C, with C constant

T(n-1) = T(n-2) + T(n-3) > T(n-2) then

T(n) > 2*T(n-2)

...

T(n) > 2^(n/2) * T(1) = O(2^(n/2))

This is just a lower bound that for the purpose of your analysis should be enough but the real time function is a factor of a constant by the same Fibonacci formula and the closed form is known to be exponential of the golden ratio.

In addition, you can find optimized versions of Fibonacci using dynamic programming like this:

static int fib(int n)
{
    /* memory */
    int f[] = new int[n+1];
    int i;

    /* Init */
    f[0] = 0;
    f[1] = 1;

    /* Fill */
    for (i = 2; i <= n; i++)
    {
        f[i] = f[i-1] + f[i-2];
    }

    return f[n];
}

That is optimized and do only n steps but is also exponential.

Cost functions are defined from Input size to the number of steps to solve the problem. When you see the dynamic version of Fibonacci (n steps to compute the table) or the easiest algorithm to know if a number is prime (sqrt(n) to analyze the valid divisors of the number). you may think that these algorithms are O(n) or O(sqrt(n)) but this is simply not true for the following reason: The input to your algorithm is a number: n, using the binary notation the input size for an integer n is log2(n) then doing a variable change of

m = log2(n) // your real input size

let find out the number of steps as a function of the input size

m = log2(n)
2^m = 2^log2(n) = n

then the cost of your algorithm as a function of the input size is:

T(m) = n steps = 2^m steps

and this is why the cost is an exponential.

how to check the version of jar file?

Just to expand on the answers above, inside the META-INF/MANIFEST.MF file in the JAR, you will likely see a line: Manifest-Version: 1.0 ? This is NOT the jar versions number!

You need to look for Implementation-Version which, if present, is a free-text string so entirely up to the JAR's author as to what you'll find in there. See also Oracle docs and Package Version specificaion

What is the difference between Class.getResource() and ClassLoader.getResource()?

The first call searches relative to the .class file while the latter searches relative to the classpath root.

To debug issues like that, I print the URL:

System.out.println( getClass().getResource(getClass().getSimpleName() + ".class") );

What is the correct XPath for choosing attributes that contain "foo"?

try this:

//a[contains(@prop,'foo')]

that should work for any "a" tags in the document

Spell Checker for Python

spell corrector->

you need to import a corpus on to your desktop if you store elsewhere change the path in the code i have added a few graphics as well using tkinter and this is only to tackle non word errors!!

def min_edit_dist(word1,word2):
    len_1=len(word1)
    len_2=len(word2)
    x = [[0]*(len_2+1) for _ in range(len_1+1)]#the matrix whose last element ->edit distance
    for i in range(0,len_1+1):  
        #initialization of base case values
        x[i][0]=i
        for j in range(0,len_2+1):
            x[0][j]=j
    for i in range (1,len_1+1):
        for j in range(1,len_2+1):
            if word1[i-1]==word2[j-1]:
                x[i][j] = x[i-1][j-1]
            else :
                x[i][j]= min(x[i][j-1],x[i-1][j],x[i-1][j-1])+1
    return x[i][j]
from Tkinter import *


def retrieve_text():
    global word1
    word1=(app_entry.get())
    path="C:\Documents and Settings\Owner\Desktop\Dictionary.txt"
    ffile=open(path,'r')
    lines=ffile.readlines()
    distance_list=[]
    print "Suggestions coming right up count till 10"
    for i in range(0,58109):
        dist=min_edit_dist(word1,lines[i])
        distance_list.append(dist)
    for j in range(0,58109):
        if distance_list[j]<=2:
            print lines[j]
            print" "   
    ffile.close()
if __name__ == "__main__":
    app_win = Tk()
    app_win.title("spell")
    app_label = Label(app_win, text="Enter the incorrect word")
    app_label.pack()
    app_entry = Entry(app_win)
    app_entry.pack()
    app_button = Button(app_win, text="Get Suggestions", command=retrieve_text)
    app_button.pack()
    # Initialize GUI loop
    app_win.mainloop()

How do I clone a github project to run locally?

To clone a repository and place it in a specified directory use "git clone [url] [directory]". For example

git clone https://github.com/ryanb/railscasts-episodes.git Rails

will create a directory named "Rails" and place it in the new directory. Click here for more information.

Simplest way to have a configuration file in a Windows Forms C# application

I agree with the other answers that point you to app.config. However, rather than reading values directly from app.config, you should create a utility class (AppSettings is the name I use) to read them and expose them as properties. The AppSettings class can be used to aggregate settings from several stores, such as values from app.config and application version info from the assembly (AssemblyVersion and AssemblyFileVersion).

Limit length of characters in a regular expression?

If you want to restrict valid input to integer values between 1 and 100, this will do it:

^([1-9]|[1-9][0-9]|100)$

Explanation:

  1. ^ = start of input
  2. () = multiple options to match
  3. First argument [1-9] - matches any entries between 1 and 9
  4. | = OR argument separator
  5. Second Argument [1-9][0-9] - matches entries between 10 and 99
  6. Last Argument 100 - Self explanatory - matches entries of 100

This WILL NOT ACCEPT: 1. Zero - 0 2. Any integer preceded with a zero - 01, 021, 001 3. Any integer greater than 100

Hope this helps!

Gez

How to set the timezone in Django?

Choose a valid timezone from the tzinfo database. They tend to take the form e.g. Africa/Gaborne and US/Eastern

Find the one which matches the city nearest you, or the one which has your timezone, then set your value of TIME_ZONE to match.

How can I deploy an iPhone application from Xcode to a real iPhone device?

No, its easy to do this. In Xcode, set the Active Configuration to Release. Change the device from Simulator to Device - whatever SDK. If you want to directly export to your iPhone, connect it to your computer. Press Build and Go. If your iPhone is not connected to your computer, a message will come up saying that your iPhone is not connected.

If this applies to you: (iPhone was not connected)

Go to your projects folder and then to the build folder inside. Go to the Release-iphoneos folder and take the app inside, drag and drop on iTunes icon. When you sync your iTouch device, it will copy it to your device. It will also show up in iTunes as a application for the iPhone.

Hope this helps!

P.S.: If it says something about a certificate not being valid, just click on the project in Xcode, the little project icon in the file stack to the left, and press Apple+I, or do Get Info from the menu bar. Click on Build at the top. Under Code Signing, change Code Signing Identity - Any iPhone OS Device to be Don't Sign.

Very simple C# CSV reader

This fixed version of code above remember the last element of CVS row ;-)

(tested with a CSV file with 5400 rows and 26 elements by row)

   public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')  {
            bool bolQuote = false;
            StringBuilder bld = new StringBuilder();
            List<string> retAry = new List<string>();

            foreach (char c in r.ToCharArray())
                if ((c == fieldSep && !bolQuote))
                {
                    retAry.Add(bld.ToString());
                    bld.Clear();
                }
                else
                    if (c == stringSep)
                        bolQuote = !bolQuote;
                    else
                        bld.Append(c);

            /* to solve the last element problem */
            retAry.Add(bld.ToString()); /* added this line */
            return retAry.ToArray();
        }

Validate date in dd/mm/yyyy format using JQuery Validate

If you use the moment js library it can easily be done like this -

jQuery.validator.addMethod("validDate", function(value, element) {
        return this.optional(element) || moment(value,"DD/MM/YYYY").isValid();
    }, "Please enter a valid date in the format DD/MM/YYYY");

C# getting its own class name

With C# 6.0, you can use the nameof operator:

nameof(MyProgram)

Using Git, show all commits that are in one branch, but not the other(s)

jimmyorr's answer does not work on Windows. it helps to use --not instead of ^ like so:

git log oldbranch --not newbranch --no-merges

Reading a text file in MATLAB line by line

You cannot read text strings with csvread. Here is another solution:

fid1 = fopen('test.csv','r'); %# open csv file for reading
fid2 = fopen('new.csv','w'); %# open new csv file
while ~feof(fid1)
    line = fgets(fid1); %# read line by line
    A = sscanf(line,'%*[^,],%f,%f'); %# sscanf can read only numeric data :(
    if A(2)<4.185 %# test the values
        fprintf(fid2,'%s',line); %# write the line to the new file
    end
end
fclose(fid1);
fclose(fid2);

C++ equivalent of java's instanceof

#include <iostream.h>
#include<typeinfo.h>

template<class T>
void fun(T a)
{
  if(typeid(T) == typeid(int))
  {
     //Do something
     cout<<"int";
  }
  else if(typeid(T) == typeid(float))
  {
     //Do Something else
     cout<<"float";
  }
}

void main()
 {
      fun(23);
      fun(90.67f);
 }

spark submit add multiple jars in classpath

You can use --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') to include entire folder of Jars. So, spark-submit -- class com.yourClass \ --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') \ ...

getting only name of the class Class.getName()

The below both ways works fine.

System.out.println("The Class Name is: " + this.getClass().getName());
System.out.println("The simple Class Name is: " + this.getClass().getSimpleName());

Output as below:

The Class Name is: package.Student

The simple Class Name is: Student

QR Code encoding and decoding using zxing

If you really need to encode UTF-8, you can try prepending the unicode byte order mark. I have no idea how widespread the support for this method is, but ZXing at least appears to support it: http://code.google.com/p/zxing/issues/detail?id=103

I've been reading up on QR Mode recently, and I think I've seen the same practice mentioned elsewhere, but I've not the foggiest where.

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

Detect the Enter key in a text input field

The best way I found is using keydown ( the keyup doesn't work well for me).

Note: I also disabled the form submit because usually when you like to do some actions when pressing Enter Key the only think you do not like is to submit the form :)

$('input').keydown( function( event ) {
    if ( event.which === 13 ) {
        // Do something
        // Disable sending the related form
        event.preventDefault();
        return false;
    }
});

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

Set adb vendor keys

Sometimes you just need to recreate new device

sqldeveloper error message: Network adapter could not establish the connection error

https://forums.oracle.com/forums/thread.jspa?threadID=2150962

Re: SQL DevErr:The Network Adapter could not establish the connection VenCode20 Posted: Dec 7, 2011 3:23 AM in response to: MehulDoshi Reply

This worked for me:

Open the "New/Select Database Connection" dialogue and try changing the connection type setting from "Basic" to "TNS" and then selecting the network alias (for me: "ORCL").

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

Only one change was needed to fix the problem:

Go to Start -> Control Panel -> System -> Advanced(tab) -> Environment Variables -> System Variables

set ANDROID_HOME to C:\Program Files (x86)\Android\android-sdk

What are ABAP and SAP?

SAP is really a big Company that offers incredible solutions oriented to medium-large companies.

Actually, I can say that the main IT products are: ERP, WEB, Human Resources, Integration, BI, Reports, Machine Learning, Mobile, Cloud, Robotics, and so on.

On the cloud, you can even find solutions using Cloud Foundry, NodeJS, HTML5, Java, etc.

It's really huge the solutions that offers to their customers.

How to automate drag & drop functionality using Selenium WebDriver Java

Selenium has pretty good documentation. Here is a link to the specific part of the API you are looking for:

WebElement element = driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element, target).perform();

This is to drag and drop a single file, How to drag and drop multiple files.

Using DataContractSerializer to serialize, but can't deserialize back

I ended up doing the following and it works.

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.

PHP-FPM doesn't write to error log

I struggled with this for a long time before finding my php-fpm logs were being written to /var/log/upstart/php5-fpm.log. It appears to be a bug between how upstart and php-fpm interact. See more here: https://bugs.launchpad.net/ubuntu/+source/php5/+bug/1319595

Using Python, find anagrams for a list of words

Since you can't import anything, here are two different approaches including the for loop you asked for.

Approach 1: For Loops and Inbuilt Sorted Function

word_list = ["percussion", "supersonic", "car", "tree", "boy", "girl", "arc"]

# initialize a list
anagram_list = []
for word_1 in word_list: 
    for word_2 in word_list: 
        if word_1 != word_2 and (sorted(word_1)==sorted(word_2)):
            anagram_list.append(word_1)
print(anagram_list)

Approach 2: Dictionaries

def freq(word):
    freq_dict = {}
    for char in word:
        freq_dict[char] = freq_dict.get(char, 0) + 1
    return freq_dict

# initialize a list
anagram_list = []
for word_1 in word_list: 
    for word_2 in word_list: 
        if word_1 != word_2 and (freq(word_1) == freq(word_2)):
            anagram_list.append(word_1)
print(anagram_list)

If you want these approaches explained in more detail, here is an article.

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

Mongoose (mongodb) batch insert?

Mongoose 4.4.0 now supports bulk insert

Mongoose 4.4.0 introduces --true-- bulk insert with the model method .insertMany(). It is way faster than looping on .create() or providing it with an array.

Usage:

var rawDocuments = [/* ... */];

Book.insertMany(rawDocuments)
    .then(function(mongooseDocuments) {
         /* ... */
    })
    .catch(function(err) {
        /* Error handling */
    });

Or

Book.insertMany(rawDocuments, function (err, mongooseDocuments) { /* Your callback function... */ });

You can track it on:

How to downgrade tensorflow, multiple versions possible?

I discovered the joy of anaconda: https://www.continuum.io/downloads

C:> conda create -n tensorflow1.1 python=3.5
C:> activate tensorflow1.1
(tensorflow1.1) 
C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl

voila, a virtual environment is created.

CSV in Python adding an extra carriage return, on Windows

Note that if you use DictWriter, you will have a new line from the open function and a new line from the writerow function. You can use newline='' within the open function to remove the extra newline.

How to config Tomcat to serve images from an external folder outside webapps?

You can deploy an images folder as a separate webapp and define the location of that folder to be anywhere in the file system.

Create a Context element in an XML file in the directory $CATALINA_HOME/conf/[enginename]/[hostname]/ where enginename might be 'Catalina' and hostname might be 'localhost'.

Name the file based on the path URL you want the images to be viewed from, so if your webapp has path 'blog', you might name the XML file blog#images.xml and so that your images would be visible at example.com/blog/images/

The content of the XML file should be <Context docBase="/filesystem/path/to/images"/>

Be careful not to undeploy this webapp, as that could delete all your images!

Xcode Debugger: view value of variable

Your confusion stems from the fact that declared properties are not (necessarily named the same as) (instance) variables.

The expresion

indexPath.row

is equivalent to

[indexPath row]

and the assignment

delegate.myData = [myData objectAtIndex:indexPath.row];

is equivalent to

[delegate setMyData:[myData objectAtIndex:[indexPath row]]];

assuming standard naming for synthesised properties.

Furthermore, delegate is probably declared as being of type id<SomeProtocol>, i.e., the compiler hasn’t been able to provide actual type information for delegate at that point, and the debugger is relying on information provided at compile-time. Since id is a generic type, there’s no compile-time information about the instance variables in delegate.

Those are the reasons why you don’t see myData or row as variables.

If you want to inspect the result of sending -row or -myData, you can use commands p or po:

p (NSInteger)[indexPath row]
po [delegate myData]

or use the expressions window (for instance, if you know your delegate is of actual type MyClass *, you can add an expression (MyClass *)delegate, or right-click delegate, choose View Value as… and type the actual type of delegate (e.g. MyClass *).

That being said, I agree that the debugger could be more helpful:

  • There could be an option to tell the debugger window to use run-time type information instead of compile-time information. It'd slow down the debugger, granted, but would provide useful information;

  • Declared properties could be shown up in a group called properties and allow for (optional) inspection directly in the debugger window. This would also slow down the debugger because of the need to send a message/execute a method in order to get information, but would provide useful information, too.

VSCode single to double quote automatic replace

As noted by @attdona the Vetur extension includes prettier.

While you can change the prettier settings, as per the accepted answer, you can also change the formatter for specific regions of a vue component.

Here, for example, I've set Vetur to use the vscode-typescript formatter as it uses single quotes by default:

vscode vetur settings

What is the purpose of Android's <merge> tag in XML layouts?

To have a more in-depth knowledge of what's happening, I created the following example. Have a look at the activity_main.xml and content_profile.xml files.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/content_profile" />

</LinearLayout>

content_profile.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Howdy" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</LinearLayout>

In here, the entire layout file when inflated looks like this.

<LinearLayout>
    <LinearLayout>
        <TextView />
        <TextView />
    </LinearLayout>
</LinearLayout>

See that there is a LinearLayout inside the parent LinearLayout which doesn't serve any purpose and is redundant. A look at the layout through Layout Inspector tool clearly explains this.

enter image description here

content_profile.xml after updating the code to use merge instead of a ViewGroup like LinearLayout.

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Howdy" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</merge>

Now our layout looks like this

<LinearLayout>
    <TextView />
    <TextView />
</LinearLayout>

Here we see that the redundant LinearLayout ViewGroup is removed. Now Layout Inspector tool gives the following layout hierarchy.

enter image description here

So always try to use merge when your parent layout can position your child layouts, or more precisely use merge when you understand that there is going to be a redundant view group in the hierarchy.

How do I return an int from EditText? (Android)

You can do this in 2 steps:

1: Change the input type(In your EditText field) in the layout file to android:inputType="number"

2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());

How to bind event listener for rendered elements in Angular 2?

HostListener should be the proper way to bind event into your component:

@Component({
  selector: 'your-element'
})

export class YourElement {
  @HostListener('click', ['$event']) onClick(event) {
     console.log('component is clicked');
     console.log(event);
  }
}

How do I perform an insert and return inserted identity with Dapper?

I was using .net core 3.1 with postgres 12.3. Building on the answer from Tadija Bagaric I ended up with:

using (var connection = new NpgsqlConnection(AppConfig.CommentFilesConnection))
        {

            string insertUserSql = @"INSERT INTO mytable(comment_id,filename,content)
                    VALUES( @commentId, @filename, @content) returning id;";

            int newUserId = connection.QuerySingle<int>(
                                            insertUserSql,
                                            new
                                            {
                                                commentId = 1,
                                                filename = "foobar!",
                                                content = "content"
                                            }
                                            );

          


        }

where AppConfig is my own class which simply gets a string set for my connection details. This is set within the Startup.cs ConfigureServices method.

How Can I Remove “public/index.php” in the URL Generated Laravel?

Option 1: Use .htaccess

If it isn't already there, create an .htaccess file in the Laravel root directory. Create a .htaccess file your Laravel root directory if it does not exists already. (Normally it is under your public_html folder)

Edit the .htaccess file so that it contains the following code:

<IfModule mod_rewrite.c>
   RewriteEngine On 
   RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

Now you should be able to access the website without the "/public/index.php/" part.

Option 2 : Move things in the '/public' directory to the root directory

Make a new folder in your root directory and move all the files and folder except public folder. You can call it anything you want. I'll use "laravel_code".

Next, move everything out of the public directory and into the root folder. It should result in something somewhat similar to this: enter image description here

After that, all we have to do is edit the locations in the laravel_code/bootstrap/paths.php file and the index.php file.

In laravel_code/bootstrap/paths.php find the following line of code:

'app' => __DIR__.'/../app',
'public' => __DIR__.'/../public',

And change them to:

'app' => __DIR__.'/../app',
'public' => __DIR__.'/../../',

In index.php, find these lines:

require __DIR__.'/../bootstrap/autoload.php';     
$app = require_once __DIR__.'/../bootstrap/start.php';

And change them to:

require __DIR__.'/laravel_code/bootstrap/autoload.php';     
$app = require_once __DIR__.'/laravel_code/bootstrap/start.php';

Source: How to remove /public/ from URL in Laravel

How can I get query parameters from a URL in Vue.js?

Another way (assuming you are using vue-router), is to map the query param to a prop in your router. Then you can treat it like any other prop in your component code. For example, add this route;

{ 
    path: '/mypage', 
    name: 'mypage', 
    component: MyPage, 
    props: (route) => ({ foo: route.query.foo })  
}

Then in your component you can add the prop as normal;

props: {
    foo: {
        type: String,
        default: null
    }
},

Then it will be available as this.foo and you can do anything you want with it (like set a watcher, etc.)