Programs & Examples On #Email publisher

iPhone X / 8 / 8 Plus CSS media queries

iPhone X

@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

iPhone 8

@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

iPhone 8 Plus

@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }


iPhone 6+/6s+/7+/8+ share the same sizes, while the iPhone 7/8 also do.


Looking for a specific orientation ?

Portrait

Add the following rule:

    and (orientation : portrait) 

Landscape

Add the following rule:

    and (orientation : landscape) 



References:

Changing EditText bottom line color with appcompat v7

It's very easy just add android:backgroundTint attribute in your EditText.

android:backgroundTint="@color/blue"
android:backgroundTint="#ffffff"
android:backgroundTint="@color/red"


 <EditText
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:backgroundTint="#ffffff"/>

Convert an array to string

You probably want something like this overload of String.Join:

String.Join<T> Method (String, IEnumerable<T>)

Docs:

http://msdn.microsoft.com/en-us/library/dd992421.aspx

In your example, you'd use

String.Join("", Client);

CAST DECIMAL to INT

There's also ROUND() if your numbers don't necessarily always end with .00. ROUND(20.6) will give 21, and ROUND(20.4) will give 20.

Enabling WiFi on Android Emulator

(Repeating here my answer elsewhere.)

In theory, linux (the kernel underlying android) has mac80211_hwsim driver, which simulates WiFi. It can be used to set up several WiFi devices (an acces point, and another WiFi device, and so on), which would make up a WiFi network.

It's useful for testing WiFi programs under linux. Possibly, even under user-mode linux or other isolated virtual "boxes" with linux.

In theory, this driver could be used for tests in the android systems where you don't have a real WiFi device (or don't want to use it), and also in some kind of android emulators. Perhaps, one can manage to use this driver in android-x86, or--for testing--in android-x86 run in VirtualBox.

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

This worked for me:

    <dependency>
        <groupId>jdk.tools</groupId>
        <artifactId>jdk.tools</artifactId>
        <version>1.7.0_05</version>
        <scope>system</scope>
        <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
    </dependency>

react-native - Fit Image in containing View, not the whole screen size

I think it's because you didn't specify the width and height for the item.

If you only want to have 2 images in a row, you can try something like this instead of using flex:

item: {
    width: '50%',
    height: '100%',
    overflow: 'hidden',
    alignItems: 'center',
    backgroundColor: 'orange',
    position: 'relative',
    margin: 10,
},

This works for me, hope it helps.

Python 101: Can't open file: No such file or directory

Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.

How to get row count using ResultSet in Java?

Do a SELECT COUNT(*) FROM ... query instead.

Import Excel Spreadsheet Data to an EXISTING sql table?

You can use import data with wizard and there you can choose destination table.

Run the wizard. In selecting source tables and views window you see two parts. Source and Destination.

Click on the field under Destination part to open the drop down and select you destination table and edit its mappings if needed.

EDIT

Merely typing the name of the table does not work. It appears that the name of the table must include the schema (dbo) and possibly brackets. Note the dropdown on the right hand side of the text field.

enter image description here

ProcessStartInfo hanging on "WaitForExit"? Why?

I was having the same issue, but the reason was different. It would however happen under Windows 8, but not under Windows 7. The following line seems to have caused the problem.

pProcess.StartInfo.UseShellExecute = False

The solution was to NOT disable UseShellExecute. I now received a Shell popup window, which is unwanted, but much better than the program waiting for nothing particular to happen. So I added the following work-around for that:

pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

Now the only thing bothering me is to why this is happening under Windows 8 in the first place.

How to calculate Date difference in Hive

I would try this first

select * from employee where month(current_date)-3 = month(joining_date)

Best Practices for Custom Helpers in Laravel 5

my initial thought was the composer autoload as well, but it didn't feel very Laravel 5ish to me. L5 makes heavy use of Service Providers, they are what bootstraps your application.

To start off I created a folder in my app directory called Helpers. Then within the Helpers folder I added files for functions I wanted to add. Having a folder with multiple files allows us to avoid one big file that gets too long and unmanageable.

Next I created a HelperServiceProvider.php by running the artisan command:

artisan make:provider HelperServiceProvider

Within the register method I added this snippet

public function register()
{
    foreach (glob(app_path().'/Helpers/*.php') as $filename){
        require_once($filename);
    }
}

lastly register the service provider in your config/app.php in the providers array

'providers' => [
    'App\Providers\HelperServiceProvider',
]

now any file in your Helpers directory is loaded, and ready for use.

UPDATE 2016-02-22

There are a lot of good options here, but if my answer works for you, I went ahead and made a package for including helpers this way. You can either use the package for inspiration or feel free to download it with Composer as well. It has some built in helpers that I use often (but which are all inactive by default) and allows you to make your own custom helpers with a simple Artisan generator. It also addresses the suggestion one responder had of using a mapper and allows you to explicitly define the custom helpers to load, or by default, automatically load all PHP files in your helper directory. Feedback and PRs are much appreciated!

composer require browner12/helpers

Github: browner12/helpers

Get last dirname/filename in a file path argument in Bash

The following approach can be used to get any path of a pathname:

some_path=a/b/c
echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))

Output:

c
b
a

Nodejs - Redirect url

You have to use the following code:

response.writeHead(302 , {
           'Location' : '/view/index.html' // This is your url which you want
        });
response.end();

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Pass in an array of Deferreds to $.when()

I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.

Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.

    // 1st
    function Outer() {
        var deferreds = GetAllData();

        $.when.apply($, deferreds).done(function () {
            // now you can do whatever you want with the updated page
        });
    }

    // 2nd
    function GetAllData() {
        var deferreds = [];
        $('.calculatedField').each(function (data) {
            deferreds.push(GetIndividualData($(this)));
        });
        return deferreds;
    }

    // 3rd
    function GetIndividualData(item) {
        var def = new $.Deferred();
        $.post('@Url.Action("GetData")', function (data) {
            item.html(data.valueFromAjax);
            def.resolve(data);
        });
        return def;
    }

Generating random strings with T-SQL

Similar to the first example, but with more flexibility:

-- min_length = 8, max_length = 12
SET @Length = RAND() * 5 + 8
-- SET @Length = RAND() * (max_length - min_length + 1) + min_length

-- define allowable character explicitly - easy to read this way an easy to 
-- omit easily confused chars like l (ell) and 1 (one) or 0 (zero) and O (oh)
SET @CharPool = 
    'abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789.,-_!$@#%^&*'
SET @PoolLength = Len(@CharPool)

SET @LoopCount = 0
SET @RandomString = ''

WHILE (@LoopCount < @Length) BEGIN
    SELECT @RandomString = @RandomString + 
        SUBSTRING(@Charpool, CONVERT(int, RAND() * @PoolLength) + 1, 1)
    SELECT @LoopCount = @LoopCount + 1
END

I forgot to mention one of the other features that makes this more flexible. By repeating blocks of characters in @CharPool, you can increase the weighting on certain characters so that they are more likely to be chosen.

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

Well, this answer has become its own beast. Many new versions, it was getting stupid long. Many thanks to all of the great many contributors to this answer. But, in order to keep it simple for the masses. I archived all the versions/history of this answer's evolution to my github. And started it over clean on StackOverflow here with the newest version. A special thanks goes out to Mike 'Pomax' Kamermans for this version. He gave me the new math.


This function (pSBC) will take a HEX or RGB web color. pSBC can shade it darker or lighter, or blend it with a second color, and can also pass it right thru but convert from Hex to RGB (Hex2RGB) or RGB to Hex (RGB2Hex). All without you even knowing what color format you are using.

This runs really fast, probably the fastest, especially considering its many features. It was a long time in the making. See the whole story on my github. If you want the absolutely smallest and fastest possible way to shade or blend, see the Micro Functions below and use one of the 2-liner speed demons. They are great for intense animations, but this version here is fast enough for most animations.

This function uses Log Blending or Linear Blending. However, it does NOT convert to HSL to properly lighten or darken a color. Therefore, results from this function will differ from those much larger and much slower functions that use HSL.

jsFiddle with pSBC

github > pSBC Wiki

Features:

  • Auto-detects and accepts standard Hex colors in the form of strings. For example: "#AA6622" or "#bb551144".
  • Auto-detects and accepts standard RGB colors in the form of strings. For example: "rgb(123,45,76)" or "rgba(45,15,74,0.45)".
  • Shades colors to white or black by percentage.
  • Blends colors together by percentage.
  • Does Hex2RGB and RGB2Hex conversion at the same time, or solo.
  • Accepts 3 digit (or 4 digit w/ alpha) HEX color codes, in the form #RGB (or #RGBA). It will expand them. For Example: "#C41" becomes "#CC4411".
  • Accepts and (Linear) blends alpha channels. If either the c0 (from) color or the c1 (to) color has an alpha channel, then the returned color will have an alpha channel. If both colors have an alpha channel, then the returned color will be a linear blend of the two alpha channels using the percentage given (just as if it were a normal color channel). If only one of the two colors has an alpha channel, this alpha will just be passed thru to the returned color. This allows one to blend/shade a transparent color while maintaining the transparency level. Or, if the transparency levels should blend as well, make sure both colors have alphas. When shading, it will pass the alpha channel straight thru. If you want basic shading that also shades the alpha channel, then use rgb(0,0,0,1) or rgb(255,255,255,1) as your c1 (to) color (or their hex equivalents). For RGB colors, the returned color's alpha channel will be rounded to 3 decimal places.
  • RGB2Hex and Hex2RGB conversions are implicit when using blending. Regardless of the c0 (from) color; the returned color will always be in the color format of the c1 (to) color, if one exists. If there is no c1 (to) color, then pass 'c' in as the c1 color and it will shade and convert whatever the c0 color is. If conversion only is desired, then pass 0 in as the percentage (p) as well. If the c1 color is omitted or a non-string is passed in, it will not convert.
  • A secondary function is added to the global as well. pSBCr can be passed a Hex or RGB color and it returns an object containing this color information. Its in the form: {r: XXX, g: XXX, b: XXX, a: X.XXX}. Where .r, .g, and .b have range 0 to 255. And when there is no alpha: .a is -1. Otherwise: .a has range 0.000 to 1.000.
  • For RGB output, it outputs rgba() over rgb() when a color with an alpha channel was passed into c0 (from) and/or c1 (to).
  • Minor Error Checking has been added. It's not perfect. It can still crash or create jibberish. But it will catch some stuff. Basically, if the structure is wrong in some ways or if the percentage is not a number or out of scope, it will return null. An example: pSBC(0.5,"salt") == null, where as it thinks #salt is a valid color. Delete the four lines which end with return null; to remove this feature and make it faster and smaller.
  • Uses Log Blending. Pass true in for l (the 4th parameter) to use Linear Blending.

Code:

