Programs & Examples On #Musicbrainz

MusicBrainz is a community maintained database of music information. One of its primary uses is as a source of metadata for tagging MP3s. It provides a web service to access the data.

Simple and fast method to compare images for similarity

If you want to get an index about the similarity of the two pictures, I suggest you from the metrics the SSIM index. It is more consistent with the human eye. Here is an article about it: Structural Similarity Index

It is implemented in OpenCV too, and it can be accelerated with GPU: OpenCV SSIM with GPU

Error in contrasts when defining a linear model in R

It appears that at least one of your predictors ,x1, x2, or x3, has only one factor level and hence is a constant.

Have a look at

lapply(dataframe.df[c("x1", "x2", "x3")], unique)

to find the different values.

How to compare two dates in Objective-C

The best way I found was to check the difference between the given date and today:

NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* now = [NSDate date];
int differenceInDays =
[calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:date] -
[calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:now];

According to Listing 13 of Calendrical Calculations in Apple's Date and Time Programming Guide [NSCalendar ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:myDate] gives you the number of midnights since the start of the era. This way it's easy to check whether the date is yesterday, today, or tomorrow.

switch (differenceInDays) {
    case -1:
        dayString = @"Yesterday";
        break;
    case 0:
        dayString = @"Today";
        break;
    case 1:
        dayString = @"Tomorrow";
        break;
    default: {
        NSDateFormatter* dayFormatter = [[NSDateFormatter alloc] init];
        [dayFormatter setLocale:usLocale];
        [dayFormatter setDateFormat:@"dd MMM"];
        dayString = [dayFormatter stringFromDate: date];
        break;
    }
}

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

pip install access denied on Windows

In case of windows, in cmd try to run pip install using python executable

e.g.

python -m pip install mitmproxy

this should work, at least it worked for me for other package installation.

Clearing coverage highlighting in Eclipse

Added shortcut Ctrl+Shift+X C to Keybindings (Window -> Preferences -> filter for Keys) when 'Editing Java Source' for 'Remove Active Session'.

python: How do I know what type of exception occurred?

To add to Lauritz's answer, I created a decorator/wrapper for exception handling and the wrapper logs which type of exception occurred.

class general_function_handler(object):
    def __init__(self, func):
        self.func = func
    def __get__(self, obj, type=None):
        return self.__class__(self.func.__get__(obj, type))
    def __call__(self, *args, **kwargs):
        try:
            retval = self.func(*args, **kwargs)
        except Exception, e :
            logging.warning('Exception in %s' % self.func)
            template = "An exception of type {0} occured. Arguments:\n{1!r}"
            message = template.format(type(e).__name__, e.args)
            logging.exception(message)
            sys.exit(1) # exit on all exceptions for now
        return retval

This can be called on a class method or a standalone function with the decorator:

@general_function_handler

See my blog about for the full example: http://ryaneirwin.wordpress.com/2014/05/31/python-decorators-and-exception-handling/

Calling Javascript function from server side

This works for me. Hope it will work for you too.

ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);

I have edited the html page which you have provided. The updated page is as below

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>My Page</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function Test() {
                alert("Hello Test!!!!");
                $('#ButtonRow').css("display", "block");
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <table>
            <tr>
                <td>
                    <asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
                        BorderStyle="Solid">
                        <asp:ListItem>Merchant</asp:ListItem>
                        <asp:ListItem>Store</asp:ListItem>
                        <asp:ListItem>Terminal</asp:ListItem>
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr id="ButtonRow" style="display: none">
                <td>
                    <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
                </td>
            </tr>
        </table>
        </form>
    </body>
    </html>

    <script type="text/javascript">

        $("#<%=SearchCategory.ClientID%> input").change(function () {
            alert("hi");
            $("#ButtonRow").show();
        });
    </script>

How to get index in Handlebars each helper?

In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.


snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811

The index of the current array item has been available for some time now via @index:

{{#each array}}
    {{@index}}: {{this}}
{{/each}}

For object iteration, use @key instead:

{{#each object}}
    {{@key}}: {{this}}
{{/each}} 

Create a hidden field in JavaScript

You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true.

You can also add multiple hidden fields. Use this way:

CustomizePPT.setHiddenFields( 
    { 
        "hidden" : 
        {
            'fieldinFORM' : 'thisdata201' , 
            'fieldinFORM2' : 'this3' //multiple hidden fields
            .
            .
            .
            .
            .
            'nNoOfFields' : 'nthData'
        },
    "form" : 
    {
        "status" : "true",
        "formID" : "form3"
    } 
} );

_x000D_
_x000D_
var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
    var request = [];_x000D_
 var container = '';_x000D_
 console.log(arguments);_x000D_
 request = arguments[0].hidden;_x000D_
    console.log(arguments[0].hasOwnProperty('form'));_x000D_
 if(arguments[0].hasOwnProperty('form') == true)_x000D_
 {_x000D_
  if(arguments[0].form.status == 'true'){_x000D_
   var parent = document.getElementById("container");_x000D_
   container = document.createElement('form');_x000D_
   parent.appendChild(container);_x000D_
   Object.assign(container, {'id':arguments[0].form.formID});_x000D_
  }_x000D_
 }_x000D_
 else{_x000D_
   container = document.getElementById("container");_x000D_
 }_x000D_
 _x000D_
 //var container = document.getElementById("container");_x000D_
 Object.keys(request).forEach(function(elem)_x000D_
 {_x000D_
  if($('#'+elem).length <= 0){_x000D_
   console.log("Hidden Field created");_x000D_
   var input = document.createElement('input');_x000D_
   Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
   container.appendChild(input);_x000D_
  }else{_x000D_
   console.log("Hidden Field Exists and value is below" );_x000D_
   $('#'+elem).val(request[elem]);_x000D_
  }_x000D_
 });_x000D_
};_x000D_
_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I delete multiple rows with different IDs?

  • You can make this.

    CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
    @CODE XML ,@ERRFLAG CHAR(1) = '0' OUTPUT

AS

SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DELETE tb_SampleTest WHERE CODE IN( SELECT Item.value('.', 'VARCHAR(20)') FROM @CODE.nodes('RecordList/ID') AS x(Item) )

IF @@ROWCOUNT = 0 SET @ERRFLAG = 200

SET NOCOUNT OFF

  • <'RecordList'><'ID'>1<'/ID'><'ID'>2<'/ID'><'/RecordList'>

How to cat <<EOF >> a file containing code?

Or, using your EOF markers, you need to quote the initial marker so expansion won't be done:

#-----v---v------
cat <<'EOF' >> brightup.sh
#!/bin/bash
curr=`cat /sys/class/backlight/intel_backlight/actual_brightness`
if [ $curr -lt 4477 ]; then
   curr=$((curr+406));
   echo $curr  > /sys/class/backlight/intel_backlight/brightness;
fi
EOF

IHTH

How to send control+c from a bash script?

ctrl+c and kill -INT <pid> are not exactly the same, to emulate ctrl+c we need to first understand the difference.

kill -INT <pid> will send the INT signal to a given process (found with its pid).

ctrl+c is mapped to the intr special character which when received by the terminal should send INT to the foreground process group of that terminal. You can emulate that by targetting the group of your given <pid>. It can be done by prepending a - before the signal in the kill command. Hence the command you want is:

kill -INT -<pid>

You can test it pretty easily with a script:

#!/usr/bin/env ruby

fork {
    trap(:INT) {
        puts 'signal received in child!'
        exit
    }
    sleep 1_000
}

puts "run `kill -INT -#{Process.pid}` in any other terminal window."
Process.wait

Sources:

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

eslint: error Parsing error: The keyword 'const' is reserved

you also can add this inline instead of config, just add it to the same file before you add your own disable stuff

/* eslint-env es6 */
/* eslint-disable no-console */

my case was disable a file and eslint-disable were not working for me alone

/* eslint-env es6 */
/* eslint-disable */

How to find an object in an ArrayList by property

If you use Java 8 and if it is possible that your search returns null, you could try using the Optional class.

To find a carnet:

private final Optional<Carnet> findCarnet(Collection<Carnet> yourList, String codeIsin){
    // This stream will simply return any carnet that matches the filter. It will be wrapped in a Optional object.
    // If no carnets are matched, an "Optional.empty" item will be returned
    return yourList.stream().filter(c -> c.getCodeIsin().equals(codeIsin)).findAny();
}

Now a usage for it:

public void yourMethod(String codeIsin){
    List<Carnet> listCarnet = carnetEJB.findAll();

    Optional<Carnet> carnetFound = findCarnet(listCarnet, codeIsin);

    if(carnetFound.isPresent()){
        // You use this ".get()" method to actually get your carnet from the Optional object
        doSomething(carnetFound.get());
    }
    else{
        doSomethingElse();
    }
}

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

I came across the same issue recently. I had to insert new rows in a document with hidden rows and faced the same issues with you. After some search and some emails in apache poi list, it seems like a bug in shiftrows() when a document has hidden rows.

How to "EXPIRE" the "HSET" child key in redis?

You could use the Redis Keyspace Notifications by using psubscribe and "__keyevent@<DB-INDEX>__:expired".

With that, each time that a key will expire, you will get a message published on your redis connection.

Regarding your question basically you create a temporary "normal" key using set with an expiration time in s/ms. It should match the name of the key that you wish to delete in your set.

As your temporary key will be published to your redis connection holding the "__keyevent@0__:expired" when it expired, you can easily delete your key from your original set as the message will have the name of the key.

A simple example in practice on that page : https://medium.com/@micah1powell/using-redis-keyspace-notifications-for-a-reminder-service-with-node-c05047befec3

doc : https://redis.io/topics/notifications ( look for the flag xE)

HTML5 Email Validation

Here is the example I use for all of my form email inputs. This example is ASP.NET, but applies to any:

<asp:TextBox runat="server" class="form-control" placeholder="Contact's email" 
    name="contact_email" ID="contact_email" title="Contact's email (format: [email protected])" 
    type="email" TextMode="Email" validate="required:true"
    pattern="[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*" >
</asp:TextBox>

HTML5 still validates using the pattern when not required. Haven't found one yet that was a false positive.

This renders as the following HTML:

<input class="form-control" placeholder="Contact's email" 
    name="contact_email" id="contact_email" type="email" 
    title="Contact's email (format: [email protected])" 
    pattern="[a-zA-Z0-9!#$%&amp;'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*">

Selecting only numeric columns from a data frame

This an alternate code to other answers:

x[, sapply(x, class) == "numeric"]

with a data.table

x[, lapply(x, is.numeric) == TRUE, with = FALSE]

HTML Mobile -forcing the soft keyboard to hide

I am facing the same issue, I am able to hide android keyboard even focus is in textbox by just adding one css property

<input type="text" style="pointer-events:none" />

and it works fine...

Batch file to move files to another directory

Try:

move "C:\files\*.txt" "C:\txt"

Reading file from Workspace in Jenkins with Groovy script

I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.

Turns out it's very easy, there is a readfile step, and I should have rtfm:

env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"

Update all objects in a collection using LINQ

You can use Magiq, a batch operation framework for LINQ.

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In JSF 1.2 this was done by <f:setPropertyActionListener> (within the command component). In JSF 2.0 (EL 2.2 to be precise, thanks to BalusC) it's possible to do it like this: action="${filterList.insert(f.id)}

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

This is indeed a strange error that can be caused by multidexing your app. To get around it, use the following block in your app's build.gradle file:

android {
  splits {
    abi {
        enable true
        reset()
        include 'x86', 'armeabi-v7a'
        universalApk true
    }
  }
  ...[rest of your gradle script]

Move to another EditText when Soft Keyboard Next is clicked on Android

Add inputType to edittext and on enter it will go the next edittext

android:inputType="text"
android:inputType="textEmailAddress"
android:inputType="textPassword" 

and many more.

inputType=textMultiLine does not go to the next edittext on enter

Get current time in milliseconds in Python?

If you want a simple method in your code that returns the milliseconds with datetime:

from datetime import datetime
from datetime import timedelta

start_time = datetime.now()

# returns the elapsed milliseconds since the start of the program
def millis():
   dt = datetime.now() - start_time
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   return ms

initializing strings as null vs. empty string

Best:

 std::string subCondition;

This creates an empty string.

This:

std::string myStr = "";

does a copy initialization - creates a temporary string from "", and then uses the copy constructor to create myStr.

Bonus:

std::string myStr("");

does a direct initialization and uses the string(const char*) constructor.

To check if a string is empty, just use empty().

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

Not exactly the same problem for me, because I was running the last java version 1.8.0_92, IE v11 and windows 7.

My situation was also that I had Chrome as the default browser.

So what for me fixed it, was to set IExplorer as the default browser again, uninstall Java, go to Java.com using the IExplorer, and from the IExplorer download and install Java again to the last version.

Use string in switch case in java

To reduce cyclomatic complexity use a map:

Map<String,Callable<Object>> map = new HashMap < > ( ) ;
map . put ( "apple" , new Callable<Object> () { public Object call ( method1 ( ) ; return null ; } ) ;
...
map . get ( x ) . call ( ) ;

or polymorphism

Htaccess: add/remove trailing slash from URL

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]


<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.

How to make type="number" to positive numbers only

_x000D_
_x000D_
<input type="number" min="1" step="1">
_x000D_
_x000D_
_x000D_

How to switch activity without animation in Android?

Try this code,

this.startActivity(new Intent(v.getContext(), newactivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));

Html: Difference between cell spacing and cell padding

This is the simple answer I can give.

enter image description here

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Only using Session.Clear() when a user logs out can pose a security hole. As the session is still valid as far as the Web Server is concerned. It is then a reasonably trivial matter to sniff, and grab the session Id, and hijack that session.

For this reason, when logging a user out it would be safer and more sensible to use Session.Abandon() so that the session is destroyed, and a new session created (even though the logout UI page would be part of the new session, the new session would not have any of the users details in it and hijacking the new session would be equivalent to having a fresh session, hence it would be mute).

Cannot find control with name: formControlName in angular reactive form

You should specify formGroupName for nested controls

<div class="panel panel-default" formGroupName="address"> <== add this
    <div class="panel-heading">Contact Info</div>

Plunker Example

How to call a shell script from python code?

In case you want to pass some parameters to your shell script, you can use the method shlex.split():

import subprocess
import shlex
subprocess.call(shlex.split('./test.sh param1 param2'))

with test.sh in the same folder:

#!/bin/sh
echo $1
echo $2
exit 0

Outputs:

$ python test.py 
param1
param2

Force “landscape” orientation mode

It is now possible with the HTML5 webapp manifest. See below.


Original answer:

You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.

You can detect the device orientation with CSS3 media queries like this:

@media screen and (orientation:portrait) {
    // CSS applied when the device is in portrait mode
}

@media screen and (orientation:landscape) {
    // CSS applied when the device is in landscape mode
}

Or by binding a JavaScript orientation change event like this:

document.addEventListener("orientationchange", function(event){
    switch(window.orientation) 
    {  
        case -90: case 90:
            /* Device is in landscape mode */
            break; 
        default:
            /* Device is in portrait mode */
    }
});

Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.

As explained on html5rocks.com, you can now force the orientation mode using a manifest.json file.

You need to include those line into the json file:

{
    "display":      "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
    "orientation":  "landscape", /* Could be "landscape" or "portrait" */
    ...
}

And you need to include the manifest into your html file like this:

<link rel="manifest" href="manifest.json">

Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

Get all Attributes from a HTML element with Javascript/jQuery

Very simple. You just need to loop over the attributes element and push their nodeValues into an array:

let att = document.getElementById('id');

let arr = Array();

for (let i = 0; i < att.attributes.length; i++) {
    arr.push(att.attributes[i].nodeValue);
}

If want the name of the attribute you can replace 'nodeValue' for 'nodeName'.

let att = document.getElementById('id');

let arr = Array();

for (let i = 0; i < att.attributes.length; i++) {
    arr.push(att.attributes[i].nodeName);
}

Convert milliseconds to date (in Excel)

Converting your value in milliseconds to days is simply (MsValue / 86,400,000)

We can get 1/1/1970 as numeric value by DATE(1970,1,1)

= (MsValueCellReference / 86400000) + DATE(1970,1,1)

Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss gives me a date and time of 19/04/2010 08:16:11

CSS selector based on element text?

It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:

<li><span class="foo">some text</span></li>
<li>some other text</li>

Then refer to it the usual way:

li > span.foo {...}

How do I run a batch file from my Java Application?

Sometimes the thread execution process time is higher than JVM thread waiting process time, it use to happen when the process you're invoking takes some time to be processed, use the waitFor() command as follows:

try{    
    Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");
    p.waitFor();

}catch( IOException ex ){
    //Validate the case the file can't be accesed (not enought permissions)

}catch( InterruptedException ex ){
    //Validate the case the process is being stopped by some external situation     

}

This way the JVM will stop until the process you're invoking is done before it continue with the thread execution stack.

Changing cell color using apache poi

I believe it is because cell.getCellStyle initially returns the default cell style which you then change.

Create styles like this and apply them to cells:

cellStyle = (XSSFCellStyle) cell.getSheet().getWorkbook().createCellStyle();

Although as the previous poster noted try and create styles and reuse them.

There is also some utility class in the XSSF library that will avoid the code I have provided and automatically try and reuse styles. Can't remember the class 0ff hand.

How and where to use ::ng-deep?

I would emphasize the importance of limiting the ::ng-deep to only children of a component by requiring the parent to be an encapsulated css class.

For this to work it's important to use the ::ng-deep after the parent, not before otherwise it would apply to all the classes with the same name the moment the component is loaded.

Using the :host keyword before ::ng-deep will handle this automatically:

:host ::ng-deep .mat-checkbox-layout

Alternatively you can achieve the same behavior by adding a component scoped CSS class before the ::ng-deep keyword:

.my-component ::ng-deep .mat-checkbox-layout {
    background-color: aqua;
}

Component template:

<h1 class="my-component">
    <mat-checkbox ....></mat-checkbox>
</h1>

Resulting (Angular generated) css will then include the uniquely generated name and apply only to its own component instance:

.my-component[_ngcontent-c1] .mat-checkbox-layout {
    background-color: aqua;
}

HTML input arrays

There are some references and pointers in the comments on this page at PHP.net:

Torsten says

"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."

Jetboy says

"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."

How do I turn a python datetime into a string, with readable format date?

very old question, i know. but with the new f-strings (starting from python 3.6) there are fresh options. so here for completeness:

from datetime import datetime

dt = datetime.now()

# str.format
strg = '{:%B %d, %Y}'.format(dt)
print(strg)  # July 22, 2017

# datetime.strftime
strg = dt.strftime('%B %d, %Y')
print(strg)  # July 22, 2017

# f-strings in python >= 3.6
strg = f'{dt:%B %d, %Y}'
print(strg)  # July 22, 2017

strftime() and strptime() Behavior explains what the format specifiers mean.

Cast object to T

First check to see if it can be cast.

if (readData is T) {
    return (T)readData;
} 
try {
   return (T)Convert.ChangeType(readData, typeof(T));
} 
catch (InvalidCastException) {
   return default(T);
}

How to lay out Views in RelativeLayout programmatically?

From what I've been able to piece together, you have to add the view using LayoutParams.

LinearLayout linearLayout = new LinearLayout(this);

RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

parentView.addView(linearLayout, relativeParams);

All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.

TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);

Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());

How do write IF ELSE statement in a MySQL query

you must write it in SQL not it C/PHP style

IF( action = 2 AND state = 0, 1, 0 ) AS state

for use in query

IF ( action = 2 AND state = 0 ) THEN SET state = 1

for use in stored procedures or functions

How to get access to raw resources that I put in res folder?

InputStream in = getResources().openRawResource(resourceName);

This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.

Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.

DateTime and CultureInfo

You may try the following:

System.Globalization.CultureInfo cultureinfo =
        new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);

How can I get log4j to delete old rotating log files?

Logs rotate for a reason, so that you only keep so many log files around. In log4j.xml you can add this to your node:

<param name="MaxBackupIndex" value="20"/>

The value tells log4j.xml to only keep 20 rotated log files around. You can limit this to 5 if you want or even 1. If your application isn't logging that much data, and you have 20 log files spanning the last 8 months, but you only need a weeks worth of logs, then I think you need to tweak your log4j.xml "MaxBackupIndex" and "MaxFileSize" params.

Alternatively, if you are using a properties file (instead of the xml) and wish to save 15 files (for example)

log4j.appender.[appenderName].MaxBackupIndex = 15

Change DataGrid cell colour based on values

        // Example: Adding a converter to a column (C#)
        Style styleReading = new Style(typeof(TextBlock));
        Setter s = new Setter();
        s.Property = TextBlock.ForegroundProperty;
        Binding b = new Binding();
        b.RelativeSource = RelativeSource.Self;
        b.Path = new PropertyPath(TextBlock.TextProperty);
        b.Converter = new ReadingForegroundSetter();
        s.Value = b;
        styleReading.Setters.Add(s);
        col.ElementStyle = styleReading;

Converting a value to 2 decimal places within jQuery

you can use just javascript for it

var total =10.8
(total).toFixed(2); 10.80


alert(total.toFixed(2))); 

Oracle date format picture ends before converting entire input string

Perhaps you should check NLS_DATE_FORMAT and use the date string conforming the format. Or you can use to_date function within the INSERT statement, like the following:

insert into visit
values(123456, 
       to_date('19-JUN-13', 'dd-mon-yy'),
       to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));

