Programs & Examples On #Railo

Railo is an Open Source (LGPL) rapid application development platform implementing the general-purpose CFML language, compatible with Adobe ColdFusion's implementation but with various extensions/updates. Don't forget to also use the `cfml` tag for any Railo questions involving the CFML language or any general CFML concepts.

Open text file and program shortcut in a Windows batch file

I was able to figure out the solution:

start notepad "myfile.txt"
"myshortcut.lnk"
exit

Vue js error: Component template should contain exactly one root element

For a more complete answer: http://www.compulsivecoders.com/tech/vuejs-component-template-should-contain-exactly-one-root-element/

But basically:

  • Currently, a VueJS template can contain only one root element (because of rendering issue)
  • In cases you really need to have two root elements because HTML structure does not allow you to create a wrapping parent element, you can use vue-fragment.

To install it:

npm install vue-fragment

To use it:

import Fragment from 'vue-fragment';
Vue.use(Fragment.Plugin);

// or

import { Plugin } from 'vue-fragment';
Vue.use(Plugin);

Then, in your component:

<template>
  <fragment>
    <tr class="hola">
      ...
    </tr>
    <tr class="hello">
      ...
    </tr>
  </fragment>
</template>

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

The functionality, you described, can be easily achieved using the Bootstrap tooltip.

<button id="example1" data-toggle="tooltip">Tooltip on left</button>

Then call tooltip() function for the element.

$('#example1').tooltip();

http://getbootstrap.com/javascript/#tooltips

click() event is calling twice in jquery

This is definitely a bug specially while it's FireFox. I searched alot tried all the above answers and finally got it as bug by many experts over SO. So, I finally came up with this idea by declaring variable like

var called = false;
$("#ColorPalete li").click(function() {
    if(!called)
    {
             called = true;
             setTimeout(function(){ //<-----This can be an ajax request but keep in mind to set called=false when you get response or when the function has successfully executed.
                 alert('I am called');
                 called = false;
             },3000);

    }
});

In this way it first checks rather the function was previously called or not.

Play local (hard-drive) video file with HTML5 video tag?

It is possible to play a local video file.

<input type="file" accept="video/*"/>
<video controls autoplay></video>

When a file is selected via the input element:

  1. 'change' event is fired
  2. Get the first File object from the input.files FileList
  3. Make an object URL that points to the File object
  4. Set the object URL to the video.src property
  5. Lean back and watch :)

http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/

_x000D_
_x000D_
(function localFileVideoPlayer() {_x000D_
  'use strict'_x000D_
  var URL = window.URL || window.webkitURL_x000D_
  var displayMessage = function(message, isError) {_x000D_
    var element = document.querySelector('#message')_x000D_
    element.innerHTML = message_x000D_
    element.className = isError ? 'error' : 'info'_x000D_
  }_x000D_
  var playSelectedFile = function(event) {_x000D_
    var file = this.files[0]_x000D_
    var type = file.type_x000D_
    var videoNode = document.querySelector('video')_x000D_
    var canPlay = videoNode.canPlayType(type)_x000D_
    if (canPlay === '') canPlay = 'no'_x000D_
    var message = 'Can play type "' + type + '": ' + canPlay_x000D_
    var isError = canPlay === 'no'_x000D_
    displayMessage(message, isError)_x000D_
_x000D_
    if (isError) {_x000D_
      return_x000D_
    }_x000D_
_x000D_
    var fileURL = URL.createObjectURL(file)_x000D_
    videoNode.src = fileURL_x000D_
  }_x000D_
  var inputNode = document.querySelector('input')_x000D_
  inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
  background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
_x000D_
_x000D_

why $(window).load() is not working in jQuery?

I have to write a whole answer separately since it's hard to add a comment so long to the second answer.

I'm sorry to say this, but the second answer above doesn't work right.

The following three scenarios will show my point:

Scenario 1: Before the following way was deprecated,

  $(window).load(function () {
     alert("Window Loaded.");
  });

if we execute the following two queries:

<script>
   $(window).load(function () {
     alert("Window Loaded.");
   }); 

   $(document).ready(function() {
     alert("Dom Loaded.");
   });
</script>,

the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the way it should be.

Scenario 2: But if we execute the following two queries like the second answer above suggests:

<script>
   $(window).ready(function () {
     alert("Window Loaded.");
   }); 

   $(document).ready(function() {
     alert("Dom Loaded.");
   });
</script>,

the alert (Window Loaded.) from the first query will show first, and the one (Dom Loaded.) from the second query will show later, which is NOT right.

Scenario 3: On the other hand, if we execute the following two queries, we'll get the correct result:

<script>
   $(window).on("load", function () {
     alert("Window Loaded.");
   }); 

   $(document).ready(function() {
     alert("Dom Loaded.");
   });
</script>,

that is to say, the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the RIGHT result.

In short, the FIRST answer is the CORRECT one:

$(window).on('load', function () {
  alert("Window Loaded.");
});

Remove gutter space for a specific div only

To add to Skelly's Bootstrap 3 no-gutter answer above (https://stackoverflow.com/a/21282059/662883)

Add the following to prevent gutters on a row containing only one column (useful when using column-wrapping: http://getbootstrap.com/css/#grid-example-wrapping):

.row.no-gutter [class*='col-']:only-child,
.row.no-gutter [class*='col-']:only-child
{
    padding-right: 0;
    padding-left: 0;
}

Press TAB and then ENTER key in Selenium WebDriver

WebElement webElement = driver.findElement(By.xpath(""));

//Enter the xpath or ID.

     webElement.sendKeys("");

//Input the string to pass.

     webElement.sendKeys(Keys.TAB);

//This will enter the string which you want to pass and will press "Tab" button .

What are App Domains in Facebook Apps?

In this example:

http://www.example.com:80/somepage?parameter1="hello"&parameter2="world"

the bold part is the Domainname. 80 is rarely included. I post it since many people may wonder if 3000 or some other port is part of the domain if their not staging their app for production yet. Normally you don't specify it since 80 is the default, but if you just want to specify localhost just do it without the port number, it works just as fine. The adress, though, should be http://localhost:3000 (if you have it on that port).

Insert/Update/Delete with function in SQL Server

Functions are not meant to be used that way, if you wish to perform data change you can just create a Stored Proc for that.

Create a folder inside documents folder in iOS apps

I do that the following way:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

How to integrate sourcetree for gitlab

Sourcetree 3.x has an option to accept gitLab. See here. I now use Sourcetree 3.0.15. In Settings, put your remote gitLab host and url, etc. If your existing git client version is not supported any more, the easiest way is perhaps to use Sourcetree embedded Git by Tools->Options->Git, in Git Version near the bottom, choose Embedded. A download may happen.

equals vs Arrays.equals in Java

The equals() of arrays is inherited from Object, so it does not look at the contents of the arrrays, it only considers each array equal to itself.

The Arrays.equals() methods do compare the arrays' contents. There's overloads for all primitive types, and the one for objects uses the objects' own equals() methods.

Angular 2 Show and Hide an element

You should use the *ngIf Directive

<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>


export class AppComponent implements OnInit{

  (...)
  public edited = false;
  (...)
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);
  }
}

Update: you are missing the reference to the outer scope when you are inside the Timeout callback.

so add the .bind(this) like I added Above

Q : edited is a global variable. What would be your approach within a *ngFor-loop? – Blauhirn

A : I would add edit as a property to the object I am iterating over.

<div *ngFor="let obj of listOfObjects" *ngIf="obj.edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>


export class AppComponent implements OnInit{
   
  public listOfObjects = [
    {
       name : 'obj - 1',
       edit : false
    },
    {
       name : 'obj - 2',
       edit : false
    },
    {
       name : 'obj - 2',
       edit : false
    } 
  ];
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);
  }
}

Make body have 100% of the browser height

If you want to keep the margins on the body and don't want scroll bars, use the following css:

html { height:100%; }
body { position:absolute; top:0; bottom:0; right:0; left:0; }

Setting body {min-height:100%} will give you scroll bars.

See demo at http://jsbin.com/aCaDahEK/2/edit?html,output .

How to highlight cell if value duplicate in same column for google spreadsheet?

Answer of @zolley is right. Just adding a Gif and steps for the reference.

  1. Goto menu Format > Conditional formatting..
  2. Find Format cells if..
  3. Add =countif(A:A,A1)>1 in field Custom formula is
    • Note: Change the letter A with your own column.

enter image description here

Android Percentage Layout Height

With introduction of ContraintLayout, it's possible to implement with Guidelines:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.eugene.test1.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#AAA"
        android:text="TextView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/guideline" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

</android.support.constraint.ConstraintLayout>

Result View

You can read more in this article Building interfaces with ConstraintLayout.

Amazon S3 boto - how to create a folder?

Although you can create a folder by appending "/" to your folder_name. Under the hood, S3 maintains flat structure unlike your regular NFS.

var params = {
            Bucket : bucketName,
            Key : folderName + "/"
        };
s3.putObject(params, function (err, data) {});

Nullable property to entity field, Entity Framework through Code First

Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }

// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }

LINQ: Distinct values

Are you trying to be distinct by more than one field? If so, just use an anonymous type and the Distinct operator and it should be okay:

var query = doc.Elements("whatever")
               .Select(element => new {
                             id = (int) element.Attribute("id"),
                             category = (int) element.Attribute("cat") })
               .Distinct();

If you're trying to get a distinct set of values of a "larger" type, but only looking at some subset of properties for the distinctness aspect, you probably want DistinctBy as implemented in MoreLINQ in DistinctBy.cs:

 public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
     this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     IEqualityComparer<TKey> comparer)
 {
     HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
     foreach (TSource element in source)
     {
         if (knownKeys.Add(keySelector(element)))
         {
             yield return element;
         }
     }
 }

(If you pass in null as the comparer, it will use the default comparer for the key type.)

virtualenvwrapper and Python 3

On Ubuntu; using mkvirtualenv -p python3 env_name loads the virtualenv with python3.

Inside the env, use python --version to verify.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

Looks like you're trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!

In the child pom, use something like this:

<modelVersion>4.0.0</modelVersion>

<parent>
  <groupId>org.felipe</groupId>
  <artifactId>tutorial_maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <relativePath>../pom.xml</relativePath>
</parent>

<artifactId>tutorial_maven_jar</artifactId>

Using properties like ${project.groupId} won't work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.

typescript - cloning object

For a simple clone of the hole object's content, I simply stringify and parse the instance :

let cloneObject = JSON.parse(JSON.stringify(objectToClone))

Whereas I change data in objectToClone tree, there is no change in cloneObject. That was my requierement.

Hope it help

Passing data between different controller action methods

I prefer to use this instead of TempData

public class Home1Controller : Controller 
{
    [HttpPost]
    public ActionResult CheckBox(string date)
    {
        return RedirectToAction("ActionName", "Home2", new { Date =date });
    }
}

and another controller Action is

public class Home2Controller : Controller 
{
    [HttpPost]
    Public ActionResult ActionName(string Date)
    {
       // do whatever with Date
       return View();
    }
}

it is too late but i hope to be helpful for any one in the future

Disabled UIButton not faded or grey

Set title color for different states:

@IBOutlet weak var loginButton: UIButton! {
        didSet {
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 0.3), for: .disabled)
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 1), for: .normal)
        }
    }

