Programs & Examples On #Seam3

Seam 3 is a collection of modules and developer tooling tailored for Java EE 6 application development, with CDI as the central piece. http://seamframework.org/Seam3

How exactly does <script defer="defer"> work?

As defer attribute works only with scripts tag with src. Found a way to mimic defer for inline scripts. Use DOMContentLoaded event.

<script defer src="external-script.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
    // Your inline scripts which uses methods from external-scripts.
});
</script>

This is because, DOMContentLoaded event fires after defer attributed scripts are completely loaded.

Popup window in PHP?

if (isset($_POST['Register']))
    {
        $ErrorArrays = array (); //Empty array for input errors 

        $Input_Username = $_POST['Username'];
        $Input_Password = $_POST['Password'];
        $Input_Confirm = $_POST['ConfirmPass'];
        $Input_Email = $_POST['Email'];

        if (empty($Input_Username))
        {
            $ErrorArrays[] = "Username Is Empty";
        }
        if (empty($Input_Password))
        {
            $ErrorArrays[] = "Password Is Empty";
        }
        if ($Input_Password !== $Input_Confirm)
        {
            $ErrorArrays[] = "Passwords Do Not Match!";
        }
        if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

        if (count($ErrorArrays) == 0)
        {
            // No Errors
        }
        else
        {
            foreach ($ErrorArrays AS $Errors)
            {
                echo "<font color='red'><b>".$Errors."</font></b><br>";
            }
        }
    }

?>

    <form method="POST"> 
        Username: <input type='text' name='Username'> <br>
        Password: <input type='password' name='Password'><br>
        Confirm Password: <input type='password' name='ConfirmPass'><br>
        Email: <input type='text' name='Email'> <br><br>

        <input type='submit' name='Register' value='Register'>


    </form> 

This is a very basic PHP Form validation. This could be put in a try block, but for basic reference, I see this fit following our conversation in the comment box.

What this script will do, is process each of the post elements, and act accordingly, for example:

    if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

This will check:

if $Input_Email is not a valid email. If this is not a valid E-mail, then a message will get added to a empty array.

Further down the script, you will see:

    if (count($ErrorArrays) == 0)
    {
        // No Errors
    }
    else
    {
        foreach ($ErrorArrays AS $Errors)
        {
            echo "<font color='red'><b>".$Errors."</font></b><br>";
        }
    }

Basically. if the array count is not 0, errors have been found. Then the script will print out the errors.

Remember, this is a reference based on our conversation in the comment box, and should be used as such.

Android Bitmap to Base64 String

Now that most people use Kotlin instead of Java, here is the code in Kotlin for converting a bitmap into a base64 string.

import java.io.ByteArrayOutputStream

private fun encodeImage(bm: Bitmap): String? {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val b = baos.toByteArray()
        return Base64.encodeToString(b, Base64.DEFAULT)
    }

How do I format XML in Notepad++?

If you get this error:

Notepad++ Error: Cannot load 32-bit plugin

Cannot load 32-bit plugin, XMLTools.dll is not compatible with the current version of Notepad++

Here you can find a working version for Windows 10 x64: Xml Tools 2.4.9.2 Unicode

Note: It's the only version I've found working on Windows 10 Professional x64.

How to make a flex item not fill the height of the flex container?

The align-items, or respectively align-content attribute controls this behaviour.

align-items defines the items' positioning perpendicularly to flex-direction.

The default flex-direction is row, therfore vertical placement can be controlled with align-items.

There is also the align-self attribute to control the alignment on a per item basis.

_x000D_
_x000D_
#a {_x000D_
  display:flex;_x000D_
_x000D_
  align-items:flex-start;_x000D_
  align-content:flex-start;_x000D_
  }_x000D_
_x000D_
#a > div {_x000D_
  _x000D_
  background-color:red;_x000D_
  padding:5px;_x000D_
  margin:2px;_x000D_
  }_x000D_
 #a > #c {_x000D_
  align-self:stretch;_x000D_
 }
_x000D_
<div id="a">_x000D_
  _x000D_
  <div id="b">left</div>_x000D_
  <div id="c">middle</div>_x000D_
  <div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

css-tricks has an excellent article on the topic. I recommend reading it a couple of times.

Test for array of string type in TypeScript

I know this has been answered, but TypeScript introduced type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards

If you have a type like: Object[] | string[] and what to do something conditionally based on what type it is - you can use this type guarding:

function isStringArray(value: any): value is string[] {
  if (value instanceof Array) {
    value.forEach(function(item) { // maybe only check first value?
      if (typeof item !== 'string') {
        return false
      }
    })
    return true
  }
  return false
}

function join<T>(value: string[] | T[]) {
  if (isStringArray(value)) {
    return value.join(',') // value is string[] here
  } else {
    return value.map((x) => x.toString()).join(',') // value is T[] here
  }
}

There is an issue with an empty array being typed as string[], but that might be okay

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

ESRI : Failed to parse source map

I had the same problem because .htaccess has incorrect settings:

RewriteEngine on
RewriteRule !.(js|gif|jpg|png|css)$ index.php


I solved this by modifying the file:

RewriteEngine on
RewriteRule !.(js|gif|jpg|png|css|eot|svg|ttf|woff|woff2|map)$ index.php

How to update column value in laravel

Version 1:

// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();

Version 2:

$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();

In case of answered question you can use them:

$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();

How do I change a tab background color when using TabLayout?

Add atribute in xml:

<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

And create in drawable folder, tab_color_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
    <item android:drawable="@color/tab_background_unselected"/>
</selector>

Get HTML code from website in C#

Try this solution. It works fine.

 try{
        String url = textBox1.Text;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(sr);
        var aTags = doc.DocumentNode.SelectNodes("//a");
        int counter = 1;
        if (aTags != null)
        {
            foreach (var aTag in aTags)
            {
                richTextBox1.Text +=  aTag.InnerHtml +  "\n" ;
                counter++;
            }
        }
        sr.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to retrieve related keywords." + ex);
        }

sorting and paging with gridview asp.net

Save your sorting order in a ViewState.

private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";

public SortDirection GridViewSortDirection
{
    get
    {
        if (ViewState["sortDirection"] == null)
            ViewState["sortDirection"] = SortDirection.Ascending;

        return (SortDirection) ViewState["sortDirection"];                
    }
    set { ViewState["sortDirection"] = value; } 
}

protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
    string sortExpression = e.SortExpression;

    if (GridViewSortDirection == SortDirection.Ascending)
    {
        GridViewSortDirection = SortDirection.Descending;
        SortGridView(sortExpression, DESCENDING);
    }
    else
    {
        GridViewSortDirection = SortDirection.Ascending;
        SortGridView(sortExpression, ASCENDING); 
    }   

}

private void SortGridView(string sortExpression,string direction)
{
    //  You can cache the DataTable for improving performance
    DataTable dt = GetData().Tables[0]; 

    DataView dv = new DataView(dt); 
    dv.Sort = sortExpression + direction;         

    GridView1.DataSource = dv;
    GridView1.DataBind();         
}

Why you don't want to use existing sorting functionality? You can always customize it.

Sorting Data in a GridView Web Server Control at MSDN

Here is an example with customization:

http://www.netomatix.com/development/GridViewSorting.aspx

Order by descending date - month, day and year

You have the field in a string, so you'll need to convert it to datetime

order by CONVERT(datetime, EventDate ) desc

How can you tell if a value is not numeric in Oracle?

SELECT DECODE(REGEXP_COUNT(:value,'\d'),LENGTH(:value),'Y','N') AS is_numeric FROM dual;

There are many ways but this one works perfect for me.

How to convert BigDecimal to Double in Java?

You need to use the doubleValue() method to get the double value from a BigDecimal object.

BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

Given an RGB value, how do I create a tint (or shade)?

Some definitions

  • A shade is produced by "darkening" a hue or "adding black"
  • A tint is produced by "ligthening" a hue or "adding white"

Creating a tint or a shade

Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:

  • RGB:

    • To shade:

      newR = currentR * (1 - shade_factor)
      newG = currentG * (1 - shade_factor)
      newB = currentB * (1 - shade_factor)
      
    • To tint:

      newR = currentR + (255 - currentR) * tint_factor
      newG = currentG + (255 - currentG) * tint_factor
      newB = currentB + (255 - currentB) * tint_factor
      
    • More generally, the color resulting in layering a color RGB(currentR,currentG,currentB) with a color RGBA(aR,aG,aB,alpha) is:

      newR = currentR + (aR - currentR) * alpha
      newG = currentG + (aG - currentG) * alpha
      newB = currentB + (aB - currentB) * alpha
      

    where (aR,aG,aB) = black = (0,0,0) for shading, and (aR,aG,aB) = white = (255,255,255) for tinting

  • HSV or HSB:

    • To shade: lower the Value / Brightness or increase the Saturation
    • To tint: lower the Saturation or increase the Value / Brightness
  • HSL:
    • To shade: lower the Lightness
    • To tint: increase the Lightness

There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB and want to use the HSV model to shade for example, you can just convert to HSV, do the shading and convert back to RGB. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :

Comparing the models

  • RGB has the advantage of being really simple to implement, but:
    • you can only shade or tint your color relatively
    • you have no idea if your color is already tinted or shaded
  • HSV or HSB is kind of complex because you need to play with two parameters to get what you want (Saturation & Value / Brightness)
  • HSL is the best from my point of view:
    • supported by CSS3 (for webapp)
    • simple and accurate:
      • 50% means an unaltered Hue
      • >50% means the Hue is lighter (tint)
      • <50% means the Hue is darker (shade)
    • given a color you can determine if it is already tinted or shaded
    • you can tint or shade a color relatively or absolutely (by just replacing the Lightness part)

concat scope variables into string in angular directive expression

You can just concat the values using +

<a ng-click="$navigate.go('#/path/' + obj.val1 + '/' + obj.val2)">{{obj.val1}}, {{obj.val2}}</a>

Simple example on jsfiddle

I am sure the code you posted is a simplified example, if your path building is more complex I would recommend extracting out a function (or service) that would build your urls so you can effectively write unit test.

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

if you compile in C change

