text:
Q: Proper coded examples of MVC 3 error handling I'm coming from the Winforms world where I trapped everything and handled errors with messages to the user with MessageBox.Show(ex.message) or just logged it.
Now I'm in the web (MVC 3) world and I can't seem to find a definitive coded example of how to employ proper error handling. Let me show you what I'm using:
User clicks on a link which runs a controller action:
Function SelectAlertKPIs() As ActionResult

    Try
        Return PartialView()

    Catch ex As Exception
        TempData("ErrorMessage") = "There was a problem during page load: " & ex.Message & vbCrLf & vbCrLf & ex.StackTrace
        Return RedirectToAction("HttpError", "Error")
    End Try

End Function

This view loads a Telerik grid with AJAX binding, so now the binding runs this action:
<GridAction()> _
Function _SelectAlertKPIs() As ActionResult

    Try
        Return PartialView(New GridModel(AlertKPIRepository.All()))

    Catch ex As Exception
        TempData("ErrorMessage") = "There was a problem during page load: " & ex.Message & vbCrLf & vbCrLf & ex.StackTrace
        Return RedirectToAction("HttpError", "Error")
    End Try

End Function

Which calls this method to get data:
Public Shared Function All() As IList(Of AlertKPI)

    Dim l As IList(Of AlertKPI) = Nothing

    Try
        Using dc As New AdminAlertKPIDataContext(TripleDESSecurity.Decrypt(SharedData.PortalCnx))
            l = (From d In dc.AdminAlertKPIs Order By d.ID Select New AlertKPI With {
                .ID = d.ID,
                .KPI = d.KPI,
                .KPIName = d.KPIName,
                .KPIDescription = d.KPIDescription
            }).ToList
        End Using

        Return l

    Catch ex As Exception
        Throw
    Finally
        If Not l Is Nothing Then l = Nothing
    End Try

End Function

These are my ErrorController actions:
Public Function HttpError() As ActionResult

    Dim s As String = String.Empty

    s = TempData("ErrorMessage")
    ViewData("ErrorMessage") = "An error occurred. " & s

    Return PartialView("Error")

End Function

Public Function Http404() As ActionResult

    Try
        ViewData("ErrorMessage") = "The page you requested could not be found"

        Return View("Error")

    Catch ex As Exception
        Return View("Error")
    End Try

End Function

This is what I have in my web.config:
<customErrors mode="On" defaultRedirect="/Error/HttpError">
  <error statusCode="404" redirect="/Error/Http404" />
</customErrors>

Now if I add code into my controller action to purposely throw:
Throw New HttpUnhandledException

Then it falls to the catch block, and then routes to the HttpError action.. Twice! and then my Error.aspx view never opens, instead I get either no JSON result or a 500 internal server error... makes not a lick of sense to me. Basically, I don't know what I'm doing.
And I could use some really good guidance....

A: You need to look into [HandleErrorAttribute] - there is no need to polute your action methods with try catch blocks. You might want to implement your own error handler attribute for additional logging - which is what I'm doing today. This is today's post on exception handling: click here
Your web config is for exceptions that occur outside of MVC application pipeline. IIS will be able to read the web config and then re-direct user to the correct page. Others, please correct me if I'm wrong as I only started looking at this today.


text:
Q: Start Driver When Graphics Tablet is Connected I have this veik-tablet app installed on my Ubuntu 22.04.1 system. I must start it first and it opens minimized at system tray only after that I'm able to use my tablet.
But I want the app to start automatically as soon as the tablet connected via usb, is that possible?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best practices for creating CRUD services in AngularJS What is the best practice for designing CRUD services / factories within an AngularJS application that process single and multiple entities?
For example I have a customer object in a factory called customerFactory that contains a structure similar to this:
var customer = {
    newCustomer: false,
    selfUri: null,
    editUri: null,
    deleteUri: null,
    customerName: null,
    customerAddress: null
};

And that I also have the following example functions exposed on that factory that call REST services:
var create = function() {
    $http.post('api/customers/1', { customer: customer } );
}