Usage: (text color will get change automatically)

loginButton.isEnabled = false

enter image description here

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

How to call servlet through a JSP page

You could use <jsp:include> for this.

<jsp:include page="/servletURL" />

It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. Create a Servlet which does something like following in doGet() method.

request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);

and in /WEB-INF/result.jsp

<p>The result is ${result}</p>

Now call the Servlet by the URL which matches its <url-pattern> in web.xml, e.g. http://example.com/contextname/servletURL.

Do note that the JSP file is explicitly placed in /WEB-INF folder. This will prevent the user from opening the JSP file individually. The user can only call the servlet in order to open the JSP file.


If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form action.

<form action="servletURL" method="post">

Its doPost() method will then be called.


See also:

Centering brand logo in Bootstrap Navbar

Try this:

.navbar {
    position: relative;
}
.brand {
    position: absolute;
    left: 50%;
    margin-left: -50px !important;  /* 50% of your logo width */
    display: block;
}

Centering your logo by 50% and minus half of your logo width so that it won't have problem when zooming in and out.

See fiddle

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Setting the height of a SELECT in IE

Even though setting a CSS height value to the select element does not work, the padding attribute works alright. Setting a top and bottom padding will make your select element look taller.

call a function in success of datatable ajax call

Try Following Code.

       var oTable = $('#app-config').dataTable(
        {
            "bAutoWidth": false,                                                
            "bDestroy":true,
            "bProcessing" : true,
            "bServerSide" : true,
            "sPaginationType" : "full_numbers",
            "sAjaxSource" : url,                    
            "fnServerData" : function(sSource, aoData, fnCallback) {
                alert("sSource"+ sSource);
                alert("aoData"+ aoData);
                $.ajax({
                    "dataType" : 'json',
                    "type" : "GET",
                    "url" : sSource,
                    "data" : aoData,
                    "success" : fnCallback
                }).success( function(){  alert("This Function will execute after data table loaded");   });
            }

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

You can configure property inclusion, and numerous other settings, via application.properties:

spring.jackson.default-property-inclusion=non_null

There's a table in the documentation that lists all of the properties that can be used.

If you want more control, you can also customize Spring Boot's configuration programatically using a Jackson2ObjectMapperBuilderCustomizer bean, as described in the documentation:

The context’s Jackson2ObjectMapperBuilder can be customized by one or more Jackson2ObjectMapperBuilderCustomizer beans. Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.

Lastly, if you don't want any of Boot's configuration and want to take complete control over how the ObjectMapper is configured, declare your own Jackson2ObjectMapperBuilder bean:

@Bean
Jackson2ObjectMapperBuilder objectMapperBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    // Configure the builder to suit your needs
    return builder;
}

Count table rows

$sql="SELECT count(*) as toplam FROM wp_postmeta WHERE meta_key='ICERIK' AND post_id=".$id;
$total = 0;
$sqls = mysql_query($sql,$conn);
if ( $sqls ) {
    $total = mysql_result($sqls, 0);
};
echo "Total:".$total;`

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

NoClassDefFoundError for code in an Java library on Android

The NoClassDefFoundError description is, from the SO tag:

The Java Error thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Or better:

NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.

from this page. Check it, there are some ways to solve the error. I hope it helps.

Are there constants in JavaScript?

Yet there is no exact cross browser predefined way to do it , you can achieve it by controlling the scope of variables as showed on other answers.

But i will suggest to use name space to distinguish from other variables. this will reduce the chance of collision to minimum from other variables.

Proper namespacing like

var iw_constant={
     name:'sudhanshu',
     age:'23'
     //all varibale come like this
}

so while using it will be iw_constant.name or iw_constant.age

You can also block adding any new key or changing any key inside iw_constant using Object.freeze method. However its not supported on legacy browser.

ex:

Object.freeze(iw_constant);

For older browser you can use polyfill for freeze method.


If you are ok with calling function following is best cross browser way to define constant. Scoping your object within a self executing function and returning a get function for your constants ex:

var iw_constant= (function(){
       var allConstant={
             name:'sudhanshu',
             age:'23'
             //all varibale come like this

       };

       return function(key){
          allConstant[key];
       }
    };

//to get the value use iw_constant('name') or iw_constant('age')


** In both example you have to be very careful on name spacing so that your object or function shouldn't be replaced through other library.(If object or function itself wil be replaced your whole constant will go)

Tab separated values in awk

Should this not work?

echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk '{print $1}'

Select a date from date picker using Selenium webdriver

Just do

  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("document.getElementById('id').value='1988-01-01'");

SQL split values to multiple rows

Best Practice. Result:

SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX('ab,bc,cd',',',help_id+1),',',-1) AS oid
FROM
(
SELECT @xi:=@xi+1 as help_id from 
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc1,
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc2,
(SELECT @xi:=-1) xc0
) a
WHERE 
help_id < LENGTH('ab,bc,cd')-LENGTH(REPLACE('ab,bc,cd',',',''))+1

First, create a numbers table:

SELECT @xi:=@xi+1 as help_id from 
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc1,
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc2,
(SELECT @xi:=-1) xc0;
| help_id  |
| --- |
| 0   |
| 1   |
| 2   |
| 3   |
| ...   |
| 24   |

Second, just split the str:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('ab,bc,cd',',',help_id+1),',',-1) AS oid
FROM
numbers_table
WHERE
help_id < LENGTH('ab,bc,cd')-LENGTH(REPLACE('ab,bc,cd',',',''))+1
| oid  |
| --- |
| ab   |
| bc   |
| cd   |

Javascript, viewing [object HTMLInputElement]

<input type="text" />
<script>
$("input:text").change(function() {
    var value=$("input:text").val();
    alert(value);
});
</script>

use .val() to get value of the element (jquery method), $("input:text") this selector to select your input, .change() to bind an event handler to the "change" JavaScript event.

Javascript Append Child AFTER Element

You need to append the new element to existing element's parent before element's next sibling. Like:

var parentGuest = document.getElementById("one");
var childGuest = document.createElement("li");
childGuest.id = "two";
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);

Or if you want just append it, then:

var parentGuest = document.getElementById("one"); 
var childGuest = document.createElement("li"); 
childGuest.id = "two"; 
parentGuest.parentNode.appendChild(childGuest);

linux script to kill java process

If you just want to kill any/all java processes, then all you need is;

killall java

If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;

PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID

Should do it, there is probably an easier way though...

Show a div with Fancybox

padde's solution is right, but risen up another problem i.e.

As said by Adam (the questioner) that it is showing empty popup. Here is the complete and working solution

<html>
<head>
    <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.0.5"></script>
    <link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.0.5" media="screen" />
</head>
<body>

<a href="#divForm" id="btnForm">Load Form</a>

<div id="divForm" style="display:none">
    <form action="tbd">
        File: <input type="file" /><br /><br />
        <input type="submit" />
    </form>
</div>

<script type="text/javascript">
$(function() {
    $("#btnForm").fancybox({
        'onStart': function() { $("#divForm").css("display","block"); },            
        'onClosed': function() { $("#divForm").css("display","none"); }
    });
});
</script>

</body>
</html>

INNER JOIN in UPDATE sql for DB2

In standard SQL this type of update looks like:

update a
   set a.firstfield ='BIT OF TEXT' + b.something
  from file1 a
  join file2 b
    on substr(a.firstfield,10,20) = 
       substr(b.anotherfield,1,10)
 where a.firstfield like 'BLAH%' 

With minor syntactic variations this type of thing will work on Oracle or SQL Server and (although I don't have a DB/2 instance to hand to test) will almost certainly work on DB/2.

Regex allow digits and a single dot

If you want to allow 1 and 1.2:

(?<=^| )\d+(\.\d+)?(?=$| )

If you want to allow 1, 1.2 and .1:

(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )

If you want to only allow 1.2 (only floats):

(?<=^| )\d+\.\d+(?=$| )

\d allows digits (while \D allows anything but digits).

(?<=^| ) checks that the number is preceded by either a space or the beginning of the string. (?=$| ) makes sure the string is followed by a space or the end of the string. This makes sure the number isn't part of another number or in the middle of words or anything.

Edit: added more options, improved the regexes by adding lookahead- and behinds for making sure the numbers are standalone (i.e. aren't in the middle of words or other numbers.

Difference between decimal, float and double in .NET?

  1. Double and float can be divided by integer zero without an exception at both compilation and run time.
  2. Decimal cannot be divided by integer zero. Compilation will always fail if you do that.

How do I create a file AND any folders, if the folders don't exist?

To summarize what has been commented in other answers:

//path = @"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));

Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.

If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

SQL subquery with COUNT help

SELECT e.*,
       cnt.colCount 
FROM eventsTable e
INNER JOIN (
           select columnName,count(columnName) as colCount
           from eventsTable e2 
          group by columnName
           ) as cnt on cnt.columnName = e.columnName
WHERE e.columnName='Business'

-- Added space

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

View>Tool Windows>Run

It will show you the console

How to Consolidate Data from Multiple Excel Columns All into One Column

Here is how you do it with some simple Excel formulae, and no fancy VBA needed. The trick is to use the OFFSET formula. Please see this example spreadsheet:

https://docs.google.com/spreadsheet/ccc?key=0AuSyDFZlcRtHdGJOSnFwREotRzFfM28tWElpZ1FaR2c&usp=sharing#gid=0

Automatically deleting related rows in Laravel (Eloquent ORM)

I would iterate through the collection detaching everything before deleting the object itself.

here's an example:

try {
        $user = User::findOrFail($id);
        if ($user->has('photos')) {
            foreach ($user->photos as $photo) {

                $user->photos()->detach($photo);
            }
        }
        $user->delete();
        return 'User deleted';
    } catch (Exception $e) {
        dd($e);
    }

I know it is not automatic but it is very simple.

Another simple approach would be to provide the model with a method. Like this:

public function detach(){
       try {
            
            if ($this->has('photos')) {
                foreach ($this->photos as $photo) {
    
                    $this->photos()->detach($photo);
                }
            }
           
        } catch (Exception $e) {
            dd($e);
        }
}

Then you can simply call this where you need:

$user->detach();
$user->delete();

How to return a complex JSON response with Node.js?

I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:

query.exec(function (err, results){
  if (err) res.writeHead(500, err.message)
  else if (!results.length) res.writeHead(404);
  else {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
  }
  res.end();
});

How do I set up CLion to compile and run?

I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.

The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.

SHORT ANSWER (should be similar for MinGW too but I haven't tried it):

  1. Install Cygwin with GCC, G++, GDB and CMake (the required versions)
  2. Add full path to Cygwin 'bin' directory to Windows Environment variables
  3. Restart CLion and check 'Settings' -> 'Build, Execution, Deployment' to make sure CLion has picked up the right versions of Cygwin, make and gdb
  4. Check the project configuration ('Run' -> 'Edit configuration') to make sure your project name appears there and you can select options in 'Target', 'Configuration' and 'Executable' fields.
  5. Build and then Run
  6. Enjoy

LONG ANSWER:

Below are the detailed steps that solved this issue for me:

  1. Uninstall/delete the previous version of Cygwin (MinGW in your case)

  2. Make sure that CLion is up-to-date

  3. Run Cygwin setup (x64 for my 64-bit OS)

  4. Install at least the following packages for Cygwin: gcc g++ make Cmake gdb Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).

  5. Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows

[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']

  1. Add the 'bin' folder to the Path variable. For Cygwin, I added: D:\cygwin64\bin

  2. Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings

  3. Select 'Build, Execution, Deployment' and then click on 'Toolchains'

  4. Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)

  5. For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)

  6. 'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]

  7. Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'

See screenshot: Check all paths to the compiler, make and gdb

  1. Now go to 'Run' -> 'Edit configuration'. You should see your project name in the left-side panel and the configurations on the right side

See screenshot: Check the configuration to run the project

  1. There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active

  2. Build your project and then run the project. You should see the output in the terminal window

Hope this helps! Good luck and enjoy CLion.

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

fastest MD5 Implementation in JavaScript

I wrote tests to compare several JavaScript hash implementations, including most MD5 implementations mentioned here. To run the tests, go to http://brillout.github.io/test-javascript-hash-implementations/ and wait a bit.

It seems that the YaMD5 implementation of R. Hill's answer is the fastest.

Laravel 5 PDOException Could Not Find Driver

You should install PDO on your server. Edit your php.ini (look at your phpinfo(), "Loaded Configuration File" line, to find the php.ini file path). Find and uncomment the following line (remove the ; character):

;extension=pdo_mysql.so

Then, restart your Apache server. For more information, please read the documentation.

How to add 10 days to current time in Rails

This definitely works and I use this wherever I need to add days to the current date:

Date.today + 5

How to send json data in the Http request using NSURLRequest

Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):

NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
  [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

NSString *jsonRequest = [jsonDict JSONRepresentation];

NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
 receivedData = [[NSMutableData data] retain];
}

The receivedData is then handled by:

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];

This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made. Hope that helps.

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

I was getting the same error after granting remote access until I made this:

From /etc/mysql/my.cnf

In newer versions of mysql the location of the file is /etc/mysql/mysql.conf.d/mysqld.cnf

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address           = 127.0.0.1

(comment this line: bind-address = 127.0.0.1)

Then run service mysql restart.

If statement in select (ORACLE)

So simple you can use case statement here.

CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 
         CASE WHEN  ISSUE_DIVISION is null then "Null Value found" //give your option
         Else 1 End
ELSE 0 END As Issue_Division_Result

RadioGroup: How to check programmatically

Also you can use getChildAt() method. Like this:

mOption = (RadioGroup) findViewById(R.id.option);
((RadioButton)mOption.getChildAt(0)).setChecked(true);

Replace String in all files in Eclipse

Use Ctrl+H for opening Eclipse search dialog, select appropriate search tab and select "Replace..." to get you to the "Search and replace" dialog

How to customise file type to syntax associations in Sublime Text?

I've found the answer (by further examining the Sublime 2 config files structure):

I was to open

~/.config/sublime-text-2/Packages/Scala/Scala.tmLanguage

And edit it to add sbt (the extension of files I want to be opened as Scala code files) to the array after the fileTypes key:

<dict>
  <key>bundleUUID</key>
  <string>452017E8-0065-49EF-AB9D-7849B27D9367</string>
  <key>fileTypes</key>
  <array>
    <string>scala</string>
    <string>sbt</string>
  <array>
  ...

PS: May there be a better way, something like a right place to put my customizations (insted of modifying packages themselves), I'd still like to know.

Maven: repository element was not specified in the POM inside distributionManagement?

For me, this was something as simple as a missing version for my artifact - "1.1-SNAPSHOT"

How to install Java SDK on CentOS?

enter image description here

This is what I did:

  1. First, I downloaded the .tar file for Java JDK and JRE from the Oracle site.

  2. Extract the .tar file into the opt folder.

  3. I faced an issue that despite setting my environment variables, JAVA_HOME and PATH for Java 9, it was still showing Java 8 as my runtime environment. Hence, I symlinked from the Java 9.0.4 directory to /user/bin using the ln command.

  4. I used java -version command to check which version of java is currently set as my default java runtime environment.

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

How is using OnClickListener interface different via XML and Java code?

These are exactly the same. android:onClick was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener on the Button, which calls your DoIt method.

Here is what using a android:onClick="DoIt" does internally:

Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DoIt(v);
    }
});

The only thing you trade off by using android:onClick, as usual with XML configuration, is that it becomes a bit more difficult to add dynamic content (programatically, you could decide to add one listener or another depending on your variables). But this is easily defeated by adding your test within the DoIt method.

How to get the full path of running process?

I guess you already have the process object of the running process (e.g. by GetProcessesByName()). You can then get the executable file name by using

Process p;
string filename = p.MainModule.FileName;

Getting individual colors from a color map in matplotlib

In order to get rgba integer value instead of float value, we can do

rgba = cmap(0.5,bytes=True)

So to simplify the code based on answer from Ffisegydd, the code would be like this:

#import colormap
from matplotlib import cm

#normalize item number values to colormap
norm = matplotlib.colors.Normalize(vmin=0, vmax=1000)

#colormap possible values = viridis, jet, spectral
rgba_color = cm.jet(norm(400),bytes=True) 

#400 is one of value between 0 and 1000

Collapsing Sidebar with Bootstrap

Via Angular: using ng-class of Angular, we can hide and show the side bar.

http://jsfiddle.net/DVE4f/359/

<div class="container" style="width:100%" ng-app ng-controller="AppCtrl">
<div class="row">
    <div ng-class="showgraphSidebar ? 'col-xs-3' : 'hidden'" id="colPush" >
        Sidebar
    </div>
    <div ng-class="showgraphSidebar ? 'col-xs-9' : 'col-xs-12'"  id="colMain"  >
        <button  ng-click='toggle()' >Sidebar Toggle</a>
    </div>    
  </div>
</div>

.

function AppCtrl($scope) {
    $scope.showgraphSidebar = false;
    $scope.toggle = function() {
        $scope.showgraphSidebar = !$scope.showgraphSidebar;
    }
}

How to get a reversed list view on a list in Java?

You can also invert the position when you request an object:

Object obj = list.get(list.size() - 1 - position);

How do I print colored output with Python 3?

To use colour in the console see here and here.

There are modules dedicated to this task such as colorama and curses

Merging arrays with the same keys

$arr1 = array(
   "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
   "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
   "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
   "3" => array("fid" => 1, "tid" => 7, "name" => "Xi"),
   "4" => array("fid" => 2, "tid" => 9, "name" => "Xigua")
);

if you want to convert this array as following:

$arr2 = array(
   "0" => array(
          "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
          "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
          "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
          "3" => array("fid" => 1, "tid" => 7, "name" => "Xi")
    ),

    "1" => array(
          "0" =>array("fid" => 2, "tid" => 9, "name" => "Xigua")
     )
);

so, my answer will be like this:

$outer_array = array();
$unique_array = array();
foreach($arr1 as $key => $value)
{
    $inner_array = array();

    $fid_value = $value['fid'];
    if(!in_array($value['fid'], $unique_array))
    {
            array_push($unique_array, $fid_value);
            unset($value['fid']);
            array_push($inner_array, $value);
            $outer_array[$fid_value] = $inner_array;


    }else{
            unset($value['fid']);
            array_push($outer_array[$fid_value], $value);

    }
}
var_dump(array_values($outer_array));

hope this answer will help somebody sometime.

Node - how to run app.js?

The code downloaded may require you to install dependencies first. Try commands(in app.js directory): npm install then node app.js. This should install dependencies and then start the app.

Update OpenSSL on OS X with Homebrew

installed openssl on mac with brew but nothing found on /usr/local/bin where other brew installed bins are located. Found my fresh openssl here:

/usr/local/opt/openssl/bin/openssl

Run it like this:

/usr/local/opt/openssl/bin/openssl version

I don't want to update OS X openssl, while some OS stuff or other 3rd party apps may have dependency on older version.

I also don't mind longer path than just openssl

Writing this here for all the Googlers who are looking for location of openssl installed by brew.

angular2 submit form by pressing enter without submit button

Hopefully this can help somebody: for some reason I couldn't track because of lack of time, if you have a form like:

<form (ngSubmit)="doSubmit($event)">
  <button (click)="clearForm()">Clear</button>
  <button type="submit">Submit</button>
</form>

when you hit the Enter button, the clearForm function is called, even though the expected behaviour was to call the doSubmit function. Changing the Clear button to a <a> tag solved the issue for me. I would still like to know if that's expected or not. Seems confusing to me

Java - remove last known item from ArrayList

This line means you instantiated a "List of ClientThread Objects".

private List<ClientThread> clients = new ArrayList<ClientThread>();

This line has two problems.

String hey = clients.get(clients.size());

1. This part of the line:

clients.get(clients.size());

ALWAYS throws IndexOutOfBoundsException because a collections size is always one bigger than its last elements index;

2. Compiler complains about incompatible types because you cant assign a ClientThread object to String object. Correct one should be like this.

ClientThread hey = clients.get(clients.size()-1);

Last but not least. If you know index of the object to remove just write

 clients.remove(23); //Lets say it is in 23. index

Don't write

   ClientThread hey = clients.get(23); 

   clients.remove(hey);

because you are forcing the list to search for the index that you already know. If you plan to do something with the removed object later. Write

   ClientThread hey = clients.remove(23); 

This way you can remove the object and get a reference to it at the same line.

Bonus: Never ever call your instance variable with name "hey". Find something meaningful.

And Here is your corrected and ready-to-run code:

public class ListExampleForDan {

    private List<ClientThread> clients = new ArrayList<ClientThread>();

    public static void main(String args[]) {

        clients.add(new ClientThread("First and Last Client Thread"));

        boolean success = removeLastElement(clients);

        if (success) {

            System.out.println("Last Element Removed.");

        } else {

            System.out.println("List Is Null/Empty, Operation Failed.");

        }

    }

    public static boolean removeLastElement(List clients) {

        if (clients == null || clients.isEmpty()) {

            return false;

        } else {

            clients.remove(clients.size() - 1);

            return true;

        }

    }
}

Enjoy!

Removing NA observations with dplyr::filter()

From @Ben Bolker:

[T]his has nothing specifically to do with dplyr::filter()

From @Marat Talipov:

[A]ny comparison with NA, including NA==NA, will return NA

From a related answer by @farnsy:

The == operator does not treat NA's as you would expect it to.

Think of NA as meaning "I don't know what's there". The correct answer to 3 > NA is obviously NA because we don't know if the missing value is larger than 3 or not. Well, it's the same for NA == NA. They are both missing values but the true values could be quite different, so the correct answer is "I don't know."

R doesn't know what you are doing in your analysis, so instead of potentially introducing bugs that would later end up being published an embarrassing you, it doesn't allow comparison operators to think NA is a value.

MAX function in where clause mysql

Do you want the first and last name of the row with the largest id?

If so (and you were missing a FROM clause):

SELECT firstname, lastname, id
FROM foo
ORDER BY id DESC
LIMIT 1;

Better way to get type of a Javascript variable?

function getType(obj) {
    if(obj && obj.constructor && obj.constructor.name) {
        return obj.constructor.name;
    }
    return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

In my preliminary tests, this is working pretty well. The first case will print the name of any object created with "new", and the 2nd case should catch everything else.

I'm using (8, -1) because I'm assuming that the result is always going to start with [object and end with ] but I'm not certain that's true in every scenario.

Regex to match words of a certain length

I think you want \b\w{1,10}\b. The \b matches a word boundary.

Of course, you could also replace the \b and do ^\w{1,10}$. This will match a word of at most 10 characters as long as its the only contents of the string. I think this is what you were doing before.

Since it's Java, you'll actually have to escape the backslashes: "\\b\\w{1,10}\\b". You probably knew this already, but it's gotten me before.

Display progress bar while doing some work in C#?

There's a load of information about threading with .NET/C# on Stackoverflow, but the article that cleared up windows forms threading for me was our resident oracle, Jon Skeet's "Threading in Windows Forms".

The whole series is worth reading to brush up on your knowledge or learn from scratch.

I'm impatient, just show me some code

As far as "show me the code" goes, below is how I would do it with C# 3.5. The form contains 4 controls:

  • a textbox
  • a progressbar
  • 2 buttons: "buttonLongTask" and "buttonAnother"

buttonAnother is there purely to demonstrate that the UI isn't blocked while the count-to-100 task is running.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void buttonLongTask_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(LongTask);
        thread.IsBackground = true;
        thread.Start();
    }

    private void buttonAnother_Click(object sender, EventArgs e)
    {
        textBox1.Text = "Have you seen this?";
    }

    private void LongTask()
    {
        for (int i = 0; i < 100; i++)
        {
            Update1(i);
            Thread.Sleep(500);
        }
    }

    public void Update1(int i)
    {
        if (InvokeRequired)
        {
            this.BeginInvoke(new Action<int>(Update1), new object[] { i });
            return;
        }

        progressBar1.Value = i;
    }
}

How to know if a DateTime is between a DateRange in C#

Following on from Sergey's answer, I think this more generic version is more in line with Fowler's Range idea, and resolves some of the issues with that answer such as being able to have the Includes methods within a generic class by constraining T as IComparable<T>. It's also immutable like what you would expect with types that extend the functionality of other value types like DateTime.

public struct Range<T> where T : IComparable<T>
{
    public Range(T start, T end)
    {
        Start = start;
        End = end;
    }

    public T Start { get; }

    public T End { get; }

    public bool Includes(T value) => Start.CompareTo(value) <= 0 && End.CompareTo(value) >= 0;

    public bool Includes(Range<T> range) => Start.CompareTo(range.Start) <= 0 && End.CompareTo(range.End) >= 0;
}

How To Convert A Number To an ASCII Character?

Edit: By request, I added a check to make sure the value entered was within the ASCII range of 0 to 127. Whether you want to limit this is up to you. In C# (and I believe .NET in general), chars are represented using UTF-16, so any valid UTF-16 character value could be cast into it. However, it is possible a system does not know what every Unicode character should look like so it may show up incorrectly.

// Read a line of input
string input = Console.ReadLine();

int value;
// Try to parse the input into an Int32
if (Int32.TryParse(input, out value)) {
    // Parse was successful
    if (value >= 0 and value < 128) {
        //value entered was within the valid ASCII range
        //cast value to a char and print it
        char c = (char)value;
        Console.WriteLine(c);
    }
}

What are the differences between 'call-template' and 'apply-templates' in XSL?

xsl:apply-templates is usually (but not necessarily) used to process all or a subset of children of the current node with all applicable templates. This supports the recursiveness of XSLT application which is matching the (possible) recursiveness of the processed XML.

xsl:call-template on the other hand is much more like a normal function call. You execute exactly one (named) template, usually with one or more parameters.

So I use xsl:apply-templates if I want to intercept the processing of an interesting node and (usually) inject something into the output stream. A typical (simplified) example would be

<xsl:template match="foo">
  <bar>
    <xsl:apply-templates/>
  </bar>
</xsl:template>

whereas with xsl:call-template I typically solve problems like adding the text of some subnodes together, transforming select nodesets into text or other nodesets and the like - anything you would write a specialized, reusable function for.

Edit:

As an additional remark to your specific question text:

<xsl:call-template name="nodes"/> 

This calls a template which is named 'nodes':

    <xsl:template name="nodes">...</xsl:template>

This is a different semantic than:

<xsl:apply-templates select="nodes"/>

...which applies all templates to all children of your current XML node whose name is 'nodes'.

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

What is the difference between #include <filename> and #include "filename"?

The #include <filename> is used when a system file is being referred to. That is a header file that can be found at system default locations like /usr/include or /usr/local/include. For your own files that needs to be included in another program you have to use the #include "filename" syntax.

Android - Handle "Enter" in an EditText

This will give you a callable function when the user presses the return key.

fun EditText.setLineBreakListener(onLineBreak: () -> Unit) {
    val lineBreak = "\n"
    doOnTextChanged { text, _, _, _ ->
        val currentText = text.toString()

        // Check if text contains a line break
        if (currentText.contains(lineBreak)) {

            // Uncommenting the lines below will remove the line break from the string
            // and set the cursor back to the end of the line

            // val cleanedString = currentText.replace(lineBreak, "")
            // setText(cleanedString)
            // setSelection(cleanedString.length)

            onLineBreak()
        }
    }
}

Usage

editText.setLineBreakListener {
    doSomething()
}

How do I get the YouTube video ID from a URL?

Try this one -

function getYouTubeIdFromURL($url) 
{
  $pattern = '/(?:youtube.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?/ ]{11})/i';
  preg_match($pattern, $url, $matches);

  return isset($matches[1]) ? $matches[1] : false;
}

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How to use the ProGuard in Android Studio?

NB.: Now instead of

runProguard false

you'll need to use

minifyEnabled false

How do I get formatted JSON in .NET using C#?

Using System.Text.Json set JsonSerializerOptions.WriteIndented = true:

JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize<Type>(object, options);

How to set URL query params in Vue with Vue-Router

this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })

How do you setLayoutParams() for an ImageView?

Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

What are .dex files in Android?

dex file is a file that is executed on the Dalvik VM.

Dalvik VM includes several features for performance optimization, verification, and monitoring, one of which is Dalvik Executable (DEX).

Java source code is compiled by the Java compiler into .class files. Then the dx (dexer) tool, part of the Android SDK processes the .class files into a file format called DEX that contains Dalvik byte code. The dx tool eliminates all the redundant information that is present in the classes. In DEX all the classes of the application are packed into one file. The following table provides comparison between code sizes for JVM jar files and the files processed by the dex tool.

The table compares code sizes for system libraries, web browser applications, and a general purpose application (alarm clock app). In all cases dex tool reduced size of the code by more than 50%.

enter image description here

In standard Java environments each class in Java code results in one .class file. That means, if the Java source code file has one public class and two anonymous classes, let’s say for event handling, then the java compiler will create total three .class files.

The compilation step is same on the Android platform, thus resulting in multiple .class files. But after .class files are generated, the “dx” tool is used to convert all .class files into a single .dex, or Dalvik Executable, file. It is the .dex file that is executed on the Dalvik VM. The .dex file has been optimized for memory usage and the design is primarily driven by sharing of data.

Deep copy vs Shallow Copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }
};

Here, the pi member of the original and copied X object will both point to the same int.


Deep copy:

All members of the original are cloned (recursively, if necessary). There are no shared objects:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }
};

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.


The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.

Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.

Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

Popup window in PHP?

You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.

I need to round a float to two decimal places in Java

You can make use of DecimalFormat to give you the style you wish.

DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number));  // prints 1.30E7

Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.

Remove multiple objects with rm()

Make the list a character vector (not a vector of names)

rm(list = c('temp1','temp2'))

or

rm(temp1, temp2)

How do you check that a number is NaN in JavaScript?

While @chiborg 's answer IS correct, there is more to it that should be noted:

parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true

Point being, if you're using this method for validation of input, the result will be rather liberal.

So, yes you can use parseFloat(string) (or in the case of full numbers parseInt(string, radix)' and then subsequently wrap that with isNaN(), but be aware of the gotcha with numbers intertwined with additional non-numeric characters.

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

Making heatmap from pandas DataFrame

Surprised to see no one mentioned more capable, interactive and easier to use alternatives.

A) You can use plotly:

  1. Just two lines and you get:

  2. interactivity,

  3. smooth scale,

  4. colors based on whole dataframe instead of individual columns,

  5. column names & row indices on axes,

  6. zooming in,

  7. panning,

  8. built-in one-click ability to save it as a PNG format,

  9. auto-scaling,

  10. comparison on hovering,

  11. bubbles showing values so heatmap still looks good and you can see values wherever you want:

import plotly.express as px
fig = px.imshow(df.corr())
fig.show()

enter image description here

B) You can also use Bokeh:

All the same functionality with a tad much hassle. But still worth it if you do not want to opt-in for plotly and still want all these things:

from bokeh.plotting import figure, show, output_notebook
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.transform import transform
output_notebook()
colors = ['#d7191c', '#fdae61', '#ffffbf', '#a6d96a', '#1a9641']
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
data = df.corr().stack().rename("value").reset_index()
p = figure(x_range=list(df.columns), y_range=list(df.index), tools=TOOLS, toolbar_location='below',
           tooltips=[('Row, Column', '@level_0 x @level_1'), ('value', '@value')], height = 500, width = 500)

p.rect(x="level_1", y="level_0", width=1, height=1,
       source=data,
       fill_color={'field': 'value', 'transform': LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max())},
       line_color=None)
color_bar = ColorBar(color_mapper=LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max()), major_label_text_font_size="7px",
                     ticker=BasicTicker(desired_num_ticks=len(colors)),
                     formatter=PrintfTickFormatter(format="%f"),
                     label_standoff=6, border_line_color=None, location=(0, 0))
p.add_layout(color_bar, 'right')

show(p)

enter image description here

How to make a phone call programmatically?

Here I will show you that how you can make a phone call from your activity. To make a call you have to put down this code in your app.

try {
    Intent my_callIntent = new Intent(Intent.ACTION_CALL);
    my_callIntent.setData(Uri.parse("tel:"+phn_no));
    //here the word 'tel' is important for making a call...
    startActivity(my_callIntent);
} catch (ActivityNotFoundException e) {
    Toast.makeText(getApplicationContext(), "Error in your phone call"+e.getMessage(), Toast.LENGTH_LONG).show();
}

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.

In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".

Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.

If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)

However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.

Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.

Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:

   =VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)

Forward host port to docker container

I had a similar problem accessing a LDAP-Server from a docker container. I set a fixed IP for the container and added a firewall rule.

docker-compose.yml:

version: '2'
services:
  containerName:
    image: dockerImageName:latest
    extra_hosts:
      - "dockerhost:192.168.50.1"
    networks:
      my_net:
        ipv4_address: 192.168.50.2
networks:
  my_net:
    ipam:
      config:
      - subnet: 192.168.50.0/24

iptables rule:

iptables -A INPUT -j ACCEPT -p tcp -s 192.168.50.2 -d $192.168.50.1 --dport portnumberOnHost

Inside the container access dockerhost:portnumberOnHost

Git Push error: refusing to update checked out branch

Maybe your remote repo is in the branch which you want to push. You can try to checkout another branch in your remote machine. I did this, than these error disappeared, and I pushed success to my remote repo. Notice that I use ssh to connect my own server instead of github.com.

Is Unit Testing worth the effort?

In short - yes. They are worth every ounce of effort... to a point. Tests are, at the end of the day, still code, and much like typical code growth, your tests will eventually need to be refactored in order to be maintainable and sustainable. There's a tonne of GOTCHAS! when it comes to unit testing, but man oh man oh man, nothing, and I mean NOTHING empowers a developer to make changes more confidently than a rich set of unit tests.

I'm working on a project right now.... it's somewhat TDD, and we have the majority of our business rules encapuslated as tests... we have about 500 or so unit tests right now. This past iteration I had to revamp our datasource and how our desktop application interfaces with that datasource. Took me a couple days, the whole time I just kept running unit tests to see what I broke and fixed it. Make a change; Build and run your tests; fix what you broke. Wash, Rinse, Repeat as necessary. What would have traditionally taken days of QA and boat loads of stress was instead a short and enjoyable experience.

Prep up front, a little bit of extra effort, and it pays 10-fold later on when you have to start dicking around with core features/functionality.

I bought this book - it's a Bible of xUnit Testing knowledge - tis probably one of the most referenced books on my shelf, and I consult it daily: link text

How to uninstall mini conda? python

To update @Sunil answer: Under Windows, Miniconda has a regular uninstaller. Go to the menu "Settings/Apps/Apps&Features", or click the Start button, type "uninstall", then click on "Add or Remove Programs" and finally on the Miniconda uninstaller.

Prevent double submission of forms in jQuery

If using AJAX to post a form, set async: false should prevent additional submits before the form clears:

$("#form").submit(function(){
    var one = $("#one").val();
    var two = $("#two").val();
    $.ajax({
      type: "POST",
      async: false,  // <------ Will complete submit before allowing further action
      url: "process.php",
      data: "one="+one+"&two="+two+"&add=true",
      success: function(result){
        console.log(result);
        // do something with result
      },
      error: function(){alert('Error!')}
    });
    return false;
   }
});

How to change background and text colors in Sublime Text 3

  1. Go to the preferences
  2. Click on color scheme
  3. Choose your color scheme
  4. I chose plastic, for my case.

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

How to refresh Gridview after pressed a button in asp.net

I was totally lost on why my Gridview.Databind() would not refresh.

My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:

gvServerConfiguration.Databind()
uppServerConfiguration.Update()

uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.

Hope this helps someone.

Call An Asynchronous Javascript Function Synchronously

Take a look at JQuery Promises:

http://api.jquery.com/promise/

http://api.jquery.com/jQuery.when/

http://api.jquery.com/deferred.promise/

Refactor the code:


    var dfd = new jQuery.Deferred();


    function callBack(data) {
       dfd.notify(data);
    }

    // do the async call.
    myAsynchronousCall(param1, callBack);

    function doSomething(data) {
     // do stuff with data...
    }

    $.when(dfd).then(doSomething);


Eclipse error: "The import XXX cannot be resolved"

Try adding JRE System Library in the build path of your project.

Is there a Sleep/Pause/Wait function in JavaScript?

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
  ...
  window.setTimeout(partB,1000);
}

function partB() {
   ...
}

Path to MSBuild

Poking around the registry, it looks like

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0

may be what you're after; fire up regedit.exe and have a look.

Query via command line (per Nikolay Botev)

reg.exe query "HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0" /v MSBuildToolsPath

Query via PowerShell (per MovGP0)

dir HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\

Convert binary to ASCII and vice versa

For ASCII characters in the range [ -~] on Python 2:

>>> import binascii
>>> bin(int(binascii.hexlify('hello'), 16))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> binascii.unhexlify('%x' % n)
'hello'

In Python 3.2+:

>>> bin(int.from_bytes('hello'.encode(), 'big'))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
'hello'

To support all Unicode characters in Python 3:

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0'

Here's single-source Python 2/3 compatible version:

import binascii

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return int2bytes(n).decode(encoding, errors)

def int2bytes(i):
    hex_string = '%x' % i
    n = len(hex_string)
    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

Example

>>> text_to_bits('hello')
'0110100001100101011011000110110001101111'
>>> text_from_bits('110100001100101011011000110110001101111') == u'hello'
True

Remove part of string in Java

Using StringBuilder, you can replace the following way.

StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");

What is JavaScript's highest integer value that a number can go to without losing precision?

JavaScript has two number types: Number and BigInt.

The most frequently-used number type, Number, is a 64-bit floating point IEEE 754 number.

The largest exact integral value of this type is Number.MAX_SAFE_INTEGER, which is:

  • 253-1, or
  • +/- 9,007,199,254,740,991, or
  • nine quadrillion seven trillion one hundred ninety-nine billion two hundred fifty-four million seven hundred forty thousand nine hundred ninety-one

To put this in perspective: one quadrillion bytes is a petabyte (or one thousand terabytes).

"Safe" in this context refers to the ability to represent integers exactly and to correctly compare them.

From the spec:

Note that all the positive and negative integers whose magnitude is no greater than 253 are representable in the Number type (indeed, the integer 0 has two representations, +0 and -0).

To safely use integers larger than this, you need to use BigInt, which has no upper bound.

Note that the bitwise operators and shift operators operate on 32-bit integers, so in that case, the max safe integer is 231-1, or 2,147,483,647.

_x000D_
_x000D_
const log = console.log_x000D_
var x = 9007199254740992_x000D_
var y = -x_x000D_
log(x == x + 1) // true !_x000D_
log(y == y - 1) // also true !_x000D_
_x000D_
// Arithmetic operators work, but bitwise/shifts only operate on int32:_x000D_
log(x / 2)      // 4503599627370496_x000D_
log(x >> 1)     // 0_x000D_
log(x | 1)      // 1
_x000D_
_x000D_
_x000D_


Technical note on the subject of the number 9,007,199,254,740,992: There is an exact IEEE-754 representation of this value, and you can assign and read this value from a variable, so for very carefully chosen applications in the domain of integers less than or equal to this value, you could treat this as a maximum value.

In the general case, you must treat this IEEE-754 value as inexact, because it is ambiguous whether it is encoding the logical value 9,007,199,254,740,992 or 9,007,199,254,740,993.

Make a link in the Android browser start up my app?

Once you have the intent and custom url scheme for your app set up, this javascript code at the top of a receiving page has worked for me on both iOS and Android:

<script type="text/javascript">
// if iPod / iPhone, display install app prompt
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i) ||
    navigator.userAgent.match(/android/i)) {
  var store_loc = "itms://itunes.com/apps/raditaz";
  var href = "/iphone/";
  var is_android = false;
  if (navigator.userAgent.match(/android/i)) {
    store_loc = "https://play.google.com/store/apps/details?id=com.raditaz";
    href = "/android/";
    is_android = true;
  }
  if (location.hash) {
    var app_loc = "raditaz://" + location.hash.substring(2);
    if (is_android) {
      var w = null;
      try {
        w = window.open(app_loc, '_blank');
      } catch (e) {
        // no exception
      }
      if (w) { window.close(); }
      else { window.location = store_loc; }
    } else {
      var loadDateTime = new Date();
      window.setTimeout(function() {
        var timeOutDateTime = new Date();
        if (timeOutDateTime - loadDateTime < 5000) {
          window.location = store_loc;
        } else { window.close(); }
      },
      25);
      window.location = app_loc;
    }
  } else {
    location.href = href;
  }
}
</script>

This has only been tested on the Android browser. I am not sure about Firefox or Opera. The key is even though the Android browser will not throw a nice exception for you on window.open(custom_url, '_blank'), it will fail and return null which you can test later.

Update: using store_loc = "https://play.google.com/store/apps/details?id=com.raditaz"; to link to Google Play on Android.

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

import { FormsModule } from '@angular/forms'; //<<<< import it here

BrowserModule, FormsModule //<<<< and here

So simply looks for app.module.ts or another module file and make sure you have FormsModule imported in...

What is the meaning of Bus: error 10 in C

Let me explain why you do you got this error "Bus error: 10"

char *str1 = "First string";
// for this statement the memory will be allocated into the CODE/TEXT segment which is READ-ONLY

char *str2 = "Second string";
// for this statement the memory will be allocated into the CODE/TEXT segment which is READ-ONLY

strcpy(str1, str2);
// This function will copy the content from str2 into str1, this is not possible because you are try to perform READ WRITE operation inside the READ-ONLY segment.Which was the root cause 

If you want to perform string manipulation use automatic variables(STACK segment) or dynamic variables(HEAP segment)

Vasanth

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

Classes vs. Modules in VB.NET

Modules are by no means deprecated and are used heavily in the VB language. It's the only way for instance to implement an extension method in VB.Net.

There is one huge difference between Modules and Classes with Static Members. Any method defined on a Module is globally accessible as long as the Module is available in the current namespace. In effect a Module allows you to define global methods. This is something that a class with only shared members cannot do.

Here's a quick example that I use a lot when writing VB code that interops with raw COM interfaces.

Module Interop
  Public Function Succeeded(ByVal hr as Integer) As Boolean
    ...
  End Function

  Public Function Failed(ByVal hr As Integer) As Boolean
    ...
  End Function
End Module

Class SomeClass
  Sub Foo()
    Dim hr = CallSomeHrMethod()
    if Succeeded(hr) then
      ..
    End If
  End Sub
End Class

How to get "wc -l" to print just the number of lines without file name?

Comparison of Techniques

I had a similar issue attempting to get a character count without the leading whitespace provided by wc, which led me to this page. After trying out the answers here, the following are the results from my personal testing on Mac (BSD Bash). Again, this is for character count; for line count you'd do wc -l. echo -n omits the trailing line break.

FOO="bar"
echo -n "$FOO" | wc -c                          # "       3"    (x)
echo -n "$FOO" | wc -c | bc                     # "3"           (v)
echo -n "$FOO" | wc -c | tr -d ' '              # "3"           (v)
echo -n "$FOO" | wc -c | awk '{print $1}'       # "3"           (v)
echo -n "$FOO" | wc -c | cut -d ' ' -f1         # "" for -f < 8 (x)
echo -n "$FOO" | wc -c | cut -d ' ' -f8         # "3"           (v)
echo -n "$FOO" | wc -c | perl -pe 's/^\s+//'    # "3"           (v)
echo -n "$FOO" | wc -c | grep -ch '^'           # "1"           (x)
echo $( printf '%s' "$FOO" | wc -c )            # "3"           (v)

I wouldn't rely on the cut -f* method in general since it requires that you know the exact number of leading spaces that any given output may have. And the grep one works for counting lines, but not characters.

bc is the most concise, and awk and perl seem a bit overkill, but they should all be relatively fast and portable enough.

Also note that some of these can be adapted to trim surrounding whitespace from general strings, as well (along with echo `echo $FOO`, another neat trick).

Enzyme - How to access and set <input> value?

This worked for me:

let wrapped = mount(<Component />);
expect(wrapped.find("input").get(0).props.value).toEqual("something");

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

If you're using 64-bit but still having problem even after installing AccessDatabaseEngine, see this post, it solved the problem for me.

i.e. You need to install this AccessDatabaseEngine

Create XML in Javascript

Only works in IE

 $(function(){

        var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>'; 

        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(xml);

        alert(xmlDoc.xml);

    });

Then push xmlDoc.xml to your java code.

C# LINQ find duplicates in List

The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to:

var query = lst.GroupBy(x => x)
              .Where(g => g.Count() > 1)
              .Select(y => y.Key)
              .ToList();

If you want to know how many times the elements are repeated, you can use:

var query = lst.GroupBy(x => x)
              .Where(g => g.Count() > 1)
              .Select(y => new { Element = y.Key, Counter = y.Count() })
              .ToList();

This will return a List of an anonymous type, and each element will have the properties Element and Counter, to retrieve the information you need.

And lastly, if it's a dictionary you are looking for, you can use

var query = lst.GroupBy(x => x)
              .Where(g => g.Count() > 1)
              .ToDictionary(x => x.Key, y => y.Count());

This will return a dictionary, with your element as key, and the number of times it's repeated as value.

Download image from the site in .NET/C#

There is no need to involve any image classes, you can simply call WebClient.DownloadFile:

string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}

Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:

private static void DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK || 
        response.StatusCode == HttpStatusCode.Moved || 
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download oit
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

In brief, it makes a request for the file, verifies that the response code is one of OK, Moved or Redirect and also that the ContentType is an image. If those conditions are true, the file is downloaded.

Starting Docker as Daemon on Ubuntu

I had a same issue on ubuntu 14.04 Here is a solution

sudo service docker start

or you can list images

docker images

Which language uses .pde extension?

This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.

EDIT - And yes it is C syntax, used mostly for art or live media presentations.

How to make a GridLayout fit screen size

After many attempts I found what I was looking for in this layout. Even spaced LinearLayouts with automatically fitted ImageViews, with maintained aspect ratio. Works with landscape and portrait with any screen and image resolution.

Nexus 7 Nexus 5 Nexus 10

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffcc5d00" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">


        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_weight="1"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image1"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image2"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_weight="1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image3"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image4"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</FrameLayout>

Load dimension value from res/values/dimension.xml from source code

Context.getResources().getDimension(int id);

Get remote registry value

If you have Powershell remoting and CredSSP setup then you can update your code to the following:

$Session = New-PSSession -ComputerName $Computer1 -Authentication CredSSP
$NetbackupVersion1 = Invoke-Command -Session $Session -ScriptBlock { $(Get-ItemProperty hklm:\SOFTWARE\Veritas\NetBackup\CurrentVersion).PackageVersion}
Remove-PSSession $Session

How to programmatically empty browser cache?

_x000D_
_x000D_
//The code below should be put in the "js" folder with the name "clear-browser-cache.js"_x000D_
_x000D_
(function () {_x000D_
    var process_scripts = false;_x000D_
    var rep = /.*\?.*/,_x000D_
    links = document.getElementsByTagName('link'),_x000D_
    scripts = document.getElementsByTagName('script');_x000D_
    var value = document.getElementsByName('clear-browser-cache');_x000D_
    for (var i = 0; i < value.length; i++) {_x000D_
        var val = value[i],_x000D_
            outerHTML = val.outerHTML;_x000D_
        var check = /.*value="true".*/;_x000D_
        if (check.test(outerHTML)) {_x000D_
            process_scripts = true;_x000D_
        }_x000D_
    }_x000D_
    for (var i = 0; i < links.length; i++) {_x000D_
        var link = links[i],_x000D_
        href = link.href;_x000D_
        if (rep.test(href)) {_x000D_
            link.href = href + '&' + Date.now();_x000D_
        }_x000D_
        else {_x000D_
            link.href = href + '?' + Date.now();_x000D_
        }_x000D_
    }_x000D_
    if (process_scripts) {_x000D_
        for (var i = 0; i < scripts.length; i++) {_x000D_
            var script = scripts[i],_x000D_
            src = script.src;_x000D_
            if (src !== "") {_x000D_
                if (rep.test(src)) {_x000D_
                    script.src = src + '&' + Date.now();_x000D_
                }_x000D_
                else {_x000D_
                    script.src = src + '?' + Date.now();_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
})();
_x000D_
At the end of the tah head, place the line at the code below_x000D_
_x000D_
    < script name="clear-browser-cache" src='js/clear-browser-cache.js' value="true" >< /script >
_x000D_
_x000D_
_x000D_

Count length of array and return 1 if it only contains one element

Maybe I am missing something (lots of many-upvotes-members answers here that seem to be looking at this different to I, which would seem implausible that I am correct), but length is not the correct terminology for counting something. Length is usually used to obtain what you are getting, and not what you are wanting.

$cars.count should give you what you seem to be looking for.

How do I add a Fragment to an Activity with a programmatically created content view

After read all Answers I came up with elegant way:

public class MyActivity extends ActionBarActivity {

 Fragment fragment ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FragmentManager fm = getSupportFragmentManager();
    fragment = fm.findFragmentByTag("myFragmentTag");
    if (fragment == null) {
        FragmentTransaction ft = fm.beginTransaction();
        fragment =new MyFragment();
        ft.add(android.R.id.content,fragment,"myFragmentTag");
        ft.commit();
    }

}

basically you don't need to add a frameLayout as container of your fragment instead you can add straight the fragment into the android root View container

IMPORTANT: don't use replace fragment as most of the approach shown here, unless you don't mind to lose fragment variable instance state during onrecreation process.

How to make this Header/Content/Footer layout using CSS?

Here is how to to that:

The header and footer are 30px height.

The footer is stuck to the bottom of the page.

HTML:

<div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>

CSS:

#header {
    height: 30px;
}
#footer {
    height: 30px;
    position: absolute;
    bottom: 0;
}
body {
    height: 100%;
    margin-bottom: 30px;
}

Try it on jsfiddle: http://jsfiddle.net/Usbuw/

How to implement a tree data-structure in Java?

I wrote a small "TreeMap" class based on "HashMap" that supports adding paths:

import java.util.HashMap;
import java.util.LinkedList;

public class TreeMap<T> extends LinkedHashMap<T, TreeMap<T>> {

    public void put(T[] path) {
        LinkedList<T> list = new LinkedList<>();
        for (T key : path) {
            list.add(key);
        }
        return put(list);
    }

    public void put(LinkedList<T> path) {
        if (path.isEmpty()) {
            return;
        }
        T key = path.removeFirst();
        TreeMap<T> val = get(key);
        if (val == null) {
            val = new TreeMap<>();
            put(key, val);
        }
        val.put(path);
    }

}

It can be use to store a Tree of things of type "T" (generic), but does not (yet) support storing extra data in it's nodes. If you have a file like this:

root, child 1
root, child 1, child 1a
root, child 1, child 1b
root, child 2
root, child 3, child 3a

Then you can make it a tree by executing:

TreeMap<String> root = new TreeMap<>();
Scanner scanner = new Scanner(new File("input.txt"));
while (scanner.hasNextLine()) {
  root.put(scanner.nextLine().split(", "));
}

And you will get a nice tree. It should be easy to adapt to your needs.

How to zip a file using cmd line?

Not exactly zipping, but you can compact files in Windows with the compact command:

compact /c /s:<directory or file>

And to uncompress:

compact /u /s:<directory or file>

NOTE: These commands only mark/unmark files or directories as compressed in the file system. They do not produces any kind of archive (like zip, 7zip, rar, etc.)

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

python mpl_toolkits installation issue

It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.

Solution

Uninstall matplotlib from pip then install it again with apt-get

python 2:

sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib

python 3:

sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib

MySQL - SELECT all columns WHERE one column is DISTINCT

If you want all columns where link is unique:

SELECT * FROM posted WHERE link in
     (SELECT link FROM posted WHERE ad='$key' GROUP BY link);

Django - limiting query results

Looks like the solution in the question doesn't work with Django 1.7 anymore and raises an error: "Cannot reorder a query once a slice has been taken"

According to the documentation https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets forcing the “step” parameter of Python slice syntax evaluates the Query. It works this way:

Model.objects.all().order_by('-id')[:10:1]

Still I wonder if the limit is executed in SQL or Python slices the whole result array returned. There is no good to retrieve huge lists to application memory.

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

Webpack - webpack-dev-server: command not found

I noticed the same problem after installing VSCode and adding a remote Git repository. Somehow the /node_modules/.bin folder was deleted and running npm install --save webpack-dev-server in the command line re-installed the missing folder and fixed my problem.

Jenkins: Is there any way to cleanup Jenkins workspace?

You will need to install this plugin before the options mentioned above will appear

Workspace Cleanup Plugin

This plugin add the check box to all job configs to allow you to delete the whole workspace before any steps (inc source control) are run

This is useful to make sure you always start from a known point to guarantee how you build will run

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

Set up a scheduled job?

Celery is a distributed task queue, built on AMQP (RabbitMQ). It also handles periodic tasks in a cron-like fashion (see periodic tasks). Depending on your app, it might be worth a gander.

Celery is pretty easy to set up with django (docs), and periodic tasks will actually skip missed tasks in case of a downtime. Celery also has built-in retry mechanisms, in case a task fails.

How do I convert a C# List<string[]> to a Javascript array?

For those trying to do it without using JSON, the following is how I did it:

<script>
    var originalLabels = [ '@Html.Raw(string.Join("', '", Model.labels))'];
</script>

Java properties UTF-8 encoding in Eclipse

Properties props = new Properties();
URL resource = getClass().getClassLoader().getResource("data.properties");         
props.load(new InputStreamReader(resource.openStream(), "UTF8"));

this works well in java 1.6. How can i do this in 1.5, Since Properties class does not have a method to pars InputStreamReader.

What is ".NET Core"?

.NET Core is an open source and cross platform version of .NET Framework.

How to parse a string into a nullable int

I felt I should share mine which is a bit more generic.

Usage:

var result = "123".ParseBy(int.Parse);

var result2 = "123".ParseBy<int>(int.TryParse);

Solution:

public static class NullableParse
{
    public static Nullable<T> ParseBy<T>(this string input, Func<string, T> parser)
        where T : struct
    {
        try
        {
            return parser(input);
        }
        catch (Exception exc)
        {
            return null;
        }
    }

    public delegate bool TryParseDelegate<T>(string input, out T result);

    public static Nullable<T> ParseBy<T>(this string input, TryParseDelegate<T> parser)
        where T : struct
    {
        T t;
        if (parser(input, out t)) return t;
        return null;
    }
}

First version is a slower since it requires a try-catch but it looks cleaner. If it won't be called many times with invalid strings, it is not that important. If performance is an issue, please note that when using TryParse methods, you need to specify the type parameter of ParseBy as it can not be inferred by the compiler. I also had to define a delegate as out keyword can not be used within Func<>, but at least this time compiler does not require an explicit instance.

Finally, you can use it with other structs as well, i.e. decimal, DateTime, Guid, etc.

How to set the project name/group/version, plus {source,target} compatibility in the same file?

I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle file as following:

  rootProject.name='YourNewName'

This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.

What are the differences in die() and exit() in PHP?

This page says die is an alies of exit, so they are identical. But also explains that:

there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script.

So, call me paranoid, but there may be no dieing in the future.

Script to Change Row Color when a cell changes text

user2532030's answer is the correct and most simple answer.

I just want to add, that in the case, where the value of the determining cell is not suitable for a RegEx-match, I found the following syntax to work the same, only with numerical values, relations et.c.:

[Custom formula is]
=$B$2:$B = "Complete"
Range: A2:Z1000

If column 2 of any row (row 2 in script, but the leading $ means, this could be any row) textually equals "Complete", do X for the Range of the entire sheet (excluding header row (i.e. starting from A2 instead of A1)).

But obviously, this method allows also for numerical operations (even though this does not apply for op's question), like:

=$B$2:$B > $C$2:$C

So, do stuff, if the value of col B in any row is higher than col C value.

One last thing: Most likely, this applies only to me, but I was stupid enough to repeatedly forget to choose Custom formula is in the drop-down, leaving it at Text contains. Obviously, this won't float...

JavaScript Array to Set

What levi said about passing it into the constructor is correct, but you could also use an object.

I think what Veverke is trying to say is that you could easily use the delete keyword on an object to achieve the same effect.

I think you're confused by the terminology; properties are components of the object that you can use as named indices (if you want to think of it that way).

Try something like this:

var obj = {
    "bob": "dole",
    "mr.": "peabody",
    "darkwing": "duck"
};

Then, you could just do this:

delete obj["bob"];

The structure of the object would then be this:

{
    "mr.": "peabody",
    "darkwing": "duck"
}

Which has the same effect.

Android WebView Cookie Problem

Encountered this too also. Here's what I did.

On my LoginActivity, inside my AsyncTask, I have the following:

CookieStoreHelper.cookieStore = new BasicCookieStore();
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, CookieStoreHelper.cookieStore);

HttpResponse postResponse = client.execute(httpPost,localContext);
CookieStoreHelper.sessionCookie = CookieStoreHelper.cookieStore.getCookies();

//WHERE CookieStoreHelper.sessionCookie is another class containing the variable sessionCookie defined as List cookies; and cookieStore define as BasicCookieStore cookieStore;

Then on my Fragment, where my WebView is located i have the following:

//DECLARE LIST OF COOKIE
List<Cookie> sessionCookie;

inside my method or just before you are setting the WebViewClient()

WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

sessionCookie = CookieStoreHelper.cookieStore.getCookies();
CookieSyncManager.createInstance(webView.getContext());
CookieSyncManager.getInstance().startSync();
CookieManager cookieManager = CookieManager.getInstance();
CookieManager.getInstance().setAcceptCookie(true);
if (sessionCookie != null) {
   for(Cookie c:  sessionCookie){
      cookieManager.setCookie(CookieStoreHelper.DOMAIN, c.getName() + "=" + c.getValue());
   }
   CookieSyncManager.getInstance().sync();

 }

 webView.setWebViewClient(new WebViewClient() {
    //AND SO ON, YOUR CODE
 }

Quick Tip: Have firebug installed on firefox or use developer console on chrome and test first your webpage, capture the Cookie and check the domain so you can store it somewhere and be sure that you are correctly setting the right domain.

Edit: edited CookieStoreHelper.cookies to CookieStoreHelper.sessionCookie

How to find lines containing a string in linux

The usual way to do this is with grep, which uses a pattern to match lines:

grep 'pattern' file

Each line which matches the pattern will be output. If you want to search for fixed strings only, use grep -F 'pattern' file.

VBA procedure to import csv file into access

Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work

Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant

    sFileIn = "z:\docs\FileName.csv"
    sFileOut = "z:\docs\FileOut.csv"

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading

    sTmp = tsIn.ReadAll

    Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
    aryFile = Split(sTmp, vbCrLf)

    ''Start at line 3 and end at last line -1
    For i = 3 To UBound(aryFile) - 1
        tsOut.WriteLine aryFile(i)
    Next

    tsOut.Close

    DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub

Edit re various comments

It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.

About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003

Introduction to importing and exporting data -- Applies to: Microsoft Access 2010

Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

Make xargs handle filenames that contain spaces

Alternative solutions can be helpful...

You can also add a null character to the end of your lines using Perl, then use the -0 option in xargs. Unlike the xargs -d '\n' (in approved answer) - this works everywhere, including OS X.

For example, to recursively list (execute, move, etc.) MPEG3 files which may contain spaces or other funny characters - I'd use:

find . | grep \.mp3 | perl -ne 'chop; print "$_\0"' | xargs -0  ls

(Note: For filtering, I prefer the easier-to-remember "| grep" syntax to "find's" --name arguments.)

How to make child element higher z-index than parent?

Use non-static position along with greater z-index in child element:

.parent {
    position: absolute
    z-index: 100;
}

.child {
    position: relative;
    z-index: 101;
}

How to make Python script run as service?

My non pythonic approach would be using & suffix. That is:

python flashpolicyd.py &

To stop the script

killall flashpolicyd.py

also piping & suffix with disown would put the process under superparent (upper):

python flashpolicyd.pi & disown

How do you create a Marker with a custom icon for google maps API v3?

marker = new google.maps.Marker({
    map:map,
    // draggable:true,
    // animation: google.maps.Animation.DROP,
    position: new google.maps.LatLng(59.32522, 18.07002),
    icon: 'http://cdn.com/my-custom-icon.png' // null = default icon
  });

Reactjs convert html string to jsx

There are now safer methods to accomplish this. The docs have been updated with these methods.

Other Methods

  1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    <div>{'First · Second'}</div>

  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>

    or

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

Change a Nullable column to NOT NULL with Default Value

you need to execute two queries:

One - to add the default value to the column required

ALTER TABLE 'Table_Name` ADD DEFAULT 'value' FOR 'Column_Name'

i want add default value to Column IsDeleted as below:

Example: ALTER TABLE [dbo].[Employees] ADD Default 0 for IsDeleted

Two - to alter the column value nullable to not null

ALTER TABLE 'table_name' ALTER COLUMN 'column_name' 'data_type' NOT NULL

i want to make the column IsDeleted as not null

ALTER TABLE [dbo].[Employees] Alter Column IsDeleted BIT NOT NULL

What is the best way to use a HashMap in C++?

For those of us trying to figure out how to hash our own classes whilst still using the standard template, there is a simple solution:

  1. In your class you need to define an equality operator overload ==. If you don't know how to do this, GeeksforGeeks has a great tutorial https://www.geeksforgeeks.org/operator-overloading-c/

  2. Under the standard namespace, declare a template struct called hash with your classname as the type (see below). I found a great blogpost that also shows an example of calculating hashes using XOR and bitshifting, but that's outside the scope of this question, but it also includes detailed instructions on how to accomplish using hash functions as well https://prateekvjoshi.com/2014/06/05/using-hash-function-in-c-for-user-defined-classes/

namespace std {

  template<>
  struct hash<my_type> {
    size_t operator()(const my_type& k) {
      // Do your hash function here
      ...
    }
  };

}
  1. So then to implement a hashtable using your new hash function, you just have to create a std::map or std::unordered_map just like you would normally do and use my_type as the key, the standard library will automatically use the hash function you defined before (in step 2) to hash your keys.
#include <unordered_map>

int main() {
  std::unordered_map<my_type, other_type> my_map;
}

How to escape the equals sign in properties files

Moreover, Please refer to load(Reader reader) method from Property class on javadoc

In load(Reader reader) method documentation it says

The key contains all of the characters in the line starting with the first non-white space character and up to, but not including, the first unescaped '=', ':', or white space character other than a line terminator. All of these key termination characters may be included in the key by escaping them with a preceding backslash character; for example,

\:\=

would be the two-character key ":=". Line terminator characters can be included using \r and \n escape sequences. Any white space after the key is skipped; if the first non-white space character after the key is '=' or ':', then it is ignored and any white space characters after it are also skipped. All remaining characters on the line become part of the associated element string; if there are no remaining characters, the element is the empty string "". Once the raw character sequences constituting the key and element are identified, escape processing is performed as described above.

Hope that helps.

How to count the number of observations in R like Stata command count

You can also use the filter function from the dplyr package which returns rows with matching conditions.

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2

Sieve of Eratosthenes - Finding Primes Python

Here's a version that's a bit more memory-efficient (and: a proper sieve, not trial divisions). Basically, instead of keeping an array of all the numbers, and crossing out those that aren't prime, this keeps an array of counters - one for each prime it's discovered - and leap-frogging them ahead of the putative prime. That way, it uses storage proportional to the number of primes, not up to to the highest prime.

import itertools

def primes():

    class counter:
        def __init__ (this,  n): this.n, this.current,  this.isVirgin = n, n*n,  True
            # isVirgin means it's never been incremented
        def advancePast (this,  n): # return true if the counter advanced
            if this.current > n:
                if this.isVirgin: raise StopIteration # if this is virgin, then so will be all the subsequent counters.  Don't need to iterate further.
                return False
            this.current += this.n # pre: this.current == n; post: this.current > n.
            this.isVirgin = False # when it's gone, it's gone
            return True

    yield 1
    multiples = []
    for n in itertools.count(2):
        isPrime = True
        for p in (m.advancePast(n) for m in multiples):
            if p: isPrime = False
        if isPrime:
            yield n
            multiples.append (counter (n))

You'll note that primes() is a generator, so you can keep the results in a list or you can use them directly. Here's the first n primes:

import itertools

for k in itertools.islice (primes(),  n):
    print (k)

And, for completeness, here's a timer to measure the performance:

import time

def timer ():
    t,  k = time.process_time(),  10
    for p in primes():
        if p>k:
            print (time.process_time()-t,  " to ",  p,  "\n")
            k *= 10
            if k>100000: return

Just in case you're wondering, I also wrote primes() as a simple iterator (using __iter__ and __next__), and it ran at almost the same speed. Surprised me too!

Multiple actions were found that match the request in Web Api

In Web API (by default) methods are chosen based on a combination of HTTP method and route values.

MyVm looks like a complex object, read by formatter from the body so you have two identical methods in terms of route data (since neither of them has any parameters from the route) - which makes it impossible for the dispatcher (IHttpActionSelector) to match the appropriate one.

You need to differ them by either querystring or route parameter to resolve ambiguity.

Where can I find documentation on formatting a date in JavaScript?

JsSimpleDateFormat is a library that can format the date object and parse the formatted string back to Date object. It uses the Java format (SimpleDateFormat class). The name of months and days can be localized.

Example:

var sdf = new JsSimpleDateFormat("EEEE, MMMM dd, yyyy");
var formattedString = sdf.format(new Date());
var dateObject = sdf.parse("Monday, June 29, 2009");

What's a simple way to get a text input popup dialog box on an iPhone

To make sure you get the call backs after the user enters text, set the delegate inside the configuration handler. textField.delegate = self

Swift 3 & 4 (iOS 10 - 11):

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
    textField.placeholder = "Enter text:"
    textField.isSecureTextEntry = true // for password input
})
self.present(alert, animated: true, completion: nil)

