text:
Q: PayPal Adaptive Payments refund Issue I'm trying to refund an adaptive payment chained payment totally to the sender, but I'm stuck. I'm using CodeIgniter and Andrew Angell's awesome library for adaptive payments.
The refund I want to make has details like this: (you can see the raw xml requests and responds below)
Array
(
    [Errors] => Array
        (
        )

    [Ack] => Success
    [Build] => 5472483
    [CorrelationID] => 4d31bf900a109
    [Timestamp] => 2013-03-20T09:45:02.585-07:00
    [ActionType] => PAY_PRIMARY
    [CancelURL] => http://my-cancel-url.com
    [CurrencyCode] => TRY
    [FeesPayer] => PRIMARYRECEIVER
    [FundingTypes] => Array
        (
        )

    [IPNNotificationURL] =>
    [Memo] =>
    [PayKey] => my-paykey
    [PaymentInfo] => Array
        (
            [PendingRefund] => false
            [RefundAmount] => 0.00
            [SenderTransactionID] =>
            [SenderTransactionStatus] => COMPLETED
            [TransactionID] => my-transaction-id
            [TransactionStatus] => COMPLETED
        )

    [PreapprovalKey] =>
    [ReturnURL] => http://success-url-area.com
    [ReverseAllParallelPaymentsOnError] => false
    [SenderEmail] => sender@email.com
    [Status] => INCOMPLETE
    [TrackingID] =>
    [Receiver] => Array
        (
            [Amount] => 5.00
            [Email] => receiver@email.com
            [InvoiceID] =>
            [PaymentType] => SERVICE
            [Primary] => true
        )

    [XMLRequest] => <?xml version="1.0" encoding="utf-8"?><PaymentDetailsRequest xmlns="http://svcs.paypal.com/types/ap"><requestEnvelope xmlns=""><detailLevel>ReturnAll</detailLevel><errorLanguage>en_US</errorLanguage></requestEnvelope><payKey xmlns="">my-paykey</payKey></PaymentDetailsRequest>
    [XMLResponse] => <?xml version='1.0' encoding='UTF-8'?><ns2:PaymentDetailsResponse xmlns:ns2="http://svcs.paypal.com/types/ap"><responseEnvelope><timestamp>2013-03-20T09:45:02.585-07:00</timestamp><ack>Success</ack><correlationId>4d31bf900a109</correlationId><build>5472483</build></responseEnvelope><cancelUrl>http://my-cancel-url.com</cancelUrl><currencyCode>TRY</currencyCode><paymentInfoList><paymentInfo><transactionId>my-transaction-id</transactionId><transactionStatus>COMPLETED</transactionStatus><receiver><amount>5.00</amount><email>receiver@email.com</email><primary>true</primary><paymentType>SERVICE</paymentType><accountId>7VYWTSCQKWPAL</accountId></receiver><refundedAmount>0.00</refundedAmount><pendingRefund>false</pendingRefund><senderTransactionId>7P642947V2872150G</senderTransactionId><senderTransactionStatus>COMPLETED</senderTransactionStatus></paymentInfo><paymentInfo><receiver><amount>4.60</amount><email>soulsmasher@gmail.com</email><primary>false</primary><paymentType>SERVICE</paymentType><accountId>7UZSWUVKCU4UW</accountId></receiver><refundedAmount>0.00</refundedAmount><pendingRefund>false</pendingRefund></paymentInfo></paymentInfoList><returnUrl>http://success-url-area.com</returnUrl><senderEmail>sender@email.com</senderEmail><status>INCOMPLETE</status><payKey>my-paykey</payKey><actionType>PAY_PRIMARY</actionType><feesPayer>PRIMARYRECEIVER</feesPayer><reverseAllParallelPaymentsOnError>false</reverseAllParallelPaymentsOnError><sender><email>sender@email.com</email><accountId>Y2BSLXZ8DQYY2</accountId><useCredentials>false</useCredentials></sender></ns2:PaymentDetailsResponse>
)

When I try to execute refund, providing paykey, transaction ID (which I got from the request above), and sender email (which will get refund) this error comes up (you can see the raw request and responses below):
Array
(
    [Errors] => Array
        (
            [0] => Array
                (
                    [Receiver] =>
                    [Category] => Application
                    [Domain] => PLATFORM
                    [ErrorID] => 589061
                    [ExceptionID] =>
                    [Message] => The receiver sender@email.com is invalid for this refund
                    [Parameter] => sender@email.com
                    [Severity] => Error
                    [Subdomain] => Application
                )

        )

    [Ack] => Failure
    [Build] => 5472483
    [CorrelationID] => 2a1630b772ee0
    [Timestamp] => 2013-03-20T09:52:10.986-07:00
    [EncryptedTransactionID] =>
    [RefundFeeAmount] =>
    [RefundGrossAmount] =>
    [RefundHasBecomeFull] =>
    [RefundNetAmount] =>
    [RefundStatus] =>
    [RefundTransactionStatus] =>
    [TotalOfAllRefunds] =>
    [Receiver] => Array
        (
            [Amount] =>
            [Email] =>
            [InvoiceID] =>
            [PaymentType] =>
            [Primary] =>
        )

    [RawRequest] => <?xml version="1.0" encoding="utf-8"?><RefundRequest xmlns="http://svcs.paypal.com/types/ap"><requestEnvelope xmlns=""><detailLevel>ReturnAll</detailLevel><errorLanguage>en_US</errorLanguage></requestEnvelope><currencyCode>TRY</currencyCode><payKey xmlns="">my-paykey</payKey><receiverList xmlns=""><receiver xmlns=""><amount xmlns="">1.00</amount><email xmlns="">sender@email.com</email><paymentType xmlns="">SERVICE</paymentType></receiver></receiverList><transactionId xmlns="">1VL98806A27476639</transactionId></RefundRequest>
    [RawResponse] => <?xml version='1.0' encoding='UTF-8'?><ns3:FaultMessage xmlns:ns3="http://svcs.paypal.com/types/common" xmlns:ns2="http://svcs.paypal.com/types/ap"><responseEnvelope><timestamp>2013-03-20T09:52:10.986-07:00</timestamp><ack>Failure</ack><correlationId>2a1630b772ee0</correlationId><build>5472483</build></responseEnvelope><error><errorId>589061</errorId><domain>PLATFORM</domain><subdomain>Application</subdomain><severity>Error</severity><category>Application</category><message>The receiver sender@email.com is invalid for this refund</message><parameter>sender@email.com</parameter></error></ns3:FaultMessage>
)
1

Also when I don't provide transaction ID and leave the rest to PayPal, the issue changes to this (raw XML request are below the array):
Array
(
    [Errors] => Array
        (
            [0] => Array
                (
                    [Receiver] =>
                    [Category] => Application
                    [Domain] => PLATFORM
                    [ErrorID] => 589036
                    [ExceptionID] =>
                    [Message] => The currency code is missing or doesn't match the code in the payment request
                    [Parameter] =>
                    [Severity] => Error
                    [Subdomain] => Application
                )

        )

    [Ack] => Failure
    [Build] => 5472483
    [CorrelationID] => e3fc5e41040f3
    [Timestamp] => 2013-03-20T10:02:29.233-07:00
    [EncryptedTransactionID] =>
    [RefundFeeAmount] =>
    [RefundGrossAmount] =>
    [RefundHasBecomeFull] =>
    [RefundNetAmount] =>
    [RefundStatus] =>
    [RefundTransactionStatus] =>
    [TotalOfAllRefunds] =>
    [Receiver] => Array
        (
            [Amount] =>
            [Email] =>
            [InvoiceID] =>
            [PaymentType] =>
            [Primary] =>
        )

    [RawRequest] => <?xml version="1.0" encoding="utf-8"?><RefundRequest xmlns="http://svcs.paypal.com/types/ap"><requestEnvelope xmlns=""><detailLevel>ReturnAll</detailLevel><errorLanguage>en_US</errorLanguage></requestEnvelope><currencyCode>TRY</currencyCode><payKey xmlns="">AP-52A99028X8685964M</payKey><receiverList xmlns=""><receiver xmlns=""><amount xmlns="">1.00</amount><email xmlns="">sender@email.com</email><paymentType xmlns="">SERVICE</paymentType></receiver></receiverList></RefundRequest>
    [RawResponse] => <?xml version='1.0' encoding='UTF-8'?><ns3:FaultMessage xmlns:ns3="http://svcs.paypal.com/types/common" xmlns:ns2="http://svcs.paypal.com/types/ap"><responseEnvelope><timestamp>2013-03-20T10:02:29.233-07:00</timestamp><ack>Failure</ack><correlationId>e3fc5e41040f3</correlationId><build>5472483</build></responseEnvelope><error><errorId>589036</errorId><domain>PLATFORM</domain><subdomain>Application</subdomain><severity>Error</severity><category>Application</category><message>The currency code is missing or doesn't match the code in the payment request</message></error></ns3:FaultMessage>
)
1

As you can see, I've already provided the CurrencyCode, also the sender's email adress is taken from the request itself to prevent typos. Even if I hardcode it doesn't change the situation.
Can you help me, what am I missing?
Thanks,

A: check the documentation say by paypal here
Turkish Lira     TRY

NOTE:This currency is supported as a payment currency and a currency balance for in-country PayPal accounts only.


text:
Q: How to understand the Repeated Median Estimator (Siegel 1982)? I guess I did not understand the formula of the repeated median estimator introduced by Siegel (1982):
This is the formula:

If I got the following time series for instance:
y = { 2.3  , 5.6 , 7.8,  100, 110, 8, 4 }

Clearly $i$ and $j$ run from 1 to 7 as $|y|=7$. But how can I compute $\hat{\beta_0}$? Thanks for your help.

A: Just consider starting with 2.3 and calculating the Slope to all other values in the dataset. Then taking the Median Slope and associating it with the 2.3 value.
Then move on to 5.6 and repeat the process. At the end of this you will have a Median Slope for each value.
Then you extract the median of these Median Slopes. This is why it is called a "Repeated" Median Estimator.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serialization Exception while using LINQ to populate objects (ASP.NET MVC2) I have a set of Objects (ViewModel objects used to build strongly typed Views) which I populate from:

*

*External J2EE services for dynamic content. I use LINQ2XML to read the XML response returned by J2EE service to populate my objects

*Local DB for static content. I basically merge the static content from local DB with the dynamic content returned by J2EE services. I use NHibernate and LINQ for this operation.
Once I populate my ViewModels with all the data required, I plan to store them in SESSION (using AppFabric for Out-Of-Proc Session State). I have [Serializable]
 attribute for all my ViewModel classes as its required if I plan to store them in out-of-proc Session. However I am getting following exception:
Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

Stack Trace:

[SerializationException: Type 'System.Linq.Enumerable+WhereEnumerableIterator`1[[TrvCity.Services.ViewModels.ResortsView, TrvCity.Services, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' in Assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.]
   System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +9452985
   System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +247
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +160
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +218
   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) +388
   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +444
   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +133
   System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1708

