Programs & Examples On #Subview

subview is an abstract representation of a nested hierarchy of views in a MVC framework

Bringing a subview to be in front of all other views

Let me make a conclusion. In Swift 5

You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.

let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)

You can also set the zPosition. But the drawback is that you can not change the gesture responding order.

view.layer.zPosition = 1

Remove all subviews?

In Swift you can use a functional approach like this:

view.subviews.forEach { $0.removeFromSuperview() }

As a comparison, the imperative approach would look like this:

for subview in view.subviews {
    subview.removeFromSuperview()
}

These code snippets only work in iOS / tvOS though, things are a little different on macOS.

Match multiline text using regular expression

This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find() and matches() methods. find() succeeds if a match can be found anywhere in the target string, while matches() expects the regex to match the entire string.

Pattern p = Pattern.compile("xyz");

Matcher m = p.matcher("123xyzabc");
System.out.println(m.find());    // true
System.out.println(m.matches()); // false

Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true

Furthermore, MULTILINE doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^ and $.

Normally ^ matches the very beginning of the target string, and $ matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^ and $ to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.

So forget about what MULTILINE means and just remember what it does: changes the behavior of the ^ and $ anchors. DOTALL mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.

In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.

How do you read a file into a list in Python?

hdl = open("C:/name/MyDocuments/numbers", 'r')
milist = hdl.readlines()
hdl.close()

How to set a dropdownlist item as selected in ASP.NET?

dropdownlist.ClearSelection(); //making sure the previous selection has been cleared
dropdownlist.Items.FindByValue(value).Selected = true;

What does "implements" do on a class?

An interface defines a simple contract of methods all implementing classes must implement. When a class implements an interface, it must provide implementations for all its methods.

I guess the poster assumes a certain level of knowledge about the language.

SQL join on multiple columns in same tables

You want to join on condition 1 AND condition 2, so simply use the AND keyword as below

ON a.userid = b.sourceid AND a.listid = b.destinationid;

Add regression line equation and R^2 on graph

Here is one solution

# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA

lm_eqn <- function(df){
    m <- lm(y ~ x, df);
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
         list(a = format(unname(coef(m)[1]), digits = 2),
              b = format(unname(coef(m)[2]), digits = 2),
             r2 = format(summary(m)$r.squared, digits = 3)))
    as.character(as.expression(eq));
}

p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)

EDIT. I figured out the source from where I picked this code. Here is the link to the original post in the ggplot2 google groups

Output

Android: How can I print a variable on eclipse console?

If the code you're testing is relatively simple then you can just create a regular Java project in the Package Explorer and copy the code across, run it and fix it there, then copy it back into your Android project.

The fact that System.out is redirected is pretty annoying for quickly testing simple methods, but that's the easiest solution I've found, rather than having to run the device emulator just to see if a regular expression works.

Android getActivity() is undefined

You want getActivity() inside your class. It's better to use

yourclassname.this.getActivity()

Try this. It's helpful for you.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

When you use the url tag you should use quotes for string literals, for example:

{% url 'products' %}

At the moment product is treated like a variable and evaluates to '' in the error message.

Can I override and overload static methods in Java?

As any static method is part of class not instance so it is not possible to override static method

Calculating sum of repeated elements in AngularJS ng-repeat

Taking Vaclav's answer and making it more Angular-like:

angular.module('myApp').filter('total', ['$parse', function ($parse) {
    return function (input, property) {
        var i = input instanceof Array ? input.length : 0,
            p = $parse(property);

        if (typeof property === 'undefined' || i === 0) {
            return i;
        } else if (isNaN(p(input[0]))) {
            throw 'filter total can count only numeric values';
        } else {
            var total = 0;
            while (i--)
                total += p(input[i]);
            return total;
        }
    };
}]);

This gives you the benefit of even accessing nested and array data:

{{data | total:'values[0].value'}}

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

In order to better understand [] and new Array():

> []
  []
> new Array()
  []
> [] == []
  false
> [] === []
  false
> new Array() == new Array()
  false
> new Array() === new Array()
  false
> typeof ([])
  "object"
> typeof (new Array())
  "object"
> [] === new Array()
  false
> [] == new Array()
  false

The above result is from Google Chrome console on Windows 7.

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

I had to run my commands in the one and same terminal, not seperately.

nohup sudo Xvfb :10 -ac
export DISPLAY=:10
java -jar vendor/se/selenium-server-standalone/bin/selenium-server-standalone.jar -Dwebdriver.chrome.bin="/usr/bin/google-chrome" -Dwebdriver.chrome.driver="vendor/bin/chromedriver"

Is there a foreach loop in Go?

You can in fact use range without referencing it's return values by using for range against your type:

arr := make([]uint8, 5)
i,j := 0,0
for range arr {
    fmt.Println("Array Loop",i)
    i++
}

for range "bytes" {
    fmt.Println("String Loop",j)
    j++
}

https://play.golang.org/p/XHrHLbJMEd

C#: How would I get the current time into a string?

Be careful when accessing DateTime.Now twice, as it's possible for the calls to straddle midnight and you'll get wacky results on rare occasions and be left scratching your head.

To be safe, you should assign DateTime.Now to a local variable first if you're going to use it more than once:

var now = DateTime.Now;
var time = now.ToString("hh:mm:ss tt");
var date = now.ToString("MM/dd/yy");

Note the use of lower case "hh" do display hours from 00-11 even in the afternoon, and "tt" to show AM/PM, as the question requested. If you want 24 hour clock 00-23, use "HH".

Combining border-top,border-right,border-left,border-bottom in CSS

No you can't set them as single one for example if you have div{ border-top: 2px solid red; border-right: 2px solid red; border-bottom: 2px solid red; border-left: 2px solid red; } same properties for all fours then you can set them in single line

div{border:2px solid red;}

How to export datagridview to excel using vb.net?

Excel Method

This method is different than many you will see. Others use a loop to write each cell and write the cells with text data type.

This method creates an object array from a DataTable or DataGridView and then writes the array to Excel. This means I can write to Excel without a loop and retain data types.

I extracted this from my library and I think I changed it enough to work with this code only, but more minor tweaking might be necessary. If you get errors just let me know and I'll correct them for you. Normally, I create an instance of my class and call these methods. If you would like to use my library then use this link to download it and if you need help just let me know.
https://zomp.co/Files.aspx?ID=zExcel


After copying the code to your solution you will use it like this.

In your button code add this and change the names to your controls.

WriteDataGrid("Sheet1", grid)

To open your file after exporting use this line

System.Diagnostics.Process.Start("The location and filename of your file")

In the WriteArray method you'll want to change the line that saves the workbook to where you want to save it. Probably makes sense to add this as a parameter.

wb.SaveAs("C:\MyWorkbook.xlsx")


Public Function WriteArray(Sheet As String, ByRef ObjectArray As Object(,)) As String
    Try
        Dim xl As Excel.Application = New Excel.Application
        Dim wb As Excel.Workbook = xl.Workbooks.Add()
        Dim ws As Excel.Worksheet = wb.Worksheets.Add()
        ws.Name = Sheet
        Dim range As Excel.Range = ws.Range("A1").Resize(ObjectArray.GetLength(0), ObjectArray.GetLength(1))
        range.Value = ObjectArray

        range = ws.Range("A1").Resize(1, ObjectArray.GetLength(1) - 1)

        range.Interior.Color = RGB(0, 70, 132)  'Con-way Blue
        range.Font.Color = RGB(Drawing.Color.White.R, Drawing.Color.White.G, Drawing.Color.White.B)
        range.Font.Bold = True
        range.WrapText = True

        range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
        range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter

        range.Application.ActiveWindow.SplitColumn = 0
        range.Application.ActiveWindow.SplitRow = 1
        range.Application.ActiveWindow.FreezePanes = True

        wb.SaveAs("C:\MyWorkbook.xlsx")
        wb.CLose()
        xl.Quit()
        xl = Nothing
        wb = Nothing
        ws  = Nothing
        range = Nothing
        ReleaseComObject(xl)
        ReleaseComObject(wb)
        ReleaseComObject(ws)
        ReleaseComObject(range)

        Return ""
    Catch ex As Exception
        Return "WriteArray()" & Environment.NewLine & Environment.NewLine & ex.Message
    End Try
End Function

Public Function WriteDataGrid(SheetName As String, ByRef dt As DataGridView) As String
        Try
            Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
            For c As Integer = 0 To dt.Columns.Count - 1
                l(0, c) = dt.Columns(c).HeaderText
            Next

            For r As Integer = 1 To dt.Rows.Count
                For c As Integer = 0 To dt.Columns.Count - 1
                    l(r, c) = dt.Rows(r - 1).Cells(c)
                Next
            Next

            Dim errors As String = WriteArray(SheetName, l)
            If errors <> "" Then
                Return errors
            End If

            Return ""
        Catch ex As Exception
            Return "WriteDataGrid()" & Environment.NewLine & Environment.NewLine & ex.Message
        End Try
    End Function


 Public Function WriteDataTable(SheetName As String, ByRef dt As DataTable) As String
        Try
            Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
            For c As Integer = 0 To dt.Columns.Count - 1
                l(0, c) = dt.Columns(c).ColumnName
            Next

            For r As Integer = 1 To dt.Rows.Count
                For c As Integer = 0 To dt.Columns.Count - 1
                    l(r, c) = dt.Rows(r - 1).Item(c)
                Next
            Next

            Dim errors As String = WriteArray(SheetName, l)
            If errors <> "" Then
                Return errors
            End If

            Return ""
        Catch ex As Exception
            Return "WriteDataTable()" & Environment.NewLine & Environment.NewLine & ex.Message
        End Try
    End Function

I actually don't use this method in my Database program because it's a slow method when you have a lot of rows/columns. I instead create a CSV from the DataGridView. Writing to Excel with Excel Automation is only useful if you need to format the data and cells otherwise you should use CSV. You can use the code after the image for CSV export.


CSV Method

Private Sub DataGridToCSV(ByRef dt As DataGridView, Qualifier As String)  
        Dim TempDirectory As String = "A temp Directory"  
        System.IO.Directory.CreateDirectory(TempDirectory)
        Dim oWrite As System.IO.StreamWriter
        Dim file As String = System.IO.Path.GetRandomFileName & ".csv"
        oWrite = IO.File.CreateText(TempDirectory & "\" & file)

        Dim CSV As StringBuilder = New StringBuilder()

        Dim i As Integer = 1
        Dim CSVHeader As StringBuilder = New StringBuilder()
        For Each c As DataGridViewColumn In dt.Columns
            If i = 1 Then
                CSVHeader.Append(Qualifier & c.HeaderText.ToString() & Qualifier)
            Else
                CSVHeader.Append("," & Qualifier & c.HeaderText.ToString() & Qualifier)
            End If
            i += 1
        Next

        'CSV.AppendLine(CSVHeader.ToString())
        oWrite.WriteLine(CSVHeader.ToString())
        oWrite.Flush()

        For r As Integer = 0 To dt.Rows.Count - 1

            Dim CSVLine As StringBuilder = New StringBuilder()
            Dim s As String = ""
            For c As Integer = 0 To dt.Columns.Count - 1
                If c = 0 Then
                    'CSVLine.Append(Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
                    s = s & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
                Else
                    'CSVLine.Append("," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
                    s = s & "," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
                End If

            Next
            oWrite.WriteLine(s)
            oWrite.Flush()
            'CSV.AppendLine(CSVLine.ToString())
            'CSVLine.Clear()
        Next

        'oWrite.Write(CSV.ToString())

        oWrite.Close()
        oWrite = Nothing    

        System.Diagnostics.Process.Start(TempDirectory & "\" & file)   

        GC.Collect()

    End Sub

Entity framework linq query Include() multiple children entities

You might find this article of interest which is available at codeplex.com.

The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.

Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.

How to reverse an std::string?

Try

string reversed(temp.rbegin(), temp.rend());

EDIT: Elaborating as requested.

string::rbegin() and string::rend(), which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator* to dereference to an element, i.e. a character of the string, and operator++ to advance to the "next" element), such that rbegin() points to the last character of the string, rend() points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).