In Swift (iOS 8-10):

enter image description here

override func viewDidAppear(animated: Bool) {
    var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
    alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Enter text:"
        textField.secureTextEntry = true
        })
    self.presentViewController(alert, animated: true, completion: nil)
}

In Objective-C (iOS 8):

- (void) viewDidLoad 
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Click" style:UIAlertActionStyleDefault handler:nil]];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Enter text:";
        textField.secureTextEntry = YES;
    }];
    [self presentViewController:alert animated:YES completion:nil];
}

FOR iOS 5-7:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"INPUT BELOW" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];

enter image description here


NOTE: Below doesn't work with iOS 7 (iOS 4 - 6 Works)

Just to add another version.

UIAlert With UITextField

- (void)viewDidLoad{

    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Preset Saving..." message:@"Describe the Preset\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
    UITextField *textField = [[UITextField alloc] init];
    [textField setBackgroundColor:[UIColor whiteColor]];
    textField.delegate = self;
    textField.borderStyle = UITextBorderStyleLine;
    textField.frame = CGRectMake(15, 75, 255, 30);
    textField.placeholder = @"Preset Name";
    textField.keyboardAppearance = UIKeyboardAppearanceAlert;
    [textField becomeFirstResponder];
    [alert addSubview:textField];

}

then I call [alert show]; when I want it.