var read = function() {
    $http.get('api/customers', { params { uri : customer.selfUri } );
}

var update  = function() {
    $http.put('api/customers/1', { customer: customer } );
}

var delete = function() {
    $http.delete('api/customers/1', { uri: customer.deleteUri } );
}

// This is an oddity and probably shouldn't be in this factory??
var readAll = function() {
    $http.get('api/customers', {} );
}

All of these methods basically work on the customer object within the factory.
Should the readAll() method be put into a different service / factory that handles retrieving ALL customers rather than put into the above factory as it deals with single entities?  Should REST calls that retrieve multiple entities be placed into it's own factory?
Example: customerFactory
// Deal with single customer entities
app.factory('customerFactory', ['$http',
    function($http) {
        var customerFactory = {};

        var customer = {
            newCustomer: false,
            selfUri: null,
            editUri: null,
            deleteUri: null,
            customerName: null,
            customerAddress: null
        };

        var create = function() {
            $http.post('api/customers/1', { customer: customer } );
        }

        var read = function() {
            $http.get('api/customers', { params { uri : customer.selfUri } );
        }

        var update  = function() {
            $http.put('api/customers/1', { customer: customer } );
        }

        var delete = function() {
            $http.delete('api/customers/1', { uri: customer.deleteUri } );
        }

        customerFactory.create = create;
        customerFactory.read= read;
        customerFactory.update= update;
        customerFactory.create = delete;

       return customerFactory;

    }]);

Example: customersFactory
// Deal with multiple customer entities
app.factory('customersFactory', ['$http',
    function($http) {
        var customersFactory = {};
        var customers = {};

        var readAll = function() {
        $http.get('api/customers', {} ).then(function(response) {
            customers.push(response.data);
        });

        customersFactory.readAll = readAll;

        return customersFactory;

    }]);

A: Let me preface by saying I am pretty new to angular. With that said, you can create a CustomerClass that is used in the CustomerList and Customer services. The customerlist service will return an array, whereas the customer service will return a single customer. Even though I add them to the app with .factory(), they are used as services.
Notice that CustomerClass only returns the function (class) without a new keyword. This is so that you can instantiate a new CustomerClass on your own in the other services. The self.init function is the constructor and it will automatically extend the values of an object that you pass in. Self.init is called automatically right under the declaration.
I use Self.ready in my factories so that if I am using ng-repeat, it won't show unless the factory has a status of ready=true. Because you are pulling data in an ajaxy way, you don't want to update the views with anything until the data is received and ready.
myApp.factory("CustomerClass", function ($http) {
    function CustomerClass(extendableObject) {

        var self = this;
        self.init = function () {
            //will extend newCustomer, selfUri, editUri etc... fields
            angular.extend(self, extendableObject);
        };
        self.init();
    }

    return CustomerClass;
});

myApp.factory("CustomerListService", function ($http, CustomerClass) {
    function CustomerList() {
        var self = this;
        self.ready = false;
        //return array of customer objects
        self.readAll = function () {
            var customers = [];
            $http.get('api/customers/list')
                .success(function (payload) {
                    angular.forEach(payload.customers, function (customer) {
                        customers.push(new CustomerClass(customer));
                    });
                    self.ready = true;
                    return customers;
                });
        };
    }

    return new CustomerList;
});

myApp.factory("CustomerService", function ($http, CustomerClass) {

    function Customer() {
        var self = this;
        self.ready = false;
        //return one customer object
        self.read = function (id) {
            $http.get('api/customers/single', {params: {id: id}})
                .success(function (payload) {
                    return new CustomerClass(payload);
                    self.ready = true;
                });
        };
    }

    return new Customer;
});

A: I'd prefer you to use $resource that will suits better in your case.
Only you need to write a single method inside a service that can remove your all redundant code of your service like it'll act as GET, PUT, DELETE & UPDATE
Factory CODE
var app = angular.module('mainApp',['ngResource']);
app.factory('Customer', function($resource) {
  return $resource('/api/customers/:id'); // Note the full endpoint address
});

Controller
app.controller('CustomerController', function($scope, Customer) {
    var customer = Customer.get({ id: $scope.id }, function() {
        console.log(customer);
    }); // get() returns a single entry

    var customers = Customer.query(function() {
        console.log(customers);
    }); //query() returns all the customers

    $scope.customer = new Customer(); //You can instantiate resource class

    $scope.customer.data = 'some data';

    Customer.save($scope.customer, function() {
        //data saved. do something here.
    }); //saves an customer. Assuming $scope.customer is the Entry object
});

By using single service method you can do many thing. I'd prefer using $resource when dealing with REST API
For more detailed information do visit here
Update
If you still want to stick with $http For making your code more reusable i'll avoid to create customerFactory which is having all methods related to customer, Rather than that I'd love to create angular.constant, by using that constant array we'll create a new service using that array.
Constant
app.constant('customerMethods', [
            {name: 'create', type: 'post', url: 'api/customers/1', dataParam:{ customer: customer }},
            {name: 'read', type: 'get', url: 'api/customers', dataParam:{ params: { uri : customer.selfUri }},
            {name: 'create', type: 'post', url: 'api/customers/1, dataParam:{ customer: customer }}, //you need to provide customer object
            {name: 'create', type: 'post', 'api/customers/1', dataParam: { customer: customer }},//you need to provide customer object
]);

Factory
app.factory('customersFactory', ['$http', 'customerMethods', 'customer',
    function($http, customerMethods, customer) {
        var customersFactory = {};
        var customers = {};
        var customerMethods = customerMethods;

        angular.forEach(customerMethods, function(val, index) {
            angular.extend(customersFactory, {
                val.name: function() {
                    return $http[val.type](val.url, val.dataParam);
                }
            });
        });

        return customersFactory;

    }
]);

Your re-factored code will look like above. Though it is not tested, but I'm sure the way would be like this only.
Hope this could help you. Thanks.


text:
Q: Genus over finite fields Is there a way of computing the genus of a parametrized curve over a finite field?
For instance I am interested in the genus of the following space curve in the m-dimensional space over $F_{q^k}$ given parametrically as:
$(x, x^h, x^{h^2}, \dots , x^{h^{m-1}})$
Here h and m are some fixed constants, say.
I basically work in theoretical computer science, more specifically in algebraic coding theory, so am not that familiar with advanced algebraic geometry, so I apologize in advance if the question is vague. Any help or references in this regard would be appreciated.

A: The map you describe is also defined over the algebraic closure of $\mathbb F_q$ and is a morphism of algebraic varieties from the affine line to the affine space of dimension $m$. The projection to the first coordinate, when restricted to the image, is the inverse map. So the image is isomorphic to the affine line. You can say it has genus $0$ (usually, the genus is defined for projective curves).


text:
Q: Confused on which variables should be shared or private in nested OpenMP loop I have a nested loop and im confused on which variables should be shared or private. I believe that i and j should be private but im confused on whether other variables also need to be shared or privated in my code:
    y = p->yMax;
    #pragma omp parallel for private(i,j)
    for (i = 0; i < p->height; i++) {
        x = p->xMin;
        for (j = 0; j < p->width; j++) {
            p->carray[i * p->width + j] = x + y * I;
            x += p->step;
        }
        y -= p->step;
    }

    for (i = 0; i < p->maxIter; i++) {
        p->histogram[i] = 0;
    }
}

Cheers

A: *

*Assuming that you do not need the values of i and j after the loops and observing that you reset i and j to zero at the beginning of the loops, I would simply define the i and j within the loop. If so, you don't have to state the behaviour of i and j when entering and exiting the loop (because it is automatically private).

*I think that the value of x before entering the loop is not needed as well, so you can also go for private here or define x as a local varieble.

*If y is treated similar as x and has to be reset to p->yMax in every step, you can either declare y as private and move into the loop, same as x. Or you have to declare y as firstprivate such that the previous value is not lost when entering the parallel region. Using shared is not an option for both x and y since you += and -= change the value of these variables.

*p should be shared, as you need the values of p->xMin, p->step and p->yMax and you probably also want to use the values of p->carray after exiting the loop.

``
#pragma omp parallel for shared(p)
    for (size_t i = 0; i < p->height; i++) {
        auto x = p->xMin;
        auto y = p->yMax;
        for (size_t j = 0; j < p->width; j++) {
            p->carray[i * p->width + j] = x + y * I;
            x += p->step;
        }
        y -= p->step;
    }

//This one isn't in the parallel region
    for (size_t i = 0; i < p->maxIter; i++) {
        p->histogram[i] = 0;
    }


text:
Q: how to change permalinks format for pagination? Sorry if my question was basic or stupid. Please help me how to do this in wordpress, i m new to wordpress.
I have permalinks for pagination page like this
www.website.com/customtaxonomy.html/1
www.website.com/customtaxonomy.html/2

but i need to change this permalinks as
www.website.com/customtaxonomy.html?page=1
www.website.com/customtaxonomy.html?page=2

only for paginations pages.0


text:
Q: Are there any set rules for string limits in Facebook Graph API? On Twitter it's clear - 140 utf-8 chars, no html.
Does Facebook have clear set of rules about what is allowed in strings posted to wall via API?
I am referring to this API: http://developers.facebook.com/docs/reference/api/post/
I did some experiments and it looks like the content of "message" cannot contain any html tags - they will all be converted to html entities.
The content of "description" can contain bold and italic tag but the rest of the html tags are completely removed - not even converted to html entities - just removed along with the values of tags.
I still have no idea as to the maximum lengths of string allowed in "message", "description" and "caption". What formatting tags are allowed?
Does anyone know if Facebook clearly stated the limits for those strings?

A: I don't think there's any "official" notation about this, which is one more "flaw" to add to their documentation!
I hope someone can prove me wrong! (I really do!)


text:
Q: No UICollectionViewLayoutAttributes instance for layoutAttributesForSupplementaryElementOfKind? 2014-07-24 11:50:15.925  *** Assertion failure in -[UICollectionViewData layoutAttributesForSupplementaryElementOfKind:atIndexPath:], /SourceCache/UIKit/UIKit-2935.137/UICollectionViewData.m:787

2014-07-24 11:50:15.927  *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForSupplementaryElementOfKind: UICollectionElementKindSectionFooter at path <NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}'

i have this error message occurs when i scrolling my collection view and i totally loss in mind how could this happen ? any suggestion to help are thankful.
The register
[self.collectionView registerClass:[CollectionViewFooter class]
            forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"CollectionViewFooter"];

The Delegate Method
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //declare the reusable view of header and footer
    UICollectionReusableView *reusableview = nil;

    CollectionViewFooter *footer=nil;

    if([kind isEqual:UICollectionElementKindSectionFooter])
    {
        footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"CollectionViewFooter" forIndexPath:indexPath];

        //attach the footer to reusable view
        reusableview = footer;
    }

    return reusableview;
}

Check by break point, error occur when reach to line
 [self.collectionView performBatchUpdates:^{


text:
Q: Does killing the parent actor kill the children too? Seeing some different behaviour I was underassumption that, if you kill the parent actor, the children will be killed too, but when I tried something like this given below, I am getting a different behaviour. Could someone please explain?
1. Here the actor GrandFather creates Son and Son creates GrandSon.
2. Grandson sends a message to GandFather, so Grandfather gets the actoRef of the Grandson.
3. Then on receiving a specific message ("crash") from GrandFather, Son throws an exception.
4. Now GrandFather tries to send messages to both Son and GrandSon. Messages to Son goes to Deadletter Queue, whild messsages to GrandSon is received and printed.

 object GrandFather{
   def props()=Props(new GrandFather)
 }
 class GrandFather extends Actor with ActorLogging {
   var child:ActorRef=Actor.noSender
   override def receive: Receive = {
     case x:String if x.equals("Test Grandpa") =>
       println("I am grand father ->" + x)
       child = context.actorOf(Son.props)
       child ! "Test Son"
     case y:String =>
      val grandChild = sender()
      println("I am the grandfather, Got Message from grand child, gonna kill my son")
      child ! "crash"
      child ! "there"
      grandChild ! "Are you Alive?"
       child ! "there"
       grandChild ! "Are you Alive?"
       child ! "there"
       grandChild ! "Are you Alive?"
       child ! "there"
       grandChild ! "Are you Alive?"
       child ! "there"
   }
 }

 object Son{
   def props:Props = Props(new Son)
 }
 class Son extends Actor with ActorLogging {
   var actr:ActorRef = Actor.noSender

   def receive:Receive={
     case y:String if y.equals("crash") => throw new Exception("killed by self")
     case z:String if z.equals("there") => println("I am the son -> " + "still here")
     case x:String => {
       val k = sender()
       println("I am the son -> " + x)
       actr = context.actorOf(GrandSon.props())
       actr ! ("Test GrandChild ", k)
     }
   }
 }

 object GrandSon{
   def props() = Props(new GrandSon)
 }
 class GrandSon extends Actor with ActorLogging {
   def receive:Receive={
     case (x:String, y:ActorRef) => {
       println("I am the grand child -> " + x)
       y ! "go ahead and kill your son, i.e. my father"
     }
     case y:String if y.equals("Are you Alive?") => println("I am Grand Child, grandpa I am still alive")
   }
 }

The output of this code:
 Testing started at 17:57 ...
 I am grand father ->Test Grandpa
 I am the son -> Test Son
 I am the grand child -> Test GrandChild
 I am the grandfather, Got Message from grand child, gonna kill my son
 I am Grand Child, grandpa I am still alive
 I am Grand Child, grandpa I am still alive
 I am Grand Child, grandpa I am still alive
 I am Grand Child, grandpa I am still alive
 [WARN] [10/07/2016 17:57:10.818] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there
 [WARN] [10/07/2016 17:57:10.819] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there
 [WARN] [10/07/2016 17:57:10.820] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there
 [WARN] [10/07/2016 17:57:10.821] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there
 [WARN] [10/07/2016 17:57:10.821] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there

A: per documentation default strategy
ActorInitializationException will stop the failing child actor
ActorKilledException will stop the failing child actor
Exception will restart the failing child actor
Other types of Throwable will be escalated to parent actor

you are actually not killing the actor but restarting it.
if you want to prove this, override more methods for son actor
like in documentation
def preStart(): Unit = ()

def postStop(): Unit = ()

def preRestart(reason: Throwable, message: Option[Any]): Unit = {
  context.children foreach { child ⇒
    context.unwatch(child)
    context.stop(child)
  }
  postStop()
}

def postRestart(reason: Throwable): Unit = {
  preStart()
}


text:
Q:  stretches while wrapping becoming unnecessarily wide Each row of the tree is nested inside a div with flex display. The whole tree is inside a fixed width (200px) div - the one with the gray background.
I want all the blue buttons to only take up as much width as needed to fit the text. When text wraps into multiple lines, the divs stretch to fill up the whole row. Can it be prevented without setting a constant width to the div?

https://jsfiddle.net/nLcgym5z/2/

-

Karpaty

-

Karpaty Zachodnie

-

Zewnętrzne Karpaty Zachodnie

Karpaty Austriacko-Morawskie

Karpaty Środkowomorawskie

+

Beskidy Zachodnie

Beskidy Środkowe

Karpaty Wschodnie

CSS:
.filter-name {
    font-size: 0.85em;
    line-height: 1;
    padding: 3px;
    margin: 1px;
    cursor: pointer;
    user-select: none;
    align-self: flex-start;
    width: auto;
}
.filter-name:hover {
    color: royalblue;
}

/* selected filter names - collapsed or open view */
.filter-name.selected {
    background: royalblue;
    border-radius: 4px;
    color: white;
}
.filter-name.selected:hover {
    background: #5179f1;
}

/* blue selected filters buttons - collapsed branch view */
.applied-filters {
    display: flex;
    flex-wrap: wrap;
    margin-left: 10px;
}

/* Displays filter name, plus/minus button and button horizontal tree branch centered in a row */
.filter-row {
    display: flex;
    align-items: center;
}

.filter-branch {
    margin-left: 12px;
    position: relative;
}

/*Tree vertical branches display */
.filter-row,
.filter-category {
    position: relative;
}
.filter-category:not(:last-child)::before {
    z-index: 1;
    content: '';
    position: absolute;
    top: -15px;
    left: 0px;
    bottom: 10px;
    border-left: 1px solid royalblue;
}
.filter-category:last-child .filter-row-container .filter-row::before {
    z-index: 1;
    content: '';
    position: absolute;
    top: -15px;
    left: 0px;
    bottom: 50%;
    border-left: 1px solid royalblue;
}

/* Tree horizontal branches display */
.tree-button-guide {
    line-height: 0.6;
    height: 1px;
    width: 5px;
    margin-right: 2px;
    border-top: 1px solid royalblue;

    flex-shrink: 0;
}

/* Plus / minus tree buttons */
div.tree-button {
    z-index: 3;
    font-size: 0.8em;
    text-align: center;
    line-height: 10px;
    width: 10px;
    height: 10px;
    padding: 2px;
    margin: 2px;
    margin-left: -3px;
    background-color: royalblue;
    border-radius: 2px;
    color: white;
    cursor: pointer;

    flex-shrink: 0;
}

body {
    font-family: sans-serif;
    font-size: 90%;
    background-image:url("../img/bg.jpg");
    background-size: cover;
    background-attachment: fixed;
}

.filter-panel {
    width: 200px;
    background: lightgray;
}

A: Add the following:
.filter-name.selected {
flex: 0;
}

A: You can add a flex-basis of 0% to the selected items:
.filter-name.selected {
  flex-basis: 0%;
}

Unfortunately, this will force some items to line wrap before it is necessary.
The better answer might be to put the blue box inside the .filter-name element, as a new sub-element:

Beskidy Zachodnie

Then apply the bg color, padding, and border radius to that element. You may also want to set it to display: inline-block.


text:
Q: Web API POST method for Tables with Relationship I am new to Web API.
I am creating web API POST method for Order. in which two tables I have created
1)Tbl_Order have columns- Order_ID -Primary Key, Employee_ID, TotalBill,
2)Tbl_OrderMenu have columns- OrderMenuID -Primary Key, Order_ID -Foreign Key from Tbl_Order, MenuName, Quantity
the relationship between tables is one-to-many i.e. Tbl_Order(1)-to-Tbl_OrderMenu(* or Many).
How can I create Web API to POST method to create Data at the same time?
public class myCombinedClass
{
 public int Order_ID {get;set;}
 public int Employee_ID {get;set;}
 public string TotalBill {get;set;}
 public List<Tbl_OrderMenu> OrderMenu { get; set; }
}

My API POST controller is
public HttpResponseMessage Post(myCombinedClass myData)
{
 if(myData.id == 0)
  {
    // This is a new entry to Tbl_Order.
  }
 else
  {
   //You just need to update the Tbl_Order. I mean, here you are adding
   //data to Tbl_OrderMenu table with  Order_ID.
  }
}

What will come in POST method.

A: @manish, here is an example of the POST method using EF:
// POST: api/myCombinedClasses
[ResponseType(typeof(myCombinedClass))]
public async Task<IHttpActionResult> PostmyCombinedClass(myCombinedClass mycombinedclass)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.myCombinedClasses.Add(mycombinedclass);
    db.OrderMenus.AddRange(mycombinedclass.OrderMenu);
    await db.SaveChangesAsync();

    return CreatedAtRoute("DefaultApi", new { id = mycombinedclass.Order_ID }, mycombinedclass);
}


