text:
Q: How to safely apply multiple axon event I am creating an application for learning purpose and in the application i am trying to raise multiple events  i want to know is it safe trigger/apply multiple events one after another
e.g. in my demo application  when user(lender) deposit loan cash i want to first deposit the amount to lender account and then withdraws from borrower account.  Below is the code i wrote
@CommandHandler
public void handle(LoanCashDepositCommand command) {
    LoanCashDepositedEvent event = LoanCashDepositedEvent.builder()
            .id(command.getId())
            .amount(command.getAmount())
            .build();

    AggregateLifecycle.apply(event);
}

@EventSourcingHandler
public void on(LoanCashDepositedEvent event){
    if(event.getAmount() > this.amount ) {
        FundsDepositedEvent fundsDepositedEvent = FundsDepositedEvent.builder()
                .id(this.lenderId)
                .amount(this.amount)
                .build();

        AggregateLifecycle.apply(fundsDepositedEvent);

        FundsWithdrawnEvent fundsWithdrawnEvent = FundsWithdrawnEvent.builder()
                .id(this.borrowerId)
                .amount(event.getAmount() -  this.amount)
                .build();

        AggregateLifecycle.apply(fundsWithdrawnEvent);

        AggregateLifecycle.markDeleted();
    }
    else{

        FundsDepositedEvent fundsDepositedEvent = FundsDepositedEvent.builder()
                .id(this.lenderId)
                .amount(event.getAmount())
                .build();

        AggregateLifecycle.apply(fundsDepositedEvent);

        FundsWithdrawnEvent fundsWithdrawnEvent = FundsWithdrawnEvent.builder()
                .id(this.borrowerId)
                .amount(event.getAmount())
                .build();

        AggregateLifecycle.apply(fundsWithdrawnEvent);

        this.amount -= event.getAmount();

        if(this.amount == 0) {
            AggregateLifecycle.markDeleted();
        }
    }
}

A: There is nothing wrong with applying multiple events inside the same @CommandHandler. In fact, that is quite normal I would say.
But, for your example/use case, it does not seems to be a simple apply but rather a Saga where you have to manage 2 different Aggregates (Account in your case) getting money from one and sending to another inside the same (distributed) transaction.
Also from your example, you should not apply inside an @EventSourcingHandler method but on the @CommandHandler as I said before.
If you need more help, I would recommend a small sample where we can see what you are trying to do and where you are having a hard time.

Edit 1: Here is a link for a hands-on Saga blogpost that can help you on this journey!
https://axoniq.io/blog-overview/sagas-in-practice


text:
Q: Re-sort orders to improve warehouse efficiency I am trying to optimize how orders are filled at my work. Right now, an employee just grabs the latest 16 orders(sometimes 14 or 18) and fills them.
I am trying to change it so that instead of simply going by the latest list of orders, that it orders them so each batch has order in similar locations. But I can't figure out how I should go about sorting the list.  Below is a simplified example of what I want to do.
Example Order List:

*

*order 1: 2 products in location E, 5 products in location Q

*order 2: 1 in location Z, 20 in location B

*order 3: 1 in location Y, 1 in location N

*order 4: 3 in location B

*order 5: 1 in location A, 10 in location E

*order 6: 1 in location A, 1 in location B, 5 in location Q

After sorting the list, I want order 2 and 4 next to each other, 1 and 6 next to each other, etc. Something like this:

*

*order 1: 2 products in location E, 5 products in location Q

*order 6: 1 in location A, 1 in location B, 5 in location Q

*order 2: 1 in location Z, 20 in location B

*order 4: 3 in location B

*order 3: 1 in location Y, 1 in location N

*order 5: 1 in location A, 10 in location E

I am using PHP, but any examples or hints in any language would be greatly helpfully.
Edit:
Let me try to explain this in better detail. Employees grab batches of orders and they they go fill the orders using a PDA with a barcode scanner. Our warehouse is set up so that location A is first, B is next and so on. There is no backtracking involved at all. Generally, they have to walk the whole warehouse to fill the batch of orders because on average, the 16 orders will have products from all of the locations.
If I change the sorting of which orders are being filled next from the date of the order to the location of the products of the order, then a batch of orders might only have locations A-G and wont have to walk the whole warehouse.
Another Edit(I really need to get better at posting good details)
Here is our current process:

*

*Picker grabs a cart with 16 buckets on it

*Picker scans the 16 unique bar codes from the buckets onto a webpage via a PDA(with scanner and wifi) and a 'picking ticket' is created

*The products are ordered by location (the picker only walks by any product once)

*The special webpage then tells the employee which product and how many to grab and they scan the bar code on the product

*Then it says which bucket to place the product in and they they scan the bar code on the bucket they are putting the product in

*After all the products are picked, Picker goes to the shipping station and scans in one of the buckets into a VB program (yes, eww I know. Someday that will get converted)

*Receipts are printed for all the orders in that 'picking ticket' and are placed into the correct bucket

*Each bucket is emptied and packaged up

*Picker now shipper places packaged order on a scale and scans the bar code on the receipt into a program.

*The correct postage is printed automatically and the order is marked as shipped and the customer is sent an email with tracking information

*Shipper puts postage label on the page, seals it up and puts it in the pile of finished packages

*At the end of the day, USPS and UPS pick up the shipments.

I should also note, that a lot/most of our products are small and a 16 order 'picking ticket' can have 500-800 individual pieces. Right now, we have about 28,000 different products in stock.

A: As I wrote in the comments on the question, I think you're just looking at the problem the wrong way.
Your description implies that they can go to all the locations before they have to "build"/finish the orders. The problem is that right now, things are grouped in terms of orders, so they try to fill Order #1 by going to all the locations that it requires, then they start looking at Order #2, etc.
Instead, you need to give them aggregated information in terms of the locations, and what they need to pick up at each one. Then they just go to all of the locations, in any order, and pick up everything they need from each one. When they've been to all locations, they go through the list and fill the orders from their big pile of stuff.
Let me know if I've made some incorrect assumptions here, and I'll try to come up with a different approach.

Just to try and clear up the difference, here's the employee's motion in each method (the first two are not definite, because they could have gone to locations in different orders, I just followed the exact order you listed in, as an employee probably would).
Original sort by date (12 moves):
E > Q > Z > B > Y > N > B > A > E > A > B > Q

Your re-sorted version (10 moves):
E > Q > A > B > Z > B > Y > N > A > E

By aggregating by location (7 moves):
A > B > E > N > Q > Y > Z

