Android Jackson Library parsing

I am getting a "JSONObject can't be cast to ClassResponse" error after getting a server response.  Im guessing its because the response from server doesn't match the fields in ClassResponse?  Is it because of the "data" struct in the JSON response? I have a setter for each of the fields but not sure what I am doing wrong. Is there a way to change the annotation for the Jackson library to parse other layers of the json object?  for instance..

@JsonProperty("data:accessToken")  or something of that nature... or is that even necessary?

server response:

{
    success: "true"
    message: "Record Created"
    data: {
      userToken : "1"
          }
}

ClassResponse:

@JsonIgnoreProperties(ignoreUnknown = true)
public class LoginResponse extends Response<LoginResponse.Result>
{
    public static class Result
    {

        private String mUserToken;
        private String mAccessToken;
        private String mUserId;

        public String getUserToken(){
            return mUserToken;
        }

        @JsonProperty("userToken")
        public void setUserToken(final String aUserToken){
            mUserToken = aUserToken;
        }

        public String getAccessToken(){
            return mAccessToken;
        }

        @JsonProperty("accessToken")
        public void setAccessToken(final String aAccessToken){
            mAccessToken = aAccessToken;
        }

        public String getUserId(){
            return mUserId;
        }

        @JsonProperty("user_id")
        public void setUserId(final String aUserId){
            mUserId = aUserId;
        }
    }
}

    (edit)
    @JsonProperty("data")
    public void accessDataLayer(final String data) throws JSONException {

        JSONObject jobj = new JSONObject(data);

        mUserToken = jobj.getString("userToken");
        mAccessToken = jobj.getString("accessToken");
        mUserId = jobj.getString("user_id");

    }

@Override
public RESULT loadDataFromNetwork() throws Exception{
    final String url = buildUrl();

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    String response;

    try{
        conn.setDoInput(true);
        conn.setDoOutput(true);

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        JSONObject submitInfo = new JSONObject();
        submitInfo = buildParams(entity);

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(submitInfo.toString());
        out.close();

            response = readStream(conn.getErrorStream());

        conn.disconnect();
    }
    return parse(response);


Connection from PowerDesigner to MS SQL Server 2008 R2

I'm trying to connect from Sybase PowerDesigner 15 to MS SQL SERVER 2008 R2. I basically entered the following into the Connection Profile Definition dialog:

Connection Type: Native

DBMS Type: Microsoft SQL Server

Server Name: MSSQLSERVER (which is the instance name installed on my machine, I also tried 192.168.1.44\MSSQLSERVER which is my IP on the network and the instance name)

Database name: Prevent-01222013

Use integrated login: checked

Unfortunately, it keeps telling me "Connection Failed!". Where did I go wrong?


Obtain 3-D matrix from multiplication of one 1-D matrix and one 2-D matrix

I want to something like this:

a = [1,2,3]
b = [1,2,3;4,5,6]

Then,

a *some operation* b =
[1,2,3;4,5,6]
[2,4,6;8,10,12]
[3,6,9;12,15,18]

Each element of matrix a is multiplied with all the elements matrix b and as many elements there are in a those many matrices are obtained as results. I don't want to use loops.


Android - service running in the background

I want to call a method every time when the battery goes to 50%, even when the app is closed or the screen is turned off.
I tried Service and BroadcastReceiver but when I remove the app from recent apps list the Service is stopped and I doe't get calls of this method anymore.
How can I save it in backgroud?


sharing SQL database between two or more android clients

I have created a java servlet with which I have attached SQL database. Android client is sendig data to java servlet to save it in database which is working fine. I want to know if multiple android clients will share the same database connection or do i need to do some threading or something else?

Regards,


Plot negative of an array value in gnuplot

I have a file whose data looks as follows,

ESCALE ; pCOHP file generated by LOBSTER. Energy is shifted such that the Fermi level lies at 0 eV.
         3          1        301  -6.23689e+00   8.81327e+00   3.79655e+00
Average
No.1:O67->Zr40(2.0986491691399038)
No.2:O67->Zr49(2.0986491691399038)
-10.03344   0.00000  -2.82630   0.00000  -2.82968   0.00000  -2.82292
 -9.98328   0.00000  -2.82630   0.00000  -2.82968   0.00000  -2.82292
 -9.93311   0.00000  -2.82630   0.00000  -2.82968   0.00000  -2.82292
 -9.88294   0.00000  -2.82630   0.00000  -2.82968   0.00000  -2.82292
 -9.83278   0.00000  -2.82630   0.00000  -2.82968   0.00000  -2.82292
 -9.78261   0.00000  -2.82630   0.00000  -2.82968   0.00000  -2.82292
 -9.73244   0.00000  -2.82630   0.00000  -2.82968   0.00000  -2.82292
 ...
 ...

Now if I need to plot the second column against first column with gnuplot, I just use the command

plot "<fileName>" every ::<startLineNo>::<endLineNo> using 1:2 title '<TitleValue>' with lines

where  would be 6 in this case. My question is

How to plot the negative of the second column values against the first column?

If I try 1:-2 in the previous command, it throws me a warning that says

Warning: empty y range [0:0], adjusting to [-1:1]

If its hard to plot it using gnuplot, I will appreciate answers using other freely available plotting tools


Data provider is not running in Selenium Grid

Can anyone please tell me that why the below error occurs: it occurs for all data provider methods. I use a static class for entire data providers and am using @Test(dataProvider = "Search", dataProviderClass= StaticProvider.class). it was running when i run normally with a test but on running Selenium Grid with 2 test all my data providers are throwing the below exception. I am running in sequential mode as i could not succed in parallel run.

java.lang.RuntimeException: jxl.read.biff.BiffException: Compound file does not contain the specified stream

org.testng.internal.MethodInvocationHelper.invokeDataProvider(MethodInvocationHelper.java:130)
org.testng.internal.Parameters.handleParameters(Parameters.java:413)
org.testng.internal.Invoker.handleParameters(Invoker.java:1319)
org.testng.internal.Invoker.createParameters(Invoker.java:1021)
org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1121)
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
org.testng.TestRunner.runWorkers(TestRunner.java:1182)
org.testng.TestRunner.privateRun(TestRunner.java:761)
org.testng.TestRunner.run(TestRunner.java:612)
org.testng.SuiteRunner.runTest(SuiteRunner.java:335)
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:330)
org.testng.SuiteRunner.privateRun(SuiteRunner.java:292)
org.testng.SuiteRunner.run(SuiteRunner.java:241)
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
org.testng.TestNG.runSuitesSequentially(TestNG.java:1169)
org.testng.TestNG.runSuitesLocally(TestNG.java:1094)
org.testng.TestNG.run(TestNG.java:1006)
org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:107)
org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:199)
org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:170)
Caused by: jxl.read.biff.BiffException: Compound file does not contain the specified stream

jxl.read.biff.CompoundFile.getPropertyStorage(CompoundFile.java:451)
jxl.read.biff.CompoundFile.getStream(CompoundFile.java:326)
jxl.read.biff.File.<init>(File.java:135)
jxl.Workbook.getWorkbook(Workbook.java:221)
jxl.Workbook.getWorkbook(Workbook.java:198)
com.lm.sl.StaticProvider.getTableArray(StaticProvider.java:135)
com.lm.sl.StaticProvider.createSearch(StaticProvider.java:32)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
org.testng.internal.MethodInvocationHelper.invokeDataProvider(MethodInvocationHelper.java:117)
org.testng.internal.Parameters.handleParameters(Parameters.java:413)
org.testng.internal.Invoker.handleParameters(Invoker.java:1319)
org.testng.internal.Invoker.createParameters(Invoker.java:1021)
org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1121)
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
org.testng.TestRunner.runWorkers(TestRunner.java:1182)
org.testng.TestRunner.privateRun(TestRunner.java:761)
org.testng.TestRunner.run(TestRunner.java:612)
org.testng.SuiteRunner.runTest(SuiteRunner.java:335)
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:330)
org.testng.SuiteRunner.privateRun(SuiteRunner.java:292)
org.testng.SuiteRunner.run(SuiteRunner.java:241)
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
org.testng.TestNG.runSuitesSequentially(TestNG.java:1169)
org.testng.TestNG.runSuitesLocally(TestNG.java:1094)
org.testng.TestNG.run(TestNG.java:1006)
org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:107)
org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:199)
org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:170)


SonarQube Integration with Jenkins and Jira

I am supposed to setup SonarQube and I have Jenkins and Jira already running in the server. I need to know whether SonarQube has to be integrated with Jenkins alone or Jenkins and Jira both. I did a google and searched forums and found that plugins are available for integrating with Jenkins. But could not find integrations for Sonarqube and Jira. I also have Github configured for Version control.
Has anyone integrated Jenkins,SonarQube and Jira together. Anyone has idea on these integrations


SlidingUpPanelLayout doesnot work Properly with CoordinatorLayout as first child of SlidingUpPanelLayout

So when fitssystemwindow is true when it collopse it automatically increase its panel hight and when it is false it works fine . But in my project i need that true So please give me any Solution;

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"
android:layout_height="match_parent"
 >
<com.sothree.slidinguppanel.SlidingUpPanelLayout
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:id="@+id/slideUpLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"

    sothree:umanoDragView="@+id/dragView"
    sothree:umanoOverlay="true"
    sothree:umanoPanelHeight="68dp"
    sothree:umanoParallaxOffset="100dp"
    sothree:umanoShadowHeight="4dp">
    <!-- This is the first child  and show main content-->
    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" // when this is false work fine otherwise     not
 >

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

    <!-- this is second child and contain inside the slidingpanel -->
    <LinearLayout
        android:id="@+id/dragView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        android:clickable="true"
        android:focusable="false"
        android:orientation="vertical">

    </LinearLayout>

 </com.sothree.slidinguppanel.SlidingUpPanelLayout>