Finally, the constructor we are passing these iterators into is a string constructor of the form:

template <typename Iterator>
string(Iterator first, Iterator last);

which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.

Force "portrait" orientation mode

I think android:screenOrientation="portrait" can be used for individual activities. So use that attribute in <activity> tag like :

<activity android:name=".<Activity Name>"
    android:label="@string/app_name" 
    android:screenOrientation="portrait">
   ...         
</activity>

How to check if field is null or empty in MySQL?

SELECT * FROM ( 
    SELECT  2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'')  AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION 
    FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
    JOIN acc_head L ON(D.ACC_ID=L.ID) 
    JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)  
    WHERE T.CMPID=',COMPANYID,' AND  d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
    ORDER BY CAST(ENTDT AS DATE)) AS ta

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

Hiding user input on terminal in Linux script

A bit different from (but mostly like) @lesmana's answer

stty -echo
read password
stty echo

simply: hide echo do your stuff show echo

How to install mongoDB on windows?

Install MongoDB Community Edition for Windows.

1.Now go to Download Center.

  1. The Download Center should display the Current Stable Release for Windows

  2. Click Download (msi) and run it

  3. When you go through You can choose either the Complete or Custom setup type. Select Complete Setup.

Starting MongoDB server from the Command Prompt

1.Add this path to environmental variables

“C:\ProgramFiles\MongoDB\Server\4.0\bin” For those who struggle to setup environmental variable please follow this steps

  • Windows 10 and Windows 8

  • In Search, search for and then select: System (Control Panel)

  • Click the Advanced system settings link.

  • Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit.

  • If the PATH environment variable does not exist, click New.

  • In the Edit System Variable (or New System Variable) window, specify the value of the PATH as “C:\ProgramFiles\MongoDB\Server\4.0\bin”environment variable.

  • Click OK.

  • Close all remaining windows by clicking OK.

  • Now create MongoDB Data Directory MongoDB requires a data directory to store all data. Open Command Prompt and paste below

md "C:\data\db" "C:\data\log"

3.Lets point server to your database directory.Type below code

mongod --dbpath="c:\data\db"

4.Now lets connect to MongoDB Type below code

mongo

5.If it is working properly Command prompt will show

[initandlisten] waiting for connections

Bingo!! You are done, Apparently it is bit confusing to use CLI, well MongoDB introduced a GUI which you can see the actual data ,

To use mongoDB GUI version Above steps must have been performed

  1. Now go to Download Center. Download MongoDb Compass ,a GUI for MongoDB
  2. Install it and open

You can see the hostname : localhost and port : 27017.

Whenever you wanted to connect to mongoDB Server , You have to open Command prompt

Type

mongod

then again start a new Command prompt and type

mongo

Keep ‘em all settings as it is in mongoDB Compass. Now click connect ,

You are in !! Easy .. isn’t it?

How to test that a registered variable is not empty?