To further stress the difference, if I assume that all your locations are equidistant from the previous one (so moving from A to B has a cost of 1), and that you have one for each letter. Also assuming that you both want to start and end at location 0, you have:
Original sort by date: amount of movement = 138
Your re-sorted version: amount of movement = 138 (that's kind of surprising)
By aggregating by location: amount of movement = 52

A: I think the best solution here would be to seperate the picking and packing stage.
Here's how it works at my workplace

*

*Batch of orders is allocated
(generally based on delivery method
and/or website order is from)

*Picker gets assigned, pick slip
prints, containing list of products
and quantities (not specific to
order)

*Picker goes and picks, brings back
to station.

*Items are scanned on PC, going
through "checkout" process. This
makes sure that the picker has
picked everything correctly.

*Invoices are printed

*Batch goes to packing, each invoice
is scanned, followed by the items
for the order, packed, dropped in
shipping bin

*Cycle through orders

*Complete batch, emails/SMS are sent
to customers saying their order is
being dispatched

*Royal Mail/Other shipping company
come and take away the orders

We find that this works pretty well, espescially the confirmation at each stage.
We're currently re-implementing everything in PHP, and this is working pretty darn well for us.
My advice would be, rethink your workflow

A: The question seems to contradict itself - the first part before the edit deals with the ordering of the orders, whereas the edit talks about getting the correct batch of orders to give to a user.  I am going to assume your edit is more correct, and discuss batching more than ordering.
It sounds like that, at worst, the employee needs to walk all locations (A-Z, I'm assuming), then return back to A to begin their next batch of orders.  Given this assumption, it seems that you're simply trying to create batches wherein the maximum location is less than Z.  In other words, if you had six orders you were grouping into two batches, like this: [A, Y, B, G, Y, Z], you'd split them into [ABG] and [YYZ].  As such, I think the algorithm would be pretty simple:

*

*Run through each order and calculate the maximum distance item.

*Sort orders by maximum location.

*Return batches based on this sorting.

For example, suppose we have four orders that we want to make two batches from: (A, B), (A, Y), (F, G), (E, P).  We would then calculate their maximum distance items as [B, Y, G, P].  After sorting, we end up with [B, G, P, Y].  And thus the first batch would contain #1 and #3, and the second would contain #2 and #4.  The order that contains a Y was going to have to go all the way from A to Y anyways, so it makes no difference that it also requires an item from A; but by keeping #1 and #3 together, one of the employees walks a lot less.

A: By using usort, you can custom define your sorting method.  Such that, based on the array (list), you can compare the elements and put that array in the optimal order you wish, without being limited to simply the keys or values.  You can use the objects in the array itself, and determine what the order should be.

A: This is a complex problem, sounds like the traveling salesman.
What you can do is:
Create the list in all possible orders.
Calculate a score for each list based on how many connections there are between each row.
For example:
if order2 is followed by order6 the score would be 1, because 1 location(B) is overlapping. if the next order is order3 the score would be increased with 0, because neither Y or N is in order6.
The list with the highest score is in the optimal order.
For 18 elements in the list there are 18! = 6402373710000000 possible ways to order the list.
So I would create 10 a 20 lists in random order and pick the one with the best score.

A: You may be lacking focus here: too many details like what programming language you use, what kind of PDA/scanner end users use, etc.
All you need is one thing: a transitive comparison (<) operator for two elements (transitive meaning if A<B and B<C then A<C always).  If you have this operator, you have a sort.
Focus on this one thing and go back to your customer if necessary to discuss requirements.  If defining operator < is too complicated, chances are the customer won't be happy with the solution anyway.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google map v2 Marker drag and drop with Alert Android I have implemented movable marker in my map by setting dragchangelistner and setdraggable flag as true.
But when the user tries to drag and drop the marker, i want to show an alert with the message that do you want to update the marker position?
if user says OK then i do something on function onMarkerDragEnd() otherwise i want to move back the marker to its original position.
How can we do this?

A: Create a standard alert dialog that calls .show in the onMarkerDragEnd method. Save a reference to your objects position in onMarkerDragStart. For example:
LatLng markerOriginalPosition;

public void onMarkerDragStart(Marker marker) {
    markerOriginalPosition = marker.getPosition();
}

public void onMarkerDragEnd(Marker marker) {
dialog.show();

}

public void dialogPositiveAction() {
   // do nothing marker is already set
}

public void dialogNegativeAction() {
    // set back to original position
    mMarker.setPosition(markerOriginalPosition);
}

Either via callback or action you can set the positive and negative actions the will occur when a user makes their choice. If they like the new position, (positive action), then do nothing since the marker object is already there. If they want to return it back to the original position, set it to the original positions LatLng.


text:
Q: Using Amazon route53 for high availability Using Amazon Route53 DNS, is it possible to build a highly available setup pointing to multiple web servers not on Amazon? I don't need to worry about session stickyness.
Let's assume I have two web servers:
 web1 - 50.23.45.100
 web2 - 50.23.45.101

If I create two A records for mydomain.com. pointing to 50.23.45.100 and 50.23.45.101 with a TTL of 1 minute each, will this work?
How are requests sent when both web servers are up? Evenly? Only to web1?
When web2 goes down, can I have an automated script which deletes the A record for 50.23.45.101? Then when web2 comes back up, simple re-create the A record?
Thanks.

A: So, this is simple round robin technique.
In normal scenario, all your requests will be send in round robin fashion. When both web servers are up,  one client will get the first IP and the next client will get the second IP.
There are few DNS providers which provides the service of weighted load Balancing in DNS, but mostly are paid services.
The setup you are looking for, is fisible, but then there will be a downtime of around one minute, when any of your server goes down. Are you ready for this?
If yes, then it's possible and you can do that. Although I will recommend putting the TTL to be less than that, somewhere around 30 secs (in ideal scenarios, it should be 0 sec), so that your downtime can be decreased.
Though for better setup, what I will suggest that you can run a small instance and run some caching server on top of that, something like Varnish or nginx, which will increase the performance of your website drastically and on top of that, will provide you the facility of Load Balancing with zero downtime.


text:
Q: How to hide all tabs on default with jQuery accordion? I have implement Jquery accordian in my wesbite as shown here. I have enabled collapsible which allows me to collapse all tabs. But I'd like all tabs to be closed by default. Currently the first tab is open by default. How do I do that?

A: Just set the active option to false.

Boolean: Setting active to false will collapse all panels. This requires the collapsible option to be true.

http://api.jqueryui.com/accordion/


text:
Q: generalization of a chaining operator I know that the %>% operator allows one to input the LHS to the first argument of the RHS, (so that xxx %>% fun() is equivalent to fun(xxx,)) which allows us to "chain" functions together, but is there a way to generalize this operation so that I can pass the LHS to the "nth" argument of the RHS? I am using the R programming language.

A: You use the . to pass the LHS into the desired named argument on right.  If you want to replace 'hey' with 'ho' in 'hey ho' using gsub(pattern,replacement,text) then you could do any of the following. Note, %>% does not pass the LHS into the first argument of the function, but the first unnamed argument (see the third example below).
'hey ho' %>% gsub('hey','ho',.)
'hey ho' %>% gsub('hey','ho',text=.)
'hey ho' %>% gsub(pattern='hey',replacement='ho')


text:
Q: What happens when we dont specify 0dp for layout_width or layout_height when using layout_weight attribute? I have the following code from a project
         <LinearLayout
                android:id="@+id/linear"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/relative"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/label_friend_count"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:layout_weight="0.6"
                        android:gravity="end"
                        android:paddingTop="@dimen/padding_10dp"
                        android:text="@string/lbl_lead_count"
                        android:textColor="@color/color_grey_icon"
                        android:textSize="16sp" />

                    <TextView
                        android:id="@+id/txt_lead_count"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:layout_marginStart="@dimen/padding_10dp"
                        android:layout_weight="0.4"
                        android:gravity="start"
                        android:paddingTop="@dimen/padding_10dp"
                        android:textColor="@color/color_323232"
                        android:textSize="16sp"
                        android:layout_marginLeft="@dimen/padding_10dp" />
                 </LinearLayout>

Here both the TextViews don't specify the width as 0dp and specify the layout_weight attribute with values 0.6 and 0.4, According to the tutorials i have gone through 1st TextView with id label_friend_count should occupy 60% of the space and 2nd TextView with id txt_lead_count should occupy 40% of the space. But in this code First TextView occupies less space and 2nd TextView ocuupies more space... Can anyone tell me how is this possible? Is it because of not specifying layout_width as 0dp and when to use floating point values with layout_weight?
This is the Snapshot of my layout

A: add android:weightSum="1" to your LinearLayout and use 0dp width instead of match_parent in TextView to get your desired result
<LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:weightSum="1"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/label_friend_count"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_weight="0.6"
                    android:gravity="end"
                    android:paddingTop="@dimen/padding_10dp"
                    android:text="@string/lbl_lead_count"
                    android:textColor="@color/color_grey_icon"
                    android:textSize="16sp" />

                <TextView
                    android:id="@+id/txt_lead_count"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_marginStart="@dimen/padding_10dp"
                    android:layout_weight="0.4"
                    android:gravity="start"
                    android:paddingTop="@dimen/padding_10dp"
                    android:textColor="@color/color_323232"
                    android:textSize="16sp"
                    android:layout_marginLeft="@dimen/padding_10dp" />
             </LinearLayout>

A:
android:layout_weight Indicates how much of the extra space in the LinearLayout is allocated
  to the view associated with these LayoutParams. Specify 0 if the view
  should not be stretched. Otherwise the extra pixels will be pro-rated
  among all views whose weight is greater than 0.

Set  android:layout_width="0dp"
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal"
android:weightSum="1">

        <TextView
        android:id="@+id/label_friend_count"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="0.6"
        android:gravity="end"
        android:paddingTop="@dimen/padding_10dp"
        android:text="@string/lbl_lead_count"
        android:textColor="@color/color_grey_icon"
        android:textSize="16sp" />

        <TextView
        android:id="@+id/txt_lead_count"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginStart="@dimen/padding_10dp"
        android:layout_weight="0.4"
        android:gravity="start"
        android:paddingTop="@dimen/padding_10dp"
        android:textColor="@color/color_323232"
        android:textSize="16sp"
        android:layout_marginLeft="@dimen/padding_10dp" />

A: You can check this.
You can use the layout_width as wrap_content or 0dp.
The Default weightsum for layout is 1.
<LinearLayout
                android:id="@+id/linear"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/relative"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/label_friend_count"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:layout_weight="0.6"
                        android:gravity="end"
                        android:paddingTop="@dimen/padding_10dp"
                        android:text="@string/lbl_lead_count"
                        android:textColor="@color/color_grey_icon"
                        android:textSize="16sp" />

                    <TextView
                        android:id="@+id/txt_lead_count"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:layout_marginStart="@dimen/padding_10dp"
                        android:layout_weight="0.4"
                        android:gravity="start"
                        android:paddingTop="@dimen/padding_10dp"
                        android:textColor="@color/color_323232"
                        android:textSize="16sp"
                        android:layout_marginLeft="@dimen/padding_10dp" />
                 </LinearLayout>
 </LinearLayout>


text:
Q: What do the results of tuning β1, β2 in ADAM imply about the gradients or the data? For example:
If I have a simple 3-layer neural network that demonstrates better performance on the test set when the value of β2 is .95 when compared to the default .999 over several trials of cross-validation, is there any assumption that we can make about properties of the data or gradients?
Is there any literature on this matter?

A: No you cannot make assumptions on the data because of this. If you want literature on the matter I would suggest reading the original paper by Kingma. You should see the adam method solely as an optimizer. The optimizer often works better in certain classes of data. This does however not imply the converse: so tuning parameters does not necessarily mean that the data has certain characteristics.


text:
Q: Redirect to other html page and scrollTop: to a certain div It's been already asked, but the two given answers don't work for me.
Redirect to some other page then animate to reach a certain scrollTop
My html is something like:
html1:
<!doctype html>

       boxes

html2:
<!doctype html>

So I need when you click on  in html1 to go to  in html2
Thank you for the help !

A: That's what a url hash is for:
boxes

Browser will automatically scroll to the matching id


text:
Q: Coding issue with webview I've uploaded my app on the playstore and for me and the most majority of users everything works fine.
Some users,however, complained about latin accempted letters like àèìòù saying strange symbols appear in their place. On my phone these letters are successfully displayed and so on my friends' phones...I can't understand where is the problem!
I load my data like this:
view.loadData("<meta http-equiv=\"Content-Type\" content=\"text/html\"; charset=\"UTF-8\" />"+
                                            myText, "text/html", "UTF-8");

A: Solved thanks to @Sabre's link:

try adding <html></html> tags. Described here.


text:
Q: Why does Ipywidget slider update variable only if it's an item from a list? I created an ipywidget slider that, as you slide it, the image being displayed changes + the text displayed also changes. All images were previously stored in a list called image_data & same with the text, in a list called comp_scores. So, this works well (image/text change as slider is moved), but for some reason, when I call the "current_image" variable later- in another jupyter notebook cell-, it returns the original value ("1") which was set before I moved the slider, instead of the value that the slider was moved to.
However, when I set "current_image=[1]" (a list) and then interchange all "current_image" instances in the code below with "current_image[0]", and then I call current_image[0] later, it returns the updated value. Does anyone know why this is?
%matplotlib notebook
from ipywidgets import *
import numpy as np
import matplotlib.pyplot as plt

current_image=1
slider_fig = plt.figure(figsize=(4,2))
ax = slider_fig.add_subplot(1, 1, 1)
line = ax.imshow(image_data[current_image], cmap='gray')

n = widgets.Text(
    value= "Comp Value: " + str(round(comp_scores[0][current_image],1)) ,
    description='',
    disabled=True)

display(n)

plt.axis('off')

def update(image=current_image):

    current_image=image

    line.set_data(image_data[current_image])
    slider_fig.canvas.draw()

    n.value="Comp Value: "+ str(round(comp_scores[0][current_image],1))

s_range=(0,24,1)
interact(update,image=s_range)


text:
Q: How to print logs which have markers in them in logback using java I have a program in which I'm using slf4j with logback for logging and there is different type of logging pattern for clients and developers, like below:
if(userType.equals("clients")){
    encoder.setPattern("[%5level] - %date{dd MMM yyyy;HH:mm:ss.SSS} : %message%n");
}else{
    encoder.setPattern("[%5level] - %date{dd MMM yyyy;HH:mm:ss.SSS} [%thread]: %message%n");
}

But I cannot apply the above code using configuration file because it won't give me the feasibility to do it.
Now I have applied markers in the logs and want to print only those logs which have marker in them. And for that I need to use configuration file.
Is there any way in which I can print the logs with markers without using the configuration file.


text:
Q: VBA Calendar Control Different Versions Issue I've built a simple Excel tool that uses the additional Calendar Control(mscal.ocx). Everything worked out fine, on different systems, however, the calendar seems not to be implemented and instead of just not showing the date picker, the whole form crashes.
Is there a way to implement the calendar control so that it runs on every system? Or do I have to code a datepicker myself?
(Office12)

A: Whenever you're using controls that aren't native to all operating systems and versions of excel, you're asking for trouble on other computers. Often, when developing, you'll have access to forms that don't exist on most systems, and only exist on yours because you have Visual Studio installed, or a special Microsoft Office package. Whenever such a problem occurs you have 3 choices:

*

*Work your ass of to try and package the missing controls (mscal.ocx), and try to create a deployment script for your users which will copy it to the System32 directory and register it. This is a pain because there is usually a large chain of dependencies for a single control.

*Deal with the fact that some systems won't support your tool and warn users upfront or provide a virtual machine that they can access that and that your tool will run on.

*Reinvent whatever fancy control you're using with basic buttons, list-boxes, drop-downs, images, etc, which is the biggest pain of all and often requires you to compromise some nice functionality.
I've had to do number 3 countless times for excel 2007 tools that work on XP systems, but not Vista+ where certain ActiveX controls (i.e. Datagrid) are no longer supported.

A: i would build against Excel 10 (2003) as not everyone might have new Office 12 (2010).
or see if you can reference that ocx locally and deploy with your excel file

A: You can do this without the calendar controls.
Like this example here


text:
Q: split option using filename with extension Below we have two file name with .pdf extension. If I am splitting both file names, it gives wrong output. Any one have an idea on how to split both files using .pdf or any format?
I have placed code and the output I get.
dim ssfile() as string
Dim sscheck As String="Your Weekend (Supp. to Press and Journal, Aberdeen)_20140205_004.pdf,Your Weekend (Supp. to Press and Journal, Aberdeen) _11111111_004.pdf"
ssfile= sscheck .Split(".pdf,")

Output which I got follows:
ssfile(1)='Your Weekend (Supp'
ssfile(2)='to Press and Journal, Aberdeen)_20140205_004'
ssfile(3)='pdf,Your Weekend (Supp'
ssfile(4)='to Press and Journal, Aberdeen) _11111111_004'
ssfile(5)='pdf'

but I need an ouput as:
 ssfile(1)='Your Weekend (Supp. to Press and Journal, Aberdeen)_20140205_004.pdf'
 ssfile(2)='Your Weekend (Supp. to Press and Journal, Aberdeen) _11111111_004.pdf'

thank you

A: You need to set the correct overload of string.Split
ssfile= sscheck.Split(new string() {".pdf,"}, StringSplitOptions.RemoveEmptyEntries)

but afterwards, the first file loose its extension so you need to readd it
ssFile(0) = ssFile(0) & ".pdf"

By the way, your actual result seems to be the effect of having Option Strict set to Off in your project. This allows the implicit conversion of the first character of your string to a single char and thus the selection of the wrong Split overload (the one that takes just a single char).
I really suggest to change Option Strict to On for your project even if at first attempt you have many error to fix.

A:     if (args[0] != null) {
                    String path = System.getProperty("user.dir");
                    String fileName = args[0];

                    String nameOfFile[] = fileName.split("\\.(?=[^\\.]+$)");

                    if (nameOfFile[1].equals("docx"))
                        new DocToXmlConverter().processDocxToXml(path, nameOfFile[0]);
                    else if (nameOfFile[1].equals("doc"))
                        new DocToXmlConverter().processDocToXml(path, nameOfFile[0]);
                    else
                        throw new Exception("please provide Correct File Extension");
}


text:
Q: Import .csv data into class I have some code that saves data from a class to .csv files, but I am not sure how to read it back into a class so I can put it in a listview. Here is the code for the save:
        SaveFileDialog save = new SaveFileDialog();
        save.Filter = "Excel|*.csv";

        if (save.ShowDialog() == DialogResult.OK)
        {
            StreamWriter sw = new StreamWriter(save.FileName);
            try
            {
                sw.WriteLine("Name" + ";" + "Authors" + ";" + "Pages" + ";" + "Date" + ";" + "Price" + ";" + "Copies");
                foreach (Book b in bookList)
                {
                    string aux = "";
                    aux = string.Join(";", b.Authors);//I know I will probably need to change ';' here because it will have trouble reading it
                    sw.WriteLine(b.Name + ";" + aux + ";" + b.Pages + ";" + b.Date.ToString("dd.MM.yyyy") + ";" + b.Price + ";" + b.Copies);
                }
            }
            catch (IOException ert)
            {
                MessageBox.Show(ert.Message);
            }
            catch (Exception ew)
            {
                MessageBox.Show(ew.Message);
            }
            finally
            {
                sw.Close();
            }
        }

A: This is actually pretty easy. Lets assume you have the following class Book:
public class Book
{
    public string Name { get; set; }
    public int Pages { get; set; }
    public string AuthorName { get; set; }
}

Then you can simple read it like this:
var BooksFromCsv = from row in File.ReadLines(@"C:\books.csv").Where(arg => !string.IsNullOrWhiteSpace(arg) && arg.Length > 0).AsEnumerable()
                   let column = row.Split(';')
                   select new Book
                   {
                      Name = column[0],
                      Pages = column[1],
                      AuthorName = column[2],
                   };

The Result will be an IEnumerable<Book>. If you want a List or an Array just append an .ToList() or .ToArray().

A: If you only want to save your data persistent you could serialise and deserialise your object like this:
// SAVE
using (var fs = new FileStream(path, FileMode.Create))
{
      var xSer = new XmlSerializer(typeof(objecttype));
      xSer.Serialize(fs, myObject);
}

// LOAD
using (var fs = new FileStream(path, FileMode.Open))
{
     var xSer = new XmlSerializer(typeof(objecttype));
     myObject = (objecttype)xSer.Deserialize(fs);
}


text:
Q: Encoding UTF8 data within a table with latin1 character set I have a [legacy] mysql table with character set of "latin-1" but storing json information in "utf-8". A user interface is connected to this table which shows the characters correctly. I need to update this table using a python script but I can't get rid of encoding hell.
On mysql shell I issue "select words from pip where id_pip=42" and receive:
"ventilationsplåtslageri":{"day":"1000","hour":"200","min":"30"}

But when I tried to fetch it from database, I couldn't get the same encoding even though I try several different encodings.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
import json
dbconn = MySQLdb.connect(host="host",port=3306,user="user",
                passwd="pass",db="db", use_unicode=True, charset="utf8")
cursor1 = dbconn.cursor()
cursor1.execute("select words from pip where id_pip=42")
track = cursor1.fetchall()
print json.dumps(track, encoding="utf8" )

I tried many different configuarations on this code, e.g. I changed  "use_unicode=False, charset="latin1" with print json.dumps(filter_track, encoding="utf8" )  but I still get either "ventilationspl\u00c3\u00a5tslageri\" or "ventilationspl\u00e5tslageri\" and not what I want which is: "ventilationsplåtslageri"
I couldn't change the database and I need to update this field of database with sql update command, so I am afraid if I mess up the lagacy database.

A: I'm not sure if I understand your question, but...
If the content is being returned in Latin-1 and you want it in UTF-8, I would assume that you'd first need to decode the content from Latin-1 and then encode it to UTF-8.
latin1_content.decode('latin1').encode('utf8')


text:
Q: Updating a Code Signing Identity in Xcode 4.2 I am coding an iPhone app using Xcode 4.2.
My iPhone development provisioning profile expired. When I try to build and run my app on my iPhone, I get a message saying: Code Sign error: "Provisioning profile '(expired provisioning profile number)' can't be found"
I went to the iOS developer provisioning portal, renewed the provisioning profile, and downloaded it.
In Xcode I opened up the Organizer window. I deleted the expired provisioning profile, and added the renewed provisioning profile. (They both have the same name).
In my project Build Settings, under Code Signing Identity, I set the provisioning profile to the name that I want (which is the same as the expired profile name) and try to build, and I get the same error message, with the expired provisioning profile number. I can't find the renewed provisioning profile in the list that pops up when I click on the Code Signing Identity table cells in the Build Settings.
How do I set the Code Signing Identity to the Provisioning Profile that I want?

A: Try Clean all Targets and see if that helps.

A: The provisioning profile can be set for the "Project" and "Target" make sure you set them both.
Also delete all profiles and use automatic device provisioning in xcode to import profiles, which sounds like what you did.

A: Valid development profiles need to be installed on the device itself.  I have not had one expire so I am not sure if putting it in the organizer will cause it to be copied across.
You can check in your phone menu SETTINGS>GENERAL>PROFILES.  If it is still showing as expired then the updated one has not been copied across.  To copy it across open iTunes on your computer and go to the apps screen for your device, then drag the provisioning profile into there.  Once that is done resync your device and it should appear on your phone.


text:
Q: Let $p$ be a prime then which of the following are true? Let $p$ be a prime. Pick each correct statement from below. Upto isomorphism,

*

*there are exactly two abelian groups of order $p^2$.

*there are exactly two groups of order $p^2$.

*there are exactly two commutative rings of order $p^2$.

*there are exactly one integral domain of order $p^2$.

My try:
The number of abelian groups up to isomorphism, of order $p^2$ is equal to the partition of $2$. So 1 is correct. Again any group of order $p^2$ is abelian, hence 2 is also correct. But I am confused with 3 and 4. In case of 4, we know that there is a unique field of order $p^2$, and a field is an integral domain. But will this imply 4? Any hints/ answer will be helpful. Thanks.

A: For $4.$, a finite integral domain is a field.
For $3.$, think about $\Bbb Z/p^2\Bbb Z$, $\Bbb Z/p\Bbb Z \times \Bbb Z/p\Bbb Z$ and $\Bbb F_{p^2}$.


text:
Q: Passing data between components in React/Redux I'm new to React and am trying to build an app which shuffles football players into two teams and am having difficulty with passing data from one component to another.
I have redux and react-redux installed.
In my reducer.js, I take a list of players and shuffle them, adding the shuffled list to state:
const shufflePlayers = (state) => {
  return {
    ...state,
    shuffledList: [
      ...state.playersList.sort(() => Math.random() - 0.5)
    ]
  }
}

Then in 'src/components/DisplayTeams.index.js', I map the 'shuffledList' array to props:
import { connect } from "react-redux";
import DisplayTeams from "./DisplayTeams";

const mapStateToProps = (state) => {
  return {
    shuffledList: state.shuffledList,
  };
};

export default connect(mapStateToProps)(DisplayTeams);

and finally, in 'src/components/DisplayTeams.js', I attempt to render the 'shuffledList' array in a list:
import React from 'react';
import '../../App.css';

const DisplayTeams = ({ shuffledList }) => (

      {shuffledList.map((player, index) => (

{player.name}

      ))}

);

export default DisplayTeams;

but am getting TypeError: Cannot read property 'map' of undefined, indicating that the 'shuffledList' array is empty or not set at all.
Any help will be much appreciated!!

A: Two things:

*

*You should add add an initial state, you can set it directly in the reducer file
 const initialState = {
     // other reducer parts here
     shuffledList: []
 }

*The reducer should check the action type, otherwise it would run at any action. Something like this:
 const shufflePlayers = (state = initialState, action) => {
    switch (action.type) {

       case actionTypes.SHUFFLE_LIST: {
           // use a new array, avoid mutating the previous state
           const sortedList = [...state.playersList].sort(() => Math.random() - 0.5)

           return {
               ...state,
               shuffledList: sortedList
           }
       }

 }

A: You should not copy data in state, the list and shuffledList are the same data but shuffledList is a calculated result of list.
You can use a selector to calculate shuffled list from list instead to prevent it from re calculating on renders you can use reselect (should use that anyway) and memoize shuffled result as long as list doesn't change.

const { Provider, useSelector } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;
const { createSelector } = Reselect;

const initialState = {
  list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
};
const reducer = (state = initialState) => state;
//selectors
const selectList = (state) => state.list;
//if state.list changes then it will shuffle again
const selectShuffledList = createSelector(
  [selectList],
  (list) => [...list].sort(() => Math.random() - 0.5)
);
const selectTeams = createSelector(
  [selectShuffledList, (_, size) => size],
  (shuffledList, teamSize) => {
    const teams = [];
    shuffledList.forEach((item, index) => {
      if (index % teamSize === 0) {
        teams.push([]);
      }
      teams[teams.length - 1].push(item);
    });
    return teams;
  }
);
const selectTeamsCurry = (teamSize) => (state) =>
  selectTeams(state, teamSize);
//creating store with redux dev tools
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(() => (n) => (a) => n(a))
  )
);
const App = () => {
  //you can re render app with setCount
  const [count, setCount] = React.useState(0);
  //setting count has no effect on teams because
  // state.list didn't change and selectShuffledList
  // will use memoized shuffled result
  const teams = useSelector(selectTeamsCurry(3));
  return (

      <button onClick={() => setCount((w) => w + 1)}>
        re render {count}
      </button>

{JSON.stringify(teams, undefined, 2)}

  );
};

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

A: The above code looks fine. You can check the shuffledList in the initial state and also in the Redux store while dispatching actions.


text:
Q: Adding Firebase reduces app overall speed I have built an app that searches for books using Google Books API. Its' functionality stands in a search bar that queries for some particular books and them displays them in a Listview.
I then decided to add Firebase as a cloud backend for my app.
Note: Before adding Firebase my app took around 1 sec to retrieve information and display searched books in the ListView (for first search) and approx. 500ms to any after searches.
After implementing Firebase(added sign up and log in activities and xmls that lead to the main activity that actually searches for books) I started to experience unpleasant waiting time.
From couple of seconds for a simple log-in to around 5 seconds for first query and display (of books) and 4 seconds for any after queries and displays of books (that is around 5 times slower comparing to older version of the app without Firebase).
I am posting the App-level Build.gradle file for info purposes:
apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
    applicationId "com.example.android.booktrade_v10"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
 }
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-database:9.4.0'
compile 'com.google.firebase:firebase-auth:9.4.0'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Do you guys have any ideas why my app started being so slow?
Any help is appreciated.