</RelativeLayout>

So please Give me solution for that or any other library which has SlideupPaneLayout from bottom to Top.


Soundcloud API get reposts from specific user

Iam building a simple Soundcloud API app for myself. I did some research for reposts with API and I figured out that I can only repost tracks with the API but not retrieve them. Is that correct?

What I want to achieve: Get all Reposted Tracks from a specific username/user_id of soundcloud.

Is it possible to get this information?
The code to repost a track is:

 $repost = json_decode($soundcloud->put('e1/me/track_reposts/<track-id>'), true); // do repost //

I hope someone can help me


iOS: How to get access to a variable used in the root view controller when I'm 2 levels down in the navigation stack?

I'm trying to build an app that sends and HTTP request and some part of this request is stored in an object in the root view controller. How can I get access to this object once I'm two levels down in the navigation stack? Global variables declared in the App Delegate? I'm trying to keep MVC rules in place.


Nokogiri XPATH - get range of nodes based on a search key

I have an html file with some paragraphs as below:

<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
<p> paragraph 4 </p>

Now I want to get the first two or three of the above paragraphs.

The snippet below only returns one paragraph based on the index I define..

doc = Nokogiri::HTML(open('test.html'))
p doc.xpath('//p[1][contains(text(), "paragraph")]')

but I want a range of paragraphs like 1..2 how can I achieve this? Thanks


Qt Problems Adding Table Widget Items

I have an invoice form which i am using to both create invoices and display the results of a stored invoice. I when i am trying to read back data from the database and display it i am getting the error of

QTableWidget: cannot insert an item that is already owned by another QTableWidget
  QTableWidget: cannot insert an item that is already owned by another QTableWidget
  QTableWidget: cannot insert an item that is already owned by another QTableWidget
  QTableWidget: cannot insert an item that is already owned by another QTableWidget
  QTableWidget: cannot insert an item that is already owned by another QTableWidget

I don't understand why this is being cause. The query that i am trying to run will return 4 rows. My code is below

QString CompanyID;
            int row = 0;
            ui->comboBox_Invoice_Account_Search->setCurrentIndex(1);
            QSqlQuery Account_Name_Query;
            QTableWidgetItem *Qty_Search = new QTableWidgetItem();
            QTableWidgetItem *Description_Search = new QTableWidgetItem();
            QTableWidgetItem *Product_Code_Search = new QTableWidgetItem();
            QTableWidgetItem *Unit_Price_Search = new QTableWidgetItem();
            QTableWidgetItem *Total_Price_Search = new QTableWidgetItem();
            while(Query.next())
            {
                CompanyID = Query.value(10).toString();
                //qDebug() << "CompanyID " << CompanyID;
                ui->lineEdit_Invoice_VAT->setText(Query.value(9).toString());
                ui->lineEdit_Invoice_Total->setText(Query.value(8).toString());
                ui->lineEdit_Goods_Total->setText(Query.value(7).toString());
                Qty_Search->setText(Query.value(3).toString());
                Description_Search->setText(Query.value(4).toString());
                Product_Code_Search->setText(Query.value(5).toString());
                Unit_Price_Search->setText(Query.value(6).toString());
                Total_Price_Search->setText(Query.value(7).toString());
                ui->tableWidget_Invoice->setItem(row, 0, Qty_Search);
                ui->tableWidget_Invoice->setItem(row, 1, Description_Search);
                ui->tableWidget_Invoice->setItem(row, 2, Product_Code_Search);
                ui->tableWidget_Invoice->setItem(row, 3, Unit_Price_Search);
                ui->tableWidget_Invoice->setItem(row, 4, Total_Price_Search);
                row++;
                Account_Name_Query.prepare("SELECT Company_Name FROM Customer WHERE Company_ID = '"+ CompanyID +"'");
                Account_Name_Query.exec();
                while(Account_Name_Query.next())
                {
                    ui->lineEdit_Invoice_Account->setText(Account_Name_Query.value(0).toString());
                }
            }

what is causing this error?


COMException when creating COM object for Excel Automation in C#

I've got this error when I create a COM object in order to use Excel automation. Any one knows why I am getting this error?

System.Runtime.InteropServices.COMException(errorCode = -2146959355)
Message: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005.

The call stack is following:

System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)
  at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(Type objectType)
  at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(Type serverType)
  at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(Type serverType, Object[] props, Boolean bNewObj)
  at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
  at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
  at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
  at System.Activator.CreateInstance(Type type, Boolean nonPublic)
  at Geotab.ComObject..ctor(Type type)

This is my code:
Type excelAppType = Type.GetTypeFromProgID("Excel.Application");
comExcelObject = new ComObject(excelAppType);


Set padding for textview works only after setting background resource - Android

Setting the background resource to a drawable xml for a textview after setting its padding doesn't pad the textview, but vice versa works. How ?

Example

works

   textView.setBackgroundResource(borderColor);
   textView.setPadding(10, 0, 10, 0);

doesn't work

   textView.setPadding(10, 0, 10, 0);
   textView.setBackgroundResource(borderColor);


how to write custom linear collection in scala

I'd like to write custom linear collection. Something like extended List in some specific cases (not for all parameter types).

Scala has complicated collection class hierarchy and I'm lost. What trait should I extend, what methods should I implement?

I've found comprehended tutorial for custom traversable implementation: http://daily-scala.blogspot.ru/2010/04/creating-custom-traversable.html.

And I'm searching for similar hints about implementing custom linear sequence.


How to check out a branch in Bitbucket

I have a Git repository at https://user_name@bitbucket.org/path/git.git.
This repository has a branch called feature/myFeature, which I want to check out. I have run

git init

in the desired folder, and then, according to Bitbucket, I need to run

git fetch && git checkout feature/myFeature

However, I get the following error,

fatal: No remote repository specified.  Please,
  specify either a URL or a remote name from which new revisions should
  be fetched.

I guess I need to specify the repository, but I don't know how exactly to do this, and at the same time specify the branch.

What should I do?


Strictly server-side processing (no web browser interaction):  is Java or PHP better for this scenario?

Here's the situation:

I currently have a web application that uses PHP to serve HTML/CSS/JS and that talks to a MySQL DB. Completely vanilla and common. The PHP is a mixture of presentation logic (HTML generation, etc) and business logic (the app uses Ajax extensively to make requests for data or to tell the server to make changes to something).

As part of a redesign of this system I am removing all of the presentation logic from the PHP. Instead, I will be using Ext JS 4 (a javascript-based windowing toolkit / app) connected to a web socket gateway (a COMET/AJAX replacement that allows bi-directional communication) on the server. Let's wave a magic wand for a minute and forget about how the Ext JS 4 gets delivered to the browser and how it talks to the web socket gateway.

What we are left with is a web socket gateway (written in Java and running persistently listening on a specific port for web socket connections) and some business logic / DB interaction currently written in PHP.

At this point, I see one of two options:

Keep the business logic / DB interaction in the PHP and execute it by calling either PHP from the command line or by having the PHP / Apache listen on a different port only for communications from the web socket gateway.

Write a new Java or C++ application that will be persistent and listen on a specific port for communications from the web socket gateway. The business logic / DB integration is re-written in Java or C++ code and is part of this application.

Would re-writing in Java or C++ give better performance than calling PHP over and over? (The PHP code is pretty cleanly written: object-oriented using packages like CodeIgniter and Doctrine).

Would the performance benefits outweigh the hassle of re-writing all the business logic? Obviously dependent on many factors such as quantity of code but what is your gut feeling?

In case it might influence your thinking / feedback, you should know that the web socket gateway (Kaazing) supports JMS, Stomp, AMQP, XMPP, or something custom you build yourself.

Let me know if there is any other info I can provide to help you with your answers.

Thanks!


What is the impact of appName in DpapiDataProtectionProvider constructor

In our IdentityManager class we have the follow line:

protectionProvider = new DpapiDataProtectionProvider("OurProduct");

What is the implication of that last parameter, and does it have any correlation to how the site is set up on IIS?

Background:
We've been deploying an MVC5 site with a custom IdentityManager class to a validation environment for a long time without hassles, and now we're getting the following issue when attempting to reset user passwords:

System.Security.Cryptography.CryptographicException: The data protection operation was unsuccessful. This may have been caused by not having the user profile loaded for the current thread's user context, which may be the case when the thread is impersonating.

Some solutions are described in the following thread:
Generating reset password token does not work in Azure Website

Everything is located on the same machine: IIS, Sql Server, Firefox test browser.

Unfortunately I don't have a full grasp of the concepts and I'm trying to figure out how the test environment has changed in order to trigger this issue where it's never happened before?


High CPU usage using Lauterbach T32 with Linux/Qt

I'm experiencing a very high CPU usage (~100%) using the Qt version of T32 on Linux, even when the program is waiting user interaction. The executable is t32marm-qt.

This does not happen when I use the standard Tcl-based t32marm executable.

A strace shows that the executable continuosly cycles on the

 clock_gettime(CLOCK_REALTIME,...)

syscall.

The Linux distribution is Mint 14 32-bit (derivation of Ubuntu 12.10).

Has anybody experienced this behavior ?

If so, is it a bug or just a wrong configuration ?


Do I need a Google Apps Account for GCE?

We are working on testing email on-premise and may be considering moving away from Google Apps for Email. Our current projects within GCE are tied to our current Google Apps Email accounts. Do we have to use Google Apps Email in order to use GCE? If not, does anyone know how login to the GCE web console would work since it is currently tied to our Google Apps Email accounts?

I can't seem to find a proper way to shift the project to a non-google authentication method.


make a value selected in drop down when editing

I am adding a feature to edit the ads a user puts. For that I want to make the value selected which is selected by the user when he entered the values . How can I implement this?

<div class="nm">
  Category