- name: set pkg copy dir name
  set_fact:
    PKG_DIR: >-
      {% if ansible_os_family == "RedHat" %}centos/*.rpm
      {%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
      {%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
      {%- else %}{%- endif %}

Connecting to remote MySQL server using PHP

I just solved this kind of a problem. What I've learned is:

  1. you'll have to edit the my.cnf and set the bind-address = your.mysql.server.address under [mysqld]
  2. comment out skip-networking field
  3. restart mysqld
  4. check if it's running

    mysql -u root -h your.mysql.server.address –p 
    
  5. create a user (usr or anything) with % as domain and grant her access to the database in question.

    mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
    mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
    
  6. open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)

  7. restart firewall/iptables

you should be able to now connect mysql server form your client server php script.

How do I subtract minutes from a date in javascript?

You can also use get and set minutes to achieve it:

var endDate = somedate;

var startdate = new Date(endDate);

var durationInMinutes = 20;

startdate.setMinutes(endDate.getMinutes() - durationInMinutes);

Java JSON serialization - best practice

Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.

How to sort pandas data frame using values from several columns?

DataFrame.sort is deprecated; use DataFrame.sort_values.

>>> df.sort_values(['c1','c2'], ascending=[False,True])
   c1   c2
0   3   10
3   2   15
1   2   30
4   2  100
2   1   20
>>> df.sort(['c1','c2'], ascending=[False,True])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ampawake/anaconda/envs/pseudo/lib/python2.7/site-packages/pandas/core/generic.py", line 3614, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'sort'

Navigate to another page with a button in angular 2

Having the router link on the button seems to work fine for me:

<button class="nav-link" routerLink="/" (click)="hideMenu()">
     <i class="fa fa-home"></i> 
     <span>Home</span>
</button>

How to include vars file in a vars file with ansible?

I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :

cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or 
#cat release_vars.yml >> vars.yml
mvn ....

Creating a LINQ select from multiple tables

If you don't want to use anonymous types b/c let's say you're passing the object to another method, you can use the LoadWith load option to load associated data. It requires that your tables are associated either through foreign keys or in your Linq-to-SQL dbml model.

db.DeferredLoadingEnabled = false;
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<ObjectPermissions>(op => op.Pages)
db.LoadOptions = dlo;

var pageObject = from op in db.ObjectPermissions
         select op;

// no join needed

Then you can call

pageObject.Pages.PageID

Depending on what your data looks like, you'd probably want to do this the other way around,

DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Pages>(p => p.ObjectPermissions)
db.LoadOptions = dlo;

var pageObject = from p in db.Pages
                 select p;

// no join needed

var objectPermissionName = pageObject.ObjectPermissions.ObjectPermissionName;

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Here is what I did

private void myEvent_Handler(object sender, SomeEvent e)
{
  // I dont know how many times this event will fire
  Task t = new Task(() =>
  {
    if (something == true) 
    {
        DoSomething(e);  
    }
  });
  t.RunSynchronously();
}

working great and not blocking UI thread

Set Date in a single line

Calendar has a set() method that can set the year, month, and day-of-month in one call:

myCal.set( theYear, theMonth, theDay );

UITableView, Separator color where to set?

Now you should be able to do it directly in the IB.

Not sure though, if this was available when the question was posted originally.

enter image description here

Pass arguments into C program from command line

You could use getopt.

 #include <ctype.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int
 main (int argc, char **argv)
 {
   int bflag = 0;
   int sflag = 0;
   int index;
   int c;

   opterr = 0;

   while ((c = getopt (argc, argv, "bs")) != -1)
     switch (c)
       {
       case 'b':
         bflag = 1;
         break;
       case 's':
         sflag = 1;
         break;
       case '?':
         if (isprint (optopt))
           fprintf (stderr, "Unknown option `-%c'.\n", optopt);
         else
           fprintf (stderr,
                    "Unknown option character `\\x%x'.\n",
                    optopt);
         return 1;
       default:
         abort ();
       }

   printf ("bflag = %d, sflag = %d\n", bflag, sflag);

   for (index = optind; index < argc; index++)
     printf ("Non-option argument %s\n", argv[index]);
   return 0;
 }

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

How to find which git branch I am on when my disk is mounted on other server

Our git repo disk is mounted on AIX box to do BUILD.

It sounds like you mounted the drive on which the git repository is stored on another server, and you are asking how to modify that. If that is the case, this is a bad idea.

The build server should have its own copy of the git repository, and it will be locally managed by git on the build server. The build server's repository will be connected to the "main" git repository with a "remote", and you can issue the command git pull to update the local repository on the build server.

If you don't want to go to the trouble of setting up SSH or a gitolite server or something similar, you can use a file path as the "remote" location. So you could continue to mount the Linux server's file system on the build server, but instead of running the build out of that mounted path, clone the repository into another folder and run it from there.

Why use Select Top 100 Percent?

Just try this, it explains it pretty much itself. You can't create a view with an ORDER BY except if...

CREATE VIEW v_Test
         AS
           SELECT name
             FROM sysobjects
         ORDER BY name
        GO

Msg 1033, Level 15, State 1, Procedure TestView, Line 5 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

Trigger change event of dropdown

alternatively you can put onchange attribute on the dropdownlist itself, that onchange will call certain jquery function like this.

<input type="dropdownlist" onchange="jqueryFunc()">

<script type="text/javascript">
$(function(){
    jqueryFunc(){
        //something goes here
    }
});
</script>

hope this one helps you, and please note that this code is just a rough draft, not tested on any ide. thanks

Implement a loading indicator for a jQuery AJAX call

This is how I got it working with loading remote content that needs to be refreshed:

$(document).ready(function () {
    var loadingContent = '<div class="modal-header"><h1>Processing...</h1></div><div class="modal-body"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>';

    // This is need so the content gets replaced correctly.
    $("#myModal").on("show.bs.modal", function (e) {
        $(this).find(".modal-content").html(loadingContent);        
        var link = $(e.relatedTarget);
        $(this).find(".modal-content").load(link.attr("href"));
    });    

    $("#myModal2").on("hide.bs.modal", function (e) {
        $(this).removeData('bs.modal');
    });
});

Basically, just replace the modal content while it's loading with a loading message. The content will then be replaced once it's finished loading.

in iPhone App How to detect the screen resolution of the device

CGRect screenBounds = [[UIScreen mainScreen] bounds];

That will give you the entire screen's resolution in points, so it would most typically be 320x480 for iPhones. Even though the iPhone4 has a much larger screen size iOS still gives back 320x480 instead of 640x960. This is mostly because of older applications breaking.

CGFloat screenScale = [[UIScreen mainScreen] scale];

This will give you the scale of the screen. For all devices that do not have Retina Displays this will return a 1.0f, while Retina Display devices will give a 2.0f and the iPhone 6 Plus (Retina HD) will give a 3.0f.

Now if you want to get the pixel width & height of the iOS device screen you just need to do one simple thing.

CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);

By multiplying by the screen's scale you get the actual pixel resolution.

A good read on the difference between points and pixels in iOS can be read here.

EDIT: (Version for Swift)

let screenBounds = UIScreen.main.bounds
let screenScale = UIScreen.main.scale
let screenSize = CGSize(width: screenBounds.size.width * screenScale, height: screenBounds.size.height * screenScale)

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

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

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

How to remove the Flutter debug banner?

  • If you are using Android Studio, you can find the option in the Flutter Inspector tab --> More Actions.

Android Studio

  • Or if you're using Dart DevTools, you can find the same button in the top right corner as well.

Dart DevTools

No Title Bar Android Theme

To Hide the Action Bar add the below code in Values/Styles

<style name="CustomActivityThemeNoActionBar" parent="@android:style/Theme.Holo.Light">
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

Then in your AndroidManifest.xml file add the below code in the required activity

<activity
        android:name="com.newbelievers.android.NBMenu"
        android:label="@string/title_activity_nbmenu"
        android:theme="@style/CustomActivityThemeNoActionBar">
</activity>

Is it possible to change javascript variable values while debugging in Google Chrome?

I was having the same issue, went to the 'About Google Chrome'->Help and it said I needed to restart my browser to get the latest updates.

I did this, and suddenly, I can now change local variables. Simply click the variable you want to edit in the Scope Variables window, and type in your new value.

I did notice some oddities though, that I had to step over some unrelated var assignments before I could alter the text in the right hand window (Scope Variables).

Insert array into MySQL database with PHP

You can not insert an array directly to MySQL as MySQL doesn't understand PHP data types. MySQL only understands SQL. So to insert an array into a MySQL database you have to convert it to a SQL statement. This can be done manually or by a library. The output should be an INSERT statement.

Update for PHP7

Since PHP 5.5 mysql_real_escape_string has been deprecated and as of PHP7 it has been removed. See: php.net's documentation on the new procedure.


Original answer:

Here is a standard MySQL insert statement.

INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)

If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet. Here is how your array is converted to this statement.

$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values  = implode(", ", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";

Remove Identity from a column in a table

Following script removes Identity field for a column named 'Id'

Hope it helps.

BEGIN TRAN
BEGIN TRY
    EXEC sp_rename '[SomeTable].[Id]', 'OldId';

    ALTER TABLE [SomeTable] ADD Id int NULL

    EXEC ('UPDATE [SomeTable] SET Id = OldId')

    ALTER TABLE [SomeTable] NOCHECK CONSTRAINT ALL

    ALTER TABLE [SomeTable] DROP CONSTRAINT [PK_constraintName];
    ALTER TABLE [SomeTable] DROP COLUMN OldId
    ALTER TABLE [SomeTable] ALTER COLUMN [Id] INTEGER NOT NULL
    ALTER TABLE [SomeTable] ADD CONSTRAINT PK_JobInfo PRIMARY KEY (Id)

    ALTER TABLE [SomeTable] CHECK CONSTRAINT ALL

    COMMIT TRAN
END TRY
BEGIN CATCH
    ROLLBACK TRAN   
    SELECT ERROR_MESSAGE ()
END CATCH

WCF timeout exception detailed investigation

If you havn't tried it already - encapsulate your Server-side WCF Operations in try/finally blocks, and add logging to ensure they are actually returning.

If those show that the Operations are completing, then my next step would be to go to a lower level, and look at the actual transport layer.

Wireshark or another similar packet capturing tool can be quite helpful at this point. I'm assuming this is running over HTTP on standard port 80.

Run Wireshark on the client. In the Options when you start the capture, set the capture filter to tcp http and host service.example.com - this will reduce the amount of irrelevant traffic.

If you can, modify your client to notify you the exact start time of the call, and the time when the timeout occurred. Or just monitor it closely.

When you get an error, then you can trawl through the Wireshark logs to find the start of the call. Right click on the first packet that has your client calling out on it (Should be something like GET /service.svc or POST /service.svc) and select Follow TCP Stream.

Wireshark will decode the entire HTTP Conversation, so you can ensure that WCF is actually sending back responses.

Cannot import XSSF in Apache POI

After trying multiple things,what really worked was: 1. downloading "poi" and "poi-ooxml" manually 2.Adding these d/w jars into "Maven Dependencies"

File size exceeds configured limit (2560000), code insight features not available

For those who don't know where to find the file they're talking about. On my machine (OSX) it is in:

  • PyCharm CE: /Applications/PyCharm CE.app/Contents/bin/idea.properties
  • WebStorm: /Applications/WebStorm.app/Contents/bin/idea.properties

Display a jpg image on a JPanel

You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.

how to properly display an iFrame in mobile safari

Don't scroll the IFrame page or its content, scroll the parent page. If you control the IFrame content, you can use the iframe-resizer library to turn the iframe element itself into a proper block level element, with a natural/correct/native height. Also, don't attempt to position (fixed, absolute) your iframe in the parent page, or present an iframe in a modal window, especially if it has form elements.

I also suspect that iOS Safari has a non-standards behavior that expands your iframe's height to its natural height, much like the iframe-resizer library will do for desktop browsers, which seem to render responsive iframe content at height 0px or 150px or some other not useful default. If you need to contrain width, try a max-width style inside the iframe.

Generate a Hash from string in Javascript

EDIT

based on my jsperf tests, the accepted answer is actually faster: http://jsperf.com/hashcodelordvlad

ORIGINAL

if anyone is interested, here is an improved ( faster ) version, which will fail on older browsers who lack the reduce array function.

hashCode = function(s){
  return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);              
}

one-liner arrow function version :

hashCode = s => s.split('').reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)

Toolbar overlapping below status bar

For me, the problem was that I copied something from an example and used

<item name="android:windowTranslucentStatus">true</item>

just removing this fixed my problem.

What is the default username and password in Tomcat?

Look in your conf/tomcat-users.xml. If there is nothing there, you'd have to configure it.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

I had a similar problem. But I was working with Episerver locally with ssl enabled. When I wasn't getting a

Server Error in '/' Application.

I was getting a Insecure connection error. In the end, for me, this post on PluralSight together with configuring the website urls, accordingly with the ssl link set up on the project's config, on Admin's Manage Website's screen solved the problem.

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

Hide/Show Column in an HTML Table

The following should do it:

$("input[type='checkbox']").click(function() {
    var index = $(this).attr('name').substr(2);
    $('table tr').each(function() { 
        $('td:eq(' + index + ')',this).toggle();
    });
});

This is untested code, but the principle is that you choose the table cell in each row that corresponds to the chosen index extracted from the checkbox name. You could of course limit the selectors with a class or an ID.

Can a unit test project load the target application's app.config file?

Whether you're using Team System Test or NUnit, the best practice is to create a separate Class Library for your tests. Simply adding an App.config to your Test project will automatically get copied to your bin folder when you compile.

If your code is reliant on specific configuration tests, the very first test I would write validates that the configuration file is available (so that I know I'm not insane) :

<configuration>
   <appSettings>
       <add key="TestValue" value="true" />
   </appSettings>
</configuration>

And the test:

[TestFixture]
public class GeneralFixture
{
     [Test]
     public void VerifyAppDomainHasConfigurationSettings()
     {
          string value = ConfigurationManager.AppSettings["TestValue"];
          Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
     }
}

Ideally, you should be writing code such that your configuration objects are passed into your classes. This not only separates you from the configuration file issue, but it also allows you to write tests for different configuration scenarios.

public class MyObject
{
     public void Configure(MyConfigurationObject config)
     {
          _enabled = config.Enabled;
     }

     public string Foo()
     {
         if (_enabled)
         {
             return "foo!";
         }
         return String.Empty;
     }

     private bool _enabled;
}

[TestFixture]
public class MyObjectTestFixture
{
     [Test]
     public void CanInitializeWithProperConfig()
     {
         MyConfigurationObject config = new MyConfigurationObject();
         config.Enabled = true;

         MyObject myObj = new MyObject();
         myObj.Configure(config);

         Assert.AreEqual("foo!", myObj.Foo());
     }
}

List files committed for a revision

To just get the list of the changed files with the paths, use

svn diff --summarize -r<rev-of-commit>:<rev-of-commit - 1>

For example:

svn diff --summarize -r42:41

should result in something like

M       path/to/modifiedfile
A       path/to/newfile

How to check if the key pressed was an arrow key in Java KeyListener?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code
    }

    repaint();
}

The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

PHP Session timeout

<?php 
session_start();

if (time()<$_SESSION['time']+10){
$_SESSION['time'] = time();
echo "welcome old user";
}

else{
session_destroy();
session_start();
$_SESSION['time'] = time();
echo "welcome new user";
}
?>

How to run the Python program forever?

sleep is a good way to avoid overload on the cpu

not sure if it's really clever, but I usually use

while(not sleep(5)):
    #code to execute

sleep method always returns None.

Detecting touch screen devices with Javascript

Wrote this for one of my sites and probably is the most foolproof solution. Especially since even Modernizr can get false positives on touch detection.

If you're using jQuery

$(window).one({
  mouseover : function(){
    Modernizr.touch = false; // Add this line if you have Modernizr
    $('html').removeClass('touch').addClass('mouse');
  } 
});

or just pure JS...

window.onmouseover = function(){ 
    window.onmouseover = null;
    document.getElementsByTagName("html")[0].className += " mouse";
}

Elegant way to report missing values in a data.frame

Another function that would help you look at missing data would be df_status from funModeling library

library(funModeling)

iris.2 is the iris dataset with some added NAs.You can replace this with your dataset.

df_status(iris.2)

This will give you the number and percentage of NAs in each column.

Limit results in jQuery UI Autocomplete

If the results come from a mysql query, it is more efficient to limit directly the mysql result:

select [...] from [...] order by [...] limit 0,10

where 10 is the max numbers of rows you want

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

Any constructor for any class as you know creates an object. So, the constructor should contain proper initialization code for its class. But if you have some class which extends another one (lets call it "parent") then constructor for the class cannot contain all the code needed for the initialization by definition (for example, you cannot define private fields of the parent). That's why constructor of the class has to call constructor of its parent. If you do not call it explicitly then the default parent constructor is called (which is without any parameter).

So, in your case, you can either implement default constructor in parent or directly call any constructor in the class.

How to create a Java / Maven project that works in Visual Studio Code?

This is not a particularly good answer as it explains how to run your java code n VS Code and not necessarily a Maven project, but it worked for me because I could not get around to doing the manual configuration myself. I decided to use this method instead since it is easier and faster.

Install VSCode (and for windows, set your environment variables), then install vscode:extension/vscjava.vscode-java-pack as detailed above, and then install the code runner extension pack, which basically sets up the whole process (in the background) as explained in the accepted answer above and then provides a play button to run your java code when you're ready.

This was all explained in this video.

Again, this is not the best solution, but if you want to cut to the chase, you may find this answer useful.

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

Found this solution which I liked: https://medium.com/@jakehasler/how-to-create-a-remote-git-repo-from-the-command-line-2d6857f49564

You first need to create a Github Personal Access Token

Open up your ~/.bash_profile or ~/.bashrc in your favorite text editor. Add the following line near the top of your file, where the rest of the export ‘ed variables are:

export GITHUB_API_TOKEN=<your-token-here>

Somewhere below, by your other bash functions, you can paste something similar to the following:

function new-git() {
    curl -X POST https://api.github.com/user/repos -u <your-username>:$GITHUB_API_TOKEN -d '{"name":"'$1'"}'
}

Now, whenever you’re creating a new project, you can run the command $ new-git awesome-repo to create a new public remote repository on your Github user account.

Get all child elements

Yes, you can achieve it by find_elements_by_css_selector("*") or find_elements_by_xpath(".//*").

However, this doesn't sound like a valid use case to find all children of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.stackoverflow.com")

header = driver.find_element_by_id("header")

# start from your target element, here for example, "header"
all_children_by_css = header.find_elements_by_css_selector("*")
all_children_by_xpath = header.find_elements_by_xpath(".//*")

print 'len(all_children_by_css): ' + str(len(all_children_by_css))
print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath))

Circular gradient in android

I always find images helpful when learning a new concept, so this is a supplemental answer.

enter image description here

The %p means a percentage of the parent, that is, a percentage of the narrowest dimension of whatever view we set our drawable on. The images above were generated by changing the gradientRadius in this code

my_gradient_drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="radial"
        android:gradientRadius="10%p"
        android:startColor="#f6ee19"
        android:endColor="#115ede" />
</shape>

Which can be set on a view's background attribute like this

<View
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:background="@drawable/my_gradient_drawable"/>

Center

You can change the center of the radius with

android:centerX="0.2"
android:centerY="0.7"

where the decimals are fractions of the width and height for x and y respectively.

enter image description here

Documentation

Here are some notes from the documentation explaining things a little more.

android:gradientRadius

Radius of the gradient, used only with radial gradient. May be an explicit dimension or a fractional value relative to the shape's minimum dimension.

May be a floating point value, such as "1.2".

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

May be a fractional value, which is a floating point number appended with either % or %p, such as "14.5%". The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to some parent container.

MySQL's now() +1 day

You can use:

NOW() + INTERVAL 1 DAY

If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW:

CURDATE() + INTERVAL 1 DAY

how to parse json using groovy

        def jsonFile = new File('File Path');
        JsonSlurper jsonSlurper = new JsonSlurper();
        def parseJson = jsonSlurper.parse(jsonFile)
        String json = JsonOutput.toJson(parseJson)
        def prettyJson = JsonOutput.prettyPrint(json)
        println(prettyJson)

Python Database connection Close

Connections have a close method as specified in PEP-249 (Python Database API Specification v2.0):

import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
csr.close()
conn.close()     #<--- Close the connection

Since the pyodbc connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:

import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 
with conn:
    crs = conn.cursor()
    do_stuff
    # conn.commit() will automatically be called when Python leaves the outer `with` statement
    # Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!! 

See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.

Note that unlike the original code, this causes conn.commit() to be called. Use the outer with statement to control when you want commit to be called.


Also note that regardless of whether or not you use the with statements, per the docs,

Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [conn.close()], but you can explicitly close the connection if you wish.

and similarly for cursors (my emphasis):

Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [csr.close()] is not usually necessary.

What's the difference between a null pointer and a void pointer?

NULL is a value that is valid for any pointer type. It represents the absence of a value.

A void pointer is a type. Any pointer type is convertible to a void pointer hence it can point to any value. This makes it good for general storage but bad for use. By itself it cannot be used to access a value. The program must have extra context to understand the type of value the void pointer refers to before it can access the value.

How do I show the changes which have been staged?

If you have more than one file with staged changes, it may more practical to use git add -i, then select 6: diff, and finally pick the file(s) you are interested in.

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

Responsive width Facebook Page Plugin

To make the new Facebook Page Plugin responsive on initial page load, you'll want to remove the data-width attribute and instead add

data-adapt-container-width="true"

This will make the Facebook Page Plugin responsive, but only on the initial page render, with a minimum width of 180px.

I'm still trying to figure out how to make it truly dynamically responsive, in spite of Facebook's caveat (I'll post an update if I ever find the answer).

No Dynamic Resizing

The Page plugin works with responsive, fluid and static layouts. You can use media queries or other methods to set the width of the parent element, yet:

The plugin will determine its width on page load. It will not react changes to the box model after page load. If you want to adjust the plugin's width on window resize, you manually need to rerender the plugin.

Source: https://developers.facebook.com/docs/plugins/page-plugin

You could make it dynamically responsive by reinitializing the widget on browser resize, as Io Ctaptceb suggested, but by doing that you run the risk of eating up memory very quickly.

Yugal Jindle had a good answer, but I wanted to clarify that I have yet to find a way to make the plugin truly dynamically responsive.

Call a child class method from a parent class object

A parent class should not have knowledge of child classes. You can implement a method calculate() and override it in every subclass:

class Person {
    String name;
    void getName(){...}
    void calculate();
}

and then

class Student extends Person{
    String class;
    void getClass(){...}

    @Override
    void calculate() {
        // do something with a Student
    }
}

and

class Teacher extends Person{
    String experience;
    void getExperience(){...}

    @Override
    void calculate() {
        // do something with a Student
    }

}

By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.

In your example you can make Person abstract and the use getName() on instanced of Student and Teacher.

How to update Android Studio automatically?

Yes you are right. There is no built in mechanism for automatically updation of Android Studio. You have to manually download it and configure it.

Format a datetime into a string with milliseconds

Probably like this :

import datetime
now = datetime.datetime.now()
now.strftime('%Y/%m/%d %H:%M:%S.%f')[:-3]  
# [:-3] => Removing the 3 last characters as %f is for microsecs.

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

INNER JOIN vs LEFT JOIN performance in SQL Server

There is one important scenario that can lead to an outer join being faster than an inner join that has not been discussed yet.

When using an outer join, the optimizer is always free to drop the outer joined table from the execution plan if the join columns are the PK of the outer table, and none of the outer table columns are referenced outside of the outer join itself. For example SELECT A.* FROM A LEFT OUTER JOIN B ON A.KEY=B.KEY and B.KEY is the PK for B. Both Oracle (I believe I was using release 10) and Sql Server (I used 2008 R2) prune table B from the execution plan.

The same is not necessarily true for an inner join: SELECT A.* FROM A INNER JOIN B ON A.KEY=B.KEY may or may not require B in the execution plan depending on what constraints exist.

If A.KEY is a nullable foreign key referencing B.KEY, then the optimizer cannot drop B from the plan because it must confirm that a B row exists for every A row.

If A.KEY is a mandatory foreign key referencing B.KEY, then the optimizer is free to drop B from the plan because the constraints guarantee the existence of the row. But just because the optimizer can drop the table from the plan, doesn't mean it will. SQL Server 2008 R2 does NOT drop B from the plan. Oracle 10 DOES drop B from the plan. It is easy to see how the outer join will out-perform the inner join on SQL Server in this case.

This is a trivial example, and not practical for a stand-alone query. Why join to a table if you don't need to?

But this could be a very important design consideration when designing views. Frequently a "do-everything" view is built that joins everything a user might need related to a central table. (Especially if there are naive users doing ad-hoc queries that do not understand the relational model) The view may include all the relevent columns from many tables. But the end users might only access columns from a subset of the tables within the view. If the tables are joined with outer joins, then the optimizer can (and does) drop the un-needed tables from the plan.

It is critical to make sure that the view using outer joins gives the correct results. As Aaronaught has said - you cannot blindly substitute OUTER JOIN for INNER JOIN and expect the same results. But there are times when it can be useful for performance reasons when using views.

One last note - I haven't tested the impact on performance in light of the above, but in theory it seems you should be able to safely replace an INNER JOIN with an OUTER JOIN if you also add the condition <FOREIGN_KEY> IS NOT NULL to the where clause.

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

Stop executing further code in Java

There are two way to stop current method/process :

  1. Throwing Exception.
  2. returnning the value even if it is void method.

Option : you can also kill the current thread to stop it.

For example :

public void onClick(){

    if(condition == true){
        return;
        <or>
        throw new YourException();
    }
    string.setText("This string should not change if condition = true");
}

GitHub README.md center image

This is from Github's support:

Hey Waldyr,

Markdown doesn't allow you to tweak alignment directly (see docs here: http://daringfireball.net/projects/markdown/syntax#img), but you can just use a raw HTML 'img' tag and do the alignment with inline css.

Cheers,

So it is possible to align images! You just have to use inline css to solve the problem. You can take an example from my github repo. At the bottom of README.md there is a centered aligned image. For simplicity you can just do as follows:

<p align="center">
  <img src="http://some_place.com/image.png" />
</p>

Although, as nulltoken said, it would be borderline against the Markdown philosophy!


This code from my readme:

<p align="center">
  <img src="https://github.com/waldyr/Sublime-Installer/blob/master/sublime_text.png?raw=true" alt="Sublime's custom image"/>
</p>

Produces this image output, except centered when viewed on GitHub:

<p align="center">
  <img src="https://github.com/waldyr/Sublime-Installer/blob/master/sublime_text.png?raw=true" alt="Sublime's custom image"/>
</p>

What is default session timeout in ASP.NET?

The Default Expiration Period for Session is 20 Minutes.

You can update sessionstate and configure the minutes under timeout

<sessionState 
timeout="30">
</sessionState>

Python: Get HTTP headers from urllib2.urlopen call?

Use the response.info() method to get the headers.

From the urllib2 docs:

urllib2.urlopen(url[, data][, timeout])

...

This function returns a file-like object with two additional methods:

  • geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
  • info() — return the meta-information of the page, such as headers, in the form of an httplib.HTTPMessage instance (see Quick Reference to HTTP Headers)

So, for your example, try stepping through the result of response.info().headers for what you're looking for.

Note the major caveat to using httplib.HTTPMessage is documented in python issue 4773.

How to get character array from a string?

How about this?

function stringToArray(string) {
  let length = string.length;
  let array = new Array(length);
  while (length--) {
    array[length] = string[length];
  }
  return array;
}

strcpy() error in Visual studio 2012

The message you are getting is advice from MS that they recommend that you do not use the standard strcpy function. Their motivation in this is that it is easy to misuse in bad ways (and the compiler generally can't detect and warn you about such misuse). In your post, you are doing exactly that. You can get rid of the message by telling the compiler to not give you that advice. The serious error in your code would remain, however.

You are creating a buffer with room for 10 chars. You are then stuffing 11 chars into it. (Remember the terminating '\0'?) You have taken a box with exactly enough room for 10 eggs and tried to jam 11 eggs into it. What does that get you? Not doing this is your responsibility and the compiler will generally not detect such things.

You have tagged this C++ and included string. I do not know your motivation for using strcpy, but if you use std::string instead of C style strings, you will get boxes that expand to accommodate what you stuff in them.

Remove columns from dataframe where ALL values are NA

A handy base R option could be colMeans():

df[, colMeans(is.na(df)) != 1]

Secondary axis with twinx(): how to add to legend?

I'm not sure if this functionality is new, but you can also use the get_legend_handles_labels() method rather than keeping track of lines and labels yourself:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

pi = np.pi

# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
        * np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 10

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')

# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

Visual Studio Code: format is not using indent settings

If you're using a plugin (in my case Vetur, for vue.js), these may set their own tab formatting settings.

Open your settings, search for "format" and look through relevant plugin settings that may be overwriting the global tab format. This worked for me; once I updated Vetur tab settings to match my preference (4-size tabs in my case), formatting .vue documents started to work properly:

enter image description here

Scrolling a flexbox with overflowing content

A little late but this could help: http://webdesign.tutsplus.com/tutorials/how-to-make-responsive-scrollable-panels-with-flexbox--cms-23269

Basically you need to put html,body to height: 100%; and wrap all your content into a <div class="wrap"> <!-- content --> </div>

CSS:

html, body {
  height: 100%;
}

.wrap {
  height: 100vh;
  display: flex;
}

Worked for me. Hope it helps

Plot a legend outside of the plotting area in base graphics?

Maybe what you need is par(xpd=TRUE) to enable things to be drawn outside the plot region. So if you do the main plot with bty='L' you'll have some space on the right for a legend. Normally this would get clipped to the plot region, but do par(xpd=TRUE) and with a bit of adjustment you can get a legend as far right as it can go:

 set.seed(1) # just to get the same random numbers
 par(xpd=FALSE) # this is usually the default

 plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2), bty='L')
 # this legend gets clipped:
 legend(2.8,0,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

 # so turn off clipping:
 par(xpd=TRUE)
 legend(2.8,-1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

HTML5 - mp4 video does not play in IE9

Whithout JavaScript, the only way I could play without errors:

<!--[if lte IE 9]>
<!-- PUT HERE A FLASH PLAYER WITH video.flv -->
<![endif]-->

<!--[if gt IE 9]><!-->
<video controls class="video">
    <source src="video.mp4" type="video/mp4">
    <!-- REPEAT FLASH PLAYER CODE HERE -->
</video>
<!--<![endif]-->

Remove characters except digits from string using Python?

Not a one liner but very simple:

buffer = ""
some_str = "aas30dsa20"

for char in some_str:
    if not char.isdigit():
        buffer += char

print( buffer )

SQL How to replace values of select return?

You can use casting in the select clause like:

SELECT id, name, CAST(hide AS BOOLEAN) FROM table_name;

JavaScript Array Push key value

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


Or if you wants to create a single object from values of arrays:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Text in a flex container doesn't wrap in IE11

Hi for me I had to apply the 100% width to its grandparent element. Not its child element(s).

.grandparent {
    float:left;
    clear: both;
    width:100%; //fix for IE11 text overflow
}

.parent {
    display: flex;
    border: 1px solid red;
    align-items: center;
}

.child {
    border: 1px solid blue;
}

What is the Swift equivalent of isEqualToString in Objective-C?

Use == operator instead of isEqual

Comparing Strings

Swift provides three ways to compare String values: string equality, prefix equality, and suffix equality.

String Equality

Two String values are considered equal if they contain exactly the same characters in the same order:

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
.
.
.

For more read official documentation of Swift (search Comparing Strings).

jQueryUI modal dialog does not show close button (x)

I had a similar issue. I was using jquery and jquery-ui. When I upgraded my versions, the close dialog image no longer appeared. My problem was that when I unzipped the js package that I downloaded, the directories did not have the execute permission.

So a quick chmod +x dir-name, and also for the sub-folders, did the trick. Without the execute permission on linux, apache cannot get into the folder.

Add a scrollbar to a <textarea>

like this

css

textarea {

overflow:scroll;
height:100px;
}

jQuery - Click event on <tr> elements with in a table and getting <td> element values

<script>
jQuery(document).ready(function() {
    jQuery("tr").click(function(){
       alert("Click! "+ jQuery(this).find('td').html());
    });
});
</script>

Can I edit an iPad's host file?

The previous answer is correct, but if the effect you are looking for is to redirect HTTP traffic for a domain to another IP there is a way.

Since it technically is not answering your question, I have asked and answered the question here:

How can I redirect HTTP requests made from an iPad?

What is the @Html.DisplayFor syntax for?

I think the main benefit would be when you define your own Display Templates, or use Data annotations.

So for example if your title was a date, you could define

[DisplayFormat(DataFormatString = "{0:d}")]

and then on every page it would display the value in a consistent manner. Otherwise you may have to customise the display on multiple pages. So it does not help much for plain strings, but it does help for currencies, dates, emails, urls, etc.

For example instead of an email address being a plain string it could show up as a link:

<a href="mailto:@ViewData.Model">@ViewData.TemplateInfo.FormattedModelValue</a>

Hive load CSV with commas in quoted fields

Add a backward slash in FIELDS TERMINATED BY '\;'

For Example:

CREATE  TABLE demo_table_1_csv
COMMENT 'my_csv_table 1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\;'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 'your_hdfs_path'
AS 
select a.tran_uuid,a.cust_id,a.risk_flag,a.lookback_start_date,a.lookback_end_date,b.scn_name,b.alerted_risk_category,
CASE WHEN (b.activity_id is not null ) THEN 1 ELSE 0 END as Alert_Flag 
FROM scn1_rcc1_agg as a LEFT OUTER JOIN scenario_activity_alert as b ON a.tran_uuid = b.activity_id;

I have tested it, and it worked.

Android activity life cycle - what are all these methods for?

From the Android Developers page,

onPause():

Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

onStop():

Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.

The paused Activity gets a Resume and Stopped gets Restarted.

When you call this.finish(), onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.

I hope it's clear enough.

Remove HTML Tags from an NSString on the iPhone

I've extended the answer by m.kocikowski and tried to make it a bit more efficient by using an NSMutableString. I've also structured it for use in a static Utils class (I know a Category is probably the best design though), and removed the autorelease so it compiles in an ARC project.

Included here in case anybody finds it useful.

.h

+ (NSString *)stringByStrippingHTML:(NSString *)inputString;

.m

+ (NSString *)stringByStrippingHTML:(NSString *)inputString 
{
  NSMutableString *outString;

  if (inputString)
  {
    outString = [[NSMutableString alloc] initWithString:inputString];

    if ([inputString length] > 0)
    {
      NSRange r;

      while ((r = [outString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
      {
        [outString deleteCharactersInRange:r];
      }      
    }
  }

  return outString; 
}

How can I render a list select box (dropdown) with bootstrap?

The Bootstrap3 .form-control is cool but for those who love or need the drop-down with button and ul option, here is the updated code. I have edited the code by Steve to fix jumping to the hash link and closing the drop-down after selection.

Thanks to Steve, Ben and Skelly!

$(".dropdown-menu li a").click(function () {
    var selText = $(this).text();
    $(this).closest('div').find('button[data-toggle="dropdown"]').html(selText + ' <span class="caret"></span>');
    $(this).closest('.dropdown').removeClass("open");
    return false;
});

JavaScript OR (||) variable assignment explanation

According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)

He also suggests another use for it (quoted): "lightweight normalization of cross-browser differences"

// determine upon which element a Javascript event (e) occurred
var target = /*w3c*/ e.target || /*IE*/ e.srcElement;