// Version 4.0
const pSBC=(p,c0,c1,l)=>{
    let r,g,b,P,f,t,h,i=parseInt,m=Math.round,a=typeof(c1)=="string";
    if(typeof(p)!="number"||p<-1||p>1||typeof(c0)!="string"||(c0[0]!='r'&&c0[0]!='#')||(c1&&!a))return null;
    if(!this.pSBCr)this.pSBCr=(d)=>{
        let n=d.length,x={};
        if(n>9){
            [r,g,b,a]=d=d.split(","),n=d.length;
            if(n<3||n>4)return null;
            x.r=i(r[3]=="a"?r.slice(5):r.slice(4)),x.g=i(g),x.b=i(b),x.a=a?parseFloat(a):-1
        }else{
            if(n==8||n==6||n<4)return null;
            if(n<6)d="#"+d[1]+d[1]+d[2]+d[2]+d[3]+d[3]+(n>4?d[4]+d[4]:"");
            d=i(d.slice(1),16);
            if(n==9||n==5)x.r=d>>24&255,x.g=d>>16&255,x.b=d>>8&255,x.a=m((d&255)/0.255)/1000;
            else x.r=d>>16,x.g=d>>8&255,x.b=d&255,x.a=-1
        }return x};
    h=c0.length>9,h=a?c1.length>9?true:c1=="c"?!h:false:h,f=this.pSBCr(c0),P=p<0,t=c1&&c1!="c"?this.pSBCr(c1):P?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},p=P?p*-1:p,P=1-p;
    if(!f||!t)return null;
    if(l)r=m(P*f.r+p*t.r),g=m(P*f.g+p*t.g),b=m(P*f.b+p*t.b);
    else r=m((P*f.r**2+p*t.r**2)**0.5),g=m((P*f.g**2+p*t.g**2)**0.5),b=m((P*f.b**2+p*t.b**2)**0.5);
    a=f.a,t=t.a,f=a>=0||t>=0,a=f?a<0?t:t<0?a:a*P+t*p:0;
    if(h)return"rgb"+(f?"a(":"(")+r+","+g+","+b+(f?","+m(a*1000)/1000:"")+")";
    else return"#"+(4294967296+r*16777216+g*65536+b*256+(f?m(a*255):0)).toString(16).slice(1,f?undefined:-2)
}

Usage:

// Setup:

let color1 = "rgb(20,60,200)";
let color2 = "rgba(20,60,200,0.67423)";
let color3 = "#67DAF0";
let color4 = "#5567DAF0";
let color5 = "#F3A";
let color6 = "#F3A9";
let color7 = "rgb(200,60,20)";
let color8 = "rgba(200,60,20,0.98631)";

// Tests:

/*** Log Blending ***/
// Shade (Lighten or Darken)
pSBC ( 0.42, color1 ); // rgb(20,60,200) + [42% Lighter] => rgb(166,171,225)
pSBC ( -0.4, color5 ); // #F3A + [40% Darker] => #c62884
pSBC ( 0.42, color8 ); // rgba(200,60,20,0.98631) + [42% Lighter] => rgba(225,171,166,0.98631)

// Shade with Conversion (use "c" as your "to" color)
pSBC ( 0.42, color2, "c" ); // rgba(20,60,200,0.67423) + [42% Lighter] + [Convert] => #a6abe1ac

// RGB2Hex & Hex2RGB Conversion Only (set percentage to zero)
pSBC ( 0, color6, "c" ); // #F3A9 + [Convert] => rgba(255,51,170,0.6)

// Blending
pSBC ( -0.5, color2, color8 ); // rgba(20,60,200,0.67423) + rgba(200,60,20,0.98631) + [50% Blend] => rgba(142,60,142,0.83)
pSBC ( 0.7, color2, color7 ); // rgba(20,60,200,0.67423) + rgb(200,60,20) + [70% Blend] => rgba(168,60,111,0.67423)
pSBC ( 0.25, color3, color7 ); // #67DAF0 + rgb(200,60,20) + [25% Blend] => rgb(134,191,208)
pSBC ( 0.75, color7, color3 ); // rgb(200,60,20) + #67DAF0 + [75% Blend] => #86bfd0

/*** Linear Blending ***/
// Shade (Lighten or Darken)
pSBC ( 0.42, color1, false, true ); // rgb(20,60,200) + [42% Lighter] => rgb(119,142,223)
pSBC ( -0.4, color5, false, true ); // #F3A + [40% Darker] => #991f66
pSBC ( 0.42, color8, false, true ); // rgba(200,60,20,0.98631) + [42% Lighter] => rgba(223,142,119,0.98631)

// Shade with Conversion (use "c" as your "to" color)
pSBC ( 0.42, color2, "c", true ); // rgba(20,60,200,0.67423) + [42% Lighter] + [Convert] => #778edfac

// RGB2Hex & Hex2RGB Conversion Only (set percentage to zero)
pSBC ( 0, color6, "c", true ); // #F3A9 + [Convert] => rgba(255,51,170,0.6)

// Blending
pSBC ( -0.5, color2, color8, true ); // rgba(20,60,200,0.67423) + rgba(200,60,20,0.98631) + [50% Blend] => rgba(110,60,110,0.83)
pSBC ( 0.7, color2, color7, true ); // rgba(20,60,200,0.67423) + rgb(200,60,20) + [70% Blend] => rgba(146,60,74,0.67423)
pSBC ( 0.25, color3, color7, true ); // #67DAF0 + rgb(200,60,20) + [25% Blend] => rgb(127,179,185)
pSBC ( 0.75, color7, color3, true ); // rgb(200,60,20) + #67DAF0 + [75% Blend] => #7fb3b9

/*** Other Stuff ***/
// Error Checking
pSBC ( 0.42, "#FFBAA" ); // #FFBAA + [42% Lighter] => null  (Invalid Input Color)
pSBC ( 42, color1, color5 ); // rgb(20,60,200) + #F3A + [4200% Blend] => null  (Invalid Percentage Range)
pSBC ( 0.42, {} ); // [object Object] + [42% Lighter] => null  (Strings Only for Color)
pSBC ( "42", color1 ); // rgb(20,60,200) + ["42"] => null  (Numbers Only for Percentage)
pSBC ( 0.42, "salt" ); // salt + [42% Lighter] => null  (A Little Salt is No Good...)

// Error Check Fails (Some Errors are not Caught)
pSBC ( 0.42, "#salt" ); // #salt + [42% Lighter] => #a5a5a500  (...and a Pound of Salt is Jibberish)

// Ripping
pSBCr ( color4 ); // #5567DAF0 + [Rip] => [object Object] => {'r':85,'g':103,'b':218,'a':0.941}

The picture below will help show the difference in the two blending methods:


Micro Functions

If you really want speed and size, you will have to use RGB not HEX. RGB is more straightforward and simple, HEX writes too slow and comes in too many flavors for a simple two-liner (IE. it could be a 3, 4, 6, or 8 digit HEX code). You will also need to sacrifice some features, no error checking, no HEX2RGB nor RGB2HEX. As well, you will need to choose a specific function (based on its function name below) for the color blending math, and if you want shading or blending. These functions do support alpha channels. And when both input colors have alphas it will Linear Blend them. If only one of the two colors has an alpha, it will pass it straight thru to the resulting color. Below are two liner functions that are incredibly fast and small:

const RGB_Linear_Blend=(p,c0,c1)=>{
    var i=parseInt,r=Math.round,P=1-p,[a,b,c,d]=c0.split(","),[e,f,g,h]=c1.split(","),x=d||h,j=x?","+(!d?h:!h?d:r((parseFloat(d)*P+parseFloat(h)*p)*1000)/1000+")"):")";
    return"rgb"+(x?"a(":"(")+r(i(a[3]=="a"?a.slice(5):a.slice(4))*P+i(e[3]=="a"?e.slice(5):e.slice(4))*p)+","+r(i(b)*P+i(f)*p)+","+r(i(c)*P+i(g)*p)+j;
}

const RGB_Linear_Shade=(p,c)=>{
    var i=parseInt,r=Math.round,[a,b,c,d]=c.split(","),P=p<0,t=P?0:255*p,P=P?1+p:1-p;
    return"rgb"+(d?"a(":"(")+r(i(a[3]=="a"?a.slice(5):a.slice(4))*P+t)+","+r(i(b)*P+t)+","+r(i(c)*P+t)+(d?","+d:")");
}

const RGB_Log_Blend=(p,c0,c1)=>{
    var i=parseInt,r=Math.round,P=1-p,[a,b,c,d]=c0.split(","),[e,f,g,h]=c1.split(","),x=d||h,j=x?","+(!d?h:!h?d:r((parseFloat(d)*P+parseFloat(h)*p)*1000)/1000+")"):")";
    return"rgb"+(x?"a(":"(")+r((P*i(a[3]=="a"?a.slice(5):a.slice(4))**2+p*i(e[3]=="a"?e.slice(5):e.slice(4))**2)**0.5)+","+r((P*i(b)**2+p*i(f)**2)**0.5)+","+r((P*i(c)**2+p*i(g)**2)**0.5)+j;
}

const RGB_Log_Shade=(p,c)=>{
    var i=parseInt,r=Math.round,[a,b,c,d]=c.split(","),P=p<0,t=P?0:p*255**2,P=P?1+p:1-p;
    return"rgb"+(d?"a(":"(")+r((P*i(a[3]=="a"?a.slice(5):a.slice(4))**2+t)**0.5)+","+r((P*i(b)**2+t)**0.5)+","+r((P*i(c)**2+t)**0.5)+(d?","+d:")");
}

Want more info? Read the full writeup on github.

PT

(P.s. If anyone has the math for another blending method, please share.)

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

Not a perfect solution, but this CSS might help. The zoom is what makes this code work, and the factor should theoretically be infinite to work ideally for small images - but 2, 4, or 8 works fine in most cases.

#myImage {
    zoom: 2;  //increase if you have very small images

    display: block;
    margin: auto;

    height: auto;
    max-height: 100%;

    width: auto;
    max-width: 100%;
}

How do I remove  from the beginning of a file?

In Notepad++, choose the "Encoding" menu, then "Encode in UTF-8 without BOM". Then save.

See Stack Overflow question How to make Notepad to save text in UTF-8 without BOM?.

Is there a quick change tabs function in Visual Studio Code?

This also works on MAC OS:

Press for select specific Tab: Control + 1 or Control 2, Control 3, etc.

Press for show/select all posible Tabs: Control + Tab.

Use getElementById on HTMLElement instead of HTMLDocument

Sub Scrape()
    Dim Browser As InternetExplorer
    Dim Document As htmlDocument
    Dim Elements As IHTMLElementCollection
    Dim Element As IHTMLElement

    Set Browser = New InternetExplorer
    Browser.Visible = True
    Browser.navigate "http://www.stackoverflow.com"

    Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
        DoEvents
    Loop

    Set Document = Browser.Document

    Set Elements = Document.getElementById("hmenus").getElementsByTagName("li")
    For Each Element In Elements
        Debug.Print Element.innerText
        'Questions
        'Tags
        'Users
        'Badges
        'Unanswered
        'Ask Question
    Next Element

    Set Document = Nothing
    Set Browser = Nothing
End Sub

How can I have a newline in a string in sh?

  1. The only simple alternative is to actually type a new line in the variable:

    $ STR='new
    line'
    $ printf '%s' "$STR"
    new
    line
    

    Yes, that means writing Enter where needed in the code.

  2. There are several equivalents to a new line character.

    \n           ### A common way to represent a new line character.
    \012         ### Octal value of a new line character.
    \x0A         ### Hexadecimal value of a new line character.
    

    But all those require "an interpretation" by some tool (POSIX printf):

    echo -e "new\nline"           ### on POSIX echo, `-e` is not required.
    printf 'new\nline'            ### Understood by POSIX printf.
    printf 'new\012line'          ### Valid in POSIX printf.
    printf 'new\x0Aline'       
    printf '%b' 'new\0012line'    ### Valid in POSIX printf.
    

    And therefore, the tool is required to build a string with a new-line:

    $ STR="$(printf 'new\nline')"
    $ printf '%s' "$STR"
    new
    line
    
  3. In some shells, the sequence $' is an special shell expansion. Known to work in ksh93, bash and zsh:

    $ STR=$'new\nline'
    
  4. Of course, more complex solutions are also possible:

    $ echo '6e65770a6c696e650a' | xxd -p -r
    new
    line
    

    Or

    $ echo "new line" | sed 's/ \+/\n/g'
    new
    line
    