for (int i=0;i<10;i++) { ..

to

int i;
for (i=0;i<10;i++) { ..

You can also compile with the C99 switch set. Put -std=c99 in the compilation line:

gcc -std=c99 foo.c -o foo

REF: http://cplusplus.syntaxerrors.info/index.php?title='for'_loop_initial_declaration_used_outside_C99_mode

Boxplot show the value of mean

You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:

fun_mean <- function(x){
  return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}


ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)

enter image description here

Two Divs on the same row and center align both of them

Align to the center, using display: inline-block and text-align: center.

_x000D_
_x000D_
.outerdiv_x000D_
{_x000D_
    height:100px;_x000D_
    width:500px;_x000D_
    background: red;_x000D_
    margin: 0 auto;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
    height:40px;_x000D_
    width: 100px;_x000D_
    margin: 2px;_x000D_
    box-sizing: border-box;_x000D_
    background: green;_x000D_
    display: inline-block;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
    <div class="innerdiv"></div>_x000D_
    <div class="innerdiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Align to the center using display: flex and justify-content: center

_x000D_
_x000D_
.outerdiv_x000D_
{_x000D_
    height:100px;_x000D_
    width:500px;_x000D_
    background: red;_x000D_
    display: flex;_x000D_
    flex-direction: row;_x000D_
    justify-content: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
    height:40px;_x000D_
    width: 100px;_x000D_
    margin: 2px;_x000D_
    box-sizing: border-box;_x000D_
    background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
    <div class="innerdiv"></div>_x000D_
    <div class="innerdiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Align to the center vertically and horizontally using display: flex, justify-content: center and align-items:center.

_x000D_
_x000D_
.outerdiv_x000D_
{_x000D_
    height:100px;_x000D_
    width:500px;_x000D_
    background: red;_x000D_
    display: flex;_x000D_
    flex-direction: row;_x000D_
    justify-content: center;_x000D_
    align-items:center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
    height:40px;_x000D_
    width: 100px;_x000D_
    margin: 2px;_x000D_
    box-sizing: border-box;_x000D_
    background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
    <div class="innerdiv"></div>_x000D_
    <div class="innerdiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In R, how to find the standard error of the mean?

Remembering that the mean can also by obtained using a linear model, regressing the variable against a single intercept, you can use also the lm(x~1) function for this!

Advantages are:

  • You obtain immediately confidence intervals with confint()
  • You can use tests for various hypothesis about the mean, using for example car::linear.hypothesis()
  • You can use more sophisticated estimates of the standard deviation, in case you have some heteroskedasticity, clustered-data, spatial-data etc, see package sandwich
## generate data
x <- rnorm(1000)

## estimate reg
reg <- lm(x~1)
coef(summary(reg))[,"Std. Error"]
#> [1] 0.03237811

## conpare with simple formula
all.equal(sd(x)/sqrt(length(x)),
          coef(summary(reg))[,"Std. Error"])
#> [1] TRUE

## extract confidence interval
confint(reg)
#>                   2.5 %    97.5 %
#> (Intercept) -0.06457031 0.0625035

Created on 2020-10-06 by the reprex package (v0.3.0)

Remove attribute "checked" of checkbox

Try...

$("#captureAudio").prop('checked', false); 

How to call Stored Procedure in Entity Framework 6 (Code-First)?

.NET Core 5.0 does not have FromSql instead it has FromSqlRaw

All below worked for me. Account class here is Entity in C# with exact same table and column names as in the database.

App configuration class as below

class AppConfiguration
{
    public AppConfiguration()
    {
        var configBuilder = new ConfigurationBuilder();
        var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
        configBuilder.AddJsonFile(path, false);
        var root = configBuilder.Build();
        var appSetting = root.GetSection("ConnectionStrings:DefaultConnection");
        sqlConnectionString = appSetting.Value;
    }

    public string sqlConnectionString { get; set; }
}

DbContext class:

public class DatabaseContext : DbContext
{
    public class OptionsBuild
    {
        public OptionsBuild()
        {
            setting = new AppConfiguration();
            opsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
            opsBuilder.UseSqlServer(setting.sqlConnectionString);
            dbOptions = opsBuilder.Options;
        }

        public DbContextOptionsBuilder<DatabaseContext> opsBuilder { get; set; }
        public DbContextOptions<DatabaseContext> dbOptions { get; set; }

        private AppConfiguration setting { get; set; }
    }

    public static OptionsBuild ops = new OptionsBuild();

    public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
    {
        //disable initializer
        //  Database.SetInitializer<DatabaseContext>(null);
    }

    public DbSet<Account> Account { get; set; }
}

This code should be in your data access layer:

List<Account> accounts = new List<Account>();
var context = new DatabaseContext(DatabaseContext.ops.dbOptions);
accounts = await context.Account.ToListAsync();   //direct select from a table

var param = new SqlParameter("@FirstName", "Bill");
accounts = await context.Account.FromSqlRaw<Account>("exec Proc_Account_Select", 
param).ToListAsync();            //procedure call with parameter
        
accounts = context.Account.FromSqlRaw("SELECT * FROM dbo.Account").ToList();  //raw query

What are the obj and bin folders (created by Visual Studio) used for?

The obj directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.

You can change the actual directories used for both purposes within the project settings, if you like.

How to hide a div after some time period?

_x000D_
_x000D_
$().ready(function(){_x000D_
_x000D_
  $('div.alert').delay(1500);_x000D_
   $('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
_x000D_
_x000D_

How to use setArguments() and getArguments() methods in Fragments?

for those like me who are looking to send objects other than primitives, since you can't create a parameterized constructor in your fragment, just add a setter accessor in your fragment, this always works for me.

Most efficient way to see if an ArrayList contains an object in Java

It depends on how efficient you need things to be. Simply iterating over the list looking for the element which satisfies a certain condition is O(n), but so is ArrayList.Contains if you could implement the Equals method. If you're not doing this in loops or inner loops this approach is probably just fine.

If you really need very efficient look-up speeds at all cost, you'll need to do two things:

  1. Work around the fact that the class is generated: Write an adapter class which can wrap the generated class and which implement equals() based on those two fields (assuming they are public). Don't forget to also implement hashCode() (*)
  2. Wrap each object with that adapter and put it in a HashSet. HashSet.contains() has constant access time, i.e. O(1) instead of O(n).

Of course, building this HashSet still has a O(n) cost. You are only going to gain anything if the cost of building the HashSet is negligible compared to the total cost of all the contains() checks that you need to do. Trying to build a list without duplicates is such a case.


* () Implementing hashCode() is best done by XOR'ing (^ operator) the hashCodes of the same fields you are using for the equals implementation (but multiply by 31 to reduce the chance of the XOR yielding 0)

Address validation using Google Maps API

I am both a web developer and a former employee of one of the companies you mentioned. I completely understand where you're coming from. Verifying addresses seems like a simple problem to tackle, but it's very much an iceberg. I suppose one workaround to the legal constraints of the Google or Yahoo! Maps APIs is to request your users verify their addresses on a map. If I were in your shoes, though, I wouldn't go that route.

The reason address verification services are so expensive is that they require licenses and ongoing relationships with grumpy, bureaucratic postal authorities (including the Royal Mail). Unfortunately, postal authorities are the best (and often the only) sources of data against which to verify addresses, so there really isn't any other way to go about it. The bottom line is you need to weigh the cost of bad addresses (usually a question of mail volume) against the cost of the software to verify them. Irish postal data is even more rubbish than Irish postal formats (which frequently omit building numbers), so there's little you can do about those addresses.

Make div fill remaining space along the main axis in flexbox

Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex on the row container and at least making sure your middle container on the row has a flex-grow value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow properties applied, middle container only needs 1 for flex-grow).

Here's a pic of what I was trying to do and sample code for how I solved it.

enter image description here

_x000D_
_x000D_
.row {
  background: lightgray;
  height: 30px;
  width: 100%;
  display: flex;
  align-items:flex-end;
  margin-top:5px;
}
.left {
  background:lightblue;
}
.separator{
  flex-grow:1;
  border-bottom:dotted 2px black;
}
.right {
  background:coral;
}
_x000D_
<div class="row">
  <div class="left">Left</div>
  <div class="separator"></div>
  <div class="right">Right With Text</div>
</div>
<div class="row">
  <div class="left">Left With More Text</div>
  <div class="separator"></div>
  <div class="right">Right</div>
</div>
<div class="row">
  <div class="left">Left With Text</div>
  <div class="separator"></div>
  <div class="right">Right With More Text</div>
</div>
_x000D_
_x000D_
_x000D_

Webpack how to build production code and how to use it

You can use argv npm module (install it by running npm install argv --save) for getting params in your webpack.config.js file and as for production you use -p flag "build": "webpack -p", you can add condition in webpack.config.js file like below

plugins: [
    new webpack.DefinePlugin({
        'process.env':{
            'NODE_ENV': argv.p ? JSON.stringify('production') : JSON.stringify('development')
        }
    })
]

And thats it.

How does one convert a HashMap to a List in Java?

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
    System.out.println(s);
}

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Another reason of the above error is corrupted jar file. I got the same error but for Junit when running unit tests. Removing jar and downloading it again fixed the issue.

Set icon for Android application

1-Create Your icon in Photoshop Or Coreldraw by size 256*256

note that use PNG file format if you want to have a transparent icon

2-Upload Your icon in https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html

3-Set your setting on this site enter image description here

4-Download the zip file automatically created by the webpage by clicking on download button enter image description here

5-Extract the zip file and copy res folder to you project library enter image description here

note that res folder contain all size icon

6-finally you need to set the manifest to use icon

<application android:icon="@drawable/your_icon" >
.... 
</application>

Passing command line arguments to R CMD BATCH

I add an answer because I think a one line solution is always good! Atop of your myRscript.R file, add the following line:

eval(parse(text=paste(commandArgs(trailingOnly = TRUE), collapse=";")))

Then submit your script with something like:

R CMD BATCH [options] '--args arguments you want to supply' myRscript.R &

For example:

R CMD BATCH --vanilla '--args N=1 l=list(a=2, b="test") name="aname"' myscript.R &

Then:

> ls()
[1] "N"    "l"    "name"

NodeJS/express: Cache and 304 status code

As you said, Safari sends Cache-Control: max-age=0 on reload. Express (or more specifically, Express's dependency, node-fresh) considers the cache stale when Cache-Control: no-cache headers are received, but it doesn't do the same for Cache-Control: max-age=0. From what I can tell, it probably should. But I'm not an expert on caching.

The fix is to change (what is currently) line 37 of node-fresh/index.js from

if (cc && cc.indexOf('no-cache') !== -1) return false;  

to

if (cc && (cc.indexOf('no-cache') !== -1 ||
  cc.indexOf('max-age=0') !== -1)) return false;

I forked node-fresh and express to include this fix in my project's package.json via npm, you could do the same. Here are my forks, for example:

https://github.com/stratusdata/node-fresh https://github.com/stratusdata/express#safari-reload-fix

The safari-reload-fix branch is based on the 3.4.7 tag.

Error running android: Gradle project sync failed. Please fix your project and try again

I got this error going from Gradle 3.5.3 to 5.4.1 (Android Studio prompted and I clicked "Upgrade".)

Gradle proceeded to upgrade but yielded some errors such as:

ONFIGURE SUCCESSFUL in 1m 27s
ERROR: The Android Gradle plugin supports only Crashlytics Gradle plugin version 1.25.4 and higher.
The following dependencies do not satisfy the required version:
root project 'Android%20App' -> io.fabric.tools:gradle:1.25.1
Update plugins
Affected Modules: app

INFO: API 'variant.getExternalNativeBuildTasks()' is obsolete and has been replaced with 'variant.getExternalNativeBuildProviders()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
To determine what is calling variant.getExternalNativeBuildTasks(), use -Pandroid.debug.obsoleteApi=true on the command line to display more information.
Affected Modules: app

INFO: The specified Android SDK Build Tools version (27.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '27.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
Install Build Tools 28.0.3, update version in build file and sync project
Affected Modules: app

The thing that fixed it was opening Settings --> Appearance & Behavior --> System Settings --> Android SDK and I then selected some recent versions of Android SDK like 8, 9, and 10. (I had only had 5.1, 6.0, and Android N Preview installed.)

Once that's installed, I had to modify my build.gradle file for my Module: app

  • Removed buildToolsVersion '27.0.3'

Then I clicked the "Sync Project with Gradle Files" button on the toolbar. The Sync output window offered an option to "Update Plugins" and once I clicked through that everything seemed to work. For good measure I again clicked "Sync Project with Gradle Files" followed by Build --> Clean Project, and finally I was able to run my project again.

How to index characters in a Golang string?

Can be done via slicing too

package main

import "fmt"

func main() {
    fmt.Print("HELLO"[1:2])
}

NOTE: This solution only works for ASCII characters.

Start a fragment via Intent within a Fragment

The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...

Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.

@Override
public void onClick(View v) {
    // Create new fragment and transaction
    Fragment newFragment = new chartsFragment(); 
    // consider using Java coding conventions (upper first char class names!!!)
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit(); 
}

http://developer.android.com/guide/components/fragments.html#Transactions

Display label text with line breaks in c#

You can use <br /> for Line Breaks, and &nbsp; for white space.

string s = "First line <br /> Second line";

Output:

First line
Second line

For more info refer to this: Line break in Label

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

It just means that the server cannot find your image.

Remember The image path must be relative to the CSS file location

Check the path and if the image file exist.

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

ADB.exe is obsolete and has serious performance problems

None of the top-voted answers worked for me, except when I unchecked "Use detected ADB location" as mentioned above by @???. Fortunately, in my case though, the message didn't show up, even when I turned it back on. In other words, the problem might be resolved by restarting "Use detected ADB location" :)

Disable button in angular with two conditions?

Declare a variable in component.ts and initialize it to some value

 buttonDisabled: boolean;

  ngOnInit() {
    this.buttonDisabled = false;
  }

Now in .html or in the template, you can put following code:

<button disabled="{{buttonDisabled}}"> Click Me </button>

Now you can enable/disable button by changing value of buttonDisabled variable.

LINQ Group By and select collection

you can achive it with group join

var result = (from c in Customers
          join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
          Select new { customer = c, orderItems = g});

c is Customer and g is the customers order items.

Process to convert simple Python script into Windows executable

1) Get py2exe from here, according to your Python version.

2) Make a file called "setup.py" in the same folder as the script you want to convert, having the following code:

from distutils.core import setup
import py2exe
setup(console=['myscript.py']) #change 'myscript' to your script

3) Go to command prompt, navigate to that folder, and type:

python setup.py py2exe

4) It will generate a "dist" folder in the same folder as the script. This folder contains the .exe file.

SQLAlchemy ORDER BY DESCENDING?

Just as an FYI, you can also specify those things as column attributes. For instance, I might have done:

.order_by(model.Entry.amount.desc())

This is handy since it avoids an import, and you can use it on other places such as in a relation definition, etc.

For more information, you can refer this

How to send emails from my Android application?

To JUST LET EMAIL APPS to resolve your intent you need to specify ACTION_SENDTO as Action and mailto as Data.

private void sendEmail(){

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    emailIntent.setData(Uri.parse("mailto:" + "[email protected]")); 
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My email's subject");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "My email's body");

    try {
        startActivity(Intent.createChooser(emailIntent, "Send email using..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(Activity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();
    }

}

How to use mongoimport to import csv

1]We can save xsl as .csv file
2] Got to MongoDB bin pathon cmd - > cd D:\Arkay\soft\MongoDB\bin
3] Run below command
> mongoimport.exe -d dbname -c collectionname --type csv --file "D:\Arkay\test.csv" --headerline
4] Verify on Mongo side using below coomand.
>db.collectioname.find().pretty().limit(1)

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I'm on XP and this allowed Git Bash to communicate w/ Github (after much frustration):

  1. copy c:\cygwin\bin\cyg* (~50 files) to c:\Program Files\Git\bin\
  2. copy c:\cygwin\bin\ssh.exe to c:\Program Files\Git\bin\ (overwriting)
  3. Create the file c:\Documents and Settings\<username>\.ssh\config containing:

    Host github.com
        User git
        Hostname github.com
        PreferredAuthentications publickey
        IdentityFile "/cygdrive/c/Documents and Settings/<username>/.ssh/id_rsa"
    
  4. (optional) Use ssh -v git@github to see the connection debugged.

  5. Try a push!

Background: The general problem is a combination of these two:

  • BUG: mingw32 sees all files as 644 (other/group-readable), and nothing I tried in mingw32, cygwin, or Windows could fix it.
  • mingw32's SSH version won't allow that for private keys (generally a good policy in a server).

How to pass password to scp?

If you are connecting to the server from Windows, the Putty version of scp ("pscp") lets you pass the password with the -pw parameter.

This is mentioned in the documentation here.

Authenticating in PHP using LDAP through Active Directory

I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.

Get HTML inside iframe using jQuery

This can be another solution if jquery is loaded in iframe.html.

$('#iframe')[0].contentWindow.$("html").html()

Launch custom android application from android browser

You need to add a pseudo-hostname to the CALLBACK_URL 'app://' doesn't make sense as a URL and cannot be parsed.

How to import a bak file into SQL Server Express

Restoring a Database from Backup

sql-server-->connect to instance-->Databases-->right-click on databases-->Restore
            DataBase..-->Device-->Add-->choose the path_filename(.bak)-->click OK

Making a drop down list using swift?

Unfortunately if you're looking to apply UIPopoverController in iOS9, you'll get a deprecated class warning. Instead you need to set your desired view's UIModalPresentationPopover property to achieve the same result.

Popover

In a horizontally regular environment, a presentation style where the content is displayed in a popover view. The background content is dimmed and taps outside the popover cause the popover to be dismissed. If you do not want taps to dismiss the popover, you can assign one or more views to the passthroughViews property of the associated UIPopoverPresentationController object, which you can get from the popoverPresentationController property.

In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.

Available in iOS 8.0 and later.

Reference: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621355-modalpresentationstyle

Golang append an item to a slice

In order to make your code work without having to return the slice from Test, you can pass a pointer like this:

package main

import (
    "fmt"
)

var a = make([]int, 7, 8)

func Test(slice *[]int) {
    *slice = append(*slice, 100)

    fmt.Println(*slice)
}

func main() {

    for i := 0; i < 7; i++ {
        a[i] = i
    }

    Test(&a)

    fmt.Println(a)
}

Google Text-To-Speech API

I used the url as above: http://translate.google.com/translate_tts?tl=en&q=Hello%20World

And requested with python library..however I'm getting HTTP 403 FORBIDDEN

In the end I had to mock the User-Agent header with the browser's one to succeed.

How to draw a filled circle in Java?

/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
    g.setColor(Color.RED);
    g.fillOval(50,50,20,20);
}