typedef fixed length array

The typedef would be

typedef char type24[3];

However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and the sizeof for it will then be wrong.

A better solution would be

typedef struct type24 { char x[3]; } type24;

You probably also want to be using unsigned char instead of char, since the latter has implementation-defined signedness.

Adding a y-axis label to secondary y-axis in matplotlib

The best way is to interact with the axes object directly

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

plt.show()

example graph

Javascript can't find element by id?

The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:

window.onload = function () {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
};

Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.

Another approach is to place the script tag right before your closing </body>-tag, since everything in front of it is loaded at the time of execution, then.

Can we execute a java program without a main() method?

Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.

And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.

{
    static
    {
        System.out.println("Hello World!");
        System.exit(0); // prevents “main method not found” error
    }
}

But this will not execute with JAVA 7 version.

cast or convert a float to nvarchar?

If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.

So instead of:

select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009

You would use:

select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890

In these examples the innermost cast(1234567890 as float) is used in place of selecting a value from the appropriate column.

I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?

select cast(0100884555 as float)
100884555

Whoops! We just stored an incorrect phone number...

Swift - iOS - Dates and times in different format

You have already found NSDateFormatter, just read the documentation on it.

NSDateFormatter Class Reference

For format character definitions
See: ICU Formatting Dates and Times
Also: Date Field SymbolTable..