Compare two objects with .equals() and == operator

Here the output will be false , false beacuse in first sopln statement you are trying to compare a string type varible of Myclass type to the other MyClass type and it will allow because of both are Object type and you have used "==" oprerator which will check the reference variable value holding the actual memory not the actual contnets inside the memory . In the second sopln also it is the same as you are again calling a.equals(object2) where a is a varible inside object1 . Do let me know your findings on this .

How to send an HTTP request with a header parameter?

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

Here is an example from another Question

$http({method: 'GET', url: '[the-target-url]', headers: {
  'Authorization': '[your-api-key]'}
});

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
   type : "GET", 
   url : "[the-target-url]", 
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
   success : function(result) { 
       //set your variable to the result 
   }, 
   error : function(result) { 
     //handle the error 
   } 
 }); 

I got this from this question and I'm at work so I can't test it at the moment but looks solid

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

instead of the beforeSend line in the first edit. This may be simpler for you

Best way to check for IE less than 9 in JavaScript without library

Using conditional comments, you can create a script block that will only get executed in IE less than 9.

<!--[if lt IE 9 ]>
<script>
var is_ie_lt9 = true;
</script>
<![endif]--> 

Of course, you could precede this block with a universal block that declares var is_ie_lt9=false, which this would override for IE less than 9. (In that case, you'd want to remove the var declaration, as it would be repetitive).

EDIT: Here's a version that doesn't rely on in-line script blocks (can be run from an external file), but doesn't use user agent sniffing:

Via @cowboy:

with(document.createElement("b")){id=4;while(innerHTML="<!--[if gt IE "+ ++id+"]>1<![endif]-->",innerHTML>0);var ie=id>5?+id:0}

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Supplement to Iman Mahmoudinasab's answer

For SQL Server 2016, this is where to find the files:

https://www.microsoft.com/en-us/download/details.aspx?id=52676

Note that the files are in the list but you may need to scroll down to see/select it.

From SQL Server 2017 onwards, things change:

"Beginning with SQL Server 2017 SMO is distributed as the Microsoft.SqlServer.SqlManagementObjects NuGet package to allow users to develop applications with SMO."

Source: https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/installing-smo?view=sql-server-2017

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

To explain the actual problem that tslint is pointing out, a quote from the JavaScript documentation of the for...in statement:

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

So, basically this means you'll get properties you might not expect to get (from the object's prototype chain).

To solve this we need to iterate only over the objects own properties. We can do this in two different ways (as suggested by @Maxxx and @Qwertiy).

First solution

for (const field of Object.keys(this.formErrors)) {
    ...
}

Here we utilize the Object.Keys() method which returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Second solution

for (var field in this.formErrors) {
    if (this.formErrors.hasOwnProperty(field)) {
        ...
    }
}

In this solution we iterate all of the object's properties including those in it's prototype chain but use the Object.prototype.hasOwnProperty() method, which returns a boolean indicating whether the object has the specified property as own (not inherited) property, to filter the inherited properties out.

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

How do you execute an arbitrary native command from a string?

Invoke-Expression, also aliased as iex. The following will work on your examples #2 and #3:

iex $command

Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:

$command = 'C:\somepath\someexe.exe somearg'
iex $command

However, if the exe is in quotes, you need the help of & to get it running, as in this example, as run from the commandline:

>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"

And then in the script:

$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"

Likely, you could handle nearly all cases by detecting if the first character of the command string is ", like in this naive implementation:

function myeval($command) {
    if ($command[0] -eq '"') { iex "& $command" }
    else { iex $command }
}

But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}, perhaps for specific exception types/messages, or examine the command string.

If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

This exact error was related to a content block by Youtube when "playbacked on certain sites or applications". More specifically by WMG (Warner Music Group).

The error message did however suggest that a https iframe import to a http site was the issue, which it wasn't in this case.

Using npm behind corporate proxy .pac

Don't Forget to use URL Encoding for password.

Suppose ur username ="xyz" pwd ="abc#11"

then your C:\Users<username>.npmrc should be like

proxy= http://domainname%5Cxyz:abc%2311@servername:port

servername : It can be obtained from the pac file of your internet explorer.

How to dismiss the dialog with click on outside of the dialog?

You can use dialog.setCanceledOnTouchOutside(true); which will close the dialog if you touch outside of the dialog.

Something like,

  Dialog dialog = new Dialog(context)
  dialog.setCanceledOnTouchOutside(true);

Or if your Dialog in non-model then,

1 - Set the flag-FLAG_NOT_TOUCH_MODAL for your dialog's window attribute

Window window = this.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

2 - Add another flag to windows properties,, FLAG_WATCH_OUTSIDE_TOUCH - this one is for dialog to receive touch event outside its visible region.

3 - Override onTouchEvent() of dialog and check for action type. if the action type is 'MotionEvent.ACTION_OUTSIDE' means, user is interacting outside the dialog region. So in this case, you can dimiss your dialog or decide what you wanted to perform. view plainprint?

public boolean onTouchEvent(MotionEvent event)  
{  

       if(event.getAction() == MotionEvent.ACTION_OUTSIDE){  
        System.out.println("TOuch outside the dialog ******************** ");  
               this.dismiss();  
       }  
       return false;  
}  

For more info look at How to dismiss a custom dialog based on touch points? and How to dismiss your non-modal dialog, when touched outside dialog region

Equal height rows in a flex container

You can with flexbox:

_x000D_
_x000D_
ul.list {
    padding: 0;
    list-style: none;
    display: flex;
    align-items: stretch;
    justify-items: center;
    flex-wrap: wrap;
    justify-content: center;
}
li {
    width: 100px;
    padding: .5rem;
    border-radius: 1rem;
    background: yellow;
    margin: 0 5px;
}
_x000D_
<ul class="list">
  <li>title 1</li>
  <li>title 2<br>new line</li>
  <li>title 3<br>new<br>line</li>
</ul>
_x000D_
_x000D_
_x000D_

How to go from Blob to ArrayBuffer

Just to complement Mr @potatosalad answer.

You don't actually need to access the function scope to get the result on the onload callback, you can freely do the following on the event parameter:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Why this is better? Because then we may use arrow function without losing the context

var fileReader = new FileReader();
fileReader.onload = (event) => {
    this.externalScopeVariable = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Promise.all().then() resolve?

Your return data approach is correct, that's an example of promise chaining. If you return a promise from your .then() callback, JavaScript will resolve that promise and pass the data to the next then() callback.

Just be careful and make sure you handle errors with .catch(). Promise.all() rejects as soon as one of the promises in the array rejects.

Extract directory path and filename

echo $fspec | tr "/" "\n"|tail -1

How to know function return type and argument types?

Docstrings (and documentation in general). Python 3 introduces (optional) function annotations, as described in PEP 3107 (but don't leave out docstrings)

How to increase the max upload file size in ASP.NET?

You can write that block of code in your application web.config file.

<httpRuntime maxRequestLength="2048576000" />
<sessionState timeout="3600"  />

By writing that code you can upload a larger file than now

How to change to an older version of Node.js

nvm install 0.5.0 #install previous version of choice

nvm alias default 0.5.0 #set it to default

nvm use default #use the new default as active version globally.

Without the last, the active version doesn't change to the new default. So, when you open a new terminal or restart server, the old default version remains active.

Eclipse CDT project built but "Launch Failed. Binary Not Found"

This worked for me.

Go to Project --> Properties --> Run/Debug Settings --> Click on the configuration & click "Edit", it will now open a "Edit Configuration".

Hit on "Search Project" , select the binary file from the "Binaries" and hit ok.

Note : Before doing all this, make sure you have done the below

--> Binary is generated once you execute "Build All" or (Ctrl+B)

Print "\n" or newline characters as part of the output on terminal

If you're in control of the string, you could also use a 'Raw' string type:

>>> string = r"abcd\n"
>>> print(string)
abcd\n

Java synchronized method lock on object, or method?

If you have some methods which are not synchronized and are accessing and changing the instance variables. In your example:

 private int a;
 private int b;

any number of threads can access these non synchronized methods at the same time when other thread is in the synchronized method of the same object and can make changes to instance variables. For e.g :-

 public void changeState() {
      a++;
      b++;
    }

You need to avoid the scenario that non synchronized methods are accessing the instance variables and changing it otherwise there is no point of using synchronized methods.

In the below scenario:-

class X {

        private int a;
        private int b;

        public synchronized void addA(){
            a++;
        }

        public synchronized void addB(){
            b++;
        }
     public void changeState() {
          a++;
          b++;
        }
    }

Only one of the threads can be either in addA or addB method but at the same time any number of threads can enter changeState method. No two threads can enter addA and addB at same time(because of Object level locking) but at same time any number of threads can enter changeState.

Relative Paths in Javascript in an external file

A proper solution is using a css class instead of writing src in js file. For example instead of using:

$(this).css("background", "url('../Images/filters_collapse.jpg')");

use:

$(this).addClass("xxx");

and in a css file that is loaded in the page write:

.xxx {
  background-image:url('../Images/filters_collapse.jpg');
}

Abstract Class vs Interface in C++

An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).

How to count items in JSON data

You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':

len(data['result'][0]['run'])

How to run ssh-add on windows?

In order to run ssh-add on Windows one could install git using choco install git. The ssh-add command is recognized once C:\Program Files\Git\usr\bin has been added as a PATH variable and the command prompt has been restarted:

C:\Users\user\Desktop\repository>ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (.ssh/id_rsa)

C:\Users\user\Desktop\repository> 

How can I mock the JavaScript window object using Jest?

In my component I need access to window.location.search. This is what I did in the Jest test:

Object.defineProperty(global, "window", {
  value: {
    location: {
      search: "test"
    }
  }
});

In case window properties must be different in different tests, we can put window mocking into a function, and make it writable in order to override for different tests:

function mockWindow(search, pathname) {
  Object.defineProperty(global, "window", {
    value: {
      location: {
        search,
        pathname
      }
    },
    writable: true
  });
}

And reset after each test:

afterEach(() => {
  delete global.window.location;
});

Get next / previous element using JavaScript?

There is a attribute on every HTMLElement, "previousElementSibling".

Ex:

<div id="a">A</div>
<div id="b">B</div>
<div id="c">c</div>

<div id="result">Resultado: </div>

var b = document.getElementById("c").previousElementSibling;

document.getElementById("result").innerHTML += b.innerHTML;

Live: http://jsfiddle.net/QukKM/

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

An array is a pointer. It points to the start of a sequence of "objects".

If we do this: ìnt arr[10];, then arr is a pointer to a memory location, from which ten integers follow. They are uninitialised, but the memory is allocated. It is exactly the same as doing int *arr = new int[10];.

Get the latest record from mongodb collection

This is a rehash of the previous answer but it's more likely to work on different mongodb versions.

db.collection.find().limit(1).sort({$natural:-1})

Stateless vs Stateful

Money transfered online form one account to another account is stateful, because the receving account has information about the sender. Handing over cash from a person to another person, this transaction is statless, because after cash is recived the identity of the giver is not there with the cash.

Split and join C# string

You can use string.Split and string.Join:

string theString = "Some Very Large String Here";
var array = theString.Split(' ');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));

If you know you always only want to split off the first element, you can use:

var array = theString.Split(' ', 2);

This makes it so you don't have to join:

string restOfArray = array[1];

How do I get the unix timestamp in C as an int?