g.fillOval(x-axis,y-axis,width,height);

How to save a data.frame in R?

Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.

write.csv(Data_output, "output.csv", row.names = F, quote = F)

credit to Peter and Ilja, UMCG, the Netherlands

Sequence contains no matching element

Maybe using Where() before First() can help you, as my problem has been solved in this case.

var documentRow = _dsACL.Documents.Where(o => o.ID == id).FirstOrDefault();

Using StringWriter for XML Serialization

It may have been covered elsewhere but simply changing the encoding line of the XML source to 'utf-16' allows the XML to be inserted into a SQL Server 'xml'data type.

using (DataSetTableAdapters.SQSTableAdapter tbl_SQS = new DataSetTableAdapters.SQSTableAdapter())
{
    try
    {
        bodyXML = @"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><test></test>";
        bodyXMLutf16 = bodyXML.Replace("UTF-8", "UTF-16");
        tbl_SQS.Insert(messageID, receiptHandle, md5OfBody, bodyXMLutf16, sourceType);
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        Console.WriteLine(ex.Message);
        Console.ReadLine();
    }
}

The result is all of the XML text is inserted into the 'xml' data type field but the 'header' line is removed. What you see in the resulting record is just

<test></test>

Using the serialization method described in the "Answered" entry is a way of including the original header in the target field but the result is that the remaining XML text is enclosed in an XML <string></string> tag.

The table adapter in the code is a class automatically built using the Visual Studio 2013 "Add New Data Source: wizard. The five parameters to the Insert method map to fields in a SQL Server table.

Checking if a character is a special character in Java

This method checks if a String contains a special character (based on your definition).

/**
 *  Returns true if s contains any character other than 
 *  letters, numbers, or spaces.  Returns false otherwise.
 */

public boolean containsSpecialCharacter(String s) {
    return (s == null) ? false : s.matches("[^A-Za-z0-9 ]");
}

You can use the same logic to count special characters in a string like this:

/**
 *  Counts the number of special characters in s.
 */

 public int getSpecialCharacterCount(String s) {
     if (s == null || s.trim().isEmpty()) {
         return 0;
     }
     int theCount = 0;
     for (int i = 0; i < s.length(); i++) {
         if (s.substring(i, 1).matches("[^A-Za-z0-9 ]")) {
             theCount++;
         }
     }
     return theCount;
 }

Another approach is to put all the special chars in a String and use String.contains:

/**
 *  Counts the number of special characters in s.
 */

 public int getSpecialCharacterCount(String s) {
     if (s == null || s.trim().isEmpty()) {
         return 0;
     }
     int theCount = 0;
     String specialChars = "/*!@#$%^&*()\"{}_[]|\\?/<>,.";
     for (int i = 0; i < s.length(); i++) {
         if (specialChars.contains(s.substring(i, 1))) {
             theCount++;
         }
     }
     return theCount;
 }

NOTE: You must escape the backslash and " character with a backslashes.


The above are examples of how to approach this problem in general.

For your exact problem as stated in the question, the answer by @LanguagesNamedAfterCoffee is the most efficient approach.

Owl Carousel Won't Autoplay

This code should work for you

$("#intro").owlCarousel ({

        slideSpeed : 800,
        autoPlay: 6000,
        items : 1,
        stopOnHover : true,
        itemsDesktop : [1199,1],
        itemsDesktopSmall : [979,1],
        itemsTablet :   [768,1],
      });

Seedable JavaScript random number generator

If you don't need the seeding capability just use Math.random() and build helper functions around it (eg. randRange(start, end)).

I'm not sure what RNG you're using, but it's best to know and document it so you're aware of its characteristics and limitations.

Like Starkii said, Mersenne Twister is a good PRNG, but it isn't easy to implement. If you want to do it yourself try implementing a LCG - it's very easy, has decent randomness qualities (not as good as Mersenne Twister), and you can use some of the popular constants.

EDIT: consider the great options at this answer for short seedable RNG implementations, including an LCG option.