Java Ordered Map

You can leverage NavigableMap interface that may be accessed and traversed in either ascending or descending key order. This interface is intended to supersede the SortedMap interface. The Navigable map is usually sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time.

There are three most useful implementations of it: TreeMap, ImmutableSortedMap, and ConcurrentSkipListMap.

TreeMap example:

TreeMap<String, Integer> users = new TreeMap<String, Integer>();
users.put("Bob", 1);
users.put("Alice", 2);
users.put("John", 3);

for (String key: users.keySet()) {
  System.out.println(key + " (ID = "+ users.get(key) + ")");
}

Output:

Alice (ID = 2)
Bob (ID = 1)
John (ID = 3)

jQuery pass more parameters into callback

Let's go simple ! :)

$.ajax({
    url: myUrl,
    context: $this, // $this == Current $element
    success: function(data) {
        $.proxy(publicMethods.update, this)(data); // this == Current $element
    }
});

Download file of any type in Asp.Net MVC using FileResult?

You can just specify the generic octet-stream MIME type:

public FileResult Download()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(@"c:\folder\myfile.ext");
    string fileName = "myfile.ext";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

How to read AppSettings values from a .json file in ASP.NET Core

Super late to the party but if someone finds this out.

You can call IConfiguration from Microsoft.Extensions.Configuration;

public static IConfiguration Configuration { get; }
public static string MyAwesomeString = Configuration.GetSection("appSettings")["MyAwesomeString"].ToString();

How to detect pressing Enter on keyboard using jQuery?

The easy way to detect whether the user has pressed enter is to use key number the enter key number is =13 to check the value of key in your device

$("input").keypress(function (e) {
  if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                    || (97 <= e.which && e.which <= 97 + 25)) {
    var c = String.fromCharCode(e.which);
    $("p").append($("<span/>"))
          .children(":last")
          .append(document.createTextNode(c));
  } else if (e.which == 8) {
    // backspace in IE only be on keydown
    $("p").children(":last").remove();
  }
  $("div").text(e.which);
});

by pressing the enter key you will get result as 13 . using the key value you can call a function or do whatever you wish

        $(document).keypress(function(e) {
      if(e.which == 13) {
console.log("User entered Enter key");
          // the code you want to run 
      }
    });

if you want to target a button once enter key is pressed you can use the code

    $(document).bind('keypress', function(e){
  if(e.which === 13) { // return
     $('#butonname').trigger('click');
  }
});

Hope it help

node.js vs. meteor.js what's the difference?

Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.

The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.

java.net.BindException: Address already in use: JVM_Bind <null>:80

The error:

Tomcat: java.net.BindException: Address already in use: JVM_Bind :80

suggests that the port 80 is already in use.
You may either:

  • Try searching for that process and stop it OR
  • Make your tomcat to run on different (free) port

See also: Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Change the Arrow buttons in Slick slider

If we want to use font awesome library using the css then we can use the below css

  .slick-prev:before {
    content: "\f104";
    color: red;
    font-size: 30px;
    font-family: 'FontAwesome';
  }

  .slick-next:before {
    content: "\f105";
    color: red;
    font-size: 30px;
    font-family: 'FontAwesome';
  }

Font awesome library css must be added in the page.

#define macro for debug printing in C?

#define debug_print(FMT, ARGS...) do { \
    if (DEBUG) \
        fprintf(stderr, "%s:%d " FMT "\n", __FUNCTION__, __LINE__, ## ARGS); \
    } while (0)

Select 50 items from list at random to write to file

I think random.choice() is a better option.

import numpy as np

mylist = [13,23,14,52,6,23]

np.random.choice(mylist, 3, replace=False)

the function returns an array of 3 randomly chosen values from the list

Test if a command outputs an empty string

if [ -z "$(ls -lA)" ]; then
  echo "no files found"
else
  echo "There are files"
fi

This will run the command and check whether the returned output (string) has a zero length. You might want to check the 'test' manual pages for other flags.

Use the "" around the argument that is being checked, otherwise empty results will result in a syntax error as there is no second argument (to check) given!

Note: that ls -la always returns . and .. so using that will not work, see ls manual pages. Furthermore, while this might seem convenient and easy, I suppose it will break easily. Writing a small script/application that returns 0 or 1 depending on the result is much more reliable!

Angular2 get clicked element id

There is no need to pass the entire event (unless you need other aspects of the event than you have stated). In fact, it is not recommended. You can pass the element reference with just a little modification.

import {Component} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `
    <button #btn1 (click)="toggle(btn1)" class="someclass" id="btn1">Button 1</button>
    <button #btn2 (click)="toggle(btn2)" class="someclass" id="btn2">Button 2</button>
  `
})
export class AppComponent {
  buttonValue: string;

  toggle(button) {
    this.buttonValue = button.id;
  }

}

StackBlitz demo

Technically, you don't need to find the button that was clicked, because you have passed the actual element.

Angular guidance

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

How to hide reference counts in VS2013?

The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.

However, if the only way to disable Show References is to disable CodeLens altogether.

Then, I guess I could do just that.

Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'

If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.

In short, uncheck Codelens...

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

Mongodb service won't start