With second precision, you can print tv_sec field of timeval structure that you get from gettimeofday() function. For example:

#include <sys/time.h>
#include <stdio.h>

int main()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    printf("Seconds since Jan. 1, 1970: %ld\n", tv.tv_sec);
    return 0;
}

Example of compiling and running:

$ gcc -Wall -o test ./test.c 
$ ./test 
Seconds since Jan. 1, 1970: 1343845834

Note, however, that its been a while since epoch and so long int is used to fit a number of seconds these days.

There are also functions to print human-readable times. See this manual page for details. Here goes an example using ctime():

#include <time.h>
#include <stdio.h>

int main()
{
    time_t clk = time(NULL);
    printf("%s", ctime(&clk));
    return 0;
}

Example run & output:

$ gcc -Wall -o test ./test.c 
$ ./test 
Wed Aug  1 14:43:23 2012
$ 

How do I create ColorStateList programmatically?

if you use the resource the Colors.xml

int[] colors = new int[] {
                getResources().getColor(R.color.ColorVerificaLunes),
                getResources().getColor(R.color.ColorVerificaMartes),
                getResources().getColor(R.color.ColorVerificaMiercoles),
                getResources().getColor(R.color.ColorVerificaJueves),
                getResources().getColor(R.color.ColorVerificaViernes)

        };

ColorStateList csl = new ColorStateList(new int[][]{new int[0]}, new int[]{colors[0]}); 

    example.setBackgroundTintList(csl);

How to write LDAP query to test if user is member of a group?

If you are using OpenLDAP (i.e. slapd) which is common on Linux servers, then you must enable the memberof overlay to be able to match against a filter using the (memberOf=XXX) attribute.

Also, once you enable the overlay, it does not update the memberOf attributes for existing groups (you will need to delete out the existing groups and add them back in again). If you enabled the overlay to start with, when the database was empty then you should be OK.

How to find the Number of CPU Cores via .NET/C#?

There are several different pieces of information relating to processors that you could get:

  1. Number of physical processors
  2. Number of cores
  3. Number of logical processors.

These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):

Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.

Physical Processors:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}

Cores:

int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
    coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);

Logical Processors:

Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);

OR

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}

Processors excluded from Windows:

You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:

static void Main(string[] args)
{
    int deviceCount = 0;
    IntPtr deviceList = IntPtr.Zero;
    // GUID for processor classid
    Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");

    try
    {
        // get a list of all processor devices
        deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
        // attempt to process each item in the list
        for (int deviceNumber = 0; ; deviceNumber++)
        {
            SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
            deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);

            // attempt to read the device info from the list, if this fails, we're at the end of the list
            if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
            {
                deviceCount = deviceNumber;
                break;
            }
        }
    }
    finally
    {
        if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
    }
    Console.WriteLine("Number of cores: {0}", deviceCount);
}

[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
    [MarshalAs(UnmanagedType.LPStr)]String enumerator,
    IntPtr hwndParent,
    Int32 Flags);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
    Int32 MemberIndex,
    ref SP_DEVINFO_DATA DeviceInterfaceData);

[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
    public int cbSize;
    public Guid ClassGuid;
    public uint DevInst;
    public IntPtr Reserved;
}

private enum DIGCF
{
    DEFAULT = 0x1,
    PRESENT = 0x2,
    ALLCLASSES = 0x4,
    PROFILE = 0x8,
    DEVICEINTERFACE = 0x10,
}

Selecting empty text input using jQuery

Building on @James Wiseman's answer, I am using this:

$.extend($.expr[':'],{
    blank: function(el){
        return $(el).val().match(/^\s*$/);
    }
});

This will catch inputs which contain only whitespace in addition to those which are 'truly' empty.

Example: http://jsfiddle.net/e9btdbyn/

Using querySelectorAll to retrieve direct children

Does anyone know how to write a selector which gets just the direct children of the element that the selector is running on?

The correct way to write a selector that is "rooted" to the current element is to use :scope.

var myDiv = getElementById("myDiv");
var fooEls = myDiv.querySelectorAll(":scope > .foo");

However, browser support is limited and you'll need a shim if you want to use it. I built scopedQuerySelectorShim for this purpose.

Project vs Repository in GitHub

GitHub recently introduced a new feature called Projects. This provides a visual board that is typical of many Project Management tools:

Project

A Repository as documented on GitHub:

A repository is the most basic element of GitHub. They're easiest to imagine as a project's folder. A repository contains all of the project files (including documentation), and stores each file's revision history. Repositories can have multiple collaborators and can be either public or private.

A Project as documented on GitHub:

Project boards on GitHub help you organize and prioritize your work. You can create project boards for specific feature work, comprehensive roadmaps, or even release checklists. With project boards, you have the flexibility to create customized workflows that suit your needs.

Part of the confusion is that the new feature, Projects, conflicts with the overloaded usage of the term project in the documentation above.

Return values from the row above to the current row

Easier way for me is to switch to R1C1 notation and just use R[-1]C1 and switch back when done.

Java: How to insert CLOB into oracle database

OUTDATED See Lukas Eder's answer below.

With about 100 lines of code ;-) Here is an example.

The main point: Unlike with other JDBC drivers, the one from Oracle doesn't support using Reader and InputStream as parameters of an INSERT. Instead, you must SELECT the CLOB column FOR UPDATE and then write into the ResultSet

I suggest that you move this code into a helper method/class. Otherwise, it will pollute the rest of your code.

JS map return object

map rockets and add 10 to its launches:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
rockets.map((itm) => {_x000D_
    itm.launches += 10_x000D_
    return itm_x000D_
})_x000D_
console.log(rockets)
_x000D_
_x000D_
_x000D_

If you don't want to modify rockets you can do:

var plusTen = []
rockets.forEach((itm) => {
    plusTen.push({'country': itm.country, 'launches': itm.launches + 10})
})

Fragment Inside Fragment

you can use getChildFragmentManager() function.

example:

Parent fragment :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.parent_fragment, container,
            false);


    }

    //child fragment 
    FragmentManager childFragMan = getChildFragmentManager();
    FragmentTransaction childFragTrans = childFragMan.beginTransaction();
    ChildFragment fragB = new ChildFragment ();
    childFragTrans.add(R.id.FRAGMENT_PLACEHOLDER, fragB);
    childFragTrans.addToBackStack("B");
    childFragTrans.commit();        


    return rootView;
}

Parent layout (parent_fragment.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">



    <FrameLayout
        android:id="@+id/FRAGMENT_PLACEHOLDER"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>




</LinearLayout>

Child Fragment:

public class ChildFragment extends Fragment implements View.OnClickListener{

    View v ;
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View rootView = inflater.inflate(R.layout.child_fragment, container, false);


        v = rootView;


        return rootView;
    }



    @Override
    public void onClick(View view) {


    }


} 

Use grep --exclude/--include syntax to not grep through certain files

The suggested command:

grep -Ir --exclude="*\.svn*" "pattern" *

is conceptually wrong, because --exclude works on the basename. Put in other words, it will skip only the .svn in the current directory.

PHP preg_replace special characters

If you by writing "non letters and numbers" exclude more than [A-Za-z0-9] (ie. considering letters like åäö to be letters to) and want to be able to accurately handle UTF-8 strings \p{L} and \p{N} will be of aid.

  1. \p{N} will match any "Number"
  2. \p{L} will match any "Letter Character", which includes
    • Lower case letter
    • Modifier letter
    • Other letter
    • Title case letter
    • Upper case letter

Documentation PHP: Unicode Character Properties


$data = "Thäre!wouldn't%bé#äny";

$new_data = str_replace  ("'", "", $data);
$new_data = preg_replace ('/[^\p{L}\p{N}]/u', '_', $new_data);

var_dump (
  $new_data
);

output

string(23) "Thäre_wouldnt_bé_äny"

Mix Razor and Javascript code

Inside a code block (eg, @foreach), you need to mark the markup (or, in this case, Javascript) with @: or the <text> tag.

Inside the markup contexts, you need to surround code with code blocks (@{ ... } or @if, ...)

How to render a DateTime object in a Twig template

Dont forget

@ORM\HasLifecycleCallbacks()

Entity :

/**
     * Set gameDate
     *
     * @ORM\PrePersist
     */
    public function setGameDate()
    {
        $this->dateCreated = new \DateTime();

        return $this;
    }

View:

{{ item.gameDate|date('Y-m-d H:i:s') }}

>> Output 2013-09-18 16:14:20

How to _really_ programmatically change primary and accent color in Android Lollipop?

from an activity you can do:

getWindow().setStatusBarColor(i color);

How to get a index value from foreach loop in jstl

This works for me:

<c:forEach var="i" begin="1970" end="2000">
    <option value="${2000-(i-1970)}">${2000-(i-1970)} 
     </option>
</c:forEach>

How to use FormData in react-native?

Usage of formdata in react-native

I have used react-native-image-picker to select photo. In my case after choosing the photp from mobile. I'm storing it's info in component state. After, I'm sending POST request using fetch like below

const profile_pic = {
  name: this.state.formData.profile_pic.fileName,
  type: this.state.formData.profile_pic.type,
  path: this.state.formData.profile_pic.path,
  uri: this.state.formData.profile_pic.uri,
}
const formData = new FormData()
formData.append('first_name', this.state.formData.first_name);
formData.append('last_name', this.state.formData.last_name);
formData.append('profile_pic', profile_pic);
const Token = 'secret'

fetch('http://10.0.2.2:8000/api/profile/', {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "multipart/form-data",
      Authorization: `Token ${Token}`
    },
    body: formData
  })
  .then(response => console.log(response.json()))

How do I find out what version of WordPress is running?

I know I'm super late regarding this topic but there's this easy to use library where you can easily get the version numbers of Worpress, PHP, Apache, and MySQL, all-in-one.

It is called the Wordpress Environment (W18T) library

<?php
include_once 'W18T.class.php';
$environment = new W18T();
echo $environment;
?>

Output

{
    "platform": {
        "name": "WordPress",
        "version": "4.9.1"
    },
    "interpreter": {
        "name": "PHP",
        "version": "7.2.0"
    },
    "web_server": {
        "name": "Apache",
        "version": "2.4.16"
    },
    "database_server": {
        "name": "MySQL",
        "version": "5.7.20"
    },
    "operating_system": {
        "name": "Darwin",
        "version": "17.0.0"
    }
}

I hope it helps.

How do I manage conflicts with git submodules?

If you want to use the upstream version:

rm -rf <submodule dir>
git submodule init
git submodule update

How to read numbers from file in Python?

is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)

with open('in.txt') as f:
  rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
  data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))

another way: is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4), as well for complex matrices see the example below (only change int to complex)

with open('in.txt') as f:
   data = []
   cols,rows=list(map(int, f.readline().split()))
   for i in range(0, rows):
      data.append(list(map(int, f.readline().split()[:cols])))
print (data)

I updated the code, this method is working for any number of matrices and any kind of matrices(int,complex,float) in the initial in.txt file.

This program yields matrix multiplication as an application. Is working with python2, in order to work with python3 make the following changes

print to print()

and

print "%7g" %a[i,j],    to     print ("%7g" %a[i,j],end="")

the script:

import numpy as np

def printMatrix(a):
   print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%7g" %a[i,j],
      print
   print      

def readMatrixFile(FileName):
   rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
   a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
   return a

def readMatrixFileComplex(FileName):
   data = []
   rows,cols=list(map(int, FileName.readline().split()))
   for i in range(0, rows):
      data.append(list(map(complex, FileName.readline().split()[:cols])))
   a = np.array(data)
   return a

f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()

print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)