A:
After implementing Firebase (added sign up and log in activities

These operations require that the Firebase SDK connects to its servers, validates the user account, and creates a token. This takes time.


text:
Q: MVC Forms Authentication and Session, Authorize Issues I have a MVC project that I'm using Forms Authentication, and I had to implement Roles for certain pages, so I got this in global.asax:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie == null || authCookie.Value == "")
    {
        return;
    }

    FormsAuthenticationTicket authTicket;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }

    string[] roles = authTicket.UserData.Split(';');

    if (Context.User != null)
    {
        Context.User = new GenericPrincipal(Context.User.Identity, roles);
    }
}

And I save the user roles when I log in my model:
//After checking login/password
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (cookie == null)
{
    cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
    HttpContext.Current.Response.Cookies.Add(cookie);
}

string userRoles = null;
if (users[i].PerfilID == UserRanks.Admin)
{
    userRoles = "Admin;Users";
}
else
{
    userRoles = "Users";
}

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0,
    users[i].Name,
    DateTime.Now,
    DateTime.Now.AddDays(1),
    false,
    userRoles,
    FormsAuthentication.FormsCookiePath
);
cookie.Value = FormsAuthentication.Encrypt(ticket);

HttpContext.Current.Response.Cookies.Set(cookie);
HttpContext.Current.Session["UserID"] = users[i].UserID;
HttpContext.Current.Session["LastLogin"] = users[i].LastLogin;
HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, userRoles.Split(';'));