_x000D_
_x000D_
function RNG(seed) {_x000D_
  // LCG using GCC's constants_x000D_
  this.m = 0x80000000; // 2**31;_x000D_
  this.a = 1103515245;_x000D_
  this.c = 12345;_x000D_
_x000D_
  this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1));_x000D_
}_x000D_
RNG.prototype.nextInt = function() {_x000D_
  this.state = (this.a * this.state + this.c) % this.m;_x000D_
  return this.state;_x000D_
}_x000D_
RNG.prototype.nextFloat = function() {_x000D_
  // returns in range [0,1]_x000D_
  return this.nextInt() / (this.m - 1);_x000D_
}_x000D_
RNG.prototype.nextRange = function(start, end) {_x000D_
  // returns in range [start, end): including start, excluding end_x000D_
  // can't modulu nextInt because of weak randomness in lower bits_x000D_
  var rangeSize = end - start;_x000D_
  var randomUnder1 = this.nextInt() / this.m;_x000D_
  return start + Math.floor(randomUnder1 * rangeSize);_x000D_
}_x000D_
RNG.prototype.choice = function(array) {_x000D_
  return array[this.nextRange(0, array.length)];_x000D_
}_x000D_
_x000D_
var rng = new RNG(20);_x000D_
for (var i = 0; i < 10; i++)_x000D_
  console.log(rng.nextRange(10, 50));_x000D_
_x000D_
var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];_x000D_
for (var i = 0; i < 10; i++)_x000D_
  console.log(rng.choice(digits));
_x000D_
_x000D_
_x000D_

Rounding a double to turn it into an int (java)

You really need to post a more complete example, so we can see what you're trying to do. From what you have posted, here's what I can see. First, there is no built-in round() method. You need to either call Math.round(n), or statically import Math.round, and then call it like you have.

How to check if ZooKeeper is running or up from command prompt?

I use:

  jps

Depending on your installation a running Zookeeper would look like

  HQuorumPeer

or sth. with zookeeper in it's name.

Node - how to run app.js?

Node is complaining because there is no function called define, which your code tries to call on its very first line.

define comes from AMD, which is not used in standard node development.

It is possible that the developer you got your project from used some kind of trickery to use AMD in node. You should ask this person what special steps are necessary to run the code.

How do I move an existing Git submodule within a Git repository?

The most modern answer, taken from Valloric's comment above:

  1. Upgrade to Git 1.9.3 (or 2.18 if the submodule contains nested submodules)
  2. git mv old/submod new/submod
  3. Afterwards the .gitmodules and the submodule directory are already staged for a commit (you can verify this with git status.)
  4. Commit the changes with git commitand you're good to go!

Done!

How to reload a page using Angularjs?

$scope.rtGo = function(){
            $window.sessionStorage.removeItem('message');
            $window.sessionStorage.removeItem('status');
        }

Sorting list based on values from another list

zip, sort by the second column, return the first column.

zip(*sorted(zip(X,Y), key=operator.itemgetter(1)))[0]

Get JSON data from external URL and display it in a div as plain text

Since the desired page will be called from a different domain you need to return jsonp instead of a json.

$.get("http://theSource", {callback : "?" }, "jsonp",  function(data) {
    $('#summary').text(data.result);
});

What's a clean way to stop mongod on Mac OS X?

If the service is running via brew, you can stop it using the following command:

brew services stop mongodb

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

try

_x000D_
_x000D_
date.innerHTML= date.innerHTML.replace(/^(..)\//,'<span>$1</span></br>')
_x000D_
<div id="date">23/05/2013</div>
_x000D_
_x000D_
_x000D_

How to set delay in android?

Handler answer in Kotlin :

1 - Create a top-level function inside a file (for example a file that contains all your top-level functions) :

fun delayFunction(function: ()-> Unit, delay: Long) {
    Handler().postDelayed(function, delay)
}

2 - Then call it anywhere you needed it :

delayFunction({ myDelayedFunction() }, 300)

JavaScript isset() equivalent

Age old thread, but there are new ways to run an equivalent isset().

ESNext (Stage 4 December 2019)

Two new syntax allow us to vastly simplify the use of isset() functionality:

Please read the docs and mind the browser compatibility.

Answer

See below for explanation. Note I use StandardJS syntax

Example Usage

// IMPORTANT pass a function to our isset() that returns the value we're
// trying to test(ES6 arrow function)
isset(() => some) // false

// Defining objects
let some = { nested: { value: 'hello' } }

// More tests that never throw an error
isset(() => some) // true
isset(() => some.nested) // true
isset(() => some.nested.value) // true
isset(() => some.nested.deeper.value) // false

// Less compact but still viable except when trying to use `this` context
isset(function () { return some.nested.deeper.value }) // false

Answer Function

/**
 * Checks to see if a value is set.
 *
 * @param   {Function} accessor Function that returns our value
 * @returns {Boolean}           Value is not undefined or null
 */
function isset (accessor) {
  try {
    // Note we're seeing if the returned value of our function is not
    // undefined or null
    return accessor() !== undefined && accessor() !== null
  } catch (e) {
    // And we're able to catch the Error it would normally throw for
    // referencing a property of undefined
    return false
  }
}

Explanation

PHP

Note that in PHP you can reference any variable at any depth - even trying to access a non-array as an array will return a simple true or false:

// Referencing an undeclared variable
isset($some); // false

$some = 'hello';

// Declared but has no depth(not an array)
isset($some); // true
isset($some['nested']); // false

$some = ['nested' => 'hello'];

// Declared as an array but not with the depth we're testing for
isset($some['nested']); // true
isset($some['nested']['deeper']); // false

JS

In JavaScript, we don't have that freedom, we'll always get an error if we do the same because JS is immediately attempting to access the value of deeper before we can wrap it in our isset() function so...

// Common pitfall answer(ES6 arrow function)
const isset = (ref) => typeof ref !== 'undefined'

// Same as above
function isset (ref) { return typeof ref !== 'undefined' }

// Referencing an undeclared variable will throw an error, so no luck here
isset(some) // Error: some is not defined

// Defining a simple object with no properties - so we aren't defining
// the property `nested`
let some = {}

// Simple checking if we have a declared variable
isset(some) // true

// Now trying to see if we have a top level property, still valid
isset(some.nested) // false

// But here is where things fall apart: trying to access a deep property
// of a complex object; it will throw an error
isset(some.nested.deeper) // Error: Cannot read property 'deeper' of undefined
//         ^^^^^^ undefined

More failing alternatives:

// Any way we attempt to access the `deeper` property of `nested` will
// throw an error
some.nested.deeper.hasOwnProperty('value') // Error
//   ^^^^^^ undefined

Object.hasOwnProperty.call(some.nested.deeper, 'value') // Error
//                              ^^^^^^ undefined

// Same goes for typeof
typeof some.nested.deeper !== 'undefined' // Error
//          ^^^^^^ undefined

And some working alternatives that can get redundant fast:

// Wrap everything in try...catch
try {
  if (isset(some.nested.deeper)) {
    // ...
  }
} catch (e) {}

try {
  if (typeof some.nested.deeper !== 'undefined') {
    // ...
  }
} catch (e) {}

// Or by chaining all of the isset which can get long
isset(some) && isset(some.nested) && isset(some.nested.deeper) // false
//                        ^^^^^^ returns false so the next isset() is never run

Conclusion

All of the other answers - though most are viable...

  1. Assume you're only checking to see if the variable is not undefined which is fine for some use cases but can still throw an Error
  2. Assume you're only trying to access a top level property, which again is fine for some use cases
  3. Force you to use a less than ideal approach relative to PHP's isset()
    e.g. isset(some, 'nested.deeper.value')
  4. Use eval() which works but I personally avoid

I think I covered a lot of it. There are some points I make in my answer that I don't touch upon because they - although relevant - are not part of the question(e.g. short circuiting). If need be, though, I can update my answer with links to some of the more technical aspects based on demand.

I spent waaay to much time on this so hopefully it helps people out.

Thank-you for reading!

Set type for function parameters?

Use typeof or instanceof:

const assert = require('assert');

function myFunction(Date myDate, String myString)
{
    assert( typeof(myString) === 'string',  'Error message about incorrect arg type');
    assert( myDate instanceof Date,         'Error message about incorrect arg type');
}

How to print Unicode character in C++?

Special thanks to the answer here for more-or-less the same question.

For me, all I needed was setlocale(LC_ALL, "en_US.UTF-8");

Then, I could use even raw wchar_t characters.

Angular 2 Scroll to bottom (Chat style)

this.contentList.nativeElement.scrollTo({left: 0 , top: this.contentList.nativeElement.scrollHeight, behavior: 'smooth'});

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

How do I dump the data of some SQLite3 tables?

Not the best way, but at lease does not need external tools (except grep, which is standard on *nix boxes anyway)

sqlite3 database.db3 .dump | grep '^INSERT INTO "tablename"'

but you do need to do this command for each table you are looking for though.

Note that this does not include schema.

Using SELECT result in another SELECT

NewScores is an alias to Scores table - it looks like you can combine the queries as follows:

SELECT 
    ROW_NUMBER() OVER( ORDER BY NETT) AS Rank, 
    Name, 
    FlagImg, 
    Nett, 
    Rounds 
FROM (
    SELECT 
        Members.FirstName + ' ' + Members.LastName AS Name, 
        CASE 
            WHEN MenuCountry.ImgURL IS NULL THEN 
                '~/images/flags/ismygolf.png' 
            ELSE 
                MenuCountry.ImgURL 
        END AS FlagImg, 
        AVG(CAST(NewScores.NetScore AS DECIMAL(18, 4))) AS Nett, 
        COUNT(Score.ScoreID) AS Rounds 
    FROM 
        Members 
        INNER JOIN 
        Score NewScores
            ON Members.MemberID = NewScores.MemberID 
        LEFT OUTER JOIN MenuCountry 
            ON Members.Country = MenuCountry.ID 
    WHERE 
        Members.Status = 1 
        AND NewScores.InsertedDate >= DATEADD(mm, -3, GETDATE())
    GROUP BY 
        Members.FirstName + ' ' + Members.LastName, 
        MenuCountry.ImgURL
    ) AS Dertbl 
ORDER BY;

Access Enum value using EL with JSTL

<%@ page import="com.example.Status" %>

1. ${dp.status eq Title.VALID.getStatus()}
2. ${dp.status eq Title.VALID}
3. ${dp.status eq Title.VALID.toString()}
  • Put the import at the top, in JSP page header
  • If you want to work with getStatus method, use #1
  • If you want to work with the enum element itself, use either #2 or #3
  • You can use == instead of eq

SQL: sum 3 columns when one column has a null value?

If you want to avoid the null value use IsNull(Column, 1)

Intercept a form submit in JavaScript and prevent normal submission

<form onSubmit="return captureForm()"> that should do. Make sure that your captureForm() method returns false.

MySQL - Get row number on select

Swamibebop's solution works, but by taking advantage of table.* syntax, we can avoid repeating the column names of the inner select and get a simpler/shorter result:

SELECT @r := @r+1 , 
       z.* 
FROM(/* your original select statement goes in here */)z, 
(SELECT @r:=0)y;

So that will give you:

SELECT @r := @r+1 , 
       z.* 
FROM(
     SELECT itemID, 
     count(*) AS ordercount
     FROM orders
     GROUP BY itemID
     ORDER BY ordercount DESC
    )z,
    (SELECT @r:=0)y;

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

ENABLE is what you are looking for

USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up

 sudo systemctl enable postgresql

DISABLE exists as well ofc

Some DOC: freedesktop man systemctl

Get the value of a dropdown in jQuery

The best way is to use:

$("#yourid option:selected").text();

Depending on the requirement, you could also use this way:

var v = $("#yourid").val();
$("#yourid option[value="+v+"]").text()

Concatenate two NumPy arrays vertically

A not well known feature of numpy is to use r_. This is a simple way to build up arrays quickly:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.r_[a[None,:],b[None,:]]
print(c)
#[[1 2 3]
# [4 5 6]]

The purpose of a[None,:] is to add an axis to array a.

Remove characters from NSString?

if the string is mutable, then you can transform it in place using this form:

[string replaceOccurrencesOfString:@" "
                        withString:@""
                           options:0
                             range:NSMakeRange(0, string.length)];

this is also useful if you would like the result to be a mutable instance of an input string:

NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:@" "
                        withString:@""
                           options:0
                             range:NSMakeRange(0, string.length)];

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