text:
Q: Non-fireing if-statement How to modify this program to print just three lines and intent to 2nd and 3rd start with space. My if-statement doesn't seem work
package com.TnationChallange;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        for (String part : getParts("screen space to display information", 7, 3)) {
            System.out.println(part);
        }
    }
    private static List<String> getParts(String string, int partitionSize, int maxLine) {
        List<String> parts = new ArrayList<String>();
        int len = string.length();
        for (int i = 0; i < len; i += partitionSize) {
            parts.add(string.substring(i, Math.min(len, i + partitionSize)));
            maxLine++;
            if (maxLine == 3) {
                break;
            }
        }
        return parts;
    }
}

A: The third parameter you pass to the getParts method is 3 and because you call maxLine++ before if (maxLine == 3) that condition will never be true.
You should use something like this:
....
maxLines--;
if(maxLines == 0){
   ....
}
.....

A: You need a different variable to count the lines.
package com.TnationChallange;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {

        for (String part : getParts("screen space to display information", 7, 3)) {
            System.out.println(part);
        }
    }
    private static List<String> getParts(String string, int partitionSize, int maxLine) {
        List<String> parts = new ArrayList<String>();
        int len = string.length();
        int count = 0;
        for (int i = 0; i < len; i += partitionSize) {
            parts.add(string.substring(i, Math.min(len, i + partitionSize)));
            count++;
            if (maxLine == count) {
                break;
            }
        }
        return parts;
    }
}

This is assuming you want to limit your result by maxLine.


text:
Q: IReport text overflows to next detail band I am trying to get a TextField to dynamically size within its band.  When I have more than three rows they overflow into the following detail row.  I tried setting the Stretch with Overflow, Float, Relative to Tallest Object, and Detail Overflows to values I saw recommended here.. Stretch a row with data overflow while having multiple rows in a single band

This did not keep it within it's own band.  I tried in iReport 5.0.0 and Eclipse with JasperReports compatible with 5.1.0. The only alternative I have found so far is to make the row bigger but then the bands with fewer rows are too big.

Note the all caps are supposed to be in the same field.
No luck with Stretch Type RelativeToBandHeight

A: try set
stretchType="RelativeToBandHeight"


text:
Q: shinydashboard toggle box - hide by default This is a follow up to a previous thread. The answers give an option which shows the box by default, but how can I change it to be hidden by default?
Below code a mix of both answers.
library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      useShinyjs()
    ),
    mainPanel(
      box(id = "myBox", title = "Tree Output", width = '800px',
          selectInput(inputId = "myInput", label = "my input", choices = c(letters))
      ),
      actionButton(inputId = "button", label = "show / hide")
    )
  )
)

server <- function(input, output){

  ## observe the button being pressed
  observeEvent(input$button, {
    shinyjs::toggle("myBox")
  })
}

shinyApp(ui, server)

A: You can wrap it around another div and use hidden function from shinyjs
library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            useShinyjs()
        ),
        mainPanel(
            hidden(
                div(id = "mybox_wrapper",
                    box(id = "myBox", title = "Tree Output", width = '800px',
                        selectInput(inputId = "myInput", label = "my input", choices = c(letters))
                    )
                )),
            actionButton(inputId = "button", label = "show / hide")
        )
    )
)

server <- function(input, output){

    ## observe the button being pressed
    observeEvent(input$button, {
        shinyjs::toggle("mybox_wrapper")
    })
}

shinyApp(ui, server)

A: You can toggle the myBox. Kind of if the server clicks it for you beforehand.
server <- function(input, output){

  # Hide or show myBox
  toggle("myBox")
  ## observe the button being pressed
  observeEvent(input$button, {
    shinyjs::toggle("myBox")
  })
}


text:
Q: Post migration MySQL database validation We are migrating from 5.5 enterprise mysql to 8.0 mysql enterprise edition. And we are migrating version by version like from 5.5 to 5.6 then 5.6 to 5.7 and lastly from 5.7 to 8.0  also os migration is there from the rhel5. 4 to 8.4 it's all okay but client want data validation value by value. Normal data validations like row counts, and checksum is not sufficient to client as data is senstive.  Suggest any good tool, script or query to check value to value data validation

A: I would use pt-table-sync.
This is a free tool from Percona. It's a command-line tool, implemented in Perl. You use it by giving arguments describing connections to both the original database instance and the new database instance. It compares row by row (really small groups of rows at a time), and then generates a diff, so that you could make the new instance have the same data as the original.
You can use the tool to execute the change to synchronize the data, or optionally you can make it only report the diff, and do nothing to change data. Read the documentation I linked to for more information.

A: (This addresses the Comment about the format of DATETIME and TIMESTAMP changing.)
There are (based on documentation) two ways that the internal format is changed:

*

*If you dump (eg, via mysqldump) the data (from the old version) and load it on the new server with a newer version, the format change is changed without any hint that it is happening.  This is because of converting from the old internal format to a string, then to the new internal format.

*If you "upgrade in place", then the upgrade process takes the time to rebuild each table that has a datetime or timestamp.  (There may be some option for delaying the format change, but I am not familiar with the details.)
The bottom line is that format change is automatic, though may add time to the upgrade.
The internal structure of an InnoDB tables representation on disk makes it essentially impossible to do anything akin to a byte-by-byte file comparison.  (This statement is valid even when there is no change to an internal data format.)
You can, however, copy all the mysql files from one disk to another, then verify byte-by-byte that the files were still intact.  This is a simple way to create a new Replica.  However, once mysqld touches a table, the simple byte comparison is rendered invalid.


text:
Q: Find this integral $I=\int\frac{x}{(1-3x)^{3/2}(x+1)^{3/2}}dx$ Find the integral

$$I=\int\dfrac{x}{(1-3x)^{3/2}(x+1)^{3/2}}dx$$

My try: $$(1-3x)(x+1)=-3x^2-2x+1=-3(x+1/3)^2+\dfrac{4}{3}$$
Thus
$$I=\int\dfrac{x}{(\frac{4}{3}-3(x+\frac{1}{3})^2)^{3/2}}dx$$

A: Substitute $u=\sqrt{1-3x}$ thus $\mathrm{d}x=-\dfrac{2\sqrt{1-3x}}{3}\,\mathrm{d}u$
$$I={\displaystyle\int}\dfrac{2\left(u^2-1\right)}{\sqrt{3}u^2\left(4-u^2\right)^\frac{3}{2}}\,\mathrm{d}u$$
$$I=\dfrac{2}{\sqrt{3}}{\displaystyle\int}\left(\dfrac{1}{\left(4-u^2\right)^\frac{3}{2}}-\dfrac{1}{u^2\left(4-u^2\right)^\frac{3}{2}}\right)\mathrm{d}u$$
$$I=\dfrac{2}{\sqrt{3}}{\displaystyle\int}\dfrac{1}{\left(4-u^2\right)^\frac{3}{2}}\,\mathrm{d}u-\dfrac{2}{\sqrt{3}}{\displaystyle\int}\dfrac{1}{u^2\left(4-u^2\right)^\frac{3}{2}}\,\mathrm{d}u$$
Now perform trigonometric substitution  $u=2\sin v$ to solve other two integrals
$$I=\dfrac{2}{\sqrt{3}}{\displaystyle\int}\dfrac{2\cos\left(v\right)}{\left(4-4\sin^2\left(v\right)\right)^\frac{3}{2}}\,\mathrm{d}v-\dfrac{2}{\sqrt{3}}{\displaystyle\int}\dfrac{\cos\left(v\right)}{2\sin^2\left(v\right)\left(4-4\sin^2\left(v\right)\right)^\frac{3}{2}}\,\mathrm{d}v$$
$$I=\dfrac{1}{2\sqrt{3}}{\displaystyle\int}\dfrac{1}{\cos^2\left(v\right)}\,\mathrm{d}v-\dfrac{1}{8\sqrt{3}}{\displaystyle\int}\dfrac{1}{\cos^2\left(v\right)\sin^2\left(v\right)}\,\mathrm{d}v$$
can you solve it from here?

A: Hint:
For real calculus, we need $$-1<x<\dfrac13$$
$$\iff-\dfrac23<x+\dfrac13<\dfrac23$$
WLOG $x+\dfrac13=\dfrac23\cos2t$ where $0<2t<\pi,\cos t,\sin t,\sin2t>0$
$\iff3x+1=2\cos2t,3x=2\cos2t-1=4\cos^2t-3$
$3dx=-8\sin t\cos t\ dt$
$1-3x=1-(2\cos2t-1)=2(1-\cos2t)=4\sin^2t\implies(1-3x)^{3/2}=(2\sin t)^3$
$x+1=\dfrac{3x+3}3=\dfrac{2\cos2t-1+3}3=\dfrac{4\cos^2t}3\implies(1+x)^{3/2}=\dfrac{(2\cos t)^3}{3\sqrt3}$
$$I=\int\dfrac{-8\cdot3\sqrt3(4\cos^2t-3)\sin t\cos t\ dt}{3^28^2\sin^3t\cos^3t}dt$$
$$\implies-8\sqrt3I=\int\dfrac{4\cos^2t-3}{\sin^2t\cos^2t}dt=4\int\sec^2t\ dt-12\int\csc^22t\ dt$$
Can you take it from here?

