Q:

display URL in blackberry application

i have blackberry application and i try to display html text in a browser
i try
BrowserSession bSession = Browser.getDefaultSession();
bSession.displayPage("http://www.blackberry.com");

this page success but it display page in blackberry browser not in my own browser, and i don't need that
than i try
myBrowserField = new BrowserField();
add(myBrowserField);
myBrowserField.requestContent("http://www.blackberry.com");

this method displays error 104
and i try
BrowserFieldRequest test = new BrowserFieldRequest("http://www.blackberry.com");
BrowserField myBrowserField = new BrowserField();
add(myBrowserField);
myBrowserField.requestContent(test);

the last 2 methods
it gives no error and display empty browser but after 120 seconds it gives connection timeout
Note: i try different url but it didn't solve the problem
any help,

A:

Regarding the BrowserField,

If you are using a simulator, you should enable MDS-CS (Mobile Data System Connection Service)  for the BrowserField to work properly (I don't know any other way). If MDS-CS is not enabled, follow this guide "Testing a BlackBerry device application with the BlackBerry Smartphone Simulator" on how to enable it.
If the MDS-CS is enabled, but you are using JRE 7.0.0 (9930 simulator), then the problem is that the MDS-CS version supplied with JRE 7.0.0 is incorrect (the symptom is that the MDS-CS window doesn't show up when you run the simulator). Check my answer for "Blackberry BrowserField error in Simulator" or "Blackberry webview can not connect to internet and/or display a web page" for more details and instructions.

Hope that one of the aforementioned will work for you.


Q:

Nothing happens when clicking Update to 11.04

I am on Ubuntu 10.10 and each time I boot my OS it asks me to if I want to update to 11.04. I click "yeah, why not". It downloads 2 files, asks my password and that's all. Nothing happens.
EDIT
Ok, I've ran sudo apt-get update && sudo apt-get dist-upgrade and get downloadings and settings and after few seconds it stops after
ldconfig deferred processing now taking place

UPD 2
/etc/apt/sources.list
# deb cdrom:[Ubuntu 10.10 _Maverick Meerkat_ - Release i386 (20101007)]/ maverick main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.

deb http://ru.archive.ubuntu.com/ubuntu/ maverick main restricted
deb-src http://ru.archive.ubuntu.com/ubuntu/ maverick main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://ru.archive.ubuntu.com/ubuntu/ maverick-updates main restricted
deb-src http://ru.archive.ubuntu.com/ubuntu/ maverick-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://ru.archive.ubuntu.com/ubuntu/ maverick universe
deb-src http://ru.archive.ubuntu.com/ubuntu/ maverick universe
deb http://ru.archive.ubuntu.com/ubuntu/ maverick-updates universe
deb-src http://ru.archive.ubuntu.com/ubuntu/ maverick-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://ru.archive.ubuntu.com/ubuntu/ maverick multiverse
deb-src http://ru.archive.ubuntu.com/ubuntu/ maverick multiverse
deb http://ru.archive.ubuntu.com/ubuntu/ maverick-updates multiverse
deb-src http://ru.archive.ubuntu.com/ubuntu/ maverick-updates multiverse

## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://ru.archive.ubuntu.com/ubuntu/ maverick-backports main restricted universe multiverse
# deb-src http://ru.archive.ubuntu.com/ubuntu/ maverick-backports main restricted universe multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu maverick partner
# deb-src http://archive.canonical.com/ubuntu maverick partner

## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu maverick main
deb-src http://extras.ubuntu.com/ubuntu maverick main

deb http://security.ubuntu.com/ubuntu maverick-security main restricted
deb-src http://security.ubuntu.com/ubuntu maverick-security main restricted
deb http://security.ubuntu.com/ubuntu maverick-security universe
deb-src http://security.ubuntu.com/ubuntu maverick-security universe
deb http://security.ubuntu.com/ubuntu maverick-security multiverse
deb-src http://security.ubuntu.com/ubuntu maverick-security multiverse
deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen

A:

OK,
  it appears your package management system is a little screwed up.
edit your sources.list and # out the following entry (it isnt a standard repository that I recognise):
sudo nano /etc/apt/sources.list
#deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen

save then
See if the following cleans up the package management system:
sudo dpkg --configure -a
sudo apt-get -f install
sudo apt-get --fix-missing install
sudo apt-get clean
sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt-get clean
sudo apt-get autoremove
sudo apt-get update
sudo apt-get --reinstall --purge install update-manager
update-manager


Q:

Hide download link for 10 seconds? js

hey, how can I have my download link hidden, and make a count down type thing. Maybe have it count down from 10 and once it's done that have the download link appear, it would be best to do it in js right?
does anyone know how to do this? :D
Thanks

A:

You can use setInterval for this. setInterval behaves like a timer, where you can run a certain function periodically. Something like this should do the work(untested):
$(".link").hide();

var iteration = 0;
var timer = setInterval(function() {
    if(iteration++ >= 10) {
        clearTimeout(timer);
        $(".link").show();
        $(".counter").hide();
    }

    $(".counter").text(10 - iteration);
}, 1000);

This will initially hide the download link and run a function every second which counts down from 10. When we reaced ten, we hide the counter and show the link. ClearTimeout is used so that we don't count after we reached ten. Easy as dell.
Edit: As mentioned in the comments, this function is using jQuery to find the elements.


Q:

Why cannot I send a post to my WebApi through AngularJS's POST？

I've sent "mytest.html" onto the IIS and this project is made up of WebApi+Angularjs, and I cannot get a right request to my webApi……I don't know why?
【Codes for HTML】
<!DOCTYPE html>

    <meta charset="utf-8">

           <form method='post' name='myForm'>

                      Name：
                      <input type='text' ng-model='user.name' name='myname' required/>
                               Name cannot be empty!

                      Gender:

                        <input type='radio' ng-model='user.sex' name='mysex' value='{{s}}'>
                        {{s}}

                       Hobby:

                       <select ng-model='user.love' name='selLove'>
                           <option ng-repeat='l in loves' value='{{l}}'>{{l}}</option>
                       </select>
                       You cannot choose "Please choose"

             <input type ='submit' value='Submit' ng-click='isDisable();'/>
           </form>

【Codes for WebApi】
 namespace AngularJSDemo.Controllers
    {
        using Models;
        using System.Web.Http;

        public class DefaultController : ApiController
        {
            [HttpPost]
            public Person GetPerson([FromBody] Person p)
            {
                return p;
            }
        }
    }

【Codes for model】
 namespace AngularJSDemo.Models
    {
        public class Person
        {
            public string Name { get; set; }
            public string Sex { get; set; }
            public string Love { get; set; }
        }
    }

【Codes for Register】
namespace AngularJSDemo
{
    using Newtonsoft.Json.Serialization;
    using System.Net.Http.Formatting;
    using System.Web.Http;

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Formatters.Clear();

            var jsonFormatInstance = new JsonMediaTypeFormatter();
            jsonFormatInstance.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.Add(jsonFormatInstance);

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional,controller="Default" }
            );

        }
    }
}

Notice that the error in the console of my google chrome is:
angular.js:10695 POST http://localhost:60031/api 415 (Unsupported Media Type)

I've also tried to use json, but no help :(
$http({
                    method:'POST',
                    data: {p:$scope.user},
                    url:'http://localhost:60031/api/Default',
                    success: function (data){
                        alert(JSON.stringify(data));
                    }
                });

And my Content-Type is:
var app = angular.module('A',[],function($httpProvider){

                $httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
             });

Because I have different kinds of ports, so as to cross the domain, I also did this:
<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="*" />
        <add name="Access-Control-Request-Methods" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

A:

The URL is wrong
the URL should be : http://localhost:60031/api/Default
$http({
                        method:'POST',
                        data: requestData,
                        url:'http://localhost:60031/api/Default',
                        success: function (data){
                            alert(JSON.stringify(data));
                        }
                    });

Also, it is better to submit the data as JSON not form-urlencoded


Q:

Change style of an element when hover another element is not working

I created a triangle and it seems that the usual .something:hover .another{...} is not working on it, does anyone know what is the problem here?

.actions {
  display: flex;
  margin-top: 20px;
  max-width: 260px;
}

.action-reg-button {
  font-size: 13px;
  font-weight: bold;
  color: black;
  box-sizing: border-box;
  padding: 45px;
  padding-top: 10px;
  padding-bottom: 10px;
  transition: 150ms;
}

.action-log-button {
  font-size: 13px;
  font-weight: bold;
  color: white;
  box-sizing: border-box;
  padding: 25px;
  padding-top: 10px;
  padding-bottom: 11px;
  background-color: #0D5E5E;
  transition: 150ms;
  cursor: pointer;
}

.triangle {
  position: relative;
  width: 40px;
  margin-top: 12px;
}

.triangle-left {
  width: 0;
  height: 0;
  border-top: 37.5px solid transparent;
  border-bottom: 0px solid transparent;
  right: -1px;
  border-right: 40px solid #0D5E5E;
  position: absolute;
  right: 0px;
  transition: 150ms;
  z-index: 20;
}

.action-reg-button:hover {
  color: #b2b2b2;
  cursor: pointer;
}

.action-log-button:hover {
  color: #ddd;
  background-color: #2e2e2e;
}

.action-log-button:hover .triange-left {
  border-right: 40px solid #2e2e2e!important;
}

Register

Login

//More text
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.

A:

Issues
The selector:
.action-log-button:hover .triange-left {...

would imply this non-existent layout:

Login

CSS styles has a flow that cascades, meaning if you want to act upon a tag but affect an entirely different tag doing so, then you must ensure that the tag that gets affected follows or is a descendant of the tag your are acting upon.
So take a look at your layout it appears that hovering over .action-log-button could never affect .triangle-left because .action-log-button follows .triangle and .triangle is the tag to traverse to get to .triangle-left. Basically .tringle must be within .action-log-button or be placed after .action-log-button.

Solution
Place the HTML of .action-log-button right before .triangle* and use this ruleset:
.action-log-button:hover+.triangle .triangle-left {
  border-right-color: #2e2e2e;
}

*I know having the triangle sit after the button isn't what you want but read on
This means:

hover over .action-log-button
then go to + .triangle that's directly after
and them go inside .triangle to reach .triangle-left
and change its border-right-color: #2e2e2e;.
Note the change from border-right: 40px solid #2e2e2e;
as well as the changes in .triangle-left -- by separating the rulesets from shorthand we simplify the complexity of style which is less error prone.

Finally, in order to rectify the triangle and button swapping locations, we'll use the flexbox property: order In a default flow of DOM tags, the order goes from left to right then top to bottom. If you assign the flex-items (term for the tags that are the direct children of flex-container (term for a tag that has display: flex)) an order number, they will take those positions. So we'll assign .action-log-button order: 3 and .triangle order: 2. Although it will appear properly when rendered on a webpage, the positions in HTML are were the tags are in reality.

Demo
BTW the HTML tags are changed to more semantically sound types. Using
 or
 as a button is really bad. It's valid but it's just the worst.

.actions {
  display: flex;
  margin-top: 20px;
  max-width: 260px;
}

.action-reg-button {
  font-size: 13px;
  font-weight: bold;
  color: black;
  padding: 10px 45px 10px;
  transition: 0.2s;
  order: 1
}

.action-log-button {
  font-size: 13px;
  font-weight: bold;
  color: white;
  padding: 10px 25px 10px;
  background-color: #0D5E5E;
  cursor: pointer;
  transition: 0.2s;
  order: 3
}

.triangle {
  width: 40px;
  margin-top: 12px;
  order: 2
}

.triangle-left {
  width: 0;
  height: 0;
  border-top: 40px solid transparent;
  border-bottom: 0px solid transparent;
  border-right-width: 40px;
  border-right-style: solid;
  border-right-color: #0D5E5E;
  transition: 0.2s;
}

.action-reg-button:hover {
  color: #b2b2b2;
  cursor: pointer;
}

.action-log-button:hover+.triangle .triangle-left {
  border-right-color: #2e2e2e;
}

button {
  display: block;
}

.triangle-left {
  margin-top: -10px;
}
<fieldset class="actions">

  <button class="action-reg-button">Register</button>

  <button class="action-log-button">Login</button>

</fieldset>


Q:

How to make Recycler View not scroll when appbar snaps

I have made the snapping app bar like this:

Please note that when the scroll is left in the middle(i.e the title is half visible, then the app bar snaps automatically)
In case of google play this is what the snap looks like:

Now, I want the snap to work like the one in google play. Which is that when the snap occurs, then only the app bar should snap and the recycler view should not move. It would be better if the solution supported pre lollipop devices too.
Thanks!

A:

See my library Retractable Toolbar
You have to add this on build.gradle
compile 'it.michelelacorte.retractabletoolbar:library:1.0.0'

Than in your MainActivity.java use RecyclerView and this:
RetractableToolbarUtil.ShowHideToolbarOnScrollingListener showHideToolbarListener;
recyclerView.addOnScrollListener(showHideToolbarListener = new RetractableToolbarUtil.ShowHideToolbarOnScrollingListener(toolbar));

if (savedInstanceState != null) {
            showHideToolbarListener.onRestoreInstanceState((RetractableToolbarUtil.ShowHideToolbarOnScrollingListener.State) savedInstanceState
                    .getParcelable(RetractableToolbarUtil.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE));
}

This is effect:

EDIT:
Since 23.1.0 design library you can add |snap attribute to your ToolBar layout:
       <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|enterAlways|snap />

It should be more or less what you are looking.

A:

I found a solution that works quite well in my project. It consists of 2 behaviors, one for the AppBarLayout and another one for the scrolling container. You can find it on Github here: appbar-snap-behavior
It's quite easy to install it:
compile "com.github.godness84:appbar-snap-behavior:0.1.1"

Remember to add maven { url "https://jitpack.io" } in your root build.gradle at the end of repositories:
allprojects {
        repositories {
            ...
            maven { url "https://jitpack.io" }
        }
}

Then:

add app:layout_behavior="com.github.godness84.appbarsnapbehavior.AppBarSnapBehavior" to your AppBarLayout
use app:layout_behavior="com.github.godness84.appbarsnapbehavior.ScrollingViewBehavior" into your scrolling container.

Unfortunately, since the default behavior of the AppBarLayout is replaced, some features are not available anymore (for example AppBarLayout.setExpanded()), but in normal situations it works! Give it a try and let me know.


Q:

Node.js Tinymce storing rich text

I've got a form with Tinymce editor so any user can format it's text to look good.
If he writes any malicious script in the form, it is automatically escaped. But if the user cheats and posts the form using something like Postman, he can submit unescaped scripts (like iframes).
How do I validate the Tinymce input? If I use the validator plugin with the "escape" function, it removes all formatting. I tried to use some Google Caja plugins for node to sanitize the input but it's not removing any malicious code, like iframes. Any help?

A:

I've found a pretty good Node.js module to sanitize html input.
It's called Sanitize-html and it does exactly what I want, removes dangerous html tags from the input string and you can add/remove specific tags


Q:

which is faster: i=i+2 or i+=2?

Consider the below code snippet:
for(i=0;i<10;i+=2) // 1
for(i=0;i<2;i=i+2) // 2

Which one will be better to use?
Does it make any difference in the performance?

A:

The following took 0.0260015 seconds
for (i = 0 ; i < 10000000 ; i += 2)

And this took 0.0170010
for (i = 0 ; i < 10000000 ; i = i + 2)

@MasterID is right though when I enabled 'optimize code' both reported 0.0150009 seconds

A:

There is no definite answer to your question. It depends on how smart your compiler is among other things (optimization level, ...) and on the target platform. This is not a C language question. The language is not  more or less performant by itself. It just depends on what the compiler builds out of it. So test it for your use case if performance matters at all...
Otherwise my advice, just write it in the way you feel it more readable.

A:

The first option is as fast as the second, at least.
Although any compilation optimization would generate the same assembly code.


Q:

Queuing tasks for a service

I have a service which is getting data on a REST server. My service needs to make 3 requests on the server to get 3 different JSON objects. But I just learned that it is impossible de call multiple times a same service at the same time.
I thought then about queuing the tasks which would call the service for each object. I'm not sure how to implement this. Is there any class or library which does this in Android or Java ?
Thanks for your help.

A:

As Eran and pskink suggested, I implemented the IntentService which was exactly what I needed to queue the requests.
As the documentation says :

The IntentService does the following:
Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.


Q:

How to sum all values in a column in Jaspersoft iReport Designer?

I have below similar report in Jaspersoft iReport Designer, but not able to figure out how to sum all values present in vertical column "Doctor Payment" to get a total of "1601"? Length of this columns is variable (i.e. no of rows vary according to size of database & its update frequency ).
Is there any variable like $V{COLUMN_COUNT} (actually gives no of rows, here 5),
which gives sum of all values in a column? If no, how to do sum?
Doctor ID   Doctor Payment
 A1             123
 B1             223
 C2             234
 D3             678
 D1             343
Total          1601

A:

It is quite easy to solve your task. You should create and use a new variable for summing values of the "Doctor Payment" column.
In your case the variable can be declared like this:
<variable name="total" class="java.lang.Integer" calculation="Sum">
    <variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>

the Calculation type is Sum;
the Reset type is Report;
the Variable expression is $F{payment}, where $F{payment} is the name of a field contains sum (Doctor Payment).

The working example.
CSV datasource:

doctor_id,payment
A1,123
B1,223
C2,234
D3,678
D1,343

The template:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ...>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="doctor_id" class="java.lang.String"/>
    <field name="payment" class="java.lang.Integer"/>
    <variable name="total" class="java.lang.Integer" calculation="Sum">
        <variableExpression><![CDATA[$F{payment}]]></variableExpression>
    </variable>
    <columnHeader>
        <band height="20" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Doctor ID]]></text>
            </staticText>
            <staticText>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Doctor Payment]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{doctor_id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{payment}]]></textFieldExpression>
            </textField>
        </band>
    </detail>

        <band height="20">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>

                </textElement>
                <text><![CDATA[Total]]></text>
            </staticText>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
            </textField>
        </band>

</jasperReport>

The result will be:

You can find a lot of info in the JasperReports Ultimate Guide.

A:

iReports Custom Fields for columns
(sum, average, etc)

Right-Click on Variables and click Create Variable
Click on the new variable
a.   Notice the properties on the right
Rename the variable accordingly
Change the Value Class Name to the correct Data Type
a. You can search by clicking the 3 dots
Select the correct type of calculation
Change the Expression
a.    Click the little icon
b.    Select the column you are looking to do the calculation for
c.    Click finish
Set Initial Value Expression to 0
Set the increment type to none
Leave Incrementer Factory Class Name blank
Set the Reset Type (usually report)
Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)
Double Click the new Text Field
Clear the expression “Text Field”
Select the new variable
Click finish
Put the new text in a desirable position 


Q:

In Ruby how do you sort one multi dimendional array by another multi dimensional array?

Lets say I have an array : a=[[1,2,3],[4,5]]
and I have another array : b=[[2.5,1.5,3.5],[1.5,2.5]]
I need to sort 'a' with respect to 'b'.
i.e the output should be = [[3,1,2],[5,4]]
I tried but my code seemed to be very lengthy. It would be great if you could help me out.Thanks!

A:

This gives your sample output for your sample input, so hopefully it's what you want (it sorts the values of each subarray in the first array by the value at the same position in the corresponding subarray of the second array, descendingly):
class Array
  def sort_by_other_array(arr)
    zip(arr).sort_by {|x,y| y}.map {|x,y| x}
  end
end