</div>
<div class="fl">
  <select name="category" id = "ad_category" onchange="cangeSubCat(this.value)" >
    <option value="">---Select Category---</option>
    <option value="real_estate">Real Estate</option>
    <option value="hotels_resturants">Hotels and Resturants</option>
    <option value="car">Car Rental</option>
  </select>
</div>


Mapview swift add multiple markers

for result in swiftyData.arrayValue {
                        let classId = result[0].stringValue
                        let className = result[1].stringValue
                        let longitude = result[2].doubleValue
                        let latitude = result[3].doubleValue
                        let newClass = NearestClasses()
                        newClass.classId = classId
                        newClass.className = className
                        newClass.longitude = longitude
                        newClass.latitude = latitude
                        nearestClasses?.append(newClass)

                        let locationSec = CLLocationCoordinate2DMake(CLLocationDegrees(latitude), CLLocationDegrees(longitude))
                        dropPin.coordinate = newYorkLocation
                        dropPin.title =  className
                        self.mapeView.addAnnotation(dropPin)*/
                        let dropPin =  MKPointAnnotation()
                        dropPin.coordinate = locationSec
                        dropPin.title =  className
                        self.mapeView.addAnnotation(dropPin)
                    }

If its one loop, this function works perfectly in swift 3. But if its multiple loop, no markers are showing on the map. Thank you


Postgresql multiple joins in single query where foreign key of a join doesn't exist in all tables

Is it possible to have two joins in a single query, where the second join is a connection between table_2 and table_3 (no key references in table_1)?

table_1

id | column_a

table_2

id | table_1_id | table_3_id | column_b

table_3

id | column_c

Existing Query:

SELECT * FROM table_1 RIGHT OUTER JOIN table_2 WHERE table_1.id id = ? and WHERE column_a = ?

Gives me the info I want from table_1 and table_2, but table_2's info will have just the table_3_id column.

In the same query, I'd like to join table_3 to get its data based on table_2.table_3_id


Need to retrieve data from cookie that holds the logged on client

I have two different pages in my WP7 Application, Page1 and Page2. On the first page the user is asked to log in using the .NET membership API through a WCF-service. When the user is logged in this client is saved in a cookie.

When the user fills in their username and password an clicks OK, the application redirects this person to the next page using the NavigationService. But after the person is redirected to Page2 I can not access the cookie of the current logged in user.

I can retrieve the logged in user on Page1 where the CookieContainer is created and the client is saved to this specific container. On Page2 I want to use the same cookie as in Page1, how do I do this?


Blank google map when using it inside multiple fragments on a viewpager

I have a viewpager where each "page" is a fragment. Each of the "page fragments" have a map fragment (google maps sdk for android) inside, added programatically using getSupportFragmentManager (If I use getFragmentManager it doesn't work either). Each added map is a new instance of SupportMapFragment (MapFragment doesn't work either).

On the first fragment, the one that is first added to the viewpager, the map works. At the other fragments, the non-interactive map just show itself as a grey square.

I'm using the 'com.google.android.gms:play-services-maps:7.5.0' dependency.

All the added maps are using the lite version. I'm doing this with:

GoogleMapOptions options = new GoogleMapOptions();
options.liteMode(true);
options.mapToolbarEnabled(false);
SupportMapFragment mapFragment = SupportMapFragment.newInstance(options);

I've read on some blogspots and here on Stackoverflow that maybe an app can only have one instance of google maps per process. Have anybody faced the same problem? Is my guess correct?

Thanks.


All process suspended - SQL Server

I'm trying to figured it out why our reporting tools slow down.

I ran sp_who2 and I've noticed a few connections that have a status of SUSPENDED and high DiskIO. The interesting thing is there is just one process that runnable at that time which is my sp_who2 query.

What happened with this DB? why is all process is suspended?

Thank you in advance for your time.


Would like some clarification on screen resolution and screen size

I use: http://quirktools.com/screenfly/ when viewing my web pages at different resolutions. I noticed when selecting the display icon which is the very first icon top left hand corner (It looks like a computer monitor), I see a drop down menu with various resolution dimensions and next to those dimensions are inches. For example, on that list, 1920 X 2000 has "24 inches next to it. Does this mean that a 24 inch monitor will typically by default have a resolution of 1920 X 2000? or is that just a demonstration of a monitor that is 24 inches and is displaying content with a resolution of 1920 X 2000? Or can you assume that most likely a 24 inch monitor will display content with a resolution f 1920 X 2000 by default?


My project is faculty allocation. when i try to insert data, it shows the following exception.

"com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'hourId' cannot be null"

Can anyone help me how to overcome this problem?
Please provide sample code to avoid this exception.

My coding is

<%
    Connection con = null;
    String StaffName = request.getParameter("StaffName");
   // String subcode = request.getParameter("subcode");
    String hourId = request.getParameter("hourId");
    String daysId = request.getParameter("daysId");
    String date = request.getParameter("date");

  //String queryText = "insert into tblstaffallocation (StaffName, subcode,hourId, daysId, date) values('"+StaffName+"','"+subcode+"','+hourId+','+daysId+','+date+')";

    try {
          Class.forName("com.mysql.jdbc.Driver");
          con = DriverManager.getConnection("jdbc:mysql://localhost:3306/StaffAllocation","root","success");

       // PreparedStatement stat = con.PrepareStatement();
        String updateString ="INSERT INTO tblstaffallocation (StaffName,hourId,daysId,date) VALUES (?,?,?,?)";

        PreparedStatement preparedStatement = con.prepareStatement(updateString);

        preparedStatement.setString(1, StaffName);
        preparedStatement.setString(2, hourId);
        preparedStatement.setString(3, daysId);
        preparedStatement.setString(4, date);
        preparedStatement.executeUpdate();
        //int rst = stat.executeUpdate("insert into tblstaffallocation ('StaffName','hourId', 'daysId', 'date') values('"+StaffName+"','"+hourId+"','"+daysId+"','"+date+"')");

        %>
        <table cellpadding="4" border="1" cellspacing="4" align="center">
        <th>StaffName</th><th>hourId</th><th>daysId</th><th>date</th>
        <%
        Statement st=con.createStatement();
        ResultSet rs=st.executeQuery("select * from tblstaffallocation");
        while(rs.next()){
            rs.getString(1);
            rs.getString(2);
            rs.getString(3);
            rs.getString(4);

        }
        } catch (Exception e) {
        out.print(e);

    }


IvoryGoogleMapBundle: How to access Google Map Object after rendering it

I'm using IvoryGoogleMapBundle in my Symfony3 project to render a map. After configuring $map object in the controller and using this sentences in my twig file ...

{{ ivory_google_map(map) }}
{{ ivory_google_api([map]) }}

It produces something like that ...

<div id="map_canvas" style="width: 100%;height: 100vh;"></div>
<style type="test/css">
    #map_canvas {
    width: 100%;
    height: 100vh;
    }
</style>
<script type="text/javascript">
    function ivory_google_map_map58e92cb0aa95e139417147 () {
    map58e92cb0aa95e139417147_container = {
        "base": {
            "coordinates": [],
            "bounds": [],
            "points": [],
            "sizes": []
        },
        "map": null,
        "overlays": {
            "icons": [],
            "symbols": [],
            "icon_sequences": [],
            "circles": [],
            "encoded_polylines": [],
            "ground_overlays": [],
            "polygons": [],
            "polylines": [],
            "rectangles": [],
            "info_windows": [],
            "info_boxes": [],
            "marker_shapes": [],
            "markers": [],
            "marker_cluster": null
        },
        "layers": {
            "heatmap_layers": [],
            "kml_layers": []
        },
        "events": {
            "dom_events": [],
            "dom_events_once": [],
            "events": [],
            "events_once": []
        },
        "functions": []
    };
    map58e92cb0aa95e139417147_container.functions.info_windows_close = function () {};
    map58e92cb0aa95e139417147_container.functions.to_array = function (o) {
        var a = [];
        for (var k in o) {
            a.push(o[k]);
        }
        return a;
    };
    map58e92cb0aa95e139417147_container.base.coordinates.coordinate58e92cb0aaca1311661317 = coordinate58e92cb0aaca1311661317 = new google.maps.LatLng(40.416862923413, -3.7034607678652, true);
    map58e92cb0aa95e139417147_container.map = map58e92cb0aa95e139417147 = new google.maps.Map(document.getElementById("map_canvas"), {
        "fullscreenControl": true,
        "fullscreenControlOptions": {
        "position": google.maps.ControlPosition.RIGHT_TOP
    },
        "mapTypeId": google.maps.MapTypeId.HYBRID,
        "zoom": 5
    });
    map58e92cb0aa95e139417147.setCenter(coordinate58e92cb0aaca1311661317);

    }
</script>

<script type="text/javascript">
    function ivory_google_map_load () {
    google.load("maps", "3", {
        "other_params": "language=en&key=__MY_API_KEY__,
        "callback": ivory_google_map_init
    })
    };
    function ivory_google_map_init_source (src) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    script.src = src;
    document.getElementsByTagName("head")[0].appendChild(script);
    };
    function ivory_google_map_init_requirement (c, r) {
    if (r()) {
        c();
    } else {
        var i = setInterval(function () {
            if (r()) {
                clearInterval(i);
                c();
            }
        }, 100);
    }
    };
    function ivory_google_map_init () {
    ivory_google_map_init_requirement(ivory_google_map_map58e92cb0aa95e139417147, function () {
        return typeof google.maps !== typeof undefined;
    });
    };
    ivory_google_map_init_source("https://www.google.com/jsapi?callback=ivory_google_map_load");
</script>

Now, from javascript console I can reach some properties like bounds using ...

map58e92cb0aa95e139417147_container.map.getBounds().getNorthEast().lat();
>> 48.2861355244946

But map container object has a random name on each render, so ... how can I guess that name in order to write some javascript to play with the map?