A: By using Euler's 3rd substitution $x = \frac{1-y^2}{3+y^2}$ ($y > 0$,
so $y = \sqrt{\frac{1-3x}{x+1}}$), we have
$(1-3x)(x+1) = \frac{16y^2}{(3+y^2)^2}$,
$\sqrt{(1-3x)(x+1)} = \frac{4y}{3+y^2}$,
$\mathrm{d} x = -\frac{8y}{(3+y^2)^2} \mathrm{d}y$, and hence
\begin{align}
I &= \int \Big(\frac{1}{8} - \frac{1}{8y^2}\Big) \mathrm{d} y\\
&= \frac{1}{8}y + \frac{1}{8y} + C \\
&= \frac{1}{8}\sqrt{\frac{1-3x}{x+1}} + \frac{1}{8}\sqrt{\frac{x+1}{1-3x}} + C\\
&= \frac{1-x}{4\sqrt{(1-3x)(x+1)}} + C.
\end{align}
Euler's 3rd substitution, see: https://en.wikipedia.org/wiki/Euler_substitution

A: Since
$$\dfrac x{(1-3x)(1+x)} = \dfrac14\cdot\dfrac1{1-3x}-\dfrac14\cdot\dfrac1{1+x},$$
then
$$I(x)=\int\dfrac{x\,\mathrm dx}{(1-3x)^{^{^3/_2}}(1+x)^{^{^3/_2}}}
=I_1(x)+I_2(x),\tag1$$
where
$$I_1(x)=\dfrac14\int\dfrac{\mathrm dx}{(1-3x)^{^{^3/_2}}\sqrt{1+x}},\quad
I_2(x) = -\dfrac14\int\dfrac{\mathrm dx}{(1+x)^{^{^3/_2}}\sqrt{1-3x}}.$$
1.
Substitution
$$t=\dfrac1{\sqrt{1-3x}},\quad \mathrm dt=\dfrac32\dfrac{\mathrm dx}{(1-3x)^{^{^3/_2}}},\quad x=\dfrac{t^2-1}{3t^2},$$
allows to get
$$I_1=\dfrac{\sqrt3}6\int\dfrac{t\,\mathrm dt}{\sqrt{4t^2-1}}
=\dfrac{\sqrt3}{24} \sqrt{4t^2-1}+\mathrm{const}
=\dfrac{\sqrt3}{24} \sqrt{\dfrac4{1-3x}-1}+\mathrm{const},$$
$$I_1(x) = \dfrac18\sqrt{\dfrac{1+x}{1-3x}}+\mathrm{const}.\tag2$$
2.
Similarly, substituion
$$t=\dfrac1{\sqrt{1+x}},\quad \mathrm dt=-\dfrac12\dfrac{\mathrm dx}{(1+x)^{^{^3/_2}}},\quad x=\dfrac{1-t^2}{t^2},$$
allows to get
$$I_2 = \dfrac12\int\dfrac{t\,\mathrm dt}{\sqrt{4t^2-3}}
= \dfrac18\sqrt{4t^2-3}+\mathrm{const}
= \dfrac18\sqrt{\dfrac4{1+x}-3}+\mathrm{const},$$
$$I_2(x) = \dfrac18\sqrt{\dfrac{1-3x}{1+x}} + \mathrm{const}.\tag3$$
3.
From $(1)-(3)$ should
$$\color{brown}{\mathbf{I(x) = \dfrac18\sqrt{\dfrac{1+x}{1-3x}} + \dfrac18\sqrt{\dfrac{1-3x}{1+x}} + \mathrm{const}}}.$$


text:
Q: PostgreSQL function or stored procedure that outputs multiple columns? Here is what I ideally want. Imagine that I have a table with the row A.
I want to do:
SELECT A, func(A) FROM table

and for the output to have say 4 columns.
Is there any way to do this? I have seen things on custom types or whatever that let you sort of get a result that would look like

A,(B,C,D)

But it would be really great if I could have that one function return multiple columns without any more finagling.
Is there anything that can do something like this?

A: I agree with bambam's answer but would like to point out that JackPDouglas's more succinct syntax SELECT a, (func(a)).* FROM table1, from my tests, would actually execute the function once for each column returned whereas the CTE expression will only execute the function once. So the CTE expression is preferred if the function takes a long time to execute.

A: If the function func returns only 1 row with 3 values, such as:
CREATE OR REPLACE FUNCTION func
(
    input_val       integer,
    OUT output_val1 integer,
    OUT output_val2 integer,
    OUT output_val3 integer
)
AS $$
BEGIN
  output_val1 := input_val + 1;
  output_val2 := input_val + 2;
  output_val3 := input_val + 3;
END;
$$ LANGUAGE plpgsql;

and you then execute SELECT a, func(a) FROM table1 you'll get:
a       | func
integer | record
========|==========
1       | (2, 3, 4)
2       | (3, 4, 5)
3       | (4, 5, 6)

but, if you execute:
SELECT a, (f).output_val1, (f).output_val2, (f).output_val3
FROM (SELECT a, func(a) AS f FROM table1) AS x

you'll get:
a       | output_val1 | output_val2 | output_val3
integer | integer     | integer     | integer
========|=============|=============|=============
1       | 2           | 3           | 4
2       | 3           | 4           | 5
3       | 4           | 5           | 6

or, using CTE (Common Table Expressions), if you execute:
WITH temp AS (SELECT a, func(a) AS f FROM table1)
SELECT a, (f).output_val1, (f).output_val2, (f).output_val3 FROM temp

you'll also get:
a       | output_val1 | output_val2 | output_val3
integer | integer     | integer     | integer
========|=============|=============|=============
1       | 2           | 3           | 4
2       | 3           | 4           | 5
3       | 4           | 5           | 6

Note: you may also use the following queries to obtain the same results:
SELECT a, (f).*
FROM (SELECT a, func(a) AS f FROM table1) AS x

or
WITH temp AS (SELECT a, func(a) AS f FROM table1)
SELECT a, (f).* FROM temp

A: If the function always returns 3 columns, you can do something like that:
CREATE TYPE sometype AS (b INT, c TEXT, d TEXT);

CREATE OR REPLACE FUNCTION func(a TEXT) RETURNS SETOF sometype AS $$
BEGIN
  RETURN QUERY EXECUTE 'SELECT b, c, d FROM ' || a;
END;
$$ LANGUAGE plpgsql;

SELECT a, (f).b, (f).c, (f).d
FROM (SELECT a, func(a) AS f FROM table) x;

If you can access the table from within a view, maybe you can create a view in some way
CREATE VIEW v AS
SELECT 'tab1' AS a, b, c, d FROM tab1 WHERE 'tab1' IN (SELECT a FROM table)
UNION
SELECT 'tab2' AS a, b, c, d FROM tab2 WHERE 'tab2' IN (SELECT a FROM table)
UNION
SELECT 'tab3' AS a, b, c, d FROM tab3 WHERE 'tab3' IN (SELECT a FROM table);

then it's just a SELECT * FROM v. But again this looks like Inheritance could be used.

A: I think you will want to return a single record, with multiple columns? In that case you can use the return-type RECORD for example. This will allow you to return an anonymous variable with as many columns as you want. You can find more information about all the different variables here:
http://www.postgresql.org/docs/9.0/static/plpgsql-declarations.html
And about return types:
http://www.postgresql.org/docs/9.0/static/xfunc-sql.html#XFUNC-OUTPUT-PARAMETERS
If you want to return multiple records with multiple columns, first check and see if you have to use a stored procedure for this. It might be an option to just use a VIEW (and query it with a WHERE-clause) instead. If that's not a good option, there is the possibility of returning a TABLE from a stored procedure in version 9.0.


text:
Q: Filter Issues by JQL I have list of issues which contain certain set of fields (6 custom fields) these fields can be have values only "A"or "B". the my question is how can I filter those issues if one these field have a value "A". let say for a example these custom fields are
cus_field1,cus_field2,cus_field3,cus_field4,cus_field5,cus_field6 and if one these field have certain value how can I filter those issues?

A: I am not sure, do you mean how to use an 'or' clause? As I understand, a simple "cus_field1=A or cus_field2=A or cus_field3=A or cus_field4=A or cus_field5=A or cus_field6=A" should solve your problem, isn't it?
According to the reference, I couldn't find any possibility to combine different fields, so you have no other choice but specify the A filter value for each custom field...
https://confluence.atlassian.com/jira/searching-for-issues-185729570.html


text:
Q: What is the asymptotic behavior of this product? It is not very difficult to find lower and upper bounds for the product $$\prod_{ k=1}^n \left(1+\frac{1}{\sqrt k}\right)$$
For example one can easily prove that the product is greater than $n$ and less than $2^n$ (of course these bounds can be improved).
My question is: Is it possible to determine the asymptotic behavior of this product?

A: $$\exp\sum_{k=1}^{n}\log\left(1+\frac{1}{\sqrt{k}}\right)=\exp\sum_{k=1}^{n}\left(\frac{1}{\sqrt{k}}-\frac{1}{2k}+O\left(\frac{1}{k^{3/2}}\right)\right) $$
equals
$$ \exp\left[2\sqrt{n}-\frac{1}{2}\log(n)+O(1)\right] $$
hence your product behaves like $\frac{e^{2\sqrt{n}}}{K\sqrt{n}}$ for large values of $n$. Are you interested in a explicit value for $K$? We approximately have $K\approx 3.1$.


text:
Q: PHP CURL, PayPal Redirect Lemme explain what I want to do:

*

*Capture custom info in a form.

*User Submits Form.

*I capture the data in a DB.

*I pass entry ID to PayPal(custom var), and take user to PayPal.

*User puts in info on PayPal and submits payment.

*PayPal sends me IPN.

*I update status of DB entry to paid.

I have all this working except step 4. In the php where i capture the data, I am trying to use curl to POST to the PayPal page... but it doesn't want to redirect as it post the data.
New to CURL, so I am sure I've made a mistake in that area.
This is what I have with $custom just set to a random string instead of DB id:
    $url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
    //$url =
    $cmd = "_s-xclick";
    $custom = "id1234";
    $b_id = "";

    switch($_POST["streamer"]){
        case "mrhyubusa":
            $b_id = "BTS5M8QXSGR3G";
            break;
        default:
            break;
    }

    //set POST variables
    $fields = array(
                'cmd' => urlencode($cmd),
                'hosted_button_id' => urlencode($b_id),
                'custom' => urlencode($custom)
    );

    //url-ify the data for the POST
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