a=[[1,2,3],[4,5]]
b=[[2.5,1.5,3.5],[1.5,2.5]]
a.zip(b).map {|x,y| x.sort_by_other_array(y).reverse}
#=> [[3, 1, 2], [5, 4]]


Q:

java - print() does not output char array if the array has int value?

I am bit confused about how Java handle conversion.
I have char array consist of 0 (not '0')
char[] bar = {0, 'a', 'b'};
System.out.println(String.valueOf(bar));

When this happens println method does not output anything. But when I treat zero as character:
char[] bar = {'0', 'a', 'b'};
System.out.println(String.valueOf(bar));

Then it output "0ab" as expected.
My understanding was if you declare array of primitive type with empty value like:
char[] foo = new char[10];
those empty cells have default value of 0 in Java, so I thought it was ok to have 0 in the char array but seems like not. Could anyone explain why print method is not even outputting 'a' and 'b' ?

A:

As you have discovered, the character value of the integer 0 and the character literal '0' are different.  To convert a number to the character representation of a decimal digit, you need to do something like this:
int digit = ... // some value between 0 and 9
char ch = (char)(digit + '0');

You can also do this as:
int digit = ...
char ch = Character.forDigit(digit, radix);

where radix has a value between Character.MIN_RADIX and Character.MAX_RADIX.  A  radix of 10 gives you a decimal digit.  See Character.forDigit(int,int).
The character value zero is the Unicode codepoint NULL (0x0000).  This is a non-displayable "control character".  If you try to display it, you are liable to see either nothing at all (as you are getting) or a special glyph that means "I cannot display this character".


Q:

Prove acceleration in orbit with newtons second law

I want to prove that the acceleration in a orbit at a given point r=(x,y) is $a=-\frac{GM}{R^3}r$ (My professor said this can be proven by newtons second law, but he never explained in detail how). I know that N2 gives $F=ma$ substituted into $F=\frac{GMm}{R^2}r$ gives $a=\frac{GM}{R^2}r$ (Where r is the positional vector of the orbiting point). How can you prove    $a=-\frac{GM}{R^3}r$ ?

A:

Gravitational force is attractive, so its direction is opposite to the radial vector, which points outward. And its magnitude is $\frac{GMm}{r^2}$.
So $\vec{F}=-\frac{GMm}{r^2}\hat{r}= -\frac{GMm}{r^3}\vec{r}$, where $\hat{r}=\frac{\vec{r}}{r}$ is the unit vector joining the two point masses $M$ and $m$.
And Newton's second law says force is mass times acceleration.


Q:

How can I simulate the same Window layout as Finder?

How can I make a window with same basic structure as the Finder window (a menu/source list to the left with icons that can be organized, and the content in a larger view on the right)?

A:

To replicate the content view of the Finder, use:

Icon view: NSCollectionView
List view: NSOutlineView
Column view: NSBrowser
CoverFlow: Custom on top, NSOutlineView (list view) below

You can probably find a third-party open-source implementation of CoverFlow for the Mac with a bit of Googling.
As Williham Totland already mentioned, the way to make a source list (sidebar) is NSOutlineView. There are a few questions here on Stack Overflow about getting it to look more like that.
A toolbar is, of course, NSToolbar.


Q:

Double is not stored correctly in MySQL database

I have an MVC application which has a restful service that updates latitude and longitude to the database. I am sending the values to the API as string and its converted to Double before it is stored in database as Double. Here is the code I am using to convert string to double:
Double _latitude, _longitude;
try
{
     Double.TryParse(lattitude, NumberStyles.Any,CultureInfo.CurrentCulture, out _latitude);
     Double.TryParse(Longtitude, NumberStyles.Any,CultureInfo.CurrentCulture, out _longitude);
}
catch(Exception e)
{
     _latitude = 0;
     _longitude = 0;
}

When its stored in database I am missing decimal points. For example:

53.345634 is stored as 53345634

I have this working on development environment running on Windows 2012. But when its moved to Windows 2008 production server I am seeing this issue.

A:

Specifying correct IFormatProvider/CultureInfo
The behavior that you observed might be caused by the fact that two machines have different CurrentCultures. Default value of CurrentCulture depends on a version of Windows.
To get consistent results across various machines, you should provide a specific CultureInfo (or any other class implementing IFormatProvider) for Parse or TryParse method, e.g.
// using System.Globalization;
double value = Double.Parse(stringValue, CultureInfo.InvariantCulture);

or
double valueUsEnglish = Double.Parse(stringValue, new CultureInfo("en-US"));

Parse method uses a culture-specific decimal point symbol and group-separator symbol. In some languages (e.g. in English) decimal point symbol is a dot whereas in others (e.g. in Polish) it's a comma. Group-separator symbols are also different in various languages.
If 53.345634 is parsed as 53345634, your computer uses a culture where dot is a group-separator.
Parse vs TryParse
You should also think whether using Parse of TryParse method is more appropriate.
If during normal operation your program expects invalid output (e.g. it a user-provided value), you should definitely use TryParse and inspect returned value. TryParse returns a bool indicating whether parsing was successful and doesn't throw exceptions.
If the value that you are parsing should never be wrong (e.g. you are parsing resources that bounded with your program) you can use Parse. If you have some way to recover or provide some additional information to the user, you can catch appropriate exceptions. According to documentation possible exceptions are: ArgumentNullException,  FormatException and OverflowException.


Q:

SoundManager 2 playing same sound more times at once