I verified permissions but all was good (mongod:mongod). As I'm working on a large project and from a similar issue in our dev environment where we had a script consuming all available disk space, I could see in the error messages that mongod needs at least 3.7Gb free disk space to run..

I checked my own disk space only to see that less than 2Gb was remaining. After moving / erasing some data I can successfully start mongod again.

Hope this helps ;-)

Get element type with jQuery

you should use tagName property and attr('type') for inputs

Getting only hour/minute of datetime

I would recommend keeping the object you have, and just utilizing the properties that you want, rather than removing the resolution you already have.

If you want to print it in a certain format you may want to look at this...That way you can preserve your resolution further down the line.

That being said you can create a new DateTime object using only the properties you want as @romkyns has in his answer.

Oracle - What TNS Names file am I using?

strace sqlplus -L scott/tiger@orcl helps to find .tnsnames.ora file on /home/oracle to find the file it takes instead of $ORACLE_HOME/network/admin/tnsnames.ora file. Thanks for the posting.

Getting Access Denied when calling the PutObject operation with bucket-level permission

In case this help out anyone else, in my case, I was using a CMK (it worked fine using the default aws/s3 key)

I had to go into my encryption key definition in IAM and add the programmatic user logged into boto3 to the list of users that "can use this key to encrypt and decrypt data from within applications and when using AWS services integrated with KMS.".

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Django DB Settings 'Improperly Configured' Error

You can't just fire up Python and check things, Django doesn't know what project you want to work on. You have to do one of these things:

  • Use python manage.py shell
  • Use django-admin.py shell --settings=mysite.settings (or whatever settings module you use)
  • Set DJANGO_SETTINGS_MODULE environment variable in your OS to mysite.settings
  • (This is removed in Django 1.6) Use setup_environ in the python interpreter:

    from django.core.management import setup_environ
    from mysite import settings
    
    setup_environ(settings)
    

Naturally, the first way is the easiest.

how to use Spring Boot profiles

The @Profile annotation allows you to indicate that a component is eligible for registration when one or more specified profiles are active. Using our example above, we can rewrite the dataSource configuration as follows:

@Configuration
@Profile("dev")
public class StandaloneDataConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("classpath:com/bank/config/sql/schema.sql")
            .addScript("classpath:com/bank/config/sql/test-data.sql")
            .build();
    }
}

And other one:

@Configuration
@Profile("production")
public class JndiDataConfig {

    @Bean(destroyMethod="")
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
    }
}

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

javascript /jQuery - For Loop

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});

MySQL DISTINCT on a GROUP_CONCAT()

SELECT
  GROUP_CONCAT(DISTINCT (category))
FROM (
  SELECT
    SUBSTRING_INDEX(SUBSTRING_INDEX(tableName.categories, ' ', numbers.n), ' ', -1) category
  FROM
    numbers INNER JOIN tableName
    ON LENGTH(tableName.categories)>=LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1
  ) s;   

This will return distinct values like: test1,test2,test4,test3

Perl read line by line

#!/usr/bin/perl
use utf8                       ;
use 5.10.1                     ;
use strict                     ;
use autodie                    ;
use warnings FATAL => q  ?all?;
binmode STDOUT     => q ?:utf8?;                  END {
close   STDOUT                 ;                     }
our    $FOLIO      =  q + SnPmaster.txt +            ;
open    FOLIO                  ;                 END {
close   FOLIO                  ;                     }
binmode FOLIO      => q{       :crlf
                               :encoding(CP-1252)    };
while (<FOLIO>)  { print       ;                     }
       continue  { ${.} ^015^  __LINE__  ||   exit   }
                                                                                                                                                                                                                                              __END__
unlink  $FOLIO                 ;
unlink ~$HOME ||
  clri ~$HOME                  ;
reboot                         ;

Check if instance is of a type

A little more compact than the other answers if you want to use c as a TForm:

if(c is TForm form){
    form.DoStuff();
}

PHP preg replace only allow numbers

I think you're saying you want to remove all non-numeric characters. If so, \D means "anything that isn't a digit":

preg_replace('/\D/', '', $c)

Convert a tensor to numpy array in Tensorflow?

You can convert a tensor in tensorflow to numpy array in the following ways.

First: Use np.array(your_tensor)

Second: Use your_tensor.numpy

Python not working in command prompt?

Rather than the command "python", consider launching Python via the py launcher, as described in sg7's answer, which by runs your latest version of Python (or lets you select a specific version). The py launcher is enabled via a check box during installation (default: "on").

Nevertheless, you can still put the "python" command in your PATH, either at "first installation" or by "modifying" an existing installation.


First Installation:

Checking the "[x] Add Python x.y to PATH" box on the very first dialog. Here's how it looks in version 3.8: enter image description here

This has the effect of adding the following to the PATH variable:

C:\Users\...\AppData\Local\Programs\Python\Python38-32\Scripts\
C:\Users\...\AppData\Local\Programs\Python\Python38-32\

Modifying an Existing Installation:

Re-run your installer (e.g. in Downloads, python-3.8.4.exe) and Select "Modify". Check all the optional features you want (likely no changes), then click [Next]. Check [x] "Add Python to environment variables", and [Install]. enter image description here

How to center a component in Material-UI and make it responsive?

All you have to do is wrap your content inside a Grid Container tag, specify the spacing, then wrap the actual content inside a Grid Item tag.

 <Grid container spacing={24}>
    <Grid item xs={8}>
      <leftHeaderContent/>
    </Grid>

    <Grid item xs={3}>
      <rightHeaderContent/>
    </Grid>
  </Grid>

Also, I've struggled with material grid a lot, I suggest you checkout flexbox which is built into CSS automatically and you don't need any addition packages to use. Its very easy to learn.

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

How to find the 'sizeof' (a pointer pointing to an array)?

The answer is, "No."

What C programmers do is store the size of the array somewhere. It can be part of a structure, or the programmer can cheat a bit and malloc() more memory than requested in order to store a length value before the start of the array.

Wait till a Function with animations is finished until running another Function

This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.

You can get the Deferred object jQuery creates for the animation using .promise() on the animation call. Wrapping these Deferreds into ES6 Promises results in much cleaner code than using timers.

You can also use Deferreds directly, but this is generally discouraged because they do not follow the Promises/A+ specification.

The resulting code would look like this:

var p1 = Promise.resolve($('#Content').animate({ opacity: 0.5 }, { duration: 500, queue: false }).promise());
var p2 = Promise.resolve($('#Content').animate({ marginLeft: "-100px" }, { duration: 2000, queue: false }).promise());
Promise.all([p1, p2]).then(function () {
    return $('#Content').animate({ width: 0 }, { duration: 500, queue: false }).promise();
});

Note that the function in Promise.all() returns the promise. This is where magic happens. If in a then call a promise is returned, the next then call will wait for that promise to be resolved before executing.

jQuery uses an animation queue for each element. So animations on the same element are executed synchronously. In this case you wouldn't have to use promises at all!

I have disabled the jQuery animation queue to demonstrate how it would work with promises.

Promise.all() takes an array of promises and creates a new Promise that finishes after all promises in the array finished.

Promise.race() also takes an array of promises, but finishes as soon as the first Promise finished.

AppCompat v7 r21 returning error in values.xml?

my solucion is compile with other version

build.gradle (app)

compileSdkVersion 21

Good Luck

Recommended SQL database design for tags or tagging

Use a single formatted text column[1] for storing the tags and use a capable full text search engine to index this. Else you will run into scaling problems when trying to implement boolean queries.

If you need details about the tags you have, you can either keep track of it in a incrementally maintained table or run a batch job to extract the information.

[1] Some RDBMS even provide a native array type which might be even better suited for storage by not needing a parsing step, but might cause problems with the full text search.

How to remove rows with any zero value

There are a few different ways of doing this. I prefer using apply, since it's easily extendable:

##Generate some data
dd = data.frame(a = 1:4, b= 1:0, c=0:3)

##Go through each row and determine if a value is zero
row_sub = apply(dd, 1, function(row) all(row !=0 ))
##Subset as usual
dd[row_sub,]

How to change the plot line color from blue to black?

If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

plt.axes[0].get_lines()[0].set_color('black')

SQL conditional SELECT

This is a psuedo way of doing it

IF (selectField1 = true) 
SELECT Field1 FROM Table
ELSE
SELECT Field2 FROM Table

How to remove entry from $PATH on mac

Check the following files:

/etc/bashrc
/etc/profile
~/.bashrc
~/.bash_profile
~/.profile
~/.MacOSX/environment.plist

Some of these files may not exist, but they're the most likely ones to contain $PATH definitions.

How to increment variable under DOS?

Coming to the party very very late, but from my old memory of DOS batch files, you can keep adding a character to the string each loop then look for a string of that many of that character. for 250 iterations, you either have a very long "cycles" string, or you have one loop inside using one set of variables counting to 10, then another loop outside that uses another set of variable counting to 25.

Here is the basic loop to 30:

@echo off
rem put how many dots you want to loop
set cycles=..............................
set cntr=
:LOOP
set cntr=%cntr%.
echo around we go again
if "%cycles%"=="%cntr%" goto done
goto loop
:DONE
echo around we went

Adding Only Untracked Files

To add all untracked files git command is

git add -A

Also if you want to get more details about various available options , you can type command

git add -i

instead of first command , with this you will get more options including option to add all untracked files as shown below :

$ git add -i warning: LF will be replaced by CRLF in README.txt. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in package.json.

* Commands * 1: status 2: update 3: revert 4: add untracked 5: patch 6: diff 7: quit 8: help What now> a

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

You may try to check your registry

  • HKEY_LOCAL_MACHINE\SOFTWARE\Classes\TypeLib{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}

If it is 2.1 version, it will cause cannot load MSCOMCTL.OCX issue.

You may restore to 2.0 verion (not only copy the file, you should unregiser 2.1 and register the restored file)

Or

You may try latest 2.2 version

Some version information :

  • 6.0.88.62 (2.0)
  • 6.1.97.82 (2.0)
  • 6.1.98.34 (2.1) <<< not work for me
  • 6.1.98.46 (2.2)

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

If the above CMD command option is not working and you cannot make it work in any other way then follow this below.

Click on below link

http://adbshell.com/downloads

and download the first link with name ADB Kits ( contains adb.exe and necessary .dll files).

After downloading replace these files with the ones in the path

Android/Sdk/platform-tools/

Now click on adb.exe and it will open cmd and will start the adb server.

Now it will detect the device and no problem. OOOOOllllaaaaa.....

If the Problem persists again then do the same... save the folder somewhere.... just replace files... it will detect the device automatically then

Ruby - test for array

Are you sure it needs to be an array? You may be able to use respond_to?(method) so your code would work for similar things that aren't necessarily arrays (maybe some other enumberable thing). If you do actually need an array, then the post describing the Array#kind\_of? method is best.

['hello'].respond_to?('each')

How do I compile and run a program in Java on my Mac?

Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/

Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/


Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:

  • The source code editor
    • With syntax highlighting, colors and other visual cues
    • Easy cross-referencing to the documentation to facilitate learning
  • Compiler
    • Run the code with one click
    • Get notified of errors/mistakes as you go

As you gain more experience, you'll start to appreciate the rest of its rich set of features.

How to format numbers by prepending 0 to single-digit numbers?

For anyone who wants to have time differences and have results that can take negative numbers here is a good one. pad(3) = "03", pad(-2) = "-02", pad(-234) = "-234"

pad = function(n){
  if(n >= 0){
    return n > 9 ? "" + n : "0" + n;
  }else{
    return n < -9 ? "" + n : "-0" + Math.abs(n);
  }
}