Thanks in advance guys.

A: When using Payments Standard like you are you don't need CURL.  Payments Standard just works with basic HTML forms.  All you need to do is grab the HTML snippet PayPal provides in your button manager and paste it into your page where you want it to show up.
You'll have to add the custom parameter, which does work with hosted buttons as of a couple of months ago when I tested it (it didn't used to work with hosted buttons).
CURL would come into play if you were making calls to the web service API's.  Again, though, with Payments Standard you don't need that.


text:
Q: why we declare data binding adapters inside companion object? I am currently learning Data Binding in android. But I did not find any answer to my question I mentioned above.
Also we annotate it with @JvmStatic but I don't know reason why we use this annotation?
class RecipesRowBinding {

    companion object {

        @BindingAdapter("onRecipeClickListener")
        @JvmStatic
        fun onRecipeClickListener(recipeRowLayout: ConstraintLayout, result: Result) {...}
    }
}

Also my another question is, is databinding a recommended standard? I read that data binding can make app build slower as it generates classes.


text:
Q: Xceed datagrid cell editor disabled for null values I am using an Xceed datagrid to display data retreived from database. I would like to allow users the ability to edit the values that are being displayed on the grid. But it appears that when there is a null value in the underlying datasource, the corresponding cell becomes readonly. How can I resolve this issue?

A: You can explicitly set the CellEditor like this...
<xcdg:Column FieldName="From" Title="From" CellEditor="{DynamicResource dateTimeEditor}" Width="*" >


text:
Q: Unresolved external symbol __iob_func I am getting the
LNK2019 unresolved external symbol __iob_func referenced in function _usb_parse_configuration

after updating to VS 2015 and looking at the Microsoft Breaking Changes i can't find a solution. I've had more external symbol errors but most of the got solved by using the legacy library, this one stays. I have extern "C" defined in a lot of files, changing that gives only way more errors.
Did you guys have a problem with that and how did you solve it? Any help is appreciated


text:
Q: Exception in thread "main" java.sql.SQLException: Missing IN or OUT parameter at index:: 25 What was this error meant When I run the below program it producing the errors can any tell me the solution for this
I need to pass the data to my database using the parameters in method InsTable :
 import java.io.*;
 import java.sql.*;
 import java.util.*;
public class InsertusrProf
{
public static Connection prepareConnection()throws ClassNotFoundException,SQLException
{
    String dcn="oracle.jdbc.driver.OracleDriver";
    String url="jdbc:oracle:thin:@JamesPJ-PC:1521:skypark";
    String usname="system";
    String pass="tiger";
    Class.forName(dcn);
    return DriverManager.getConnection(url,usname,pass);
}
public static void InsTable(String uname,String photo1,String video1,String    music1,String notes1,String messages1,String link,String frd,String cmt,String lik,String     ulik,String shrs,String qst,String answ,String updt,String thms,String wrd,String comm,String grp,String pgs,String ntfcn,String rqst,String tps,String tg)throws ClassNotFoundException,SQLException,FileNotFoundException
{
    StringBuilder sb=new StringBuilder(1024);;
    sb.append("insert into ").append(uname).append("(PHOTO,VIDEO,MUSIC,NOTES,MESSAGES,LINKS,FRIENDS,COMMENTS,LIKES,UNLIKES,SHARES,QSTNS,ANS,UPDATES,THEMS,WORDS,LANGUAGES,RELEGION,PRIVACY,HOBBIES,FAV,QULIFICATION,COMMUNITIES,GRPS,PAGES,NOTIFICATION,REQUESTS,TIPS,CITY,TAG)values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    String stmnt=sb.toString();
    Connection con=prepareConnection();
    PreparedStatement ps=con.prepareStatement(stmnt);
    ps.setString(1,uname);

    File fl=new File(photo1);
    FileInputStream fis=new FileInputStream(fl);
    ps.setBinaryStream(2,fis,(int)fl.length());

    File fl1=new File(music1);
    FileInputStream fis1=new FileInputStream(fl1);
    ps.setBinaryStream(3,fis1,(int)fl1.length());

    File fl2=new File(video1);
    FileInputStream fis2=new FileInputStream(fl2);
    ps.setBinaryStream(4,fis2,(int)fl2.length());

    File fl3=new File(shrs);
    FileInputStream fis3=new FileInputStream(fl3);
    ps.setBinaryStream(12,fis3,(int)fl3.length());

    File fl4=new File(updt);
    FileInputStream fis4=new FileInputStream(fl4);
    ps.setBinaryStream(15,fis4,(int)fl4.length());

    File fl5=new File(notes1);
    FileReader fr=new FileReader(fl5);
    //BufferedReader r=new BufferedReader(notes1.getCharacterStream());
    ps.setCharacterStream(5,fr,(int)fl5.length());

    File fl6=new File(messages1);
    FileReader fr1=new FileReader(fl6);
    ps.setCharacterStream(6,fr1,(int)fl6.length());

    ps.setString(7,link);

    ps.setString(8,frd);

    File fl7=new File(cmt);
    FileReader fr2=new FileReader(fl7);
    ps.setCharacterStream(9,fr2,(int)fl7.length());

    ps.setString(10,lik);

    ps.setString(11,ulik);

    File fl8=new File(qst);
    FileReader fr3=new FileReader(fl8);
    ps.setCharacterStream(13,fr3,(int)fl8.length());

    File fl9=new File(answ);
    FileReader fr4=new FileReader(fl9);
    ps.setCharacterStream(14,fr4,(int)fl9.length());

    ps.setString(16,thms);

    File fl0=new File(wrd);
    FileReader fr5=new FileReader(fl0);
    ps.setCharacterStream(17,fr5,(int)fl0.length());

    ps.setString(18,comm);

    ps.setString(19,grp);

    ps.setString(20,pgs);

    File fls=new File(ntfcn);
    FileReader fr6=new FileReader(fls);
    ps.setCharacterStream(21,fr6,(int)fls.length());

    ps.setString(22,rqst);

    File fls1=new File(tps);
    FileReader fr7=new FileReader(fls1);
    //BufferedReader r=new BufferedReader(tps.getCharacterStream());
    ps.setCharacterStream(23,fr7,(int)fls1.length());

    ps.setString(24,tg);

    int i=ps.executeUpdate();

    System.out.println("<<<<<<<Record Inserted Successfully>>>>>>> Count :"+i);

    con.close();
}
public static void main(String args[])throws Exception
{
    String uname="james";
    String photo1="C:/Users/James P J/Documents/javaprog/img1.jpg";
    String video1="C:/Users/James P J/Documents/javaprog/How To Make 3D Text In Photoshop (ADOBE PHOTOSHOP CS6 TUTORIAL).flv";
    String music1="C:/Users/James P J/Documents/javaprog/Lelepadi.mp3";
    String notes1="C:/Users/James P J/Documents/javaprog/test.java";
    String messages1="C:/Users/James P J/Documents/javaprog/test.java";
    String link="aaaaa";
    String frd="bbbb";
    String cmt="C:/Users/James P J/Documents/javaprog/test.java";
    String lik="asadssfds";
    String ulik="zxzxxzcx";
    String shrs="C:/Users/James P J/Documents/javaprog/img1.jpg";
    String qst="C:/Users/James P J/Documents/javaprog/test.java";
    String answ="C:/Users/James P J/Documents/javaprog/test.java";
    String updt="C:/Users/James P J/Documents/javaprog/img1.jpg";
    String thms="bgfvdft";
    String wrd="C:/Users/James P J/Documents/javaprog/test.java";
    String langs="erdgdfgf";
    String rlgn="bngfhgfh";
    String prvc="zxcsdw";
    String hbs="bgnbvc";
    String fvt="tgfhfghjfgh";
    String qlf="mklkopi";
    String comm="mbnfchgeshgw";
    String grp="bgyeadb";
    String pgs="hfhfj";
    String ntfcn="C:/Users/James P J/Documents/javaprog/test.java";
    String rqst="ghfhgfh";
    String tps="C:/Users/James P J/Documents/javaprog/test.java";
    String cty="jjkhgjghjk";
    String tg="qwewr";
    InsTable(uname,photo1,video1,music1,notes1,messages1,link,frd,cmt,lik,ulik,shrs,qst,answ,updt,thms,wrd,comm,grp,pgs,ntfcn,rqst,tps,tg);
}
  }

I tried to solve this error by making the mode as IN OUT in procedure what i created
But the following error was not solved if any solution find please answer for it.
The Error was :
 Exception in thread "main" java.sql.SQLException: Missing IN or OUT parameter at
 index:: 25
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
:146)
    at oracle.jdbc.driver.OraclePreparedStatement.processCompletedBindRow(Or
 aclePreparedStatement.java:1681)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePrep
 aredStatement.java:3280)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePrepar
 edStatement.java:3368)
    at skypark.InsertusrProf.InsTable(InsertusrProf.java:99)
    at skypark.InsertusrProf.main(InsertusrProf.java:138)
 Press any key to continue . . .

Please answer this if you know the solution....
Thanks in advance...

A: java.sql.SQLException: Missing IN or OUT parameter at
 index:: 25

Means, your ps.set.... not matching with number of ?
You have total 30 ? but only 24 ps.Set.... statements.


text:
Q: Can data types saved in PROGMEM be changed later on in the program? Hello i am making a game on an Arduino but i need to store 2 global variables that keep track of the score currScor and hiScor both of type uint32_t and to save ram space i marked them as uint32_t currScor PROGMEM = 0; once the game starts the score would begin incrementing but the compiler says i cannot assign to a constant variable. is there a way i can add to this variable that is stored in flash? should i consider using EEPROM although i am worried that too many writes will burn out that memory type.

A: The Arduino has 4 types of memory:

*

*Flash

*EEPROM

*SRAM

*CPU Registers

Manipulating Flash and EEPROM is not possible by simple assignments. For manipulation of EEPORM there exist well known libraries. Manipulation of Flash / Progmem is also possible from within a program. The technique is described in the ATMEL datasheet AVR105: Power Efficient High Endurance Parameter Storage in Flash Memory. However I am not aware of any open source library which supports this.
If you want to preserve RAM this is most probably not the way to go. Instead you should put strings and other large and constant stuff to progmem.

A: For the score, you should use RAM instead since it's constantly updated and no need to retain it's value beyond single game cycle.
For hiscore, you can write it to EEPROM once the game is over. According to datasheet, it can be written at least 100,000 times, so if you play 100 times a day, 365 days a year, it won't worn out for almost 3 years. After that, simply change EEPROM location to another address. If you use Arduino Uno (with 1 Kb EEPROM), you have 32 different location to store an uint32_t data. 32 x 3 years = 96 years ;)