Additionally, Oracle DATE stores date and time information together.

Error in spring application context schema

Referenced file contains errors (http://www.springframework.org/schema/context/spring-context-3.0.xsd)

i faced this problem, when i was configuring dispatcher-servlet.xml ,you can remove this:

xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd"

from your xml and you can also follow the steps go to window -> preferences -> validation -> and unchecked XML validator and XML schema validator.

Update R using RStudio

Don't use Rstudio to update R. Rstudio IS NOT R, Rstudio is just an IDE. This answer is a summary of previous answers for different OS. For all OS it is convenient to have a look in advance what will happen with the packages you have already installed here.

WINDOWS ->> Open CMD/Powershell as an administrator and type "R" to go into interactive mode. If this does not work, search and run RGui.exe instead of writing R in the console ...and then:

lib_path <- gsub( "/", "\\\\" , Sys.getenv("R_LIBS_USER"))
install.packages("installr", lib = lib_path)
install.packages("stringr", lib_path)
library(stringr, lib.loc = lib_path)
library(installr, lib.loc = lib_path)
installr::updateR()

MacOS ->> You can use updateR package. The package is not on CRAN, so you’ll need to run the following code in Rgui:

install.packages("devtools")
devtools::install_github("AndreaCirilloAC/updateR")
updateR(admin_password = "PASSWORD") # Where "PASSWORD" stands for your system password

Note that it is planned to merge updateR and installR in the near future to work for both Mac and Windows.

Linux ->> For the moment installr is NOT available for Linux/MacOS (see documentation for current version 0.20). As R is installed, you can follow these instructions (in Ubuntu, although the idea is the same in other distros: add the source, update and upgrade and install.)

Login to website, via C#

Sometimes, it may help switching off AllowAutoRedirect and setting both login POST and page GET requests the same user agent.

request.UserAgent = userAgent;
request.AllowAutoRedirect = false;

Calling a stored procedure in Oracle with IN and OUT parameters

Go to Menu Tool -> SQL Output, Run the PL/SQL statement, the output will show on SQL Output panel.

Convert datetime object to a String of date only in Python

You can use strftime to help you format your date.

E.g.,

import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

will yield:

'02/23/2012'

More information about formatting see here

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

HTML rows and cols are not responsive!

So I define the size in CSS. As a tip: if you define a small size for mobiles think about using textarea:focus {};

Add some extra space here, which will only unfold the moment a user wants to actually write something

Generating sql insert into for Oracle

If you have an empty table the Export method won't work. As a workaround. I used the Table View of Oracle SQL Developer. and clicked on Columns. Sorted by Nullable so NO was on top. And then selected these non nullable values using shift + select for the range.

This allowed me to do one base insert. So that Export could prepare a proper all columns insert.

Swift apply .uppercaseString to only the first letter of a string

If you want to capitalised each word of string you can use this extension

Swift 4 Xcode 9.2

extension String {
    var wordUppercased: String {
        var aryOfWord = self.split(separator: " ")
        aryOfWord =  aryOfWord.map({String($0.first!).uppercased() + $0.dropFirst()})
        return aryOfWord.joined(separator: " ")
    }
}

Used

print("simple text example".wordUppercased) //output:: "Simple Text Example"

Regular Expressions- Match Anything

I recommend use /(?=.*...)/g

Example

const text1 = 'I am using regex';
/(?=.*regex)/g.test(text1) // true

const text2 = 'regex is awesome';
/(?=.*regex)/g.test(text2) // true

const text3 = 'regex is util';
/(?=.*util)(?=.*regex)/g.test(text3) // true

const text4 = 'util is necessary';
/(?=.*util)(?=.*regex)/g.test(text4) // false because need regex in text

Use regex101 to test

How to add text to JFrame?

You can add a multi-line label with the following:

JLabel label = new JLabel("My label");

label.setText("<html>This is a<br>multline label!<br> Try it yourself!</html>");

From here, simply add the label to the frame using the add() method, and you're all set!

Can a Windows batch file determine its own file name?

You can get the file name, but you can also get the full path, depending what you place between the '%~' and the '0'. Take your pick from

d -- drive
p -- path
n -- file name
x -- extension
f -- full path

E.g., from inside c:\tmp\foo.bat, %~nx0 gives you "foo.bat", whilst %~dpnx0 gives "c:\tmp\foo.bat". Note the pieces are always assembled in canonical order, so if you get cute and try %~xnpd0, you still get "c:\tmp\foo.bat"

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

The Aj334's recent edit works perfectly.

google CDN

<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp" rel="stylesheet">

Icon Element

<i class="material-icons">donut_small</i>
<i class="material-icons-outlined">donut_small</i>
<i class="material-icons-two-tone">donut_small</i>
<i class="material-icons-round">donut_small</i>
<i class="material-icons-sharp">donut_small</i>

Renaming columns in Pandas

Since you only want to remove the $ sign in all column names, you could just do:

df = df.rename(columns=lambda x: x.replace('$', ''))

OR

df.rename(columns=lambda x: x.replace('$', ''), inplace=True)

Write lines of text to a file in R

Based on the best answer:

file <- file("test.txt")
writeLines(yourObject, file)
close(file)

Note that the yourObject needs to be in a string format; use as.character() to convert if you need.

But this is too much typing for every save attempt. Let's create a snippet in RStudio.

In Global Options >> Code >> Snippet, type this:

snippet wfile
    file <- file(${1:filename})
    writeLines(${2:yourObject}, file)
    close(file)

Then, during coding, type wfile and press Tab.

Convert timestamp to readable date/time PHP

$timestamp = 1465298940;
$datetimeFormat = 'Y-m-d H:i:s';

$date = new \DateTime();
// If you must have use time zones
// $date = new \DateTime('now', new \DateTimeZone('Europe/Helsinki'));
$date->setTimestamp($timestamp);
echo $date->format($datetimeFormat);

result: 2016-06-07 14:29:00

Other time zones:

Remove border from buttons

input[type="button"] {
border: none;
outline:none;
}

/usr/bin/codesign failed with exit code 1

One thing that you'll want to watch out for (it's a stupid mistake on my part, but it happens), is that the email address attached to the CSR needs to be the same as the email connected to your Apple Dev account. Once I used a new CSR and rebuilt all the certs and provisioning profiles, all was well in applesville.