with open('complex_in.txt') as fid:
  a2=readMatrixFileComplex(fid)
  print(a2)
  b2=readMatrixFileComplex(fid)
  print(b2)

print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)

as input file I take in.txt:

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5

and complex_in.txt

3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j

and the output look like:

Matrix[4][4]
     1      1      1      1
     2      4      8     16
     3      9     27     81
     4     16     64    256

Matrix[4][3]
  4.02     -3      4
   -13     19     -7
     3     -2      7
    -1      1     -1

Matrix[3][4]
     1      2     -2      0
    -3      4      7      2
     6      0      3      1

Matrix[4][2]
    -1      3
     0      9
     1    -11
     4     -5

matrix multiplication
Matrix[4][3]
  -6.98      15       3
 -35.96      70      20
-104.94     189      57
-255.92     420      96

Matrix[3][2]
    -3     43
    18    -60
     1    -20

[[ 1.+1.j  2.+2.j -2.-2.j  0.+0.j]
 [-3.-3.j  4.+4.j  7.+7.j  2.+2.j]
 [ 6.+6.j  0.+0.j  3.+3.j  1.+1.j]]
[[ -1. -1.j   3. +3.j]
 [  0. +0.j   9. +9.j]
 [  1. +1.j -11.-11.j]
 [  4. +4.j  -5. -5.j]]
complex matrix multiplication
[[ 0.  -6.j  0. +86.j]
 [ 0. +36.j  0.-120.j]
 [ 0.  +2.j  0. -40.j]]
real part of complex matrix
Matrix[3][2]
      0       0
      0       0
      0       0

imaginary part of complex matrix
Matrix[3][2]
     -6      86
     36    -120
      2     -40

What should be the values of GOPATH and GOROOT?

First run go env.
If you see that the go isn't installed, you can install it via homebrew or via package and/or other ways.
If you are seeing output then your Go is installed.
It shows you all the envs that are set and are not.

If you see empty for GOROOT:

  1. Run which go (On my computer : /usr/local/go/bin/go)
  2. then export like this export GOROOT=/usr/local/go

If you see empty for GOPATH:

  1. Create any directory anywhere on your computer for go projects in my case: ~/GO_PROJECTS
  2. Then export GOPATH=~/GO_PROJECTS

Arrays.fill with multidimensional array in Java

Don't we all sometimes wish there was a
<T>void java.util.Arrays.deepFill(T[]…multiDimensional). Problems start with
Object threeByThree[][] = new Object[3][3];
threeByThree[1] = null; and
threeByThree[2][1] = new int[]{42}; being perfectly legal.
(If only Object twoDim[]final[] was legal and well defined…)
(Using one of the public methods from below keeps loops from the calling source code.
If you insist on using no loops at all, substitute the loops and the call to Arrays.fill()(!) using recursion.)

/** Fills matrix {@code m} with {@code value}.
 * @return {@code m}'s dimensionality.
 * @throws java.lang.ArrayStoreException if the component type
 *  of a subarray of non-zero length at the bottom level
 *  doesn't agree with {@code value}'s type. */
public static <T>int deepFill(Object[] m, T value) {
    Class<?> components; 
    if (null == m ||
        null == (components = m.getClass().getComponentType()))
        return 0;
    int dim = 0;
    do
        dim++;
    while (null != (components = components.getComponentType()));
    filler((Object[][])m, value, dim);
    return dim;
}
/** Fills matrix {@code m} with {@code value}.
 * @throws java.lang.ArrayStoreException if the component type
 *  of a subarray of non-zero length at level {@code dimensions}
 *  doesn't agree with {@code value}'s type. */
public static <T>void fill(Object[] m, T value, int dimensions) {
    if (null != m)
        filler(m, value, dimensions);
}

static <T>void filler(Object[] m, T value, int toGo) {
    if (--toGo <= 0)
        java.util.Arrays.fill(m, value);
    else
        for (Object[] subArray : (Object[][])m)
            if (null != subArray)
                filler(subArray, value, toGo);
}

Where do I call the BatchNormalization function in Keras?

Keras now supports the use_bias=False option, so we can save some computation by writing like

model.add(Dense(64, use_bias=False))
model.add(BatchNormalization(axis=bn_axis))
model.add(Activation('tanh'))

or

model.add(Convolution2D(64, 3, 3, use_bias=False))
model.add(BatchNormalization(axis=bn_axis))
model.add(Activation('relu'))

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Read XML Attribute using XmlDocument

I have an Xml File books.xml

<ParameterDBConfig>
    <ID Definition="1" />
</ParameterDBConfig>

Program:

XmlDocument doc = new XmlDocument();
doc.Load("D:/siva/books.xml");
XmlNodeList elemList = doc.GetElementsByTagName("ID");     
for (int i = 0; i < elemList.Count; i++)     
{
    string attrVal = elemList[i].Attributes["Definition"].Value;
}

Now, attrVal has the value of ID.

How to add Python to Windows registry

When installing Python 3.4 the "Add python.exe to Path" came up unselected. Re-installed with this selected and problem resolved.

html5 audio player - jquery toggle click play/pause?

Because Firefox does not support mp3 format. To make this work with Firefox, you should use the ogg format.

Extend contigency table with proportions (percentages)

Here's a tidyverse version:

library(tidyverse)
data(diamonds)

(as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))

Or if you want a handy function:

getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>% 
    table() %>%
    as.data.frame() %>% 
    rename({{colName}} :=1, Freq=2) %>% 
    mutate(Perc=100*Freq/sum(Freq))
}

Now you can do:

diamonds %>% getPercentages(cut)

or this:

df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)

Create an array of strings

You can create a character array that does this via a loop:

>> for i=1:10
Names(i,:)='Sample Text';
end
>> Names

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text

However, this would be better implemented using REPMAT:

>> Names = repmat('Sample Text', 10, 1)

Names =

Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text
Sample Text

Git Push ERROR: Repository not found

I had the same problem. Try the following:

1. Modifying the Keychain Access in Mac for git credentials solved the problem for me.
2. Resetting origin url

git remote rm origin
git remote add origin [email protected]:account-name/repo-name.git

Get UserDetails object from Security Context in Spring MVC controller

If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {

    ModelAndView mv = new ModelAndView("index");

    String userName = "not logged in"; // Any default user  name
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        userName = principal.getName();
    }

    mv.addObject("username", userName);

    // By adding a little code (same way) you can check if user has any
    // roles you need, for example:

    boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
    mv.addObject("isAdmin", fAdmin);

    return mv;
}

Note "HttpServletRequest request" parameter added.

Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

How can a Java program get its own process ID?

For older JVM, in linux...

private static String getPid() throws IOException {
    byte[] bo = new byte[256];
    InputStream is = new FileInputStream("/proc/self/stat");
    is.read(bo);
    for (int i = 0; i < bo.length; i++) {
        if ((bo[i] < '0') || (bo[i] > '9')) {
            return new String(bo, 0, i);
        }
    }
    return "-1";
}

php.ini: which one?

Although Pascal's answer was detailed and informative it failed to mention some key information in the assumption that everyone knows how to use phpinfo()

For those that don't:

Navigate to your webservers root folder such as /var/www/

Within this folder create a text file called info.php

Edit the file and type phpinfo()

Navigate to the file such as: http://www.example.com/info.php

Here you will see the php.ini path under Loaded Configuration File:

phpinfo

Make sure you delete info.php when you are done.

How do I convert from int to String?

Normal ways would be Integer.toString(i) or String.valueOf(i).

The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).

Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();

at compile-time. It's slightly less efficient (sb.append() ends up calling Integer.getChars(), which is what Integer.toString() would've done anyway), but it works.

To answer Grodriguez's comment: ** No, the compiler doesn't optimise out the empty string in this case - look:

simon@lucifer:~$ cat TestClass.java
public class TestClass {
  public static void main(String[] args) {
    int i = 5;
    String strI = "" + i;
  }
}
simon@lucifer:~$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
  Code:
   0:    aload_0
   1:    invokespecial    #1; //Method java/lang/Object."<init>":()V
   4:    return

public static void main(java.lang.String[]);
  Code:
   0:    iconst_5
   1:    istore_1

Initialise the StringBuilder:

   2:    new    #2; //class java/lang/StringBuilder
   5:    dup
   6:    invokespecial    #3; //Method java/lang/StringBuilder."<init>":()V

Append the empty string:

   9:    ldc    #4; //String
   11:    invokevirtual    #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;

Append the integer:

   14:    iload_1
   15:    invokevirtual    #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;

Extract the final string:

   18:    invokevirtual    #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
   21:    astore_2
   22:    return
}

There's a proposal and ongoing work to change this behaviour, targetted for JDK 9.

How to set editor theme in IntelliJ Idea

For IntelliJ in Mac