What is the difference between state and props in React?

Simple explanation is : STATE is local state of component for example colour = "blue" or animation=true etc . Use this.setState to change state of component. PROPS is how components talk to each other (send data from parent to child) and make components reusable .

How do you remove the title text from the Android ActionBar?

as a workaround just add this line incase you have custom action/toolbars

this.setTitle("");

in your Activity

How to fix "containing working copy admin area is missing" in SVN?

Just in case anyone wants yet another solution:

  1. Check in your new folder as "foldername2"
  2. Go into Tortise SVN repo browser
  3. Rename "foldername2" to "foldername"
  4. In windows explorer do an update

Hope it helps someone.

-Ev

Combine two pandas Data Frames (join on a common column)

You can use merge to combine two dataframes into one:

import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')

where on specifies field name that exists in both dataframes to join on, and how defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y'). if you wanted to do something like star_restaurant_id and star_restaurant_review, you can do:

 pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))

The parameters are explained in detail in this link.

Set language for syntax highlighting in Visual Studio Code

Press Ctrl + KM and then type in (or click) the language you want.

Alternatively, to access it from the command palette, look for "Change Language Mode" as seen below:

enter image description here

What is the best way to remove a table row with jQuery?

Is the following acceptable:

$('#myTableRow').remove();

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

Locking a file in Python

Locking a file is usually a platform-specific operation, so you may need to allow for the possibility of running on different operating systems. For example:

import os

def my_lock(f):
    if os.name == "posix":
        # Unix or OS X specific locking here
    elif os.name == "nt":
        # Windows specific locking here
    else:
        print "Unknown operating system, lock unavailable"

Full-screen responsive background image

http://css-tricks.com/perfect-full-page-background-image/

//HTML
<img src="images/bg.jpg" id="bg" alt="">

//CSS
#bg {
  position: fixed; 
  top: 0; 
  left: 0; 

  /* Preserve aspet ratio */
  min-width: 100%;
  min-height: 100%;
}

OR

img.bg {
  /* Set rules to fill background */
  min-height: 100%;
  min-width: 1024px;

  /* Set up proportionate scaling */
  width: 100%;
  height: auto;

  /* Set up positioning */
  position: fixed;
  top: 0;
  left: 0;
}

@media screen and (max-width: 1024px) { /* Specific to this particular image */
  img.bg {
    left: 50%;
    margin-left: -512px;   /* 50% */
  }
}

OR

//HTML
<img src="images/bg.jpg" id="bg" alt="">

//CSS
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }

//jQuery
$(window).load(function() {    

        var theWindow        = $(window),
            $bg              = $("#bg"),
            aspectRatio      = $bg.width() / $bg.height();

        function resizeBg() {

                if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
                    $bg
                        .removeClass()
                        .addClass('bgheight');
                } else {
                    $bg
                        .removeClass()
                        .addClass('bgwidth');
                }

        }

        theWindow.resize(resizeBg).trigger("resize");

});

Is there any good dynamic SQL builder library in Java?

Hibernate Criteria API (not plain SQL though, but very powerful and in active development):

List sales = session.createCriteria(Sale.class)
         .add(Expression.ge("date",startDate);
         .add(Expression.le("date",endDate);
         .addOrder( Order.asc("date") )
         .setFirstResult(0)
         .setMaxResults(10)
         .list();

CSS: How to position two elements on top of each other, without specifying a height?

Of course, the problem is all about getting your height back. But how can you do that if you don't know the height ahead of time? Well, if you know what aspect ratio you want to give the container (and keep it responsive), you can get your height back by adding padding to another child of the container, expressed as a percentage.

You can even add a dummy div to the container and set something like padding-top: 56.25% to give the dummy element a height that is a proportion of the container's width. This will push out the container and give it an aspect ratio, in this case 16:9 (56.25%).

Padding and margin use the percentage of the width, that's really the trick here.

How to display a range input slider vertically

You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:

_x000D_
_x000D_
input[type="range"] {_x000D_
   position: absolute;_x000D_
   top: 40%;_x000D_
   transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
_x000D_
_x000D_


or the 3d transform equivalent:

input[type="range"] {
   transform: rotateZ(270deg);
}

You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.

datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:

>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)

>>> type(yesterday)                                                                                                                                                                                    
>>> datetime.datetime    

>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'

Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:

>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'

As a function:

def yesterday(string=False):
    yesterday = datetime.now() - timedelta(1)
    if string:
        return yesterday.strftime('%Y-%m-%d')
    return yesterday

JS. How to replace html element with another element/text, represented in string?

Using jQuery you can do this:

var str = '<td>1</td><td>2</td>';
$('#__TABLE__').replaceWith(str);

http://jsfiddle.net/hZBeW/4/

Or in pure javascript:

var str = '<td>1</td><td>2</td>';
var tdElement = document.getElementById('__TABLE__');
var trElement = tdElement.parentNode;
trElement.removeChild(tdElement);
trElement.innerHTML = str + trElement.innerHTML;

http://jsfiddle.net/hZBeW/1/

What is the difference between LATERAL and a subquery in PostgreSQL?

First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.

Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:

Consider following query.

Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A 

You can use lateral in this condition.

Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
  Select B.Column1,B.Column2,B.Fk1 from B  Limit 1
) x ON X.Fk1 = A.PK

In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.

There are more usages for lateral or cross apply but this is most common one I found.

How to break out of a loop in Bash?

It's not that different in bash.

workdone=0
while : ; do
  ...
  if [ "$workdone" -ne 0 ]; then
      break
  fi
done

: is the no-op command; its exit status is always 0, so the loop runs until workdone is given a non-zero value.


There are many ways you could set and test the value of workdone in order to exit the loop; the one I show above should work in any POSIX-compatible shell.

Angular: Cannot Get /

Check if in index.html base is set

<head>
  <base href="/">
  ...
</head>

How to center a window on the screen in Tkinter?

CENTERING THE WINDOW IN PYTHON Tkinter This is the most easiest thing in tkinter because all we must know is the dimension of the window as well as the dimensions of the computer screen. I come up with the following code which can help someone somehow and i did add some comments so that they can follow up.

code

    #  create a window first
    root = Tk()
    # define window dimensions width and height
    window_width = 800
    window_height = 500
    # get the screen size of your computer [width and height using the root object as foolows]
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    # Get the window position from the top dynamically as well as position from left or right as follows
    position_top = int(screen_height/2 -window_height/2)
    position_right = int(screen_width / 2 - window_width/2)
    # this is the line that will center your window
    root.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}')
    # initialise the window
    root.mainloop(0)

Remove trailing zeros from decimal in SQL Server

I had a similar problem, needed to trim trailing zeros from numbers like xx0000,x00000,xxx000

I used:

select LEFT(code,LEN(code)+1 - PATINDEX('%[1-Z]%',REVERSE(code))) from Tablename

Code is the name of the field with the number to be trimmed. Hope this helps someone else.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:

IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END 

Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.


If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.

IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE clockDate = '08/10/2012' AND userName = 'test'
END 

As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.

Create SQL script that create database and tables

An excellent explanation can be found here: Generate script in SQL Server Management Studio

Courtesy Ali Issa Here's what you have to do:

  1. Right click the database (not the table) and select tasks --> generate scripts
  2. Next --> select the requested table/tables (from select specific database objects)
  3. Next --> click advanced --> types of data to script = schema and data

If you want to create a script that just generates the tables (no data) you can skip the advanced part of the instructions!

Static Block in Java

yes, static block is used for initialize the code and it will load at the time JVM start for execution.

static block is used in previous versions of java but in latest version it doesn't work.

HTML button onclick event

<body>
"button" value="Add Students" onclick="window.location.href='Students.html';"> 
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"> 
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">
</body>

ArrayList or List declaration in Java

There are a few situations where you might prefer the first one to (slightly) improve performance, for example on some JVMs without a JIT compiler.

Out of that kind of very specific context, you should use the first one.

How to import local packages without gopath

Run:

go mod init yellow

Then create a file yellow.go:

package yellow

func Mix(s string) string {
   return s + "Yellow"
}

Then create a file orange/orange.go:

package main
import "yellow"

func main() {
   s := yellow.Mix("Red")
   println(s)
}

Then build:

go build

https://golang.org/doc/code.html

What size should apple-touch-icon.png be for iPad and iPhone?

Use these sizes 57x57, 72x72, 114x114, 144x144 then do this in the head of your document:

<link rel="apple-touch-icon" href="apple-touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-iphone4.png" />

   

This will look good on all apple devices. ;)

Find the most popular element in int[] array

This one without maps:

public class Main {       

    public static void main(String[] args) {
        int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
        System.out.println(getMostPopularElement(a));        
    }

    private static int getMostPopularElement(int[] a) {             
        int maxElementIndex = getArrayMaximumElementIndex(a); 
        int[] b = new int[a[maxElementIndex] + 1]

        for (int i = 0; i < a.length; i++) {
            ++b[a[i]];
        }

        return getArrayMaximumElementIndex(b);
    }

    private static int getArrayMaximumElementIndex(int[] a) {
        int maxElementIndex = 0;

        for (int i = 1; i < a.length; i++) {
            if (a[i] >= a[maxElementIndex]) {
                maxElementIndex = i;
            }
        }

        return maxElementIndex;
    }      

}

You only have to change some code if your array can have elements which are < 0. And this algorithm is useful when your array items are not big numbers.

pandas: multiple conditions while indexing data frame - unexpected behavior

As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them.

That's right. Remember that you're writing the condition in terms of what you want to keep, not in terms of what you want to drop. For df1:

df1 = df[(df.a != -1) & (df.b != -1)]

You're saying "keep the rows in which df.a isn't -1 and df.b isn't -1", which is the same as dropping every row in which at least one value is -1.

For df2:

df2 = df[(df.a != -1) | (df.b != -1)]

You're saying "keep the rows in which either df.a or df.b is not -1", which is the same as dropping rows where both values are -1.