Why shouldn't I use "Hungarian Notation"?

If you don't know the type of a variable without being told, you probably shouldn't be messing with it anyways

The type might also not be that important. If you know what the methods do, you can figure out what is being done with the variable and then you'll what the program is doing

There may be times you want it; when type is important and the declaration isn't near or the type can't be inferred with ease. But it should never be seen as absolute

Renaming a directory in C#

There is no difference between moving and renaming; you should simply call Directory.Move.

In general, if you're only doing a single operation, you should use the static methods in the File and Directory classes instead of creating FileInfo and DirectoryInfo objects.

For more advice when working with files and directories, see here.

JSON.Net Self referencing loop detected

The JsonSerializer instance can be configured to ignore reference loops. Like in the following, this function allows to save a file with the content of the json serialized object:

    public static void SaveJson<T>(this T obj, string FileName)
    {
   
       JsonSerializer serializer = new JsonSerializer();
        serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        using (StreamWriter sw = new StreamWriter(FileName))
        {
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;
                serializer.Serialize(writer, obj);
            }
        }
    }

Select statement to find duplicates on certain fields

CREATE TABLE #tmp
(
    sizeId Varchar(MAX)
)

INSERT  #tmp 
    VALUES ('44'),
        ('44,45,46'),
        ('44,45,46'),
        ('44,45,46'),
        ('44,45,46'),
        ('44,45,46'),
        ('44,45,46')


SELECT * FROM #tmp
DECLARE @SqlStr VARCHAR(MAX)

SELECT @SqlStr = STUFF((SELECT ',' + sizeId
              FROM #tmp
              ORDER BY sizeId
              FOR XML PATH('')), 1, 1, '') 


SELECT TOP 1 * FROM (
select items, count(*)AS Occurrence
  FROM dbo.Split(@SqlStr,',')
  group by items
  having count(*) > 1
  )K
  ORDER BY K.Occurrence DESC    

Bootstrap control with multiple "data-toggle"

HTML (ejs dianmic web page): this is a table list of all users and from nodejs generate the table. NodeJS provide dinamic "<%= user.id %>". simply change for any value like "54"

<span type="button" data-href='/admin/user/del/<%= user.id %>' class="item" 
 data-toggle="modal" data-target="#confirm_delete">
    <div data-toggle="tooltip" data-placement="top" title="Delete" data- 
     toggle="modal">
       <i class="zmdi zmdi-delete"></i> 
    </div>
</span>
<div class="modal fade" id="confirm_delete" tabindex="-1" role="dialog" aria-labelledby="staticModalLabel" aria-hidden="true"
         data-backdrop="static">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticModalLabel">Static Modal</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>
      </div>
      <div class="modal-body">
        <p> This is a static modal, backdrop click will not close it. </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <form method="POST" class="btn-ok">
            <input  type="submit" class="btn btn-danger" value="Confirm"></input>
        </form>
      </div>
    </div>
  </div>
</div>
<!-- end modal static --> 

JS:

    $(document).ready(function(){
        $('#confirm_delete').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('action', $(e.relatedTarget).data('href'));
        });
    });

How to add more than one machine to the trusted hosts list using winrm

winrm set winrm/config/client '@{TrustedHosts="machineA,machineB"}'

Ignoring upper case and lower case in Java

I have also tried all the posted code until I found out this one

if(math.toLowerCase(Locale.ENGLISH));

Here whatever character the user input will be converted to lower cases.

Android Percentage Layout Height

There is an attribute called android:weightSum.

You can set android:weightSum="2" in the parent linear_layout and android:weight="1" in the inner linear_layout.

Remember to set the inner linear_layout to fill_parent so weight attribute can work as expected.

Btw, I don't think its necesary to add a second view, altough I haven't tried. :)

<LinearLayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:weightSum="2">

    <LinearLayout
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:layout_weight="1">
    </LinearLayout>

</LinearLayout>

Add and remove attribute with jquery

Once you remove the ID "page_navigation" that element no longer has an ID and so cannot be found when you attempt to access it a second time.

The solution is to cache a reference to the element:

$(document).ready(function(){
    // This reference remains available to the following functions
    // even when the ID is removed.
    var page_navigation = $("#page_navigation1");

    $("#add").click(function(){
        page_navigation.attr("id","page_navigation1");
    });     

    $("#remove").click(function(){
        page_navigation.removeAttr("id");
    });     
});

How to find char in string and get all the indexes?

def find_offsets(haystack, needle):
    """
    Find the start of all (possibly-overlapping) instances of needle in haystack
    """
    offs = -1
    while True:
        offs = haystack.find(needle, offs+1)
        if offs == -1:
            break
        else:
            yield offs

for offs in find_offsets("ooottat", "o"):
    print offs

results in

0
1
2

How to picture "for" loop in block representation of algorithm

Here's a flow chart that illustrates a for loop:

Flow Chart For Loop

The equivalent C code would be

for(i = 2; i <= 6; i = i + 2) {
    printf("%d\t", i + 1);
}

I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.

How to disable Hyper-V in command line?

Open command prompt as admin and write :

bcdedit /set hypervisorlaunchtype off

How to check if all of the following items are in a list?

An example of how to do this using a lambda expression would be:

issublist = lambda x, y: 0 in [_ in x for _ in y]

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

Search for a particular string in Oracle clob column

Use dbms_lob.instr and dbms_lob.substr, just like regular InStr and SubstStr functions.
Look at simple example:

SQL> create table t_clob(
  2    id number,
  3    cl clob
  4  );

Tabela zosta¦a utworzona.

SQL> insert into t_clob values ( 1, ' xxxx abcd xyz qwerty 354657 [] ' );

1 wiersz zosta¦ utworzony.

SQL> declare
  2    i number;
  3  begin
  4    for i in 1..400 loop
  5        update t_clob set cl = cl || ' xxxx abcd xyz qwerty 354657 [] ';
  6    end loop;
  7    update t_clob set cl = cl || ' CALCULATION=[N]NEW.PRODUCT_NO=[T9856] OLD.PRODUCT_NO=[T9852].... -- with other text ';
  8    for i in 1..400 loop
  9        update t_clob set cl = cl || ' xxxx abcd xyz qwerty 354657 [] ';
 10    end loop;
 11  end;
 12  /

Procedura PL/SQL zosta¦a zako?czona pomytlnie.

SQL> commit;

Zatwierdzanie zosta¦o uko?czone.
SQL> select length( cl ) from t_clob;

LENGTH(CL)
----------
     25717

SQL> select dbms_lob.instr( cl, 'NEW.PRODUCT_NO=[' ) from t_clob;

DBMS_LOB.INSTR(CL,'NEW.PRODUCT_NO=[')
-------------------------------------
                                12849

SQL> select dbms_lob.substr( cl, 5,dbms_lob.instr( cl, 'NEW.PRODUCT_NO=[' ) + length( 'NEW.PRODUCT_NO=[') ) new_product
  2  from t_clob;

NEW_PRODUCT
--------------------------------------------------------------------------------
T9856

Python - round up to the nearest ten

You can use math.ceil() to round up, and then multiply by 10

import math

def roundup(x):
    return int(math.ceil(x / 10.0)) * 10

To use just do

>>roundup(45)
50

How to concatenate strings in twig

Whenever you need to use a filter with a concatenated string (or a basic math operation) you should wrap it with ()'s. Eg.:

{{ ('http://' ~ app.request.host) | url_encode }}

What are the -Xms and -Xmx parameters when starting JVM?

Run the command java -X and you will get a list of all -X options:

C:\Users\Admin>java -X
-Xmixed           mixed mode execution (default)
-Xint             interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
-Xdiag            show additional diagnostic messages
-Xnoclassgc       disable class garbage collection
-Xincgc           enable incremental garbage collection
-Xloggc:<file>    log GC status to a file with time stamps
-Xbatch           disable background compilation
-Xms<size>        set initial Java heap size.........................
-Xmx<size>        set maximum Java heap size.........................
-Xss<size>        set java thread stack size
-Xprof            output cpu profiling data
-Xfuture          enable strictest checks, anticipating future default
-Xrs              reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni       perform additional checks for JNI functions
-Xshare:off       do not attempt to use shared class data
-Xshare:auto      use shared class data if possible (default)
-Xshare:on        require using shared class data, otherwise fail.
-XshowSettings    show all settings and continue
-XshowSettings:all         show all settings and continue
-XshowSettings:vm          show all vm related settings and continue
-XshowSettings:properties  show all property settings and continue
-XshowSettings:locale      show all locale related settings and continue

The -X options are non-standard and subject to change without notice.

I hope this will help you understand Xms, Xmx as well as many other things that matters the most. :)

Facebook Javascript SDK Problem: "FB is not defined"

Try to load your scripts in Head section. Moreover, it will be better if you define your scripts under some call like: document.ready, if you defined these scripts in body section

PHP write file from input to txt

Your form should look like this :

<form action="myprocessingscript.php" method="POST">
    <input name="field1" type="text" />
    <input name="field2" type="text" />
    <input type="submit" name="submit" value="Save Data">
</form>

and the PHP

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}

I wrote to /tmp/mydata.txt because this way I know exactly where it is. using data.txt writes to that file in the current working directory which I know nothing of in your example.

file_put_contents opens, writes and closes files for you. Don't mess with it.

Further reading: file_put_contents

JQuery: dynamic height() with window resize()

To see the window height while (or after) it is resized, try it:

$(window).resize(function() {
$('body').prepend('<div>' + $(window).height() - 46 + '</div>');
});

How Connect to remote host from Aptana Studio 3

Window -> Show View -> Other -> Studio/Remote

(Drag this tabbed window wherever)

Click the add FTP button (see below); #profit

Add New FTP Site...

How to draw a filled triangle in android canvas?

you can also use vertice :

private static final int verticesColors[] = {
    Color.LTGRAY, Color.LTGRAY, Color.LTGRAY, 0xFF000000, 0xFF000000, 0xFF000000
};
float verts[] = {
    point1.x, point1.y, point2.x, point2.y, point3.x, point3.y
};
canvas.drawVertices(Canvas.VertexMode.TRIANGLES, verts.length, verts, 0, null, 0, verticesColors,   0, null, 0, 0, new Paint());