View -> Quick Switch theme (^`)-> color schema

fork and exec in bash

Use the ampersand just like you would from the shell.

#!/usr/bin/bash
function_to_fork() {
   ...
}

function_to_fork &
# ... execution continues in parent process ...

How can I escape white space in a bash loop list?

To add to what Jonathan said: use the -print0 option for find in conjunction with xargs as follows:

find test/* -type d -print0 | xargs -0 command

That will execute the command command with the proper arguments; directories with spaces in them will be properly quoted (i.e. they'll be passed in as one argument).

What key shortcuts are to comment and uncomment code?

Use the keys CtrlK,C to comment out the line and CtrlK,U to uncomment the line.

Renaming column names of a DataFrame in Spark Scala

Suppose the dataframe df has 3 columns id1, name1, price1 and you wish to rename them to id2, name2, price2

val list = List("id2", "name2", "price2")
import spark.implicits._
val df2 = df.toDF(list:_*)
df2.columns.foreach(println)

I found this approach useful in many cases.

Why are the Level.FINE logging messages not showing?

why is my java logging not working

provides a jar file that will help you work out why your logging in not working as expected. It gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.

How to increase the timeout period of web service in asp.net?

In app.config file (or .exe.config) you can add or change the "receiveTimeout" property in binding. like this

<binding name="WebServiceName" receiveTimeout="00:00:59" />

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

var a = [];

it is use for brackets for an array of simple values. eg.

var name=["a","b","c"]

var a={}

is use for value arrays and objects/properties also. eg.

var programmer = { 'name':'special', 'url':'www.google.com'}

Push items into mongo array via mongoose

First I tried this code

const peopleSchema = new mongoose.Schema({
  name: String,
  friends: [
    {
      firstName: String,
      lastName: String,
    },
  ],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
  name: "Yash Salvi",
  notes: [
    {
      firstName: "Johnny",
      lastName: "Johnson",
    },
  ],
});
first.save();
const friendNew = {
  firstName: "Alice",
  lastName: "Parker",
};
People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
  function (error, success) {
    if (error) {
      console.log(error);
    } else {
      console.log(success);
    }
  }
);

But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element ! So the simple solution is written below

const peopleSchema = new mongoose.Schema({
  name: String,
  friends: [
    {
      firstName: String,
      lastName: String,
    },
  ],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
  name: "Yash Salvi",
  notes: [
    {
      firstName: "Johnny",
      lastName: "Johnson",
    },
  ],
});
first.save();
const friendNew = {
  firstName: "Alice",
  lastName: "Parker",
};
People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
  { upsert: true }
);

Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements ! The upsert = true option creates the object if it doesn't exist. default is set to false.

if it doesn't work use below snippet

People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
).exec();

How to make a movie out of images in python

I use the ffmpeg-python binding. You can find more information here.

import ffmpeg
(
    ffmpeg
    .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
    .output('movie.mp4')
    .run()
)

Setting default permissions for newly created files and sub-directories under a directory in Linux?

in your shell script (or .bashrc) you may use somthing like:

umask 022

umask is a command that determines the settings of a mask that controls how file permissions are set for newly created files.

How to add an object to an array

Expanding Gabi Purcaru's answer to include an answer to number 2.

a = new Array();
b = new Object();
a[0] = b;

var c = a[0]; // c is now the object we inserted into a...

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21

webViewClient = object : WebViewClient() {
.
.
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            parseUri(request?.url)
            return true
        }

        @SuppressWarnings("deprecation")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            parseUri(Uri.parse(url))
            return true
        }
}

Get the last non-empty cell in a column in Google Sheets

Calculate the difference between latest date in column A with the date in cell A2.

=MAX(A2:A)-A2

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

new Image(), how to know if image 100% loaded or not?

Using the Promise pattern:

function getImage(url){
        return new Promise(function(resolve, reject){
            var img = new Image()
            img.onload = function(){
                resolve(url)
            }
            img.onerror = function(){
                reject(url)
            }
            img.src = url
        })
    }

And when calling the function we can handle its response or error quite neatly.

getImage('imgUrl').then(function(successUrl){
    //do stufff
}).catch(function(errorUrl){
    //do stuff
})

Android list view inside a scroll view

  • It is not possible to use Scroll-view inside List-view as List-view already has scrolling property.
  • To use list-view inside Scroll-view you can follow these steps which worked for me :

    1) Create NonScrollListView java file that disable the default scrolling property of list-view. and code is below

    package your-package-structure;
    
    import android.content.Context;
    import android.util.AttributeSet;
    import android.view.ViewGroup;
    import android.widget.ListView;
    
    public class NonScrollListView extends ListView {
    
      public NonScrollListView(Context context) {
          super(context);
      }
      public NonScrollListView(Context context, AttributeSet attrs) {
          super(context, attrs);
      }
      public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
          super(context, attrs, defStyle);
      }
      @Override
      public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = getMeasuredHeight();
      }
    }
    

    2) Now create xml file which which has NestedScrollView and inside this use NonScrollListView for listing your items. This will make your entire screen to scroll with all the views.

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical">
                <ViewFlipper
    
                    android:id="@+id/v_flipper"
                    android:layout_width="match_parent"
                    android:layout_height="130dp">
                </ViewFlipper>
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
    
                    android:text="SHOP"
                    android:textSize="15dp"
                    android:textStyle="bold"
                    android:gravity="center"
                    android:padding="5dp"
                    android:layout_marginTop="15dp"
                    android:layout_marginBottom="5dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
    
                    android:layout_marginBottom="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:background="#ddd"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_weight="1"
                >
                <com.abc.xyz.NonScrollListView
                    android:id="@+id/listview"
    
                    android:divider="@null"
                    android:layout_width="match_parent"
                    android:layout_marginBottom="10dp"
                    android:layout_height="match_parent"
                    android:padding="8dp">
                </com.abc.xyz.NonScrollListView>
            </LinearLayout>
    
           <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
    
                android:gravity="bottom">
                <include layout="@layout/footer" />
            </LinearLayout>
    
        </LinearLayout>
    

    3) Now in java class i.e, home.java define NonScrollListView instead of Listview.

    package comabc.xyz.landscapeapp;
    import android.content.Intent;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.os.Bundle;
    import android.support.v4.app.FragmentTransaction;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.ImageView;
    
    import android.widget.ListView;
    import android.widget.Toast;
    import android.widget.Toolbar;
    import android.widget.ViewFlipper;
    

    public class home extends Fragment { int pos = 0; ViewFlipper v_flipper;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_home, container, false);
        return view;
    }
    
    @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
        NonScrollListView listView = (NonScrollListView) view.findViewById(R.id.listview);
        customAdapter customAdapter = new customAdapter(getActivity());
        listView.setAdapter(customAdapter);
        listView.setFocusable(false);
    
        customAdapter.notifyDataSetChanged();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d("listview click", "onItemClick: ");
               /* FragmentTransaction fr = getFragmentManager().beginTransaction().replace(R.id.fragment_container, new productdisplay());
    
                fr.putExtra("Position", position);
                fr.addToBackStack("tag");
                fr.commit();*/
                Intent intent = new Intent(getActivity(), productdisplay.class);
                intent.putExtra("Position", position);
                startActivity(intent);
            }
        });
    
    
        //image slider
        int images[] = {R.drawable.slide1, R.drawable.slide2, R.drawable.slide3};
        v_flipper = view.findViewById(R.id.v_flipper);
        for (int image : images) {
            flipperImages(image);
    
        }
    }
    
    private void flipperImages(int image) {
        ImageView imageView = new ImageView(getActivity());
        imageView.setBackgroundResource(image);
    
        v_flipper.addView(imageView);
        v_flipper.setFlipInterval(4000);
        v_flipper.setAutoStart(true);
    
        v_flipper.setInAnimation(getActivity(), android.R.anim.slide_in_left);
        v_flipper.setOutAnimation(getActivity(), android.R.anim.slide_out_right);
    }
    }
    

    Note: I used Fragments here.

How to split (chunk) a Ruby array into parts of X elements?

If you're using rails you can also use in_groups_of:

foo.in_groups_of(3)

Java - Check if input is a positive integer, negative integer, natural number and so on.

Use like below code.

if(number >=0 ) {
            System.out.println("Number is natural and positive.");
}

How to include css files in Vue 2

If you want to append this css file to header you can do it using mounted() function of the vue file. See the example.
Note: Assume you can access the css file as http://www.yoursite/assets/styles/vendor.css in the browser.

mounted() {
        let style = document.createElement('link');
        style.type = "text/css";
        style.rel = "stylesheet";
        style.href = '/assets/styles/vendor.css';
        document.head.appendChild(style);
    }

How do you hide the Address bar in Google Chrome for Chrome Apps?

2016-05-04-03:59A - Windows 7 - Google Chrome [Version 50.0.2661.94]

wanted this done for a 'YouTube Pop-out Player' without Chrome Address / Toolbar or Bookmarks Bar; solution ended up being a small edit of MarkHu's answer (because of new updates, i guess?)

Go to the page you want altered, select Chrome Toolbar's 'Hamburger button' (3 horizontal lines).

From there: More tools > Add to desktop... > Open as window (tick box) > Add (button).

... and, simply open your page from the new desktop shortcut, adjust as needed, and enjoy!

Creating a comma separated list from IList<string> or IEnumerable<string>

You can use .ToArray() on Lists and IEnumerables, and then use String.Join() as you wanted.

Way to go from recursion to iteration

There is a general way of converting recursive traversal to iterator by using a lazy iterator which concatenates multiple iterator suppliers (lambda expression which returns an iterator). See my Converting Recursive Traversal to Iterator.

download a file from Spring boot rest service

If you need to download a huge file from the server's file system, then ByteArrayResource can take all Java heap space. In that case, you can use FileSystemResource

Read line with Scanner


For everybody who still can't read in a simple .txt file with the Java scanner.


I had the problem that the scanner couldn't read in the next line, when I Copy and Pasted the information, or when there was to much text in my file.

The solution is: Coder your .txt file into UTF-8.
This can be done fairly simple by saving opening the file again and changing the coding to UTF-8. (Under Win7 near the bottom right corner)

The Scanner shouldn't have any problem after this.

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

This is an API issue, you won't get this error if using Postman/Fielder to send HTTP requests to API. In case of browsers, for security purpose, they always send OPTIONS request/preflight to API before sending the actual requests (GET/POST/PUT/DELETE). Therefore, in case, the request method is OPTION, not only you need to add "Authorization" into "Access-Control-Allow-Headers", but you need to add "OPTIONS" into "Access-Control-allow-methods" as well. This was how I fixed:

if (context.Request.Method == "OPTIONS")
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
            context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept, Authorization" });
            context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
            context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });

        }

Matplotlib: "Unknown projection '3d'" error

Import mplot3d whole to use "projection = '3d'".

Insert the command below in top of your script. It should run fine.

from mpl_toolkits import mplot3d

Why rgb and not cmy?

the 3 additive colors are in fact red, green, and blue. printers use cmyk (cyan, magenta, yellow, and black).

and as http://en.wikipedia.org/wiki/Additive_color explains: if you use RYB as your primary colors, how do you make green? since yellow is made from equal amounts of red and green.

How can I safely create a nested directory?

On Python = 3.5, use pathlib.Path.mkdir:

from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)

For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:

Try os.path.exists, and consider os.makedirs for the creation.

import os
if not os.path.exists(directory):
    os.makedirs(directory)

As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.

One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.

Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.

Modern versions of Python improve this code quite a bit, both by exposing FileExistsError (in 3.3+)...

try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass

...and by allowing a keyword argument to os.makedirs called exist_ok (in 3.2+).

os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.

includes() not working in all browsers

import 'core-js/es7/array' 

into polyfill.ts worked for me.

How to get the ASCII value of a character

From here:

The function ord() gets the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick.

>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>

In Python 2, there was also the unichr function, returning the Unicode character whose ordinal is the unichr argument:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'

In Python 3 you can use chr instead of unichr.


ord() - Python 3.6.5rc1 documentation

ord() - Python 2.7.14 documentation

Determine .NET Framework version for dll

dotPeek is a great (free) tool to show this information.

If you are having a few issues getting hold of Reflector then this is a good alternative.

enter image description here

Join/Where with LINQ and Lambda

Posting because when I started LINQ + EntityFramework, I stared at these examples for a day.

If you are using EntityFramework, and you have a navigation property named Meta on your Post model object set up, this is dirt easy. If you're using entity and don't have that navigation property, what are you waiting for?

database
  .Posts
  .Where(post => post.ID == id)
  .Select(post => new { post, post.Meta });

If you're doing code first, you'd set up the property thusly:

class Post {
  [Key]
  public int ID {get; set}
  public int MetaID { get; set; }
  public virtual Meta Meta {get; set;}
}

Login credentials not working with Gmail SMTP

if you are getting error this(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o60sm2132303pje.21 - gsmtp')

then simply go in you google accountsettings of security section and make a less secure account and turn on the less secure button

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Pass CultureInfo.InvariantCulture as the second parameter of DateTime, it will return the string as what you want, even a very special format:

DateTime.Now.ToString("dd|MM|yyyy", CultureInfo.InvariantCulture)

will return: 28|02|2014

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

`require': no such file to load -- mkmf (LoadError)

You've Ruby 1.8 so you need to upgrade to at least 1.9 to make it working.

If so, then check How to install a specific version of a ruby gem?

If this won't help, then reinstalling ruby-dev again.

How to get a random number between a float range?

Use random.uniform(a, b):

>>> random.uniform(1.5, 1.9)
1.8733202628557872

Cannot set content-type to 'application/json' in jQuery.ajax

I had the same issue. I'm running a java rest app on a jboss server. But I think the solution is similar on an ASP .NET webapp.

Firefox makes a pre call to your server / rest url to check which options are allowed. That is the "OPTIONS" request which your server doesn't reply to accordingly. If this OPTIONS call is replied correct a second call is performed which is the actual "POST" request with json content.

This only happens when performing a cross-domain call. In your case calling 'http://localhost:16329/Hello' instead of calling a url path under the same domain '/Hello'

If you intend to make a cross domain call you have to enhance your rest service class with an annotated method the supports a "OPTIONS" http request. This is the according java implementation:

@Path("/rest")
public class RestfulService {

    @POST
    @Path("/Hello")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public string HelloWorld(string name)
    {
        return "hello, " + name;
    }

//THIS NEEDS TO BE ADDED ADDITIONALLY IF MAKING CROSS-DOMAIN CALLS

    @OPTIONS
    @Path("/Hello")
    @Produces(MediaType.TEXT_PLAIN+ ";charset=utf-8")
    public Response checkOptions(){
        return Response.status(200)
        .header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Headers", "Content-Type")
        .header("Access-Control-Allow-Methods", "POST, OPTIONS") //CAN BE ENHANCED WITH OTHER HTTP CALL METHODS 
        .build();
    }
}

So I guess in .NET you have to add an additional method annotated with

[WebInvoke(
        Method = "OPTIONS",
        UriTemplate = "Hello",
        ResponseFormat = WebMessageFormat.)]

where the following headers are set

.header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Headers", "Content-Type")
        .header("Access-Control-Allow-Methods", "POST, OPTIONS")

Check if PHP session has already started

For versions of PHP prior to PHP 5.4.0:

if(session_id() == '') {
    // session isn't started
}

Though, IMHO, you should really think about refactoring your session management code if you don't know whether or not a session is started...

That said, my opinion is subjective, and there are situations (examples of which are described in the comments below) where it may not be possible to know if the session is started.

gem install: Failed to build gem native extension (can't find header files)

It's necessary to install redhat-rpm-config to. I guess it solve your problem!

How to enable Ad Hoc Distributed Queries

You may check the following command

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO  --Added        
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
     'SELECT GroupName, Name, DepartmentID
      FROM AdventureWorks2012.HumanResources.Department
      ORDER BY GroupName, Name') AS a;
GO

Or this documentation link

How to store values from foreach loop into an array?

$items=array(); 
$j=0; 

foreach($group_membership as $i => $username){ 
    $items[$j++]=$username; 
}

Just try the above in your code .

How to import multiple csv files in a single load?

val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\*.csv)

will consider files tmp, tmp1, tmp2, ....

Python error: "IndexError: string index out of range"

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    print(so_far)
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
            else:
                new += so_far[i]    # same value as before
        so_far = new
    else:
        print("try_again")

print('finish')

I tried to write it for py3k with a py2k ide, be careful with errors.

How do I close an open port from the terminal on the Mac?

In 2018 here is what worked for me using MacOS HighSierra:

sudo lsof -nPi :yourPortNumber

then:

sudo kill -9 yourPIDnumber

Concatenate columns in Apache Spark DataFrame

Here is another way of doing this for pyspark:

#import concat and lit functions from pyspark.sql.functions 
from pyspark.sql.functions import concat, lit

#Create your data frame
countryDF = sqlContext.createDataFrame([('Ethiopia',), ('Kenya',), ('Uganda',), ('Rwanda',)], ['East Africa'])

#Use select, concat, and lit functions to do the concatenation
personDF = countryDF.select(concat(countryDF['East Africa'], lit('n')).alias('East African'))

#Show the new data frame
personDF.show()

----------RESULT-------------------------

84
+------------+
|East African|
+------------+
|   Ethiopian|
|      Kenyan|
|     Ugandan|
|     Rwandan|
+------------+

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I got this error message from using an oracle database in a docker despite the fact i had publish port to host option "-p 1521:1521". I was using jdbc url that was using ip address 127.0.0.1, i changed it to the host machine real ip address and everything worked then.

C: What is the difference between ++i and i++?

The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.

In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.

However, you should consider two main problems with the preceding logic.

  1. Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler.

  2. In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.

In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.

This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice."

Run command on the Ansible host

you can try this way

Angular - ng: command not found

Before wasting lots of time in installing and uninstalling, read this.

If you already installed angular before and found this issue, may be it is the reason that you installed angular before with running terminal as Administrator and now trying this command without administrator mode or vice versa. There is a difference in these two.

If you installed angular without administrator mode you can only use angular commands such as ng without administrator mode. Similarly,

If you installed angular with administrator mode you can use angular commands such as ng in administrator mode only.

Run local python script on remote server

Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach.

Using the paramiko library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script. So this solution is pretty much independent of an IDE.

On my local machine, I run the script with a cmd-line parameter 'deploy', which triggers the remote execution. Without such a parameter, the actual code intended for the remote host is run.

import sys
import os

def main():
    print os.name

if __name__ == '__main__':
    try:
        if sys.argv[1] == 'deploy':
            import paramiko

            # Connect to remote host
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect('remote_hostname_or_IP', username='john', password='secret')

            # Setup sftp connection and transmit this script
            sftp = client.open_sftp()
            sftp.put(__file__, '/tmp/myscript.py')
            sftp.close()

            # Run the transmitted script remotely without args and show its output.
            # SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)
            stdout = client.exec_command('python /tmp/myscript.py')[1]
            for line in stdout:
                # Process each line in the remote output
                print line

            client.close()
            sys.exit(0)
    except IndexError:
        pass

    # No cmd-line args provided, run script normally
    main()

Exception handling is left out to simplify this example. In projects with multiple script files you will probably have to put all those files (and other dependencies) on the remote host.

How to create JSON string in C#

If you can't or don't want to use the two built-in JSON serializers (JavaScriptSerializer and DataContractJsonSerializer) you can try the JsonExSerializer library - I use it in a number of projects and works quite well.

cordova Android requirements failed: "Could not find an installed version of Gradle"

If you have android studio installed then you might want to try:

export PATH="$PATH:/home/<username>/android-studio/gradle/<gradle-4.0>/bin" 

This solved my problem.

Ajax success function

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

jQuery.ajax({

            type:"post",
            dataType:"json",
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                successmessage = 'Data was succesfully captured';
                $("label#successmessage").text(successmessage);
            },
            error: function(data) {
                successmessage = 'Error';
                $("label#successmessage").text(successmessage);
            },
        });

        $(":input").val('');
        return false;