I have throughly verified all my classes and they are marked as [Serializable]. To debug further, I manually (WITHOUT using step 1 & 2 mentioned above) populated them using MOCK DATA and I am able to put them in session, I don't get SerializationException in this case. I feel becuase I am using LINQ (LINQ2XML and LINQ2Objects) to populate them its not liking it.
I would appreciate someone can give me some direction in resolving this.
Here is the code snippet of my objects/classes:
[Serializable]
public class ResortsView : SupplierView
{
    public IList<ProductView> ResortProducts { get; set; }
    public string CheckInTime { get; set; }
    public string CheckOutTime { get; set; }
    public virtual IList<ImageView> Images { get; set; }
}

[Serializable]
public class SupplierView
{
    public string SupplierID { get; set; }
    public string SupplierName { get; set; }
    public string Description { get; set; }
    public string Rating { get; set; }
    public string URL { get; set; }
}

[Serializable]
public class ProductView
{
    public string Code { get; set; }
    public string Description { get; set; }
    public decimal? Price { get; set; }
    public ErrorView PricingError { get; set; }
}

A: That's probably because of lazy loading. Try eagerly fetching the collection before attempting to store it in session:
IEnumerable<ResortsView> resortsViews = ...
Session["resortsViews"] = resortsViews.ToArray();


text:
Q: How to replace non-latin letters with PHP preg_replace function?
Possible Duplicate:
php preg_replace with Unicode chars

I have tried to solve this myself but failed.
I need to "clean" my string using PHP preg_replace so every character except a-z, A-Z, 0-9, space (' ') and latin letters "ČčĆćĐ𩹮ž" are removed.
I have learned how to solve first part of my problem: $cleanstring = preg_replace('[^a-zA-Z0-9 ]', '', $originalstring);
But I'm not successful in including other latin letters in my pattern. I do not need all latin characters, just those listed above.
Edit: When my $originalstring is "Đak", my $cleanstring is "272ak"! How can I fix this?
Can anybody help?
Thank you in advance!
milosh


text:
Q: If I don't see the X Hunters on the map can I still get Zero's parts? I think I was slow in finding the X Hunters (I game overed and or missed at least one of them in a stage) so I seem to have 2 Zero parts with only 2 bosses remaining on the map, and no X Hunters are on the map anymore.
If I miss an X hunter at any time does that mean I can't recover all of Zero's parts or will I be able to get them later?

A:
with only 2 bosses remaining on the map

if by this you are talking about the original 8 bosses that appear after the intro stage then yes you still have time, the X Hunters will randomly change locations every time you clear a map (may also work with escaping, have not tried), this counts cleared stages where you reach the boss room and instantly warp out
when i was playing it for the first time i only had Crystal Snail left to take out and Agile was there, a really hard fight given Magnet Mine is his weakness and with Crystal Snail being my last boss before the final stages i had to defeat him so it's possible to only have 1 boss left and have 1 X Hunter left to beat
if you beat all 8 bosses and still haven't beaten all 3 X Hunters to get all 3 Zero Parts

 then in the final stage you will have to fight Zero before Sigma which is very hard, otherwise having all 3 you will face a Black Zero yet not fight him as the real Zero comes in to destroy him, saving you energy for your fight against Sigma


text:
Q: UIButton in tableFooterView not responding to click event In my viewDidLoad, I have written this code:
UIView *footerView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(10,10, 300, 40);
[btn setTitle:@"Select" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(onClickSelect:) forControlEvents:UIControlEventTouchUpInside];
[footerView addSubview:btn];

myTableView.tableFooterView = footerView;

and My selector method is:
- (void) onClickSelect: (UIButton*) sender
{
NSLog(@"selext");
 }

but when I click the button (which I have added in the table footer view), the selector method doesn't get called. Does anyone know what might be the problem?

A: Set the correct frame for FooterView.Something like
UIView *footerView = [[[UIView alloc] initWithFrame:CGRectMake(10,10, 320, 60)] autorelease];


text:
Q: Stick text element to right of div I've got a menu of items that need to be displayed with their prices in the following manner:
ITEM...................120
(The dots are just to show the spacing between the two and will not appear in the code)
What I've done till now is create a div of width:200px in which I've put the text.
Like this: http://jsfiddle.net/Newtt/jE2YL/1/
However, I'd like to know if it's possible to stick the price to the right margin of the box?
I've tried padding-left: X px;, but I've got a list of 100+ menu items each of which have arbitrary length of characters which in turn changes the padding for each price element and changing the padding of each element is rather cumbersome.
Thanks!

A: You can combine position: absolute and position: relative.
Use the following CSS:
.abc{
    width:200px;
    background:#ccc;
}
    .abc h5 {
        position: relative;
    }
        .abc h5 span {
            position: absolute;
            right: 0;
        }

jsFiddle Demo
Alternatively, you can just use float: right on the <span>:
.abc h5 span {
    float: right
}

jsFiddle Demo 2


text:
Q: Generating a random number in an SHTML page I need to attach a random number to a query string in an SHTML page. It's straightforward to generate the value in PHP:
function get_random_id(){
  srand ((double) microtime( )*1000000);
  return rand(0,1844);
}

But how do you use this when the SHTML page uses syntax like this?
<img src="<!--#echo var="imagemapgif" -->" name="Image1" width="169" height="41" usemap="#Map" id="Image1">

Anyone know of a syntax manual for SHTML pages? Thanks.

A: You need to run an external program to get a random number using a server side include.


text:
Q: Compare variables and set the first that has value I have an Event lister loop, where I made variables from the Event's dates and today date. There is a Required $maindate, but there are also other dates of the same event $otherdates, which are later than the main.
I want to set-up the latest date that is set in a separate variable, and compare it to the today's date to have the if ( $comparedate >= $today ) controlling the listing only the future events.
Here are my variables:
    $maindate = DateTime::createFromFormat('Ymd', get_field('date'));
    $otherdates1 = DateTime::createFromFormat('Ymd', get_field('other_dates'));
    $otherdates2 = DateTime::createFromFormat('Ymd', get_field('other_dates_2'));
    $otherdates3 = DateTime::createFromFormat('Ymd', get_field('other_dates_3'));
    $today = DateTime::createFromFormat('Ymd', date('Ymd'));

/* I need to set up the first available variable here */
$comparedate = $otherdates3 || $otherdates2 || $otherdates1 || $maindate;

if ( $comparedate >= $today ) :

/* list the future events */

How can I make this comparison?

A: $lastestDate = null;
$datesSet = [$maindate, $otherdates1, $otherdates2, $otherdates3];
foreach($datesSet as $date) {
     if($lastestDate == null || $lastestDate->getTimeStamp() < $date->getTimeStamp())
          $lastestDate = $date;
}
$comparedate = $lastestDate;

A: As pointed by Ianis, I had to compare the variables by php max operator, and the if statement gets the latest date like that.
The variable is:
$comparedate = max( $maindate, $otherdates1, $otherdates2, $otherdates3 );


text:
Q: Avoid loops in MATLAB while finding indices I have a faces list "faces" in the form n x 3.
Each row contains 3 indices of 3 different rows from a n x 3 vertex list. (So each value is the index to a row which contains 3 coordinates of a vertex.
In my vector "indices" in the form n x 1 I have stored indices of vertices which are of interest for me.
Now I want to see where in my "faces list" these indices from my vector "indices" are contained.
At the moment I'm looping through my faces list to get "vector s" which has the indices to the rows of the "faces list".
To improve the performance I preallocated the "vector s" with zeros.
Is there a faster method to get the same result?
s = zeros(9000000,1);
aa = 0;
for a = 1:size(indices,1)
    [i,j] = find (faces == indices(a));

    s(aa+1:aa + size(i,1),1) = i;
    aa = aa + size(i,1);
end

ss = s(any(s,2),:);
faces = faces(ss(:,1),:);

Thank you for your help.
Unfortunately I'm not that proficient with MATLAB and have still trouble vectorizing my code.

A: The key here is to use ismember. This gives you a logical array that is 1 wherever an element of the first array is equal to any of the elements in the second, in this case faces and indices.
As a toy example,
>> faces = randi(10, 10, 3)
faces =

    5    3    9
    8    4    4
   10    7   10
    6    6    3
    8   10    1
    9    2    2
    4    7    9
    5    8    3
    7    8    4
    2    4    9

>> indices = [1, 2, 3].'
indices =

   1
   2
   3

>> s = ismember(faces, indices)
s =

  0  1  0
  0  0  0
  0  0  0
  0  0  1
  0  0  1
  0  1  1
  0  0  0
  0  0  1
  0  0  0
  1  0  0

From there, you can continue just as you did before to find rows that have any 1 value in them.


text:
Q: streaming audio and video in python so I found this code somewhere and I tried running it:
import cv2
from ffpyplayer.player import MediaPlayer

video_path = "video.mp4"

def video_audio(path):
    video = cv2.VideoCapture(video_path)
    player = MediaPlayer(video_path)
    while True:
        ret, frame = video.read()
        audio_frame, val = player.get_frame()
        if not ret:
            print("End of video")
            break
        if cv2.waitKey(28) & 0xFF == ord("q"):
            break
        cv2.imshow("Video", frame)
        if val != 'eof' and audio_frame is not None:
            # audio
            img, t = audio_frame
    video.release()
    cv2.destroyAllWindows()

video_audio(video_path)

it does actually play the video and audio, but there is a delay between the two (current audio frame is played ahead of the current video frame)
does anyone know a possible solution to fix that?


text:
Q: How do I create a link_to tag with both class and data fields? I want to create a Rails link_to tag that will ultimately spawn a dialog box and so it just link to "#".  However, I would like it to have a class and data attribute.  But when I try this
<%= link_to "What's This?", "#", {class: "more_info"}, :data => { :more_info => 'mt_hashes_info' } %>

I get the error
wrong number of arguments (given 4, expected 0..3)

What's the right way to construct this link?

A: This is what it should look like:
<%= link_to "What's This?", "#", {:class => "more_info", :data => { :more_info => 'mt_hashes_info' }} %>
Class and Data both go into the same options hash.

A: You can do this simply like this
<%= link_to "What's This?", "#", class: "more_info", data: { more_info: "mt_hashes_info" } %>

the generated HTML
What's This?

With confirmation dialog
<%= link_to "What's This?", "#", class: "more_info", data: { confirm: "Are you sure?" } %>

the generated HTML
What's This?

You can find more the link_to

A: Here's an example from the heart of Redmine:
link_to(l(:button_archive), archive_project_path(project, :status => params[:status]), :data => {:confirm => l(:text_are_you_sure)}, :method => :post, :class => 'icon icon-lock')

Sorry about the run-on statement; you know Redmine! But note both :data and :class are peers of the same Hash...


text:
Q: How can I make text alternate color every line? I'm not referring to tables, just normal paragraphs of text. I want, for example, every other line to be drawn in red, or otherwise highlighted.
My use case is preparing exams for students with special needs.
I thought that something could be worked out maybe calling some TikZ code after the line has been drawn, similar to what packages like lineno do. But that is far beyond my LaTeX skills.
Any help is appreciated.

A: This is something quickly written with this answer as starting point. It works for plain text but not for equations. Thanks to TikZ' modulo function you could also add a longer color list and alternate between n colors. In principle this can be done without TikZ (e.g. with zrefpos). And it does not require any special compiler like lualatex
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{soul}
\def\lstcolors{"black","red"}
\newcounter{colorindex}
\makeatletter
\DeclareRobustCommand*\myalternate{%
\begin{tikzpicture}[overlay,remember picture]
\path let \p1=($(0,0)-(current page.south)$) in \pgfextra{
\xdef\lasty{\y1}};
\end{tikzpicture}%
\def\SOUL@everytoken{\begin{tikzpicture}[overlay,remember picture]
\path let \p1=($(0,0)-(current page.south)$) in \pgfextra{
\ifdim\y1<\lasty
 \stepcounter{colorindex}
 \xdef\lasty{\y1}
\fi};
\end{tikzpicture}%
\pgfmathsetmacro{\currentcolor}{{\lstcolors}[mod(\number\value{colorindex},2)]}%
\textcolor{\currentcolor}{\the\SOUL@token}}%
\SOUL@}
\makeatother
\begin{document}
\myalternate{hello hello hello hello hello hello hello hello hello hello
hello hello hello hello hello hello hello hello hello hello hello
hello hello hello hello hello hello hello hello hello hello hello
hello hello hello hello hello hello hello hello hello hello hello
hello hello hello hello hello hello hello hello hello hello hello}
\end{document}


text:
Q: Finding the AspNetUser from within a trigger I am working with an ASP.NET MVC application. In this application I am wanting to update some data fields on the record just written - including the userID of the person responsible for the change. The problem is that I don't know how to find out who has changed the record.
I have used CURRENT_USER in my script but that always returns the current SQL_SERVER security user - in this case "dbo" as that is the user that ASP.NET MVC connects to the database with. This would mean that all changes were made by the same user. If I can get the AspNetUser record ID then I'll be okay.
Any Ideas? Do I need to find a way to add unique users for all web logins? That is not mentioned anywhere, so I suspect that it's not expected.
Thanks

A: From a SQL Server perspective the "user" of the database is your MVC application, not a user logged in to your web application. The only way to change this is to create database logins for all web application users, but I wouldn't recommend this approach.
IMHO it is best to move the mentioned functionallity from SQL Server triggers to your data access layer (in .NET, your "repositories" or whatever data access pattern you are using).


text:
Q: IScroll bounces back i'm doing phonegap project with html5-css-Jsmobile...i'm using a multipage template...
i'm trying to use Iscroll to implement scroll for some text views...when i test it on FF it works only if i refresh the page...the first time i load the page it doesn't work...on iOs device it doesn't work...the scroll bounces to the top and doesn't scroll down...i tried some differents solutions finded on the web...i tried to add css hight to the #scroller>#wrapper...tried to use iscroll-lite...
in some page i have multiple scroll...the only solution i found is to add var myScroll2, var myScroll3 and so on...
Help me ;)
my code:

HTML DIV DATA-ROLE PAGE with the scroll (i have some others similar pages with scroll)

Nel 1877 l'esploratore e geografo Renzo Manzoni, nipote del celebre scrittore di Fermo e Lucia, si reca nello Yemen dove soggiorna tre anni, in particolare a San'a, e scrive El Yèmen. Tre anni nell'Arabia Felice, pubblicato nel 1884. Manzoni racconta le sue impressioni di viaggio, con precise descrizioni degli ambienti, corredati da disegni e fotografie.....

CSS
#wrapper {
position:absolute; z-index:1;
top:221px; bottom:48px; left:0;
width:100%;
overflow:auto;
height:206px;
color:#FFF;
text-shadow:none;
font-family:"Interstate-Regular";
font-size: 13px;
}

#scroller {
position:absolute; z-index:1;
-webkit-tap-highlight-color:rgba(0,0,0,0);
width:100%;
padding:0;
}

#scroller p {
padding:0px 12px 0px 12px;

}

A: try initializing the iScroll in a timeout like so
setTimeout(function () {
        myScroll = new iScroll('wrapper');
    }, 100);

as stated here - http://cubiq.org/iscroll-4 in the ONLOAD section


text:
Q: render issue in reactjs why is the Tags react component not showing the data from the getTags() function, I am not getting any error in console, not able to find the reason behind it.
this.props.discussion.tags the data is in this format

i am using the flux architecture
this is the snippet of the code

class DiscussionCard extends React.Component {

  constructor(props) {
    super(props);

  }
  render() {
    return (

      <Tags tags = {this.props.discussion.tags}/>

       );
    }

}

class Tags extends React.Component {

    constructor(props) {
        super(props);
        this.getTags = this.getTags.bind(this);
    }

     getTags(){
     return this.props.tags.map(tag => {
   {tag.name} |
    });
}
render() {
    console.log(this.props.tags)
    return (

 {this.getTags()}

        );
    }

}

A: You are missing a return statement:
 getTags(){
    return this.props.tags.map(tag => {
        return {tag.name} |
});

A: try any one:
getTags(){
    return this.props.tags.map(tag => {
       return {tag.name} |
   });
}

or
getTags(){
   return this.props.tags.map(tag =>
         {tag.name} |
   );
}


text:
Q: Cache partition not replicated I have 2 nodes with the persistence enabled. I create a cache like so
  // all the queues across the frontier instances
    CacheConfiguration cacheCfg2 = new CacheConfiguration("queues");
    cacheCfg2.setBackups(backups);
    cacheCfg2.setCacheMode(CacheMode.PARTITIONED);
    globalQueueCache = ignite.getOrCreateCache(cacheCfg2);

where backups is a value > 1
When one of the nodes dies, I get
Exception in thread "Thread-2" javax.cache.CacheException: class org.apache.ignite.internal.processors.cache.CacheInvalidStateException: Failed to execute query because cache partition has been lostParts [cacheName=queues, part=2]
    at org.apache.ignite.internal.processors.cache.query.GridCacheQueryAdapter.executeScanQuery(GridCacheQueryAdapter.java:597)
    at org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl$1.applyx(IgniteCacheProxyImpl.java:519)
    at org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl$1.applyx(IgniteCacheProxyImpl.java:517)
    at org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
    at org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:3482)
    at org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.query(IgniteCacheProxyImpl.java:516)
    at org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.query(IgniteCacheProxyImpl.java:843)
    at org.apache.ignite.internal.processors.cache.GatewayProtectedCacheProxy.query(GatewayProtectedCacheProxy.java:418)
    at crawlercommons.urlfrontier.service.ignite.IgniteService$QueueCheck.run(IgniteService.java:270)
Caused by: class org.apache.ignite.internal.processors.cache.CacheInvalidStateException: Failed to execute query because cache partition has been lostParts [cacheName=queues, part=2]
    ... 9 more

I expected the content to have been replicated onto the other node. Why isn't that the case?

A: Most likely there is a misconfiguration somewhere. Check the following:

*

*you are not working with an existing cache (replace getOrCreateCache to createCache)

*you are not having more server nodes than the backup factor is

*inspect the logs for "Detected lost partitions" message and what happened prior


text:
Q: How to read data from .adf file and insert into mysql table using php? Anyone knows how to read ADF file from the URL in PHP and render it and save it in MySQL table?
When I use function like
$xml=simplexml_load_file($_REQUEST['adfpath']) or die("Error: Cannot create object");

it's showing

Error: Cannot create object

Below is the ADF File Sample:
<?ADF VERSION "1.0"?>
<?XML VERSION "1.0"?>
<adf>
     <prospect>
        <requestdate>2010-11-18</requestdate>
        <vehicle>
            <year></year>
            <make></make>
            <model></model>
        </vehicle>
        <customer>
             <contact>
                   <name part="first">Test11</name>
                   <name part="last">mctester</name>
                        <address type ="home">
                             <street line ="1">1722 W test test RD</street>
                             <city></city>
                             <state>AZ</state>
                             <postalcode></postalcode>
                        </address>
                   <phone type="voice"></phone>
              </contact>
        </customer>
        <vendor>
            <vendorname>
            Test vender
            </vendorname>
        </vendor>
        <provider>
            <name part='full'>test11 test22 </name>
            <service>Leads - </service>
            <url>test</url>
            <email>test</email>
            <phone>800-123-4567</phone>
            <contact primarycontact='1'>
            <name part='full'>Dennys Test11</name>
            <email>test</email>
            <phone type='voice' time='day'></phone>
            <phone type='fax' time='day'></phone>
            <address>
            <street line='1'>Apple </street>
            <street line='2'>K Mart </street>
            <city></city>
            <regioncode></regioncode>
            <postalcode></postalcode>
            <country>US</country>
            </address>
            </contact>
        </provider>
     </prospect>
</adf>

Any help is greatly appreciated..


text:
Q: Corrupted Files Microsoft Office 2007 ASP.NET 1.1 and SQL Server I am working on an ASP.NET 1.1 website that stores files in the database. The website has been working great with no problems uploading and downloading any type of documents since 2001.
However, recently the customer noticed that all Microsoft Office 2007 documents DOCX, XLSX, ect are corrupted when any user try to download them.
What I have noticed is that SQL Server adds an extra byte to the DocumentContent (image column). Before uploading the document the content and length are fine. However, after they get stored, SQL Server adds an EXTRA Byte.... WHY?????
Many people on the internet provided a solution on how to download the file, which is great and it worked for me.
I am looking for an answer to this question... WHY DOES SQL SERVER ADD AN EXTRA BYTE TO THE IMAGE COLUMN?
It is an Asp.NET 1.1 and SQL 2000 but we just moved it to 2008 and we still have the same problem.

A: I am not 100% sure if your problem was the same as what I have had but in my case, I found that the problem was actually in the writing part, not in the reading part. For example, my original writing code was like this:
Dim FILE_CONTENT(len) As Byte
File.InputStream.Read(FILE_CONTENT, 0, len)
SaveFileToDatabase(FILE_NAME, CONTENT_TYPE, FILE_CONTENT)

When I changed the first line as the following :
Dim FILE_CONTENT(0 To len - 1) As Byte

the reading error disappeared. I just forgot that VB actually allocates N+1 bytes (O to N) by default when you dimension it without specifying the lower bound. See similar situation described here: Uploaded Docx Files are getting corrupted . Hope that helps.


text:
Q: HTML INPUT tag not inheriting CSS from FORM I have some HTML forms. I am using tables. I am superimposing png's over submit buttons.
In example A, the CSS below works. In example B it does not. I have checked the CSS debugger, and the issue seems to be that the INPUT field does not inherit from FORM, when it is separated from it by the TR or TD tags. Presumably there should be a way to statically redefine this inheritance in CSS.  Can anybody point me at the correct solution?
The use of tables is a constraint in this particular case.
EXAMPLE A:

   <form method="post" action="/AdminPalette" enctype="application/x-www-form-urlencoded">
   <input type="submit" name="add" value="add" class="add" />

</form>

EXAMPLE B:

   <form method="post" action="/AdminPalette" enctype="application/x-www-form-urlencoded">

   <input type="submit" name="add" value="add" class="add" />