Download a file with Android, and showing the progress in a ProgressDialog

I am adding another answer for other solution I am using now because Android Query is so big and unmaintained to stay healthy. So i moved to this https://github.com/amitshekhariitbhu/Fast-Android-Networking.

    AndroidNetworking.download(url,dirPath,fileName).build()
      .setDownloadProgressListener(new DownloadProgressListener() {
        public void onProgress(long bytesDownloaded, long totalBytes) {
            bar.setMax((int) totalBytes);
            bar.setProgress((int) bytesDownloaded);
        }
    }).startDownload(new DownloadListener() {
        public void onDownloadComplete() {
            ...
        }

        public void onError(ANError error) {
            ...
        }
    });

How to add display:inline-block in a jQuery show() function?

Best way is to add !important suffix to the selector .

Example:

 #selector{
     display: inline-block !important;                   
}

How to tell Maven to disregard SSL errors (and trusting all certs)?

You can disable SSL certificate checking by adding one or more of these command line parameters:

  • -Dmaven.wagon.http.ssl.insecure=true - enable use of relaxed SSL check for user generated certificates.
  • -Dmaven.wagon.http.ssl.allowall=true - enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.
  • -Dmaven.wagon.http.ssl.ignore.validity.dates=true - ignore issues with certificate dates.

Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/

Here's the oneliner for an easy copy-and-paste:

-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true

Ajay Gautam suggested that you could also add the above to the ~/.mavenrc file as not to have to specify it every time at command line:

$ cat ~/.mavenrc 
MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"

Styling twitter bootstrap buttons

You can change background-color and use !important;

_x000D_
_x000D_
.btn-primary {_x000D_
  background-color: #003c79 !important;_x000D_
  border-color: #15548b !important;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.btn-primary:hover {_x000D_
  background-color: #4289c6 !important;_x000D_
  border-color: #3877ae !important;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.btn-primary.focus, .btn-primary:focus {_x000D_
   background-color: #4289c6 !important;_x000D_
   border-color: #3877ae !important;_x000D_
   color: #fff;_x000D_
}
_x000D_
_x000D_
_x000D_

Showing an image from console in Python

I made a simple tool that will display an image given a filename or image object or url.
It's crude, but it'll do in a hurry.

Installation:

 $ pip install simple-imshow

Usage:

from simshow import simshow
simshow('some_local_file.jpg')  # display from local file
simshow('http://mathandy.com/escher_sphere.png')  # display from url

How to to send mail using gmail in Laravel?

Note: Laravel 7 replaced MAIL_DRIVER by MAIL_MAILER

MAIL_MAILER=smtp    
MAIL_HOST=smtp.gmail.com   
MAIL_PORT=587      
MAIL_USERNAME=yourgmailaddress
MAIL_PASSWORD=yourgmailpassword
MAIL_ENCRYPTION=tls

Allow less secure apps from "Google Account" - https://myaccount.google.com/ - Settings - Less secure app access (Turn On)

Flush cache config:

php artisan config:cache

For Apache:

sudo service apache2 restart

assign multiple variables to the same value in Javascript

Nothing stops you from doing the above, but hold up!

There are some gotchas. Assignment in Javascript is from right to left so when you write:

var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

it effectively translates to:

var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));

which effectively translates to:

var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));

Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.

Note: My above example assumes you are running your code in the browser, hence window. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global which is the global context for that environment).

Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.

var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.


Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.

Line break in HTML with '\n'

This is to show new line and return carriage in html, then you don't need to do it explicitly. You can do it in css by setting the white-space attribute pre-line value.

<span style="white-space: pre-line">@Model.CommentText</span>

Have border wrap around text

This is because h1 is a block element, so it will extend across the line (or the width you give).

You can make the border go only around the text by setting display:inline on the h1

Example: http://jsfiddle.net/jonathon/XGRwy/1/

php how to go one level up on dirname(__FILE__)

dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder

ReactJS map through Object

Also you can use Lodash to direct convert object to array:

_.toArray({0:{a:4},1:{a:6},2:{a:5}})
[{a:4},{a:6},{a:5}]

In your case:

_.toArray(subjects).map((subject, i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">Name: {subject[name]}</span>
    </li>
))}

GDB: break if variable equal value

There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:

http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html

To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.

watch command is used to set a watchpoit for writing, while rwatch for reading, and awatch for reading/writing.

How does createOrReplaceTempView work in Spark?

createOrReplaceTempView creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.

scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]

scala> s.createOrReplaceTempView("nums")

scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]

scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]

scala> spark.table("nums").count
res24: Long = 3

The data is cached fully only after the .count call. Here's proof it's been cached:

Cached nums temp view/table

Related SO: spark createOrReplaceTempView vs createGlobalTempView

Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables

Note : createOrReplaceTempView was formerly registerTempTable

Why is @font-face throwing a 404 error on woff files?

Also check your URL rewriter. It may throw 404 if something "weird" was found.

How to read a line from a text file in c/c++?

getline() is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.

Assuming std namespace:

 ifstream file1("myfile.txt");
 string stuff;

 while (getline(file1, stuff, '\n')) {
      cout << stuff << endl;
 }

 file1.close();

Bash loop ping successful

You probably shouldn't rely on textual output of a command to decide this, especially when the ping command gives you a perfectly good return value:

The ping utility returns an exit status of zero if at least one response was heard from the specified host; a status of two if the transmission was successful but no responses were received; or another value from <sysexits.h> if an error occurred.

In other words, use something like:

((count = 100))                            # Maximum number to try.
while [[ $count -ne 0 ]] ; do
    ping -c 1 8.8.8.8                      # Try once.
    rc=$?
    if [[ $rc -eq 0 ]] ; then
        ((count = 1))                      # If okay, flag to exit loop.
    fi
    ((count = count - 1))                  # So we don't go forever.
done

if [[ $rc -eq 0 ]] ; then                  # Make final determination.
    echo `say The internet is back up.`
else
    echo `say Timeout.`
fi

Remove trailing comma from comma-separated string

You can use this:

String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));

Pyspark: display a spark data frame in a table format

As mentioned by @Brent in the comment of @maxymoo's answer, you can try

df.limit(10).toPandas()

to get a prettier table in Jupyter. But this can take some time to run if you are not caching the spark dataframe. Also, .limit() will not keep the order of original spark dataframe.

PHP - Get array value with a numeric index

Yes, for scalar values, a combination of implode and array_slice will do:

$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));

Or mix it up with array_values and list (thanks @nikic) so that it works with all types of values:

list($bar) = array_values(array_slice($array, 0, 1));

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

How do I split a string on a delimiter in Bash?

This also works:

IN="[email protected];[email protected]"
echo ADD1=`echo $IN | cut -d \; -f 1`
echo ADD2=`echo $IN | cut -d \; -f 2`

Be careful, this solution is not always correct. In case you pass "[email protected]" only, it will assign it to both ADD1 and ADD2.

In Python, what happens when you import inside of a function?

It imports once when the function is called for the first time.

I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...

Convert bytes to bits in python

using python format string syntax

>>> mybyte = bytes.fromhex("0F") # create my byte using a hex string
>>> binary_string = "{:08b}".format(int(mybyte.hex(),16))
>>> print(binary_string)
00001111

The second line is where the magic happens. All byte objects have a .hex() function, which returns a hex string. Using this hex string, we convert it to an integer, telling the int() function that it's a base 16 string (because hex is base 16). Then we apply formatting to that integer so it displays as a binary string. The {:08b} is where the real magic happens. It is using the Format Specification Mini-Language format_spec. Specifically it's using the width and the type parts of the format_spec syntax. The 8 sets width to 8, which is how we get the nice 0000 padding, and the b sets the type to binary.

I prefer this method over the bin() method because using a format string gives a lot more flexibility.

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Something happened in Java 8 Update 91 that broke existing JSP code. That seems pretty clear. Here is a sample of similar questions and bug reports:

All these are about problems with Java 8 Update 91 (or later) that are not present when using earlier JRE/JDK versions.


The following OpenJDK changeset from 22 January 2016 appears to be related: http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/rev/32f64c19b5fb (commit message "8144430: Improve JMX connections"). The changeset seems to be related to this vulnerability, https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-3427, which is mentioned in a comment to this Red Hat bug report, https://bugzilla.redhat.com/show_bug.cgi?id=1336481.

The Update 91 release notes document mentions JDK-8144430 (non-public ticket): http://www.oracle.com/technetwork/java/javase/8u91-relnotes-2949462.html.

In "Oracle Critical Patch Update Advisory - April 2016", the CVE-2016-3427 vulnerability is mentioned: http://www.oracle.com/technetwork/security-advisory/cpuapr2016v3-2985753.html.

How can I remove the outline around hyperlinks images?

For Remove outline for anchor tag

a {outline : none;}

Remove outline from image link

a img {outline : none;}

Remove border from image link

img {border : 0;}

Invoking JavaScript code in an iframe from the parent page

I found quite an elegant solution.

As you said, it's fairly easy to execute code located on the parent document. And that's the base of my code, do to just the opposite.

When my iframe loads, I call a function located on the parent document, passing as an argument a reference to a local function, located in the iframe's document. The parent document now has a direct access to the iframe's function thru this reference.

Example:

On the parent:

function tunnel(fn) {
    fn();
}

On the iframe:

var myFunction = function() {
    alert("This work!");
}

parent.tunnel(myFunction);

When the iframe loads, it will call parent.tunnel(YourFunctionReference), which will execute the function received in parameter.

That simple, without having to deal with the all the non-standards methods from the various browsers.

How can I get the timezone name in JavaScript?

Retrieve timezone by name (i.e. "America/New York")

moment.tz.guess();

Calculating the sum of two variables in a batch script

@ECHO OFF
ECHO Welcome to my calculator!
ECHO What is the number you want to insert to find the sum?
SET /P Num1=
ECHO What is the second number? 
SET /P Num2=
SET /A Ans=%Num1%+%Num2%
ECHO The sum is: %Ans%
PAUSE>NUL

Pointers in C: when to use the ampersand and the asterisk?

When you are declaring a pointer variable or function parameter, use the *:

int *x = NULL;
int *y = malloc(sizeof(int)), *z = NULL;
int* f(int *x) {
    ...
}

NB: each declared variable needs its own *.

When you want to take the address of a value, use &. When you want to read or write the value in a pointer, use *.

int a;
int *b;
b = f(&a);
a = *b;

a = *f(&a);

Arrays are usually just treated like pointers. When you declare an array parameter in a function, you can just as easily declare it is a pointer (it means the same thing). When you pass an array to a function, you are actually passing a pointer to the first element.

Function pointers are the only things that don't quite follow the rules. You can take the address of a function without using &, and you can call a function pointer without using *.

What are good grep tools for Windows?

I always use WinGREP, but I've had issues with it not letting go of files.

SQL query return data from multiple tables

Part 1 - Joins and Unions