The method that goes along

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {         
    NSString* detailString = textField.text;
    NSLog(@"String is: %@", detailString); //Put it on the debugger
    if ([textField.text length] <= 0 || buttonIndex == 0){ 
        return; //If cancel or 0 length string the string doesn't matter
    }
    if (buttonIndex == 1) {
        ...

    }
}

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

This is the normal behavior and the reason is that your sqlCommandHandlerService.persist method needs a TX when being executed (because it is marked with @Transactional annotation). But when it is called inside processNextRegistrationMessage, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist method, it causes TX to be set to rollBackOnly (even if you catch the exception in the caller and ignore it).

To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.

Update; Read this!

Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.


EDIT Link to current version of the documentation

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

Fill in the service layer with the model and then send it to the view. For example: ViewItem=ModelItem.ToString().Substring(0,100);

How to auto-size an iFrame?

My workaround is to set the iframe the height/width well over any anticipated source page size in CSS & the background property to transparent.

In the iframe set allow-transparency to true and scrolling to no.

The only thing visible will be whatever source file you use. It works in IE8, Firefox 3, & Safari.

How can building a heap be O(n) time complexity?

Intuitively:

"The complexity should be O(nLog n)... for each item we "heapify", it has the potential to have to filter down once for each level for the heap so far (which is log n levels)."