I`m making a game (top view, walking with heroe and doing some actions). Using HTML5 canvas for graphics and SoundManager 2 for the game audio.
In game world is many objects, that making sound, and sound volume is dependent of heroe distance (if object, which making sound, is near to heroe, then it sound will be louder).
I doing like this:
soundManager.play(soundId,{volume:vol});

So, I understand, that volume parameter is for sound with specified soundId (if I play this sound more times at the same time, then it all will be played with equal volume).
Can i do something, to get, that more objects uses one sound at the same time, but with different volume?

A:

Didn't get any answer, so I fix it self and it`s work for me (maybe not the right way).
Before adding audio samples to SoundManager, I collect information from game map, to get all objects, who uses sound samples, then simple added samples for each object - equal sound files with different ID`s.
I add this answer, because maybe someone find it helpful.


Q:

Remove spaces in words including ampersand with Regex

In python3, using the re.sub(pattern, replacement, string), I have been able to remove spaces around ampersand. For instance, the following phrases should be modified as follows:
"A & D ALTERNATIVE SOLUTIONS" to "AD ALTERNATIVE SOLUTIONS"
"WESTMOUNT PLUMBING & HEATING" to "WESTMOUNT PLUMBING HEATING"
"A PANORAMIC VIEW B & B" to "A PANORAMIC VIEW BB"
I have been able to fix the first two patterns, but I am having problems with the third, I tried the following:
import re
#str="A & D ALTERNATIVE SOLUTIONS LTD."
#str="WESTMOUNT PLUMBING & HEATING LTD."
str= "A PANORAMIC VIEW B & B"

str = re.sub('(?<=\\&)\s','',str)
str = re.sub('(?<=^[A-Z])\s','',str)
str = re.sub('[^\w\s]','',str)

print(str)

How could I get all the patterns?

A:

you could do the following:
strlist = ["A & D ALTERNATIVE SOLUTIONS LTD.","WESTMOUNT PLUMBING & HEATING LTD.", "A PANORAMIC VIEW B & B"]
pattern = r'(\w{2}\s)?\s?& (\w{2})?'

 [re.sub(pattern,r'\1\2',str_) for str_ in strlist]
Out[120]:
['AD ALTERNATIVE SOLUTIONS LTD.',
 'WESTMOUNT PLUMBING HEATING LTD.',
 'A PANORAMIC VIEW BB']


Q:

How to write MifareClassic with Custom Key

I need to find a solution to write Mifare Classic 1 K Tag with Custom Key. I am unable to write it, I have tried with every option but unfortunately all the time I get the error "IOException: Transceive Failed".
Below is my code snippet:
byte custom_key[]={
  (byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff
};

// 16 bytes of Data. Otherwise it was throwing IllegalArgumentException .
byte[] data="Hello world of N".getBytes();
getMfc().connect();

if(getMfc().authenticateSectorWithKeyA(4, custom_key)) {
  getMfc().writeBlock(3, data); // Here I receive IOException all the time.
} else {
  getMfc().close();
}

Please help me in this regard. I need to write Mifare Classic 1 K Tag with my own key.

A:

You authenticate to sector 4 and then you try to write to block 3. Block 3 is in sector 0, so this will always fail. Try authenticating to sector 0 instead.
BTW: Please, don't write random data to a sector trailer (such as block 3). It will likely lock up the sector with no way to recover.


Q:

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

I've just downloaded and installed XAMPP 5.6.11 and started all the tools from the control panel. I've seen that one of it's new features is that it has a Welcome/Dashboard page.
Previously, going to 127.0.0.1 would take me to a language selection page and then to a orange-yellow page where I could configure XAMPP. Now, going to 127.0.0.1 or hitting Apache's "Admin" button in the XAMPP Control Panel takes me to the dashboard/welcome page no matter what.
One curious thing: attempting to go to http://localhost/xampp/ shows me an empty directory listing. I figured perhaps my install was botched so I reinstalled XAMPP. Still no luck. Even tried installing Apache 5.5.27. Same problem.
Am I missing something?

A:

Open the htdocs folder there will be index.php file.
In that file script is written to go in dashboard folder and show dashboard.
So you just have to comment it or delete that script and write any code save it and run http://localhost now dashboard screen will not open and you will see what you have written in that file.

A:

Delete the file(index.php) from your xampp folder, you will get the list of directories and files from htdocs folder.

A:

Hey here is the solution for windows 7+.
You need admin rights to make changes to the hosts file
Right click on your favorit text-editor and select "run as administrator" before opening the file
Open the following file "c:/windows/system32/driver/etc/hosts"
Enter the line:
127.0.0.1 localhost

Next: Define a virtual host in /xampfolder/apache/conf/extra/httpd-vhosts.conf
<VirtualHost  127.0.0.1>
  DocumentRoot "c:\your\document\root"
  ServerName localhost
    <Directory "c:\your\document\root">
      Options Indexes FollowSymLinks Includes ExecCGI
      Options All
      AllowOverride All
      Require all granted
    </Directory>
</VirtualHost>

Restart your apache!
Now you can enter http://localhost in your browser and access your page.
Pro-Tip:
You can use other names as localhost or have multiple localhosts this way. Just enter the names in the hosts file and define your virtual hosts.


Q:

How to write a single pixel or a line of pixels to GeoTIFF using GDAL/Python

Let's say I want to write a single pixel or a 1D array of pixels (e.g.all at the same latitude) of pixels to a single-band of a Float32 GeoTIFF using the Python GDAL bindings.  How can I do so?  Or is it not possible?
I currently have the following method for truly 2D ndarrays. But occasionally I get requests for a pixel or line of pixels, which cause this method to fail.
raster_band.WriteArray(my_pixel_array)

FURTHER CLARIFICATION:
I'm trying to write a new image where the entire extent of the new image is either just one pixel or just a line of pixels. Thus, I've tried just setting xoff and yoff to 0, and this fails the same way as without xoff and yoff. The error I'm getting is expected array of dim 2, e.g. when the shape of my ndarray is (4,) (and when the GDAL raster is initialized with RasterXSize to 4 and RasterYSize to 1 via a pertinent out_raster.SetGeoTransform (EPSG:4326 location and size) method).

A:

The WriteArray() method has two useful optional arguments to accomplish this:

xoff: specifies the offset on the x axis.
yoff: specifies the offset on the y axis.

This means that it will write a 2D array (this is very important) to the band, starting from the specified offsets (which are 0 by default). This is very useful because you don't have to read the whole array into memory, change one pixel or one row, and then write it again. This lets you specify where you want to write the data in the array. Imagine you wanted to replace all the pixels in the last row of the raster with values of 100, and you also wanted to replace the most upper right pixel with a value of 99.
import gdal
import numpy as np

# open the raster in writing mode
ds = gdal.Open('path/to/raster.tif', 1)

# get first band and raster dimensions
band = ds.GetRasterBand(1)
cols = ds.RasterXSize
rows = ds.RasterYSize

# create the arrays you are going to write
row_data = np.full(shape=(1, cols), fill_value=100)  # note that eventhough it contains just one row of data it is a 2D array
pixel_data = np.array([[99]])  # again, a 2D array. This time it contains just one value

# write the arrays specifying the proper offsets
band.WriteArray(row_data, xoff=0, yoff=(rows-1))
band.WriteArray(pixel_data, xoff=(cols-1), yoff=0)

# save and close the file
del band, ds

Note that the WriteArray() method only accepts a 2D array, whether it has just one value, one row, or many rows. Furthermore, if you try to write an array with higher dimensions (e.g. you set the offset to be the last row but pass an array with two rows or more columns that ds.RasterXSize), it will throw an Exception because the array does not fit.


Q:

Find matching strings in an array and re-write the array

I need your help.
I would like to be able to find a string in an array and based on as to whether or not the value has been found, to be able to mofiy the array accordingly.
var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"]

Some processing now....
If ("BNI to" matches what is in the array temp then) {

    Find the instance of "BNI to" and re-label to single name: Briefing Notes (Info)
}

If ("BNA to" matches what is in the array temp then) {

    Find the instance of "BNA to" and re-label to single name: Briefing Notes (Approval)

}

Re-write and output the same temp array to now read as:
var temp = ["Briefing Notes (Info)", "Briefing Notes (Approval)", "Media Call", "Report Paper", "Issue Paper"]

A:

Do a map - replace what you need - then run a reduce to get rid of duplicates:
var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"];

var formatted = temp.map(function(str) {
    //Replace strings
    if (str.indexOf("BNI to") > -1) {
        return "Briefing Notes (Info)"
    } else if (str.indexOf("BNA to") > -1) {
        return "Briefing Notes (Approval)";
    } else {
        return str;
    }
}).reduce(function(p, c, i, a) {
    //Filter duplicates
    if (p.indexOf(c) === -1) {
        p.push(c);
    }
    return p;
}, []);

//Output: ["Briefing Notes (Info)", "Briefing Notes (Approval)", "Media Call", "Report Paper", "Issue Paper"]


Q:

C++ После выполнения одной функции execl, не выполняются другие

Стоит задача: запустить 4 процесса системными вызовами: execl, execlp, execv, execvp; вывести идентификаторы этих процессов и закрыть их в обратном порядке.
Мой код:
int main(int argc, char *argv[])
{
    // Путь к выполняемому процессу
    auto firstPath = "/home/artem/CLionProjects/first_proc/cmake-build-debug/first_proc";
    auto secondPath = "/home/artem/CLionProjects/second_proc/cmake-build-debug/second_proc";

    execl(firstPath, "Функция execl" ,"Лабораторная", "работа", "№", "4", NULL);
    execlp(secondPath, "Лаба", "4", NULL);

    return 0;
}

Почему получается так, что после выполнения execl все, что стоит ниже нее не выполняется? Как это исправить?

A:

Дело в том, что функции семейства exec* замещают текущий исполняемый образ вновь запущенным. То есть, после выполнения первой execl вашей программы больше не существует, так как она замещается той которую вы запустили!
Как это исправить? А вот в этом и состоит суть лабораторной работы № 4.

A:

Нужно делать так: сначала создать новый процесс и потом уже в нем вызывать  execvp:
bool launch(const char* path, const char* arg)
{
    int pid = fork();
    if (pid < 0)
    {
        return false;
    }
    else if (pid == 0)
    {
        //Дочерний процесс
        execvp(path, arg);
        _exit(72);
    }
    return true;
}

Это схематичный пример, подробней можно посмотреть в библиотеке POCO


Q:

How can I use two versions of the same package?

What do I need to change in the cabal file and or Login.hs?
Note that other .hs files in this package need a different conduit version.
(src https://github.com/gertcuykens/haskell-design)
gert@couchdb:~/Downloads/haskell-design/src$ ghci Chat.hs
GHCi, version 7.4.2: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 2] Compiling Login            ( Login.hs, interpreted )

Login.hs:27:9:
    No instance for (Control.Monad.Trans.Control.MonadBaseControl
                       IO m0)
      arising from a use of `withManager'
    Possible fix:
      add an instance declaration for
      (Control.Monad.Trans.Control.MonadBaseControl IO m0)
    In the expression: withManager
    In the expression:
      withManager
      $ \ manager
          -> FB.runFacebookT app manager
             $ FB.getUserAccessTokenStep1 url perms
    In an equation for `fbUrl':
        fbUrl
          = withManager
            $ \ manager
                -> FB.runFacebookT app manager
                   $ FB.getUserAccessTokenStep1 url perms

Login.hs:27:55:
    Couldn't match expected type `http-conduit-1.4.1.8:Network.HTTP.Conduit.Manager.Manager'
                with actual type `http-conduit-1.5.0.3:Network.HTTP.Conduit.Manager.Manager'
    In the second argument of `FB.runFacebookT', namely `manager'
    In the expression: FB.runFacebookT app manager
    In the expression:
      FB.runFacebookT app manager $ FB.getUserAccessTokenStep1 url perms

Login.hs:31:13:
    No instance for (Control.Monad.Trans.Control.MonadBaseControl
                       IO m1)
      arising from a use of `withManager'
    Possible fix:
      add an instance declaration for
      (Control.Monad.Trans.Control.MonadBaseControl IO m1)
    In the expression: withManager
    In the expression:
      withManager
      $ \ manager
          -> FB.runFacebookT app manager
             $ do { t <- FB.getUserAccessTokenStep2 url [...];
                    u <- FB.getUser "me" [] (Just t);
                    .... }
    In an equation for `fbEmail':
        fbEmail c
          = withManager
            $ \ manager
                -> FB.runFacebookT app manager
                   $ do { t <- FB.getUserAccessTokenStep2 url ...;
                          .... }

Login.hs:31:59:
    Couldn't match expected type `http-conduit-1.4.1.8:Network.HTTP.Conduit.Manager.Manager'
                with actual type `http-conduit-1.5.0.3:Network.HTTP.Conduit.Manager.Manager'
    In the second argument of `FB.runFacebookT', namely `manager'
    In the expression: FB.runFacebookT app manager
    In the expression:
      FB.runFacebookT app manager
      $ do { t <- FB.getUserAccessTokenStep2 url [c];
             u <- FB.getUser "me" [] (Just t);
             return $ FB.userEmail u }

Login.hs:37:12:
    No instance for (Control.Monad.Trans.Control.MonadBaseControl
                       IO m2)
      arising from a use of `withManager'
    Possible fix:
      add an instance declaration for
      (Control.Monad.Trans.Control.MonadBaseControl IO m2)
    In the expression: withManager
    In the expression:
      withManager
      $ \ manager
          -> FB.runFacebookT app manager
             $ do { t <- FB.getUserAccessTokenStep2 url [...];
                    u <- FB.getUser "me" [] (Just t);
                    .... }
    In an equation for `fbName':
        fbName c
          = withManager
            $ \ manager
                -> FB.runFacebookT app manager
                   $ do { t <- FB.getUserAccessTokenStep2 url ...;
                          .... }

Login.hs:37:58:
    Couldn't match expected type `http-conduit-1.4.1.8:Network.HTTP.Conduit.Manager.Manager'
                with actual type `http-conduit-1.5.0.3:Network.HTTP.Conduit.Manager.Manager'
    In the second argument of `FB.runFacebookT', namely `manager'
    In the expression: FB.runFacebookT app manager
    In the expression:
      FB.runFacebookT app manager
      $ do { t <- FB.getUserAccessTokenStep2 url [c];
             u <- FB.getUser "me" [] (Just t);
             return $ FB.userName u }