A: Your intuition is correct, in that you will not be able to change the value that is stored in Program Memory space (aka Flash/ROM). If you are concerned about burning out the EEPROM. Have it only update periodically. However, you will still need to have RAM to buffer it.
I highly recommend conserving RAM else where.
See the following examples library to measure and conserve RAM


text:
Q: Query to find records with more than one date I'm trying to build a query for a MS SQL database that will find records with more than one year but not the records with only one.
Lets say I have a car dealership and I have 1 Chevy from 2015 and 2 from 2017 then I would want to find Chevy 2015 1 and chevy 2017 2 but if I have a three Fords from 2018 and only 2018 then I don't want that at all.
I have tweeked with groups and joins but I don't get any where.  So I need Select from table something.  I'm leaning toward a pivot table but not sure what to do.  Thanks for the help
MyTable Contents
              Model  year   count
              Chevy 2012    1
              Chevy 2012    1
              Chevy 2015    1
              Ford  2018    1
              Ford  2018    1
              Ford  2018    1
              Buick 2017    1
              Lexus 2017    1
              Lexus 2015    1

Desired Result Set
             Chevy  2012    2
             Chevy  2015    1
             Lexus 2017    1
             Lexus 2015    1

Because it has 2 different years for the model

A: The below query should help you. Need not hardcode model values.
Select T.Model,T.[year] ,count(T.[year])
from T
join (select distinct * from T) S on T.model = S.model and T.year!=S.year
group by T.Model,T.[year]

A: You need to use SUM function and group by on subquery,Because there might be Multiple count on count column. then join itself and distinct to exclude duplicate data.
Select distinct t1.*
from (
  SELECT Model,[year] ,sum([count]) totle
  FROM T
  group by Model,[year]
) t1
inner join T t2 on t1.Model = t2.Model and t1.[year] !=t2.[year]

sqlfiddle:http://sqlfiddle.com/#!18/e8756/55
Note:[table],[year] are keyword in sql avoid naming it as column name


text:
Q: Acceder a las variables de la actividad desde su fragmento ACTIVIDAD
Tengo en la actividad con las siguientes variables globales:
public String variable="";
public static final String KEYVARIABLE= "KEY";

En el onCreate modifico el valor de "variable":
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Intent intent=getIntent();
    variable=intent.getStringExtra(KEYVARIABLE);
}

En el onSaveInstanceState añado al bundle los datos que recojo en el onCreate
@Override
public void onSaveInstanceState(Bundle bd) {

    bd.putString(KEYVARIABLE, variable);

}

FRAGMENTO
En el fragmento tengo como globales:
public String variable="";
public static final String KEYVARIABLE= "KEY";

En el onCreate:
 variable=savedInstanceState.getString(KEYVARIABLE);

Esto no me funciona, ya que me dice que "variable" es vacío. ¿Qué puede estar pasando? ¿Cómo podría acceder a las variables globales de la actividad desde su fragmento?

A: Si necesitas pasar al Fragment variables en el método onCreate, te recomiendo que lo crees programáticamente.
Lo que tienes que hacer entonces es pasarle las variables al crearlo, guardarlas dentro de un Bundle pasarsela como argumento al Fragment y recuperarlas cuando las necesites.
Te quedaría algo así:
Activity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent intent=getIntent();
        variable=intent.getStringExtra(KEYVARIABLE);
        TuFragment fragment = TuFragment.newInstance(variable);
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, fragment, TAG_FRAGMENT).commit();
    }

Fragment
    public static TuFragment newInstance(String variable) {
        TuFragment fragment = new TuFragment();
        Bundle args = new Bundle();
        args.putString(KEYVARIABLE, variable);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle arg = getArguments();
        if (arg != null)
            variable = arg.getString(KEYVARIABLE);
    }

El método onSaveInstanceState y el argumento savedInstanceState del onCreate no son para el uso que tu quieres darle, es para guardar y recuperar las variables que necesites cuando el Activity o el Fragment tienen que reconstruirse.
Un saludo.


text:
Q: SFML Error - isOpen non-standard syntax; So I am getting this error: game.cpp(15): error C3867: 'sf::Window::isOpen': non-standard syntax; use '&' to create a pointer to member
Game.cpp
#include "Game.h"
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>

Game::Game() :
    window(sf::VideoMode(200, 200), "SFML works!"),
    player()
{
    player.setRadius(40.f);
    player.setPosition(100.f, 100.f);
    player.setFillColor(sf::Color::Cyan);
}

void Game::run() {
    while (window.isOpen) {
        processEvents();
        update();
        render();
    }
}

void Game::processEvents()
{
    sf::Event event;
    while (window.pollEvent(event)) {
        if (event.type == sf::Event::Closed)
            window.close();
    }
}

void Game::update() {

}

void Game::render() {
    window.clear();
    window.draw(player);
    window.display();
}

And this is my game.h
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>

class Game {
public:
    Game();
    void run();
    sf::RenderWindow window;
    sf::CircleShape  player;
private:
    void processEvents();
    void update();
    void render();
};

I have no idea what I am doing wrong, I looked trough other stackoverflow answers to the same error but they are all general and they do not help me fix this error because its from the SFML library. If someone know how to fix it please help me :)

A: Here while (window.isOpen) you are testing that the member function pointer 'window.isOpen' is not nullptr. What you intended was to call the function while (window.isOpen()).


text:
Q: when dialog open and after close dialog when focus on textFormField widget rebuild unnecessarily and user doesn't able to put text in this When I click on the update profile button I want to show a dialog if no changes are found, but when I close this and try to change the username or email again the entire widget rebuilds twice as soon as I focus on the TextFormField.
import 'dart:developer';

import 'package:chatappwithfirebase/Screens/profilescreen.dart';
import 'package:chatappwithfirebase/api/customtranscation.dart';
import 'package:chatappwithfirebase/widgets/imagepick.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../Screens/mainscreen.dart';
import '../utils/utils.dart';

class EditProfile extends StatefulWidget {
   EditProfile({Key? key,required this.initialValues}) : super(key: key);

   final Map<String,String> initialValues;

  @override
  State<EditProfile> createState() => _EditProfileState();
}

class _EditProfileState extends State<EditProfile> {
    final _fromKey = GlobalKey<FormState>();
   final firebase =FirebaseFirestore.instance.collection('users');

   final firebaseAuth =FirebaseAuth.instance;

  TextEditingController? txtEmail;
  TextEditingController? txtUsername;
  var updatedProfileImageLink;
  File? selectedImage;

  @override
  void initState() {
    txtEmail =TextEditingController(text: widget.initialValues['emailAddress']);
    txtUsername =TextEditingController(text: widget.initialValues['username']);
    super.initState();
  }

   void getImage(ImageSource imageSource)async{
      ImagePicker picker =ImagePicker();
      Navigator.of(context).pop();
      var getImage= await picker.pickImage(source: imageSource);
      selectedImage = await File(getImage!.path);
      print(selectedImage!.path);
    }

   void updateProfile()async{
    FocusScope.of(context).unfocus();
    if(
    widget.initialValues['imageUrl'] != updatedProfileImageLink && selectedImage != null ||
          widget.initialValues['emailAddress'] != txtEmail!.text ||
          widget.initialValues['username'] != txtUsername!.text)
     {
            if (widget.initialValues['imageUrl'] != updatedProfileImageLink && selectedImage != null)  {
              showDialog(
                  barrierDismissible: false,
                  context: context, builder: (context){
                return AlertDialog(
                  content: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                          CircularProgressIndicator(),
                          SizedBox(width: 5,),
                          Text('Uploading...')
                      ],
                  ),
                );
              }).then((value) => setState((){}));
              final storage =FirebaseStorage.instance.ref().child('User_image').child(firebaseAuth.currentUser!.uid +'.jpg');
              await storage.putFile(selectedImage!);
              updatedProfileImageLink = await storage.getDownloadURL();
              await firebase.doc(firebaseAuth.currentUser!.uid).update({
                'imageUrl': updatedProfileImageLink}).then((value) => Navigator.of(context).pop());
              }
            if (widget.initialValues['emailAddress'] != txtEmail!.text) {
              final userdata = await firebase.doc(firebaseAuth.currentUser!.uid).get();
              await firebaseAuth.signInWithEmailAndPassword(
                      email: userdata['email'], password: userdata['password']);
              await FirebaseAuth.instance.currentUser!.updateEmail(txtEmail!.text);
              await firebase.doc(firebaseAuth.currentUser!.uid).update({
                'email': txtEmail!.text}).then((value) => showDialog(
                  context: context,
                  builder: (context){
                    return CupertinoAlertDialog(
                      title: CircleAvatar(
                          backgroundColor: Colors.green,
                          child: Icon(Icons.done,color: Colors.white,size: 30,)),
                      content: Text('Email Address Updated'),
                      actions: [
                        CupertinoDialogAction(
                            onPressed: (){
                              widget.initialValues['emailAddress'] =txtUsername!.text;
                              Navigator.of(context).pop();
                            },
                            child: Text('Ok')
                        )
                      ],
                    );
                  }));
               }
            if (widget.initialValues['username'] != txtUsername!.text) {
              await firebase.doc(firebaseAuth.currentUser!.uid).update({
                'username': txtUsername!.text}).then((value) => showDialog(
                  context: context,
                  builder: (context){
                    return CupertinoAlertDialog(
                      title: CircleAvatar(
                          backgroundColor: Colors.green,
                          child: Icon(Icons.done,color: Colors.white,size: 30,)),
                      content: Text('Username Updated'),
                      actions: [
                        CupertinoDialogAction(
                            onPressed: (){
                              widget.initialValues['username'] =txtUsername!.text;
                              Navigator.of(context).pop();
                            },
                            child: Text('ok')
                        ),
                      ],
                    );
                  })
              );
            }
         }
    else{
        showDialog(
          context: context,
          builder: (BuildContext context) => AlertDialog(
            title: const Text('Alert'),
            content: const Text('Changes Not Found'),
            // actions: <CupertinoDialogAction>[
            //   CupertinoDialogAction(
            //     //isDefaultAction: true,
            //     onPressed: () {
            //       Navigator.pop(context);
            //     },
            //     child: const Text('ok'),
            //   ),
            // ],
          ),
        );
    }
   }

   void _showImagePickOptions(context){
     showModalBottomSheet(
         shape: const RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft :Radius.circular(20),topRight:Radius.circular(20) )),
         context: context,
         builder: (context){
           return Padding(
             padding: const EdgeInsets.all(20.0),
             child: Column(
               mainAxisSize: MainAxisSize.min,
               children:  [
                 ListTile(
                   onTap:() => getImage(ImageSource.camera),
                   leading: const Icon(Icons.camera_enhance,color: Colors.pink,),
                   title: const Text('Capture Image',style: TextStyle(color: Colors.grey),),
                 ),
                 ListTile(
                     onTap:() => getImage(ImageSource.gallery),
                     leading: const Icon(Icons.image_sharp,color: Colors.purple,),
                     title: const Text('Select Image',style: TextStyle(color: Colors.grey),)
                 )
               ],
             ),
           );
         });
       }

   @override
  Widget build(BuildContext context) {
    log('loaded');
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
        title: Text('Edit Profile',style: TextStyle(color: Colors.black),),
        leading: IconButton(onPressed: (){
          Navigator.of(context).pop();
        },icon: Icon(CupertinoIcons.back,color: iconColor,),),
        actions: [
          const Icon(Icons.more_vert,color: Colors.black,)
        ],
      ),
      body: FutureBuilder(
        future: firebase.doc(FirebaseAuth.instance.currentUser!.uid).get(),
          builder: (context,userdata){
          if(userdata.connectionState ==ConnectionState.waiting){
            return Center(child: CircularProgressIndicator(color: accentColor,));
          }
            return Padding(
              padding: EdgeInsets.all(20),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Padding(
                      padding: EdgeInsets.all(20),
                      child: Stack(
                          alignment: Alignment.bottomRight,
                          children: [
                            CircleAvatar(
                              radius: 60,
                              backgroundImage:updatedProfileImageLink == null ? NetworkImage(widget.initialValues['imageUrl']!) :
                              NetworkImage(updatedProfileImageLink)
                            ),
                            CircleAvatar(
                              backgroundColor: accentColor,
                              child: IconButton(onPressed:()=> _showImagePickOptions(context),icon: Icon(Icons.camera_enhance,color: Colors.white,
                                ),
                              ),
                            )
                          ]
                      ),
                    ),
                    SizedBox(height:  MediaQuery.of(context).size.height * 0.04 ,),
                     Form(
                         key: _fromKey,
                         child: Column(
                          children: [
                              TextFormField(
                                controller: txtEmail,
                                decoration: InputDecoration(
                                  prefixIcon: Icon(Icons.email),
                                  label: Text('Email Address'),
                                  focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: accentColor)),
                                 enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: iconColor))
                                ),
                              ),
                         SizedBox(height: MediaQuery.of(context).size.height * 0.02,),
                         TextFormField(
                                controller: txtUsername,
                                decoration: InputDecoration(
                                labelStyle: TextStyle(fontFamily: 'Roboto'),
                                prefixIcon: Icon(Icons.supervised_user_circle_rounded),
                                label: Text('Username'),
                                focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: accentColor)),
                                enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: iconColor))
                            ),
                         ),
                        ],
                     )),
                    SizedBox(height:  MediaQuery.of(context).size.height * 0.03,),
                    ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: accentColor,
                          fixedSize: Size(200, 50)
                        ),
                        onPressed: updateProfile,
                      child: Text('Update Profile'),),
                  ],
                ),
              ),
            );

      }),
    );
  }
}