Not quite. Your logic does not produce a tight bound -- it over estimates the complexity of each heapify. If built from the bottom up, insertion (heapify) can be much less than O(log(n)). The process is as follows:

( Step 1 ) The first n/2 elements go on the bottom row of the heap. h=0, so heapify is not needed.

( Step 2 ) The next n/22 elements go on the row 1 up from the bottom. h=1, heapify filters 1 level down.

( Step i ) The next n/2i elements go in row i up from the bottom. h=i, heapify filters i levels down.

( Step log(n) ) The last n/2log2(n) = 1 element goes in row log(n) up from the bottom. h=log(n), heapify filters log(n) levels down.

NOTICE: that after step one, 1/2 of the elements (n/2) are already in the heap, and we didn't even need to call heapify once. Also, notice that only a single element, the root, actually incurs the full log(n) complexity.


Theoretically:

The Total steps N to build a heap of size n, can be written out mathematically.

At height i, we've shown (above) that there will be n/2i+1 elements that need to call heapify, and we know heapify at height i is O(i). This gives:

enter image description here

The solution to the last summation can be found by taking the derivative of both sides of the well known geometric series equation:

enter image description here

Finally, plugging in x = 1/2 into the above equation yields 2. Plugging this into the first equation gives:

enter image description here

Thus, the total number of steps is of size O(n)