Failed, modules loaded: none.
Prelude>

A:

You could specify version in your cabal-file and use cabal-dev ghci(if you use cabal-dev).
And you can not use two versions of same package, but in your case you can use fb from github:
$ git clone https://github.com/snoyberg/fb.git
$ cd fb
$ cabal install fb.cabal


Q:

SQL Inner Join and further requirements

I would like to return table entries from an inner join which do not have any matching entries in the second column.
Lets consider the following two tables:
Table one:
Name       Number
A          1
A          2
A          4

Table two:
Name       ID
A          3

The query should return Name=A ID=3. If ID would be 4, the query should not return anything. Is this even possible in SQL? Thanks for any hints!
Edit:
the joined table would look like this:
Name       Number    ID
A          1         3
A          2         3
A          4         3

So if I do this query I get no entries in the result set:
SELECT * FROM TABLE_ONE INNER JOIN TABLE_TWO ON TABLE_ONE.NAME=TABLE_TWO.NAME WHERE NUMBER=ID

Exactly in this situation I would like to get the Name returned!

A:

SELECT *
FROM   Table2
WHERE  NOT EXISTS (
         SELECT *
         FROM   Table1
         WHERE  Table1.Name = Table2.Name AND Table1.Number = Table2.ID
       )


Q:

How can I stop the goroutine based on the returned value from that goroutine

Like here I created a go playground sample: sGgxEh40ev, but cannot get it work.
quit := make(chan bool)
res := make(chan int)

go func() {
    idx := 0
    for {
        select {
        case <-quit:
            fmt.Println("Detected quit signal!")
            return
        default:
            fmt.Println("goroutine is doing stuff..")
            res <- idx
            idx++
        }
    }

}()

for r := range res {
    if r == 6 {
        quit <- true
    }
    fmt.Println("I received: ", r)
}

Output:
goroutine is doing stuff..
goroutine is doing stuff..
I received:  0
I received:  1
goroutine is doing stuff..
goroutine is doing stuff..
I received:  2
I received:  3
goroutine is doing stuff..
goroutine is doing stuff..
I received:  4
I received:  5
goroutine is doing stuff..
goroutine is doing stuff..
fatal error: all goroutines are asleep - deadlock!

Is this possible? Where am I wrong

A:

The problem is that in the goroutine you use a select to check if it should abort, but you use the default branch to do the work otherwise.
The default branch is executed if no communications (listed in case branches) can proceed. So in each iteration quit channel is checked, but if it cannot be received from (no need to quit yet), default branch is executed, which unconditionally tries to send a value on res. Now if the main goroutine is not ready to receive from it, this will be a deadlock. And this is exactly what happens when the sent value is 6, because then the main goroutine tries to send a value on quit, but if the worker goroutine is in the default branch trying to send on res, then both goroutines try to send a value, and none is trying to receive! Both channels are unbuffered, so this is a deadlock.
In the worker goroutine you must send the value on res using a proper case branch, and not in the default branch:
select {
case <-quit:
    fmt.Println("Detected quit signal!")
    return
case res <- idx:
    fmt.Println("goroutine is doing stuff..")
    idx++
}

And in the main goroutine you must break out from the for loop so the main goroutine can end and so the program can end as well:
if r == 6 {
    quit <- true
    break
}

Output this time (try it on the Go Playground):
goroutine is doing stuff..
I received:  0
I received:  1
goroutine is doing stuff..
goroutine is doing stuff..
I received:  2
I received:  3
goroutine is doing stuff..
goroutine is doing stuff..
I received:  4
I received:  5
goroutine is doing stuff..
goroutine is doing stuff..


Q:

Google Maps API v2 Android Studio Map not loading

Please keep in mind that I have read through the hundreds of similar questions such as this but I've seemed to cross off the check list of everything that has been stated in the instructions on how to get the Google maps to start working.
First things first, I'll show my code, then I'll narrate what has been happening.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="elephant.tuskapp"
      android:versionCode="49"
      android:versionName="4.6">

     <uses-sdk android:minSdkVersion="15"/>
     <uses-feature
         android:glEsVersion="0x00020000"
         android:required="true"/>
     <permission android:name="elephant.tuskapp.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>
     <uses-permission android:name="elephant.tuskapp.permission.MAPS_RECEIVE"/>
     <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.ACCESS_GPS"/>
     <uses-permission android:name="android.permission.ACCESS_LOCATION"/>
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.CALL_PHONE"/>
     <uses-permission android:name="android.permission.WAKE_LOCK"/>
     <uses-permission android:name="android.permission.SEND_SMS"/>
     <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-feature android:name="android.hardware.camera"/>
     <uses-feature android:name="android.hardware.camera.autofocus"/>

     <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
     <uses-permission android:name="android.permission.GET_ACCOUNTS"/>

     <permission android:name="elephant.tuskapp.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
     <uses-permission android:name="elephant.tuskapp.permission.C2D_MESSAGE"/>

     <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

     <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:name=".NVtuskapplication"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <meta-data
             android:name="com.google.android.gms.version"
             android:value="@integer/google_play_services_version" />

       <activity
             android:name=".activity.MainActivity"
             android:label="@string/activity_name">
            <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
         </activity>

         <receiver android:name="elephant.tuskapp.service.AlarmReceiver"></receiver>

    <receiver android:name="elephant.tuskapp.service.TimeSynchronizer">
         <intent-filter>
              <action android:name="android.intent.action.ACTION_TIME_CHANGED"/>
              <action android:name="android.intent.action.TIMEZONE_CHANGED"/>
        </intent-filter>
    </receiver>

    <service android:name=".service.GPSService"></service>
    <service android:name=".service.RouteUpdateService"></service>

    <meta-data android:name="com.google.android.gms.version"
               android:value="@integer/google_play_services_version"/>

    <receiver
            android:name=".service.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
            <category android:name="elephant.tuskapp"/>
        </intent-filter>
    </receiver>
    <service android:name=".service.GcmIntentService"/>

    <meta-data
        android:name="io.fabric.ApiKey"
        android:value="key" />

    <!-- google maps api v2-->
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="key"/>
</application>

Layout XML
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/map"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:name="com.google.android.gms.maps.MapFragment"/>

Main Activity
package elephant.tuskapp.activity;
import android.app.Activity;
import android.os.Bundle;
import elephant.tuskapp.R;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.route_details);
    }
}

When I run my app, I see a blank canvas with the Google logo on the bottom left corner. The Logcat prints out the following error:
-22 20:47:24.822  22720-22720/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: free.elephant.tuskapp, PID: 22720
java.lang.RuntimeException: Unable to start activity ComponentInfo{free.elephant.tuskapp/elephant.tuskapp.activity.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2301)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2361)
      at android.app.ActivityThread.access$800(ActivityThread.java:147)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:135)
      at android.app.ActivityThread.main(ActivityThread.java:5232)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:767)
      at android.view.LayoutInflater.inflate(LayoutInflater.java:486)
      at android.view.LayoutInflater.inflate(LayoutInflater.java:418)
      at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
      at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
      at android.app.Activity.setContentView(Activity.java:2161)
      at elephant.tuskapp.activity.MainActivity.onCreate(MainActivity.java:18)
      at android.app.Activity.performCreate(Activity.java:5984)
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2254)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2361)
      at android.app.ActivityThread.access$800(ActivityThread.java:147)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:135)
      at android.app.ActivityThread.main(ActivityThread.java:5232)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.RuntimeException: API key not found.  Check that <meta-data android:name="com.google.android.geo.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml
      at com.google.maps.api.android.lib6.d.fk.a(Unknown Source)
      at com.google.maps.api.android.lib6.a.g.a(Unknown Source)
      at com.google.android.gms.maps.internal.CreatorImpl.b(Unknown Source)
      at com.google.android.gms.maps.internal.CreatorImpl.b(Unknown Source)
      at com.google.android.gms.maps.internal.i.onTransact(SourceFile:62)
      at android.os.Binder.transact(Binder.java:380)
      at com.google.android.gms.maps.internal.zzc$zza$zza.zzr(Unknown Source)
      at com.google.android.gms.maps.MapFragment$zzb.zzvu(Unknown Source)
      at com.google.android.gms.maps.MapFragment$zzb.zza(Unknown Source)
      at com.google.android.gms.dynamic.zza.zza(Unknown Source)
      at com.google.android.gms.dynamic.zza.onInflate(Unknown Source)
      at com.google.android.gms.maps.MapFragment.onInflate(Unknown Source)
      at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2117)
      at android.app.Activity.onCreateView(Activity.java:5333)
      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:737)
      at android.view.LayoutInflater.inflate(LayoutInflater.java:486)
      at android.view.LayoutInflater.inflate(LayoutInflater.java:418)
      at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
      at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
      at android.app.Activity.setContentView(Activity.java:2161)
      at elephant.tuskapp.activity.MainActivity.onCreate(MainActivity.java:18)
      at android.app.Activity.performCreate(Activity.java:5984)
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2254)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2361)
      at android.app.ActivityThread.access$800(ActivityThread.java:147)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:135)
      at android.app.ActivityThread.main(ActivityThread.java:5232)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

Familiar right? You see it in a lot of other questions. I think what differentiates my question from the others is I may have a problem with different flavors of my app.
To cross out the mistakes others have encountered, I have done the following:
 - Made sure my api keys are inside the  tag of the manifest file.
 - Ensured that the Google Maps API v2 for Android is enabled on Google Consoles
 - I'm using the Google Play Services via Gradle (Scroll down for my gradle snippet)
 - I made sure all of the essential permissions are set
 - I made sure to enable the glEsVersion.
What I think the problem is?
I think I'm having a problem with my "free.elephant.tuskapp" flavor to authenticate with googles servers. In my gradle build, I maintain two different flavors of my application and I seem to be getting an error with authentication:
Ensure that the "Google Maps Android API v2" is enabled.
Ensure that the following Android Key exists:
API Key: myAPIKEY
Android Application (<cert_fingerprint>;<package_name>): SHA-1;free.elephant.tuskapp