This answer covers:

  1. Part 1
    • Joining two or more tables using an inner join (See the wikipedia entry for additional info)
    • How to use a union query
    • Left and Right Outer Joins (this stackOverflow answer is excellent to describe types of joins)
    • Intersect queries (and how to reproduce them if your database doesn't support them) - this is a function of SQL-Server (see info) and part of the reason I wrote this whole thing in the first place.
  2. Part 2
    • Subqueries - what they are, where they can be used and what to watch out for
    • Cartesian joins AKA - Oh, the misery!

There are a number of ways to retrieve data from multiple tables in a database. In this answer, I will be using ANSI-92 join syntax. This may be different to a number of other tutorials out there which use the older ANSI-89 syntax (and if you are used to 89, may seem much less intuitive - but all I can say is to try it) as it is much easier to understand when the queries start getting more complex. Why use it? Is there a performance gain? The short answer is no, but it is easier to read once you get used to it. It is easier to read queries written by other folks using this syntax.

I am also going to use the concept of a small caryard which has a database to keep track of what cars it has available. The owner has hired you as his IT Computer guy and expects you to be able to drop him the data that he asks for at the drop of a hat.

I have made a number of lookup tables that will be used by the final table. This will give us a reasonable model to work from. To start off, I will be running my queries against an example database that has the following structure. I will try to think of common mistakes that are made when starting out and explain what goes wrong with them - as well as of course showing how to correct them.

The first table is simply a color listing so that we know what colors we have in the car yard.

mysql> create table colors(id int(3) not null auto_increment primary key, 
    -> color varchar(15), paint varchar(10));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from colors;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| color | varchar(15) | YES  |     | NULL    |                |
| paint | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

mysql> insert into colors (color, paint) values ('Red', 'Metallic'), 
    -> ('Green', 'Gloss'), ('Blue', 'Metallic'), 
    -> ('White' 'Gloss'), ('Black' 'Gloss');
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from colors;
+----+-------+----------+
| id | color | paint    |
+----+-------+----------+
|  1 | Red   | Metallic |
|  2 | Green | Gloss    |
|  3 | Blue  | Metallic |
|  4 | White | Gloss    |
|  5 | Black | Gloss    |
+----+-------+----------+
5 rows in set (0.00 sec)

The brands table identifies the different brands of the cars out caryard could possibly sell.

mysql> create table brands (id int(3) not null auto_increment primary key, 
    -> brand varchar(15));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from brands;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| brand | varchar(15) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

mysql> insert into brands (brand) values ('Ford'), ('Toyota'), 
    -> ('Nissan'), ('Smart'), ('BMW');
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from brands;
+----+--------+
| id | brand  |
+----+--------+
|  1 | Ford   |
|  2 | Toyota |
|  3 | Nissan |
|  4 | Smart  |
|  5 | BMW    |
+----+--------+
5 rows in set (0.00 sec)

The model table will cover off different types of cars, it is going to be simpler for this to use different car types rather than actual car models.

mysql> create table models (id int(3) not null auto_increment primary key, 
    -> model varchar(15));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from models;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| model | varchar(15) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> insert into models (model) values ('Sports'), ('Sedan'), ('4WD'), ('Luxury');
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from models;
+----+--------+
| id | model  |
+----+--------+
|  1 | Sports |
|  2 | Sedan  |
|  3 | 4WD    |
|  4 | Luxury |
+----+--------+
4 rows in set (0.00 sec)

And finally, to tie up all these other tables, the table that ties everything together. The ID field is actually the unique lot number used to identify cars.

mysql> create table cars (id int(3) not null auto_increment primary key, 
    -> color int(3), brand int(3), model int(3));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from cars;
+-------+--------+------+-----+---------+----------------+
| Field | Type   | Null | Key | Default | Extra          |
+-------+--------+------+-----+---------+----------------+
| id    | int(3) | NO   | PRI | NULL    | auto_increment |
| color | int(3) | YES  |     | NULL    |                |
| brand | int(3) | YES  |     | NULL    |                |
| model | int(3) | YES  |     | NULL    |                |
+-------+--------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> insert into cars (color, brand, model) values (1,2,1), (3,1,2), (5,3,1), 
    -> (4,4,2), (2,2,3), (3,5,4), (4,1,3), (2,2,1), (5,2,3), (4,5,1);
Query OK, 10 rows affected (0.00 sec)
Records: 10  Duplicates: 0  Warnings: 0

mysql> select * from cars;
+----+-------+-------+-------+
| id | color | brand | model |
+----+-------+-------+-------+
|  1 |     1 |     2 |     1 |
|  2 |     3 |     1 |     2 |
|  3 |     5 |     3 |     1 |
|  4 |     4 |     4 |     2 |
|  5 |     2 |     2 |     3 |
|  6 |     3 |     5 |     4 |
|  7 |     4 |     1 |     3 |
|  8 |     2 |     2 |     1 |
|  9 |     5 |     2 |     3 |
| 10 |     4 |     5 |     1 |
+----+-------+-------+-------+
10 rows in set (0.00 sec)

This will give us enough data (I hope) to cover off the examples below of different types of joins and also give enough data to make them worthwhile.

So getting into the grit of it, the boss wants to know The IDs of all the sports cars he has.

This is a simple two table join. We have a table that identifies the model and the table with the available stock in it. As you can see, the data in the model column of the cars table relates to the models column of the cars table we have. Now, we know that the models table has an ID of 1 for Sports so lets write the join.

select
    ID,
    model
from
    cars
        join models
            on model=ID

So this query looks good right? We have identified the two tables and contain the information we need and use a join that correctly identifies what columns to join on.

ERROR 1052 (23000): Column 'ID' in field list is ambiguous

Oh noes! An error in our first query! Yes, and it is a plum. You see, the query has indeed got the right columns, but some of them exist in both tables, so the database gets confused about what actual column we mean and where. There are two solutions to solve this. The first is nice and simple, we can use tableName.columnName to tell the database exactly what we mean, like this:

select
    cars.ID,
    models.model
from
    cars
        join models
            on cars.model=models.ID

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  3 | Sports |
|  8 | Sports |
| 10 | Sports |
|  2 | Sedan  |
|  4 | Sedan  |
|  5 | 4WD    |
|  7 | 4WD    |
|  9 | 4WD    |
|  6 | Luxury |
+----+--------+
10 rows in set (0.00 sec)

The other is probably more often used and is called table aliasing. The tables in this example have nice and short simple names, but typing out something like KPI_DAILY_SALES_BY_DEPARTMENT would probably get old quickly, so a simple way is to nickname the table like this:

select
    a.ID,
    b.model
from
    cars a
        join models b
            on a.model=b.ID

Now, back to the request. As you can see we have the information we need, but we also have information that wasn't asked for, so we need to include a where clause in the statement to only get the Sports cars as was asked. As I prefer the table alias method rather than using the table names over and over, I will stick to it from this point onwards.

Clearly, we need to add a where clause to our query. We can identify Sports cars either by ID=1 or model='Sports'. As the ID is indexed and the primary key (and it happens to be less typing), lets use that in our query.

select
    a.ID,
    b.model
from
    cars a
        join models b
            on a.model=b.ID
where
    b.ID=1

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  3 | Sports |
|  8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)

Bingo! The boss is happy. Of course, being a boss and never being happy with what he asked for, he looks at the information, then says I want the colors as well.

Okay, so we have a good part of our query already written, but we need to use a third table which is colors. Now, our main information table cars stores the car color ID and this links back to the colors ID column. So, in a similar manner to the original, we can join a third table:

select
    a.ID,
    b.model
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
where
    b.ID=1

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  3 | Sports |
|  8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)

Damn, although the table was correctly joined and the related columns were linked, we forgot to pull in the actual information from the new table that we just linked.

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
where
    b.ID=1

+----+--------+-------+
| ID | model  | color |
+----+--------+-------+
|  1 | Sports | Red   |
|  8 | Sports | Green |
| 10 | Sports | White |
|  3 | Sports | Black |
+----+--------+-------+
4 rows in set (0.00 sec)

Right, that's the boss off our back for a moment. Now, to explain some of this in a little more detail. As you can see, the from clause in our statement links our main table (I often use a table that contains information rather than a lookup or dimension table. The query would work just as well with the tables all switched around, but make less sense when we come back to this query to read it in a few months time, so it is often best to try to write a query that will be nice and easy to understand - lay it out intuitively, use nice indenting so that everything is as clear as it can be. If you go on to teach others, try to instill these characteristics in their queries - especially if you will be troubleshooting them.

It is entirely possible to keep linking more and more tables in this manner.

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1

While I forgot to include a table where we might want to join more than one column in the join statement, here is an example. If the models table had brand-specific models and therefore also had a column called brand which linked back to the brands table on the ID field, it could be done as this:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
            and b.brand=d.ID
where
    b.ID=1

You can see, the query above not only links the joined tables to the main cars table, but also specifies joins between the already joined tables. If this wasn't done, the result is called a cartesian join - which is dba speak for bad. A cartesian join is one where rows are returned because the information doesn't tell the database how to limit the results, so the query returns all the rows that fit the criteria.

So, to give an example of a cartesian join, lets run the following query:

select
    a.ID,
    b.model
from
    cars a
        join models b

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  1 | Sedan  |
|  1 | 4WD    |
|  1 | Luxury |
|  2 | Sports |
|  2 | Sedan  |
|  2 | 4WD    |
|  2 | Luxury |
|  3 | Sports |
|  3 | Sedan  |
|  3 | 4WD    |
|  3 | Luxury |
|  4 | Sports |
|  4 | Sedan  |
|  4 | 4WD    |
|  4 | Luxury |
|  5 | Sports |
|  5 | Sedan  |
|  5 | 4WD    |
|  5 | Luxury |
|  6 | Sports |
|  6 | Sedan  |
|  6 | 4WD    |
|  6 | Luxury |
|  7 | Sports |
|  7 | Sedan  |
|  7 | 4WD    |
|  7 | Luxury |
|  8 | Sports |
|  8 | Sedan  |
|  8 | 4WD    |
|  8 | Luxury |
|  9 | Sports |
|  9 | Sedan  |
|  9 | 4WD    |
|  9 | Luxury |
| 10 | Sports |
| 10 | Sedan  |
| 10 | 4WD    |
| 10 | Luxury |
+----+--------+
40 rows in set (0.00 sec)

Good god, that's ugly. However, as far as the database is concerned, it is exactly what was asked for. In the query, we asked for for the ID from cars and the model from models. However, because we didn't specify how to join the tables, the database has matched every row from the first table with every row from the second table.

Okay, so the boss is back, and he wants more information again. I want the same list, but also include 4WDs in it.

This however, gives us a great excuse to look at two different ways to accomplish this. We could add another condition to the where clause like this:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1
    or b.ID=3

While the above will work perfectly well, lets look at it differently, this is a great excuse to show how a union query will work.

We know that the following will return all the Sports cars:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1

And the following would return all the 4WDs:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=3

So by adding a union all clause between them, the results of the second query will be appended to the results of the first query.

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1
union all
select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=3

+----+--------+-------+
| ID | model  | color |
+----+--------+-------+
|  1 | Sports | Red   |
|  8 | Sports | Green |
| 10 | Sports | White |
|  3 | Sports | Black |
|  5 | 4WD    | Green |
|  7 | 4WD    | White |
|  9 | 4WD    | Black |
+----+--------+-------+
7 rows in set (0.00 sec)

As you can see, the results of the first query are returned first, followed by the results of the second query.

In this example, it would of course have been much easier to simply use the first query, but union queries can be great for specific cases. They are a great way to return specific results from tables from tables that aren't easily joined together - or for that matter completely unrelated tables. There are a few rules to follow however.

  • The column types from the first query must match the column types from every other query below.
  • The names of the columns from the first query will be used to identify the entire set of results.
  • The number of columns in each query must be the same.

Now, you might be wondering what the difference is between using union and union all. A union query will remove duplicates, while a union all will not. This does mean that there is a small performance hit when using union over union all but the results may be worth it - I won't speculate on that sort of thing in this though.

On this note, it might be worth noting some additional notes here.

  • If we wanted to order the results, we can use an order by but you can't use the alias anymore. In the query above, appending an order by a.ID would result in an error - as far as the results are concerned, the column is called ID rather than a.ID - even though the same alias has been used in both queries.
  • We can only have one order by statement, and it must be as the last statement.

For the next examples, I am adding a few extra rows to our tables.

I have added Holden to the brands table. I have also added a row into cars that has the color value of 12 - which has no reference in the colors table.