Is -fsanitize=bounds-strict included in -fsanitize=undefined for GCC 6?

I'm working on a problem report for a C++ library compiled with GCC 6. I'm reading through the GCC 6 Changes, New Features, and Fixes, and one of the notes is:

UndefinedBehaviorSanitizer gained a new sanitization option, -fsanitize=bounds-strict, which enables strict checking of array bounds. In particular, it enables -fsanitize=bounds as well as instrumentation of flexible array member-like arrays.

Is strict bounds checking included in -fsanitize=undefined? Or do we need both -fsanitize=undefined and -fsanitize=bounds-strict?


Replacing href click behavior with jquery

As an exercise, I'm trying to make my links in the navbar contract the content div, load the page in #content using ajaxpage() and then slide it back down. I'm using the following:

EDIT: I realized that I probably needed everything in a callback function, so I fixed that. The call still isn't working, though.

$(document).ready(function()
  {
  $("a.link").click(function() {
    //...
    return false;
});
  $("#navbar a").click(function(){
    $("#content").slideUp(500,function(){
        var a_href = $(this).attr('href');
        ajaxpage(a_href, 'content');
        $("#content").slideDown(500);
        });
  });
});

With the link being:

<a class="link" href="home.php">Home</a>

When I test it, the content div correctly slides up, but then it stays there and nothing else happens. What did I do wrong here?

EDIT: After some debugging, it seems like this is the culprit:

var a_href = $(this).attr('href');

When I declare that variable and send it through an alert(), it says "undefined". I'm guessing I'm not grabbing the attribute properly, so this is where it's hanging up! How would I properly go about grabbing the href attribute of the link that you click?


Scanning every file in a folder in c

I'm writing a program where I need to print all the files in a given folder and store the content of the files in order to compare it to another string.
What I have now is:

while ((ent = readdir(dir)) != NULL)
        {
            if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
            {
                // do nothing (straight logic)
            }
            else {

                file_name = ent->d_name;
                printf("%s\n", file_name);
                file_name = ent->d_name;
            printf("%s\n", file_name);
            char *fd = file_name;
            struct stat *buf;
            buf = malloc(sizeof(struct stat));
            stat(fd, buf);
            int size = buf->st_size;
            printf("%d", size);
            }
        }

edit:
my problem now is that it prints the size as negative


tinymce selector to div id only

With current setup tinymce selector is set to all textarea fields on my page. How can I change this to only one field using css id property?

This is my current setup

<script>
    tinymce.init({ selector: 'textarea' });
</script>


Not receiving WM_COMMAND in GetMessage loop

Could someone explain why I never receive a WM_COMMAND message in my GetMessage loop?

I've checked and the WndProc is receiving the WM_COMMAND message, so i'm very confused why this doesn't work.

while (GetMessage(&msg, NULL, 0, 0) != 0)
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);

    if (msg.message == WM_COMMAND)
    {
        // This never happens:
        MessageBox(NULL, "WM_COMMAND", "WM_COMMAND", MB_OK);
    }
}

OS: Windows 8


Building a line chart using d3.js

I'm trying to follow this tutorial to produce a simple line chart for my data in JSON format:

[{"Machine":"S2","Data":[{"Percentage":0,"Week":33,"Year":2014,"Monday":"11/08/14","Items":0},{"Percentage":0,"Week":34,"Year":2014,"Monday":"18/08/14","Items":0},{"Percentage":0,"Week":35,"Year":2014,"Monday":"25/08/14","Items":0},{"Percentage":0,"Week":36,"Year":2014,"Monday":"01/09/14","Items":0},{"Percentage":1.141848548192784,"Week":37,"Year":2014,"Monday":"08/09/14","Items":2},{"Percentage":58.264732011508123,"Week":38,"Year":2014,"Monday":"15/09/14","Items":4},{"Percentage":0,"Week":39,"Year":2014,"Monday":"22/09/14","Items":0}]},{"Machine":"S3","Data":[{"Percentage":0,"Week":33,"Year":2014,"Monday":"11/08/14","Items":0},{"Percentage":0,"Week":34,"Year":2014,"Monday":"18/08/14","Items":0},{"Percentage":0,"Week":35,"Year":2014,"Monday":"25/08/14","Items":0},{"Percentage":0,"Week":36,"Year":2014,"Monday":"01/09/14","Items":0},{"Percentage":7.7532100624144213,"Week":37,"Year":2014,"Monday":"08/09/14","Items":15},{"Percentage":0,"Week":38,"Year":2014,"Monday":"15/09/14","Items":0},{"Percentage":0,"Week":39,"Year":2014,"Monday":"22/09/14","Items":0}]}]

This is the code I have produced:

function CreateOeeChart(json)
{
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

// Parse the date / time - this is causing me problems
var parseDate = d3.time.format("%d/%m/%Y").parse;

// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

// Define the axes
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(5);

var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);

// Define the line
var line = d3.svg.line()
    .x( function(d) { return x(d.Monday); })
    .y( function(d) { return y(d.Percentage); });

// Adds the svg canvas
var svg = d3.select("#oeeChart")
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
    .append("g")
        .attr("transform",
              "translate(" + margin.left + "," + margin.top + ")");

// Modify date data
jsonString.forEach(function (d) {
    d.Data.forEach(function (v) {
        v.Monday = parseDate(v.Monday);
    });
});

// Scale the range of the data
x.domain(d3.extent(jsonString, function (d) {
    d.Data.forEach(function (v) {
        return v.Monday;
    });
}));
y.domain([0, 100]);

// Loop through the json object and use line function to draw the lines
jsonString.forEach( function (d) {
    svg.append("path")
        .attr("class", "line")
        .attr("d", line(d.Data));
});

// Add the X Axis
svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

// Add the Y Axis
svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

}