I obtained my API by using the 'elephant.tuskapp' package name rather than the 'free.elephant.tuskapp'
Here's my gradle build if it's of any help:
Gradle
   buildscript {
        repositories {
            maven {
                url 'https://maven.fabric.io/public'
            }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }
    apply plugin: 'com.android.application'
    apply plugin: 'io.fabric'

    repositories {
        maven {
            url 'https://maven.fabric.io/public'
        }
    }

    android {
        compileSdkVersion 22
        buildToolsVersion "23.0.0 rc2"

        defaultConfig {
            applicationId "elephant.tuskapp"
            minSdkVersion 15
            targetSdkVersion 15
        }

        productFlavors {
            demo {
                applicationId "demo.elephant.tuskapp"
            }
            free {
                applicationId "free.elephant.tuskapp"
            }
        }

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }
    }

    dependencies {
        compile 'com.google.android.gms:play-services:7.5.0'
        compile 'com.google.zxing:core:3.2.0'
        compile('com.crashlytics.sdk.android:crashlytics:2.3.2@aar') {
            transitive = true;
        }
    }

Am I missing out on something? Or does it really have something to do with my flavor builds? If it's the flavors causing trouble, how am I supposed to handle this? I generated new api keys for all my flavors but I don't see how I'm supposed to make that work within the manifest file as well as having it look elegant.

A:

Since my app has multiple flavors, I was getting thrown an error that my api-keys were not being validated. The way to resolve this is to ensure that you add all packages of your project into the Google Developer Console.
SHA1;packagename
Then press enter
SHA1;packagename2(flavor)
In my case it was:
SHA1;elephant.tuskapp
SHA1;free.elephant.tuskapp
SHA1;demo.elephant.tuskapp


Q:

Querying riak through curl blocking return

I'm relatively new to riak and am just in the process of exploring things
I seem to have this recurring problem thats an on again ..off again thing ..
NOTE: This issue started after i tried setting up a mulit backend setup but reverted back to this one for now
Everytime i start a riak node(i clear all the data in /var/lib/riak/) and try to perform a basic curl insertion on it ..
curl -v -XPUT http://10.151.99.77:8087/riak/test/doc?returnbody=true
-H "Content-Type: application/json"   -d '{"bar":"baz"}'