Simple and clean way to convert JSON string to Object in Swift

Use swiftyJson swiftyJson

platform :ios, '8.0'
use_frameworks!

target 'MyApp' do
pod 'SwiftyJSON', '~> 4.0'
end

Usage

import SwiftyJSON

let json = JSON(jsonObject)

let id = json["Id"].intValue
let name = json["Name"].stringValue
let lat = json["Latitude"].stringValue
let long = json["Longitude"].stringValue
let address = json["Address"].stringValue
            
print(id)
print(name)
print(lat)
print(long)
print(address)

Custom "confirm" dialog in JavaScript?

SweetAlert

You should take a look at SweetAlert as an option to save some work. It's beautiful from the default state and is highly customizable.

Confirm Example

sweetAlert(
  {
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",   
    showCancelButton: true,   
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!"
  }, 
  deleteIt()
);

Sample Alert

Angular-cli from css to scss

A quick and easy way to perform the migration is to use the schematic NPM package schematics-scss-migrate. this package rename all css to scss file :

ng add schematics-scss-migrate

https://github.com/Teebo/scss-migrate#readme

Watermark / hint text / placeholder TextBox

There is an article on CodeProject on how to do it in "3 lines of XAML".

<Grid Background="{StaticResource brushWatermarkBackground}">
  <TextBlock Margin="5,2" Text="Type something..."
             Foreground="{StaticResource brushForeground}"
             Visibility="{Binding ElementName=txtUserEntry, Path=Text.IsEmpty,
                          Converter={StaticResource BooleanToVisibilityConverter}}" />
  <TextBox Name="txtUserEntry" Background="Transparent"
           BorderBrush="{StaticResource brushBorder}" />