To retrieve the values of the session variables, I have a static property:
public static int UserID
{
    get
    {
        object sessionData = HttpContext.Current.Session["UserID"];
        if (sessionData == null)
        {
            //I had something here...
            return 0;
        }

        return Convert.ToInt32(sessionData);
    }
    private set { }
}

Before I implemented roles authorization, I used to save the UserID in the cookie userData, and if the UserID in the session, when requested, was null, I'd retrieve it from the cookie instead (and set it to the session again).
Now the userData is being used to the roles management and I'm having issues with the session dropping faster than the cookie expiration, and I have users logged in which I can't retrieve their UserIDs and thus fails for all operations.
So I have to put a checker in each controller function such as:
if (MyUser.Session.UserID == 0)
{
    //redirect to Login
}

...which defeats the whole purpose of using [Authorize] I guess.
Is there a better way to handle login expiration and session variables like this?
I thought about using JSON or some other format and save a bunch of userData in the cookie, but I'd like something simpler, if possible.
Also, I'm doing this in the login:
HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, userRoles.Split(';'));

Which seems to be about the same the AuthenticateRequest does (I got that part from elsewhere, seemed to be the recommended way to handle member roles), but it doesn't work like it should. The user always gets redirected out on the [Authorize(Roles="Admin")] or even the [Authorize] only functions if I leave only that (and remove the global.asax part). Why?


text:
Q: Returning large object from method runs 100x slower in production environment I have a model for which I store a fairly large serialized object as one of its attributes.
When passing this object from one method to another i production environment, as can be seen from the logs below, takes a lot of time (100x to be precise).
Weird thing is, it doesnt occur in development environment, only production. Also it happens during an ajax request, but not sure if it's relevant
This is the piece of code invoking the method
    now = Time.now
    price_document  = self.applied_price_document
    Rails.logger.info "cp_id: #{self.id} self.try :applied_price_document (2) #{Time.now - now} "

Which logs 1.06 seconds
I then tried to log each instruction in that method to find the bottleneck, and it turns out there is none as can be seen from the logs
  def applied_carrier_product
    start = Time.now
    ancestors = CarrierProduct.find_carrier_product_ancestors(carrier_product_id: self.id).includes(:carrier_product_price).references(:carrier_product_price)

    parent    = ancestors.select{ |cp| cp.id == self.carrier_product_id }.first
    until parent.nil? || ancestors.empty?
      is_successful = parent.carrier_product_price.try('successful?')

      if is_successful
        Rails.logger.info "cp_id: #{self.id} end #{Time.now - start} "
        return parent.carrier_product_price
      end

      parent = ancestors.select{ |cp| cp.id == parent.carrier_product_id }.first

    end
  end