When I try to append path

 jsonString.forEach( function (d) {
    svg.append("path")
        .attr("class", "line")
        .attr("d", line(d.Data));

I get the "Invalid value for path attribute..." error. Why is that?


Audio streaming using bluetooth-A2dp profile to two speakers

I am new to bluetooth and have just started using bluez stack(5.37). I would like to know the possibilities of streaming audio simultaneously to two bluetooth speakers/Headsets using A2dp profile.

As per my study and experimentation A2dp profile is able to stream over only to one connected device although I  successfully connected to 3 headsets.

I am using Imx6-Sabre board running linux which is integrated with Bluez(5.37). Also my condition is I should be able to use A2dp so that interoperability remains with standard headsets/speakers.

Please guide me in this.


app engine upload mechanisme for changed data, does it upload whole or delta?

I upload my_app to  app engine app by:

appcfg.py update c:\my_app ...

If I already uploaded for my_app then done a minor changement in file,

Does it upload whole project to app engine and overwrite whole previous project?

Or does it upload only relevent change and overwrite relevent part?

And what is the case for the issue for this command:

bulkloader.py --restore --filename=my_kind.dump ...


Unique Key Constraint

What's the best practice in handling data insertion/update on a table with unique key constraints at the application level? These are what I came up with:

1. Run a query on the table before inserting data to see if it will violate the constraint.

Pros

You have full control so you don't have to deal with any DBMS specific error messages.

Addtional layer of data integrity check

Cons

There might be a performance hit since there will be no constraint violation most of the time.

You will need to lock the table while you run the query for duplicate data.

2. Do nothing. Update the table and see what sticks.

Pros

Simple!

Faster overall since you don't have to run an additional query everytime you update a table.

Cons

Your validation routine depends on the database layer.

If the data doesn't stick, you have to wade through the stack trace to find the cause.

Which one is the more widely accepted solution? Are there alternatives to these?

I'm using Java, JPA, Hibernate, and Spring BTW. Any suggestions, even framework specific, are welcome!

Thanks!


Drag and drop file and send with post request

I'm attempting to create a drag and drop file upload form. I got the drag and drop part working, but I can't figure out how to submit the file once I have it. I can't use ajax, the form needs to redirect just like an html upload form would.

Here's my drag and drop code.

$("html").on("dragover", function(event) {
    event.preventDefault();
    event.stopPropagation();
    $(this).addClass('dragging');
});

$("html").on("dragleave", function(event) {
    event.preventDefault();
    event.stopPropagation();
    $(this).removeClass('dragging');
});

$("html").on("drop", function(event) {
    event.preventDefault();
    event.stopPropagation();
    console.log(event.originalEvent.dataTransfer.files)
});

Normally when posting data generated through javscript I use the function below, but it doesn't work for files as you can't set file inputs.

function post(path, data) {
  let form = $('<form>')
    .attr({
      method: 'post',
      path: path
    })
    .appendTo('body')

  for(let key in data) {
    if(!data.hasOwnProperty(key)) continue;

    $('<input>')
      .attr({
        type: 'hidden',
        name: key,
        value: data[key]
      })
      .appendTo(form)
  }

  form.submit()
}


A bit of an explanation on the array_diff_uassoc function in php

Sorry for another noob question, but... Can someone please explain to me what the function myfunction is actually doing. I understand it's checking if the variables $a and $b are identical and than it's suppose to return 0 if they're identical but the next return is confusing. I see their using the ternary operators.

function myfunction($a,$b)
{
if ($a===$b)
  {
  return 0;
  }
  return ($a>$b)?1:-1;
}

$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","b"=>"green","d"=>"blue");
$a3=array("e"=>"yellow","a"=>"red","d"=>"blue");

$result=array_diff_uassoc($a1,$a2,$a3,"myfunction");
print_r($result);

the print_r returns

Array ( [c] => blue )

but how did we get here...


Select ListViewItem when child element has focus UWP

I'm writing a Universal Windows App and I have a ListView where the ListViewItems contain a TextBox and a Button. When I click in the text box I would like that ListViewItem to become selected. I've found solutions for WPF but Style.Triggers isn't available in UWP. Can anyone point me to the correct way to do this?

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:controls="using:CycleStreetsUniversal.Controls"
    xmlns:common="using:CycleStreetsUniversal.Common"
    xmlns:utils="using:CycleStreetsUniversal.Utils"
    xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
    xmlns:core="using:Microsoft.Xaml.Interactions.Core"
    xmlns:converters="using:CycleStreetsUniversal.Converters"
    x:Class="CycleStreetsUniversal.Pages.HomePage"
    mc:Ignorable="d" FontWeight="Light">

    <Page.Resources>
        <DataTemplate x:Key="DirectionItem">
            <Grid Padding="8,6,0,6">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition Width="50"/>
                    <ColumnDefinition Width="50"/>
                </Grid.ColumnDefinitions>
                <AutoSuggestBox x:Name="autoSuggestBox" PlaceholderText="{Binding Watermark}" QueryIcon="Find" Text="{Binding LocationName}" />
                <Button Grid.Column="2" Visibility="{Binding ShowAddButton, Converter={StaticResource BooleanToVisibilityConverter}}" />
                <Button Grid.Column="1" Visibility="{Binding ShowMinusButton, Converter={StaticResource BooleanToVisibilityConverter}}" />
            </Grid>
        </DataTemplate>
    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid x:Name="Directions" HorizontalAlignment="Left" Margin="0" Width="346" DataContext="{Binding DirectionPlanner, Mode=OneWay, Source={StaticResource Locator}}">
            <Grid.Background>
                <SolidColorBrush Color="{ThemeResource SystemAltHighColor}"/>
            </Grid.Background>
            <StackPanel VerticalAlignment="Top">
                <ListView x:Name="DirectionEntryList" ItemTemplate="{StaticResource DirectionItem}" ItemsSource="{Binding Entries}">
                    <ListView.ItemContainerStyle>
                        <Style TargetType="ListViewItem">
                            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                        </Style>
                    </ListView.ItemContainerStyle>
                </ListView>
                <Button x:Name="crosshairButton" VerticalAlignment="Top" d:LayoutOverrides="LeftPosition, RightPosition" Margin="20,0" HorizontalAlignment="Stretch" Padding="0" Click="crosshairButton_Click">
                    <Grid Height="50">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Image x:Name="image" Source="ms-appx:///Assets/crosshair.png"/>
                        <TextBlock Text="Set Location to Crosshair" Grid.Column="1" VerticalAlignment="Center" MaxLines="2" TextWrapping="Wrap"/>
                    </Grid>
                </Button>
            </StackPanel>
        </Grid>
    </Grid>
</Page>

The AutoSuggestBox in the data template needs to set the selected item in DirectionEntryList to the List View item that the AutoSuggestBox is a child of.


Regular expression for matching css string

I search for regular expression that will validate css code.
I want to take css string(from text input) and match by this expression.
Is anybody know useful regex for this staff
thanks for advise


How to check the boolean of checkbox?

I know this might sounds duplicate questions but none of them work for me. So far that i have done is getting the value but i want to know how to get the on/off value from the checkbox. I tried hidden field but i can't get the 1/0 value from the checkbox itself. All i get is the value.

My code is like this

$(document).delegate('.sBorrow', 'change', function(){
            var sBorrowClass = $(this).attr('class');
            var sBorrowValue = $(this).attr('value');
            var sBorrowName = $(this).attr('name');

            if(sBorrowClass.checked = true){
                alert(sBorrowValue);
                alert("unchecked");
            }
            else{
                alert(sBorrowValue);
                alert(sBorrowClass);
            }

For the checkbox form is like this

foreach($r as $row){
            $sBorrow = $_SESSION['sBorrow'];

            echo "<tr align='center'><td>". ($startrow+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['thesis_level'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td>
            <form method='post'>
            <input type='checkbox' name='sBorrow' id='sBorrow' class='sBorrow' value='". $row['serialno'] ."'>
            <input type='hidden' name='sBorrow' value=0 />
            </form></td></tr>";
            $startrow++;
            //echo $row['education_level'];

and questions 2..
Also how to make my checkbox remains checked when the user searching for more data after check the checkbox (Livesearch Ajax). Should i use localStorage or SESSION to store the value up until the user refresh?


simple attr_accesible in rails

I have a simple rails application were book belongs_to user and user has_many book. In the book model I have a filed for user which is the user_id field and I use devise for my current_user method. Now I want the current_user to add a new bood and I keep getting the error cannot mass-assign protected attributes : item, user. I have no idea were the item is coming from and do I have to include user into the list of attr_assible items. The problem is that I don't want the user attribute in the book to be massisined so people don't just try to hack and change the owner of the book. I am using rails 3.2.3


NoSuchMethodError using @Parcelize Annotation in Kotlin

I'm currently trying out the experimental (which might be why it's not working...) @Parcelize annotation to generate Parcelable code.  Most types seem to be working fine, but I'm having issues with Serializables throwing a NoSuchMethodError:

   10-05 13:55:18.549 20808-20808/com.app E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.app, PID: 20808
   java.lang.NoSuchMethodError: No virtual method writeSerializable(Ljava/util/Date;)V in class Landroid/os/Parcel;
   or its super classes (declaration of 'android.os.Parcel' appears in /system/framework/framework.jar)
       at com.app.models.Job.writeToParcel(Job.kt)
       at android.os.Parcel.writeParcelable(Parcel.java:1496)
       at android.os.Parcel.writeValue(Parcel.java:1402)
       at android.os.Parcel.writeArrayMapInternal(Parcel.java:724)
       at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
       at android.os.Bundle.writeToParcel(Bundle.java:1157)
       at android.os.Parcel.writeBundle(Parcel.java:764)
       at android.content.Intent.writeToParcel(Intent.java:8687)
       at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3082)
       at android.app.Instrumentation.execStartActivity(Instrumentation.java:1518)
       at android.app.Activity.startActivityForResult(Activity.java:4225)
       at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
       at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:65)
       at android.app.Activity.startActivityForResult(Activity.java:4183)
       at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:711)
       at android.app.Activity.startActivity(Activity.java:4522)
       at android.app.Activity.startActivity(Activity.java:4490)

I know I could fix this by changing the Date objects to Strings, but would rather not.  Has anyone else run into this issue that could provide a viable workaround other than using Strings?

If needed, here's the implementation for reference:

@Parcelize
data class Job(val id: String,
               val description: String,
               val state: String,
               val job_type: String?,
               val close_on: Date?,
               val posted_on: Date?) : Parcelable


how to stop user to download the current app

I have an app on the app store with version as 1.5

I update it to 1.6 and have some problems. The app with 1.6 is live.

What I want to do is revert app store to 1.5 and let users not to download 1.6

OR

Don't let user download 1.6 and I will fix those issue and update to 1.7 and I will allow user to download 1.7

Is there any way to get this done?


RSelenium Open Method fails with error 10061

I'm trying to get RSelenium working for the first time. Here's my code:

library(RSelenium)
checkForServer()
RSelenium::startServer()
remDr <- remoteDriver()
startServer()
remDr$open()

The return text (after the open method) is:

[1] "Connecting to remote server"
[[1]]
[1] "ï»¿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\r\n<head>\r\n \r\n<title>Error Message</title>\r\n<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\r\n\r\n<style>\r\nbody {\r\n\t\r\n\tbackground:#e5eaf5 url(/Wbo-FD9B7ED9-215B-4626-9B9E-D453142D7B18/bg.gif) top left repeat-x ;\r\n\tmargin:0px 0px 0px 0px;\r\n\tfont-family:Arial, Helvetica, sans-serif;\r\n\tmin-width:1000px;\r\n\tfont-size:12px;\r\n\tcolor:#000000;\r\n\tdirection:ltr;\r\n\t}\r\nimg {border:none}\r\n\r\n\r\n\t.main {\r\n\t\twidth:100%;\r\n\t\tbackground:url(/Wbo-FD9B7ED9-215B-4626-9B9E-D453142D7B18/topright.gif) top right no-repeat;\r\n\t\tmin-width:1000px;\r\n\t\tmin-height:400px;\r\n\t\tmargin-left:auto;\r\n\t\tmargin-right:auto;\r\n\t\ttext-align:left;\r\n\t}\r\n\t\r\n\t.logo {float:left;  height:103px; }\r\n\t.sidetext {float:right; width:182px; height:52px; background:url(/Wbo-FD9B7ED9-215B-4626-9B9E-D453142D7B18/sidetext.png) top left; border:1px solid #2a2e31; margin-right:20px; margin-top:20px; padding:4px; }\r\n\t.sidetextNone {visibility:hidden; }\r\n\t\r\n\t.whiteline {float:left; clear:both; font-size:20px; margin-left:47px; margin-top:17px; color:#ffffff; white-space:nowrap; }\r\n\t.bold {font-weight:bold;}\r\n\t\r\n\t.maintext {float:left; margin-top:20px; clear:both; color:#000; margin-left:47px;}\r\n\t\r\n\t.color1 {color:#677183;}\r\n\t\r\n\tul {margin-top:0; padding-left:15px; padding-top:5px; padding-bottom:5px;}\r\n\t\r\n\tul li {list-style-image:url(/Wbo-FD9B7ED9-215B-4626-9B9E-D453142D7B18/bullet.gif)}\r\n\tA {\r\n    FONT-WEIGHT: bold; COLOR: #005a80;\r\n}\r\nA:hover {\r\n    FONT-WEIGHT: bold;COLOR: #0d3372;\r\n}\r\n</style>\r\n  \r\n</head>\r\n<body>\r\n\t<div class=\"main\">\r\n        <div class=\"logo\"><img src=\"/Wbo-FD9B7ED9-215B-4626-9B9E-D453142D7B18/logo.png\" alt=\"ForeFront\" /></div>\r\n        <div class=\"whiteline\"><td id=L_10061_2><span class=\"bold\">Network Access Message:</span> The page cannot be displayed </td></div>\r\n    <div class=\"maintext\">\r\n    <td id=L_10061_3><span class=\"bold color1\">Explanation:</span> The Web server refused the connection.  </td><br />\r\n<br />\r\n\r\n<td id=L_10061_5><span class=\"bold color1\">Try the following:</span></td><br />\r\n\r\n<ul>\r\n<li><td id=L_10061_6><span class=\"bold\">Refresh page:</span> Search for the page again by clicking the Refresh button. The timeout could have occurred due to Internet congestion.   </td></li>\r\n<li><td id=L_10061_7><span class=\"bold\">Check spelling:</span> Check that the Web page address is spelled correctly. The address may have been mistyped.</td></li>\r\n<li><td id=L_10061_8><span class=\"bold\">Access from a link:</span> If there is a link to the page you are looking for, try accessing the page from that link. </td></li>\r\n<li><td id=L_10061_9><span class=\"bold\">Contact website:</span>You may want to contact the website administrator to make sure the Web page still exists. You can do this by using the e-mail address or phone number listed on the website home page.</td></li>\r\n</ul>\r\n<br />\r\n\r\n<td id=L_10061_10><span>If you are still not able to view the requested page, try contacting your administrator or Helpdesk.</span></td> <br />\r\n\r\n<br />\r\n<td id=L_10061_11><span class=\"bold color1\">Technical Information (for support personnel)</span></td><br />\r\n<ul>\r\n<li><td id=L_10061_12><span class=\"bold\">Error Code 10061:</span> Connection refused</td></li>\r\n<li><td id=L_10061_13><span class=\"bold\">Background:</span>The server you are attempting to access has refused the connection with the gateway. This usually results from trying to connect to a service that is inactive on the server.</td></li>\r\n<li><td id=L_10061_14><span class=\"bold\">Date:</span></td> 24/02/2015 3:45:09 AM [GMT]</li>\r\n<li><td id=L_10061_15><span class=\"bold\">Server:</span></td> MELDVTMG1.oceania.cshare.net </li>\r\n<li><td id=L_10061_16><span class=\"bold\">Source:</span> Remote server </td></li>\r\n</ul>\r\n    </div>\r\n</div>\r\n</body>\r\n</html>\r\n"

Extracting some of the pertinent text I gather that

Error number 10061 occurred, with associated text:

The server you are attempting to access has refused the connection with the gateway. This usually results from trying to connect to a service that is inactive on the server

The server in question is MELDVTMG1.oceania.cshare.net

This is a server in my organisation. I'm running behind a firewall, using a proxy, but as I understand it Selenium doesn't need to go through the firewall, it's the browser that does that. I hope I'm right in saying this.

I've googled 'rselenium open method 10061' and various combinations with no luck.

I've also tried using phantomjs with the code:

require(RSelenium)
pJS <- phantom()
Sys.sleep(5) # give the binary a moment
remDr <- remoteDriver(browserName = 'phantomjs')
remDr$open()

I get the same error text returned. However if I run phantomjs directly form the command line with a command like phantomjs test.js where the test.js file is:

var page = require('webpage').create();
page.open('http://www.news.com.au/', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
    page.render('example.png');
    console.log('http://www.news.com.au/');
  }
  phantom.exit();
});

...then it return 'success', along with a snapshot of the site, which indicates to me that it can get through the firewall and that's not the problem.

Am I missing something obvious? Any pointers would be gratefully received.

I guess I should say why I'm trying to use RSelenium in case there are better approaches. Basically I want to go to a web page, fill in some drop downs and press a button which causes a file to be downloaded.

Versions installed are:

phantomjs v2.0

RSelenium v1.0

RStudio v0.98.1083

R v3.1.1 (64-bit)

Windows 7 (64-bit)


Anti file deletion for multiplatform (Windows, Linux and OSX); is it possible?

I'm developing some software for data encryption in C. Here, I just want to ask whether there are any possibilities to make use of some techniques for anti data deletion "without relying much on specific OS API"? If your answer is that it is possible, I would be happy if you can to tell how and give me a lot of explanation. Otherwise, if it is impossible, you can give me the answer "It is impossible" without much explanation.

The reason why I do to ask is that, I anticipate if someday the attacker had already physical access   to the machine, the anti-deletion by using dependent OS API will not work (for example, by using a very fast booting OS like Backtrack 5).


How to filter by id in a list with Sencha touch app

I have a list in Sencha Touch, and I need to get different records for each item list it is very important have in mind for each item list I have a button, showing in the inside of a modal window other list with the "templates" records.. (I will try to explain me with the code..)

  {
    "id" : "0100144200",
    "address" : "hello street,Hamm",
    "openSurveys" : 1,
    "type" : 0,
    "withSurveys" : true,
    "templates": {
      "results": [
        {
          "id": "0000000772",
          "name": "TEST GENERAL AV 1"
        },
        {
          "id": "0000000799",
          "name": "TEST_TEMPLATE2"
        }
      ]
    }
  }

I am receiving this object for each item list, and I need to include in a modal window data included in the templates object.. How to detect in the list id number and related templates?

Thank you!!


Is it possible to store a method in Android shared preference

How to store a user defined method in shared preferences in android and how to load the data from that method in another activity


statically linking c file with android bionic c library

I just wrote a small c file and its header file.
dev_access.c and dev_access.h

I want to link it to the bionic library in android and create a statically/dynamically linked archive file.

My files are in /home/preetam/mydev/
The android sources are in /home/preetam/android_source

The following is my current makefile

CROSS           := /home/preetam/bin/CodeSourcery/arm2010/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi
CC              := $(CROSS)-gcc
INC_DIR         := /home/preetam/android_source/bionic/libc
CFLAGS          := -Wall -c -I$(INC_DIR)/include

android_hal: dev_access.o
        ${CC} ${CFLAGS} dev_access.c -o dev_access.a

clean:
        rm -f *.o dev_access.a

I am not sure whats going wrong but header files are not linking and some missing and redefinition errors are coming up.
The following is the Console output:

/home/preetam/bin/CodeSourcery/arm2010/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-gcc -c -Wall -I/home/preetam/android_source/bionic/libc/include -static   -c -o dev_access.o dev_access.c
In file included from /home/preetam/android_source/bionic/libc/include/stdio.h:42,
                 from dev_access.c:1:
/home/preetam/android_source/bionic/libc/include/sys/_types.h:40: fatal error: machine/_types.h: No such file or directory
compilation terminated.
make: *** [dev_access.o] Error 1

First of all, Is my Makefile correct?
Whats the proper way to link your programs with bionic libc ?
How to make the final object an archive?


Upgrade from embedded jetty8 to embedded jetty9 without changing code?

I need to upgrade from embedded jetty8 to embedded jetty9 (9.4.7.v20170914 or even a little bit lower version 9.xx ) in maven project.

First I realized that there is no org.eclipse.jetty.jetty-websocket in jetty9.

In my current java code, there are some places to use

import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketHandler;

import org.eclipse.jetty.server.handler.GzipHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;

which are not available in jetty9.

I googled it and it seems like I have to change my existing java code a lot to use jetty9.

Is there a way to upgrade jetty9 without much changing java code?


implement ActionListener in the same class for three buttons

I have three buttons in a frame, two of which I want to edit a String with, which is a package public member in the main Class (Lab2TestDrive), something like

 public class Lab2TestDrive{
...
String cale;

public static main void(String[] args){
    JButton button1.. button2.. button3..

}

Can I implement an ActionListener on Lab2TestDrive, and override the actionPerformed(...) method in there? But if I do that, I don't know how I would be able to know which button triggered the actionPerformed method.

I know I could make a separate class,

public class ButtonListener implements ActionListener {
    JButton button;
    ButtonListener(JButton button){
        this.button = button;
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        if(button.getText().equals("Save")){

        };

    }
}

But then I don't know how I could access the "cale" variable :(


Access Datagrid row on TemplateColumn button click

I am implementing a file upload tool using Silverlight. In this I can browse for files and when I select a file then it is bound to a datagrid. In the datagrid I have a template column with a button to delete the particular item from the datagrid and ItemSource of the datagrid which is a List<>.

I have a class UploadedFiles as below.

public class UploadedFiles
{
    public FileInfo FileInf{get;set;}
    public int UniqueID{get;set;}
    public string FileName{get;set;}
    public string FileExtension{get;set;}
    public long FileSize{get;set;}
}

I am using a datagrid with a templatecolumn like below with ItemSource set as List<UploadedFiles>

<data:DataGridTemplateColumn Width="100">
  <data:DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <Button Click="btn_Click" Content="Del" Width="45"/>
    </DataTemplate>
   </data:DataGridTemplateColumn.CellTemplate>
  </data:DataGridTemplateColumn>

and the button click event handler is

private void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
    /* I need to access the particular list item based on the datagrid
       row in which the clicked button resides.*/
}

I need to access the particular list item based on the datagrid row in which the clicked button resides and remove the item from the List<UploadedFiles> and rebind the datagrid.

Thanks


Copy cell from on sheet to another, if other cell in row matches values

What I want, is to copy a cell(s) from one sheet to another, only if another cell in the same row (different column) have/has a particular value(s) in Google Sheets.

Ideally, I would like this to be live; if I add a row in the first sheet and the criterion matches, the second sheet will update too. Here's an example:

Sheet one

Column A | Column(s)…  | Column D
=================================
Hello    |             | Yes
World!   |             | Yes
Foo      |             | Maybe
Bar      |             |

Sheet two

Column A | Column(s)…  | Column D
=================================
Hello    |             |
World!   |             |
Foo      |             |
         |             |

So in this example, my criteria is that if the row's cell in Column D equals either Yes or Maybe, that row's cell in Column A is copied into the second sheet.


IIS 7.5 URL Rewrite 2.0 to HTML Page

I have the following rule:

    <rewrite>
        <rules>
            <rule name="FlowURLs">
                <match url="^flows/[_0-9a-zA-Z-]+/[_0-9a-zA-Z-]+/([._0-9a-zA-Z-]+)" />
                <action type="Rewrite" url="music.html?flow={R:1}" />
            <conditions logicalGrouping="MatchAny">
                    <add input="{URL}" pattern="^.*\.(ashx|axd|css|gif|png|jpg|jpeg|js|flv|f4v|html)$" negate="true" />
            </conditions>
            </rule>
        </rules>
    </rewrite>

What I am trying to do is if a url is incoming something like the following:

http://localhost/flows/t/twit_nobone/twit_nobone1354334226132.mp3

I want to rewrite it to:

http://localhost/music.html?id=twit_nobone1354334226132.mp3

The music.html resides in the root and it has a stylesheet, javascript and images.  The problem I am seeing is that when it rewrites, no images, js or stylesheets are being displayed.  When I inspect the resources, it looks like the links are now

http://localhost/flows/t/twit_nobone/twit_nobone1354334226132.mp3/demo.css
http://localhost/flows/t/twit_nobone/twit_nobone1354334226132.mp3/images/screenshot.png

instead of

http://localhost/demo.css
http://localhost/images/screenshot.png

What am I doing wrong?  I also noticed that the url in the browser never changes to the rewritten one.


Auto/Manual Select Peers As Group Owner When Group Owner leaves the Group

Hi i would like know if it is possible to automatically/manually select the other peers to become the Group Owner , once the Group owner decide to leave the group.

For example:

Phone 1 , Phone  2 are both connected to Phone 3(Group Owner).
Phone 3 leaves the Group.

Either Phone 1 or Phone 2 will now become the GO.

My idea: Maybe when the Group owner leaves, we detect it by using OnDisconnect()? Then inside the function i do some code that will pass the value config.groupOwnerIntent =15; to the other peers? Hurmmm I really need help on this . Thank you very much.


AngularJS binding chokes on closing round bracket in JSON

I'm getting this error:

Error: [$parse:lexerr] Lexer Error: Unterminated quote ...

.... when angular tries to bind some JSON to my view.  This is because part of my json has a closing round bracket like this:

[{"title":"(MyString)"}]

This is correctly formed in the JSON, however at some point when angular tries to bind the JSON, I get the error. It's like angular is interpreting the closing round bracket as JavaScript or something, so it fails to recognise any of the JSON after 'MyString', and sees the JSON as malformed. I've googled and looked at similar errors on StackOverflow, but can't see anything talking about issues with a round closing bracket in JSON causing problems with angular.

My JSON defines geographic locations, and I suspect the issue may be occuring when angular tries to bind the locations in an ng-repeat directive like this:

<div ng-repeat="loc in mapsCtrl.locations">

I tried using the ngSanitize module to sanitize the json within my controller javascript (I know that's for HTML sanitization, however I wondered if it might work - it didn't):

title: this.$sanitize(results.MapLocation[i].Title),

I've also tried a Javascript replace:

title: results.MapLocation[i].Title.replace(")","\)"

but for some reason (maybe because I'm using TypeScript which then gets transpiled?), the JSON looks exactly the same when I inspect in the Chrome debugger:

title: "(MyString)"

So I then try a double escape:

title: results.MapLocation[i].Title.replace(")","\\)"

... and my JSON in the debugger looks like:

title : "(MyString\)"

... but I get the same error. This looks like a bug in angular. I'm thinking maybe there's some specific Angular directive I need to use for the binding? Using 'ng-bind' instead of {{}} for the expression shouldn't make any difference, since ng-bind is just longhand for the curly brace syntax. I'd appreciate any advice or suggestions on any way to fix this issue.


Iterate datastore in Sencha touch & edit record

I am using Sencha touch v 2.3.0 for my hybrid cordova app.
How can we loop through Sencha touch data store & update each record?

for (var x = 0 ;x <listStore.data.length;x++){
        var record = listStore.getAt(x);
            console.log('iterate rec at index:'+x+ ' fav list name:'+record.get('favorite_name')+'orderInd:'+record.get('order_index'));
            record.set('order_index',x);
            record.dirty = true;
            listStore.sync();

        });

This will update 1st record only correct, after that when i update 2nd record, that still have reference to 1st record.Also i have applied sorting on data store with field order_index as ASC. This data store is used on list for which i have enabled drag & sort.I have to do this update ondragsort function

onDragSort:function(list, row, from, to) {
var listStore = Ext.getStore('FavoriteListStore');
    for (x = 0 ;x <listStore.data.length;x++){
        console.log('before drag fav list name:'+listStore.data.items[x].get('favorite_name')+'orderInd:'+listStore.data.items[x].get('order_index'));
    }
for (var x = 0 ;x <listStore.data.length;x++){
        var record = listStore.getAt(x);
            console.log('iterate rec at index:'+x+ ' fav list name:'+record.get('favorite_name')+'orderInd:'+record.get('order_index'));
            record.set('order_index',x);
            record.dirty = true;
            listStore.sync();

        });
}

Initial my favorite list store have following data

name:Steel order_index:0
name:Sample Favorite List order_index:1
name:Electrical Essentials order_index:2

Above data is shown on list,now when i drag third row on list to bring it to top.
Below is console when i try to set order_index by iteration

before drag fav list name:Electrical Essentials orderInd:2
before drag fav list name:Steel orderInd:0
before drag fav list name:Sample Favorite List orderInd:1

After setting order_index by iteration , below is data on data store while iteration
iterate rec at index:0 fav list name:Electrical EssentialsorderInd:2
iterate rec at index:1 fav list name:Electrical EssentialsorderInd:0
iterate rec at index:2 fav list name:Electrical EssentialsorderInd:1

I am confused on why record is not fetched correctly when i am doing iterate & updating orderInd.Intially before set , record where fetched correctly


How to show bootstrap popover for invalid input?

I've some input boxes where if it's value is other than 1,I need to show a popover saying it is invalid for that particular input.

My code

<br/>
<br/>
<br/>
<input type="text" class="check" />
<input type="text" class="check" />
<input type="text" class="check" />
<input type="text" class="check" />
<input type="button" id="Save" value="Save" />

JavaScript

$(document).ready(function() {
  $("#Save").click(function() {
    $(".check").each(function() {
      $val = $(this).val();
      if ($val != 1) {
        $(this).popover({
          content: "Invalid"
        });
      }
    })
  })
})

LIVE DEMO


Calling activity method from FragmentPagerAdapter

My MainActivity has a double latitude value that I would like to pass to a fragment inside a FragmentPagerAdapter, so I created this getter method in MainActivity.java:

public double getLatitude() {
   return this.latitude;
}

Now I am trying to pass this value to a fragment when I create it (the getItem() method is part of a FragmentPagerAdapter class):

    public Fragment getItem(int position) {
            if (position == 0) {
                return new Fragment1();
            } else if (position == 1) {
                return new Fragment2();
            } else {
                Fragment3 fragment3 = new Fragment3();
                Bundle args = new Bundle();
                args.putDouble(fragment3.ARG_PARAM1, getActivity().getLatitude());
                fragment3.setArguments(args);
                return fragment3;
            }
        }

However, I get a compilation error that says Error:(156, 68) error: cannot find symbol method getActivity().

How can I get my main activity's getLatitude() when I create a new instance of a fragment?


Pass data between 2 dynamically loaded User control

I have a scenario where I dynamically load 2 user controls in a webform, and need them to interact together. Here's the code :

default.aspx.cs
ControlA cA = (ControlA)LoadControl("~/controlA.ascx");
ControlB cB = (ControlB)LoadControl("~/controlB.ascx");
Page.Controls.Add(cA);
Page.Controls.Add(cB);

Now the thing is, controlB needs to pass a data to controlA. Data is not from an event (well part of). When user click on a link from controlB, we get data from a DB, and what I need to pass to controlA is the ID of the first data fetch from request. And of course, when user click on the link in controlB, page do a postback.

I looked at events & delegates, but I can't make it to work. Is it the right way to go ?

If anyone could have a clue, it would be really appreciated !


removing autoreleased UIWebview results in crash

I have a view containing a subview which in turn contains a UIWebview.

the subview is allocated and autoreleased

theController = [[[viewContainer alloc] initWithNibName:@"viewContainer" bundle:[NSBundle mainBundle]]  autorelease];

The content for the webview is loaded onViewDidLoad in the subview.

I can remove this subview with no problem - as long as the app didn't go to the background before! The webview contains a link - when the user clicks on it, the app goes to the background and Safari opens the link. So far, so good. When I return to the app now and try to remove the subview containing the webview, I get this error:

bool _WebTryThreadLock(bool), 0x7f3e970: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

[Edit]

Didn't really find a solution, just a mere workaround (thanks to Jumhyn for the help!):

I added an NSNotification to the subview that holds the webview.
When I get the applicationDidBecomeActive-Notification, I just use the same NSURLrequest again that I use in the viewDidLoadMethod and reload the content of the webview.
Now I can safely remove the view without getting an error...

Very weird behaviour...


Pointers: a query about pointers

I'm learning C and C#. I'm learning about pointers and don't know what it means to combine the indirection operator and the address operator. What does it mean to combine the two?

Here is an example:

    int *p, *q;
    p = *&q;


PHPMailer attachment, doing it without a physical file

So:

// Setup mail class, recipients and body
$mailer->AddAttachment('/home/mywebsite/public_html/file.zip', 'file.zip');
The AddAttachment function has four arguments:

AddAttachment(PATH_TO_FILE, FILENAME, ENCODING, HEADER_TYPE)

I used to use xmail() and when I added a attachment here, I passed the filename and the content, that should be in it.

Like this:

$xmail->addAttachment('myamazingfile.pdf', $content);

How can I make it work the same way, so when i call AddAttachment() from the PHPmailer class, I can either pass the same or something like it, so I dont need to have a actual file on my server to send?


php in resultStr in callback jquery function, not working

I have a view, the controller renders the view sending some data, example $sizes.
In the view I have a jquery function that based on form post retrieves objects from database and returns a json response.
in the callback function I append a resultStr so to update the view with the item I got from the database.
the problem was I am using laravel and blade and blade doesn't get parsed if the script is separated from the view.
So I thought, ok I will have the resultStr use plain php instead but it doesn't work either.
For example I put this code in the callback function:

resultStr = resultStr +

      "<?php " +
      "foreach ($possible_sizes as $size){" +
      "print(\" {$size[\"it\"]} \")}" +
      " ?>";

$("#results").html(resultStr);

but then what I get in my div is not the data but this line:

<div id="results">

<!--?php foreach ($possible_sizes as $size){print(" {$size["it"]} ")} ?-->

</div>

question is: why?

example of code in script.js

    jQuery(function ($) {
        $(document).ready(function () {
            var form = $('form');
            form.submit(function (e) {
                e.preventDefault();
                $.ajax({
                    url: form.prop('action'),
                    type: 'post',
                    dataType: 'json',
                    data: form.serialize(),
                    success: function (data) {

                        var obj = (data);
                        var resultStr = "";
                        for (var i = 0; i < obj.length; i++) {

                            resultStr = resultStr +
                            "string to be" +
                            "inserted in the #results" +
                            "div and containing php code" +
                            "to be executed in the view";

                        }

                        $("#results").html(resultStr);

                    }

                })
            });

        });
    });


Example of an elegant implementation of 'Defensive Copying' of a nullable java.util.Date in a JavaBean's getter/setter implementation?

Is there an elegant Java implementation of Joshua Bloch's defensive copying techniques using the example below?  The nullChecking is really the issue I think, but perhaps there is a much simpler way to achieve defensive copying.

   public class Audit {
      private Date dateCompleted;
      ...
      public Audit() {
        super();
      }

      //defensive copy of dateCompleted
      public final Date getDateCompleted() {
        if (dateCompleted != null){
          return new Date(dateCompleted.getTime());
        }else{
          return null;
        }
      }

      public final void setDateCompleted(Date dateCompleted) {
        if (dateCompleted != null){
          this.dateCompleted = new Date(dateCompleted.getTime());
        }else{
          this.dateCompleted = null;
        }
      }
      ...
   }


How to deal with reversing an array when we do not want to change the position of special characters

I'm working on reversing a sentence. I'm able to do it. But I'm not sure, how to reverse the word without changing the special characters positions. I'm using regex but as soon as it finds the special characters it's stopping the reversal of the word.

Following is the code:

Console.WriteLine("Enter:");
string w = Console.ReadLine();
string rw = String.Empty;
String[] arr = w.Split(' ');
var regexItem = new Regex("^[a-zA-Z0-9]*$");
StringBuilder appendString = new StringBuilder();
for (int i = 0; i < arr.Length; i++)
{
    char[] chararray = arr[i].ToCharArray();
    for (int j = chararray.Length - 1; j >= 0; j--)
    {

     if (regexItem.IsMatch(rw))
{
    rw = appendString.Append(chararray[j]).ToString();
}
    }
    sb.Append(' ');
}
Console.WriteLine(rw);
Console.ReadLine();

Example : Input

Marshall! Hello.

Expected output

llahsram! olleh.


UINavigationBar displays incorrectly when combine with UITabBarController

I'm trying to create Home Screen for UITabBarViewController with another UINavigationViewController and UIViewController Subclass.

In application,There are:

two Tab for loading NewsController and VideoController

HomeViewController that loads immediately when application finish launch.

This is my application shot screen.

HomeViewController

NavigationBar show a half

NewsViewController

This is my code.

//In TabBarWithHomeDelegate.m

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    homeViewController = [[HomeViewController alloc]init];

    UINavigationController *nav = [[UINavigationController alloc]init];

    nav.navigationItem.title = @"Tab 1 Data";
    [nav pushViewController:homeViewController animated:NO];

    [self.tabBarController setSelectedViewController:nav];

    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

//In NewsViewController.m for touching on home button

-(IBAction) homeButtonClick:(id)sender
{
        TabBarWithHomeAppDelegate * appDelegate
        = [[UIApplication sharedApplication] delegate];

        UITabBarController * tabBarController =  appDelegate.tabBarController;
        [tabBarController setSelectedViewController:nil];
        [tabBarController setSelectedViewController:appDelegate.homeViewController];

}

In addition, I have attached source code. I'm will be grad if you see that and help me to solve this. In fact, I try to do it myself almost 6 hours.

link to download source code.


Convert an expression tree for a c# query expression

I am having a problem converting this query via an expression tree:

WageConstIn => Convert.ToString(WageConstIn.Serialno).StartsWith("2800")

This is my expression tree:

var searchTextExp = LinqExpression.Constant("2800");
var parameterExp  = LinqExpression.Parameter(typeof(WageConstInEntity), "WageConstIn");
var propertyExp   = LinqExpression.Property(parameterExp, "Serialno");
var convertExpr   = LinqExpression.Parameter(typeof(Convert), "Convert");
var toStringExp   = LinqExpression.Call(convertExpr, "ToString", new[] { typeof(decimal) }, new[] { propertyExp });
var startsWithExp = LinqExpression.Call(toStringExp, "StartsWith", null, new[] { searchTextExp });

I am getting the following error:

"No method 'ToString' on type 'System.Convert' is compatible with the supplied arguments"


Tinyint in MySQL Results Returning Wrong Values

I have a table with about 50k records.  Each record is associated with an activation code and a tinyint(1) that is either a 1 or a 0 depending on if it has been activated or not.

I wrote this script to search activation codes:

$count = 1;
foreach ($array as $value) {

    try{
        $stmt = $db->prepare("SELECT * FROM customers WHERE code = '$value'");
        $stmt->execute();
        $row = $stmt->fetchAll();

        foreach ($row as $row1) {
            echo "$count,{$row1['code']},{$row1['activated']} <br />";
        }

    }catch(PDOException $e){
        echo $e;
    }

    $count++;
}

It will print out results as such:

263,GCTDA598149901,1
264,GCTDA363633527,1
265,GCTDA474011458,1
266,GCTDA610122649,1
267,GCTDA973129612,1
268,GCTDA472831092,1
269,GCTDA567914117,1
270,GCTDA763417638,1
271,GCTDA833541425,1
272,GCTDA556328307,1
273,GCTDA441015640,1
274,GCTDA266326284,1
275,GCTDA495338154,1
276,GCTDA320542455,1
277,GCTDA429649757,1
278,GCTDA468213166,1
279,GCTDA264634579,1
280,GCTDA842325439,1
281,GCTDA331321327,1
282,GCTDA280321014,1
283,GCTDA904841155,1
284,GCTDA728739105,1

All of the tinyint's are returned as a 1 whether is it a 1 or a 0 in the database.  I am truly at a loss right now on what is causing it.  I hope someone can help.


Firebase Cloud Messaging not working on IOS

So I have been trying to figure this out for a while I have followed the set up guide a few times and I can't even get the push notifications sent form the firebase console to show up. I have Phone Auth set up and working, which required push notifications and APN set up, same as FCM. Here is my AppDelegate file:

//
//  AppDelegate.swift
//  texter
//
//  Created by Johnathan Saunders on 3/28/17.
//  Copyright © 2017 Johnathan Saunders. All rights reserved.
//
import UIKit
import Firebase

import UserNotifications
@UIApplicationMain
class AppDelegate:  UIResponder, UIApplicationDelegate,MessagingDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        FirebaseApp.configure()

        // [START set_messaging_delegate]
        Messaging.messaging().delegate = self
        // [END set_messaging_delegate]
        // Register for remote notifications. This shows a permission dialog on first run, to
        // show the dialog at a more appropriate time move this registration accordingly.
        // [START register_for_notifications]
        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
        let token = Messaging.messaging().fcmToken
        print("FCM token: \(token ?? "")")
        // [END register_for_notifications]

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // Pass device token to auth.
        let firebaseAuth = Auth.auth()

        //At development time we use .sandbox
        firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
        print("APNs token retrieved: \(deviceToken)")
        InstanceID.instanceID().setAPNSToken(deviceToken, type: .prod)
        // With swizzling disabled you must set the APNs token here.
        Messaging.messaging().apnsToken = deviceToken
        //At time of production it will be set to .prod
    }

    //notifcation stuff

    // [START receive_message]
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification
        // With swizzling disabled you must let Messaging know about the message, for Analytics
         Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification
        // With swizzling disabled you must let Messaging know about the message, for Analytics
         Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
    }
    // [END receive_message]
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }

    // [END ios_10_message_handling]

    // [START refresh_token]
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")

        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }
    // [END refresh_token]
    // [START ios_10_data_message]
    // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
    // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")

    }
    // [END ios_10_data_message]

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")

        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }

}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        // Change this to your preferred presentation option
        completionHandler([])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        completionHandler()
    }

}

The certs and keys I downloaded/ generated are:
The Certificates, Identifiers & Profiles section looks like this:

In firebase's setting its looks like this:


Find a gem version via bundler

Is there a way we can find a Gem version via bundler ?

For eg

$ bundle show capistrano
/Users/ankitgupta/.rvm/gems/ruby-2.1.1/gems/capistrano-3.2.1

This gives me the version, but i don't want to play with splitting and finding the value via last index.

I tried it this way

a = `bundle show capistrano`
b = a.split("/").last
b.slice! ("capistrano-")
puts b

$3.2.1

The above does my work, but is there a quick way to do it?