Create the perfect JPA entity

The JPA 2.0 Specification states that:

  • The entity class must have a no-arg constructor. It may have other constructors as well. The no-arg constructor must be public or protected.
  • The entity class must a be top-level class. An enum or interface must not be designated as an entity.
  • The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
  • If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.
  • Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.

The specification contains no requirements about the implementation of equals and hashCode methods for entities, only for primary key classes and map keys as far as I know.

DNS problem, nslookup works, ping doesn't

I think this behavior can be turned off, but Window's online help wasn't extremely clear:

If you disable NetBIOS over TCP/IP, you cannot use broadcast-based NetBIOS name resolution to resolve computer names to IP addresses for computers on the same network segment. If your computers are on the same network segment, and NetBIOS over TCP/IP is disabled, you must install a DNS server and either have the computers register with DNS (or manually configure DNS records) or configure entries in the local Hosts file for each computer.

In Windows XP, there is a checkbox:

Advanced TCP/IP Settings

[ ] Enable LMHOSTS lookup

There is also a book that covers this at length, "Networking Personal Computers with TCP/IP: Building TCP/IP Networks (old O'Reilly book)". Unfortunately, I cannot look it up because I disposed of my copy a while ago.

How to get a URL parameter in Express?

If you want to grab the query parameter value in the URL, follow below code pieces

//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid

If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;

next();
});

// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});

Javascript ES6/ES5 find in array and change

worked for me

let returnPayments = [ ...this.payments ];

returnPayments[this.payments.findIndex(x => x.id == this.payment.id)] = this.payment;

Database development mistakes made by application developers

Many developers tend to execute multiple queries against the database (often querying one or two tables) extract the results and perform simple operations in java/c/c++ - all of which could have been done with a single SQL statement.

Many developers often dont realize that on development environments database and app servers are on their laptops - but on a production environment, database and apps server will be on different machines. Hence for every query there is an additional n/w overhead for the data to be passed between the app server and the database server. I have been amazed to find the number of database calls that are made from the app server to the database server to render one page to the user!

sh: react-scripts: command not found after running npm start

Just ran into this problem after installing material-ui.

Solved it by simply running npm install again.

How to get the innerHTML of selectable jquery element?

Use .val() instead of .innerHTML for getting value of selected option

Use .text() for getting text of selected option

Thanks for correcting :)

Python reading from a file and saving to utf-8

You can't do that using open. use codecs.

when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:

import codecs
file = codecs.open('data.txt','w','utf-8')

How to get the home directory in Python?

I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

Code:

import os
print(os.path.expanduser("~"))

Output Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

Output Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

I also tested it on Python 2.7.17 and that works too.

What does void* mean and how to use it?

a void* is a pointer, but the type of what it points to is unspecified. When you pass a void pointer to a function you will need to know what its type was in order to cast it back to that correct type later in the function to use it. You will see examples in pthreads that use functions with exactly the prototype in your example that are used as the thread function. You can then use the void* argument as a pointer to a generic datatype of your choosing and then cast it back to that type to use within your thread function. You need to be careful when using void pointers though as unless you case back to a pointer of its true type you can end up with all sorts of problems.

How to Update/Drop a Hive Partition?

Alter table table_name drop partition (partition_name);

Jenkins Slave port number for firewall

We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").

TCP
49187 - Fixed jnlp port
8080 - jenkins http port

Other ports needed to launch slave as a windows service

TCP
135 
139 
445

UDP
137
138

How to generate a core dump in Linux on a segmentation fault?

What I did at the end was attach gdb to the process before it crashed, and then when it got the segfault I executed the generate-core-file command. That forced generation of a core dump.

Difference between string object and string literal

According to String class documentation they are equivalent.

Documentation for String(String original) also says that: Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