JQuery - Call the jquery button click event based on name property

You have to use the jquery attribute selector. You can read more here:

http://api.jquery.com/attribute-equals-selector/

In your case it should be:

$('input[name="btnName"]')

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

Storing integer values as constants in Enum manner in java

if you want to be able to convert integer back to corresponding enum with selected value see Constants.forValue(...) in below auto generated code but if not the answer of BlairHippo is best way to do it.

public enum Constants
{
SIGN_CREATE(0),
SIGN_CREATE(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);

    public static final int SIZE = java.lang.Integer.SIZE;

    private int intValue;
    private static java.util.HashMap<Integer, Constants> mappings;
    private static java.util.HashMap<Integer, Constants> getMappings()
    {
        if (mappings == null)
        {
            synchronized (Constants.class)
            {
                if (mappings == null)
                {
                    mappings = new java.util.HashMap<Integer, Constants>();
                }
            }
        }
        return mappings;
    }

    private Constants(int value)
    {
        intValue = value;
        getMappings().put(value, this);
    }

    public int getValue()
    {
        return intValue;
    }

    public static Constants forValue(int value)
    {
        return getMappings().get(value);
    }
}

Android: how to make an activity return results to the activity which calls it?

In order to start an activity which should return result to the calling activity, you should do something like below. You should pass the requestcode as shown below in order to identify that you got the result from the activity you started.

startActivityForResult(new Intent(“YourFullyQualifiedClassName”),requestCode);

In the activity you can make use of setData() to return result.

Intent data = new Intent();
String text = "Result to be returned...."
//---set the data to pass back---
data.setData(Uri.parse(text));
setResult(RESULT_OK, data);
//---close the activity---
finish();

So then again in the first activity you write the below code in onActivityResult()

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String returnedResult = data.getData().toString();
            // OR
            // String returnedResult = data.getDataString();
        }
    }
}

EDIT based on your comment: If you want to return three strings, then follow this by making use of key/value pairs with intent instead of using Uri.

Intent data = new Intent();
data.putExtra("streetkey","streetname");
data.putExtra("citykey","cityname");
data.putExtra("homekey","homename");
setResult(RESULT_OK,data);
finish();

Get them in onActivityResult like below:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String street = data.getStringExtra("streetkey");
            String city = data.getStringExtra("citykey");
            String home = data.getStringExtra("homekey");
        }
    }
}

How can I convert a VBScript to an executable (EXE) file?

You can try VbsEdit. Get the latest version from Adersoft's VbsEdit http://www.vbsedit.com its a small download but it is a powerful tool to create and edit vbs files and convert them into executables without unpacking to temporary folder. (unless you get an old version like version 4.x.x.x) I've been using this program since 2008, and it's free to evaluate forever but comes with a reminder to activate and each time you Start your script from the vbsedit window you will have to wait a few seconds, Or you could purchase it for $60 to remove those minor annoyances.
Unlike ScriptCryptor, the converted exe won't have any limitations if you are still evaluating, it will run without any unwanted additional windows.

Sleep for milliseconds

Select call is a way of having more precision (sleep time can be specified in nanoseconds).

How to write DataFrame to postgres table?

Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The sql module now uses sqlalchemy to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see docs). E.g.:

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')
df.to_sql('table_name', engine)

You are correct that in pandas up to version 0.13.1 postgresql was not supported. If you need to use an older version of pandas, here is a patched version of pandas.io.sql: https://gist.github.com/jorisvandenbossche/10841234.
I wrote this a time ago, so cannot fully guarantee that it always works, buth the basis should be there). If you put that file in your working directory and import it, then you should be able to do (where con is a postgresql connection):

import sql  # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')

Convert time.Time to string

Go Playground http://play.golang.org/p/DN5Py5MxaB

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    // The Time type implements the Stringer interface -- it
    // has a String() method which gets called automatically by
    // functions like Printf().
    fmt.Printf("%s\n", t)

    // See the Constants section for more formats
    // http://golang.org/pkg/time/#Time.Format
    formatedTime := t.Format(time.RFC1123)
    fmt.Println(formatedTime)
}

How to make rectangular image appear circular with CSS

This one works well if you know height and width:

img {
  object-fit: cover;
  border-radius: '50%';
  width: 100px;
  height: 100px;
}

via https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87

Why can't overriding methods throw exceptions broader than the overridden method?

Let us take an interview Question. There is a method that throws NullPointerException in the superclass. Can we override it with a method that throws RuntimeException?

To answer this question, let us know what is an Unchecked and Checked exception.

  1. Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown.

  2. Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.

public class NullPointerException extends RuntimeException

Unchecked exceptions extend the java.lang.RuntimeException. Thst's why NullPointerException is an Uncheked exception.

Let's take an example: Example 1 :

    public class Parent {
       public void name()  throws NullPointerException {
           System.out.println(" this is parent");
       }
}

public class Child  extends Parent{
     public  void name() throws RuntimeException{
             System.out.println(" child ");
     }

     public static void main(String[] args) {
        Parent parent  = new Child();
        parent.name();// output => child
    }
}

The program will compile successfully. Example 2:

    public class Parent {
       public void name()  throws RuntimeException {
           System.out.println(" this is parent");
       }
}

public class Child  extends Parent{
     public  void name() throws  NullPointerException {
             System.out.println(" child ");
     }

     public static void main(String[] args) {
        Parent parent  = new Child();
        parent.name();// output => child
    }
}

The program will also compile successfully. Therefore it is evident, that nothing happens in case of Unchecked exceptions. Now, let's take a look what happens in case of Checked exceptions. Example 3: When base class and child class both throws a checked exception

    public class Parent {
       public void name()  throws IOException {
           System.out.println(" this is parent");
       }
}
public class Child  extends Parent{
     public  void name() throws IOException{
             System.out.println(" child ");
     }

     public static void main(String[] args) {
        Parent parent  = new Child();

        try {
            parent.name();// output=> child
        }catch( Exception e) {
            System.out.println(e);
        }

    }
}

The program will compile successfully. Example 4: When child class method is throwing border checked exception compared to the same method of base class.

import java.io.IOException;

public class Parent {
       public void name()  throws IOException {
           System.out.println(" this is parent");
       }
}
public class Child  extends Parent{
     public  void name() throws Exception{ // broader exception
             System.out.println(" child ");
     }

     public static void main(String[] args) {
        Parent parent  = new Child();

        try {
            parent.name();//output=> Compilation failure
        }catch( Exception e) {
            System.out.println(e);
        }

    }
}

The program will fail to compile. So, we have to be careful when we are using Checked exceptions.

Android emulator not able to access the internet

I am also facing the same problem, but I am trying to solve the problem using various posts. Today I discovered this problem. Your computer configuration is most likely the problemm, not Android Studio and the Android Emulator.

The problem is coming from your Network setup. Just set the Primary DNS Server to 8.8.8.8, which will solve the problem.

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

How do I release memory used by a pandas dataframe?

It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659

The monkey patch detailed on this issue has resolved the problem for me:

# monkeypatches.py

# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
    cdll.LoadLibrary("libc.so.6")
    libc = CDLL("libc.so.6")
    libc.malloc_trim(0)
except (OSError, AttributeError):
    libc = None

__old_del = getattr(pd.DataFrame, '__del__', None)

def __new_del(self):
    if __old_del:
        __old_del(self)
    libc.malloc_trim(0)

if libc:
    print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
    pd.DataFrame.__del__ = __new_del
else:
    print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)

How to call a method after bean initialization is complete?

There are three different approaches to consider, as described in the reference

Use init-method attribute

Pros:

  • Does not require bean to implement an interface.

Cons:

  • No immediate indication this method is required after construction to ensure the bean is correctly configured.

Implement InitializingBean

Pros:

  • No need to specify init-method, or turn on component scanning / annotation processing.
  • Appropriate for beans supplied with a library, where we don't want the application using this library to concern itself with bean lifecycle.

Cons:

  • More invasive than the init-method approach.

Use JSR-250 @PostConstruct lifecyle annotation

Pros:

  • Useful when using component scanning to autodetect beans.
  • Makes it clear that a specific method is to be used for initialisation. Intent is closer to the code.

Cons:

  • Initialisation no longer centrally specified in configuration.
  • You must remember to turn on annotation processing (which can sometimes be forgotten)

What's the difference between unit, functional, acceptance, and integration tests?

http://martinfowler.com/articles/microservice-testing/

Martin Fowler's blog post speaks about strategies to test code (Especially in a micro-services architecture) but most of it applies to any application.

I'll quote from his summary slide:

  • Unit tests - exercise the smallest pieces of testable software in the application to determine whether they behave as expected.
  • Integration tests - verify the communication paths and interactions between components to detect interface defects.
  • Component tests - limit the scope of the exercised software to a portion of the system under test, manipulating the system through internal code interfaces and using test doubles to isolate the code under test from other components.
  • Contract tests - verify interactions at the boundary of an external service asserting that it meets the contract expected by a consuming service.
  • End-To-End tests - verify that a system meets external requirements and achieves its goals, testing the entire system, from end to end.

Lotus Notes email as an attachment to another email

I have been trying to do this for a while also. Here is what I do now. Highlight the email you want to create as a file. Click on Create. Hover over Special, then click on Link message. This will open up a new tab for the link. At the bottom of the message is a small yellow piece of paper icon. Copy this icon and paste into your message like you would any other file. It is tiny, so I put a statement like "see email attachment ---->" in front of the icon. You might like this way. Not sure though.

How do I print my Java object without getting "SomeType@2f92e0f4"?

Background

All Java objects have a toString() method, which is invoked when you try to print the object.

System.out.println(myObject);  // invokes myObject.toString()

This method is defined in the Object class (the superclass of all Java objects). The Object.toString() method returns a fairly ugly looking string, composed of the name of the class, an @ symbol and the hashcode of the object in hexadecimal. The code for this looks like:

// Code of Object.toString()
public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

A result such as com.foo.MyType@2f92e0f4 can therefore be explained as:

  • com.foo.MyType - the name of the class, i.e. the class is MyType in the package com.foo.
  • @ - joins the string together
  • 2f92e0f4 the hashcode of the object.