It works fine if I don't open a dialog, but when I do this problem shows up again.


text:
Q: SQL COALESCE adding leading character I am trying to build a concatenated string (a version number) based off of rows in a temp table. When trying to run it as a standalone script, I am having no issues, but when it is executed as part of a stored procedure, I am having issues.
Here is what I am doing: I have a temp table with the following structure:

    ElementId     |Element
    ---------------------
    1             |2
    2             |0
    3             |1
    4             |4

I am using the following command to concatenate the values:
declare @nNewVersion        VARCHAR(50)

SELECT @nNewVersion = COALESCE(@nNewVersion + '.' ,'') + Element
FROM #TEMP_VERSION
ORDER BY ElementID

When I run it by itself, I get
2.0.1.4

However, when it is run through the stored procedure, I get the following:
.2.0.1.4

What could be causing that extra "." to be applied to the beginning of the string?
Edit: Actual code snippet from SP - in this case, release version would be 2.0.1.3
DECLARE @nCurrentVersion    VARCHAR(50),
        @nNewVersion        VARCHAR(50)

SELECT TOP 1 @nCurrentVersion = ReleaseVersion
FROM ReleaseDetail
ORDER BY ReleaseDetailID Desc

select *
into #TEMP_VERSION
from dbo.ufn_SplitString(@nCurrentVersion, '.', 0)

UPDATE #TEMP_VERSION
SET Element = CONVERT(VARCHAR(50), CAST(Element as int) + 1)
WHERE ElementID = 4

SELECT @nNewVersion = COALESCE(@nNewVersion + '.' ,'') + Element
FROM #TEMP_VERSION
ORDER BY ElementID

@nNewVersion is then used in an insert statement


text:
Q: Get a post_id where meta_value equals something in a serialized meta_value field I'm storing CPT products' post IDs into CPT companies' post meta (meta_key = prefix_products). As a company can have multiple products, so I'm storing them into a PHP serialized array value.
s:48:"a:3:{i:0;s:3:"334";i:1;s:3:"333";i:2;s:3:"331";}";

Where 334, 333, 331 are three post_ids of post type products.
I need to get the post_id of the CPT companies where the product id (post_id of CTP products) is equal to 331 (dynamic - can be any value). It should compare with meta_value of the meta_key prefix_products.
I can get post_id using a meta_value, but I'm stuck where the data is stored as serialized. :(
What I did so far, can't get to the solution:
function get_company_of_the_product( $product_id ) {
    global $project_prefix;
    $prod_meta_key = $project_prefix .'products';

    $companies = get_posts( array(
            'post_type'     => 'companies',
            'post_status'   => 'publish',
            'meta_key'      => $prod_meta_key
        ) );
    $products_array = array();
    foreach ( $companies as $company ) {
        $products = get_post_meta( $company->ID, $prod_meta_key, true );
        $products_array[$company->ID] = unserialize( $products );
        //if( in_array( $product_id, $products_array ) ) return $company->ID; //I know it's wrong
    }

    var_dump($products_array);
}

Is this the way, or am I missing something seriously easy? How can I solve the riddle?

A: It's not possible, you have to store that value separately, and then you'll be able to use it.

A: I would strongly suggest to separate the products and not to put them all into one array. Or even to create a taxonomy companies, but this is more up to the while design and maybe a bad idea. Nevertheless this is a nice question to solve, so let's play.
So, the 'prefix_products' meta key is always an array of products. Now you need all companies, which sell a product with a certain ID.
This should do the trick:
function get_all_companies_selling( $product_id ){
    global $wpdb;
    $sql = "select post_id from " . $wpdb->prefix . "postmeta where
        meta_key = 'prefix_products' &&
        meta_value like '%%%s%%'";

    $product_id = 's:' . strlen( $product_id ) . ':"' . (int) $product_id . '";';
    $sql = $wpdb->prepare( $sql, $product_id );
    $res = $wpdb->get_results( $sql );

    return $res;
}

get_all_companies_selling( 331  );

A: This is very possible though possibly slow. It's essentially a reverse relationship search and is common with Advanced Custom Fields or any other custom field used for relationships.
The following will get not just the IDs, it returns an array of posts object via WP_Query.
$some_product_id = '123';
$args= array(
  'post_type' => 'companies',  // only search postmeta of these cpts
  'posts_per_page' => 5,  // limit or not depending on your use
  'orderby' => 'date',  // use whatever order you like
  'meta_query' => array(
    array(
    'key' => 'prefix_products', // name of custom field
    'value' => '"' . $some_product_id . '"', // matches exactly "123" not just 123.
    'compare' => 'LIKE'
  )
);

$the_related_companies = new WP_Query( $args );

if( $the_related_companies->have_posts() ) :
  <div class="container">
  while( $the_related_companies->have_posts() ) :
    [do stuff with your posts]
  endwhile;
  </div>
endif;

(Excuse my PHP, I've been working in Blade a lot and it's hard to go back)


text:
Q: SQL DB2 store query result into variable Usind a DB2 tables:
This is what is done manually in a table
select app_id from table_app where APP_NAME='App_Temp';

gets me an ID, say it's 234
I copy than and do:
select * form table_roles where role_app_id=234;

gets me a row , which is my desired end result.
Is there a way save the result of the first one into a variable and do the second query without the manual step in between using local variables?
I know, you can query out the information with a very simple join between two tables, but I'd like to know, how it works with variables. Is there a way?

A: Just can just plug it in:
select *
from table_roles
where role_app_id = (select app_id from table_app where APP_NAME = 'App_Temp');

If there can be more than one match, use in instead of =.
You can also phrase this as a join:
select r.*
from table_roles r join
     table_app
     on r.role_app_id = a.app_id and APP_NAME = 'App_Temp';

However, this might return duplicates, if two apps have the same name.  In that case, use select distinct:
select distinct r.*
from table_roles r join
     table_app
     on r.role_app_id = a.app_id and APP_NAME = 'App_Temp';


text:
Q: Bind DataGrid Columns to list I'm developing a WPF app based on MVVM. I want to bind a list of strings to column header ie., if the list contains "abc", "xyz", "pqr", then my DataGrid should have three columns with header abc, xyz, pqr. Here is my class to which I am binding the datagrid. The rows are stored in ObservableCollection<List<string>> where each element of ObservableCollection is a List of string which forms the cells of the rows.
public class Resource
{
    private ObservableCollection<string> columns;
    public ObservableCollection<string> Columns
    {
        get
        {
            return columns;
        }
        set
        {
            columns = value;
        }

    }

    private ObservableCollection<List<string>> row;
    public ObservableCollection<List<string>> Row
    {
        get
        {
            return row;
        }
        set
        {
            row = value;
        }
    }

    public Resource()
    {
        List<string> a = new List<string>();
        a.Add("1");
        a.Add("2");
        List<string> b = new List<string>();
        b.Add("11");
        b.Add("21");
        Row = new ObservableCollection<List<string>>();
        Row.Add(a);
        Row.Add(b);

        Columns = new ObservableCollection<string>();
        Columns.Add("Hello");
        Columns.Add("World");
    }
}

I have searched Internet a lot but couldn't find anything with a working example. I really need to bind DataGrid by this method only.

A: You can use the DataGrid in one of two ways :
1) Bind the DataGrid's ItemsSource to a Collection of elements which Expose 3 properties abc , xyz , pqr.
CS :
    public List<MyDataItem> DataItems
    {
        get
        {
            List<MyDataItem> items = new List<MyDataItem>(5);

            for (int i = 0; i < 5; i++)
            {
                items.Add(new MyDataItem { abc = abc[i], qrt = qrt[i], xyz = xyz[i] });
            }

            return items;
        }
    }

    int[] abc = new int[5] { 1, 2, 3, 4, 5 };
    int[] qrt = new int[5] { 6,7,8,9,10 };
    int[] xyz = new int[5] { 11,12,13,14,15};

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

}

public class MyDataItem
{
    public int abc { get; set; }
    public int qrt { get; set; }
    public int xyz { get; set; }
}