PS: chained access like df['a'][1] = -1 can get you into trouble. It's better to get into the habit of using .loc and .iloc.

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

Count cells that contain any text

Sample file

enter image description here

Note:

  • Tried to find the formula for counting non-blank cells (="" is a blank cell) without a need to use data twice. The solution for : =ARRAYFORMULA(SUM(IFERROR(IF(data="",0,1),1))). For ={SUM(IFERROR(IF(data="",0,1),1))} should work (press Ctrl+Shift+Enter in the formula).

Can I set background image and opacity in the same property?

I came across this post as I had the same issue then I thought why mess about with css, adjusting values and hitting refresh when you can easily adjust the opacity in Photoshop? Copy the image, paste it as a new layer then move the opacity slider.

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

I ended up with cleaning the project file (csproj) and the applicationhost.config (iis express) with all entries regarding iis express configuration. After that, it worked.

How to write data with FileOutputStream without losing old data?

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);

Is there a pure CSS way to make an input transparent?

In case you just need the existence of it you could also throw it off the screen with display: fixed; right: -1000px;. It is useful when you need an input for copying to clipboard. :)

ResourceDictionary in a separate assembly

Using XAML:

If you know the other assembly structure and want the resources in c# code, then use below code:

 ResourceDictionary dictionary = new ResourceDictionary();
 dictionary.Source = new Uri("pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml", UriKind.Absolute);
 foreach (var item in dictionary.Values)
 {
    //operations
 }

Output: If we want to use ResourceDictionary RD1.xaml of Project WpfControlLibrary1 into StackOverflowApp project.

Structure of Projects:

Structure of Projects

Resource Dictionary: Resource Dictionary

Code Output:

Output

PS: All ResourceDictionary Files should have Build Action as 'Resource' or 'Page'.

Using C#:

If anyone wants the solution in purely c# code then see my this solution.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused

When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.

The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.

Android: how to draw a border to a LinearLayout

Do you really need to do that programmatically?

Just considering the title: You could use a ShapeDrawable as android:background…

For example, let's define res/drawable/my_custom_background.xml as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

and define android:background="@drawable/my_custom_background".

I've not tested but it should work.

Update:

I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.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="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

and a res/drawable/border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
   <stroke
        android:width="5dip"
        android:color="@android:color/white" />
</shape>

Reported to work on a gingerbread device. Note that you'll need to relate android:padding of the LinearLayout to the android:width shape/stroke's value. Please, do not use @android:color/white in your final application but rather a project defined color.

You could apply android:background="@drawable/border" android:padding="10dip" to each of the LinearLayout from your provided sample.

As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…

Your problem resides clearly in the use of getBorder.set{Width,Height}(100);. Why do you do that in an onClick method?

I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.

To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…

Can't access Eclipse marketplace

I know it's a bit old but I ran in the same problem today. I wanted to install eclipse on my vm with xubuntu. Because I've had problems with the latest eclipse version 2019-06 I tried with Oxygen. So I went to eclipse.org and downloaded oxygen. When running oxygen, the problem with merketplace not reachable occurs. So I downloaded the eclipse installer not immediatly the oxygen. After that I can use eclipse as expectet ( all versions)

How to catch a specific SqlException error?

If you are looking for a better way to handle SQLException, there are a couple things you could do. First, Spring.NET does something similar to what you are looking for (I think). Here is a link to what they are doing:

http://springframework.net/docs/1.2.0/reference/html/dao.html

Also, instead of looking at the message, you could check the error code (sqlEx.Number). That would seem to be a better way of identifying which error occurred. The only problem is that the error number returned might be different for each database provider. If you plan to switch providers, you will be back to handling it the way you are or creating an abstraction layer that translates this information for you.

Here is an example of a guy who used the error code and a config file to translate and localize user-friendly error messages:

https://web.archive.org/web/20130731181042/http://weblogs.asp.net/guys/archive/2005/05/20/408142.aspx

What exactly is Apache Camel?

Camel sends messages from A to B:

enter image description here

Why a whole framework for this? Well, what if you have:

  • many senders and many receivers
  • a dozen of protocols (ftp, http, jms, etc.)
  • many complex rules
    • Send a message A to Receivers A and B only
    • Send a message B to Receiver C as XML, but partly translate it, enrich it (add metadata) and IF condition X, then send it to Receiver D too, but as CSV.

So now you need:

  • translate between protocols
  • glue components together
  • define routes - what goes where
  • filter some things in some cases

Camel gives you the above (and more) out of the box:

enter image description here

with a cool DSL language for you to define the what and how:

  new DefaultCamelContext().addRoutes(new RouteBuilder() {
        public void configure() {
            from("jms:incomingMessages")
                    .choice() // start router rules
                    .when(header("CamelFileName")
                            .endsWith(".xml"))
                    .to("jms:xmlMessages")
                    .when(header("CamelFileName")
                            .endsWith(".csv"))
                    .to("ftp:csvMessages");
}

See also this and this and Camel in Action (as others have said, an excellent book!)

Create PostgreSQL ROLE (user) if it doesn't exist

Bash alternative (for Bash scripting):

psql -h localhost -U postgres -tc \
"SELECT 1 FROM pg_user WHERE usename = 'my_user'" \
| grep -q 1 \
|| psql -h localhost -U postgres \
-c "CREATE ROLE my_user LOGIN PASSWORD 'my_password';"

(isn't the answer for the question! it is only for those who may be useful)

Method to find string inside of the text file. Then getting the following lines up to a certain limit

Here is a java 8 method to find a string in a text file:

for (String toFindUrl : urlsToTest) {
        streamService(toFindUrl);
    }

private void streamService(String item) {
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
           stream.filter(lines -> lines.contains(item))
                       .forEach(System.out::println);

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

PHP sessions that have already been started

Only if you want to destroy previous session :

<?php
    if(!isset($_SESSION)) 
    { 
        session_start(); 
    }
    else
    {
        session_destroy();
        session_start(); 
    }
?>

or you can use

unset($_SESSION['variable_session _data'])

to destroy a particular session variable.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.

In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
        if (!item.isFormField()) {
            //your operations on file
        } else {
            String name = item.getFieldName();
            String value = item.getString();
            //you operations on paramters
        }
}

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Get content of a DIV using JavaScript

Right now you're setting the innerHTML to an entire div element; you want to set it to just the innerHTML. Also, I think you want MyDiv2.innerHTML = MyDiv 1 .innerHTML. Also, I think the argument to document.getElementById is case sensitive. You were passing Div2 when you wanted DIV2

var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML; 

Also, this code will run before your DOM is ready. You can either put this script at the bottom of your body like paislee said, or put it in your body's onload function

<body onload="loadFunction()">

and then

function loadFunction(){
    var MyDiv1 = Document.getElementById('DIV1');
    var MyDiv2 = Document.getElementById('DIV2');
    MyDiv2.innerHTML = MyDiv1.innerHTML; 
}

How to save a data frame as CSV to a user selected location using tcltk

Take a look at the write.csv or the write.table functions. You just have to supply the file name the user selects to the file parameter, and the dataframe to the x parameter:

write.csv(x=df, file="myFileName")

Is it possible to have multiple styles inside a TextView?

Here is an easy way to do so using HTMLBuilder

    myTextView.setText(new HtmlBuilder().
                    open(HtmlBuilder.Type.BOLD).
                    append("Some bold text ").
                    close(HtmlBuilder.Type.BOLD).
                    open(HtmlBuilder.Type.ITALIC).
                    append("Some italic text").
                    close(HtmlBuilder.Type.ITALIC).
                    build()
    );

Result:

Some bold text Some italic text

How do you get a query string on Flask?

from flask import request

@app.route('/data')
def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get('user')

Creating an R dataframe row-by-row

I've found this way to create dataframe by raw without matrix.

With automatic column name

df<-data.frame(
        t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
        ,row.names = NULL,stringsAsFactors = FALSE
    )

With column name

df<-setNames(
        data.frame(
            t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
            ,row.names = NULL,stringsAsFactors = FALSE
        ), 
        c("col1","col2","col3")
    )

Sum the digits of a number

Doing some Codecademy challenges I resolved this like:

def digit_sum(n):
    digits = []
    nstr = str(n)
    for x in nstr:
        digits.append(int(x))
    return sum(digits)

Android Studio with Google Play Services

Open your project build.gradle file and add below line under dependencies module.

dependencies {
    compile 'com.google.android.gms:play-services:7.0.0'
}

The below will be add Google Analytics and Maps if you don't want to integrate full library

dependencies {
    compile 'com.google.android.gms:play-services-analytics:7.0.0'
    compile 'com.google.android.gms:play-services-maps:7.0.0'
}

Simultaneously merge multiple data.frames in a list

Here is a generic wrapper which can be used to convert a binary function to multi-parameters function. The benefit of this solution is that it is very generic and can be applied to any binary functions. You just need to do it once and then you can apply it any where.

To demo the idea, I use simple recursion to implement. It can be of course implemented with more elegant way that benefits from R's good support for functional paradigm.

fold_left <- function(f) {
return(function(...) {
    args <- list(...)
    return(function(...){
    iter <- function(result,rest) {
        if (length(rest) == 0) {
            return(result)
        } else {
            return(iter(f(result, rest[[1]], ...), rest[-1]))
        }
    }
    return(iter(args[[1]], args[-1]))
    })
})}

Then you can simply wrap any binary functions with it and call with positional parameters (usually data.frames) in the first parentheses and named parameters in the second parentheses (such as by = or suffix =). If no named parameters, leave second parentheses empty.

merge_all <- fold_left(merge)
merge_all(df1, df2, df3, df4, df5)(by.x = c("var1", "var2"), by.y = c("var1", "var2"))

left_join_all <- fold_left(left_join)
left_join_all(df1, df2, df3, df4, df5)(c("var1", "var2"))
left_join_all(df1, df2, df3, df4, df5)()

Convert negative data into positive data in SQL Server

UPDATE mytbl
SET a = ABS(a)
where a < 0

How to get the selected row values of DevExpress XtraGrid?

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.

For example:

private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
        return;
    MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());            
}

Comparing two .jar files

The result of a query cannot be enumerated more than once

if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this ex:-

repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();

try like this

jQuery Mobile: document ready vs. page events

Some of you might find this useful. Just copy paste it to your page and you will get a sequence in which events are fired in the Chrome console (Ctrl + Shift + I).

$(document).on('pagebeforecreate',function(){console.log('pagebeforecreate');});
$(document).on('pagecreate',function(){console.log('pagecreate');});
$(document).on('pageinit',function(){console.log('pageinit');});
$(document).on('pagebeforehide',function(){console.log('pagebeforehide');});
$(document).on('pagebeforeshow',function(){console.log('pagebeforeshow');});
$(document).on('pageremove',function(){console.log('pageremove');});
$(document).on('pageshow',function(){console.log('pageshow');});
$(document).on('pagehide',function(){console.log('pagehide');});
$(window).load(function () {console.log("window loaded");});
$(window).unload(function () {console.log("window unloaded");});
$(function () {console.log('document ready');});

You are not going see unload in the console as it is fired when the page is being unloaded (when you move away from the page). Use it like this:

$(window).unload(function () { debugger; console.log("window unloaded");});

And you will see what I mean.

Delaying function in swift

You can use GCD (in the example with a 10 second delay):

Swift 2

let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
    self.functionToCall()
})