</Grid>

Ok, well it might not be 3 lines of XAML formatted, but it is pretty simple.

One thing to note though, is that it uses a non-standard extension method on the Text property, called "IsEmpty". You need to implement this yourself, however the article doesn't seem to mention that.

How to change the commit author for one specific commit?

You can change author of last commit using the command below.

git commit --amend --author="Author Name <[email protected]>"

However, if you want to change more than one commits author name, it's a bit tricky. You need to start an interactive rebase then mark commits as edit then amend them one by one and finish.

Start rebasing with git rebase -i. It will show you something like this.

https://monosnap.com/file/G7sdn66k7JWpT91uiOUAQWMhPrMQVT.png

Change the pick keyword to edit for the commits you want to change the author name.

https://monosnap.com/file/dsq0AfopQMVskBNknz6GZZwlWGVwWU.png

Then close the editor. For the beginners, hit Escape then type :wq and hit Enter.

Then you will see your terminal like nothing happened. Actually you are in the middle of an interactive rebase. Now it's time to amend your commit's author name using the command above. It will open the editor again. Quit and continue rebase with git rebase --continue. Repeat the same for the commit count you want to edit. You can make sure that interactive rebase finished when you get the No rebase in progress? message.

How do I find duplicates across multiple columns?

You have to self join stuff and match name and city. Then group by count.