The name of array classes look a little different, which is explained well in the Javadocs for Class.getName(). For instance, [Ljava.lang.String means:

  • [ - an single-dimensional array (as opposed to [[ or [[[ etc.)
  • L - the array contains a class or interface
  • java.lang.String - the type of objects in the array

Customizing the Output

To print something different when you call System.out.println(myObject), you must override the toString() method in your own class. Here's a simple example:

public class Person {

  private String name;
  
  // constructors and other methods omitted
  
  @Override
  public String toString() {
    return name;
  }
}

Now if we print a Person, we see their name rather than com.foo.Person@12345678.

Bear in mind that toString() is just one way for an object to be converted to a string. Typically this output should fully describe your object in a clear and concise manner. A better toString() for our Person class might be:

@Override
public String toString() {
  return getClass().getSimpleName() + "[name=" + name + "]";
}

Which would print, e.g., Person[name=Henry]. That's a really useful piece of data for debugging/testing.

If you want to focus on just one aspect of your object or include a lot of jazzy formatting, you might be better to define a separate method instead, e.g. String toElegantReport() {...}.


Auto-generating the Output

Many IDEs offer support for auto-generating a toString() method, based on the fields in the class. See docs for Eclipse and IntelliJ, for example.

Several popular Java libraries offer this feature as well. Some examples include:


Printing groups of objects

So you've created a nice toString() for your class. What happens if that class is placed into an array or a collection?

Arrays

If you have an array of objects, you can call Arrays.toString() to produce a simple representation of the contents of the array. For instance, consider this array of Person objects:

Person[] people = { new Person("Fred"), new Person("Mike") };
System.out.println(Arrays.toString(people));

// Prints: [Fred, Mike]

Note: this is a call to a static method called toString() in the Arrays class, which is different to what we've been discussing above.

If you have a multi-dimensional array, you can use Arrays.deepToString() to achieve the same sort of output.

Collections

Most collections will produce a pretty output based on calling .toString() on every element.

List<Person> people = new ArrayList<>();
people.add(new Person("Alice"));
people.add(new Person("Bob"));    
System.out.println(people);

// Prints [Alice, Bob]

So you just need to ensure your list elements define a nice toString() as discussed above.

Export table data from one SQL Server to another

If the tables are already created using the scripts, then there is another way to copy the data is by using BCP command to copy all the data from your source server to your destination server

To export the table data into a text file on source server:

bcp <database name>.<schema name>.<table name> OUT C:\FILE.TXT -c -t -T -S <server_name[ \instance_name]> -U <username> -P <Password> 

To import the table data from a text file on target server:

bcp <database name>.<schema name>.<table name> IN C:\FILE.TXT -c -t -T -S <server_name[ \instance_name]> -U <username> -P <Password>

Read/Write 'Extended' file properties (C#)

For those of not crazy about VB, here it is in c#:

Note, you have to add a reference to Microsoft Shell Controls and Automation from the COM tab of the References dialog.

public static void Main(string[] args)
{
    List<string> arrHeaders = new List<string>();

    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder objFolder;

    objFolder = shell.NameSpace(@"C:\temp\testprop");

    for( int i = 0; i < short.MaxValue; i++ )
    {
        string header = objFolder.GetDetailsOf(null, i);
        if (String.IsNullOrEmpty(header))
            break;
        arrHeaders.Add(header);
    }

    foreach(Shell32.FolderItem2 item in objFolder.Items())
    {
        for (int i = 0; i < arrHeaders.Count; i++)
        {
            Console.WriteLine(
              $"{i}\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}");
        }
    }
}

Content Type text/xml; charset=utf-8 was not supported by service

Do not forget check the bindings-related code too. So if you wrote:

BasicHttpBinding binding = new BasicHttpBinding();

Be sure that all your app.config files contains

<endpoint address="..."
          binding="basicHttpBinding" ...

not the

<endpoint address="..."
          binding="wsHttpBinding" ...

or so.

Javascript format date / time

You can do that:

function formatAMPM(date) { // This is to display 12 hour format like you asked
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);

Fiddle

BAT file to map to network drive without running as admin

@echo off
net use z: /delete
cmdkey /add:servername /user:userserver /pass:userstrongpass

net use z: \\servername\userserver /savecred /persistent:yes
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"

echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%USERPROFILE%\Desktop\userserver_in_server.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "Z:\" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%

cscript /nologo %SCRIPT%
del %SCRIPT%

Adding timestamp to a filename with mv in BASH

First, thanks for the answers above! They lead to my solution.

I added this alias to my .bashrc file:

alias now='date +%Y-%m-%d-%H.%M.%S'

Now when I want to put a time stamp on a file such as a build log I can do this:

mvn clean install | tee build-$(now).log

and I get a file name like:

build-2021-02-04-03.12.12.log

PHP memcached Fatal error: Class 'Memcache' not found

The right is php_memcache.dll. In my case i was using lib compiled with vc9 instead of vc6 compiler. In apatche error logs i got something like:

PHP Startup: sqlanywhere: Unable to initialize module Module compiled with build ID=API20090626, TS,VC9 PHP compiled with build ID=API20090626, TS,VC6 These options need to match

Check if you have same log and try downloading different dll that are compiled with different compiler.

Creating .pem file for APNS?

NOTE: You must have the Team Agent or Admin role in App Store Connect to perform any of these tasks. If you are not part of a Team in App Store Connect this probably does not affect you.

Sending push notifications to an iOS application requires creating encyption keys. In the past this was a cumbersome process that used SSL keys and certificates. Each SSL certificate was specific to a single iOS application. In 2016 Apple introduced a new authentication key mechanism that is more reliable and easier to use. The new authentication keys are more flexible, simple to maintain and apply to more than on iOS app.

Even though it has been years since authentication keys were introduced not every service supports them. FireBase and Amazon Pinpoint support authentication keys. Amazon SNS, Urban Airship, Twilio, and LeanPlum do not. Many open source software packages do not yet support authentication keys.

To create the required SSL certificate and export it as PEM file containing public and private keys:

  1. Navigate to Certificates, Identifiers & Profiles
  2. Create or Edit Your App ID.
  3. Enable Push Notifications for the App ID
  4. Add an SSL Certificate to the App ID
  5. Convert the certificate to PEM format

If you already have the SSL certificate set up for the app in the Apple Developer Center website you can skip ahead to Convert the certificate to PEM format. Keep in mind that you will run into problems if you do not also have the private key that was generated on the Mac that created the signing request that was uploaded to Apple.

Read on to see how to avoid losing track of that private key.

Navigate to Certificates, Identifiers & Profiles

Xcode does not control certificates or keys for push notifications. To create keys and enable push notifications for an app you must go to the Apple Developer Center website. The Certificates, Identifiers & Profiles section of your account controls App IDs and certificates.

To access certificates and profiles you must either have a paid Apple Developer Program membership or be part of a Team that does.

  1. Log into the Apple Developer website enter image description here
  2. Go to Account, then Certificates, Identifiers & Profiles enter image description here

Create an App ID

Apps that use push notifications can not use wildcard App IDs or provisioning profiles. Each app requires you to set up an App ID record in the Apple Developer Center portal to enable push notifications.

  1. Go to App IDs under Identifiers
  2. Search for your app using the bundle identifier. It may already exist.
  3. If there is no existing App ID for the app click the (+) button to create it.
  4. Select Explicit App ID in the App ID Suffix section. enter image description here
  5. Enter the bundle identifier for the app.
  6. Scroll to the bottom and enable Push Notifications. enter image description here
  7. Click Continue.
  8. On the next screen click Register to complete creating the App ID. enter image description here

Enable Push Notifications for the App ID

  1. Go to App IDs under Identifiers
  2. Click on the App ID to see details and scroll to the bottom. enter image description here
  3. Click Edit enter image description here
  4. In the App ID Settings screen scroll down to Push Notifications enter image description here
  5. Select the checkbox to enable push notifications. enter image description here

Creating SSL certificates for push notifications is a process of several tasks. Each task has several steps. All of these are necessary to export the keys in P12 or PEM format. Review the steps before proceeding.

Add an SSL Certificate to the App ID

  1. Under Development SSL Certificate click Create Certificate. You will need to do this later for production as well.
  2. Apple will ask you to create a Certificate Signing Request enter image description here

To create a certificate you will need to make a Certificate Signing Request (CSR) on a Mac and upload it to Apple.

Later if you need to export this certificate as a pkcs12 (aka p12) file you will need to use the keychain from the same Mac. When the signing request is created Keychain Access generates a set of keys in the default keychain. These keys are necessary for working with the certificate Apple will create from the signing request.

It is a good practice to have a separate keychain specifically for credentials used for development. If you do this make sure this keychain is set to be the default before using Certificate Assistant.

Create a Keychain for Development Credentials

  1. Open Keychain Access on your Mac
  2. In the File menu select New Keychain...
  3. Give your keychain a descriptive name, like "Shared Development" or the name of your application

Create a Certificate Signing Request (CSR)

When creating the Certificate Signing Request the Certificate Assistant generates two encryption keys in the default keychain. It is important to make the development keychain the default so the keys are in the right keychain.

  1. Open Keychain Access on your Mac.
  2. Control-click on the development keychain in the list of keychains
  3. Select Make keychain "Shared Development" Default enter image description here
  4. From the Keychain Access menu select Certificate Assistant, then Request a Certificate From a Certificate Authority... from the sub menu. enter image description here
  5. When the Certificate Assistant appears check Saved To Disk. enter image description here
  6. Enter the email address associated with your Apple Developer Program membership in the User Email Address field.
  7. Enter a name for the key in the Common Name field. It is a good idea to use the bundle ID of the app as part of the common name. This makes it easy to tell what certificates and keys belong to which app.
  8. Click continue. Certificate Assistant will prompt to save the signing request to a file.
  9. In Keychain Access make the "login" keychain the default again.

Creating the signing request generated a pair of keys. Before the signing request is uploaded verify that the development keychain has the keys. Their names will be the same as the Common Name used in the signing request.

enter image description here

Upload the Certificate Signing Request (CSR)

Once the Certicate Signing Request is created upload it to the Apple Developer Center. Apple will create the push notification certificate from the signing request.

  1. Upload the Certificate Signing Request
  2. Download the certificate Apple has created from the Certificate Signing Request enter image description here
  3. In Keychain Access select the development keychain from the list of keychains
  4. From the File menu select Import Items... enter image description here
  5. Import the certificate file downloaded from Apple

Your development keychain should now show the push certificate with a private key under My Certificates in Keychain Access:

enter image description here

At this point the development keychain should be backed up. Many teams keep their push certificates on secure USB drives, commit to internal version control or use a backup solution like Time Machine. The development keychain can be shared between different team members because it does not contain any personal code signing credentials.

Keychain files are located in ~/Library/Keychains.

Some third party push services require certificates in Privacy Enhanced Mail (PEM) format, while others require Public-Key Cryptography Standards #12 (PKCS12 or P12). The certificate downloaded from Apple can be used to export certificates in these formats - but only if you have kept the private key.

Convert the certificate to PEM format

  1. In Keychain Access select the development keychain created earlier.
  2. Select the push certificate in My Certificates. There should be a private key with it. ![Download CER push certificate](keychain/import complete.png)
  3. From the File menu select Export Items... enter image description here
  4. In the save panel that opens, select Privacy Enhanced Mail (.pem) as the file format.
  5. Save the file

How to delete files older than X hours

Does your find have the -mmin option? That can let you test the number of mins since last modification:

find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete

Or maybe look at using tmpwatch to do the same job. phjr also recommended tmpreaper in the comments.

How Connect to remote host from Aptana Studio 3

From the Project Explorer, expand the project you want to hook up to a remote site (or just right click and create a new Web project that's empty if you just want to explore a remote site from there). There's a "Connections" node, right click it and select "Add New connection...". A dialog will appear, at bottom you can select the destination as Remote and then click the "New..." button. There you can set up an FTP/FTPS/SFTP connection.

That's how you set up a connection that's tied to a project, typically for upload/download/sync between it and a project.

You can also do Window > Show View > Remote. From that view, you can click the globe icon in the upper right to add connections and in this view you can just browse your remote connections.

JavaScript - Hide a Div at startup (load)

Barring the CSS solution. The fastest possible way is to hide it immediatly with a script.

<div id="hideme"></div>
<script type="text/javascript">
    $("#hideme").hide();
</script>

In this case I would recommend the CSS solution by Vega. But if you need something more complex (like an animation) you can use this approach.

This has some complications (see comments below). If you want this piece of script to really run as fast as possible you can't use jQuery, use native JS only and defer loading of all other scripts.

how to run vibrate continuously in iphone?

iOS 5 has implemented Custom Vibrations mode. So in some cases variable vibration is acceptable. The only thing is unknown what library deals with that (pretty sure not CoreTelephony) and if it is open for developers. So keep on searching.