</form>

EXAMPLE CSS:

form input[type=submit].add {
 width : 32px;
 height :32px;
 border : none;
 color : transparent;
 font-size : 0;
        cursor: pointer;
}

form input[type=submit].add {
 background : url("/Art/GCON/green/add-item.png") no-repeat center center;
}

A: This has nothing to do with inheritance.
Your HTML is invalid. Use a validator.
A table can be contained with in a form. A form can be contained within a table cell. A form cannot be a child element of a table (or of a table row, table body, table header or table footer).
Your browser is error correcting by putting the form after the table (but leaving the inputs behind).


text:
Q: Reference of a Class ? How does it workout in memory? class A {
}

class B extends A {
}

A a01 = new A();
A a02 = new B();

What difference this reference a02 has compared to a01?
What does it mean for a reference to be of type class A or class B?
How does it work out in memory?

A: There is no difference between a01 and a02. Both are references of type A. This means that you can only use members of class A and not of any of its subtypes.

what does reference of type class A or class B means ?

The reference type is determined by the declaration of the reference variable:
A a; // This is a reference of type A
B b; // This is a reference of type B

is it such that if reference is of type class A it automatically points to object of class A

Yes, a reference of type A must point to an object of type A, but it also may point to any object that has a subclass of A for its type. In your example, a B is a A because B extends A.

A: It is important to distinguish between the declared type of a variable, and the runtime class of an object.
In Java, each object has a runtime class, as specified in the class instance (or array ) creation expression that created it. The runtime stores this information in the object itself, enabling us to query it with the instanceof operator or the getClass() method.
In addition, each variable has a declared type. Declared types are used at compile time to verify that the variables support the operators, fields and methods the code uses on them. To do this, the compiler and runtime collaborate to enforce that a variable declared with reference type D either references null, or an object whose runtime class is D or a subtype of D at all times (excepting a few pathological corner cases arising from incorrect use of generic types).
In memory, your code would look something like this:
+-------+-------+
|  a01  |  a02  |       thread call stack
+-------+-------+
    |       |
    |       |
    v       v
+-----+  +-----+
|  A  |  |  B  |        object heap
+-----+  +-----+

A: In this example Class A is your parent class and Class B is child class you might be knowing that, Basically your child class knows about your parent class. But parent class does not know how many child classes has extended its functionality. So basically you can use Parent class as reference to hold child class object but child class can not hold parent class object. In your case both of the object has reference of Class A which does not make any difference. JVM will reserve memory for the object in the heap and provide reference in respective object reference. At the compile it doesn't make any difference but at the runtime it will call respective method of the object.


text:
Q: Select 2 ajax search fires when pressing ctrl keys I have the following select 2 field:
$("select#edit-property-id").select2({
  multiple: false,
  width: 150,
  delay: 250,
  placeholder: "Type",
  minimumInputLength: 1,
  ajax: {// instead of writing the function to execute the request we use Select2's
  // convenient helper
    url: "/tell/product_chosen_search",
    dataType: 'json',
    data: function (params) {
      return {
        term: params.term, // search term
      };
    },
    processResults: function (data, page) {
      return {
        results: data
      };
    },
  },
});

The ajax search fires correctly when I enter characters, however it also fires when I press keys such as ctrl, down button etc... How can I prevent that? Is there a setting?

A: This appears to be a defect in the new 4.0 version of Select2, which is still in beta.
jsfiddle
With v3.5.2, the following line in the updateResults function prevents the unnecessary ajax calls:
// prevent duplicate queries against the same term
if (initial !== true && lastTerm && equal(term, lastTerm)) return;

jsfiddle
Here's a somewhat related issue. At least, I think both issues could be fixed at the same time. You may want to add a comment to that issue.