Look for other responses, because it seems that Java documentation is misleading :(

Text in a flex container doesn't wrap in IE11

I had a similar issue with overflowing images in a flex wrapper.

Adding either flex-basis: 100%; or flex: 1; to the overflowing child fixed worked for me.

Simple if else onclick then do?

You should use onclick method because the function run once when the page is loaded and no button will be clicked then

So you have to add an even which run every time the user press any key to add the changes to the div background

So the function should be something like this

htmlelement.onclick() = function(){
    //Do the changes 
}

So your code has to look something like this :

var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no = document.getElementById("no");

yes.onclick = function(){
    box.style.backgroundColor = "red";
}

no.onclick = function(){
    box.style.backgroundColor = "green";
}

This is meaning that when #yes button is clicked the color of the div is red and when the #no button is clicked the background is green

Here is a Jsfiddle

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

How do I view the list of functions a Linux shared library is exporting?

What you need is nm and its -D option:

$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
         U atanf
         U calloc
.
.
.

Exported sumbols are indicated by a T. Required symbols that must be loaded from other shared objects have a U. Note that the symbol table does not include just functions, but exported variables as well.

See the nm manual page for more information.

C++ vector of char array

What I found out is that it's OK to put char* into a std::vector:

//  1 - A std::vector of char*, more preper way is to use a std::vector<std::vector<char>> or std::vector<std::string>
std::vector<char*> v(10, "hi!");    //  You cannot put standard library containers e.g. char[] into std::vector!
for (auto& i : v)
{
    //std::cout << i << std::endl;
    i = "New";
}
for (auto i : v)
{
    std::cout << i << std::endl;
}

What is Parse/parsing?

Parsing means we are analyzing an object specifically. For example, when we enter some keywords in a search engine, they parse the keywords and give back results by searching for each word. So it is basically taking a string from the file and processing it to extract the information we want.

Example of parsing using indexOf to calculate the position of a string in another string:

String s="What a Beautiful day!";

int i=s.indexOf("day");//value of i would be 17
int j=s.indexOf("be");//value of j would be -1
int k=s.indexOf("ea");//value of k would be 8

paresInt essentially converts a String to a Integer.

String s="9876543";
int a=new Integer(s);//uses constructor
System.out.println("Constructor method: " + a);
a=Integer.parseInt(s);//uses parseInt() method
System.out.println("parseInt() method: " + a);

Output:

Constructor method: 9876543

parseInt() method: 9876543

How do I get the information from a meta tag with JavaScript?

If you are interessted in a more far-reaching solution to get all meta tags you could use this piece of code

function getAllMetas() {
    var metas = document.getElementsByTagName('meta');
    var summary = [];
    Array.from(metas)
        .forEach((meta) => {
            var tempsum = {};
            var attributes = meta.getAttributeNames();
            attributes.forEach(function(attribute) {
                tempsum[attribute] = meta.getAttribute(attribute);
            });
            summary.push(tempsum);
        });
    return summary;
}

// usage
console.log(getAllMetas());

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

Dictionary with list of strings as value

I'd wrap the dictionary in another class:

public class MyListDictionary
{

    private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();

    public void Add(string key, string value)
    {
        if (this.internalDictionary.ContainsKey(key))
        {
            List<string> list = this.internalDictionary[key];
            if (list.Contains(value) == false)
            {
                list.Add(value);
            }
        }
        else
        {
            List<string> list = new List<string>();
            list.Add(value);
            this.internalDictionary.Add(key, list);
        }
    }

}

How to create a zip archive with PowerShell?

The ionic approach rocks:

https://dotnetzip.codeplex.com/wikipage?title=PS-Examples

supports passwords, other crypto methods, etc.

How can I configure my makefile for debug and release builds?

you can have a variable

DEBUG = 0

then you can use a conditional statement

  ifeq ($(DEBUG),1)

  else

  endif

Reset CSS display property to default value

Unset display:

You can use the value unset which works in both Firefox and Chrome.

display: unset;

.foo     { display: none;  }
.foo.bar { display: unset; }

How / can I display a console window in Intellij IDEA?

On IntelliJ IDEA 2020.2.1

Click on the tab that you want to open as window mode.

Right-click on the tab name and select View mode > Window

As this image

When to use reinterpret_cast?

Quick answer: use static_cast if it compiles, otherwise resort to reinterpret_cast.

Check if string doesn't contain another string

Or alternatively, you could use this:

WHERE CHARINDEX(N'Apples', someColumn) = 0

Not sure which one performs better - you gotta test it! :-)

Marc

UPDATE: the performance seems to be pretty much on a par with the other solution (WHERE someColumn NOT LIKE '%Apples%') - so it's really just a question of your personal preference.

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

Thought I'll add this one to the mix:

Collections.addAll(result, preprocessor.preprocess(lines));

This is the change that Intelli recommends.

from the javadocs:

_x000D_
_x000D_
Adds all of the specified elements to the specified collection._x000D_
Elements to be added may be specified individually or as an array._x000D_
The behavior of this convenience method is identical to that of_x000D_
<tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely_x000D_
to run significantly faster under most implementations._x000D_
 _x000D_
When elements are specified individually, this method provides a_x000D_
convenient way to add a few elements to an existing collection:_x000D_
<pre>_x000D_
Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");_x000D_
</pre>
_x000D_
_x000D_
_x000D_

How to get the first and last date of the current year?

The best way to get First Date and Last Date of a year Is

SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '01' + '-' + '01' AS DATE) FIRST_DATE
SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '12' + '-' + '31' AS DATE) LAST_DATE

When to use AtomicReference in Java?

Another simple example is to do a safe-thread modification in a session object.

public PlayerScore getHighScore() {
    ServletContext ctx = getServletConfig().getServletContext();
    AtomicReference<PlayerScore> holder 
        = (AtomicReference<PlayerScore>) ctx.getAttribute("highScore");
    return holder.get();
}

public void updateHighScore(PlayerScore newScore) {
    ServletContext ctx = getServletConfig().getServletContext();
    AtomicReference<PlayerScore> holder 
        = (AtomicReference<PlayerScore>) ctx.getAttribute("highScore");
    while (true) {
        HighScore old = holder.get();
        if (old.score >= newScore.score)
            break;
        else if (holder.compareAndSet(old, newScore))
            break;
    } 
}

Source: http://www.ibm.com/developerworks/library/j-jtp09238/index.html

How to run Visual Studio post-build events for debug build only

In Visual Studio 2012 you have to use (I think in Visual Studio 2010, too)

if $(Configuration) == Debug xcopy

$(ConfigurationName) was listed as a macro, but it wasn't assigned.

Enter image description here

Compare: Macros for Build Commands and Properties

What is sys.maxint in Python 3?

Python 3.0 doesn't have sys.maxint any more since Python 3's ints are of arbitrary length. Instead of sys.maxint it has sys.maxsize; the maximum size of a positive sized size_t aka Py_ssize_t.

Get contentEditable caret index position

//global savedrange variable to store text range in
var savedrange = null;

function getSelection()
{
    var savedRange;
    if(window.getSelection && window.getSelection().rangeCount > 0) //FF,Chrome,Opera,Safari,IE9+
    {
        savedRange = window.getSelection().getRangeAt(0).cloneRange();
    }
    else if(document.selection)//IE 8 and lower
    { 
        savedRange = document.selection.createRange();
    }
    return savedRange;
}

$('#contentbox').keyup(function() { 
    var currentRange = getSelection();
    if(window.getSelection)
    {
        //do stuff with standards based object
    }
    else if(document.selection)
    { 
        //do stuff with microsoft object (ie8 and lower)
    }
});

Note: the range object its self can be stored in a variable, and can be re-selected at any time unless the contents of the contenteditable div change.

Reference for IE 8 and lower: http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx

Reference for standards (all other) browsers: https://developer.mozilla.org/en/DOM/range (its the mozilla docs, but code works in chrome, safari, opera and ie9 too)

Finish an activity from another activity

First call startactivity() then use finish()

ValueError: setting an array element with a sequence

When the shape is not regular or the elements have different data types, the dtype argument passed to np.array only can be object.

import numpy as np

# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32)  # error
arr2 = np.array([[10, 20.], [30], [40]])  # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello'])     # OK, and the dtype is also object

``

How do I expand the output display to see more columns of a pandas DataFrame?

You can simply do the following steps,

  • You can change the options for pandas max_columns feature as follows

    import pandas as pd
    pd.options.display.max_columns = 10
    

    (this allows 10 columns to display, you can change this as you need)

  • Like that you can change the number of rows as you need to display as follows (if you need to change maximum rows as well)

    pd.options.display.max_rows = 999
    

    (this allows to print 999 rows at a time)

Please kindly refer the doc to change different options/settings for pandas

PySpark 2.0 The size or shape of a DataFrame

You can get its shape with:

print((df.count(), len(df.columns)))

How to get the current time in milliseconds in C Programming

There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

How do I pull files from remote without overwriting local files?

You can stash your local changes first, then pull, then pop the stash.

git stash
git pull origin master
git stash pop

Anything that overrides changes from remote will have conflicts which you will have to manually resolve.

How to prevent a browser from storing passwords

< input type="password" style='pointer-event: none' onInput= (e) => handleInput(e) />
function handleInput(e) {
  e.preventDefault();
  e.stopPropagation();
  e.target.setAttribute('readonly', true);
  setTimeout(() => {
    e.target.focus();
    e.target.removeAttribute('readonly');
  });
}

How to check if a map contains a key in Go?

In addition to The Go Programming Language Specification, you should read Effective Go. In the section on maps, they say, amongst other things:

An attempt to fetch a map value with a key that is not present in the map will return the zero value for the type of the entries in the map. For instance, if the map contains integers, looking up a non-existent key will return 0. A set can be implemented as a map with value type bool. Set the map entry to true to put the value in the set, and then test it by simple indexing.

attended := map[string]bool{
    "Ann": true,
    "Joe": true,
    ...
}

if attended[person] { // will be false if person is not in the map
    fmt.Println(person, "was at the meeting")
}

Sometimes you need to distinguish a missing entry from a zero value. Is there an entry for "UTC" or is that 0 because it's not in the map at all? You can discriminate with a form of multiple assignment.

var seconds int
var ok bool
seconds, ok = timeZone[tz]

For obvious reasons this is called the “comma ok” idiom. In this example, if tz is present, seconds will be set appropriately and ok will be true; if not, seconds will be set to zero and ok will be false. Here's a function that puts it together with a nice error report:

func offset(tz string) int {
    if seconds, ok := timeZone[tz]; ok {
        return seconds
    }
    log.Println("unknown time zone:", tz)
    return 0
}

To test for presence in the map without worrying about the actual value, you can use the blank identifier (_) in place of the usual variable for the value.

_, present := timeZone[tz]

How to limit text width

You can apply css like this:

div {
   word-wrap: break-word;
   width: 100px;
}

Usually browser does not break words, but word-wrap: break-word; will force it to break words too.

Demo: http://jsfiddle.net/Mp7tc/

More info about word-wrap

Set UITableView content inset permanently

After one hour of tests the only way that works 100% is this one:

-(void)hideSearchBar
{
    if([self.tableSearchBar.text length]<=0 && !self.tableSearchBar.isFirstResponder)
    {
        self.tableView.contentOffset = CGPointMake(0, self.tableSearchBar.bounds.size.height);
        self.edgesForExtendedLayout = UIRectEdgeBottom;
    }
}

-(void)viewDidLayoutSubviews
{
    [self hideSearchBar];
}

with this approach you can always hide the search bar if is empty

Best way to require all files from a directory in ruby?

If it's a directory relative to the file that does the requiring (e.g. you want to load all files in the lib directory):

Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }

Edit: Based on comments below, an updated version:

Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);

Rename Oracle Table or View

In order to rename a table in a different schema, try:

ALTER TABLE owner.mytable RENAME TO othertable;

The rename command (as in "rename mytable to othertable") only supports renaming a table in the same schema.

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

This is an IndexError in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.

# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64) 

# check its shape      
In [15]: arr.shape  
Out[15]: (0,)

with this array arr in place, if we now try to assign any value to some index, for example to the index 0 as in the case below

In [16]: arr[0] = 23     

Then, we will get an IndexError, as below:


IndexError                                Traceback (most recent call last)
<ipython-input-16-0891244a3c59> in <module>
----> 1 arr[0] = 23

IndexError: index 0 is out of bounds for axis 0 with size 0

The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0).

In [19]: arr.size * arr.itemsize  
Out[19]: 0

So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0 and fix that.

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

If you are on mac, Use rvm to install your specific version of ruby. See https://owanateamachree.medium.com/how-to-install-ruby-using-ruby-version-manager-rvm-on-macos-mojave-ab53f6d8d4ec

Make sure you follow all the steps. This worked for me.

Enable 'xp_cmdshell' SQL Server

Right click server -->Facets-->Surface Area Configuration -->XPCmshellEnbled -->true enter image description here

Suppress Scientific Notation in Numpy When Creating Array From Nested List

for 1D and 2D arrays you can use np.savetxt to print using a specific format string:

>>> import sys
>>> x = numpy.arange(20).reshape((4,5))
>>> numpy.savetxt(sys.stdout, x, '%5.2f')
 0.00  1.00  2.00  3.00  4.00
 5.00  6.00  7.00  8.00  9.00
10.00 11.00 12.00 13.00 14.00
15.00 16.00 17.00 18.00 19.00

Your options with numpy.set_printoptions or numpy.array2string in v1.3 are pretty clunky and limited (for example no way to suppress scientific notation for large numbers). It looks like this will change with future versions, with numpy.set_printoptions(formatter=..) and numpy.array2string(style=..).