select 
   s.id, s.name, s.city 
from stuff s join stuff p ON (
   s.name = p.city OR s.city = p.name
)
group by s.name having count(s.name) > 1

How do I copy the contents of one stream to another?

From .NET 4.5 on, there is the Stream.CopyToAsync method

input.CopyToAsync(output);

This will return a Task that can be continued on when completed, like so:

await input.CopyToAsync(output)

// Code from here on will be run in a continuation.

Note that depending on where the call to CopyToAsync is made, the code that follows may or may not continue on the same thread that called it.

The SynchronizationContext that was captured when calling await will determine what thread the continuation will be executed on.

Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).

From .NET 4.0 on, there's is the Stream.CopyTo method

input.CopyTo(output);

For .NET 3.5 and before

There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length? Because that Length may not be available! From the docs:

If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.

SQL Server 2008 R2 can't connect to local database in Management Studio

I had this problem. My solution is: change same password of other in windowns. Restart Service (check logon in tab Service SQL).

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I'm using Juno 4.2 with latest spring, maven plugin and JDK1.6.0_25.

I faced same issue and here is my fix that make default after each Eclipse restart:

  1. List item
  2. Right-click on the maven project
  3. Java Build Path
  4. Libraries tab
  5. Select current wrong JRE item
  6. Click Edit
  7. Select the last option (Workspace default JRE (jdk1.6.0_25)

SimpleXml to string

Actually asXML() converts the string into xml as it name says:

<id>5</id>

This will display normally on a web page but it will cause problems when you matching values with something else.

You may use strip_tags function to get real value of the field like:

$newString = strip_tags($xml->asXML());

PS: if you are working with integers or floating numbers, you need to convert it into integer with intval() or floatval().

$newNumber = intval(strip_tags($xml->asXML()));

CSS, Images, JS not loading in IIS

This issue occurs when IIS does not render the static contents like your JS, CSS, Image files.

To resolve this issue, you need to follow the below steps:

GO to Control Panel > Turn Windows features on or off > Internet Information Services > World Wide Web Services > Common HTTP Features > Static Content.

Ensure that static content is turned on.

Bingo. And you are done. Hard-reload the page and you will be able to see all the static contents.

How do MySQL indexes work?

I want to add my 2 cents. I am far from being a database expert, but I've recently read up a bit on this topic; enough for me to try and give an ELI5. So, here's may layman's explanation.


I understand it as such that an index is like a mini-mirror of your table, pretty much like an associative array. If you feed it with a matching key then you can just jump to that row in one "command".

But if you didn't have that index / array, the query interpreter must use a for-loop to go through all rows and check for a match (the full-table scan).

Having an index has the "downside" of extra storage (for that mini-mirror), in exchange for the "upside" of looking up content faster.

Note that (in dependence of your db engine) creating primary, foreign or unique keys automatically sets up a respective index as well. That same principle is basically why and how those keys work.

Directory Chooser in HTML page

Try this, I think it will work for you:

<input type="file" webkitdirectory directory multiple/>

You can find the demo of this at https://plus.google.com/+AddyOsmani/posts/Dk5UhZ6zfF3 , and if you need further information you can find it here.

Disable a textbox using CSS

Going further on Pekka's answer, I had a style "style1" on some of my textboxes. You can create a "style1[disabled]" so you style only the disabled textboxes using "style1" style:

.style1[disabled] { ... }

Worked ok on IE8.

How to remove underline from a name on hover

You can use CSS under legend.green-color a:hover to do it.

legend.green-color a:hover {
    color:green;
    text-decoration:none;
}

Threading pool similar to the multiprocessing Pool?

For something very simple and lightweight (slightly modified from here):

from Queue import Queue
from threading import Thread


class Worker(Thread):
    """Thread executing tasks from a given tasks queue"""
    def __init__(self, tasks):
        Thread.__init__(self)
        self.tasks = tasks
        self.daemon = True
        self.start()

    def run(self):
        while True:
            func, args, kargs = self.tasks.get()
            try:
                func(*args, **kargs)
            except Exception, e:
                print e
            finally:
                self.tasks.task_done()


class ThreadPool:
    """Pool of threads consuming tasks from a queue"""
    def __init__(self, num_threads):
        self.tasks = Queue(num_threads)
        for _ in range(num_threads):
            Worker(self.tasks)

    def add_task(self, func, *args, **kargs):
        """Add a task to the queue"""
        self.tasks.put((func, args, kargs))

    def wait_completion(self):
        """Wait for completion of all the tasks in the queue"""
        self.tasks.join()

if __name__ == '__main__':
    from random import randrange
    from time import sleep

    delays = [randrange(1, 10) for i in range(100)]

    def wait_delay(d):
        print 'sleeping for (%d)sec' % d
        sleep(d)

    pool = ThreadPool(20)

    for i, d in enumerate(delays):
        pool.add_task(wait_delay, d)

    pool.wait_completion()

To support callbacks on task completion you can just add the callback to the task tuple.

How do I solve the INSTALL_FAILED_DEXOPT error?

There's no generic solution, you have to find the error reported on your Logcat to be able to figure it out. Sometimes it's a class that can't be 'dexed' due to an usage of a class not available on the specified Target API for instance. Or it could be a class that you're making reference in your code, but the library that it is in is not being packaged.

Updating .class file in jar

Editing properties/my_app.properties file inside jar:

"zip -u /var/opt/my-jar-with-dependencies.jar properties/my_app.properties". Basically "zip -u <source> <dest>", where dest is relative to the jar extract folder.