Swift 3 and Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    self.functionToCall()
})

Swift 5 or Later

 DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
        //call any function
    }

Visual Studio Code: format is not using indent settings

I had a similar problem -- no matter what I did I couldn't get the tabsize to stick at 2, even though it is in my user settings -- that ended up being due to the EditorConfig extension. It looks for a .editorconfig file in your current working directory and, if it doesn't find one (or the one it finds doesn't specify root=true), it will continue looking at parent directories until it finds one.

Turns out I had a .editorconfig in a parent directory of the dir I put all my new code projects in, and it specified a tabSize of 4. Deleting that file fixed my issue.

Remove an item from a dictionary when its key is unknown

a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']

Checking host availability by using ping in bash scripts

I can think of a one liner like this to run

ping -c 1 127.0.0.1 &> /dev/null && echo success || echo fail

Replace 127.0.0.1 with IP or hostname, replace echo commands with what needs to be done in either case.

Code above will succeed, maybe try with an IP or hostname you know that is not accessible.

Like this:

ping -c 1 google.com &> /dev/null && echo success || echo fail

and this

ping -c 1 lolcatz.ninja &> /dev/null && echo success || echo fail

How to get a DOM Element from a JQuery Selector

I needed to get the element as a string.

jQuery("#bob").get(0).outerHTML;

Which will give you something like:

<input type="text" id="bob" value="hello world" />

...as a string rather than a DOM element.

How can I force input to uppercase in an ASP.NET textbox?

Why not use a combination of the CSS and backend? Use:

style='text-transform:uppercase' 

on the TextBox, and in your codebehind use:

Textbox.Value.ToUpper();

You can also easily change your regex on the validator to use lowercase and uppercase letters. That's probably the easier solution than forcing uppercase on them.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

Finally I got a way to to solve this issue by server side as it's more like an issue with AngularJs itself I am using 1.5 Angularjs and I got same issue on reload the page. But after adding below code in my server.js file it is save my day but it's not a proper solution or not a good way .

app.use(function(req, res, next){
  var d = res.status(404);
     if(d){
        res.sendfile('index.html');
     }
});

Angular2 @Input to a property with get/set

You could set the @Input on the setter directly, as described below:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input() set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.

Order of items in classes: Fields, Properties, Constructors, Methods

I know this is old but my order is as follows:

in order of public, protected, private, internal, abstract

  • Constants
  • Static Variables
  • Fields
  • Events
  • Constructor(s)
  • Methods
  • Properties
  • Delegates

I also like to write out properties like this (instead of the shorthand approach)

// Some where in the fields section
private int someVariable;

// I also refrain from
// declaring variables outside of the constructor

// and some where in the properties section I do
public int SomeVariable
{
    get { return someVariable; }
    set { someVariable = value; }
}

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

Calculating arithmetic mean (one type of average) in Python

def avg(l):
    """uses floating-point division."""
    return sum(l) / float(len(l))

Examples:

l1 = [3,5,14,2,5,36,4,3]
l2 = [0,0,0]

print(avg(l1)) # 9.0
print(avg(l2)) # 0.0

Force “landscape” orientation mode

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


Original answer:

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

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

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

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

Or by binding a JavaScript orientation change event like this:

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

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

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

You need to include those line into the json file:

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

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

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

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

bootstrap popover not showing on top of all elements

Problem solved with data-container="body" and z-index
1->
<div class="button btn-align"
data-container="body"  
data-toggle="popover"
data-placement="top"
title="Top"
data-trigger="hover"
data-title-backcolor="#fff"
data-content="A top aligned popover is a really boring thing in the real 
life.">Top</div>
2->
.ggpopover.in {
z-index: 9999 !important;
}

How to copy files across computers using SSH and MAC OS X Terminal

You can do this with the scp command, which uses the ssh protocol to copy files across machines. It extends the syntax of cp to allow references to other systems:

scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file

Copy something from this machine to some other machine:

scp /path/to/local/file username@hostname:/path/to/remote/file

Copy something from another machine to this machine:

scp username@hostname:/path/to/remote/file /path/to/local/file

Copy with a port number specified:

scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file

How do I completely rename an Xcode project (i.e. inclusive of folders)?

To add to @luke-west 's excellent answer:

When using CocoaPods

After step 2:

  1. Quit XCode.
  2. In the master folder, rename OLD.xcworkspace to NEW.xcworkspace.

After step 4:

  1. In XCode: choose and edit Podfile from the project navigator. You should see a target clause with the OLD name. Change it to NEW.
  2. Quit XCode.
  3. In the project folder, delete the OLD.podspec file.
  4. rm -rf Pods/
  5. Run pod install.
  6. Open XCode.
  7. Click on your project name in the project navigator.
  8. In the main pane, switch to the Build Phases tab.
  9. Under Link Binary With Libraries, look for libPods-OLD.a and delete it.
  10. If you have an objective-c Bridging header go to Build settings and change the location of the header from OLD/OLD-Bridging-Header.h to NEW/NEW-Bridging-Header.h
  11. Clean and run.

Appending a line break to an output file in a shell script

this also works, and prolly is more readable than the echo version:

printf "`date` User `whoami` started the script.\r\n" >> output.log

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

mysql> CREATE USER 'name'@'%' IDENTIFIED BY 'passWord'; Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON . TO 'name'@'%'; Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)

mysql>

  1. Make sure you have your name and % the right way round
  2. Makes sure you have added your port 3306 to any firewall you may be running (although this will give a different error message)

hope this helps someone...

How to add header row to a pandas DataFrame

Alternatively you could read you csv with header=None and then add it with df.columns:

Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]

Android, How can I Convert String to Date?

using SimpleDateFormat or DateFormat class through

for e.g.

try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
    // handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}

How do I get the parent directory in Python?

os.path.split(os.path.abspath(mydir))[0]

How to get Database Name from Connection String using SqlConnectionStringBuilder

A much simpler alternative is to get the information from the connection object itself. For example:

IDbConnection connection = new SqlConnection(connectionString);
var dbName = connection.Database;

Similarly you can get the server name as well from the connection object.

DbConnection connection = new SqlConnection(connectionString);
var server = connection.DataSource;

Can I have an onclick effect in CSS?

How about a pure CSS solution without being (that) hacky?

enter image description here

_x000D_
_x000D_
.page {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  background-color: #121519;_x000D_
  color: whitesmoke;_x000D_
}_x000D_
_x000D_
.controls {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.arrow {_x000D_
  cursor: pointer;_x000D_
  transition: filter 0.3s ease 0.3s;_x000D_
}_x000D_
_x000D_
.arrow:active {_x000D_
  filter: drop-shadow(0 0 0 steelblue);_x000D_
  transition: filter 0s;_x000D_
}
_x000D_
<body class="page">_x000D_
  <div class="controls">_x000D_
    <div class="arrow">_x000D_
      <img src="https://i.imgur.com/JGUoNfS.png" />_x000D_
    </div>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

@TylerH has a great response but its a pretty complex solution. I have a solution for those of you that just want a simple "onclick" effect with pure css without a bunch of extra elements.

We will simply use css transitions. You could probably do similar with animations.

The trick is to change the delay for the transition so that it will last when the user clicks.

.arrowDownContainer:active,
.arrowDownContainer.clicked {
  filter: drop-shadow(0px 0px 0px steelblue);
  transition: filter 0s;
}

Here I add the "clicked" class as well so that javascript can also provide the effect if it needs to. I use 0px drop-shadow filter because it will highlight the given transparent graphic blue this way for my case.

I have a filter at 0s here so that it wont take effect. When the effect is released I can then add the transition with a delay so that it will provide a nice "clicked" effect.

.arrowDownContainer {
  cursor: pointer;
  position: absolute;
  bottom: 0px;
  top: 490px;
  left: 108px;
  height: 222px;
  width: 495px;
  z-index: 3;
  transition: filter 0.3s ease 0.3s;
}

This allows me to set it up so that when the user clicks the button, it highlights blue then fades out slowly (you could, of course, use other effects as well).

While you are limited here in the sense that the animation to highlight is instant, it does still provide the desired effect. You could likely use this trick with animation to produce a smoother overall transition.

enter image description here

enter image description here

Getting execute permission to xp_cmdshell

tchester said :

(2) Create a login for the non-sysadmin user that has public access to the master database

I went to my user's database list (server/security/connections/my user name/properties/user mapping, and wanted to check the box for master database. I got an error message telling that the user already exists in the master database. Went to master database, dropped the user, went back to "user mapping" and checked the box for master. Check the "public" box below.

After that, you need to re-issue the grant execute on xp_cmdshell to "my user name"

Yves

appending list but error 'NoneType' object has no attribute 'append'

I think what you want is this:

last_list=[]
if p.last_name != None and p.last_name != "":
    last_list.append(p.last_name)
print last_list

Your current if statement:

if p.last_name == None or p.last_name == "":
    pass

Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.

Also, it looks like your statement pan_list.append(p.last) is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.

Java: How to insert CLOB into oracle database

The easiest way is to simply use the

stmt.setString(position, xml);

methods (for "small" strings which can be easily kept in Java memory), or

try {
  java.sql.Clob clob = 
    oracle.sql.CLOB.createTemporary(
      connection, false, oracle.sql.CLOB.DURATION_SESSION);

  clob.setString(1, xml);
  stmt.setClob(position, clob);
  stmt.execute();
}

// Important!
finally {
  clob.free();
}

Failed linking file resources

I was having the same issue. It was due to a typo in an attribute in one of my XML file. Anyways, Android Studio did not specify the source of the error in the first run. But when I did a

Build -> Clean Project

and then ran the app again it showed me the exact line in the XML code where the typo was.

Change Toolbar color in Appcompat 21

UPDATE 12/11/2019: Material Components Library

With the Material Components and Androidx libraries you can use:

  • the android:background attribute in the layout:

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
    
  • apply the default style: style="@style/Widget.MaterialComponents.Toolbar.Primary" or customize the style inheriting from it:

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
    
  • override the default color using the android:theme attribute:

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/MyThemeOverlay_Toolbar"
    

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <item name="android:textColorPrimary">....</item>
    <item name="colorPrimary">@color/.....
    <item name="colorOnPrimary">@color/....</item>
  </style>

OLD: Support libraries:
You can use a app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" theme as suggested in other answers, but you can also use a solution like this:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/HeaderBar"
    app:theme="@style/ActionBarThemeOverlay"
    app:popupTheme="@style/ActionBarPopupThemeOverlay"/>

And you can have the full control of your ui elements with these styles:

<style name="ActionBarThemeOverlay" parent="">
    <item name="android:textColorPrimary">#fff</item>
    <item name="colorControlNormal">#fff</item>
    <item name="colorControlHighlight">#3fff</item>
</style>

<style name="HeaderBar">
    <item name="android:background">?colorPrimary</item>
</style>

<style name="ActionBarPopupThemeOverlay" parent="ThemeOverlay.AppCompat.Light" >
    <item name="android:background">@android:color/white</item>
    <item name="android:textColor">#000</item>
</style>

How to extract IP Address in Spring MVC Controller get call?

In my case, I was using Nginx in front of my application with the following configuration:

location / {
     proxy_pass        http://localhost:8080/;
     proxy_set_header  X-Real-IP $remote_addr;
     proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header  Host $http_host;
     add_header Content-Security-Policy 'upgrade-insecure-requests';
}

so in my application I get the real user ip like so:

String clientIP = request.getHeader("X-Real-IP");

How to add icon to mat-icon-button

My preference is to utilize the inline attribute. This will cause the icon to correctly scale with the size of the button.

    <button mat-button>
      <mat-icon inline=true>local_movies</mat-icon>
      Movies
    </button>

    <!-- Link button -->
    <a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>

I add this to my styles.css to:

  • solve the vertical alignment problem of the icon inside the button
  • material icon fonts are always a little too small compared to button text
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
  vertical-align: top;
  font-size: 1.25em;
}