text:
Q: Can't use onCompletion route scope with transacted routes I didn't manage to customize transacted route with rollback/commit  post-processing. Any help on how to write this kind of transacted route will be really appreciated. Based on some example code, I wrote something like this :
from(direct("global")
  .log("anything before that doesn't need transaction context")
  .to(direct("transacted")
  .log("anything after that doesn't need transaction context")
;

from(direct("transacted"))

  .onCompletion().onCompleteOnly()
    .validate().simple("${body.state} == 'MOVE_SUCCESS'")
    .log("success, with commit ")
  .end()

  .onCompletion().onFailureOnly()
    .validate().simple("${body.state} == 'WAITING_MOVE'")
    .bean(DbService.class, "documentInError(${body}, ${exception})")
    .bean(FileService.class, "moveFileToError")

    .log("error, with rollback")
  .end()

  .transacted()
    .bean(DbService.class, "updateDocument")
    .bean(FileService.class, "moveFileToTarget")
;

but don't know why, I still have this kind of error :

Caused by: java.lang.IllegalArgumentException: The output must be
added as top-level on the route. Try moving onCompletion[[]] to the
top of route.     at
camel.core.model@3.15.0/org.apache.camel.model.ProcessorDefinition.addOutput(ProcessorDefinition.java:209)
~[camel-core-model-3.15.0.jar:na]     at
camel.core.model@3.15.0/org.apache.camel.model.ProcessorDefinition.onCompletion(ProcessorDefinition.java:3637)
~[camel-core-model-3.15.0.jar:na]

I'm permitted to declare those onCompletion only "outside" any route, but that doesn't correspond to what I want. Beacause then the onCompletion processing is hold in both global and transacted route, leading to other issues.
I already have onException application wise configured, with retry policy on FileService errors (handling redelivery of processor nodes). And would prefere to keep them configured application wise.
thanks,

A: We finally achieved kind of route scope of onCompletion and onException, by separating global route and transacted route in two distinct route builders.
But we decided to handle a transaction in java (spring) rather than in camel.
Mainly because the transaction scope is difficult to figure out in camel. the transaction error handler, taking the lead once redelevery policy are exhausted, and somehow seems to happen within onException without clear demarcation :
for example :
onException(IOException)
  // the "following" (whatever holds behind the scene) happens inside transaction
  .maximumRedeliveries(3)
  .retryAttemptedLogLevel(WARN)
  .retriesExhaustedLogLevel(ERROR)
  .onExceptionOccurred(exceptionOccurredProcessor)

  // then on redelivery exhaustion the transaction is rolledback
  // the following happens after rollback
  .log(...)
  .to(...)

We had to make database operation support retries (due to some autonomous transactions), but this is simplier than structuring for camel transacted route.
Furthermore, it just happens that transacted route main purpose is the rollback of the message in the jms as well, but we don't want this because we handle errors with DLQs.
with_spring_transaction


text:
Q: Множественный data-category Существует следующая страница с фильтром через checkbox

  <input class="cardCheckBox" type="checkbox" value="foo"> foo

  <input class="cardCheckBox" type="checkbox" value="xyz"> xyz

foo 1

xyz 1

foo 2

Не могу понять, что нужно добавить в скрипт, если в data-category много категорий находится, как тогда фильтром выводить div? Что добавить?
Много типа:

A: разделите категории в массив
const categories = $(this).data('category').split(',');

а условие тогда на какое нить
checkedArr.some(c => categories.includes(c))

вообще, наверное, лучше будет вместо each-toggle сделать filter-toggle


text:
Q: Apex Source Scanner flag CRUD/ FLS as security risk for no reason I've been using FFLIB_SecurityUtils lib to enforce CRUD and FLS in my apex classes. I've no issues when running unit tests, but when submitting my code on Source Scanner for partners, i've several security risks flag although CRUD and FLS are enforced as required
//..some code

fflib_SecurityUtils.checkInsert(    //Throw an exception if CRUD/ FLS is not valid
                customObject__c.SObjectType,   // check sObject.isCreatable()
                new List<Schema.SObjectField>{
                        customObject__c.Age, //check customObject__c.Age.isCreatable()
                        customObject__c.Address }); //check customObject__c.Address.isCreatable()

customObject__c cust = new customObject__c(

                Age= 10,
                Address = 'Paris, France'
);

            insert cust;

SOURCE SCANNER SECURITY RISK FLAG

Do you think i should consider it as False positive and document it for the security review team or should i check any further?
Thank you

A: To help others who end up here, my response as an answer:
From what you posted, looks like a false positive - so I would document it in review.
Here is a link to a recent update from the SR team about how to document your false positives
As much as anything, the team is looking for you to show awareness of implementing security on the platform, so if you can show you are not exposing data etc, they should be ok with it
e.g.

FLS Create result path 1:  Object: status__c in file:
  /classes/MyRequestData.cls
Response: This is checked via a general security/permissions check at
  start of class using fflib_SecurityUtils.checkInsert
If no access, permission check will throw exception, and code will no
  longer execute


text:
Q: HA-JDBC database password decryption in xml config file I read the document in the website of HA-JDBC about database password encryption in the xml config file and I unable to decrypt the password when I connect to my database. So, it return me exception which is invalid user or password. The following is my configuration in my xml config file:
<xa-datasource id="Derby1A" weight="100" local="true">
<name>org.apache.derby.jdbc.ClientXADataSource</name>
<property name="user">clientuser</property>
<property name="password">64:MTIzNDU2Nzg=</property>
<property name="portNumber">1527</property>
<property name="databaseName">Testing</property>
<property name="serverName">127.0.0.1</property>
<user>clientuser</user>
<password>64:MTIzNDU2Nzg=</password>
</xa-datasource>

I put 64 in front the encrypted password, so, it will decrypt the password by using Base64 decoder to decrypt the password. How to decrypt the password when connect to database ?
Thanks a lot...

A: To answer your question, the password defined in the ha-jdbc configuration is only used by HA-JDBC itself - these are not the credentials used when your application connects to your HA-JDBC cluster.  When you connect to the HA-JDBC cluster from your application, you need to specify the password either in your application itself (e.g. DataSource.getConnection(user, password)), or preferably in your application server configuration of your HA-JDBC datasource.
The credentials used in ha-jdbc configuration should have administrative privileges (e.g. drop/create tables, etc.), while the credentials used by your application are typically CRUD privileges only.


text: Q: Pressure sensitive stylus for Lenovo Edge I just got a Lenovo Edge 15, and was wondering if there were any styluses that would work for it. I've seen Thinkpad styluses for very little and would get one of those if they work. I also tried a Wacom Bamboo stylus but it didn't work.


text:
Q: Getting pages by url using Wordpress REST API I'm attempting to using WP REST API on a site that uses pretty URLs, not ID's (which is typical in a REST scenario). All I have to query with is the requested URL.
Lets say a user lands on example.com/about, I can do the following:
/wp-json/wp/v2/pages/?slug=about

No sweat. However, what if a users lands on example.com/about/team? I could query by the slug team, but maybe my site also has example.com/contact/team as a possible URL. It's not reliable.
What I need is a way of achieving the following:
/wp-json/wp/v2/pages/?permalink=about%2team

It's unfeasible to have to set up custom routes for each page that gets created. I'm surprised the API doesn't appear to have some kind of permalink handler out of the box.

A: Well, since there is no tool to handle all of the cases, you have to be a bit crafty. It is possible to use a combination of wp functions like url_to_postid or get_term_by and global variables like $wp_taxonomies to figure out all of the cases.
You can create a custom endpoint and use the code below to handle the path. I think that I have covered all of the possible cases, but use carefully cause I might miss something.
function ca_path_to_object($path = '/') {
    $path = $path === '/' ? $path : trim($path, '/');
    $path = $path === '' ? '/' : $path; // Return homepage for no arguments
    $for_front = intval(get_option('page_on_front'));
    $for_posts = intval(get_option( 'page_for_posts' ));
    if($path == '/') $pid = $for_front; // It is the homepage
    else $pid = url_to_postid($path); // It is not
    if($for_posts != 0) { //For some reason url_to_postid does not work if the page is set to be the blog feed
        if($for_posts == $for_front) { // if both $for_front & $for_posts set to the same page get_permalink returns 404 for some reason, so lets construct it manually
            $pst = get_post($for_posts);
            $prnt = intval($pst->post_parent);
            $url = '';
            if($prnt != 0) {
                $url = parse_url(get_permalink($prnt));
                $url = trim($url['path'], '/');
            }
            $url .= '/'.$pst->post_name;
            // if it matches it will return the results as Homepage as per default WP behaviour
        }
        else {
            $url = parse_url(get_permalink($for_posts)); // otherwise just get it
            $url = $url['path'];
        }
        if(trim($url, '/') == $path) $pid = $for_posts;
    }
    if($pid == 0) { // not a page or cpt, let's try to find a taxonomy out of it
        $path_arr = explode('/', $path);
        global $wp_taxonomies;
        $tax = null;
        foreach ($wp_taxonomies as $key => $value) {
            if ($value->rewrite['slug'] === $path_arr[0]){
                $tax = $key;
            }
        }
        if($tax !== null) {
            $term = get_term_by('slug', end($path_arr), $tax);
            if($term !== false) {
                $pid = $term->term_id;
                return array(
                    'type' => 'term',
                    'id' => $term->term_id,
                    'object' => $term,
                );
            }
        }
    }
    if($pid == 0) { // If still 0, perhaps it's an user profile url?
        global $wp_rewrite;
        $base = explode('/', trim($wp_rewrite->get_author_permastruct(), '/'));
        $base = $base[0];
        if($path_arr[0] === $base) {
            $user = get_user_by('slug', end($path_arr));
            if($user !== false) {
                $pid = $user->ID;
                return array(
                    'type' => 'user',
                    'id' => $user->ID,
                    'object' => $user,
                );
            }
        }
    }
    if(($pid == 0) && ($path == '/')) { // If still 0, lets check if the page is the homepage without any associated page entity
        return array(
            'type' => 'home',
            'id' => null,
            'object' => null,
        );
    }
    if($pid == 0) { // If still 0, return nothing found or 404
        return array(
            'type' => '404',
            'id' => null,
            'object' => null,
        );
    }
    $post = get_post($pid);
    if($post->ID == $for_front) { // It's a page assigned to be a homepage
        return array(
            'type' => 'home',
            'id' => $post->ID,
            'object' => $post,
        );
    }
    if($post->ID == $for_posts) { // It's a page assigned to be a posts feed
        return array(
            'type' => 'feed',
            'id' => $post->ID,
            'object' => $post,
        );
    }
    return array( // It's just a post object
        'type' => 'post',
        'id' => $post->ID,
        'object' => $post,
    );
}


text:
Q: Future predictions payment amount program I'm working on a program to estimate the future tuition fee for an institution as it increases by 7% yearly, so how many years will it take to double the amount.
Let's say the current amount is $10000
Here is my Java code:
public class FutureTuition{
 public static void main(String[] args) {
       double tuition = 10000;
       //7% of tuition = 7/100 * 10000 = 700
        Int year = 1;

        while(tuition < 20000){
                tuition = tuition+700;
                year++;
     }

     System.out.println("Tuition will be doubled in " + year + " years");}}

The result was :
Tuition will be doubled in 16 years
I don't think that's right,what's wrong?

A: Your code is almost right. Just the increasement rate must be 1.07*tuition, not 700 flat every time. Which Java version did you use? This works with 1.8.
public class FutureTuition{
    public static void main(String[] args) {
        double tuition = 10000;
        //7% of tuition = 7/100 * 10000 = 700
        Integer year = 0;

        while(tuition < 20000){
            tuition = tuition * 1.07;
            year++;
        }

        System.out.println("Tuition will be doubled in " + year + " years");}

}


text:
Q: What are the most recent devopments with applying fractals to economics? I was researching fractals for my senior mathematics presentation and discovered that one of the most recent pioneers in that section of the field was able to apply fractal mathematics to the field of economics.  One of his first discoveries was finding a fractal pattern to fluctuations in cotton prices.
What further advancements have been made in the applications of fractals to economics?

A: Fractal and chaos theory both were very popular in Economics in the early 90's but to the best of my knowledge it was more of an academic fad: no lasting advances were made.


text:
Q: $R$ is a prime right Goldie ring which contains a minimal right ideal. Show that $R$ must be a simple Artinian ring. $R$ (1 is not assumed to be in $R$) is a prime right Goldie ring (finite dimensional and ACC on right annihilators) which contains a minimal right ideal. Show that $R$ must be a simple Artinian ring.
This appeared in a past paper, the first 2 parts which I managed to prove were "Every essential right ideal of a semi-prime right Goldie ring contains a regular element" and "Every non-zero ideal of a prime ring must be essential as a right ideal". There is also an extra hint that I might have to use Artin-Wedderburn.
I've been trying (and failing) to find a way to use these results since I can't assume (or prove that) the minimal right ideal is an ideal (to use the previous result). I also have that the minimal ideal is of the form $eR$ where $e$ is idempotent, but I feel like i'm barking up the wrong tree. Any help is appreciated, thanks.

A: Let $E(R)$ be the right socle of $R$. $E(R)$ is an ideal of $R$, so it is essential as a right ideal and therefore contains a regular element, $c$ say.
$R$ is isomorphic to $cR$, via the isomorphism $r\rightarrow cr$. (If $cr=0$ then $r(c)=0$ implies $r=0$, injective. Surjective obvious.)
$cR$ is inside $E(R)$, so it is completely reducible, therefore $R$ is completely reducible. R is then a direct sum of irreducible submodules, this direct sum is finite as $R$ is Goldie. Therefore $R$ is right Artinian. Prime right Artinian rings are simple.

A: By primeness of $R$, the minimal right ideal of $R$ must be faithful, so the ring is actually right primitive, and its Jacobson radical is zero.
There exists, then, a collection of maximal regular right ideals $\{T_i\mid i\in I\}$ such that $J(R)=\cap T_i=\{0\}$. This allows the natural embedding of $R_R\hookrightarrow\prod_{i\in I} R/M_i$.
Going back to the assumptions, we know that $soc(R_R)$ is an essential right ideal of $R$. Since it is Goldie, the semisimple module $soc(R_R)$ is finitely generated. It's well known that if $R$ has a finitely generated essential right socle, then it is finitely cogenerated as a module. The embedding $R_R\hookrightarrow\prod_{i\in I} R/M_i$ therefore restricts to a finite subset $F$ so that $R_R\hookrightarrow\prod_{i\in F} R/M_i$.
But $\prod_{i\in F} R/M_i=\bigoplus_{i\in F}R/M_i$, so that $R$ is embedded in this finitely generated completely reducible module, and therefore is completely reducible itself, hence Artinian.
According to your notes, this prime Artinian ring has identity and is a simple Artinian ring by the Artin-Wedderburn theorem.


text:
Q: How do you filter an array of objects for undefined values? I have the following array:
[{object}, {object}, {object}]

Each object looks something like:
{key0: 3, key1: undefined, key2: 7}

I want to filter the array for undefined properties so that each object in the array now looks like:
{key0: 3, key2: 7}

I've tried everything with Lo_Dash and I'm thinking I must be going crazy.

A: What code do you have written right now?
You could do something like this:
_.each(array, function(item, index, collection){
  collection[index] = _.filter(item, function(value){
    return value !== undefined;
  });
});

This will iterate over the array, then filter each object in the array.
EDIT:
If you'd like to maintain the array elements as objects, you can use _.reduce instead. IE:
_.each(array, function(item, index, collection){
  collection[index] = _.reduce(item, function(result, value, key){
    if(value !== undefined) { result[key] = value; }
    return result;
  }, {});
});

A: This is the approach that I would take. Use filter on your array and check for all the undefined props in a loop. Then simply delete them from your object. I just looked and another poster noted this. I've included the hasOwnProperty check as well.
var data = [{
    key0: 3,
    key1: undefined,
    key2: 7
}, {
    key0: 4,
    key1: undefined,
    key2: 8
}, {
    key0: 5,
    key1: undefined,
    key2: 9
}];

function removeUndefined(obj) {
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop) && obj[prop] === undefined) {
            // do stuff
           delete obj[prop];
        }
    }
    return obj;
}

var filtered = data.filter(removeUndefined);

console.log(filtered);

A: In LoDash you can use a combination of map + omit:
objs = _.map(objs, function(x) {
    return _.omit(x, _.isUndefined)
})

A: You can loop through all properties and remove undefined properties using the "delete" keyword.

var myObj = {key0: 3, key1: undefined, key2: 7};

for (var i in myObj) {
  if (myObj[i] === undefined) {
    delete myObj[i];
  }
}


text:
Q: Nano: can the escape key be mapped? I've been playing with the keyboard mapping in the .nanorc file some today, and you can map the F keys like...bind F3 cancel all, however, i haven't had any luck with trying find how nano recognizes the escape key. I've already tried Esc, esc, nano keeps giving me an error message. Is there a way to bind/map the escape key in the corner of your keyboard?

A: You can not do it.
The keys which could be mapped are described here:
https://www.nano-editor.org/dist/latest/nano.html#Rebinding-Keys
It also has a statement:

Rebinding ^[ (Esc) is not possible, because its keycode is the starter byte of Meta keystrokes and escape sequences.


text:
Q: Payable Invoice Capturing OR extracting automation I am creating a desktop/winform application that reads tif/pdf payable invoices and extract all the invoice information to store into database.
I can read the standard barcodes(QR Code, Code39 etc), and some of the payable invoice' standard fields(Invoice Date, Company Name, Address) with OCR (ocr specific region of image) but unable to capture Line items, amount correctly.
I extract information in two phases:
 1. Read specific regions based on the template(user mapped region
    for specific fields)
 2. OCR whole page and search for payable
    invoice standard field names and values
I have idea about following 3 approaches:
 1. Create a Template for one type of Invoice and process all invoices.
 2. Nural network based engine which need to be trained with sample data to work it based on patterns.
 3. Form processing, a kind of OMR. The OCR to look at exact same coordinates where fields were placed on form(during form desing)
Question:
How to extact payable invoice using OCR or some inteligent reader?
Primarily I look for some algorithem (C# + OCR engine)/ philoshpy of payable invoice capturing but reference to some SDK with same feature or solid kind of commercial product would be helpfull too.
I googled and found Abbyy FlexiCapture Engine, IRIS Capture & Extract somewhat promissing but mostly are based on templates, or training. They claim that no template or training required but nothing looks 100 auto capture.
Kindly refere some product (at least with free trial), SDK  or Example/sample.

A: Of course, by 2018 the situation improved a bit. Let me recapitulate the main approaches today:

*

*Still a raw OCR engine (tesseract, Abbyy, Google OCR etc.) and regexes (this may still work just fine for some very limited use-cases)

*Abbyy FlexiCapture Engine - still going strong, but still based on templates, if you are willing to define one new template for each specific invoice format

*Rossum Elis (invoices), TagGun (receipts), ... - APIs based on pre-trained machine learning models, i.e. usable and working immediately, with free monthly volumes

*LucidTech, Itemize, ... - less accessible APIs with a similar functionality (you need to go through a demo and sales process)

*Datamolino, CloudFactory, ... - APIs with humans behind the scenes performing the data transcription manually (different latency, pricing and accuracy structure)

A: I did R&D and concluded that: There is no specialized SDK for invoice Capture that can automate it 95-100%. Only there are OCR/ICR and Imaging SDKs which can help to convert images into text/readable documents but rest of capturing/data extraction is solely based on custom search algorithems( as ilya-evdokimov mentioned above, you need mixup of steps(zonal ocr, full text ocr and then intelligent data extraction). I had studied some of very popluar products but they just claim auto capture but ultimately they just pul the standard invoice fields automatically but rest of work is same either zonal ocr or manual. This is what I suggest but there are many more improvement depending on the natuture applicaiton:

*

*Store the key field(e.g VAT# information for customers in database/xml file

*Do full page OCR, find key field, match to the customers list and identitfy/classify the type of document/image.

*Once document type (Invoice payable/recieveable etc) is identified then look for standard fields

*Allow user to create pre-defined templates for each type of document for each company(the sender of invoices).

*Compare the results of both algo (full text ocr and zonal) keep the one with better accuracy.

A: After more R&D (*) now there now actually are specialized SDKs with APIs:
First - for starters, there is demo at https://rossum.ai/developers
The whole extraction process can now be automated with API (https://docs.api.rossum.ai/) like this:
to upload an invoice:
invoice_file=$1
endpoint='https://all.rir.rossum.ai'
curl -H "Authorization: secret_key $ELIS_API_KEY" -X POST -F file="@$invoice_file;type=application/pdf" $endpoint/document

to download the results:
invoice_id=$1
endpoint='https://all.rir.rossum.ai'
curl -H "Authorization: secret_key $ELIS_API_KEY" $endpoint/document/$invoice_id

These bash examples are from https://github.com/rossumai/elis-client-examples/
(* to add, the API is a direct consequence of my own R&D work in the company ;) )


text:
Q: Scope of Popup and InteractionRequest in Prism I need clarification on when to use Pop-up, InteractionRequest. Here is my scenario.
I have left side navigation view which displays the Folder's in tree format (as same as Windows Directory). I should allow the user to Add, Rename and Remove the directory by using context menu. For Add and Rename operation, it should popup a window with "TextBox" for user input and should have "Save" and "Cancel" button. For Remove option, if should ask for confirmation.
What should i do for Add/Rename operation?

*

*Create simple Window (with user input TextBox , Save and Cancel Button) without ViewModel. Save and Cancel Button click will set the DialogResult flag and close the window.

*Create simple Window (with user input TextBox , Save and Cancel Button) with ViewModel.
Save and Cancel button click will be handled in ViewModel (This look bit tedious since very limited code).

*Is there any alternative way to handle this?
What should i do for Remove Operation?

*

*I will go for InteractionRequest

*I will go for Customized Window (Dialog) which will be called as like MessageBox, without popup or InteractionRequest(ie from view model => MyMessageBox.Show(.....) == Dialog.Ok..
please give me the right solution.

A: Since your Popup is so small, I would actually create a DataTemplate inside your current View and just bind the Add/Rename/Remove commands to the same ViewModel.
I like using my own custom Popup, because I've had many issues with WPF's popup's in the past. It is generally used like this:
<Grid Name="RootPanel">

    <DockPanel>
        <TreeView DockPanel.Dock="Right" />
        // <!-- Other Window Content -->
    </DockPanel>

    <local:PopupPanel
        local:PopupPanel.PopupParent="{Binding ElementName=RootPanel}"
        local:PopupPanel.IsPopupVisible="{Binding IsPopupVisible}"

        local:PopupPanel.BackgroundOpacity=".5"
        local:PopupPanel.PopupEnterKeyCommand="{Binding SaveCommand}"
        local:PopupPanel.PopupEscapeKeyCommand="{Binding CancelCommand}">

        // Put whatever you want for Popup Content here

        // Usually I have a property in my ViewModel for PopupContent, and
        // will put a ContentControl here that uses a different ContentTemplate
        // based on what type of object is in PopupContent
    </local:PopupPanel>

</Grid>


text:
Q: Finding Database Entries via Join Table So I have two resources, project and collective, with a has_many through relation via my join table projectships. My project resource of course has id as a column but also has unique_id as a column (its important). The projectships table has standard columns id, project_id, and collective_id except that project's unique_id is used for the join table's project_id.
What I want to do is pull all of the projects relating to a specific collective. Normally I would just use:
@projects = @collective.projects

but this doesn't work since my project_id column is populated by unique_id instead of project's id.
Any help would be greatly appreciated! Thanks!


text:
Q: How to create a stacked geom_bar with three columns of data? Looking for some help as to how to make a stacked bar plot using the following data:
DF <- data.frame(group = c("Pensioner", "Adult", "Teenager", "Child", "Toddler"),
                 Beach = c(30,20,35,10,5),
                 Park = c(40,15,20,25,10))

This is completely fictitious data, with values representing the percentage of people in each age class who were at the two locations. I just wish to understand how to make this sort of plot.
I am looking to make a plot with the x axis containing the labels 'beach' and 'park' with the fill representing the different values for each age group, which would feature in the legend. Essentially one which looks like this:

I have tried some coding with melt, but haven't quite got it right:
R_Edits.m <- melt(R_Edits,id.vars = "Group")

AgeSite <- ggplot(R_Edits.m, aes(x=Group, y=value, fill=Variable)) + geom_bar(stat="identity", position ="stack")

This produces a stacked barplot, but instead with the group at the bottom as opposed to being the fill,  and I am unsure how to reorganise this appropriately.
Any help would be appreciated.


text:
Q: Uncaught Error: Module name "twilio" has not been loaded yet Problem
I'm receiving an error in the terminal related to the require method when I'm looking to send a pre-done SMS message through Twilio. I've read other similar StackOverflow questions and I've tried to use include the CDN for RequireJS in my scripts section my index.html, alternatively npm installing Browserify, but I'm not sure why I'm still getting the error.
Error
Uncaught Error: Module name "twilio" has not been loaded yet for context: _. Use require([])
scripts.js
// Twilio Credentials
var accountSid = 'AC7*********';
var authToken = '6b6*********';

// Require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);

client.messages.create({
    to: "+16479933461",
    from: "+12044002143",
    body: "There is a new highest bidder. Visit {{websiteUrl}} to place another bid. All proceeds from the silent auction will go to the Samaritian House.",
    mediaUrl: "http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg",
}, function(err, message) {
    console.log(message.sid);
});

A: Twilio developer evangelist here.
According to the RequireJS errors page, when using RequireJS like this, you should use the asynchronous loading method, like this:
// Twilio Credentials
var accountSid = 'AC7*********';
var authToken = '6b6*********';

// Require the Twilio module and create a REST client
require(['twilio'], function(twilio){
  var client = twilio(accountSid, authToken);

  client.messages.create({
      to: "+16479933461",
      from: "+12044002143",
      body: "There is a new highest bidder. Visit {{websiteUrl}} to place another bid. All proceeds from the silent auction will go to the Samaritian House.",
      mediaUrl: "http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg",
  }, function(err, message) {
      console.log(message.sid);
  });
});

If this is in the terminal, can I ask why you are using RequireJS though? Node.js has require built in and synchronous.
I'm wondering if you are trying to use the Twilio module in the front end? If so, you shouldn't as you expose your account credentials which could be used to abuse your account. It's better and safer to perform Twilio API requests on a  server. That's what the Node.js module is for.


text:
Q: Getting false-positives in Magento when validating number of items to add to cart When a visitor enters a string in the quantity field of the "Add to Cart" input box, Magento doesn't throw an error, but instead accepts the string and interprets it as the quantity "1". How can I change this so that validation recognizes strings as invalid input? There already exists an onClick function on the "Add to Cart" button, so I don't think I can attach my own validation code to that button.

A: There is a setting at a product level which is called "Maximum Qty Allowed in Shopping Cart" that may be set to one.


text:
Q: How to understand conditional expectation w.r.t sigma-algebra: is the conditional expectation unique in this example? This board has many questions on how to understand conditional expectations w.r.t a $\sigma$-algebra; it's clearly a topic that confuses many. I am one of them. I read all the other questions and answers and I still don't understand the intuition behind it.
I have an example here that leads to the wrong answer, and I hope that by figuring out where I'm going wrong I can figure out more about how these conditional expectations work, and also why $E(\xi \mid \mathcal{H}) = \xi (\omega)$ when $\xi$ is $\mathcal{H}$-measurable.

Here I will follow the definition on wikipedia. Say we have:

*

*a probability space $(\Omega, \mathcal{F}, \mathbb{P})$

*a random variable $\xi : (\Omega, \mathcal{F}) \mapsto (X, \mathcal{B})$

*a sub-$\sigma$-algebra $\mathcal{H} \subseteq \mathcal{F}$, where $\xi$ is not necessarily $\mathcal{H}$-measurable (i.e. we cannot say that $\sigma (\xi) \subseteq \mathcal{H}$, where $\sigma(\xi)$ is the $\sigma$-algebra generated by $\xi$).

The conditional expectation of $\xi$ w.r.t $\mathcal{H}$, or $E(\xi \mid \mathcal{H})$, is not a constant number but a function $E(\xi \mid \mathcal{H}) : \Omega \mapsto X$. It is defined as any $\mathcal{H}$-measurable function $E(\xi \mid \mathcal{H}) : \Omega \mapsto X$ that satisfies:
\begin{equation}
\int _H E(\xi \mid \mathcal{H}) (\omega) d\mathbb{P} (\omega) = \int _H \xi (\omega) d\mathbb{P} (\omega)
\tag{1}\label{1}
\end{equation}
for any $H \in \mathcal{H}$.
It can then be shown that it is unique and equal to what I think is a Radon-Nikodyn derivative.
Finally, if $\xi$ is $\mathcal{H}$-measurable, we have that $E(\xi \mid \mathcal{H}) = \xi (\omega)$.

Now, if we then consider the following example: $\Omega = \mathbb{R}$, $X = \mathbb{R}$, $\mathcal{B} = \{\emptyset, X\}$, $\mathcal{H} = \{ \emptyset, \Omega\}$, and $\xi$ being any nice continuous function from the reals to the reals.
In this example, it seems obvious to me that $\sigma(\xi) = \{ \emptyset, \Omega\}$ and thus that $\xi$ is $\mathcal{H}$-measurable. Therefore $E(\xi \mid \mathcal{H}) = \xi (\omega)$.
But could I not also satisfy Equation \ref{1} by letting the conditional expectation be a constant? Something like:
\begin{eqnarray}
E(\xi \mid \mathcal{H})(\omega) & = \begin{cases}
\frac{\int _\Omega \xi (\omega') d\mathbb{P} (\omega')} {\int _\Omega d\mathbb{P} (\omega')} & \omega \in \Omega \tag{2}\label{2} \\
\text{anything} & \omega \in \emptyset
\end{cases}
\end{eqnarray}
So does this not mean that $E(\xi \mid \mathcal{H})(\omega)$ is not unique? Equation \ref{2} seems to be at odds with $E(\xi \mid \mathcal{H}) = \xi (\omega)$. So what did I do wrong here?
For example: does the standard definition for conditional expectations assume that the $\sigma$-algebra of the random variable is a Borel $\sigma$-algebra? I can see why the above would then be wrong.

A: You're not doing anything wrong in your example. However, you're operating outside of the 'usual' framework of conditions: most of the theory of expectations and conditional expectations assumes (not always explicitly) that the 'output' $\sigma$-algebra is the Borel one. (Incidentally, the notation $\mathcal{B}$ in your example is a bit confusing, as $\mathcal{B}$ is usually reserved for the Borel $\sigma$-algebra on the reals.)
In the context of your example, one problem is that any indicator function $1_A$ is measurable regardless of $A$, while normally when defining Lebesgue integrals we have $1_A$ being measurable iff $A\in\mathcal{F}$, which comes from assuming that the 'output' $\sigma$-algebra is the Borel one. That is to say, the definition of the integral assumes that the 'output' $\sigma$-algebra is the Borel one. So, I guess you can still define the expectation $\int _\Omega \xi (\omega) d\mathbb{P} (\omega)$ but be aware that this is implicitly assuming that the 'output' $\sigma$-algebra is Borel.
You can then define the conditional expectation, but the proof of uniqueness of the conditional expectation (up to sets of measure zero) assumes that the 'output' $\sigma$-algebra is Borel e.g. if you look at Section 9.5 in the book by Williams, Probability with Martingales, the uniqueness proof starts by considering two 'versions' of the conditional expectation $Y$ and $\tilde{Y}$ before considering the set $\{Y-\tilde{Y}>n^{-1}\}$ which is a member of the sub-$\sigma$-algebra in the context of the book, but does not necessarily belong to your $\mathcal{H}$. In your example, the conditional expectation is not unique: it can be any random variable that integrates to the same as $\xi$.
To get more intuition I'd suggest looking at the case where a random variable takes only finitely many values, which is covered in Section 9.1 of the same book.


text:
Q: Does Apple allow free apps with disabled features that, when clicked on, display a prompt to purchase content? I have been reading The Business of iPhone and iPad App Development: Making and Marketing Apps that Succeed (http://www.amazon.com/Business-iPhone-iPad-Development-ebook/dp/B004TMNSJK/ref=sr_1_2?ie=UTF8&qid=1340317546&sr=8-2&keywords=marketing+iphone+apps). The book is a little old (about a year at this point, which is a long time considering how long the app store has been around).
The book claims the Apple's iPhone development guidelines/rules state that an app must be fully functional. The book says that because of this rule, a "free" or "lite" version of an app cannot display buttons that appear to be functional but, when clicked on, prompt the user to purchase the full version of the app. For example, imagine a GPS app that has a button labeled "Give me turn-by-turn directions as I drive". If you click on the button, it just pops up a dialogue that says "Buy the full version to unlock this feature". According to this book, that app would be rejected by the Apple review team.
I have an app that allows users to download extra content with an in-app purchase. I would like to display the content as "grayed out". If the user clicks on the locked content, I want to display a popup that tells them how they can get the additional content. According to the book, this behavior will be rejected.
However, since this design is so important to my app, I've spent some time reading through all of the iPhone app guidelines, including the In-App Purchases guidelines, and I have found NOTHING that leads me to the conclusion that this sort of behavior is not allowed.
Since the app review process is currently sitting at about a week, I don't want to lose a full week of app purchases because of a rejection for this. Has anyone ever heard of this rule, and if so, can you please point me to it?
Thank you.

A: I had a "Free" or "Lite" app recently submitted (and accepted) to the App Store, where some UITextFields were greyed out and when touched, a UIAlertView was displayed . I don't know if this would be acceptable with buttons but it seems like more or less the same thing.

A: I think the book is probably right. Please check this link or read below.

The two most common reasons for application rejection are issues with core functionality and crashing. Core functionality encompasses the belief that customers rightfully expect all the features described in the marketing text and release notes to work as described, and likewise that all the buttons and menu items within the application will be fully functional (i.e., no grayed out buttons or notifications that a feature will be implemented later). Before you submit your app for approval, make sure that every aspect of your application is fully functional and that the marketing text and release notes correspond to the end user experience.


text:
Q: Http failure for getting base64 string This is my code:
getPhoto(employeeId: string): Observable<any[]> {
    const headers = new HttpHeaders({
      'responseType': 'json'
    })

    const url = `/Emps/GetPhoto`;
    const params = new HttpParams({
      fromObject: { employeeId },
    });
    return this.http.get<any[]>(url, { params, headers });
  }

And this is what is returned from that method:

data:image/svg;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgNDY4IDI4MCIgd
...

The method returns Success 200, however in console I get SyntaxError: Unexpected token d in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad, and the getPhoto subscribe debugger is never hit. What am I doing wrong?

A: The default response type for Angular HttpClient's GET method is json. Try to set the response type explicitly
return this.http.get<any[]>(url, { params, headers }, responseType: 'text' });

You could also use blob or arraybuffer if it's more appropriate to your requirement. It's type definition is as follows
responseType?: 'arraybuffer'|'blob'|'json'|'text'

Update 1: pushed responseType outside the options object


text:
Q: How can I handle Azure SAS Expiration? I have a game site on cloud and All member can access this games with Azure SAS URL.
I set expiration to be 20 minutes and I want to handle When the time is finished , I want to handle expiration and Redirect to user home page or Regenarate SAS Url .
Do you know any idea about this situation ?

A: The scenario you are describing will require some custom code to live on the Storage Service layer. Which is not supported. You typically know when the SAS expires, because you generated it. But can't know / understand when the end user of your Web Application uses this SAS.
A possible workaround is to make sure you renew this SAS and send it to the client with every (authenticated) request a browser will make to your app.
Another way to handle this, is to have a small jQuery/WebApi based module, which will live inside user's browser. That module will periodically require SAS from the Server. At best, the server will also return Expire time, so your client side script may handle this appropriately. On the client side before each request for a "game", your script shall check whether SAS Url is expired or not.


text:
Q: Eclipse JavaDoc dosen't generate @return automatically I think ${tags} can generate @param @return @throws automatically over a method.But my eclipse doesn't generate @return.What's wrong?
tags label
/**
 *
 * @param einvoiceUploadPDF
 * @return
 */
public Map<String, String> buildUploadParamMap(EinvoiceUploadPDF einvoiceUploadPDF) {
  Gson gson = new Gson();
  Map<String, String> paramsMap = new HashMap<String, String>();
  paramsMap.put("requestdatas", gson.toJson(einvoiceUploadPDF));
  return paramsMap;
}


text:
Q: Firebird 3.x error "Attempt to execute an unprepared dynamic SQL statement" in Delphi IBX exception handling? I am using Delphi 2009 Unicode and Firebird 3.x UTF8/dialect 3 database with IBX components. And now I see that all the exceptions raised from the Firebird SQL procedure and trigger code (e.g. using exception my_exception; statement) are handled by IBX as special Firebird exceptions:
Attempt to execute an unprepared dynamic SQL statement
Error Code: 335544711 SQL Code: -901

IBX does not report the name/code/content of the original Firebird exception. It is quite strange, because Delphi 2009 IBX can handle Firebird 2.1 UTF8/Unicode exceptions without problems. It seems to me that IBX is trying to do some extra steps that are not allowed.
Of course, I know that all the advices to move to other frameworks from the IBX, but we are not living in the ideal world, so, the question is as it is.
Question extended:
After initialization code in the project file (this is IB routine http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/IB_SetIBDataBaseErrorMessages.html):
SetIBDataBaseErrorMessages([ShowSQLCode,ShowIBMessage,ShowSQLMessage]);

I am getting normal error messages from the exceptions that are raised from the triggers, but I am still getting generic 'Attempt to execute...' error message in the case when exception is raised from the SQL procedure.
Question updated:
The generic exception about attempt appears when the procedure is called from the IBX TIBStoredProc, but if stored procedure is called (via select from...) from the TIBDataSet, then the right error message appears. So - there should be problem how TIBStoredProc handles the error messages.

A: Debug shows, that Delphi IBX code IBSQL.pas contains code:
SQLExecProcedure:
    begin
      fetch_res := Call(FGDSLibrary.isc_dsql_execute2(StatusVector, TRHandle,
                            @FHandle, Database.SQLDialect, FSQLParams.AsXSQLDA,
                            FSQLRecord.AsXSQLDA), False);
      if (fetch_res <> 0) then
      begin
        if (fetch_res <> isc_lock_conflict) then
        begin
           { Sometimes a prepared stored procedure appears to get
             off sync on the server ....This code is meant to try
             to work around the problem simply by "retrying". This
             need to be reproduced and fixed.
           }
          FGDSLibrary.isc_dsql_prepare(StatusVector, TRHandle, @FHandle, 0,
                          PByte(FProcessedSQL.Text), Database.SQLDialect, nil);
          Call(FGDSLibrary.isc_dsql_execute2(StatusVector, TRHandle,
                             @FHandle, Database.SQLDialect, FSQLParams.AsXSQLDA,
                             FSQLRecord.AsXSQLDA), True);
        end
        else
          IBDataBaseError;  // go ahead and raise the lock conflict
      end;
    end

and the error message about unprepared statement is raised exactly upon the second execution isc_dsql_execute2(...), so - maybe such second try is not necessary and we can raise Exception IBDataBaseError whenever the fetch_res is not 0? Maybe someone knows why Jeff introduced such second call and what bugs this second call tried to solve?
It appears, that Delphi XE 10.2 code makes the second call only in the specific case:
if (fetch_res = isc_bad_stmt_handle) then

And that makes the erroneous second call rare enough to solve the problem in my question. So, the solution is to replace the initial general condition (fetch_res <> isc_lock_conflict) with the more specific condition (fetch_res = isc_bad_stmt_handle).


text:
Q: HTML Character Identities in Twitter I'm developing a twitter app, and when I submit a new tweet from php with abrahams twitteroauth and with any special character it submits it to twitter as the HTML identity. I've tried all the html_entity_decode() and the htmlspecialchars_decode() but nothings working. Thank you :)
edit: heres some code as by request
(after logging in with oauth [which I know works] I'm doing this to submit the tweet)
$status = $_POST['status'];
$to->post('statuses/update', array('status' => html_entity_decode(stripslashes($status))));

A: Try:
html_entity_decode(stripslashes($status), ENT_QUOTES)


text:
Q: Решение системы нелинейных уравнений Matlab
Решал систему уравнений встроенным методом, однако получил в итоге только одну точку, вместо трех. Как найти остальные?
функция
function F= root2d(x)
F(1) = 0.5*(-17.76*x(1)-103.79*x(1)^2+229.62*x(1)^3-226.31*x(1)^4+83.72*x(1)^5)+x(2);
F(2) = 0.2*(-x(1)-1.5*x(2)+1.2);
end

и сам скрипт
fun = @root2d;
x0 = [0,0];
x = fsolve(fun,x0)

A: Говорится, что эта функция не приспособлена для нахождения нескольких решений, судя по этому ответу.
Но попадались такие описания (возможно более старые версии) с параметром maxsols, но сейчас такого параметра options просто нет.


text:
Q: Talend trest extractXMLField path I am trying to extract data from an API that setup like the below pic. I am only trying to extract the logs data. How would I go about Mapping on tExtractJsonFields. I keep getting Trying to output non-whitespace characters outside main element tree (in prolog or epilog) error
{<?xml version="1.0" encoding="UTF-8"?><root><status>success</status>
  <data>
     <story>
          <ID>BL0492PE</ID>
          <name>Atlas</name>
          <type>assessment</type>
          <app>
              <ID>pioneer</ID>
              <name>PS</name>
              <version>2.9.7</version>
          </app>
      </story>
     <logs>
       <firstname>Jan</firstname>
       <lastname>Doe</lastname>
         <country>********</country>
       <city>********</city>
 <status>
 <complete>true</complete>
   <updated>2021-10-25T13:04:45+02:00</updated>
     </status>
  </logs>
    <logs>
       <firstname>Peter</firstname>
       <lastname>Pan</lastname>
         <country>********</country>
       <city>********</city>
 <status>
 <complete>true</complete>
   <updated>2021-10-25T13:04:45+02:00</updated>
     </status>
  </logs></data><hash>1fda</hash><response_time>0.22277402877807617</response_time></root>}

A: Your "xpath Query" expressions does not seem correct, if I refer to the screenshot of your actual XML. It seems that you have inverted Column and XpathQuery.
Also, you won't access "complete" with this expression, you'll need to use "./status/complete".
To access logs directly, either use "//logs" or "/root/logs".

A: I was also suppose to select Body instead of string on tExtractXMLField xml field. Thank you


text:
Q: Product rule for Wirtinger derivatives? The Wirtinger derivatives are defined as:
Let $f(z)=f(x+iy)=u(x,y)+iv(x,y)$
Then
$$\frac{\partial f}{\partial  z}= \frac{1}{2}[\frac{\partial f}{\partial  x}-i\frac{\partial f}{\partial  y}]$$
$$\frac{\partial f}{\partial  \bar{z}}= \frac{1}{2}[\frac{\partial f}{\partial  x}+i\frac{\partial f}{\partial  y}]$$
Now what does the product rule look for these?

A: As usual, that is
$$ \partial_z (fg) = \partial_z f \cdot g + f \cdot \partial_z g $$
(the same for $\partial_{\bar z}$). For the proof note that the product rule is true for $\partial_x$ and $\partial_y$, we now have
\begin{align*}
  \partial_z (fg) &= \frac 12 \left(\partial_x (fg) - i \partial_y(fg)\right)\\
    &= \frac 12 \left( \partial_x f \cdot g + f \cdot \partial_x g
    - i  \partial_y f \cdot g -i f \cdot \partial_y g\right)\\
    &= \frac 12 \left(\partial_x f - i \partial_y f\right)g + f \cdot \frac 12 \left(\partial_x g - i \partial_y g\right)\\
    &=  \partial_z f \cdot g + f \cdot \partial_z g
\end{align*}
Along the same line of thought one proves
$$ \partial_{\bar z}= \partial_{\bar z} f \cdot g + f \cdot \partial_{\bar z} g$$


text:
Q: How to install tar.gz package to Yocto by adding new layer? I new to Yocto so there are probably some mistakes and misunderstanding that I've had, I appreciate if you can help.
So, I want to add a new package (tar file) to my custom image.
I have followed steps and steps in manual and some online instructions. While running: "bitbake mylayer", the layer is built fine but I got this error while building the image, here is the log file:
DEBUG: Executing python function rootfs_deb_bad_recommendations
DEBUG: Python function rootfs_deb_bad_recommendations finished
DEBUG: Executing python function extend_recipe_sysroot
NOTE: Installed into sysroot: []
NOTE: Skipping as already exists in sysroot: ['depmodwrapper-cross', 'apt-native', 'dpkg-native', 'pseudo-native', 'update-rc.d-native', 'prelink-native', 'makedevs-native', 'ldconfig-native', 'opkg-util$
DEBUG: Python function extend_recipe_sysroot finished
DEBUG: Executing python function do_rootfs
NOTE: ###### Generate rootfs #######
NOTE: Installing the following packages: apt busybox copy-uefiimg-to-sda coreutils dpkg e2fsprogs-resize2fs libfontconfig1 libfreetype6 libglib-2.0-0 gptfdisk libjemalloc2 kernel-module-axi-dma-sensor ku$
ERROR: Unable to install packages.
Reading package lists...
Building dependency tree...
Reading state information...
Package mypackage is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'mylayer' has no installation candidate

DEBUG: Python function do_rootfs finished
ERROR: Function failed: do_rootfs

And here is mylayer.bb:
SUMMARY = ""
LICENSE = "CLOSE"
FILESEXTRAPATHS_prepend := "${THISDIR}/files:"
SRC_URI += "file://mypackage.tar"

Also, I have included the package in conf/local.conf:
IMAGE_INSTALL_append += " mylayer"

So beside trying to figure out how to solve this problem, I also have some questions:

*

*I have read some example of .bb, and they mentioned about LIC_FILES_CHKSUM. The mypackage.tar.gz is a package to install a platform for the device and I don't know much about the source code, so I don't know if it is necessary to include the license? Or how to know that this package need license to install?

*In some answer I found online, there is one saying that I need to include PACKAGE_CLASSES ?= "package_deb" (they want to install the .deb file), so probably in my case I will need PACKAGE_CLASSES ?= "package.tar" right? I have tried to change variable, but it still not successful.

*The mypackage.tar includes some deb files. If I could not install mypackage.tar, can I instead install these .deb files? Can I put it all in mylayer.bb?
Thank you in advanced, I have tried to study much documents as I could but I get so confused and there is huge amount of information to digest.

A: First, before answering your questions
Let me mention some best practices advice for you:
Rename the recipe to some significant name related to you compressed package.
Naming the recipe to mylayer confuses Yocto users, because there is the term layer also.
Regarding you recipe:
There is no need for FILESEXTRAPATHS because the recipe path is added automatically to Yocto paths.
FILESEXTRAPATHS it is required for .bbappend files.
You need to override the do_install task function, it does nothing by default.
do_install is the first essential task to make sure that your sources are included in the final image.
Beside that, when specifying a compressed source file into SRC_URI, yocto automatically decompresses it.
This is mentioned here.
So, here what your recipe should look like:
SUMMARY = ""
LICENSE = "CLOSED"

# Prevent Yocto from decompressing the file
SRC_URI = "file://mypackage.tar;unpack=0"

do_install(){
    # Create the opt folder into the final image, ${D} is ${WORKDIR}/image
    install -d ${D}/opt
    # Copy the compressed file there; You can change permissions as you want
    install -m 0755 ${WORKDIR}/mypackage.tar ${D}/opt
}

# Very important to specify what you installed in (do_install)
FILES_${PN} = "/opt/*"

Now, when you run IMAGE_INSTALL_append += " mylayer" your file will be installed.
Regarding your questions:

*

*You mentioned that your compressed file contains .deb files, I assume that no license checksum is needed. Also, I understand that you may wanted to point to SRC_URI[md5sum] or other checksums for the full package. That is also not needed for local files, it is used to check for the integrity of online sources.

*PACKAGE_CLASSES as mentioned here, is used by the system to know in what type the data should be packaged. By the data I mean the data that you installed with do_install. That data get packaged for according to your PACKAGE_CLASSES variable, for example, to deb file. And that is used, along side with all other recipes packages, to build the final rootfs.

*Yes, if you are installing the tar file into the image and then unpack it to install all deb files, for example, with dpkg. You can use the bin_package class to do that, now the recipe must be changed for that reason:

*

*Decompress the tar file and provide the deb files in the local files folder.

*Add all deb files to SRC_URI

*Inherit the bin_package class

*Specify the files to be packaged.
Your recipe should look like this:
SUMMARY = ""
LICENSE = "CLOSED"

SRC_URI = "file://deb_file1.deb \
       file://deb_file2.deb"

# No need to `do_install` , it is invoked by the (bin_package) class

FILES_${PN} = ""

Important:
About FILES_${PN}, you need to add all what the deb installed into the image folder
Example, if your deb file installs this:
/usr/bin/hello
/etc/hello.cfg

Specify them:
FILES_${PN} = "/usr/bin/*"
FILES_${PN} += "/etc/*"

Use * so if other deb files install files into the same folder as others it will include all.


text:
Q: Load previous appsettings.json file if the current json file is not formatted properly var builder = new ConfigurationBuilder()
                 .AddJsonFile("appsettings.json", optional: true,
                    reloadOnChange: true).SetFileLoadExceptionHandler(ctx => {
                        //Load the previous working appsettings.json file if any
                     });

The above code loads appsettings.json which is in startup.cs. There is an option for users to modify appsettings.json file. If the modified file is not formatted properly I want to use the previous file.
Ex:
appsettings.json [Proper json format]

    {
      "Conn" : "Test"
    }

appsettings.json [Modified, not a proper json format]

    {
      "Conn"
    }

So, whenever user changes the appsettings.json the file is reloaded into application. Since, the modified json file is not formatted properly, it goes to SetFileLoadExceptionHandler. In the handler I would like to load the previous json file instead of modified file.
Is there a way to do it ?


text:
Q: How to initialize structs that are members of a class in c++98? The application is written in C++98, and I'm not in position to change it currently. The situation goes like this:
struct foo
{
    int x;
    int y;
    int z;
}

class myClass
{
    public:
        myClass();
        struct foo bar;
        int baz;
};

myClass::myClass() :
bar({0}),
baz(0)
{
    //something else.
}

int main(int argc, char** argv)
{
    myClass* thing = new myClass();
    cout << thing.bar.z << endl;  //want a guaranteed zero here.
}

The above works, but produces:
 warning: extended initializer lists only available with -std=c++11 or -std=gnu++11.

which is fully expectable. I can't do bar({0}) in the initializer list with c++98. Question remains what is the proper way to do it.
I can think of a couple ways that will work - memset, assign values field by field in constructor, assign using default copy constructor of the struct, etc. I don't know which way is considered 'most correct' in this situation though.