Just before returning the result, i log the total running time of the method, which results in 0.002 seconds.
This means that it takes about 1 second to pass the result to the invoking method. Given I call this methods up to 30 times in a row, this is a big problem
any idea as to why this is?


text:
Q: HTML5 video error handling I need to tell, whether video cannot be played ("x" sign is shown in browser).
This code does't works. "onerror" event will never be fired under Firefox
var v = document.getElementsByTagName("video")[0];
    if ( v != undefined )
        v.onerror = function(e) {
            if ( v.networkState == v.NETWORK_NO_SOURCE )
            {
                // handle error
            }
        }

What's wrong here ?

A: It's good to know that Chrome and Firefox have different onerror callbacks. The error must therefore be mapped. Mozilla uses error.originalTarget.
Here is a sample on how to do it with pure JavaScript:

const file = 'https://samples.ffmpeg.org/MPEG-4/MPEGSolution_jurassic.mp4';

window.fetch(file, {mode: 'no-cors'})
.then((response) => response.blob())
.then((blob) => {
  const url = window.URL.createObjectURL(blob);
  const video = document.createElement('video');

  video.addEventListener('error', (event) => {
    let error = event;

    // Chrome v60
    if (event.path && event.path[0]) {
      error = event.path[0].error;
    }

    // Firefox v55
    if (event.originalTarget) {
      error = error.originalTarget.error;
    }

    // Here comes the error message
    alert(`Video error: ${error.message}`);

    window.URL.revokeObjectURL(url);
  }, true);

  video.src = url;
  document.body.appendChild(video);
});

The above example maps an incoming error event into a MediaError which can be used to display an error playback message.