XAML :
 <DataGrid ItemsSource="{Binding DataItems}" />

2) Create a DataTable object and Bind it to your ItemsSource.
 public DataTable DataTable
    {
        get
        {
            DataTable table = new DataTable();

            table.Columns.Add("abc");
            table.Columns.Add("qrt");
            table.Columns.Add("xyz");

            table.Rows.Add(1, 6, 11);
            table.Rows.Add(2, 7, 12);
            table.Rows.Add(3, 8, 13);
            table.Rows.Add(4, 9, 14);
            table.Rows.Add(5, 10, 15);

            return table;
        }
    }


text:
Q: laravel : redirect to admin when logged in user is admin using the Auth scaffold I'm trying to build a web app using laravel for the backend! I used the php artisan make:auth command to generate the basic login logic and views. Now I'm trying to redirect users according to the admin field in the users table in the database. The problem is this : it think i don't get the right values from the db so the redirect never works...
here is the routes.php
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/register', function () {
    return redirect('/step1');
});
route::get('/dashboard', function () {
    return view('admin.dashboard');
});
// after login --> else "welcome"
Route::get('/home', 'HomeController@index');
// register user + agency
Route::get('/step1', 'AgencyController@showStep1');
Route::post('/step1', 'Auth\AuthController@register');
// complete registration step 2 --> 9
Route::get('/step{stepId}', ['middleware' => 'auth', 'uses' => 'AgencyController@show']);
Route::post('/step{stepId}', 'AgencyController@store');});

Here is the code for the redirect (in AuthController.php)
<?php

namespace App\Http\Controllers\Auth;

use App\Agency;
use App\Http\Controllers\Controller;
use App\User;
use Auth;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Validator;

class AuthController extends Controller {
/*
        |-------------------------------------------------------------------             -------
        | Registration & Login Controller
        |--------------------------------------------------------------------------
        |
        | This controller handles the registration of new users, as well as the
        | authentication of existing users. By default, this controller uses
        | a simple trait to add these behaviors. Why don't you explore it?
        |
*/

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

/**
 * Where to redirect users after login / registration.
 *
 * @var string
 */
protected $redirectTo = '/';

/**
 * Create a new authentication controller instance.
 *
 * @return void
 */
public function __construct() {
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}

public function login() {
    if (Auth::check()) {

        if (Auth::User()->admin != '1') {

            return redirect('/dashboard');
        } else {
            return redirect('/step1');
        }
    } else {return 'doesnt work :(';}
}

when i run this and login i always get the 'doesnt work' text.
NOTE: the Auth command generated routes :
$this->get('login', 'Auth\AuthController@showLoginForm');
$this->post('login', 'Auth\AuthController@login');
$this->get('logout', 'Auth\AuthController@logout');

// Registration Routes...
$this->get('register', 'Auth\AuthController@showRegistrationForm');
$this->post('register', 'Auth\AuthController@register');

thanks in advance !

A: Are you using laravel 4.2?
It seems like you're login manually, if you want to login a user,
you shoule
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
    if(Auth::User()->admin != 1){
        #your logic
    }
    return Redirect::intended('dashboard');
}


text:
Q: Issue while using webservice to call some java application method which is using resource file Issue while using webservice to call some java application method which is using resource file
I have created one java application which contains following directory structure in my src folder of java..
Src/
  Transcriber.java
  config.xml
  digits.gram
  transcriber.manifest

I have successfully created web-service of this java application with .aar file and putting into axis2 service folder
I am packaging this whole in Transcriber.aar file with the following structure
Transcriber\edu\cmu\sphinx\demo\transcriber

and in that all 4 file above I listed.
I have two method in above Transcriber.java class.. 1st method is just processing without any of other file use like (e.g. config.xml,digits.gram and transcriber.manifest). and its working fine and I can call easily that method from android.
but my second method uses the other files also(e.g. config.xml,digits.gram and transcriber.manifest) to process some logic I want.
But some how I'm getting error when I call the second method and its give me error while I'm calling this 2nd method from android device .
My Error is as follows:
  at java.lang.Thread.run(Thread.java:662)
Caused by: Property exception component:'jsgfGrammar' property:'grammarLocation'
 - Can't locate resource:/edu/cmu/sphinx/demo/transcriber
edu.cmu.sphinx.util.props.InternalConfigurationException: Can't locate resource:
/edu/cmu/sphinx/demo/transcriber

its give me error that some how it cant locate the grammar file digits.gram which is i use to add via the config.xml file with this code in config.xml
<component name="jsgfGrammar" type="edu.cmu.sphinx.jsgf.JSGFGrammar">
        <property name="dictionary" value="dictionary"/>
        <property name="grammarLocation"
             value="resource:/edu/cmu/sphinx/demo/transcriber"/>
        <property name="grammarName" value="digits"/>
    <property name="logMath" value="logMath"/>
    </component>

Why I'm Having this kind of error?enter code here
My CODE WHERE I HAVE FIRST GET THE CONFIG.XML AND THEN CONFIG.XML GET ANOTHER RESOURCE FILE....its successfully finds the config.xml but then the code in config.xml cant locate other resource file
package edu.cmu.sphinx.demo.transcriber;

import edu.cmu.sphinx.frontend.util.AudioFileDataSource;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/** A simple example that shows how to transcribe a continuous audio file that has multiple utterances in it. */
public class TranscribeSimpleGrammar {

        private static final String PATH = "file:///D:\\Sound\\";

        @SuppressWarnings({ "null", "null" })
        public String recognize_wave(String wavePath) throws MalformedURLException{

              URL audioURL;

              //  if (args.length > 0) {
                //    audioURL = new File(args[0]).toURI().toURL();
              //  } else {
                    //audioURL = TranscribeSimpleGrammar.class.getResource("hello.wav");
                        //audioURL = new URL(PATH + "turn-on-light-kitchen-male.wav");
                        //audioURL = new URL(PATH + "turn-down-tv-volume-female.wav");
                       // audioURL = new URL(PATH + wavePath);
              audioURL = new URL(wavePath);
              //audioURL = new URL(PATH + "turn-down-dining-room-music-player-volume-male.wav");

               // }

                URL configURL = TranscribeSimpleGrammar.class.getResource("config.xml");

                ConfigurationManager cm = new ConfigurationManager(configURL);
                Recognizer recognizer = (Recognizer) cm.lookup("recognizer");

                /* allocate the resource necessary for the recognizer */
                recognizer.allocate();

                // configure the audio input for the recognizer
                AudioFileDataSource dataSource = (AudioFileDataSource) cm.lookup("audioFileDataSource");
                dataSource.setAudioFile(audioURL, null);

                // Loop until last utterance in the audio file has been decoded, in which case the recognizer will return null.
                Result result;
                while ((result = recognizer.recognize())!= null) {

                        String resultText = result.getBestResultNoFiller();
                        System.out.println(resultText);
                }

            return result.getBestResultNoFiller();
        }

        public String get_wav_byte(byte[] wavbite,String path){

            String result1="null";

            try
            {
                File dstFile = new File(path);
                FileOutputStream out = new FileOutputStream(dstFile);
                out.write(wavbite, 0, wavbite.length);

                out.close();

            }
            catch (IOException e)
            {
              System.out.println("IOException : " + e);
            }

            try {
                result1=recognize_wave(path);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         return result1;

     }

}

A: Have you ever tried to change
<property name="grammarLocation" value="resource:/edu/cmu/sphinx/demo/transcriber"/>

to
<property name="grammarLocation" value="resource:edu/cmu/sphinx/demo/transcriber"/>

(meaning just removing the leading slash before edu)?
Class.getResource() and ClassLoader.getResource() do interpret the provided name differently: while Class.getResource( "/edu/cmu/sphinx/demo/transcriber/transcriber.manifest" ) would find the resource, you have to use ClassLoader.getResource() with the argument "edu/cmu/sphinx/demo/transcriber/transcriber.manifest" to find the same resource. As you do not know which method is used by the library code you call to load the other resources, you should give it a try.


text:
Q: How to refactor these variables so they are present in the entire class component? (React) This is the code I have right now:
class QuoteDisplay extends React.Component {

  tweetOut() {
    const quote = this.props.quote;
    const author = this.props.author;
    window.open("https://twitter.com/intent/tweet?text=" + quote + ' - ' + author);
  }

  render(){
    const quote = this.props.quote;
    const author = this.props.author;
    const handleGetQuote = this.props.handleGetQuote;
    return (

        {quote}
        -{author}

        <button
          className='btn btn-primary newQuote'
          onClick={handleGetQuote}>
          New Quote
        </button>
        <button
          className='btn btn-primary tweet'
          onClick={this.tweetOut.bind(this)}
          >
          Tweet Out
        </button>

    )
  }
}

As you can see, I repeat the snippet of code twice - once in tweetOut() and once in render():
const quote = this.props.quote;
const author = this.props.author;

Is there a way to refactor this code so I don't have to repeat myself? I tried declaring it at the beginning of the class component. Even creating a constructor for it, but those methods don't seem to work.

A: This values are necessary in function and in render as well, so I suggest you to use ES6 destructuring and do:
tweetOut() {
    const { quote, author } = this.props;
    window.open("https://twitter.com/intent/tweet?text=" + quote + ' - ' + author);
  }

the same way for code in render():
const {quote, author, handleGetQuote } = this.props;


text:
Q: Understanding jpa locks vs transaction isolation levels I'm trying to understand the relationship between this concepts. Does the jpa locks is the way to provide/call transaction isolation level in DB from java? Or is it separated mechanisms, so what is the difference (their purposes)?

A: Locking means, that you prevent entities from being updated by multiple users at the same time.
There are two different types of lock mechanisms. In pessimistic locking scenarios, before performing an update, the rows in the table must be locked by the user and no other users will be able to perform an update of the target entities. After the row was updated, the table must be unlocked, so that other users can also modify the target records. Another option is using optimistic locking. In such implementations each entity has a version column (in JPA @Version can be used). If the entity was updated by a user, it's value or timestamp is also updated. If another user performs an update with a entity, that has an outdated value, an OptimisticLockException is thrown and the user or the application has to fetch the new entity and merge the changes.
This functionality is needed to prevent entities from lost updates, where the last commit would override all other changes.
Transaction Isolation Levels are responsible for the consistency of database reads. For example if "READ UNCOMMITTED" is used, you can see changes, that a database is updating, before the transaction has already finished. That means, if an error occurred and the transaction was rolled back, another user would have fetched changes, that were never stored in the database. "READ COMMITTED" will deliver only committed changes.
There's no 'perfect' isolation level. The 'correct' value of the Transaction Isolation Level depends on the use case in your application. For example the JIRA Tempo Plugin for time tracking marks not committed records with a red color, to show that the data is pending.