(Taken from riaks tutorial)
The command just seems to halt or not return .. it has this message till the point it halts
* About to connect() to 10.151.99.77 port 8087 (#0)
*   Trying 10.151.93.77... connected
* Connected to 10.151.93.77 (10.151.93.77) port 8087 (#0)
> PUT /riak/test/doc?returnbody=true HTTP/1.1
> User-Agent: curl/7.21.6 (x86_64-pc-linux-gnu) libcurl/7.21.6 OpenSSL/1.0.0e zlib/1.2.3.4     libidn/1.22 librtmp/2.3
> Host: 10.151.93.77:8087
> Accept: */*
> Content-Type: application/json
> Content-Length: 13

my app.config is pretty basic with the exceptions ..
 - Changed port to 8087
 - and i think this is default but the storage backend is {storage_backend, riak_kv_memory_backend}
and the vm.args has custom name with the ip of 10.151.99.77 ...
What i really want to know ..
 - is there some logs i can see for the curl commands ?
 - is there something im missing in the app.config ?

A:

Port 8087 is the default port for the protocol buffer interface in Riak and will not serve HTTP requests. Instead try to connect to the default HTTP interface port 8098. If this doesn't work, check what the http parameter (available under the riak_core section of the app.config file) is set to and use this.


Q:

As validatePassword () receives the user's password?

As validatePassword() receives the user's password?
I not know how validatePassword() get password user.
$password - Getting here is assigned to the user's password?
<?php
namespace app\models;

class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
    public $id;
    public $username;
    public $password;
    public $authKey;
    public $accessToken;

    private static $users = [
        '100' => [
            'id' => '100',
            'username' => 'admin',
            'password' => 'admin',
            'authKey' => 'test100key',
            'accessToken' => '100-token',
        ],
        '101' => [
            'id' => '101',
            'username' => 'demo',
            'password' => 'demo',
            'authKey' => 'test101key',
            'accessToken' => '101-token',
        ],
    ];

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        foreach (self::$users as $user) {
            if (strcasecmp($user['username'], $username) === 0) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        Yii::info('Пароль validateAuthKey ----'.$authKey);
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === $password;
    }
}

A:

THe code you show is the User.php model code in basic template application.
 as you can see in site controller  the action login call $model->login()
 public function actionLogin()
{
    if (!\Yii::$app->user->isGuest) {
        return $this->goHome();
    }

    $model = new LoginForm();
    if ($model->load(Yii::$app->request->post()) && $model->login()) { // *** here
        return $this->goBack();
    }
    return $this->render('login', [
        'model' => $model,
    ]);
}

($model  is obtained by new LoginForm();).
in $model->login (alias in LoginForm->login()) you have this code
 /**
 * Logs in a user using the provided username and password.
 * @return boolean whether the user is logged in successfully
 */
public function login()
{
    if ($this->validate()) {
        return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
    }
    return false;
}

this code perform the login


Q:

Trouble subsetting array by row in R

I have an array of data and I am trying to subset only data from the states of OR and WA. I am trying to use the row STATE, and select any with the abbreviation OR and WA. When I run the script I get
Error in dat_trans[dat_trans, "STATE" == "OR", ] :
incorrect number of dimensions

This is the data I'm working with:
dat_trans <- structure(c(
  "10263500", "   59.46390", "34.42083", "-117.8395", "CA", "old", NA,
  "10281800", "   31.38300", "36.77854", "-118.2645", "WA", "new", NA,
  "14037500", "   18.23760", "44.34155", "-118.6566", "OR", "new", NA
), .Dim = c(7L, 249L), .Dimnames = list(c("STAT_ID",
"DRAIN_AREA", "LAT", "LON", "STATE", "STUDY", "HUC_BASIN"), NULL))

Then this is the script that I've attempted to subset the data with
csv_file_name=filelist[1]
dat=read.csv(csv_file_name,header=TRUE,sep=",")
dat_trans=t(dat)

summer_storm_matrix=array()
    for (tt in 1:ncol(dat_trans)){
      storm_gaugedata=dat_trans[dat_trans,'STATE'=='OR',tt]
      summer_storm_matrix=cbind(summer_storm_matrix,storm_gaugedata)
    }

A:

You have two errors:
dat_trans[dat_trans, "STATE" == "OR", ]
          ^^^^^^^^^  ^     ^

Don't do dat_trans[dat_trans..., repeating the df name inside the indices doesn't make sense.
Don't quote the column "STATE", that makes it a string, not a column name. You wanted STATE column, or rather dat_trans$STATE

Solution:
dat_trans[dat_trans$STATE == "OR", ]

dat_trans[dat_trans$STATE == "OR", tt]

or if you use dplyr/tidyverse:
dat_trans %>% filter(STATE == "OR")


Q:

bufferedimage image.getRGB and image.setRGB not refer to same pixel

i have problem with setRGB() method. After get int color=getRGB(x,y) then setRGB(x,y,color) the image had changed.
File file=new File(fileName);
image = ImageIO.read(file);
            int width=image.getWidth();
            int high=image.getHeight();
            for (int xPixel = 0; xPixel < width; xPixel++)
            {
                for (int yPixel=0; yPixel<high; yPixel++)
                {
                    int color = image.getRGB(xPixel, xPixel);
                    image.setRGB(xPixel, yPixel, color);
                }
            }

Then i write the image to a bmp file. the new image is not same with old image.
What is problem?

A:

You call the getRGB- Function with xPixel and xPixel.
and the set function with xPixel and yPixel as arguments.
I think your code must be
 int color = image.getRGB(xPixel, yPixel);
 image.setRGB(xPixel, yPixel, color);


Q:

Binary representation of breast cancer wisconsin database

I want to produce a binary representation of the well-known breast cancer Wisconsin database.
The initial data set has 31 numerical variables, and one categorical variable.
 id_number diagnosis radius_mean texture_mean perimeter_mean area_mean smoothness_mean compactness_mean concavity_mean concave_points_mean symmetry_mean
1    842302         M       17.99        10.38         122.80    1001.0         0.11840          0.27760         0.3001             0.14710        0.2419
2    842517         M       20.57        17.77         132.90    1326.0         0.08474          0.07864         0.0869             0.07017        0.1812
3  84300903         M       19.69        21.25         130.00    1203.0         0.10960          0.15990         0.1974             0.12790        0.2069
4  84348301         M       11.42        20.38          77.58     386.1         0.14250          0.28390         0.2414             0.10520        0.2597
5  84358402         M       20.29        14.34         135.10    1297.0         0.10030          0.13280         0.1980             0.10430        0.1809

I want to produce a binary representation of this dataframe by:
transforming the diagnosis column (levels= M , B) to two columns diagnosis_M and diagnosis_B and put 1 or 0 in the relevant row depending on the value in the initial column (M or B).
Looking for the median of each numerical column and split it as two columns depending on whether the values are greater or lower than the mean value. eg: for the column radius_mean, split it in radius_mean_great in-which we put 1 if the values > mean, o else; and a column radius_mean_low inversely.
library(mlbench)
library("RCurl")
library("curl")
UCI_data_URL <- getURL('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data')

names <- c('id_number', 'diagnosis', 'radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean', 'compactness_mean', 'concavity_mean','concave_points_mean', 'symmetry_mean', 'fractal_dimension_mean', 'radius_se', 'texture_se', 'perimeter_se', 'area_se', 'smoothness_se', 'compactness_se', 'concavity_se', 'concave_points_se', 'symmetry_se', 'fractal_dimension_se', 'radius_worst', 'texture_worst', 'perimeter_worst', 'area_worst', 'smoothness_worst', 'compactness_worst', 'concavity_worst', 'concave_points_worst', 'symmetry_worst', 'fractal_dimension_worst')

breast.cancer.fr <- read.table(textConnection(UCI_data_URL), sep = ',', col.names = names)

A:

Well there are several ways to binarize the base, I found the following I hope it serves
df <- breast.cancer.fr[,3:32]
df2 <- matrix(NA, ncol = 2*ncol(df), nrow = nrow(df))
for(i in 1:ncol(df)){
df2[,2*i-1]<- as.numeric(df[,i] >  mean(df[,i]))
df2[,2*i]  <- as.numeric(df[,i] <= mean(df[,i]))}
colnames(df2) <- c(rbind(paste0(names(df),"_great"),paste0(names(df),"_low")))

library(dplyr)
df3 <- select(breast.cancer.fr,id_number,diagnosis) %>% mutate(diagnosis_M = as.numeric(diagnosis == "M")) %>%
  mutate(diagnosis_B = as.numeric(diagnosis == "B"))

df <- cbind(df3[,-2],df2)
df[1:10,1:7]
   id_number diagnosis_M diagnosis_B radius_mean_great radius_mean_low texture_mean_great texture_mean_low
1     842302           1           0                 1               0                  0                1
2     842517           1           0                 1               0                  0                1
3   84300903           1           0                 1               0                  1                0
4   84348301           1           0                 0               1                  1                0
5   84358402           1           0                 1               0                  0                1
6     843786           1           0                 0               1                  0                1
7     844359           1           0                 1               0                  1                0
8   84458202           1           0                 0               1                  1                0
9     844981           1           0                 0               1                  1                0
10  84501001           1           0                 0               1                  1                0


Q:

Combining adjusted survival estimates with multiple imputation

I've constructed a Cox PH model using multiple imputed datasets in SAS. Now I would like to estimate adjusted survival curves for each treatment group (main variable in the model). Is there a principled way of combining adjusted survival curves estimated from each imputation? Can I just estimate the probabilities from each imputation and then combine them later using PROC MIANALYZE?
Thanks!
*Edit: I've sort of rigged the pooling of multiple imputations so that the modeleffects argument in PROC MIANALYZE is the estimated survival probability for group A or B at a single timepoint. I have several of these "effects" based on the number of timepoints. The stderr argument in PROC MIANALYZE is the associated standard error. My concern is if doing it this way still leads to valid inferences.

A:

With the same predictors in all of your models, the basic rule for the pooling step of multiple imputation is:

The pooling step consists of computing the mean over the m repeated analysis, its variance, and its confidence interval or P value.

So in your case, the "mean" etc. would be for each regression coefficient in the Cox models. (It's not clear in your question what you mean by "estimate the probabilities from each imputation.") Calculating the p-values properly might require information about covariances.
I don't use SAS, but a quick look at its manual page suggests that PROC MIANALYZE is designed to do what you want. It would seem to work best if you do the analyses in a way that maintains the special data-set structures that SAS uses to keep track of covariances in multiple imputations. (That's certainly the case for the mice package in R for multiple imputation.)
EDIT: In response to the revised question, an important issue would be the distributions of survival probabilities among the imputations, as they might not be as amenable to pooling among imputed models as the regression coefficients are. For example, if some probabilities are very close to 100% or 0% then simply taking the average of the probabilities is likely to lead to trouble, particularly in calculating the p-values for differences between groups. You will be better off by following the standard imputation procedure for pooling multiple models into a single model, and then getting the estimates of survival probabilities from that single pooled model.


Q:

How to remove an css style from a div ?

I am using jQuery Autosize to enable automatic height for textarea elements.
When I focus the textarea it works great.
If I blur the texture I would like to remove the height to the texture to resize the height to the default value.
I would like to know what should I do on blur action in order to keep the textarea to the default value.
Here is what I am trying to do on javascript console to test my script.
When I load the page the textarea is on blur state:
$('#announcement').css('height'); // "36px"

If I focus the textarea:
$('#announcement').css('height'); // "90px"

$('#announcement').removeAttr('height');
$('#announcement').css('height'); // "90px"
// why do I continue to get this value even if I removed the Attribute height?

I know I can simply fix my problem simply making on blur action
$('#announcement').css('height', '36px');
but I would like o avoid to set css properties in javascript code.
Any ideas?

A:

You can clear the style.height set directly on the element with this:
$('#announcement').css('height', '');

See working example here: http://jsfiddle.net/jfriend00/LXspR/
In your example, removeAttr() works on attributes, not style properties like style.height.  .css("height") works on style.height.


Q:

.NET 4.5 installed but error message when app runs

I have .NET 4.5 installed on my dev machine:

However I get this message when my app runs:

I have this in my app.config:
<supportedRuntime version="v4.5" sku=".NETFramework, version=v4.5"/>

Is there something else I need to do?

A:

I replaced the <supportedRuntime> node with this:
<startup>
  <supportedRuntime version="v4.0.30319"/>
</startup>

as per this on MSDN. It works as both .NET 4 and 4.5 target the same version of the CLR, v4.0.30319.


Q:

How to give choices from values of another field in Django models

I have a form, which is for scheduling an appointment. I give user 3 dates on which the meeting can be scheduled. Now in the admin I want to select one of the dates according to my convenience, and store it in a field of the same model. How can I do that
Right now my meeting dates are just char fields like this
schedule1 = models.CharField()
schedule2 = model.CharField()
schedule3 = models.CharFiedl()
selected_schedule = model.CharField(choices={something here})

The schedule fields will be filled when the object is created. So I am sure the choices will be there, I just have to dynamically set them. How can I do this?
Any help will be appreciated.

A:

Here's what you do (if the schedule fields are already prefilled):
class ScheduleForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ScheduleForm, self).__init__(*args, **kwargs)
        instance = kwargs.get('instance', None)
        if instance is not None:
            self.fields['selected_schedule'].choices = (
                (instance.schedule1, instance.schedule1),
                (instance.schedule2, instance.schedule2),
                (instance.schedule3, instance.schedule3),
            )

On your admin, simply state that you want to use that form:
class TheAdminInQuestion(admin.ModelAdmin):
    form = ScheduleForm

Further note:
I'd recommend a different solution to your problem than storing the choices on the same model. For instance, you might have a model called ScheduleChoice, and there could be 3 records of that, etc. Or, you might calculate the value based on some other rules, and just don't store the choices at all. Also, I'd recommend using DateTimeField to store the dates. You can convert the date to any format you like (e.g. January 12th, 2011 at 3:35PM) and still store it as the same datetime object in the database.


Q:

filter the embedded document by each parent _id?

I have document
{
    "_id" : ObjectId("5da832caeb173112348e509b"),
    "owner" : {
        "image" : "5d999578aeb073247de4bd6e.jpg",
        "fullname" : "hem sopheap",
        "userID" : "5d999578aeb073247de4bd6e"
    },
    "project" : {},
    "image" : "hem sopheap-1571304138866.png",
    "body" : "Lorem Ipsum "),
    "comments" : [

        {
            "user" : "5d999578aeb073247de4bd6e",
            "fullname" : "hem sopheap",
            "username" : "sopheap",
            "comment" : "1000000",
            "_id" : ObjectId("5db07900ae100b0c05b1222c"),
            "replies" : [],
            "date" : ISODate("2019-10-23T15:40:57.535Z"),
            "likes" : [
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044",
                "5da85558886aee13e4e7f044"
            ]
        },
        {
            "user" : "5d999578aeb073247de4bd6e",
            "fullname" : "hem sopheap",
            "username" : "sopheap",
            "comment" : "11111111111",
            "_id" : ObjectId("5db0790aae100b0c05b1222d"),
            "replies" : [],
            "date" : ISODate("2019-10-23T15:40:57.535Z"),
            "likes" : []
        }
    ],
    "__v" : 33,
    "likes" : [
        "5d999578aeb073247de4bd6e"
    ]
}

How can I get likes, filter by post _id and comments _id to get result likes
"likes" : [
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044",
                    "5da85558886aee13e4e7f044"
                ]

A:

Let's simplify the input to this.  We have two posts, P0 and P2.  Each has an array comments.  We know that comment._id is at least unique with the post so it is OK to "reuse" them here:
var r =
[
 {
    "_id" : "P0",
    "comments" : [
{ "_id" : "C0", "likes" : [ "AA", "AA" ] }
,{"_id" : "C1", "likes" : [] }
,{"_id" : "C2",  "likes" : [ "foo", "bar" ]}
,{"_id" : "C3",  "likes" : []
        }
    ]
 }

 ,{
    "_id" : "P2",
    "comments" : [
{ "_id" : "C0", "likes" : [ "FF", "FF" ] }
,{"_id" : "C1", "likes" : [] }
,{"_id" : "C2",  "likes" : [ "foo", "bar" ]}
,{"_id" : "C3",  "likes" : []
        }
    ]
 }
];

Here is a solution:
db.foo.aggregate([
// First, match on post ID and comments ID.  Remember, comments is an
// array so ANY comments entry with key C0 inside the array will match and
// yield the entire array.  But this is OK because it very much narrows down
// the info to process:
{$match: {_id: "P2", "comments._id":"C0"}}

,{$unwind: "$comments"} // Unwind the comments:

// And now pick only that comment with ID C0:
,{$match: {"comments._id":"C0"}}

// To complete the request, make "likes" a top level field:
,{$project: {"likes": "$comments.likes"}}

   ]);

A complete answer to the OP would include setup of the post and comment _id as ObjectId not strings but the query is the same.


Q:

Question about notation in Graph Theory

Let $G$ be a graph such that $\forall$ $v$ $\in$ $V(G)$, $deg(v)$ $\geq$ $\frac{|V(G)|}{2}$
Let $p$ = $x_1x_2...x_k$ be a longest path in $G$. Show that $N(x_1)$ $\bigcup$ $N(x_k)$ $\subseteq$ {$x_1,...,x_k$}.
What does $N(x_1)$ $\bigcup$ $N(x_k)$ mean in this context? It's not explained anywhere in notes or class.