What does the ">" (greater-than sign) CSS selector mean?

All p tags with class some_class which are direct children of a div tag.

How to split data into 3 sets (train, validation and test)?

In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output). You just have to pay attention to shuffle X and y the same way before splitting.

Here, either X and y are in the same dataframe, so we shuffle them, separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.

# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]

# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]

# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

Check if a string matches a regex in Bash script

Where the usage of a regex can be helpful to determine if the character sequence of a date is correct, it cannot be used easily to determine if the date is valid. The following examples will pass the regular expression, but are all invalid dates: 20180231, 20190229, 20190431

So if you want to validate if your date string (let's call it datestr) is in the correct format, it is best to parse it with date and ask date to convert the string to the correct format. If both strings are identical, you have a valid format and valid date.

if [[ "$datestr" == $(date -d "$datestr" "+%Y%m%d" 2>/dev/null) ]]; then
     echo "Valid date"
else
     echo "Invalid date"
fi

OPTION (RECOMPILE) is Always Faster; Why?

Necroing this question but there's an explanation that no-one seems to have considered.

STATISTICS - Statistics are not available or misleading

If all of the following are true:

  1. The columns feedid and feedDate are likely to be highly correlated (e.g. a feed id is more specific than a feed date and the date parameter is redundant information).
  2. There is no index with both columns as sequential columns.
  3. There are no manually created statistics covering both these columns.

Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.

Using variables inside a bash heredoc

As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.

Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE

Demo: https://ideone.com/rMF2XA

Note that any of the quoting mechanisms -- \____HERE or "____HERE" or '____HERE' -- will disable all variable interpolation, and turn the here-document into a piece of literal text.

A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.

local=$(uname)
ssh -t remote <<:
    echo "$local is the value from the host which ran the ssh command"
    # Prevent here doc from expanding locally; remote won't see backslash
    remote=\$(uname)
    # Same here
    echo "\$remote is the value from the host we ssh:ed to"
:

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

how to use python2.7 pip instead of default pip

An alternative is to call the pip module by using python2.7, as below:

python2.7 -m pip <commands>

For example, you could run python2.7 -m pip install <package> to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.

In case the pip module has not yet been installed for this version of python, you can run the following:

python2.7 -m ensurepip

Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.

Highlighting Text Color using Html.fromHtml() in Android?

Or far simpler than dealing with Spannables manually, since you didn't say that you want the background highlighted, just the text:

String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);

Converting BitmapImage to Bitmap and vice versa

Here's an extension method for converting a Bitmap to BitmapImage.

    public static BitmapImage ToBitmapImage(this Bitmap bitmap)
    {
        using (var memory = new MemoryStream())
        {
            bitmap.Save(memory, ImageFormat.Png);
            memory.Position = 0;

            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
            bitmapImage.Freeze();

            return bitmapImage;
        }
    }

Align DIV's to bottom or baseline

Use the CSS display values of table and table-cell:

HTML

<html>
<body>

  <div class="valign bottom">
    <div>

      <div>my bottom aligned div 1</div>
      <div>my bottom aligned div 2</div>
      <div>my bottom aligned div 3</div>

    </div>
  </div>

</body>
</html>

CSS

html,body {
    width: 100%;
    height: 100%;
}
.valign {
    display: table;
    width: 100%;
    height: 100%;
}
.valign > div {
    display: table-cell;
    width: 100%;
    height: 100%;
}
.valign.bottom > div {
    vertical-align: bottom;
}

I've created a JSBin demo here: http://jsbin.com/INOnAkuF/2/edit

The demo also has an example how to vertically center align using the same technique.

How to execute VBA Access module?

You're not running a module -- you're running subroutines/functions that happen to be stored in modules.

If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).

Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:

  SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
  FROM MyTable;

That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.

Subroutines (i.e., code that returns no value) are not callable from within SQL statements.

How do I create a multiline Python string with inline variables?

The common way is the format() function:

>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'

It works fine with a multi-line format string:

>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.

You can also pass a dictionary with variables:

>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'

The closest thing to what you asked (in terms of syntax) are template strings. For example:

>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'

I should add though that the format() function is more common because it's readily available and it does not require an import line.

jQuery, get ID of each element in a class using .each?

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){
  return n.id;
});
alert(arrayOfIds);

Is there a way to instantiate a class by name in Java?

Two ways:

Method 1 - only for classes having a no-arg constructor

If your class has a no-arg constructor, you can get a Class object using Class.forName() and use the newInstance() method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).

For example:

Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.newInstance();

Method 2

An alternative safer approach which also works if the class doesn't have any no-arg constructors is to query your class object to get its Constructor object and call a newInstance() method on this object:

Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);

Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:

  • the JVM can't find or can't load your class
  • the class you're trying to instantiate doesn't have the right sort of constructors
  • the constructor itself threw an exception
  • the constructor you're trying to invoke isn't public
  • a security manager has been installed and is preventing reflection from occurring

Error in <my code> : object of type 'closure' is not subsettable

You don't define the vector, url, before trying to subset it. url is also a function in the base package, so url[i] is attempting to subset that function... which doesn't make sense.

You probably defined url in your prior R session, but forgot to copy that code to your script.

Can I use library that used android support with Androidx projects.

I had a problem like this before, it was the gradle.properties file doesn't exist, only the gradle.properties.txt , so i went to my project folder and i copied & pasted the gradle.properties.txt file but without .txt extension then it finally worked.

What is the worst programming language you ever worked with?

The worse language I've ever seen come from the tool praat, which is a good audio analysis tool. It does a pretty good job until you use the script language. sigh bad memories.

Tiny praat script tutorial for beginners

  • Function call

    We've listed at least 3 different function calling syntax :
    • The regular one

      string = selected("Strings")

      Nothing special here, you assign to the variable string the result of the selected function. Not really scary... yet.

    • The "I'm invoking some GUI command with parameters"

      Create Strings as file list... liste 'path$'/'type$'

      As you can see, the function name start at "Create" and finish with the "...". The command "Create Strings as file list" is the text displayed on a button or a menu (I'm to scared to check) on praat. This command take 2 parameters liste and an expression. I'm going to look deeper in the expression 'path$'/'type$'

      Hmm. Yep. No spaces. If spaces were introduced, it would be separate arguments. As you can imagine, parenthesis don't work. At this point of the description I would like to point out the suffix of the variable names. I won't develop it in this paragraph, I'm just teasing.

    • The "Oh, but I want to get the result of the GUI command in my variable"

      noliftt = Get number of strings
      Yes we can see a pattern here, long and weird function name, it must be a GUI calling. But there's no '...' so no parameters. I don't want to see what the parser looks like.
  • The incredible type system

    (AKA Haskell and OCaml, praat is coming to you)
    • Simple natives types

      windowname$ = left$(line$,length(line$)-4)

      So, what's going on there? It's now time to look at the convention and types of expression, so here we got :

      • left$ :: (String, Int) -> String
      • lenght :: (String) -> Int
      • windowname$ :: String
      • line$ :: String
      As you can see, variable name and function names are suffixed with their type or return type. If their suffix is a '$', then it return a string or is a string. If there is nothing it's a number. I can see the point of prefixing the type to a variable to ease implementation, but to suffix, no sorry, I can't

    • Array type

      To show the array type, let me introduce a 'tiny' loop :
      
          for i from 1 to 4
              Select... time time
              bandwidth'i'$ = Get bandwidth... i
              forhertz'i'$ = Get formant... i
          endfor
          

      We got i which is a number and... (no it's not a function)
      bandwidth'i'$
      What it does is create string variables : bandwidth1$, bandwidth2$, bandwidth3$, bandwidth4$ and give them values. As you can expect, you can't create two dimensional array this way, you must do something like that : band2D__'i'__'j'$

      http://img214.imageshack.us/img214/3008/scaredkittylolqa2.jpg
    • The special string invocation

      outline$ = "'time'@F'i':'forhertznum'Hz,'bandnum'Hz, 'spec''newline$'" outline$ >> 'outfile$'

      Strings are weirdly (at least) handled in the language. the '' is used to call the value of a variable inside the global "" string. This is weird. It goes against all the convention built into many languages from bash to PHP passing by the powershell. And look, it even got redirection. Don't be fooled, it doesn't work like in your beloved shell. No you have to get the variable value with the ''

    • Da Wonderderderfulful execution model

      I'm going to put the final touch to this wonderderderfulful presentation by talking to you about the execution model. So as in every procedural languages you got instruction executed from top to bottom, there is the variables and the praat GUI. That is you code everything on the praat gui, you invoke commands written on menu/buttons.

      The main window of praat contain a list of items which can be :

      • files
      • list of files (created by a function with a wonderderfulful long long name)
      • Spectrogramm
      • Strings (don't ask)
      So if you want to perform operation on a given file, you must select the file in the list programmatically and then push the different buttons to take some actions. If you wanted to pass parameters to a GUI action, you have to follow the GUI layout of the form for your arguments, for example "To Spectrogram... 0.005 5000 0.002 20 Gaussian " is like that because it follows this layout:

      http://img7.imageshack.us/img7/5534/tospectrogramm.png

    Needless to say, my nightmares are filled with praat scripts dancing around me and shouting "DEBUG MEEEE!!".

    More information at the praat site, under the well-named section "easy programmable scripting language"

  • align images side by side in html

    In your CSS:

    .image123{
    float:left;
    }
    

    Another Repeated column in mapping for entity error

    The message is clear: you have a repeated column in the mapping. That means you mapped the same database column twice. And indeed, you have:

    @Column(nullable=false)
    private Long customerId;
    

    and also:

    @ManyToOne(optional=false)
    @JoinColumn(name="customerId",referencedColumnName="id_customer")
    private Customer customer;
    

    (and the same goes for productId/product).

    You shouldn't reference other entities by their ID, but by a direct reference to the entity. Remove the customerId field, it's useless. And do the same for productId. If you want the customer ID of a sale, you just need to do this:

    sale.getCustomer().getId()