A: To catch error event, you should use video.addEventListener():
var video = document.createElement('video');
var onError = function() { // your handler};
video.addEventListener('error', onError, true);
...
// remove listener eventually
video.removeEventListener('error', onError, true);

Note that the 3rd parameter of addEventListener (on capture) should be set to true. Error event is typically fired from descendants of video element ( tags).
Anyway, relying on video tag to fire an error event is not the best strategy to detect if video has played. This event is not fired on some android and iOS devices.
The most reliable method, I can think of, is to listen to timeupdate and ended events. If video was playing, you'll get at least 3 timeupdate events. In the case of error, ended will be triggered more reliably than error.

A: "onerror" is not a valid event type for <video>
Use "error" instead.
document.getElementsByTagName('video')[0].addEventListener('error', function(event) { ... }, true);

For a complete list of events for <video> go here: https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox

A: From Firefox 4 onwards, the 'error' event is dispatched on the <source> element.
And you should add an error handler on the only/last source:
HTML
<video id="vid" controls>
  <source src="dynamicsearch.mp4" type="video/mp4"></source>
  <source src="otherdynamicsearch.avi" type="video/avi"></source>
</video>

JS
var v = document.querySelector('video#vid');
var sources = v.querySelectorAll('source');

if (sources.length !== 0) {
    var lastSource = sources[sources.length-1];

    lastSource.addEventListener('error', function() {
        alert('uh oh');
    });
}

JQuery
$('video source').last().on('error', function() {
    alert('uh oh');
});

AngularJS
You can create an error handling directive (or just use ng-error):
<video id="vid" controls>
  <source src="dynamicsearch.mp4" type="video/mp4"></source>
  <source src="otherdynamicsearch.avi" type="video/avi" ng-error="handleError()"></source>
</video>

Where the error handling directive's link function should do (copied from ng-error):
element.on('error', function(event) {
    scope.$apply(function() {
        fn(scope, {$event:event});
    });
});

A: Try adding the event listener to the  tag instead - I think the onerror attribute ("error" event) works on the source tag now, not the video tag.

A: Pug example
video(src= encodeURI(item.urlVideo), type='video/mp4'  onerror="myFunction('param',this)")
script(src='/javascripts/onerror.js')

function myFunction(param, me) {
    console.log(me);
    me.poster = './images/placeholder.jpg'; }


text:
Q: Docker for PHP - 403 Forbidden Today I decided to move from Vagrant to Docker but I get a 403 Forbidden error when accesing localhost:8080.
My file structure:
learning-php // root folder
  dockerconfig
    virtualhosts.conf
  web
    index.php
  docker-compose.yml

This is my docker-compose.yml file:
web:
  image: php:7.0-apache
  ports:
    - "8080:80"
  volumes:
    - .:/var/www/html
    - ./dockerconfig/virtualhosts.conf:/etc/apache2/sites-enabled/virtualhosts.conf
  links:
    - mysql
mysql:
  image: mysql:5.7
  ports:
    - "3307:3306"
  environment:
    MYSQL_ROOT_PASSWORD: 123456
    MYSQL_USER: dev
    MYSQL_PASSWORD: 123456
    MYSQL_DATABASE: mydb

And this is my dockerconfig/virtualhosts.conf file:
<VirtualHost *:80>
  ServerName localhost
  DocumentRoot /var/www/html/web
  DirectoryIndex index.php

  <Directory /var/www/html/web>
    AllowOverride All
    Require all granted
    Options FollowSymLinks
    <IfModule mod_rewrite.c>
        Options -MultiViews
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ index.php [QSA,L]
    </IfModule>

  </Directory>

</VirtualHost>

And in my index.php is just a call to phpinfo.
I use Windows 10 as my OS.
Please help me find where could be the problem.


text:
Q: Build a matrix from vectors in Fortran95 By using the following code, I am trying to build a 3*3 matrix, but unable to do so. Any help will be appreciated.
program array

  implicit none
  integer i, a(5), b(5), a1(5), a2(5), a3(5)
  integer, dimension (5,5) :: mat1

  a = [0,1,2,3,4]
  b = [1,2,2,2,1]

  i = 0
  do i = 1,5
    a1(i) = a(i)*a(i)
    a2(i) = a(i)
    a3(i) = 1
    print*, a1(i), a2(i), a3(i)
  end do

  do i=1,5
    mat1(i,:) = [a1(:,i),a2(:,i),a3(:,i)]
    print*, mat1
  end do

end program array

In my output, I am expecting to have a 5*3 matrix having as [a1; a2; a3]. But, I am getting the following errors.
$ gfortran -Wall -c "HW1.f95" #(in directory: Y:\Fortran & subroutines)

HW1.f95:28.20:
mat1(:,i) = [a1(:,i);a2(:,i);a3(:,i)]
                1
Error: Syntax error in array constructor at (1)
HW1.f95:28.26:
mat1(:,i) = [a1(:,i);a2(:,i);a3(:,i)]
                      1
Error: Invalid character in name at (1)
HW1.f95:28.34:
mat1(:,i) = [a1(:,i);a2(:,i);a3(:,i)]
                              1
Error: Invalid character in name at (1)
Compilation failed.

A: Put the three length-5 arrays (a2,a2,a3) into a single length-15 array and use RESHAPE:
program fill_mat1
    integer, dimension(5,3) :: mat1
    integer, dimension(5)   :: a1,a2,a3
    integer, dimension(15)  :: a123

    a1 = (/  1, 2, 3, 4, 5 /)
    a2 = (/  6, 7, 8, 9,10 /)
    a3 = (/ 11,12,13,14,15 /)
    a123(1:5)   = a1
    a123(6:10)  = a2
    a123(11:15) = a3
    mat1 = RESHAPE(a123,mat1)
end program

RESHAPE takes the values from a123 and fills them into the shape of mat1 in Fortran standard order. There are also options for ordering the values, and for padding when the number of elements between the list and the shape do not agree. This is all covered in documentation of the RESHAPE intrinsic.

A: There are two reasons for the compilation to fail in your program

*

*You said you are

expecting to have a 5*3 matrix

For that you need to either declare mat1 to be a 5*3 matrix in your declaration like
integer, dimension (5,3) :: mat1

or by only writing on the first three entries later on, like
do i=1,5
  mat1(i,1:3) = [a1(i),a2(i),a3(i)]
  print*, mat1
end do

Thes second opiton would still leave you with a 5*5 matrix but it would only be filled in the first tree columns.

*You declared a1,a2 and a3 to be one dimensional. As @francescalus already pointed out in the comments you are trying to access there arrays like they have two dimensions, which doesn't work. This is a possibility
mat1(i,1:3) = [a1(i),a2(i),a3(i)]


text:
Q: How to call instances by type and most recent date rails I have blog post that I want to put on 2 different show views. I want the 4 most recent post to show but all of my post are 1 of 2 different :post_types (manager or user). So i want 1 view to show the 4 most recent manager post and the other view to show the 4 most recent user post. Where should I put this logic, the controller or somewhere in the model and how do I make a method to get the 4 most recent post of each type?
Currently i have this in the controller
def index

  @blog1 = Post.order(:date => :desc).first
  @blog2 = Post.order(:date => :desc).offset(1).first
  @blog3 = Post.order(:date => :desc).offset(2).first
  @blog4 = Post.order(:date => :desc).offset(3).first

end

But it doesn't separate the post by type

A: This will do the job:
def index
  @manager_posts = Post.where(post_type: 'Manager').order('date DESC').limit(4)

  @user_posts    = Post.where(post_type: 'User').order('date DESC').limit(4)
end

Then in your view
<% @manager_posts.each do |manager_post| %>
  <%= manager_post.content %>
<% end %>

<% @user_posts.each do |user_post| %>
  <%= user_post.content %>
<% end %>

A: This seemed to get it
@blog1 = Post.where(:post_type == 'Manager' ).order(:date => :desc).first


text:
Q: How to save the result of a comparison using Django's 'with' template tag? I would like to create new variable in django template, which will have a value of comparison
obj.site.profile.default_role == obj

Unfortunately none of this code works:
{% with obj.site.profile.default_role==obj as default %}{% endwith %}

{% with default=obj.site.profile.default_role==obj %}{% endwith %}

What is the proper syntax?

A: with can take just a "plain" context variable.
You could try assignment-tags instead, passing your params to it.
@register.assignment_tag
def boolean_tag(default_role, obj):
    return default_role == obj

and in the template
{% boolean_tag obj.site.profile.default_role obj as my_check %}

This solution is good if variable is used in one template block (like the case of yours, when you try using with). If you need variable in several page blocks, adding it to page context with include tag is better

A: with tag have no support for value evaluation.
The only possible template-only solution that I can imaging is to split part of html to sub-template and use {% include %} tag
{% if obj.site.profile.default_role==obj %}
    {% include 'subtemplate.html' with default=True %}
{% else %}
    {% include 'subtemplate.html' with default=False %}
{% endif %}


text:
Q: What is the /proc/self/cmdline / GetCommandLine equivalent on Mac OS X? How can I access the command line on Mac OS X without using argc, argv? On Linux, I would simply read /proc/self/cmdline or use GetCommandLine on Windows, but I can't find the equivalent for Mac OS X.

A: There are functions called _NSGetArgv and _NSGetArgc in crt_externs.h. However, wouldn't it be simpler to just store the argc/argv in a variable at the start of main and be portable to all three platforms?
NOTE: These functions are not directly documented, but they are mentioned in the documentation for NSApplicationMain in the Application Kit Functions Reference, and the related _NSGetEnviron is mentioned in the environ(7) manpage.


text:
Q: How Can I Implement Isotope Filtering with URL Hashes? (Though this mentions Wordpress throughout, I don't think this is a Wordpress specific problem)
I am working on a personal website using Wordpress and one of the packages that the theme uses is Isotope by Metafizzy. This is for filtering posts on the page with links.
You can see the page here
I wanted to try implementing something similar to mypoorbrain.com where the page is filtered with URL hashes. The advantage of this is that if the user is one another page, he can navigate to http://www.mypoorbrain.com/#illustration and still end up on the filtered content.
I went through the Isotope docs and there is a section for implementing URL hashes and this is the code I'm inserting before the closing <head> tag:
<script>
  function getHashFilter() {
    var hash = location.hash;
    // get filter=filterName
    var matches = location.hash.match(/filter=([^&]+)/i);
    var hashFilter = matches && matches[1];
    return hashFilter && decodeURIComponent(hashFilter);
  }
  $(function() {

    var $grid = $('.isotope');

    // bind filter button click
    var $filters = $('#filters').on('click', 'button', function() {
      var filterAttr = $(this).attr('data-filter');
      // set filter in hash
      location.hash = 'filter=' + encodeURIComponent(filterAttr);
    });

    var isIsotopeInit = false;

    function onHashchange() {
      var hashFilter = getHashFilter();
      if (!hashFilter && isIsotopeInit) {
        return;
      }
      isIsotopeInit = true;
      // filter isotope
      $grid.isotope({
        itemSelector: '.selector col-md-6 col-lg-4',
        filter: hashFilter
      });
      // set selected class on button
      if (hashFilter) {
        $filters.find('.is-checked').removeClass('is-checked');
        $filters.find('[data-filter="' + hashFilter + '"]').addClass('is-checked');
      }
    }

    $(window).on('hashchange', onHashchange);
    // trigger event handler to init Isotope
    onHashchange();
  });
</script>

But this does nothing.
I think the issue here is with correctly selecting the div elements (both links and the elements being sorted). From what I could guess using inspect element, the code for selecting the entire items grid is .selector col-md-6 col-lg-4', and the code for finding the filter buttons(or links) is var $filterButtonGroup = $('.m-filters');  but like I said, this does nothing.
What am I doing wrong? How can I make sure that the filters appear as hash links in the address bar?

A: There are several steps to the solution:

*

*There is no element with the class .isotope, so add this class to the parent (the .row element).

*The inline style you set to the children conflicts with the style isotope suppose to set, remove it.

*You listen to click events on the a elements while the data-filter is on the lis. So change the event listener to $('#filters').on( 'click', 'li',.. (You can also bind the click event in a different way but it's out of this answer's scope).

*You don't need the itemSelector option (when you call to $grid.isotope) since you want to filter the direct children which is the default behaviour. BTW, .selector col-md-6 col-lg-4' is invalid selector. If any, it should be .selector.col-md-6.col-lg-4'.

I gather all these changes in the following commit: https://github.com/moshfeu/isotope.js/commit/62b9798871e9452ade26d6e2863699869b8cb612.


text:
Q: Does anyone know a good free SHA1 hash generator? Does anyone know a good free SHA1 hash generator? I am trying to has some info on the client side before post it back. I need a free SHA1 hash generator.
Thanks

A: There's a javascript implementation here.

A: The sha1sum command is included with many Linux distributions.  In CentOS 5.5, it's part of the coreutils package.


text:
Q: Image Compression without changing the resolution of an image in swift I am trying to compress an image using following method

jpegData(compressionQuality:)

In this case image got compressed but the resolution of an image also got changed. But i actually want only image will compress without changing the resolution. Please suggest the possible solutions.

A: extension UIImage {

    public func base64(format: ImageFormat) -> String? {
        var imageData: Data?
        switch format {
        case .png: imageData = UIImagePNGRepresentation(self)
        case .jpeg(let compression): imageData = UIImageJPEGRepresentation(self, compression)
        }
        return imageData?.base64EncodedString()
    }
}

use this extension to compress the image, i have been using this extension from a long time, try it if it does not affect the resolution.


text:
Q: jQuery $("#form").submit not working in FF and Chrome (works OK in IE) I've seen this same problem discussed elsewhere, but none of the fixes I've found so far solve my paticular problem:
I'm using $.post inside $(#form).submit to submit the form via AJAX so the user doesn't leave the page.  It works just dandy in IE, but both FF and Chrome refresh the current page with the form field name and value in the querystring, probably because the form has no action="" specified.  I can get IE to duplicate the problem if I rename the function that is specified in , because then IE can't find the function to correctly perform the $.post and it also will refresh the current page with the form field name and value in the querystring.
The form is dynamically created, and needs to have the random number in the form name so that more than one form can be visible at a time.  I don't think that's part of the problem though, because the form name always shows up correctly in an alert() in all browsers.
function add_new_product(){

    var formName = "frm_add_new_product_" + window.random_number_for_IDs;

    alert('this alert is BEFORE the (#formname).submit');

    $("#" + formName).submit(function(event) {
        alert('this alert is inside the (#formname).submit BEFORE .preventDefault');
        event.preventDefault();
        alert('this alert is inside the (#formname).submit AFTER .preventDefault but BEFORE $.post');
        $.post("add_new_product.php?SiteID=<?php echo $_GET['SiteID']; ?>", $("#" + formName).serialize(), function(data){$("#DIV_new_product_name_" + window.random_number_for_IDs).html(data);});
        alert('this alert is inside the (#formname).submit AFTER $.post');
    });

    alert('this alert is AFTER the (#formname).submit');

    $("#DIV_new_product_form_" + window.random_number_for_IDs).fadeOut(100, function(){$("#DIV_new_product_name_" + window.random_number_for_IDs).fadeIn(100);});

}

In IE, I see all every alert() but not in the order specified above.  It first displays the ones before and after the $(#form).submit, and THEN the ones inside.  FF and Chrome only display the alerts() before and after the $(#form).submit, but never the ones inside.

A: Fixed:
I changed the form's onSubmit from "add_new_product();" to "javascript:add_new_product();return false;" because preventDefault wasn't "prevent"ing the "default" action of the form submit.  That's why the page would just refresh with the field name and value in the querystring, because there was no "action" specified in the form tag and for whatever reason preventDefault was just not happening.  I also tried putting "return false;" inside the function after commenting out preventDefault  but it only works when it's in the  tag's onSubmit.
Then I commented out every line in the add_new_product() script except for the first line that concatenates the dynamic form name, the $.post line, and the last line that fades out the  and fades in the  that the ajax response populates via .html(data)
Works in all three browsers.


text:
Q: Merging data frames in R, in specific order I'm still very new to manipulating data in R and have run into a seemingly simple problem that i can't figure out how to solve.
I have 3 data frames each with 9 columns and 720 rows.
I need to merg them into one data frame with 9 columns and (3x720) rows, where  the first 3 rows in the final data frame is the first rows of each of the original data frames, and so forth for all rows in the original data frames.
name of the dataframes
alt1
alt2
alt3

A: You can create a new column in the data frames for the row number, then you merge them with a rbind and you order them based on the rn column that represents the row number in the original data frames. Note that the rbind will work only if the data frames have the same column names.
alt1 $rn <- seq.int(nrow(alt1))
alt2$rn <- seq.int(nrow(alt2))
alt3$rn <- seq.int(nrow(alt3))

df <- rbind(alt1, alt2, alt3)
df[order(df$rn),]

Let me know if this works.

A: I assume that the columns names are the same in all 3 datasets.
# create example dataset
set.seed(1)

alt1 = data.frame(x = rnorm(4),
                  y = rnorm(4))

alt2 = data.frame(x = rnorm(4),
                  y = rnorm(4))

alt3 = data.frame(x = rnorm(4),
                  y = rnorm(4))

library(dplyr)
library(purrr)

c("alt1", "alt2", "alt3") %>%                                        # get names of datasets
  map_df(function(x) {d = get(x); d$row_index = 1:nrow(d); d}) %>%   # for each name: get data, add a column with the name and bind them all
  arrange(row_index)                                                 # order by row index

#              x           y row_index
# 1  -0.62645381  0.32950777         1
# 2   0.57578135 -0.62124058         1
# 3  -0.01619026  0.91897737         1
# 4   0.18364332 -0.82046838         2
# 5  -0.30538839 -2.21469989         2
# 6   0.94383621  0.78213630         2
# 7  -0.83562861  0.48742905         3
# 8   1.51178117  1.12493092         3
# 9   0.82122120  0.07456498         3
# 10  1.59528080  0.73832471         4
# 11  0.38984324 -0.04493361         4
# 12  0.59390132 -1.98935170         4

This is to double check that you get the first row of each dataset on top. You can remove the unnecessary columns with %>% select(-row_index) in the end.
If you have ONLY those 3 datasets loaded in your workspace you can replace the first line c("alt1", "alt2", "alt3") with ls() to get a fully automated solution.


text:
Q: Remove values from Map while comparing the values against a List Beginner QQ : I have a list and a Map
. I need to check all the values in the "Map" against the "List", if the value is in Map BUT NOT IN the List then  i need to remove it
    List<String> list = getRequiredList();
    Set<String> set = new HashSet<>(list)
    Map<String, String> map = getMap();

need some info on how to remove from the map if its not in List

A: A neat thing about Maps is that the key set and value collection are both backed by the Map itself.  What this means is that removing a key from the key set effectively removes it from the Map it belongs to.
Therefore, you can use retainAll on the key set:
map.keySet().retainAll(list);

That will make sure that the only keys in the Map are the Strings which are in your List.


text:
Q: Pymongo read my variable as licteral, also if i write with dollar $ the problem is easy, but i cant understand where i'm wrong:
I want to duplicate a field:
client = MongoClient(uri)
mydb = client["tesi_gazzette"]
gazzette_table = mydb["gazzette"]

gazzette_table.update_one(
    {},
    {'$set':
        {
            'codicerelazionale': '$uri'
        }
    }
)

but the result is:

A: This code works:
   gazzette_table.update_one(
        {},
        [
            {"$set": {"name": '$uri'}}
        ]
    )


text:
Q: Jackson deserialization of nested objects of which one references the other. UnresolvedForwardReference I'm trying to deserialize the following JSON structure:
{
  "node" : {
    "number" : 5,
    "x" : 2000.0,
    "y" : 1500.0
  },
  "force" : {
    "number" : 1,
    "value" : -20.0,
    "angle" : 90.0,
    "node" : 5
  }
}

Into the following object:
public class NodeWithForce {

    private Node node;
    private Force force;

    public NodeWithForce(){}

    public NodeWithForce(Node node, Force force) {
        this.node = node;
        this.force = force;
    }

    //getters and setters for Node and Force, Equals and Hashcode
}

Node class:
public class Node {

    private long number;
    private double x;
    private double y;

    public Node() {}

    public Node(long number, double x, double y) {
        this.number = number;
        this.x = x;
        this.y = y;
    }

    //getters and setters for number, x and y, equals and hashcode
    }
}

Force class:
public class Force {

    private long number;
    private double value;
    private double angle;

    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "number")
    @JsonIdentityReference(alwaysAsId = true)
    private Node node;

    public Force() {}

    public Force(long number, double value, double angle, Node node) {
        this.number = number;
        this.value = value;
        this.angle = angle;
        this.node = node;
    }

    //getters and setters for number, value, angle and node. Equals and Hashcode.
}

So Node is part of the wrapper object NodeWithForce and also of one of the wrappers children: Force. The actual data structure is more complex than this, but I tried reducing the complexity and keeping only the part that matters for this question here on SO.
Then when I run this:
public NodeWithForce getNodeWithForce() throws Exception {
    Node node = new Node(5, 2000, 1500);
    Force force = new Force(1, -20, 90, node);
    NodeWithForce nwf = new NodeWithForce(node,force);
    NodeWithForce nwf2 = null;
    ObjectMapper om = context.getBean(ObjectMapper.class);
    om.enable(SerializationFeature.INDENT_OUTPUT);
    String jsonRepresentation = null;
    jsonRepresentation = om.writeValueAsString(nwf);
    System.out.println(jsonRepresentation);
    nwf2 = om.readValue(jsonRepresentation, NodeWithForce.class);
    System.out.println("equal: " + nwf.equals(nwf2));
    return nwf2;
}

It gives me the following exception:
com.fasterxml.jackson.databind.deser.UnresolvedForwardReference: Unresolved forward references for:
 at [Source: (String)"{
  "node" : {
    "number" : 5,
    "x" : 2000.0,
    "y" : 1500.0
  },
  "force" : {
    "number" : 1,
    "value" : -20.0,
    "angle" : 90.0,
    "node" : 5
  }
}"; line: 13, column: 1]Object id [5] (for `com.company.calculationmanager.pojos.Node`) at [Source: (String)"{
  "node" : {
    "number" : 5,
    "x" : 2000.0,
    "y" : 1500.0
  },
  "force" : {
    "number" : 1,
    "value" : -20.0,
    "angle" : 90.0,
    "node" : 5
  }
}"; line: 11, column: 15].
    at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.checkUnresolvedObjectId(DefaultDeserializationContext.java:165) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4015) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004) ~[jackson-databind-2.9.6.jar:2.9.6]