A:

It means the set of neighbors of the vertex: $N(x)=\{{ v\in V(G):\{v,x\}\in E(G)\}}$


Q:

Python - change switch value of array at index between 1 and 0

I got an numpy array like [[1,0,0,1]].
I wrote the following method to switch the value at a specific index in the array between 1 and 0:
'''
@param array: The array from which an value should be inverted
@param index: index at which the value should be inverted
'''
def change_binary_value(array, index):

    if array[index]==0:

        array[index] = 0
    else:
        array[index] = 1

So, i am not a every-day user of python and i get this error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Well, i dont want to use any() or all(). I just want to change a single value. Why does'nt python want me to do that? Thats a bit strange.
Hoping for quick answer,
Fabian

A:

Numpy has array within array in this case, that is why [0] after array to extract first array is necessary.
Here is the code that will invert the value at specific index (if statement was wrong):
def change_binary_value(array, index):

    if array[0][index]==0:
        array[0][index] = 1
    else:
        array[0][index] = 0
    return array


Q:

appending different data to the end of each line in csv file

I need to add text to the end of the header in a text/csv file and then add other text (date) at the end of each line below the header.  Adding the text part is working fine but it's the exporting to a csv that's not working as expected.
The expected output is (bold text is the added text);
"Folder Name","Files","Folders","Size","Comment","ReportDate"
"\\server\share\folder","2,029,756","819,527","1,785,490,958,735"," ","1/10/2020"
Instead I'm getting;
"Length"
"61"
"74"
"88"
"118"
$Path = "C:\temp\"
$files = Get-ChildItem $Path -filter '*.csv'
ForEach ($file in $files)
{
    $datetmp = $file.PSChildName.Substring(0,10)
    $datetmp = $datetmp.split("_")
    $date = $datetmp[1] + "/" + $datetmp[2] + "/" + $datetmp[0]

    $Fullpath = $Path + $file

    [System.Collections.ArrayList]$content = Get-Content $Fullpath #| %{"$_," + $date}
    $rptinsert = @()

    for ($i=0; $i -lt ($content.Count); $i++)
    {
        if ($i -eq 0)
        {
            $rptinsert += $content[$i] + ",""ReportDate"""
        }
        else
        {
            $rptinsert += $content[$i] + ",`"$date`""
        }
    }

    $Report = $Path + $file.PSChildName.Substring(0, 10) + "-FileSizes2.csv"
    $rptinsert | Export-Csv -path $Report -Encoding ascii -NoTypeInformation
    }

I'm sure there are shorter methods to perform the some of my lines as well, just not looking for that right now. ;-)

A:

To use Export-Csv the way you are expecting, you need to be inputting objects with property/value pairs. You are piping in strings. The only property a string has is Length. I would use Import-Csv to read the files, modify the returned values, and then Export-Csv to output the changed objects. Below is a blueprint that will work:
$Path = "C:\temp\"
$files = Get-ChildItem $Path -filter '*.csv'
Foreach ($file in $files) {
    $datetmp = $file.Name.Substring(0,10).Split('_')
    $date = $datetmp[1],$datetmp[2],$datetmp[0] -join '/'
    $content = Import-Csv $file | Add-Member -MemberType NoteProperty -Name 'ReportDate' -Value $date -PassThru
    $content | Export-Csv -Path ($Path + $file.Name.Substring(0, 10) + "-FileSizes2.csv") -NoType
}

The output of Import-Csv is a collection of custom objects with property names that match the header line of the CSV file. Since it appears you want the same value added to every line of a CSV file, you can just run one Add-Member command. If each line needs a different value, then you will need to loop through each line and run an Add-Member command.
Add-Member allows for adding different member types to an object. In your case, you want to add a NoteProperty type with a value.
Once the updates are complete to one CSV's contents, you can pipe those results into Export-Csv. -NoType prevents an additional header line with type information from the output.


Q:

Is it posible to see the async storage current limit React Native?

I would like to know how much is the remaining memory of a react native application using async storage.
I know in general is about 6 MB the total consumption, but I did not see in any of the methods of async storage "expo" from react native how much is the current consumption and how much is it allowed to be used from the current device.
I would love to have something like:
const currentMemory = AsyncStorage.currentMemoryConsumption();
const deviceMemoryLimit = AsyncStorage.deviceMemoryLimit();

And then I would be able to know the current memory consumption make an analysis and provide meaningful information to my client.
I don't see any information either in the current implementation of react native async storage from community.
Is it possible to know about the current memory state before using async storage to save an item?
Thanks in advance for the reading and help

A:

As far as I can tell there is no way to get AsyncStorage remaining size at the moment.
Probably the best course of action would be to just increase the limit by following official documentation and trigger a cleaning task if you reach a limit.
https://github.com/react-native-community/async-storage/blob/master/docs/OLD/advanced/IncreaseDbSize.md
This discussion explores the related topics but consensus is to just increase storage limit and be careful.
https://github.com/facebook/react-native/issues/3387


Q:

How to add custom item on Global long press Contextmenu like Translate and Wikipedia

I want to know how google translate and wikipedia app did to add their item on the webview long press context menu.
P.S. This screenshot is from Nexus 5 6.0.1 version.

A:

They added an activity that supports ACTION_PROCESS_TEXT via an <intent-filter>:
<intent-filter >
    <action android:name="android.intent.action.PROCESS_TEXT"/>
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
</intent-filter>

On the Intent delivered to the activity (obtained via getIntent()), EXTRA_PROCESS_TEXT will hold some text, or EXTRA_PROCESS_TEXT_READONLY will hold it if the text is read-only. The text will be what was highlighted when the user chose the menu option that started this activity.
The activity will be invoked via startActivityForResult(). The result Intent can have its own EXTRA_PROCESS_TEXT value, which will be the replacement text.


Q:

angularJS $stateParams in service

I try to fetch JSON data on the page post/:postId within the following factory in my service:
angular.module('sampleapp.services', [])
    .factory('DetailService', function($http) {
        return {
            getDetail: function(callback) {
                $http.get('https://example.com/posts/' + $stateParams.postId + '.json').success(callback);
            }
        };
    });

Unfortunately, $stateParams is undefined. What am I doing wrong? If I hardcode the URL, it works.
My routing:
.state('detail', {
    url: '/post/:postId',
    templateUrl: 'templates/detail.html',
    controller: 'DetailCtrl'
})

and my controller:
.controller('DetailCtrl', function ($scope, DetailService) {
    DetailService.getDetail(function(data) {
        $scope.post = data;
    });
});

My question is: How can i access the URL-paramters within my factory?

A:

Just like you inject the $http service, you must also inject the $stateParams service:
.factory('DetailService', function($http, $stateParams) {


Q:

Building Dynamic Test Classes that don't break due to Destination Org's - validation rules or Required Field settings

Scenario:
I have built a solution for a Customer and I have used Apex for this solution.The deployment went well. But after few months the customer added some validation rules to the Sobject and when they ran the test classes in the Org, My test classes broke.
Question:
1. How can i build my test classes dynamically so that it does not break in the customer's destination Org(if the customer adds more validation rules or makes some field mandatory after deployment of code)?
2. How do installed packages overcome problems like this?

A:

1.For required fields, you can use the describe information to find out which fields are required, and attempt to fill them in. For other validation rules (such as one required custom date field that must be in the past, and another required custom date field that must be in the future), you pretty much can't do it. There's an idea at success.salesforce.com to vote up to add the ability to turn off validations in tests.
2.Installed packages do not always overcome this problem. I've seen plenty of tests fail in the package after it's been installed. Since I can't see the code, I can't guarantee that validation was the problem, but in some cases it was pretty clear.


Q:

AWS - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

I'm really new to AWS so please bear with me :(
I'm currently making a web application that has a feature for uploading photos. I want to save these photos in S3 buckets and save a reference to them in my database. I am following this guide at the moment: http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html
However, I've done everything stated in the guide (or at least I hope), but when I run the app and run the createAlbum() method, I get the error:

XMLHttpRequest cannot load https://my-bucket-name.s3-us-west-2.amazonaws.com/myalbumname/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

I made sure that permissions allowed for all users in the Bucket permissions, I updated the CORS config as instructed by the docs, and updated the role policy as well.
This is my code in terms of credentials:

var albumBucketName = 'my-bucket-name'; //not the real value, obviously
var bucketRegion = 'us-west-2';
var IdentityPoolId = 'my-identity-pool-id'; //here, too
AWS.config.update({
region: bucketRegion,
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: IdentityPoolId
})
});
var s3 = new AWS.S3({
    apiVersion: '2006-03-01',
    params: {Bucket: albumBucketName}
  });

I've been trying to find a solution with no success. Does anyone know what I need to do to fix this? Any help is greatly appreciated!
Thank you.

A:

CORS on S3 bucket:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

The * in AllowedOrigin is ok for testing purposes.
Your bucket will need the temp credentials, what you can do is:
 // Set the region where your identity pool exists
    AWS.config.region = 'us-east-1';

    // Configure the credentials provider to use an identity pool for temp
    credentials
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'IDENTITY_POOL_ID',
    });

    // Make the call to obtain credentials
    AWS.config.credentials.get(function(){

    // Credentials will be available when this function is called.
    var accessKeyId = AWS.config.credentials.accessKeyId;
    var secretAccessKey = AWS.config.credentials.secretAccessKey;
    var sessionToken = AWS.config.credentials.sessionToken;

    var bucketName = 'bucket_name';

    var keyName = "key_name";

    var params = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'};

    s3.putObject(params, function (err, data) {
    if (err)
    console.log(err)
    else
    console.log("Successfully uploaded data to " + bucketName + "/" +
    keyName);
    });
    });