Okay, the boss is back again, barking requests out - *I want a count of each brand we carry and the number of cars in it!` - Typical, we just get to an interesting section of our discussion and the boss wants more work.

Rightyo, so the first thing we need to do is get a complete listing of possible brands.

select
    a.brand
from
    brands a

+--------+
| brand  |
+--------+
| Ford   |
| Toyota |
| Nissan |
| Smart  |
| BMW    |
| Holden |
+--------+
6 rows in set (0.00 sec)

Now, when we join this to our cars table we get the following result:

select
    a.brand
from
    brands a
        join cars b
            on a.ID=b.brand
group by
    a.brand

+--------+
| brand  |
+--------+
| BMW    |
| Ford   |
| Nissan |
| Smart  |
| Toyota |
+--------+
5 rows in set (0.00 sec)

Which is of course a problem - we aren't seeing any mention of the lovely Holden brand I added.

This is because a join looks for matching rows in both tables. As there is no data in cars that is of type Holden it isn't returned. This is where we can use an outer join. This will return all the results from one table whether they are matched in the other table or not:

select
    a.brand
from
    brands a
        left outer join cars b
            on a.ID=b.brand
group by
    a.brand

+--------+
| brand  |
+--------+
| BMW    |
| Ford   |
| Holden |
| Nissan |
| Smart  |
| Toyota |
+--------+
6 rows in set (0.00 sec)

Now that we have that, we can add a lovely aggregate function to get a count and get the boss off our backs for a moment.

select
    a.brand,
    count(b.id) as countOfBrand
from
    brands a
        left outer join cars b
            on a.ID=b.brand
group by
    a.brand

+--------+--------------+
| brand  | countOfBrand |
+--------+--------------+
| BMW    |            2 |
| Ford   |            2 |
| Holden |            0 |
| Nissan |            1 |
| Smart  |            1 |
| Toyota |            5 |
+--------+--------------+
6 rows in set (0.00 sec)

And with that, away the boss skulks.

Now, to explain this in some more detail, outer joins can be of the left or right type. The Left or Right defines which table is fully included. A left outer join will include all the rows from the table on the left, while (you guessed it) a right outer join brings all the results from the table on the right into the results.

Some databases will allow a full outer join which will bring back results (whether matched or not) from both tables, but this isn't supported in all databases.

Now, I probably figure at this point in time, you are wondering whether or not you can merge join types in a query - and the answer is yes, you absolutely can.

select
    b.brand,
    c.color,
    count(a.id) as countOfBrand
from
    cars a
        right outer join brands b
            on b.ID=a.brand
        join colors c
            on a.color=c.ID
group by
    a.brand,
    c.color

+--------+-------+--------------+
| brand  | color | countOfBrand |
+--------+-------+--------------+
| Ford   | Blue  |            1 |
| Ford   | White |            1 |
| Toyota | Black |            1 |
| Toyota | Green |            2 |
| Toyota | Red   |            1 |
| Nissan | Black |            1 |
| Smart  | White |            1 |
| BMW    | Blue  |            1 |
| BMW    | White |            1 |
+--------+-------+--------------+
9 rows in set (0.00 sec)

So, why is that not the results that were expected? It is because although we have selected the outer join from cars to brands, it wasn't specified in the join to colors - so that particular join will only bring back results that match in both tables.

Here is the query that would work to get the results that we expected:

select
    a.brand,
    c.color,
    count(b.id) as countOfBrand
from
    brands a
        left outer join cars b
            on a.ID=b.brand
        left outer join colors c
            on b.color=c.ID
group by
    a.brand,
    c.color

+--------+-------+--------------+
| brand  | color | countOfBrand |
+--------+-------+--------------+
| BMW    | Blue  |            1 |
| BMW    | White |            1 |
| Ford   | Blue  |            1 |
| Ford   | White |            1 |
| Holden | NULL  |            0 |
| Nissan | Black |            1 |
| Smart  | White |            1 |
| Toyota | NULL  |            1 |
| Toyota | Black |            1 |
| Toyota | Green |            2 |
| Toyota | Red   |            1 |
+--------+-------+--------------+
11 rows in set (0.00 sec)

As we can see, we have two outer joins in the query and the results are coming through as expected.

Now, how about those other types of joins you ask? What about Intersections?

Well, not all databases support the intersection but pretty much all databases will allow you to create an intersection through a join (or a well structured where statement at the least).

An Intersection is a type of join somewhat similar to a union as described above - but the difference is that it only returns rows of data that are identical (and I do mean identical) between the various individual queries joined by the union. Only rows that are identical in every regard will be returned.

A simple example would be as such:

select
    *
from
    colors
where
    ID>2
intersect
select
    *
from
    colors
where
    id<4

While a normal union query would return all the rows of the table (the first query returning anything over ID>2 and the second anything having ID<4) which would result in a full set, an intersect query would only return the row matching id=3 as it meets both criteria.

Now, if your database doesn't support an intersect query, the above can be easily accomlished with the following query:

select
    a.ID,
    a.color,
    a.paint
from
    colors a
        join colors b
            on a.ID=b.ID
where
    a.ID>2
    and b.ID<4

+----+-------+----------+
| ID | color | paint    |
+----+-------+----------+
|  3 | Blue  | Metallic |
+----+-------+----------+
1 row in set (0.00 sec)

If you wish to perform an intersection across two different tables using a database that doesn't inherently support an intersection query, you will need to create a join on every column of the tables.

Is there a Social Security Number reserved for testing/examples?

all zeros would probably be the most obvious that it wasn't a real SSN.

Codeigniter LIKE with wildcard(%)

Searching multiple fields at once can be done like so...

function search($search)
{
    $sql = "SELECT * FROM some_table
    WHERE UPPER(a_name) LIKE ?
    OR
    UPPER(a_full_name) LIKE ?
    OR
    UPPER(a_city) LIKE ?
    OR
    UPPER(a_code) LIKE ?
    ";
    $arr = array_map(array($this,"wrapLIKE"),array($search, $search, $search, $search));
    $r = $this->db->query($sql, $arr);
    return $r;
}

function wrapLIKE($string)
{
    return strtoupper("%$string%");
}

C# get and set properties for a List Collection

If I understand your request correctly, you have to do the following:

public class Section 
{ 
    public String Head
    {
        get
        {
            return SubHead.LastOrDefault();
        }
        set
        {
            SubHead.Add(value);
        }

    public List<string> SubHead { get; private set; }
    public List<string> Content { get; private set; }
} 

You use it like this:

var section = new Section();
section.Head = "Test string";

Now "Test string" is added to the subHeads collection and will be available through the getter:

var last = section.Head; // last will be "Test string"

Hope I understood you correctly.

Update some specific field of an entity in android Room

I think you don't need to update only some specific field. Just update whole data.

@Update query

It is a given query basically. No need to make some new query.

@Dao
interface MemoDao {

    @Insert
    suspend fun insert(memo: Memo)

    @Delete
    suspend fun delete(memo: Memo)

    @Update
    suspend fun update(memo: Memo)
}

Memo.class

@Entity
data class Memo (
    @PrimaryKey(autoGenerate = true) val id: Int,
    @ColumnInfo(name = "title") val title: String?,
    @ColumnInfo(name = "content") val content: String?,
    @ColumnInfo(name = "photo") val photo: List<ByteArray>?
)

Only thing you need to know is 'id'. For instance, if you want to update only 'title', you can reuse 'content' and 'photo' from already inserted data. In real code, use like this

val memo = Memo(id, title, content, byteArrayList)
memoViewModel.update(memo)

Undefined variable: $_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in beforeFind and afterFind:

App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

jQuery UI Sortable Position

As per the official documentation of the jquery sortable UI: http://api.jqueryui.com/sortable/#method-toArray

In update event. use:

var sortedIDs = $( ".selector" ).sortable( "toArray" );

and if you alert or console this var (sortedIDs). You'll get your sequence. Please choose as the "Right Answer" if it is a right one.

Is module __file__ attribute absolute or relative?

Late simple example:

from os import path, getcwd, chdir

def print_my_path():
    print('cwd:     {}'.format(getcwd()))
    print('__file__:{}'.format(__file__))
    print('abspath: {}'.format(path.abspath(__file__)))

print_my_path()

chdir('..')

print_my_path()

Under Python-2.*, the second call incorrectly determines the path.abspath(__file__) based on the current directory:

cwd:     C:\codes\py
__file__:cwd_mayhem.py
abspath: C:\codes\py\cwd_mayhem.py
cwd:     C:\codes
__file__:cwd_mayhem.py
abspath: C:\codes\cwd_mayhem.py

As noted by @techtonik, in Python 3.4+, this will work fine since __file__ returns an absolute path.

Calling async method on button click

You're the victim of the classic deadlock. task.Wait() or task.Result is a blocking call in UI thread which causes the deadlock.

Don't block in the UI thread. Never do it. Just await it.

private async void Button_Click(object sender, RoutedEventArgs 
{
      var task = GetResponseAsync<MyObject>("my url");
      var items = await task;
}

Btw, why are you catching the WebException and throwing it back? It would be better if you simply don't catch it. Both are same.

Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse method. StreamReader.ReadToEnd is a blocking call --you should be using StreamReader.ReadToEndAsync.

Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.

Your method should look something like the following when you've addressed all the above concerns.

public static async Task<List<T>> GetResponseAsync<T>(string url)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    string text = await strReader.ReadToEndAsync();

    return JsonConvert.DeserializeObject<List<T>>(text);
}

Why does SSL handshake give 'Could not generate DH keypair' exception?

The answer above is correct, but in terms of the workaround, I had problems with the BouncyCastle implementation when I set it as preferred provider:

java.lang.ArrayIndexOutOfBoundsException: 64
    at com.sun.crypto.provider.TlsPrfGenerator.expand(DashoA13*..)

This is also discussed in one forum thread I found, which doesn't mention a solution. http://www.javakb.com/Uwe/Forum.aspx/java-programmer/47512/TLS-problems

I found an alternative solution which works for my case, although I'm not at all happy with it. The solution is to set it so that the Diffie-Hellman algorithm is not available at all. Then, supposing the server supports an alternative algorithm, it will be selecting during normal negotiation. Obviously the downside of this is that if somebody somehow manages to find a server that only supports Diffie-Hellman at 1024 bits or less then this actually means it will not work where it used to work before.

Here is code which works given an SSLSocket (before you connect it):

List<String> limited = new LinkedList<String>();
for(String suite : ((SSLSocket)s).getEnabledCipherSuites())
{
    if(!suite.contains("_DHE_"))
    {
        limited.add(suite);
    }
}
((SSLSocket)s).setEnabledCipherSuites(limited.toArray(
    new String[limited.size()]));

Nasty.

Parse an HTML string with JS

1 Way

Use document.cloneNode()

Performance is:

Call to document.cloneNode() took ~0.22499999977299012 milliseconds.

and maybe will be more.

_x000D_
_x000D_
var t0, t1, html;

t0 = performance.now();
   html = document.cloneNode(true);
t1 = performance.now();

console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

html.documentElement.innerHTML = '<!DOCTYPE html><html><head><title>Test</title></head><body><div id="test1">test1</div></body></html>';

console.log(html.getElementById("test1"));
_x000D_
_x000D_
_x000D_

2 Way

Use document.implementation.createHTMLDocument()

Performance is:

Call to document.implementation.createHTMLDocument() took ~0.14000000010128133 milliseconds.

_x000D_
_x000D_
var t0, t1, html;

t0 = performance.now();
html = document.implementation.createHTMLDocument("test");
t1 = performance.now();

console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

html.documentElement.innerHTML = '<!DOCTYPE html><html><head><title>Test</title></head><body><div id="test1">test1</div></body></html>';

console.log(html.getElementById("test1"));
_x000D_
_x000D_
_x000D_

3 Way

Use document.implementation.createDocument()

Performance is:

Call to document.implementation.createHTMLDocument() took ~0.14000000010128133 milliseconds.

var t0 = performance.now();
  html = document.implementation.createDocument('', 'html', 
             document.implementation.createDocumentType('html', '', '')
         );
var t1 = performance.now();

console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

html.documentElement.innerHTML = '<html><head><title>Test</title></head><body><div id="test1">test</div></body></html>';

console.log(html.getElementById("test1"));

4 Way

Use new Document()

Performance is:

Call to document.implementation.createHTMLDocument() took ~0.13499999840860255 milliseconds.

  • Note

ParentNode.append is experimental technology in 2020 year.

var t0, t1, html;

t0 = performance.now();
//---------------
html = new Document();

html.append(
  html.implementation.createDocumentType('html', '', '')
);
    
html.append(
  html.createElement('html')
);
//---------------
t1 = performance.now();

console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

html.documentElement.innerHTML = '<html><head><title>Test</title></head><body><div id="test1">test1</div></body></html>';

console.log(html.getElementById("test1"));

Switch statement: must default be the last case?

There's no defined order in a switch statement. You may look at the cases as something like a named label, like a goto label. Contrary to what people seem to think here, in the case of value 2 the default label is not jumped to. To illustrate with a classical example, here is Duff's device, which is the poster child of the extremes of switch/case in C.

send(to, from, count)
register short *to, *from;
register count;
{
  register n=(count+7)/8;
  switch(count%8){
    case 0: do{ *to = *from++;
    case 7:     *to = *from++;
    case 6:     *to = *from++;
    case 5:     *to = *from++;
    case 4:     *to = *from++;
    case 3:     *to = *from++;
    case 2:     *to = *from++;
    case 1:     *to = *from++;
            }while(--n>0);
  }
}

How to call a parent method from child class in javascript?

How about something based on Douglas Crockford idea:

    function Shape(){}

    Shape.prototype.name = 'Shape';

    Shape.prototype.toString = function(){
        return this.constructor.parent
            ? this.constructor.parent.toString() + ',' + this.name
            : this.name;
    };


    function TwoDShape(){}

    var F = function(){};

    F.prototype = Shape.prototype;

    TwoDShape.prototype = new F();

    TwoDShape.prototype.constructor = TwoDShape;

    TwoDShape.parent = Shape.prototype;

    TwoDShape.prototype.name = '2D Shape';


    var my = new TwoDShape();

    console.log(my.toString()); ===> Shape,2D Shape

0xC0000005: Access violation reading location 0x00000000

The problem here, as explained in other comments, is that the pointer is being dereference without being properly initialized. Operating systems like Linux keep the lowest addresses (eg first 32MB: 0x00_0000 -0x200_0000) out of the virtual address space of a process. This is done because dereferencing zeroed non-initialized pointers is a common mistake, like in this case. So when this type of mistake happens, instead of actually reading a random variable that happens to be at address 0x0 (but not the memory address the pointer would be intended for if initialized properly), the pointer would be reading from a memory address outside of the process's virtual address space. This causes a page fault, which results in a segmentation fault, and a signal is sent to the process to kill it. That's why you are getting the access violation error.

Django, creating a custom 500/404 error page

Django 3.0

here is link how to customize error views

here is link how to render a view

in the urls.py (the main one, in project folder), put:

handler404 = 'my_app_name.views.custom_page_not_found_view'
handler500 = 'my_app_name.views.custom_error_view'
handler403 = 'my_app_name.views.custom_permission_denied_view'
handler400 = 'my_app_name.views.custom_bad_request_view'

and in that app (my_app_name) put in the views.py:

def custom_page_not_found_view(request, exception):
    return render(request, "errors/404.html", {})

def custom_error_view(request, exception=None):
    return render(request, "errors/500.html", {})

def custom_permission_denied_view(request, exception=None):
    return render(request, "errors/403.html", {})

def custom_bad_request_view(request, exception=None):
    return render(request, "errors/400.html", {})

NOTE: error/404.html is the path if you place your files into the projects (not the apps) template foldertemplates/errors/404.html so please place the files where you want and write the right path.

NOTE 2: After page reload, if you still see the old template, change in settings.py DEBUG=True, save it, and then again to False (to restart the server and collect the new files).

jquery ui Dialog: cannot call methods on dialog prior to initialization

Try this instead

$(document).ready(function() {
  $("#divDialog").dialog(opt).dialog("open");
});

You can also do:

var theDialog = $("#divDialog").dialog(opt);
theDialog.dialog("open");

That's because the dialog is not stored in $('#divDialog'), but on a new div that is created on the fly and returned by the .dialog(opt) function.

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

Typing the Enter/Return key using Python and Selenium

For Selenium Remote Control with Java:

selenium.keyPress("elementID", "\13");

For Selenium WebDriver (a.k.a. Selenium 2) with Java:

driver.findElement(By.id("elementID")).sendKeys(Keys.ENTER);

Or,

driver.findElement(By.id("elementID")).sendKeys(Keys.RETURN);

Another way to press Enter in WebDriver is by using the Actions class:

Actions action = new Actions(driver);
action.sendKeys(driver.findElement(By.id("elementID")), Keys.ENTER).build().perform();

How to use private Github repo as npm dependency

With git there is a https format

https://github.com/equivalent/we_demand_serverless_ruby.git

This format accepts User + password

https://bot-user:[email protected]/equivalent/we_demand_serverless_ruby.git

So what you can do is create a new user that will be used just as a bot, add only enough permissions that he can just read the repository you want to load in NPM modules and just have that directly in your packages.json

 Github > Click on Profile > Settings > Developer settings > Personal access tokens > Generate new token

In Select Scopes part, check the on repo: Full control of private repositories

This is so that token can access private repos that user can see

Now create new group in your organization, add this user to the group and add only repositories that you expect to be pulled this way (READ ONLY permission !)

You need to be sure to push this config only to private repo

Then you can add this to your / packages.json (bot-user is name of user, xxxxxxxxx is the generated personal token)

// packages.json


{
  // ....
    "name_of_my_lib": "https://bot-user:[email protected]/ghuser/name_of_my_lib.git"
  // ...
}

https://blog.eq8.eu/til/pull-git-private-repo-from-github-from-npm-modules-or-bundler.html

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

After spending an hour on this error I found that the module file is duplicated. delete the extra file, and shift+cmd+k to clean and the error is gone.

How to verify CuDNN installation?

The installation of CuDNN is just copying some files. Hence to check if CuDNN is installed (and which version you have), you only need to check those files.

Install CuDNN

Step 1: Register an nvidia developer account and download cudnn here (about 80 MB). You might need nvcc --version to get your cuda version.

Step 2: Check where your cuda installation is. For most people, it will be /usr/local/cuda/. You can check it with which nvcc.

Step 3: Copy the files:

$ cd folder/extracted/contents
$ sudo cp include/cudnn.h /usr/local/cuda/include
$ sudo cp lib64/libcudnn* /usr/local/cuda/lib64
$ sudo chmod a+r /usr/local/cuda/lib64/libcudnn*

Check version

You might have to adjust the path. See step 2 of the installation.

$ cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2

Notes

When you get an error like

F tensorflow/stream_executor/cuda/cuda_dnn.cc:427] could not set cudnn filter descriptor: CUDNN_STATUS_BAD_PARAM

with TensorFlow, you might consider using CuDNN v4 instead of v5.

Ubuntu users who installed it via apt: https://askubuntu.com/a/767270/10425

How to find patterns across multiple lines using grep?

With ugrep released a few months ago:

ugrep 'abc(\n|.)+?efg'

This tool is highly optimized for speed. It's also GNU/BSD/PCRE-grep compatible.

Note that we should use a lazy repetition +?, unless you want to match all lines with efg together until the last efg in the file.

Given URL is not permitted by the application configuration

Settings -> Advanced, add url to "Valid OAuth redirect URIs". This works for me.

Passing string to a function in C - with or without pointers?

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

Seeding the random number generator in Javascript

No, it is not possible to seed Math.random(), but it's fairly easy to write your own generator, or better yet, use an existing one.

Check out: this related question.

Also, see David Bau's blog for more information on seeding.

Python Anaconda - How to Safely Uninstall

Uninstalling Anaconda

To uninstall Anaconda, you can do a simple remove of the program. This will leave a few files behind, which for most users is just fine. See Option A.

If you also want to remove all traces of the configuration files and directories from Anaconda and its programs, you can download and use the Anaconda-Clean program first, then do a simple remove. See Option B.

Option A.

Use simple remove to uninstall Anaconda:

macOS–Open the Terminal.app or iTerm2 terminal application, and then remove your entire Anaconda directory, which has a name such as anaconda2 or anaconda3, by entering rm -rf ~/anaconda3.

Option B.

Full uninstall using Anaconda-Clean and simple remove.

NOTE: Anaconda-Clean must be run before simple remove.

Install the Anaconda-Clean package from Anaconda Prompt or a terminal window:

conda install anaconda-clean

In the same window, run one of these commands:

Remove all Anaconda-related files and directories with a confirmation prompt before deleting each one:

anaconda-clean

Or, remove all Anaconda-related files and directories without being prompted to delete each one:

anaconda-clean --yes

Anaconda-Clean creates a backup of all files and directories that might be removed, such as .bash_profile, in a folder named .anaconda_backup in your home directory. Also note that Anaconda-Clean leaves your data files in the AnacondaProjects directory untouched. After using Anaconda-Clean, follow the instructions above in Option A to uninstall Anaconda. Removing Anaconda path from .bash_profile

If you use Linux or macOS, you may also wish to check the .bash_profilefile in your home directory for a line such as:

export PATH="/Users/jsmith/anaconda3/bin:$PATH"

NOTE: Replace /Users/jsmith/anaconda3/ with your actual path.

This line adds the Anaconda path to the PATH environment variable. It may refer to either Anaconda or Miniconda. After uninstalling Anaconda, you may delete this line and save the file.

by official uninstalling way

How to run eclipse in clean mode? what happens if we do so?

What it does:

if set to "true", any cached data used by the OSGi framework and eclipse runtime will be wiped clean. This will clean the caches used to store bundle dependency resolution and eclipse extension registry data. Using this option will force eclipse to reinitialize these caches.

How to use it:

  • Edit the eclipse.ini file located in your Eclipse install directory and insert -clean as the first line.
  • Or edit the shortcut you use to start Eclipse and add -clean as the first argument.
  • Or create a batch or shell script that calls the Eclipse executable with the -clean argument. The advantage to this step is you can keep the script around and use it each time you want to clean out the workspace. You can name it something like eclipse-clean.bat (or eclipse-clean.sh).

(From: http://www.eclipsezone.com/eclipse/forums/t61566.html)

Other eclipse command line options: http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html

doGet and doPost in Servlets

Both GET and POST are used by the browser to request a single resource from the server. Each resource requires a separate GET or POST request.

  1. The GET method is most commonly (and is the default method) used by browsers to retrieve information from servers. When using the GET method the 3rd section of the request packet, which is the request body, remains empty.

The GET method is used in one of two ways: When no method is specified, that is when you or the browser is requesting a simple resource such as an HTML page, an image, etc. When a form is submitted, and you choose method=GET on the HTML tag. If the GET method is used with an HTML form, then the data collected through the form is sent to the server by appending a "?" to the end of the URL, and then adding all name=value pairs (name of the html form field and value entered in that field) separated by an "&" Example: GET /sultans/shop//form1.jsp?name=Sam%20Sultan&iceCream=vanilla HTTP/1.0 optional headeroptional header<< empty line >>>

The name=value form data will be stored in an environment variable called QUERY_STRING. This variable will be sent to a processing program (such as JSP, Java servlet, PHP etc.)

  1. The POST method is used when you create an HTML form, and request method=POST as part of the tag. The POST method allows the client to send form data to the server in the request body section of the request (as discussed earlier). The data is encoded and is formatted similar to the GET method, except that the data is sent to the program through the standard input.

Example: POST /sultans/shop//form1.jsp HTTP/1.0 optional headeroptional header<< empty line >>> name=Sam%20Sultan&iceCream=vanilla

When using the post method, the QUERY_STRING environment variable will be empty. Advantages/Disadvantages of GET vs. POST

Advantages of the GET method: Slightly faster Parameters can be entered via a form or by appending them after the URL Page can be bookmarked with its parameters

Disadvantages of the GET method: Can only send 4K worth of data. (You should not use it when using a textarea field) Parameters are visible at the end of the URL

Advantages of the POST method: Parameters are not visible at the end of the URL. (Use for sensitive data) Can send more that 4K worth of data to server

Disadvantages of the POST method: Can cannot be bookmarked with its data

Marker in leaflet, click event

Additional relevant info: A common need is to pass the ID of the object represented by the marker to some ajax call for the purpose of fetching more info from the server.

It seems that when we do:

marker.on('click', function(e) {...

The e points to a MouseEvent, which does not let us get to the marker object. But there is a built-in this object which strangely, requires us to use this.options to get to the options object which let us pass anything we need. In the above case, we can pass some ID in an option, let's say objid then within the function above, we can get the value by invoking: this.options.objid

How to set up a cron job to run an executable every hour?

You can also use @hourly instant of 0 * * * *

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

It looks like the string contains an array with a single MyStok object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStok objects, and take the object at index zero.

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];

How to properly make a http web GET request

Adding to the responses already given, this is a complete example hitting JSON PlaceHolder site.

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Publish
{
    class Program
    {
        static async Task Main(string[] args)
        {
            
            // Get Reqeust
            HttpClient req = new HttpClient();
            var content = await req.GetAsync("https://jsonplaceholder.typicode.com/users");
            Console.WriteLine(await content.Content.ReadAsStringAsync());

            // Post Request
            Post p = new Post("Some title", "Some body", "1");
            HttpContent payload = new StringContent(JsonConvert.SerializeObject(p));
            content = await req.PostAsync("https://jsonplaceholder.typicode.com/posts", payload);
            Console.WriteLine("--------------------------");
            Console.WriteLine(content.StatusCode);
            Console.WriteLine(await content.Content.ReadAsStringAsync());
        }
    }

    public struct Post {
        public string Title {get; set;}
        public string Body {get;set;}
        public string UserID {get; set;}

        public Post(string Title, string Body, string UserID){
            this.Title = Title;
            this.Body = Body;
            this.UserID = UserID;
        }
    }
}

Put text at bottom of div

<div id="container">
    <div><span>Two Words</span></div>
    <div><span>Two Words</span></div>
    <div><span>Two Words</span></div>
    <div><span>Two Words</span></div>
</div>

#container{
    width:450px;
    height:200px;
    margin:0px auto;
    border:1px solid red;
}

#container div{
    position:relative;
    width:100px;
    height:100px;
    border:1px solid #ccc;
    float:left;
    margin-right:5px;
}
#container div span{
    position:absolute;
    bottom:0;
    right:0;
}

Check working example at http://jsfiddle.net/7YTYu/2/

Retaining file permissions with Git

Git is Version Control System, created for software development, so from the whole set of modes and permissions it stores only executable bit (for ordinary files) and symlink bit. If you want to store full permissions, you need third party tool, like git-cache-meta (mentioned by VonC), or Metastore (used by etckeeper). Or you can use IsiSetup, which IIRC uses git as backend.

See Interfaces, frontends, and tools page on Git Wiki.

How to set height property for SPAN

span { display: table-cell; height: (your-height + px); vertical-align: middle; }

For spans to work like a table-cell (or any other element, for that matter), height must be specified. I've given spans a height, and they work just fine--but you must add height to get them to do what you want.

How to show/hide JPanels in a JFrame?

You can hide a JPanel by calling setVisible(false). For example:

public static void main(String args[]){
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    //create a button which will hide the panel when clicked.
    JButton b = new JButton("HIDE");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p.setVisible(false);
        }
    });

    f.add(b,BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
}

How can I display the users profile pic using the facebook graph api?

EDIT: So facebook has changed it again! No more searching by username - have amended the answer below...

https://graph.facebook.com/{{UID}}/picture?redirect=false&height=200&width=200
  • UID = the profile or page id
  • redirect either returns json (false) or redirects to the image (true)
  • height and width is the crop
  • does not require authentication

e.g. https://graph.facebook.com/4/picture?redirect=false&height=200&width=200

Facebook Graph picture doc

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

What about this?

java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");

react hooks useEffect() cleanup for only componentWillUnmount?

To add to the accepted answer, I had a similar issue and solved it using a similar approach with the contrived example below. In this case I needed to log some parameters on componentWillUnmount and as described in the original question I didn't want it to log every time the params changed.

const componentWillUnmount = useRef(false)

// This is componentWillUnmount
useEffect(() => {
    return () => {
        componentWillUnmount.current = true
    }
}, [])

useEffect(() => {
    return () => {
        // This line only evaluates to true after the componentWillUnmount happens 
        if (componentWillUnmount.current) {
            console.log(params)
        }
    }

}, [params]) // This dependency guarantees that when the componentWillUnmount fires it will log the latest params

Checking if a list of objects contains a property with a specific value

myList.Where(item=>item.Name == nameToExtract)

git rebase merge conflict

If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".

First, checkout temp branch and start standard merge

git checkout -b temp
git merge origin/master

You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.

git commit -m "Merge branch 'origin/master' into 'temp'"

Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.

git checkout alpha
git rebase origin/master -X theirs

Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.

git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)

And delete temporary branch

git branch -D temp

That's all. We did a rebase via hidden merge.

Also I wrote a script, so that can be done in a dialog manner, you can find it here.

Command line input in Python

Just Taking Input

the_input = raw_input("Enter input: ")

And that's it.

Moreover, if you want to make a list of inputs, you can do something like:

a = []

for x in xrange(1,10):
    a.append(raw_input("Enter Data: "))

In that case, you'll be asked for data 10 times to store 9 items in a list.

Output:

Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']

You can search that list the fundamental way with something like (after making that list):

if '2' in a:
    print "Found"

else: print "Not found."

You can replace '2' with "raw_input()" like this:

if raw_input("Search for: ") in a:
    print "Found"
else: 
    print "Not found"

Taking Raw Data From Input File via Commandline Interface

If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):

example.py

while(True):
    line = raw_input()
    print "input data: %s" % line

In command line interface:

example.py < input.txt

Hope that helps.

bash string compare to multiple correct values

Instead of saying:

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

say:

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

You might also want to refer to Conditional Constructs.

Use jquery click to handle anchor onClick()

The HTML should look like:

<div class="solTitle"> <a href="#"  id="solution0">Solution0 </a></div>
<div class="solTitle"> <a href="#"  id="solution1">Solution1 </a></div>

<div id="summary_solution0" style="display:none" class="summary">Summary solution0</div>
<div id="summary_solution1" style="display:none" class="summary">Summary solution1</div>

And the javascript:

$(document).ready(function(){
    $(".solTitle a").live('click',function(e){
        var contentId = "summary_" + $(this).attr('id');
        $(".summary").hide();
        $("#" + contentId).show();
    });
});

See the Example: http://jsfiddle.net/kmendes/4G9UF/

Is Fortran easier to optimize than C for heavy calculations?

There is no such thing as one language being faster than another, so the proper answer is no.

What you really have to ask is "is code compiled with Fortran compiler X faster than equivalent code compiled with C compiler Y?" The answer to that question of course depends on which two compilers you pick.

Another question one could ask would be along the lines of "Given the same amount of effort put into optimizing in their compilers, which compiler would produce faster code?" The answer to this would in fact be Fortran. Fortran compilers have certian advantages:

  • Fortran had to compete with Assembly back in the day when some vowed never to use compilers, so it was designed for speed. C was designed to be flexible.
  • Fortran's niche has been number crunching. In this domain code is never fast enough. So there's always been a lot of pressure to keep the language efficient.
  • Most of the research in compiler optimizations is done by people interested in speeding up Fortran number crunching code, so optimizing Fortran code is a much better known problem than optimizing any other compiled language, and new innovations show up in Fortran compilers first.
  • Biggie: C encourages much more pointer use than Fortran. This drasticly increases the potential scope of any data item in a C program, which makes them far harder to optimize. Note that Ada is also way better than C in this realm, and is a much more modern OO Language than the commonly found Fortran77. If you want an OO langauge that can generate faster code than C, this is an option for you.
  • Due again to its number-crunching niche, the customers of Fortran compilers tend to care more about optimization than the customers of C compilers.

However, there is nothing stopping someone from putting a ton of effort into their C compiler's optimization, and making it generate better code than their platform's Fortran compiler. In fact, the larger sales generated by C compilers makes this scenario quite feasible

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

Put this on routes.php file:

\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    echo'<pre>';
    var_dump($query->sql);
    var_dump($query->bindings);
    var_dump($query->time);
    echo'</pre>';
});

Submitted by msurguy, source code in this page. You will find this fix-code for laravel 5.2 in comments.

How to mark a build unstable in Jenkins when running shell scripts

It can be done without printing magic strings and using TextFinder. Here's some info on it.

Basically you need a .jar file from http://yourserver.com/cli available in shell scripts, then you can use the following command to mark a build unstable:

java -jar jenkins-cli.jar set-build-result unstable

To mark build unstable on error, you can use:

failing_cmd cmd_args || java -jar jenkins-cli.jar set-build-result unstable

The problem is that jenkins-cli.jar has to be available from shell script. You can either put it in easy-to-access path, or download in via job's shell script:

wget ${JENKINS_URL}jnlpJars/jenkins-cli.jar

Npm install cannot find module 'semver'

Actually, it is taking the reference of previously stored modules.

Solution:Delete the npm-cache/npm folder in the installation directory of nodejs. In windows, it is in C:/User/Username/Appdata/Roaming/npm(or npm_cache). and try to install again.

Same thing to do in any OS.

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

This might sound really simplistic...

But this will center the div inside the div, exactly in the center in relation to left and right margin or parent container, but you can adjust percentage symmetrically on left and right.

margin-right: 10%;
margin-left: 10%;

Then you can adjust % to make it as wide as you want it.

PHP: Calling another class' method

File 1

class ClassA {

    public $name = 'A';

    public function getName(){
        return $this->name;
    }

}

File 2

include("file1.php");
class ClassB {

    public $name = 'B';

    public function getName(){
        return $this->name;
    }

    public function callA(){
        $a = new ClassA();
        return $a->getName();
    }

    public static function callAStatic(){
        $a = new ClassA();
        return $a->getName();
    }

}

$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();

Round integers to the nearest 10

Slightly simpler:

def round_int(x):
    return 10 * ((x + 5) // 10)

Using await outside of an async function

As of Node.js 14.3.0 the top-level await is supported.

Required flag: --experimental-top-level-await.

Further details: https://v8.dev/features/top-level-await

How to for each the hashmap?

Use entrySet,

/**
 *Output: 
D: 99.22
A: 3434.34
C: 1378.0
B: 123.22
E: -19.08

B's new balance: 1123.22
 */

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MainClass {
  public static void main(String args[]) {

    HashMap<String, Double> hm = new HashMap<String, Double>();

    hm.put("A", new Double(3434.34));
    hm.put("B", new Double(123.22));
    hm.put("C", new Double(1378.00));
    hm.put("D", new Double(99.22));
    hm.put("E", new Double(-19.08));

    Set<Map.Entry<String, Double>> set = hm.entrySet();

    for (Map.Entry<String, Double> me : set) {
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }

    System.out.println();

    double balance = hm.get("B");
    hm.put("B", balance + 1000);

    System.out.println("B's new balance: " + hm.get("B"));
  }
}

see complete example here:

strcpy() error in Visual studio 2012

A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings

Right-click your C++ and chose the "Properties" item to get to the properties window.

Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".

In the "Preprocessor definitions" add

_CRT_SECURE_NO_WARNINGS

but it would be a good idea to add

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)

as to inherit predefined definitions

IMHO & for the most part this is a good approach.

How to use lodash to find and return an object from Array?

Fetch id basing on name

 {
    "roles": [
     {
      "id": 1,
      "name": "admin",
     },
     {
      "id": 3,
      "name": "manager",
     }
    ]
    }



    fetchIdBasingOnRole() {
          const self = this;
          if (this.employee.roles) {
            var roleid = _.result(
              _.find(this.getRoles, function(obj) {
                return obj.name === self.employee.roles;
              }),
              "id"
            );
          }
          return roleid;
        },

RegEx for Javascript to allow only alphanumeric

I have string similar to Samsung Galaxy A10s 6.2-Inch (2GB,32GB ROM) Android 9.0, (13MP+2MP)+ 8MP Dual SIM 4000mAh 4G LTE Smartphone - Black (BF19)

Below is what i did:

string.replace(/[^a-zA-Z0-9 ,._-]/g, '').split(',').join('-').split(' ').join('-').toLowerCase()

Notice i allowed ,._- then use split() and join() to replace , to - and space to - respectively.

I ended up getting something like this: samsung-galaxy-a10s-6.2-inch-2gb-32gb-rom-android-9.0-13mp-2mp-8mp-dual-sim-4000mah-4g-lte-smartphone-black-bf19-20 which is what i wanted.

There might be a better solution but this is what i found working fine for me.

How do I export (and then import) a Subversion repository?

You can also use svnsync. This only requires read-only access on the source repository

more at svnbook

TypeError: $ is not a function when calling jQuery function

You can use

jQuery(document).ready(function(){ ...... });

or

(function ($) { ...... }(jQuery));

Trigger an action after selection select2

See the documentation events section

Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".

Version 4.0 +

Events are now in format: select2:selecting (instead of select2-selecting)

Thanks to snakey for the notification that this has changed as of 4.0

$('#yourselect').on("select2:selecting", function(e) { 
   // what you would like to happen
});

Version Before 4.0

$('#yourselect').on("select2-selecting", function(e) { 
   // what you would like to happen
});

Just to clarify, the documentation for select2-selecting reads:

select2-selecting Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()

whereas change has:

change Fired when selection is changed.

So change may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.

How can I set the form action through JavaScript?

document.forms[0].action="http://..."

...assuming it is the first form on the page.

How do I parse JSON in Android?

I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:

try{
    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient();
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet("http://example.json");

    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json);

} catch(Exception e){
    // In your production code handle any errors and catch the individual exceptions
    e.printStackTrace();
}

Once you have your JSONObject refer to the SDK for details on how to extract the data you require.

Why ModelState.IsValid always return false in mvc

"ModelState.IsValid" tells you that the model is consumed by the view (i.e. PaymentAdviceEntity) is satisfy all types of validation or not specified in the model properties by DataAnotation.

In this code the view does not bind any model properties. So if you put any DataAnotations or validation in model (i.e. PaymentAdviceEntity). then the validations are not satisfy. say if any properties in model is Name which makes required in model.Then the value of the property remains blank after post.So the model is not valid (i.e. ModelState.IsValid returns false). You need to remove the model level validations.

Please initialize the log4j system properly warning

None of answered method solve the problem which log4j.properties file is not found for non-maven jsf web project in NetBeans. So the answer is:

  1. Create a folder named resources in project root folder (outermost folder).
  2. Right click project in projects explorer in left menu, select properties.
  3. Open Sources in Categories, add that folder in Source Package Folders.
  4. Open Run in Categories and add this to VM options: Dlog4j.configuration=resources/log4j.properties
  5. Click Ok, build and deploy project as you like, that's it.

I wrote special pattern in log4j file to check whether log4j is used my file:

# Root Logger Option
log4j.rootLogger=INFO, console

# Redirect Log Messages To Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-5p | %d{yyyy-MM-dd HH:mm:ss} | [%t] %C{2} xxxx (%F:%L) - %m%n

I checked it because if you use BasicConfigurator.configure(); in your code in log4j use predefined pattern.