Serialization works because it prints the object as json to the console, but deserialization does not, even though I added the JsonIdentityInfo annotation.
Am I missing some annotations here? I think writing a separate deserializer is a bit too much for this simple piece.

A: Put your @JsonIdentityInfo annotation on the Node class, not the field in Force:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "number")
public static class Node { //...

A: Create a new setter method setNode in the NodeWithForce class that accept int:
    private void setNode(int number) {
        setNode(new Node(number));
    }


text:
Q: How do I access scoped entries in a class method in Mongoid? I have an RSS Feed class, which holds the feed url, name, etc. and I want to add a posts method to loop through each post in the feed and returns the results. I have the following code, but am getting many SystemStackError: stack level too deep errors.
class Feed
  field :name
  field :url

  belongs_to :project

  def self.posts
    results = []
    scoped.all.each {|f| results << RssFeed.get(f.name, f.url)}
    results
  end
end

My application has different Projects, and each project has many feeds. So in my code I'm trying to get all posts from all rss feeds that belong to a particular project like this:
project.feeds.cached

I am able to call scoped in my posts method which will return a Mongoid::Criteria but scoped.all.each or scoped.entries both return stack level too deep errors. I was wondering how I can access the project.feeds scope from within my posts class method?
Thanks in advance!

A: My silly mistake - cached is a reserved word.


text:
Q: Получение изображения JavaScript Я в JavaScript не силен, но необходимо к нему прибегнуть. Задача весьма не стандартная. Имеется приблизительно такой html:
<img src='http://server.com/?image=RANDOM_STRING' />

Изображение генерируется разное. Я могу добавить к этому тегу атрибуты. Мне нужно получать это изображение и передавать посредством браузера, т.е через JS. С отправкой проблем не возникает, только вот с получением ничего не могу сделать.
Возможно этот пост чем-то поможет: https://stackoverflow.com/questions/934012/get-image-data-in-javascript

A: Можно пользоваться новинками XMLHttpRequest (ранее известными как XHR Level 2), чтобы получать и отправлять бинарные данные (MDN). Поддержка браузерами довольно неплоха.
Если с данными не нужно ничего делать, проще всего оперировать Blobами.
Получение:
var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "blob";

oReq.onload = function(oEvent) {
  var blob = oReq.response;
  // можно использовать blob где-то ещё
};

oReq.send();

Отправка:
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.onload = function (oEvent) {
  // отправка завершена
};

oReq.send(blob);


text:
Q: Gnu Parallel - decrypt and send file content to a Python script I would like to decrypt a bunch of very large files and use the decrypted version of each file as input to a Python script which will process its content. So, if I have a file named
 file1.sc.xz.gpg

after running the GnuPG decryption tool the output should be stored in a file named
 file1.sc.xz

inside the same directory and this file should be the input to the Python script which will process its contents. Ideally I would like to do this inside one single Bash command, but I couldn't find the right way to do it. What I tried is:
 find test/ -type f | parallel 'f="{}"; g="${f%.*}"; gpg "$f" > "$g" | python iterating-over-tokens.py "$g" '

but is not working. Any other suggestions? Many thanks in advance.
Later edit: if I could send the decrypted file (*.sc.xz) content directly to the Python script as an argument, that would be even better.

A: Directly piped to Python:
parallel gpg -o - {} '|' python -c "'import sys; print sys.stdin.read().upper()'" ::: *.gpg

Create decrypted file first:
parallel gpg -o {.} {} ';' python -c "'import sys; print sys.argv'" {.} ::: *.gpg

You need to be able to decrypt without entering a pass phrase. If gpg asks for a pass phrase run gpg-agent first.


text:
Q: How to transimit video streaming from HoloLens (C#) to PC (python) by socket communication? I can realize sending data from HoloLens (using Unity coding by C#) to PC (coding by C#) by socket communication. But how to sending video steaming in real-time (the video starts to be recorded when I open the application in HoloLens) from HoloLens to PC by my original socket frame. In my view, maybe I should add some sentences to recognize the HoloLens camera, record video and encode the video to data, then transmit the data by my previous socket. Is it right and how to realize it?
By the way, I hope that the PC can receive the video by python so that I can process the video in the following steps.

A: To send video steaming in real-time between HoloLens and PC client, WebRTC should can meets your needs. Please check out this MixedReality-WebRTC project, it can help you to integrate peer-to-peer real-time audio and video communication into your application. It also implements local video capture you need and encapsulation it as a Unity3D component for rapid prototyping and integration.
You can read its official documentation via this link: MixedReality-WebRTC 1.0.0 documentation.
Moreover, this project can be used in desktop applications or even other non-mixed reality applications, which can save your development costs.


text:
Q: Zabbix collecting prometheus encoded data from GitLab runner I am trying to collect performance data from GitLab runner prometheus Interface to zabbix server.
What do I have:

*

*A template with a couple of items in zabbix

*a userparameter conf which relies in a

*shell script which fetch data from api call and return it to the user parameter zabbix interface

What I am currently struggling with is:

*

*because we are using multiple runner, most of the KPI are separated by runner id. Therefore I would like to have a prototype function in my template and script which collects all runner ids, generate items for each runner in zabbix.

But I am really struggling with the prototyping concept in zabbix.
Does anyone would be so kind as to show me an example how to do this?


text:
Q: Regex pattern to ignore multiple folders How is the correct syntax to ignore more then one files and folders for electron-packager?
With only one arg like: --ignore=docs/* it works fine. But I want to ignore more then one folder and files like: --ignore=docs/* + dev/* + someFile.js

A: This variant works for me
--ignore=\"(docs*|dev*|somefile\.js)\"

A: Use the OR statement in the regular expression by using the | character in stead of the + character.
--ignore="docs/.*|dev/.*|somefile\.js"

A: For anyone out there who's looking for a simpler way of packaging an Angular application with Electron using electron-packager, this might get you sorted.
$ electron-packager . myapp --out=dist/builds/win --arch=x64 --icon=src/assets/images/win_icon.ico --asar --overwrite --ignore="(node_modules*|dist/builds*|dist/installers*|e2e*|src*)"

It works for me all the time, I use the terminal from VS Code.


text:
Q: PHP and DRUPAL, Cannot save values in a static variable and pass through function Developing a module for drupal and I need to pass/modify variables within functions. I avoided using global variables because drupal uses the include function which subsequently makes my global variable into local.
As such, i created the following script which stores a static variable but I cannot retain the new value. Any help will be appreciated
function _example_set_flashurl($value = '21224', $clear = NULL) {
  static $url;

  if ($clear) {
    // reset url variable back to default
    $url = null;
  }
  // assigned url a perminate value within this function
  $url = $value;
  return $url;

}

function _example_get_flashurl() {
  return _example_set_flashurl();
  // retrieve the value inside set scope
}
_example_set_flashurl('another', TRUE);
print _example_get_flashurl();  // prints 21224,  I want it to print another

A: Try this
<?
function _example_set_flashurl($value = '21224', $clear = NULL) {
  static $url;

  if ($clear) {
    // reset url variable back to default
    $url = null;
  }
  if($value!='21224') {
  // assigned url a perminate value within this function
  $url = $value;
  }
  return $url;

}

function _example_get_flashurl() {
  return _example_set_flashurl();
  // retrieve the value inside set scope
}
_example_set_flashurl('another', TRUE);
print _example_get_flashurl();  // prints 21224,  I want it to print another

A: You override the value in the empty call to set in your get function.
First, you probably want to add the default value directly to the static and not the argument. Like this: "static $url = '21224';". Then, this value will also be returned when set has never been called.
Second, there is no need for a $clear argument if you can pass in any value you want. If you want to change it, just override the old value.
Third, as the answer from bruce dou showed, you want to protect it against accidently overriding the value.
So, this code for the set function should be all you need:
<?php
function _example_set_flashurl($value = FALSE) {
  static $url = '21224';

  // Only keep value if it's not FALSE.
  if ($value !== FALSE) {
    // assigned url a perminate value within this function
    $url = $value;
  }
  return $url;
}
?>


text:
Q: upload image using PhoneGap to .NET WCF Rest Service I am facing problem upload file from camera and gallery.
When selecting few images from gallery I am able to successfully upload the image to WCF service. Thus WCF service is working fine and so is the code to upload file and also same code works with emulated web camera also.
However when selecting a few images from gallery I am getting *error code *
java.io.FileNotFoundException: http://www.foobar.com/sasas
JavaScript Code
function selectImageFromCamera(){
     var popover = new CameraPopoverOptions(300,300,100,100,Camera.PopoverArrowDirection.ARROW_ANY);
     var options = { quality: 49, destinationType: Camera.DestinationType.FILE_URI,sourceType: Camera.PictureSourceType.CAMERA, popoverOptions : popover};
     navigator.camera.getPicture(this.uploadPhoto, this.onFail, options);
}

function selectImageFromGallery(){
    var popover = new CameraPopoverOptions(300,300,100,100,Camera.PopoverArrowDirection.ARROW_ANY);
    var options = { quality: 49, destinationType: Camera.DestinationType.FILE_URI,sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY, popoverOptions : popover};
    navigator.camera.getPicture(this.uploadPhoto, this.onFail, options);
}

function uploadPhoto(imageURI) {
    var serverUrl = "http://www.foobar.com/safafa";
    var image = document.getElementById("imgUpload");
    image.style.display = "block";
    image.src = imageURI;

    var fileUploadOptions = new FileUploadOptions();
    fileUploadOptions.fileKey="file";
    fileUploadOptions.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
    fileUploadOptions.mimeType="image/png";
    fileUploadOptions.chunkedMode=true;

    var ft = new FileTransfer();
    ft.upload(imageURI, serverUrl, this.win, this.fail, fileUploadOptions);
}

Please help me to identify What I am doing wrong.

A: Your PhoneGap code seems to be all right but just check your WCF Service web.config File.
You'll want something like this to increase the file size.
<bindings>
    <basicHttpBinding>
        <binding name="basicHttp" allowCookies="true"
                 maxReceivedMessageSize="10000000"
                 maxBufferSize="10000000"
                 maxBufferPoolSize="10000000">
            <readerQuotas maxDepth="32"
                 maxArrayLength="100000000"
                 maxStringContentLength="100000000"/>
        </binding>
    </basicHttpBinding>
</bindings>

where 100000000 is your file size.

A: This worked for me.
The issue was with the WCF service. Its accepted file less than 65 KB, which is max request size by default after increasing maxReceivedMessageSizevalue problem was solved.
<standardEndpoint name=""
    helpEnabled="true"
    automaticFormatSelectionEnabled="true"
    maxBufferSize="2147483647"
    maxReceivedMessageSize="2147483647">
</standardEndpoint>


text:
Q: Analyze Changes Using LandTrendr - Run for ever I am trying to implement the following project using my own data.
https://learn.arcgis.com/en/projects/monitor-forest-change-over-time/
The problem is that when I launch Analyze Changes Using LandTrendr, it runs for ever without a result. Anybody knows why is that?


text:
Q: CardView to make a circle background, show oval background I followed this post
and tried to make a transparent circle background around my X verctor Image.
  <android.support.design.card.MaterialCardView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:innerRadius="0dp"
      android:shape="ring"
      android:thicknessRatio="0"
      app:cardCornerRadius="24dp"
      card_view:cardElevation="0dp"
      card_view:cardMaxElevation="0dp">
    <ImageView
        android:id="@+id/close_button"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="top|end"
        android:padding="@dimen/account_menu_close_button_padding"
        android:alpha="0"
        android:background="?attr/selectableItemBackground"
        android:contentDescription="@string/og_close_icon_a11y"
        android:focusable="true"
        android:theme="@style/myStyle"
        android:visibility="gone"
        app:srcCompat="@drawable/quantum_gm_ic_close_vd_theme_24"
        />
  </android.support.design.card.MaterialCardView>

However I keep on getting:
1) oval shape
2) thing white border
How can I fix these both?

A: Try this way
<com.google.android.material.card.MaterialCardView
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_gravity="center"
    android:innerRadius="0dp"
    android:shape="ring"
    android:thicknessRatio="0"
    app:cardBackgroundColor="@color/colorAccent"
    app:cardCornerRadius="24dp"
    app:cardElevation="0dp"
    card_view:cardMaxElevation="0dp">

    <ImageView
        android:id="@+id/close_button"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="top|end"
        android:background="?attr/selectableItemBackground"
        android:contentDescription="@string/app_name"
        android:focusable="true"
        android:visibility="visible"
        app:srcCompat="@drawable/ic_close" />

</com.google.android.material.card.MaterialCardView>

OUTPUT

OUTPUT in device


text:
Q: Extracting text from a column I want to import data from Excel into an existing table in a SQL Server database.
I have a column like Gender and the values are Male and Female in Excel. I want to insert only the first character into database, like M and F.
How should I achieve this thing in SSIS for SQL Server 2008?

A: You can use a Derived Column transformation. Add an expression that converts the gender column into the initial. You can use something like SUBSTRING(GENDER,1,1) for this.


text:
Q: Wordpress - Mixed Content ( SSL Insecure Content Fixer installed ) I had deployed a website using Wordpress. I was initially getting a lot of mixed content warning.
So I tried "SSL Insecure Content Fixer" to convert Http = Https , which did fix most of the mixed content warning.
However still for some URLs I am getting mixed content errors as shown below.

Initially I selected "Simple" option in "SSL Insecure" setting. But I have also tried for all other options as well. Still not able to resolve this.


text:
Q: Password of private key for installation of SSL Certificate I opened certificate for SSL - Bitbucket. while opening import wizard it needs password.
Where do i get that passsword?

A: TLS certificates don't have passwords, but the keys they're associated with do. That's set up when the key is created, so you'll need to talk to whomever created the key.


text:
Q: How to configure a timeout for an SQL query in Groovy? How do I create a timeout for this operation: ?
def db = Sql.newInstance("jdbc:mysql://${mysql_host}:3306/${dbName}",
    user, pass, 'com.mysql.jdbc.Driver')
db.eachRow(query) { row ->
  // do something with the row
}

A: I believe the correct way would be something like this:
sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:XE", "user",
                  "pwd", "oracle.jdbc.driver.OracleDriver")

sql.withStatement {
   stmt -> stmt.queryTimeout = 10
}

sql.eachRow("select * from someTable", {
 println it
} )

of course, this is where I'd used Oracle, but I hope this can give you an idea.

A: I believe there might not be a general answer, but rather a database/driver-specific answer via parameters to the connection URL.
E.g. for mysql, I think that adding connectTimeout=something&socketTimeout=something might do the trick.