text:
Q: Selenium - How to send a jQuery from inside an iframe? I have been using Selenium Webdriver for Python to automate some daily tasks at my job. Wanting to learn more, I have been using Selenium to write some scripts in my spare time. I have had some success, but recently, while trying to make a bot for neopets.com to run daily activities, I encountered a scenario that I have not been able to get any traction in automating.
The minigame is basically just a randomly determined slot game called Trudy's surprise (url: http://www.neopets.com/trudys_surprise.phtml, you may have to make an account to access it). The function I am trying to accomplish is just to click the "Play" button with Selenium, or otherwise have the slot game execute. While this function is pretty trivial, it seems to me (maybe because I can't crack it on my own) that there is a learning experience here because the solution is not as simple as using webelem.click() as far as I can tell.
I have been using the Inspect function of Chrome to look at the underlying script of the game. If you navigate to the slots game, right-click anywhere in the game frame, and click "inspect" a console should show up with a <canvas> element highlighted. This <canvas> element is inside an <iframe>, which I will refer to throughout this post.
So here are the problems I am facing (AKA things I've tried that don't work):
I cannot get an xpath for the button because the game itself is inside an iframe. I have tried going through a list of all elements in the iframe using the driver.switch_to.frame() function then doing a driver.find_elements_by_xpath("//*"), and only found the html elements described in the page (no start button).
Since I couldn't find the element, I figured I would try to replicate its effects. The source script for the slot machine is located at http://www.neopets.com/trudydaily/js/slotsgame.js?v=1525633042. I would copy it here but it is quite long. I have almost no experience with html or Javascript, but it seems like this script is called in the header of the iframe by
<script src="/trudydaily/js/slotsgame.js?v=1525633042">
</script>

creating a SlotsGame object which is then called by a script in the body of the iframe. The SlotsGame object only has three callable member functions: Initialize, LoadAssets, and Start. It also looks like the script posts a jQuery and waits for a response from the server, allowing the user to either spin or not based on the response. The script which calls the SlotsGame object looks like
  var ajaxurl = '/trudydaily/ajax/claimprize.php';
  //var data = {'action': 'getslotstate'};
  var data = {
    'action': 'getslotstate','key': '2nA6BqsTIM1IT785Di08dqyFKnLCM1M7VTcOfSnC41I%3D'};
  var resp;
  parent.$.post(ajaxurl, data, function (response){
    resp = JSON.parse(response);
                if(resp.error == ""){
          SlotsGame.LoadAssets(AssetLoadComplete, "http://images.neopets.com");
        }
      else{
        parent.CloseSlotsGame();
      }
            }
    );
    SlotsGame.Initialize();
    function AssetLoadComplete(){
      SlotsGame.Start(resp);
    }
    function CloseGame(){
      parent.CloseSlotsGame();
    };

with the key value changing each time the page is loaded.
Calls to driver.execute_script("SlotsGame.LoadAssets()") and ...Initialize()... both work when called from within the context of the iframe (they create a copy of the slots game in the iframe), so I know I am on the right track. However, I have tried executing SlotsGame.Start(i) for i=1,2,3 from within the context of the iframe and no dice (or not slots). I have also tried executing the entire above script using driver.execute_script(webelem.get_attribute('innerHTML')), but nothing happens.
I'm sure that I am missing an easy way to automatically activate this machine, but I have tried almost everything I can think of with no success.
Apologies for any imprecise terminology or similar, I am still trying to pick this skill up. I am hoping that someone who understands html, Javascript, and JSON will understand the issue. Please let me know if you can think of a way I can edit the question to make it more precise or generally applicable. Thanks in advance for any help.

A: This would be really simple if only Selenium made post requests easy.. luckily there is a package for that! https://github.com/cryzed/Selenium-Requests
import re
import time
from seleniumrequests import Firefox
from selenium.webdriver.support.ui import WebDriverWait as wait

# Selenium-Requests way of launching a browser instance
browser = Firefox()

then after your login stuff,
browser.get("http://www.neopets.com/trudys_surprise.phtml")

# Waits for trudys iframe to be loaded, and then switches to the iframe
wait(browser, 10).until(EC.frame_to_be_available_and_switch_to_it("frameTest"))
time.sleep(1)

# gets key from the iframe page_source; not the worlds best regex
matchobj = re.search(r"\'action\'\: \'\w*\',\'key\'\: \'(.*)\'\}\;", str(browser.page_source))

if(matchobj):
    key = str(matchobj.group(1))
    postPage = ('http://www.neopets.com/trudydaily/ajax/claimprize.php')

    response = browser.request('POST', postPage, data={'action':'getslotstate','key':key})
    time.sleep(2)

    response = browser.request('POST', postPage, data={'action':'beginroll'})
    time.sleep(2)

    response = browser.request('POST', postPage, data={'action':'prizeclaimed'})
    time.sleep(2)

    # switches back from the iframe to the main window
    browser.switch_to.default_content()


text:
Q: Update property bound from text field without needing to press Enter I have a text field and I bind it to an NSString instance variable.
When I type in the text field, it does not update the variable. It waits until I press the Enter key. I don't want to hit Enter every time.
What do I need to change in order to make the binding change value immediately?

A: By default, the value binding of an NSTextField does not update continuously.  To fix this, you need, after selecting your text field, to check the "Continuously Updates Value" box in the Bindings Inspector under the Value heading:

However, most often, what you really want to do is update the property to which the text field is bound when the user has finished editing and presses a button ("Save" or "OK", for example).  To do this, you needn't continuously update the property as described above, you just need to end editing.  Daniel Jalkut provides an extremely useful implementation of just such a method:
@interface NSWindow (Editing)

- (void)endEditing;

@end

@implementation NSWindow (Editing)

- (void)endEditing
{
    // Save the current first responder, respecting the fact
    // that it might conceptually be the delegate of the
    // field editor that is "first responder."
    id oldFirstResponder = [oMainDocumentWindow firstResponder];
    if ((oldFirstResponder != nil) &&
        [oldFirstResponder isKindOfClass:[NSTextView class]] &&
        [(NSTextView*)oldFirstResponder isFieldEditor])
    {
        // A field editor's delegate is the view we're editing
        oldFirstResponder = [oldFirstResponder delegate];
        if ([oldFirstResponder isKindOfClass:[NSResponder class]] == NO)
        {
            // Eh ... we'd better back off if
            // this thing isn't a responder at all
            oldFirstResponder = nil;
        }
    }

    // Gracefully end all editing in our window (from Erik Buck).
    // This will cause the user's changes to be committed.
    if([oMainDocumentWindow makeFirstResponder:oMainDocumentWindow])
    {
        // All editing is now ended and delegate messages sent etc.
    }
    else
    {
        // For some reason the text object being edited will
        // not resign first responder status so force an
        /// end to editing anyway
        [oMainDocumentWindow endEditingFor:nil];
    }

    // If we had a first responder before, restore it
    if (oldFirstResponder != nil)
    {
        [oMainDocumentWindow makeFirstResponder:oldFirstResponder];
    }
}

@end

So if for example you had a "Save" button targeting your view controller's method -save:, you would call
- (IBAction)save:(id)sender
{
    [[[self view] window] endEditing];
    //at this point, all properties bound to text fields have the same
    //value as the contents of the text fields.

    //save stuff...
}

A: The previous answer is beautiful, and I learned from it about tricking the Window/View/Document system to end-editing on everything at the programmer's will.
However, the default responder chain behavior (including the preservation of the first responder until the USER moved their focus to something else) is fundamental to the Mac's "look and feel" and I wouldn't mess with it lightly (I swear I did very powerful things in responder-chain manipulation, so I don't say that out of fear.)
In addition - there is even a simpler method - that does not require changing the binding. In the Interface-builder, select the text field, and select the "Attribute Inspector" tab. You'll see the following:

Checking the red-circled "continuous" will do the trick. This option is basic and older even than binding, and its main use is to allow validator object (a whole new story) to validate the text and change it on the fly, as the user types. When the text-field calls validator calls, it also updates bound values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Вычесть n часов из date() date('d.m.Y H:i', $timestamp);

Как вычесть например 3 часа?
A: если у вас $timestamp - в формате UNIX, то проще некуда
$timestamp-3*60*60

A: time
$time = time() - 3 * 60 * 60; // секунды
echo date('d.m.Y H:i', $time);

strtotime
$time = strtotime('-3 hours');
echo date('d.m.Y H:i', $time);

DateTime
$date = new \DateTime('-3 hours');
echo $date->format('d.m.Y H:i');


text:
Q: When Dijkstra Fails? what if the node Dijkstra chooses doesn't lead to goal ?
what if the node Dijkstra chooses is minimal in cost compare to the next one but if the  !chosen next next node leads to overall minimal cost and its not connected to chosen next what happens then?

A: Dijkstra's algorithm (in the commonly used formulation) finds the shortest path in a graph from the selected starting node to all other nodes in the graph (that are reachable from the start node).
Thus,

what if the node Dijkstra chooses doesn't lead to goal ?

is irrrelevant. Assuming the goal is in fact reachable from the start node, unrelated nodes will simply not affect the length of the path to goal.

what if the node Dijkstra chooses is minimal in cost compare to the next one but if the !chosen next next node leads to overall minimal cost and its not connected to chosen next what happens then?

In each step, the algorithm visits the node with minimal cost (so far) (call it N), and recomputes the costs for reaching the neighbours of N. If a shorter path has been found to any of the neighbours of N, the path to that node is updated.
Thus, eventually, the algorithm will visit your goal via "the chosen next next node", and find that path is shorter than the previously calculated
path length.


text:
Q: ¿Como devuelvo la diferencia de dos fechas con GregorianCalendar? Dadas en dias Estoy intentando hacer una actividad en Java, y estoy revisando la clase de GregorianCalendar y necesito comparar 2 fechas, y que me devuelva los días que hay de una a otra.
He visto el método .compareTo, pero solo me ha funcionado con la clase Date o LocalDate. Con Gregorian siempre me devuelve un 1 o un -1.
¿Alguna forma simple de hacerlo?

A: usando GregorianCalendar se me ocurre creando un metodo propio, espero te sirva
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;

public class Test{

    public static int daysBetween(Date d1, Date d2){
             return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
     }

    public static void main(String [] args){
        Calendar fecha1 = new GregorianCalendar(2019, Calendar.FEBRUARY, 10);
        Calendar fecha2 = new GregorianCalendar(2019, Calendar.FEBRUARY, 12);
        int dias = daysBetween(fecha1.getTime(),fecha2.getTime());

        System.out.println(dias);
    }

}


text:
Q: Is it wrong to ignore implicit return inside arrow function in JavaScript or TypeScript when no return required Very often I come across code that looks something like this:
ngOnDestroy() {
  this.subscriptions.forEach(subscription => subscription.unsubscribe());
}

My question is if this is, while harmless in this example, a bad practice since the implication here is that there is a return value which is equal to whatever unsubscribe() method returns.
The code above does not have any need to return anything out of the arrow function, yet there is an implicit return there, i.e., the body is translated into return subscription.unsubscribe().
Would it be a better practice to code that function as follows? (note the extra curly braces):
ngOnDestroy() {
  this.subscriptions.forEach(subscription => {
    subscription.unsubscribe();
  });
}

A: Arrow function reduces code that you write so implicit return helps saving some key strokes :) However, in your 2nd example, even there is a return that is undefined. So it is not bad practice, it is cleaner and shorter.

A: It is a matter of style, but I would call unintended implicit return a bad one. It takes a bit less to type but gives wrong impression about API in use if a developer who reads the code isn't familiar with it. This is less of a problem for well-known API like forEach. Still, if a function returns a value but it's ignored, this may cause confusion.
Implicit return won't cause runtime issues if returned value is undefined, but in case it's defined, a value may affect the code where a function is being called in such way.
An example is a pitfall I accidentally fell once with AngularJS testing. Testing modules accept module configuration functions with same signatures as production modules (a function annotated for dependency injection that returns no value), but the value is just ignored in production module:
// ok
app.config((foo) => foo.barThatReturnsAValue());

While in tests it results in obscure error:
// Error: [ng:areq] Argument 'fn' is not a function, got Object
angular.mock.module((foo) => foo.barThatReturnsAValue())

The problem that is specific to TypeScript is that such problems usually aren't detected by type checks:
let foo = () => 1;
let bar = (foo: () => void) => {};

bar(foo); // ok

A: For cleaner code and increased readability you may also use the void keyword.
For example: (Note the void keyword after the =>)
ngOnDestroy() {
  this.subscriptions.forEach(subscription => void subscription.unsubscribe());
}

No implicit return here :)

A: In theory, it would be a better practice to follow the second example for functions with return values.
In practice, however, it often does not matter if a callback function has a return value, so the cleaner syntax of the first example is worth the ambiguity.
edit: as Randy points out in the comments, if the function returns undefined, there is no difference between the two approaches. I amended my answer to take this into account.

A: Both of your examples produces return results. If you don't really need any return value. You better use for loops
for(var i=0; i<this.subscriptions.length; i++)
{
  this.subscription[i].unsubscribe();
}

Also for loops are much more efficient than forEach here


text:
Q: How to search for keywords in a txt-file and print full string out Hello i am using python combined with txt file and want to let my code search for parts of a word, like my txt file looks like this =
'www.test.com/product/wings' , 'www.test1.com/product/chicken' , 'www.okay.com/product/burger' , 'www.Test23542.com/product/smoothie'

So and i want to let my code open the file and search for 'www.test1.com/product/' and it should print out the complete link, included the product like = 'www.test1.com/product/chicken'
I am stuck and dont know how to do it so my current code wont really help because its just one line.

A: Here is an example. Use open  and then  read or  readline to read in the date in the file and then use str() methods to find what you need,


text:
Q: Network Traffic Troubleshooting Program All,
I am having intermittent network issues that I am having an issue troubleshooting. The issue is outside of my network on one of the hops in my local area. I was wondering if you all knew of a good windows based program that would monitor/log a tracert or something of that nature.
Thanks

A: PingPlotter, or VisualRoute
 should do the job.


text:
Q: Set up an integral for the length of the curve. $$x= y^{1/30},\; 0 ≤ y ≤ 2$$
I know the formula we use is $\sqrt{1 +f'(x)^2} dx. $
But now do I switch the function so it's "y="?

A: Take each side to a power of $30$: $$x^{30} = \left(y^{1/30}\right)^{30} = y$$
$$y = x^{30} \implies y' = 30x^{29} \implies (y')^2 = \Big(30x^{29}\Big)^2$$
That gives us the length of the curve, $s$:
$$s =\int_0^2\sqrt{1 + \Big(30x^{29}\Big)^2}\;dx$$

A: You don't need to. Just treat X as a function of y. And use dy instead. It is just nomenclature; how stuff is named.


text:
Q: how to call a google script function from html I am a newbie with HTML and fair at google apps scripting.
I am trying to call a gas function using a button in html.
When the function is called it gives this fault

"Uncaught Error: Cannot call method "getSheetByName" of null.  at Data (Data:29)
  (Lineup)"

It appears to fault out at the first line of the code.
I've searched around various places and I can not find why this is causing an error.
Here is the code snippets:
HTML
     <input type="button" id="br" value="Order Complete"
     onClick="Data(3,22)">
     <script>
     function Data(row,col){

     google.script.run

     .Data(row,col);
     }
     </script>

Code:
    function Data(row,col) {

      var ss = SpreadsheetApp.getActive().getSheetByName("Lineup"); // this
        is line 29 where it is faulting
      var history =  SpreadsheetApp.getActive().getSheetByName("completed");
      var data = ss.getRange(row+2,col-5,1,5).getValues();


text:
Q: Micronaut 3+ and Kafka integration I'm currently trying to get familiar with micronaut and Kafka. I've followed the documentation and created one KafkaClient in a microservice and one KafkaListener in a different microservice. The code looks like this:
Client. This is working as it's supposed to. I'm posting new messages in the vet-reviews topic:
@KafkaClient
public interface VetReviewClient {

    @Topic("vet-reviews")
    void send(VetReviewApi vetReviewApi);

}

Listener:
@KafkaListener(groupId = "pet-clinic", offsetReset = OffsetReset.EARLIEST)
@AllArgsConstructor
@Slf4j
public class VetReviewListener {

    private VetService vetService;

    @Topic("vet-reviews")
    public void receive(@MessageBody VetReviewApi vetReviewApi) {
        log.info("Received vet review: {}", vetReviewApi);

        vetService.processVetReview(vetReviewApi);
    }

}

Although posting the message in the topic, the listener does not pull the new message. I've followed the official micronaut-kafka integration documentation, but it does not work.
I know that this question was posted a while ago, but I don't see any answer and I'm unable to "revive" the problem by commenting because I don't have sufficient reputation.
Link to old post

A: Update on the problem. I've changed the Kafka docker image and that was it.
Current working kafka-zookeper-kafdrop config:
 zookeeper:
    image: confluentinc/cp-zookeeper:7.0.1
    container_name: zookeeper
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: confluentinc/cp-kafka:7.0.1
    container_name: kafka
    ports:
      # To learn about configuring Kafka for access across networks see
      # https://www.confluent.io/blog/kafka-client-cannot-connect-to-broker-on-aws-on-docker-etc/
      - "9092:9092"
    depends_on:
      - zookeeper
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_INTERNAL:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092,PLAINTEXT_INTERNAL://kafka:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1

  kafdrop:
    image: obsidiandynamics/kafdrop
    ports:
      - 9100:9000
    environment:
      - KAFKA_BROKERCONNECT=kafka:29092
      - JVM_OPTS=-Xms32M -Xmx64M
    depends_on:
      - kafka


text:
Q: is it possible to create a website with wordpress with these requirements without coading? is it possible to create a website with wordpress with these requirements without coading? if possible which would be the best theme?Thank you.
Website Requirements
1.Need to be an eCommerce marketplace
2.Need to accept paypal, credit card payments etc.
3.Manage inventory and products
4.Be able to cross sell on eBay, Amazon, Facebook, Instagram
5.Show shipping estimates to local and overseas customers.
6.Should be able to easily manage products from suppliers, thus staying upto date with supplier stock on hand.
7.Be able to run promotions and sales on  products.

A: Apart from cross selling, all requirements are covered by a standard installation of WordPress with the WooCommerce plugin. I've seen (but never used) a free extension for Facebook. For the other platforms you need to search for extensions, maybe payed extensions on woocommerce store or codecanyon.
I can not tell you what would be the best theme, but maybe the Hello Theme by Elementor and the Plugin Elementor is a good fit to customize everythin without coding.


text:
Q: How to test Number for zero java I can't seem to figure out how to test a number to see if it's zero. Couldn't someone please tell me what I'm missing.
getMin = Number.class
getMax = Number.class

Test
Number value = mvFacet.getMin() > 0 ? mvFacet.getMin() : mvFacet.getMax();
System.out.println(value.toString());

A: Number num;
...
if(num.intValue() == 0) {
    // num is 0 so do something here
}

Other methods available on Number are:
byteValue()
doubleValue()
floatValue()
longValue()
shortValue()

Select whichever method makes the most sense for the values you are using.

A: To add to Jason's answer, if you're going to use num.doubleValue() then don't use == since it doesn't handle edge cases like when the double value is NaN or Infinity. Please use Double.compare(num.doubleValue(), 0.0);.


text:
Q: disable upload in rtorrent Is it somehow possible to disable upload in rtorrent? One would think that upload_rate = 0 might do the trick, but based on my tests and commented rtorrent.rc file in rtorrent source tarball, 0 is for unlimited speed. Or is BitTorrent protocol built in a way that at least some upload bandwidth is always required?

A: Another alternative, you can setup upload connection to 0 or put 1kbps speed so it will use the minimum rate or even you can recompile the program by adding the file provided here.
I do not want to be rude but did you consider what happen if everybody start doing same thing as you. The torrent work's with peer-to-peer connection. Therefore, by using a little upload from everyone, it help's other to download the file. Other's are depending on your upload to download the file as you are depending on others upload.
As explain the link above if you are worried about privacy, please note that even if you are not uploading, others can still tack you.

Remember: people will STILL see you are connected to the tracker and if a client is using Superseeding, you will NOT GET ANY OTHER CHUNK of the file until you upload what you just downloaded to someone else! (which won't occur since you just disabled sharing).

Consider yourself warned.


text:
Q: Apply function across rows Is there a more efficient way to do this?
I have a df with 4 rows and 25 columns, and I want to make a calculation across all rows with the following formula:
(df['next column'] - df['current column'])/df['current column']

A: We can do
(df[-1] - df[-ncol(df)])/df[-ncol(df)]

data
set.seed(24)
df <- as.data.frame(matrix(1:25, 5, 5))


text:
Q: Outlier detection in curve fitting
In this picture you can see the measured datapoints (blue) and a curve I fit in (orange).
The value with x=10000 seems like an outlier, and I am thinking about removing it, to get a better fitting curve. However, I don't want to remove it manually.
Methods I considered:

*

*Trim at y<0.55. seems crude and unreliable, since the data can change.

*remove points with a big vertical distance to the neighboring points.
However, the vertical distance isn't that big, compared to the datapoints with bigger x.

*IQR; only few datapoints, and the point isn't that far out.

*fit curve iteratively and with each iteration remove one of the points. Subsequently observe how well the curve fits. With this Method I fear losing points which actually contribute valid information. Furthermore there could be more than one outlier.

Could anyone point me in the right direction?
Any help is appreciated!


text:
Q: Opencv mat truncates all double entries I am populating my cv::Mat matrix(size, size,  cv::DataType<double>::type); (tried also CV_64F and CV_64FC1 all yield same result). I am looping across size and doing this: matrix.data[x*size+y] = someFunc(); where someFunc() returns a double. The problem is that for some reason the matrix truncates the double and stores only the integer part. For the sake of testing I created the following snippet
cv::Mat mat(10, 10,  CV_64F);
for (int i=0; i<10; ++i){
    for (int j=0; j<10; ++j){
        mat.data[i*10 + j] = 1.9;
        std::cout << double(mat.data[i*10+j]) << std::endl; // outputs 1
    }
}

What am I doing wrong? How should I populate a cv::Mat() with doubles correctly?

A: cv::Mat::data is pointer to unsigned char. You have pay extra attention when accessing your data that way, i.e. cast it to double so that the offsets you add to it are correct.
The recommended way to access/modify elements of a cv::Mat is as follows:
cv::Mat mat( 10, 10, CV_64F );
mat.at<double>( y, x ) = 123.; // Careful y before x!

When you know the type of your data in advance you can use template-based cv::Mat_, which has several convenience typedefs. The above case could be rewritten to:
cv::Mat1d mat( 10, 10 ); // 1 - one channel, d - double
mat( y, x ) = 123.;

If all elements are set to the same value initially, you can also use;
double value = 1.9;
cv::Mat1d mat = value * cv::Mat1d::ones( 10, 10 );

but, of course, a double for-loop like the one you are using is fine, too.
And just to emphasize again, be careful with order of the y- and x-coordinates in the (y,x)-access operator above. I have too many people do it wrong and waste time over it.

A: Mat::data is an unsigned char*. In your case it will be enough to cast it to double before accessing each matrix element:
((double*)mat.data)[i*10 + j] = 1.9;

and
std::cout << ((double*)mat.data)[i*10+j] << std::endl;

Notice this is slightly faster than using the Mat::at() accessor.


text:
Q: creating a custom field in Tableau that would give me a count of the items that are still waiting on a response I need assistance in creating a custom field in Tableau that would give me a count of the items that are still waiting on a response.  Below is an image of some dummy data. I need the calculation to first look at the Response Requested column. If it is "yes", then look at the Receipt Date column. If it is null, then look at the requested Response Date column. If the requested response date is past today's date, then I would like it to be added to the count.
response dummy data

A: Try something like this:
count(IF [Response Requested] = 'Yes' and isnull([Response Receipt Date]) and [Response Date] < TODAY() then 1 end)


text:
Q: How to use Activity Recognition to detect walking/running vs on_foot In Google Play Services Activity Recognition there is
DetectedActivity.RUNNING,
DetectedActivity.WALKING,
DetectedActivity.ON_FOOT

when ever I get an activity update for either walking or running I get
ON_FOOT
how do I differentiate?
I know it says that RUNNING and WALKING : "This is a sub-activity of ON_FOOT"
Thanks for your help.

A: The walkingOrRunning() method provided by emil10001 works, however it will not be able to get the activity(running or walking) with the highest confidence, this because, the condition of  the second if clause in his for loop always compares the activity's confidence to 0.
To clarify this, let assume we pass a List of size 2 "probableActivities"  as argument to the walkingOrRunning() method i.e: we call walkingOrRunning(probableActivities).
Supposing,
List probableActivities = [ activity1, activity2 ],
where:
activity1 = "walking" with 75% confidence
activity2 = "running" 5% confidence.
In brief, the excution of the method walkingOrRunning(probableActivities) is as follows:
1)After the 1st iteration of the for loop, myActivity = "walking"
2)After the 2nd iteration of the for loop, myActivity = "running"
and the method retruns "running" as the activity type , meanwhile we expect the returned activity to be "walking".
In sum, in order to get the activity type (walking/running) with the highest confidence, I modified walkingOrRunning() method to the following
[ fyi: I have implemented and tested the code and it's working as expected, I welcome any feedback/comment/question].
 private DetectedActivity walkingOrRunning(List<DetectedActivity> probableActivities) {
    DetectedActivity myActivity = null;
    int confidence = 0;
    for (DetectedActivity activity : probableActivities) {
        if (activity.getType() != DetectedActivity.RUNNING && activity.getType() != DetectedActivity.WALKING)
            continue;

        if (activity.getConfidence() >= confidence) {
            confidence = activity.getConfidence();
            myActivity = activity;
        }
    }

    return myActivity;
}

A: As Sam mentioned, the WALKING and RUNNING activities come in as secondary activities in a list (ActivityRecognitionResult.getProbableActivities()), and you'll need to parse them out.
// Get the update
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

// Get the most probable activity from the list of activities in the update
DetectedActivity mostProbableActivity = result.getMostProbableActivity();

// Get the type of activity
int activityType = mostProbableActivity.getType();

if (activityType == DetectedActivity.ON_FOOT) {
    DetectedActivity betterActivity = walkingOrRunning(result.getProbableActivities());
    if (null != betterActivity)
        mostProbableActivity = betterActivity;
}

private DetectedActivity walkingOrRunning(List<DetectedActivity> probableActivities) {
    DetectedActivity myActivity = null;
    int confidence = 0;
    for (DetectedActivity activity : probableActivities) {
        if (activity.getType() != DetectedActivity.RUNNING && activity.getType() != DetectedActivity.WALKING)
            continue;

        if (activity.getConfidence() > confidence)
            myActivity = activity;
    }

    return myActivity;
}

I tested the above code this evening, both walking and running and it seemed to do fairly well. If you don't explicitly filter on only RUNNING or WALKING, you will likely get erroneous results.

A: I've observed similar behavior. My theory is that when you receive a ActivityRecognitionResult object, it will often contain several parseable DetectedActivity objects each with a confidence score specified by an integer. In the case of WALKING, there will be at least two DetectedActivity objects - one DetectedActivity object for ON_FOOT with a higher confidence level, and one DetectedActivity object for WALKING with a lower or equal confidence level.
In practice I imagine you'll often get some permutation of ON_FOOT + WALKING || RUNNING, or all three with varying confidence scores, with ON_FOOT likely being the highest.


text:
Q: App specific logging and export in Android My app logs debug information and phone state using logcat at present. What I need is the following:

*

*Is there a way to send all my logs to my app's private (say encrypted) storage not accessible to others in a neat fashion?

*I would also like to clean up and export these logs, say once every 24 hrs to my TCP server

What would be the quickest and the cleanest way to go about doing this? I understand that I could write my custom logging service that does this and use something like an AlarmManager to export the logs, but I was wondering if there exist automated solutions since the task itself appears to be quite ubiquitous.
The idea behind all this is to monitor the performance of my app, possible bugs which would enable me to work on updates. Something like automated crowd sourced feedback.

A: You could use Google Analytics which "provides a web service and a pair of SDKs to help track user interaction with websites and applications accessed from a mobile device"
Link: http://code.google.com/mobile/analytics/docs/android/
Also, actual errors that cause your app to force close will show up in your android developer account, with the same detail as in logcat.


text:
Q: I am trying to integrate GCM push notification into my app, but some errors are occurring I have followed this tutorial
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
My logcat shows error
10-05 21:25:05.154 443-498/com.example.shashi.pushnotification E/GMPM:
    getGoogleAppId failed with status: 10
10-05 21:25:05.156 443-498/com.example.shashi.pushnotification E/GMPM:
    Uploading is not possible. App measurement disabled
10-05 21:26:02.572 443-1181/com.example.shashi.pushnotification E/GCMRegistrar:
    internal error: retry receiver class not set yet
10-05 21:26:44.331 443-1181/com.example.shashi.pushnotification E/shiashi GCM:
    Failed to register on attempt 1:java.io.IOException: Post failed with error code 500
10-05 21:26:47.309 443-1181/com.example.shashi.pushnotification E/URL:
     > http://shashi8600.esy.es/gcm/register.php


text:
Q: Two dice: $\Pr(X_1 \lt X_2 \mid X_1 \leq X_2)$
This question comes from a completed, marked, and returned exam. It will not likely be reused.

Problem
The problem statement gives a fair die labeled 1-6. Let $X_1,X_2$ denote the two observed labels on two rolls. True or False: $\Pr(X_1 \lt X_2 \mid X_1 \leq X_2)=\frac{5}{7}$?
Work
I erroneously concluded during the exam that the conditional probability was certain, having flipped the two expressions in my work. I marked false.
The given answer is true, yet I am unable to convince myself of it, even with simple counting arguments. I was able to conclude from definitions that the probability given is equivalent to $$\frac{\Pr(X_1 \lt X_2 \cap X_1 \le X_2)}{\Pr(X_1 \le X_2)}$$
I have been unable to precede: my other argument goes something like

*

*if $X_2$ is 2, the conditional probability is $\frac{1}{2}$;

*if $X_2$ is 3, the conditional probability is $\frac{2}{3}$;

&c. But the sum will be greater than 1. Of course, the probability for $X_2$ is $\frac{1}{6}$, so we try $$\frac{1}{6}\sum_{1 \le i \le 5}{\frac{i}{i+1}} \neq \frac{5}{7}$$
Question
At any rate, I am unable to reach $\frac{5}{7}$ via these arguments. What reasoning leads to the conclusion?

A: $$\mathbb P\{X_1<X_2\mid X_1\leq X_2\}=1-\mathbb P\{X_1=X_2\mid X_1\leq X_2\}.$$
Now, $$|\{X_1\leq X_2\}|=1+2+3+4+5+6=21$$
and $$|\{X_1=X_2\mid X_1\leq X_2\}|=6.$$
Therefore, $$\mathbb P\{X_1=X_2\mid X_1\leq X_2\}=\frac{6}{21},$$
and thus
$$\mathbb P\{X_1<X_2\mid X_1\leq X_2\}=1-\frac{6}{21}=\frac{15}{21}=\frac{5}{7}.$$

A: There are $21$ die rolls where $X_1 \leq X_2$, each equally likely.  Of those, in $6$ of them, $X_1 = X_2$, so in the remaining $15, X_1 \lt X_2.$  Therefore, your answer is $15/21 = 5/7.
The problem with your reasoning is that given that $X_1 \leq X_2$, the possible values of $X_2$ are not equally likely.


text:
Q: Why is my background image not working? I been trying to solve this for a few days now. My background image isn't showing but the image size (blank space) does.
Here is my code
HTML

Let talk! contact us via e-mail, phone or text coming soon

CSS
#contact{
 background-image: url("C:\Users\omar\Pictures\notaryweb/redphone.JPG");
width: 100%;
height: 105%;
background-repeat: no-repeat;
}

Also not sure if this matters but I have
body{
background-color: #dddddd;
}

in the beginning of my css sheet, and the background image is in the "body".
Thanks in advance for all your help, very detail answers are preferred.

A: You can do two things........ 1st thing changing the image location and save where you save your html file ...
2nd thing
#contact{
 background-image: url("C:\Users\omar\Pictures\notaryweb\redphone.JPG");
width: 100%;
height: 105%;
background-repeat: no-repeat;
}

use this your mistake is you use forward slash it will be backward slash..

A: You have to use file:/// in your path. like below
background-image: url("file:///C:/Users/omar/Pictures/notaryweb/redphone.JPG");

Also, make sure file do exist.

A: you are making slash mistake please put back slash "\"
wrong:
url("C:\Users\omar\Pictures\notaryweb/redphone.JPG")
correct:
url("C:\Users\omar\Pictures\notaryweb\redphone.JPG")
and make sure you have picture available on this path.

A: It is always a better practice to keep your images in the context path of your web. Better to create an images folder in your web and use it. Doing so, will also not require you to replace your forward slashes with backward slashes.

A: You should change C:\Users\omar\Pictures\notaryweb/redphone.JPG to C:\Users\omar\Pictures\notaryweb\redphone.JPG.
Also you should change height: 105% from percentage to height: 105px.


text:
Q: What Tanstack testing API are they referring to for todos? Newbie question: Do I have to create my own api or is there a pre-existing "todo" api they are referring to?
Also curious if there are api's for other Doc examples in tanstack.
https://react-query-v3.tanstack.com/guides/mutations
I was looking in the tanstack docs but I did not see any "todo" api links.


text:
Q: jQuery - braces of a POST request I found the following code for a jQuery POST request. I don't understand the braces, isn't it closed already before the .done function is called?
var jqxhr = $.post( "example.php", function() {
 alert( "success" );
})
 .done(function() {
   alert( "second success" );
 })
 .fail(function() {
   alert( "error" );
 })
 .always(function() {
   alert( "finished" );
});

A: $.post is a function, which is stored in a property (post) of an object stored in the $ variable.
$.post() calls that function and returns a return value (in this case, a jqXHR object).
$.post().done is another function, which is stored in a property (done) of the value returned from calling $.post().

A: It's called chaining.
"something".length.toString().length.toString();
Each method is called on the result of the previous method.

A: It's done, but it returns a jqXHR object, to which you can still apply functions, e.g.: http://api.jquery.com/jQuery.ajax/#jqXHR


text:
Q: Error: .ini file does not include supervisorctl section in UBUNTU I have installed supervisor in my ubuntu-18. But when i type the command supervisorctl, [enter image description here][1]It's through a Error as Error: .ini file does not include supervisorctl section and some times http://localhost:9001 refused connection.
when i type the command sudo supervisorctl it thorough a error pkg_resources.DistributionNotFound: The 'supervisor==3.3.1' distribution was not found and is required by the application.


text:
Q: How to use a pre-populated sqlite database my App in Flutter As the question in the title says.
My database file could be pretty large so I don't want to make copies of it unnecessarily and I certainly don't want to build it in situ.
If the db file is a flutter asset, is there a way for sqlite to access it directly?
I've seen suggestions that I should copy the raw data of the asset into a file and then access it but that is a waste of storage.  Or can I then delete the asset?
Is there a simple way of deploying the database as something other than an asset, ie as a raw file?

A: iOS (and, I think, Android?) will require you to copy the file into the app's working directory first. This is standard practice, and it's part of working within a protected file system. If somehow it's a deal killer to have copies in both your app bundle (consider this the pristine "master") and app documents folder (the "working copy"), I suppose you could also download it from a server on initial app launch, but... time is money.
It's truly not that big a deal, though. To do so, ensure the file in included in the app bundle via your pubspec.yaml file:
flutter:
  assets:
    - assets/stored_data.db

Then, before opening the database, copy it from the app bundle to your documents directory:

Edit: The following apparently fails to copy large files; see iKK's comment below if you experience such issues, as it looks like he's found a native solution. For smaller files, however, this should work fine.

// Create a new file within your document directory (Probably want to check whether it already exists first...)

Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "working_data.db");

ByteData data = await rootBundle.load(join("assets", "stored_data.db"));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await new File(path).writeAsBytes(bytes);

Now that you have the database within your app's document directory, you should be able to open it from the path. If you're using the tekartik/sqflite package (which is where I originally got these instructions), for instance, you can simply:
Database db = await openDatabase(path); // Opens SQL database, working_data.db

There's no reason (or ability) to delete the pristine copy from the app bundle (which would alter the original binary -- a huge nono). Eventually, the OS itself may end up offloading such dreck to a cloud server or other memory-management service, but that's for the platform to decide.


text:
Q: temporary storage in Oracle? I need to store output of a query(which returns multiple rows) temporarily in Oracle. One of the ways to do this is using temporary table and I am using that currently. But the problem with them is that they stay around and cannot be created and dropped in a procedure willy nilly. Is there another object that I can use to temporarily store the output of a query to be able to use in the stored procedure ?
Here is my stored procedure for reference:
create or replace PROCEDURE procPrintOutput
IS
  l_stmt VARCHAR2(512) := '';
  create_table_stmt VARCHAR2(512) := 'create GLOBAL TEMPORARY TABLE temp(matViewLogQuery CLOB) ON COMMIT DELETE ROWS';
  drop_mat_view_logs_stmt VARCHAR2(100) := 'DROP MATERIALIZED VIEW LOG ON ';
  drop_temp_table VARCHAR2(512) := 'DROP TABLE temp';

  ref_cursor SYS_REFCURSOR;
BEGIN
    EXECUTE IMMEDIATE(create_table_stmt);
    DBMS_OUTPUT.PUT_LINE('created temp table');
    DECLARE
    CURSOR LIST_OF_MVL IS SELECT * FROM USER_MVIEW_LOGS;
    CURSOR CREATE_MVL IS SELECT * FROM temp;
    BEGIN
            FOR TEST IN LIST_OF_MVL
          LOOP
            BEGIN
              DBMS_OUTPUT.PUT_LINE('owner : ' || TEST.OWNER || ' - name : ' || TEST.MASTER);
              l_stmt := 'insert into temp SELECT SYS.DBMS_METADATA.get_dependent_ddl (''MATERIALIZED_VIEW_LOG'', '''||TEST.MASTER||''', '''||TEST.LOG_OWNER||''') from dual';
              EXECUTE IMMEDIATE (l_stmt);
              EXECUTE IMMEDIATE (drop_mat_view_logs_stmt || TEST.MASTER);
              DBMS_OUTPUT.PUT_LINE('view dropped ... ');
            END;
          END LOOP;

      FOR CREATE_SCRIPT IN CREATE_MVL
        LOOP
          BEGIN
            DBMS_OUTPUT.PUT_LINE('SCRIPT : ' || CREATE_SCRIPT.matViewLogQuery);
            EXECUTE IMMEDIATE(CREATE_SCRIPT.matViewLogQuery);
            DBMS_OUTPUT.PUT_LINE('view recreated ... ');
          END;
        END LOOP;
  END;
  EXECUTE IMMEDIATE(drop_temp_table);
  DBMS_OUTPUT.PUT_LINE('Done! Table dropped');
  ROLLBACK;
END;

Thanks

A: instead of of temp table you can use collection in pl/sql and store all information that you need into the collection by BULK COLLECT
here small example
in my example I collect all DDLs for matviews and name of the views, then in simple cycle we can do any operations...
DECLARE
   TYPE tDDL IS record (name varchar2(30), ddl CLOB);
   TYPE tblDDL IS TABLE OF tDDL INDEX BY PLS_INTEGER;
   l_ddls tblDDL;
BEGIN

   SELECT object_name, dbms_metadata.get_ddl('MATERIALIZED_VIEW', object_name)
   BULK COLLECT INTO l_ddls
     from user_objects
        where object_type= 'MATERIALIZED VIEW';

   FOR indx IN 1 .. l_ddls.COUNT
   LOOP
      --do what you need with collected DDLs
      DBMS_OUTPUT.PUT_LINE('view dropped ... ');

      --your complex execute immediate logic here
      dbms_output.put(l_ddls(indx).name);
      dbms_output.put('     :     ');
      dbms_output.put_line(substr(l_ddls(indx).ddl, 100));

      DBMS_OUTPUT.PUT_LINE('view recreated ... ');
   END LOOP;
END;


text:
Q: Fullcalendar plugin Javascript error on hover I did not have enough knowledge about JavaScript, that is why I am asking this question. On my website's employee roster dashboard I got some javascript error when hovering on some dates, like the date 8th,9th and 7th september. onhover it is showing a box with 'null' error message. Can it be removed?
I am using 'full calendar' plugin to show this dates.
Here is my dashboard.
http://www.zaika.com.au/sarkar/ab7/index.php/dashboard

A: I'm sure there is a hover event to the server that is being called but the hack solution is to give this css, which essentially "gets rid of it" but its going to take longer to trace down the fullcalender intiation, i want to say this is the case of you calling an ajax to your server to request information on these events, but it's not quite clear where that is happening:
.tooltipevent{
    display: none !important;
    visibility: hidden !important;
    opacity: 0;
}

Okay I read through the file and found the offending js....
$('#calendar').fullCalendar({ //re-initialize the calendar
            disableDragging: true,
            //header: h,
            header: {
                left: '<input type="text" value="subhash">',
                center: 'title',
                right: 'prev,next'
            },
            /* viewRender: function(view, element) {
                $('#calendar').fullCalendar( 'gotoDate', 2014, 4, 24 );
             }, */
            editable: true,
            selectable: true,
            selectHelper: true,
            dayRender: function(date, cell){
                if (date < futureBlockDate){
                    $(cell).addClass('fc-cell-overlay');
                }
                //$(cell).addClass('fc-cell-overlay')
            },
            dayClick: function(date, allDay, jsEvent, view) {

                var SelectedDate=(date.getFullYear() + '-'+number_change(date.getMonth() + 1) + '-' + number_change(date.getDate()));
                $('#start_date').val(SelectedDate);
                $( ".datepicker" ).datepicker( "option", "minDate", date);
                if(!$(this).hasClass('fc-cell-overlay')){
                $('#deleteEvent').hide();
                $('#title_popup').html('Create');
                $('#editId').val();
                $('#stack1_click').trigger('click');}
            },
            eventClick:  function(event, jsEvent, view) {

                var unid=event.id;
                var type=event.type;
                if(type=="leave"){
                    var reason = event.reason;
                    var startDate = new Date(event.start);
                    var endDate = new Date(event.end);
                    var Start=(startDate.getFullYear() + '-'+number_change(startDate.getMonth() + 1) + '-' + number_change(startDate.getDate()));
                    var End=(endDate.getFullYear() + '-'+number_change(endDate.getMonth() + 1) + '-' + number_change(endDate.getDate()));

                    $('#editId').val(unid);
                    $('#reason').html(reason);
                    $('#start_date').val(Start);
                    $('#end_date').val(End);
                    $('#deleteEvent').show();
                    $('#title_popup').html('Update');
                    $('#stack1_click').trigger('click');
                }
            },
             events: {
                url: base_url+'employees/fetch_events',
            },
            eventMouseover: function(calEvent, jsEvent) {

                if(calEvent.message!="" && typeof(calEvent.message)!="undefined"){
                var tooltip = '
' + calEvent.message + '
';
                $("body").append(tooltip);
                $(this).mouseover(function(e) {
                    $(this).css('z-index', 10000);
                    $('.tooltipevent').fadeIn('500');
                    $('.tooltipevent').fadeTo('10', 1.9);
                }).mousemove(function(e) {
                    $('.tooltipevent').css('top', e.pageY + 10);
                    $('.tooltipevent').css('left', e.pageX + 20);
                });
                }
            },
            eventMouseout: function(calEvent, jsEvent) {
                 $(this).css('z-index', 8);
                 $('.tooltipevent').remove();
            },
        });

or more succulently this piece:
eventMouseover: function(calEvent, jsEvent) {

                if(calEvent.message!="" && typeof(calEvent.message)!="undefined"){
                var tooltip = '
' + calEvent.message + '
';
                $("body").append(tooltip);
                $(this).mouseover(function(e) {
                    $(this).css('z-index', 10000);
                    $('.tooltipevent').fadeIn('500');
                    $('.tooltipevent').fadeTo('10', 1.9);
                }).mousemove(function(e) {
                    $('.tooltipevent').css('top', e.pageY + 10);
                    $('.tooltipevent').css('left', e.pageX + 20);
                });
                }
            },

I don't know what you intend to do with calEvent.message but what you can do is change this if test to, so that all "falsy" values are ignored (including your test for empty strings, undefined and null) which will all produce a false:
if(calEvent.message)


text:
Q: Need some ideas about a workflow design I want to start building a technical support application as a personal project, using Windows Workflow Foundation 4 for implementing the business process.I'm very new to WF and BPs but that's why i am doing this. Did some research and I found that a state machine workflow will be best suited for this as it is a long running process with lots of human intervention. So basically the flow I thought of will be like this:

*

*user submits a form with all the
required data.

*a Ticket object is created and passed
in as an InArgument for the workflow.
The ticket is now in the Pending
state and waits for a ResumeBookmark
call when a admin opens the ticket.

*the admin assigns (meaning that some
of the object properties will be
initialized/modified/etc and also
some db tables) the ticket to a
engineer and it goes into a Assigned
state. And so on..
Now my problem is: I can't figure out a way to add some level of complexity of the State activity flow other than modifying the object properties. By complexity I mean a way to make use of this technology, because for now i don't see the upside of this compared to a  imperative implementation.
any ideas are well received .thanks in advance

A: First, I'd recommend picking up the book Pro WF: Windows Workflow in .NET 4.0 and working through the tutorials (if you haven't yet). While it's not perfect, it covers many of the important topics.
For a long-running process you're almost certainly going to want to implement persistence. Otherwise if your server goes down, running workflows disappear. Also consider hosting under IIS.
Subscribe to The Problem Solver and check out his answers on SO. He also has an Introduction to WF 4 video series. There are several videos by others on Channel 9, too.
State Machine doesn't come out of the box; it's a separate download. It's not required, though - you could use Sequential, Flowchart, or a combination to achieve what you want.
Be prepared to write custom activities. (See the Channel 9 videos, especially Leon Welicki's.) You'll have to implement security, locking, worklists, etc. if those are part of your requirements. WF is not a BPM system out of the box.
Finally, don't be intimidated. This is all doable, and WF 4 is a well-thought-out framework. Just be prepared to spend considerable time learning and implementing this.

A: I found this worked example useful for hosting a WF4 service under WCF. It also covers a number of key concepts you can explore further:
http://programming4.us/Enterprise/332.aspx


text:
Q: Trying to install phabricator on ubuntu ec2 instance, always redirects to default index page I'm trying to install Phabricator on an AWS web instance, but I'm having trouble configuring apache to get anything other than the Apache2 Ubuntu default page to show up.
I create
<Directory "/home/ubuntu/phabricator/phabricator/webroot">
  Require all granted
</Directory>

<VirtualHost *:8080>
  # Change this to the domain which points to your host.
  ServerName -##-##-###-###.us-west-2.compute.amazonaws.com

  # Change this to the path where you put 'phabricator' when you checked it
  # out from GitHub when following the Installation Guide.
  #
  # Make sure you include "/webroot" at the end!
  DocumentRoot /home/ubuntu/phabricator/phabricator/webroot

  RewriteEngine on
  RewriteRule ^/rsrc/(.*)     -                       [L,QSA]
  RewriteRule ^/favicon.ico   -                       [L,QSA]
  RewriteRule ^(.*)$          /index.php?__path__=$1  [B,L,QSA]
</VirtualHost>

In /etc/apache2/sites-available
I then run
sudo a2dissite 000-default.conf
sudo a2ensite phabricator.conf
service apache2 reload

But when I load http://ec2-##-##-###-###.us-west-2.compute.amazonaws.com/ the default apache configuration page still shows up.  How comes its not disabled?


text:
Q: JSQMessagesViewController loading from cache I am using JSQMessagesViewController with Parse.com. I am trying to implement caching in the chatController as well.
my cache code looks like this:
        if query.hasCachedResult{
        query.cachePolicy = .cacheThenNetwork
        } else{
        query.cachePolicy = .networkOnly
        }

Since using .cacheThenNetwork I am dealing with the data twice. First from cache, then from Network.
In order to handle this in my PFQuery.findObjectsInBackground I use:
self.messages.removeAll()
self.users.removeAll()

after having found objects.
The Problem:
When I reload the data by e.g. pressing the send button.
the CollectionViewis trying to fetch data, that is not yet downloaded.
    override func collectionView(_ collectionView: JSQMessagesCollectionView!,
    messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {

    return self.messages[indexPath.item]
}

Will cause an exception.
How can I make stop the VC from loading the details before it finished loading?
The Loading and Adding of messages to the collectionView is implemented from another Project:


text:
Q: How to Deploy a Custom Model trained in Azure ML Studio Designer using Azure Devops I want to create a complete End to End ML system, where I train several models and deploy the best.
Currently, I have an End-to-End System where I used The Azure ML SDK with Azure DevOps.
Architecture currently in use:

Here all the Training jobs are run using the Azure ML SDK. They are launched within Azure DevOps.
Now, I want to use the Azure ML Pipeline for Model Training and Registering instead of using the Azure ML SDK.
Azure ML Training Pipeline:

How can I use the models trained in the Azure ML Studio Pipelines and deploy it using Azure DevOps?
Currently, I pass the metadata generated from the Azure Training jobs to the CD pipeline as artifacts, and then from there, I can deploy the best model.
Now with Azure Pipeline, how can that be done?

A: We can deploy using batch or real-time endpoint. Created a sample application with multiple models in the single pipeline. We need to get the individual model result into registration and then click on deploy in the model's section to get deployed from the pipelines perspective.

We can create any type of clusters or instances for deployment.

Using any kind of real-time endpoint and deploy the model.


text:
Q: Is it possible to send Calendar invite in Windows Phone? Is it possible to send a calendar invite through Windows Phone 7 programatically. I currently am able to open the email composer with some default text. But I need to include a schedule in it so that it goes as a calendar invite as opposed to a plain text email.
EmailComposeTask email = new EmailComposeTask();
email.Subject = "Invitation for an envent";
email.Body = "Attend this event on June 21 2012";
email.Show();

How do I do that?

A: The ability to do this is not available with the framework as it is today.
If you need to send appointments/invites via email you'll need to send these from an external source (which you could, of course, trigger from your app).


text:
Q: Obtain particular node tag value from XML with batch I have an XML file like this one:
<config>
    <intensity>0</intensity>
    <variables>
        <variable>
            <name>TONE</name>
            <value>3</value>
            <type>UNSIGNED8</type>
        </variable>
        <variable>
            <name>V_SIC</name>
            <value>0</value>
            <type>UNSIGNED8</type>
        </variable>
        <variable>
            <name>H_YPE</name>
            <value>9000</value>
            <type>INTEGER16</type>
        </variable>
        <variable>
            <name>NUM_SIC</name>
            <value>0</value>
            <type>UNSIGNED8</type>
        </variable>
    </variables>
</config>

I'm trying to get the value text from the node with the name H_YPE into a variable, so in this example, the variable should have 9000. If the node H_YPE is not on the XML, simply store a 1.
I saw This answer and tried what Magoo implements, and while I can see that the values are being parsed, I'm interested in obtaining just the one value and storing it in a variable for later use.
Apparently I'm not very savvy with batch scripts, so any and all help with this would be appreciated, thanks in advance.

A: A batch file processed by the Windows Command Processor cmd.exe is the worst choice for processing an XML file because there is no built-in support for real XML processing.
The following batch file code could be used if the XML file is always structured as shown in the question.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Value=1"
if not exist "File.xml" goto ProcessValue
set "NameTagFound="
for /F "tokens=2,3 delims=<>" %%I in ('%SystemRoot%\System32\findstr.exe /R "<name>H_YPE</name> <value>[0123456789]*</value>" "File.xml"') do (
    if "%%I" == "name" (
        if /I "%%J" == "H_YPE" set "NameTagFound=1"
    ) else if defined NameTagFound (
        if "%%I" == "value" (
            if not "%%J" == "" set "Value=%%J"
            goto ProcessValue
        )
    )
)
:ProcessValue
echo Value is: %Value%
endlocal

Please note following requirements for the structure of the data in the XML file:

*

*There must be leading spaces/tabs left to the start tags <name> and <value> because of tokens=2,3 delims=<> and the two elements must be on separate lines not containing any other element or attributes.

*An element name with value H_YPE must exist only within element variable and not within another element because of the code does not check where <name>H_YPE</name> is found in the file.

*The element name with value H_YPE must be inside the element variable on a separate line above the line with the element value. So the order of the elements name and value cannot be changed without adapting the code.

*The element variable with the element name with value H_YPE must have also the element value or the value of next element value found anywhere below the line with <name>H_YPE</name> is assigned wrongly to the environment variable Value instead of using the default value 1.

*The value H_YPE must be always in the XML file with this spelling (all letters in upper case).

The code could be enhanced to do more XML structure checks if one of the five requirements is not always fulfilled by the XML file contents.
XML tags are case-sensitive according to XML specification. Therefore this code runs FINDSTR also case-sensitive although the value H_YPE could be in any case per XML specification. The IF conditions comparing strings are also case-sensitive for the same reason including the IF condition which checks for value H_YPE.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

*

*echo /?

*endlocal /?

*findstr /?

*for /?

*goto /?

*if /?

*set /?

*setlocal /?


text:
Q: How do I repeat the button when it is clicked multiple times? For example, when I click 111222, display will show 111222.
let display = document.querySelector('.display');

let numberButtons = document.querySelectorAll('.number').forEach(function(numberButtons){
    numberButtons.addEventListener('click', showNumber)
    function showNumber(){
        display.innerHTML = numberButtons.innerHTML
    }
});

0

      <button class='number' id='one'>1</button>
      <button class='number' id="two">2</button>

A: you need to append instead:
display.innerHTML += numberButtons.innerHTML


text:
Q: Rails 4 assets is not working as expected I have a Rails 4.2 project which is working fine. Recently I added one image and is working fine DEV ENV. But in PROD it is not working.
rails c -e production
Loading production environment (Rails 4.2.6)
.bundle :001 > puts helper.asset_path("select.png")
helper.asset_path("select.png")

gives
      /assets/select-76e7d10e7bc2f4f5c52248424f10ccbe24efd6384e0be58f2c9ad15f330abc9b.png
If I simply tried <%= image_tag("select.png") %> in application.html.erb file, it works. But not in any CSS files. I tried all the below options
background: url('select.png');
background :url('<%= image_tag("select.png") %> ');
background: url('<%= asset_path("select.png") %>')

Nothing seems to be working
Note:- I am using compass-sass


text:
Q: How to learn about designing highly transactional systems? I have been mostly working on data analysis, BI tools, etc. in my career. Most of the applications I work on are majorly read-only applications. Although I have also worked on simple CRUD applications but nothing extraordinarily transactional.
As a software engineer, I feel there is a void in my learning if I don't know how to design highly transactional systems and databases, like how Amazon, airline systems, etc. work.
I would like to ask the community here to suggest some resources, books or simple projects on this subject. Something that can take hands-on approach whilst teaching about the necessary theory. I know this is a subjective matter but I can mark the most useful answer green.
Looking forward to your suggestions and thanking in anticipation.

A: I am going to organize the answer in four broad categories, namely

*

*theoretical and academic background,

*popular sources,

*software and tools, and

*exercises.

Books and Papers
This are the foundations of the field - how to go from 0 to quite a decent, expertly level, but mostly theoretically.
Intro Level
Transaction Processing: Concepts and Techniques (The Morgan Kaufmann Series in Data Management Systems) by Jim Gray
Silberschatz book (Database System Concepts) in the later chapters covers internal workings of the advanced transactional systems, has some resources, etc.
Database Specific
H-store paper - describes benefits of in-memory design for high transactional loads. H-store work has inspired development of VoltDB.
Calvin paper - Fast Distributed Transactions
for Partitioned Database Systems. Gives a very good background, related work, and an insight into the state of the art.
Architecture of a Database System by Hellerstein, Stonebraker and Hamilton
covers many aspects.
Limitations and Boundaries
Great paper on virtues and limitations of highly available transactions.
CAP Theorem paper - On the design tradeoffs of consistency, availability and partitioning for large scale systems. Very important.
Parallel Processing and Parallel Databases
Popular and Current Sources
Blogs
High Scalability is a perfect blog for what you are looking for.
Here is, for example, a great entry on the evolution of Amazon's architecture.Very close to what you've been looking for.
Facebook, LinkedIn, and Twitter engineering blogs are great resources. I would also check Google Research site and their Google+. Netflix is not bad either.
Conferences
VLDB and SIGMOD conferences (inluding SIGMOD blog) are where most of the most advanced data systems are presented by the researchers/academia, and the corporations.
HPTS is an interesting conference/workshop with the good agenda and publications.
I would even check USENIX series for cutting edge, systems stuff.
Case Study Architectures
VoltDB is an ultra-transaction, in-memory database, designed by Mike Stonebraker, ACM fellow, and "father" of the most modern database concepts.
IBM mainframe still has a very prominent place in the world of high volume transactional
processing. At the time of the writing of this answer, they are touting their Z13 system for extreme, encrypted transaction processing volumes.
If you are interested in doing transactions the "Big Data" style, there are lots of choices, but HBase is probably the most interesting one.
Here are some suggested reading sources for HBase:
Yahoo's Omid built on HBase
Transactions over HBase
Another interesting architecture is Twitter, now Apache Storm.
and Apache Kafka for streaming and real-time processing.
Benchmarks and Exercises
If you want to try few things out, look at the TPC family of benchmarks. There are transactional, ETL, BI, and decision support/mixed load analytic benchmarks.
These are relational-oriented.
You can take these benchmarks and practice them against the open source SMP (e.g. postgres, MySQL) and MPP databases such as Greenplum (a link to a great and comprehensive documentation on querying, performance, some sample setups, and how MPP databases process queries).
I recommended these practical scenarios and architectures for HBase-oriented transactional systems.
For state-of-the-art message and actor oriented transactional systems, you will probably need to buy a book or two.
   For Akka (which serves as an internal to Spark) you could probably use Akka in Action and go through the exercises at the end of each chapter.
There are also some exercises from the training sessions here.
For stream processing, here are some good exercises with Apache Kafka (parts 1 and http://www.confluent.io/blog/stream-data-platform-2/). Cloudera has a good "getting started" guide.
To practice message-oriented state-of-the-art systems, I would suggest Getting Started with Storm, and perhaps going through these exercises. There are number of real-topologies featured.
For good, old JMS, you can use this online reference for practice, or
go more sophisticated with these Active MQ exercises.
If you want to torture yourself with the mainframe, try this emulator.
It emulates IBM's OS/370-390.


text:
Q: apache proxyremote and http ProxyRemote syntax is:
<remote-server> = <protocol>://<hostname>[:port]

So, I have to put protocol before hostname.
But my proxy server is x.y.z.n:1234 (without http)
And when I use proxyremote in this way, it doesn't work. (nothing happens)
ProxyRequests On
ProxyRemote http http://x.y.z.n:1234

If I remove http:// from proxy url, Apache returns an error:
ProxyRemote: Bad syntax for a remote proxy server

How to resolve it?
Thanks.


text:
Q: Is there any way to validate only the enabled fields in the form using javascript? I am just doing simple IP Validation on the fields inside my form. There are 12 such fields which areundergoing this validation according to my current logic. Now I want to validate only those fields which are enabled and ignore the validation for the disabled fields.
Note: I am disabling fields based on the logic and I have not set disabled attribute in html for these fields.
Function EnableDisableDropDown is disabling the Controller B part. I dont want the validation to be performed on fields of Controller B.
JS Part
const ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    for (let i = 0; i < 4; i++) {

    if (ipformat.test(mcIps[i].value)== false) {
        return dialog('Invalid MC_IP Address');
    }
    else if (ipformat.test(mcNetmasks[i].value)== false){
        return dialog('Invalid MC_Netmask Address');
    }
    else if (ipformat.test(mcGateways[i].value)== false){
        return dialog('Invalid MC_Gateway Address');
    }
    }

function EnableDisableDropDown(abc) {
    var selectedValue = abc.options[abc.selectedIndex].value;
    var elems=document.querySelectorAll(".mc_ip,.Netmask_IP,.Gateway_IP,.RBOD_MC,.RBOD_SC,.RBOD_EC,.RBOD_FU,.ISCSI_IP,.CONTROLLER_ID");
    for(i=8; i<16; i++){
    //elems.disabled = selectedValue == '2' ? false : true;
    elems[i].disabled = selectedValue == '2' ? false : true;
}
    for(i=24; i<32; i++){
    //elems.disabled = selectedValue == '2' ? false : true;
    elems[i].disabled = selectedValue == '2' ? false : true;
}
}

HTML Part

Additional Details Required for Controller A

  Controller_ID:
  <select class="CONTROLLER_ID" id='Controller_ID1' required>
    <option value=""> - Select the Controller ID - </option>
    <option value='A'>A </select>
  iSCSI IPs:<input class="iSCSI_IP" type='text' name='iSCSIip1' id="ip1" placeholder='Enter iSCSI ips' disabled="disabled" />
  HBA_Ports:<input class="hba_ports" type='text' id="hba" name='hba_ports1' placeholder='Enter the HBA Ports' disabled="disabled" />
  MC_IP:<input class="mc_ip" type='text' name='extra_ip1' id='mc_ip' placeholder='Enter the MC_IP'  />
  MC_Netmask:<input class="Netmask_IP" type='text' id='netmask_ip1' placeholder='Enter the MC_Netmask' />
  MC_Gateway:<input class="Gateway_IP" type='text' id='gateway_ip1' placeholder='Enter the MC_Gateway'  />
  MC:<input class="RBOD_MC" type='text' id='rbod_mc1' placeholder='Enter the MC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  SC:<input class="RBOD_SC" type='text' id='rbod_sc1' placeholder='Enter the SC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  FU:<input class="RBOD_FU" type='text' id='rbod_fu1' placeholder='Enter the FU Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  EC:<input class="RBOD_EC" type='text' id='rbod_ec1' placeholder='Enter the EC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />

Additional Details Required for Controller B

  Controller_ID:
  <select class="CONTROLLER_ID" id='Controller_ID' required>
    <option value=""> - Select the Controller ID - </option>
    <option value='B'>B </select>
  iSCSI IPs:<input class="iSCSI_IP" type='text' name='iSCSIip2' id="ip2" placeholder='Enter iSCSI ips' disabled="disabled" />
  HBA_Ports:<input class="hba_ports" type='text' id="hba1"  placeholder='Enter the HBA Ports' disabled="disabled" />
  MC_IP:<input class="mc_ip" type='text'  id='mcip' name='extra_ip' placeholder='Enter the MC_IP'  />
  MC_Netmask:<input class="Netmask_IP" type='text'  id="netmaskip" placeholder='Enter the MC_Netmask' />
  MC_Gateway:<input class="Gateway_IP" type='text'  id="gatewayip" placeholder='Enter the MC_Gateway' />
  MC:<input class="RBOD_MC" type='text' name='rbod_mc' placeholder='Enter the MC Port' id="rbodmc" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  SC:<input class="RBOD_SC" type='text' name='rbod_sc' placeholder='Enter the SC Port' id="rbodsc" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  FU:<input class="RBOD_FU" type='text' name='rbod_fu' placeholder='Enter the FU Port' id="rbodfu" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  EC:<input class="RBOD_EC" type='text' name='rbod_ec' placeholder='Enter the EC Port' id="rbodec" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />


text:
Q: How to remove NA value from the plot with ggplot? I Have data.frame A(3 columns: x,value and SD)  with NA value for the same row of the three columns.
I plot in ggplot with standard deviation (SD), the code is:
p <- ggplot(A,aes(x=x,y=value))
p + geom_ribbon(aes(ymin=value-SD,ymax=value+SD),fill = "gray",na.rm=T)+
  geom_line(aes(y=value))+
  theme_bw()+ theme(panel.border = element_blank(), panel.grid.major = element_blank(),
                    panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))

the results is:

I would not plot the NA value (in the above plot the gray square with black line), how I can do it? I need plot subset of my df A?
Thank you

A: Here are two options for plotting gaps:
# create sample data
set.seed(1)
df <- data.frame(x=1:100, y=runif(100),SD=0.1)
df[45:55, c("x", "y", "SD")] <- NA

# option 1: groupings
ggplot(df, aes(x, y, group=cumsum(is.na(df$x)))) + geom_ribbon(aes(ymin=y-SD,ymax=y+SD),fill = "gray") + geom_line()

# options 2: interpolations
ggplot(df, aes(zoo::na.approx(x), y)) + geom_ribbon(aes(ymin=y-SD,ymax=y+SD),fill = "gray") + geom_line()

A: First some example data
A = data.frame(x = 1900:2000, value=cumsum(rnorm(101)), SD= 0.5)
A[50:60, 2:3] = NA

If I understand your question, you more or less had the answer. Just change na.rm to FALSE
p = ggplot(A,aes(x=x,y=value))
p + geom_ribbon(aes(ymin=value-SD,ymax=value+SD),fill = "gray",na.rm=FALSE)+
  geom_line()+
  theme_bw()+
   theme(panel.border = element_blank(), panel.grid.major = element_blank(),
                    panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))


text:
Q: perf stats on AMD 15h According tot he BKDG of AMD 15h (page 588), it is possbile to disable the
hardware prefetcher by setting some bits of MSRC001_1022
MSRC001_1022 Data Cache Configuration (DC_CFG)
Bits    -->  Description
63:16   -->  Reserved.
15      -->  DisPfHwForSw. Read-write. Reset: 0. 1=Disable hardware prefetches for software prefetches.
14      -->  Reserved.
13      -->  DisHwPf. Read-write. Reset: 0. 1=Disable the DC hardware prefetcher.
12:10   -->  Reserved.
9:5     -->  Reserved.
4       -->  DisSpecTlbRld. Read-write. Reset: 0. 1=Disable speculative TLB reloads.
3:0     -->  Reserved.

In order to disable all prefetch configs, I have to write 0xA008 to
that MSR. I did that for all 32 cores using
[root <at> tiger exe]# wrmsr -a 0xc0011022 0xA008
[root <at> tiger exe]# rdmsr -a -x -0 0xc0011022
000000000000a008
...

However, when I run perf along with the command, the prefetch stats
are non-zero!
[root <at> tiger exe]# perf stat -e
L1-dcache-loads:uk,L1-dcache-prefetches:uk,L1-dcache-prefetch-misses:uk ./bzip2_base.amd64-m64-gcc44-nn
spec_init
Tested 64MB buffer: OK!
 Performance counter stats for './bzip2_base.amd64-m64-gcc44-nn':
    55,341,597,193 L1-dcache-loads:uk
     1,047,662,614 L1-dcache-prefetches:uk
                 0 L1-dcache-prefetch-misses:uk
      35.921618464 seconds time elapsed

I expect to see 0 in front of  L1-dcache-prefetches. Don't you?
How can I debug the counters in order to find out how they are mapped to the MSRs?

A: Mapping of synthetic perf names for hw counters (listed by perf list) are defined inside kernel sources of perf_events subsystem for many CPUs. For amd they are in arch/x86/events/amd/core.c file. In 4.8 version of kernel and amd cpu cache events are mapped to cpu-specific constants to be written into PMC MSRs as:
http://elixir.free-electrons.com/linux/v4.8/source/arch/x86/events/amd/core.c
static __initconst const u64 amd_hw_cache_event_ids
 ... =  {
 [ C(L1D) ] = {
    [ C(OP_READ) ] = {
        [ C(RESULT_ACCESS) ] = 0x0040, /* Data Cache Accesses        */
        [ C(RESULT_MISS)   ] = 0x0141, /* Data Cache Misses          */
    },
    [ C(OP_WRITE) ] = {
        [ C(RESULT_ACCESS) ] = 0,
        [ C(RESULT_MISS)   ] = 0,
    },
    [ C(OP_PREFETCH) ] = {
        [ C(RESULT_ACCESS) ] = 0x0267, /* Data Prefetcher :attempts  */
        [ C(RESULT_MISS)   ] = 0x0167, /* Data Prefetcher :cancelled */
    },
 },
 [ C(L1I ) ] = {
    [ C(OP_READ) ] = {
        [ C(RESULT_ACCESS) ] = 0x0080, /* Instruction cache fetches  */
        [ C(RESULT_MISS)   ] = 0x0081, /* Instruction cache misses   */
    },
    [ C(OP_WRITE) ] = {
        [ C(RESULT_ACCESS) ] = -1,
        [ C(RESULT_MISS)   ] = -1,
    },
    [ C(OP_PREFETCH) ] = {
        [ C(RESULT_ACCESS) ] = 0x014B, /* Prefetch Instructions :Load */
        [ C(RESULT_MISS)   ] = 0,
    },
 },
 [ C(LL  ) ] = {
    [ C(OP_READ) ] = {
        [ C(RESULT_ACCESS) ] = 0x037D, /* Requests to L2 Cache :IC+DC */
        [ C(RESULT_MISS)   ] = 0x037E, /* L2 Cache Misses : IC+DC     */
    },
    [ C(OP_WRITE) ] = {
        [ C(RESULT_ACCESS) ] = 0x017F, /* L2 Fill/Writeback           */
        [ C(RESULT_MISS)   ] = 0,
    },
    [ C(OP_PREFETCH) ] = {
        [ C(RESULT_ACCESS) ] = 0,
        [ C(RESULT_MISS)   ] = 0,
    },
 },

...
__init int amd_pmu_init(void)
{ ...
    /* Performance-monitoring supported from K7 and later: */
    if (boot_cpu_data.x86 < 6)
        return -ENODEV;

    x86_pmu = amd_pmu;

    ret = amd_core_pmu_init();
    ...

    /* Events are common for all AMDs */
    memcpy(hw_cache_event_ids, amd_hw_cache_event_ids,
           sizeof(hw_cache_event_ids));
    return 0;
}


text:
Q: Ember: filter model by text field I want to filter a model by a text field, the filter should be applied as the user types. I am coming from angular (not a pro but I managed to create such a filter there), so I expected this to be easy. Heh.
list.hbs:
{{input type='text' placeholder='Filter' size='50' valueBinding='searchKeyword'}}

  {{#each model.articles as |article|}}

{{{article.title}}

  {{/each}}

I know that this question is asked a lot and I did a lot of research before I decided that the amout of searching is inappropriate for such a problem and that I do not understand some core ideas of ember. It seems like that with the transition from 1.x to 2.x most examples, questions and guides are invalid. My question has been asked multiple times already:
EmberJS filter array of items as the user types
text field filtering a list using ember + ember data
Emberjs - Connecting an {{ input }} filter bar with my list of Objects. As I type, the list filters
but all of the answers use controllers. The docs say that "controllers will be replaced with components". So... how to filter a model the new way?
--
UPDATE
I used Remi's example to create this component:
export default Ember.Component.extend({

  filteredArticles: Ember.computed('articles', 'filter', function() {
    var keyword = this.get('filter');
    var filtered = this.get('articles');
    if (keyword) {
      keyword = keyword.toLowerCase().trim();
      filtered = this.get('articles').filter((item) => item.get('title').toLowerCase().includes(keyword));
    }
    return filtered;
  })

});

the computed property is used as the {{#each filteredArticles... argument and setting a property beforehand (which raised a deprecation warning) is not required anymore.

A: Components act pretty similar to controllers in some ways. You can think of them as a combination of controller+view in older ember versions. They still work in current ember. But if you want to make your issue work via components, I would suggest the following:
Lest say, you have a /templates/components/list.hbs:
{{input type='text' placeholder='Filter' size='50' valueBinding='searchKeyword'}}

  {{#each filteredArticles as |article|}}

{{{article.title}}

  {{/each}}

In one of your templates that should use the components, e.g. /templates/my-list.hbs:
{{list articles=model.articles}}

Then for your component to work, add a /components/list.js:
Ember.Component.extend({
    searchKeyword: null,
    articles: null,
    filteredArticles: null,
    updateList: Ember.computed('searchKeyword', function(){
        var keyword = this.get('searchKeyword');

        var filtered = this.get('articles').filterBy('title', searchKeyword);
        this.set('filteredArticles', filtered);
    }),
    didInsertElement(){
       this.set('filteredArticles', this.get('articles'));
    }
})


text:
Q: Video upload check "Only 30 second video will upload" I am working with PHP. I want to find a way to upload a maximum of 30 second video clips on upload. How to check that the uploaded video duration is only 30 seconds long?
Also, I want to find a way with PHP to convert a video in other formats such as MP4.
Please suggest us.

A: You can get the ID3 information of the file and probably do a check later:
$getID3 = new getID3;
$file = $getID3->analyze($filename);

// Access duration and dimensions
$duration = $file['playtime_string'];
$dimensions = $file['filesize'];

If you want to convert it in other formats there is this package PHP-FFMpeg.
Also check these resources:

*

*http://getid3.sourceforge.net/

*http://ffmpeg.org/

*Similar question: How to get video duration, dimension and size in PHP?


text:
Q: Where/how do I localize exceptions raised in a web service? Let's say I have a web service which returns a collection of images based on a passed in user. Now I call the web service with a invalid user. The call throws a UnauthorizedAccessException with a message saying the user is not authorized to get the collection.
I want this message to be localized. Where do I localize this message, on the client-side based on a error code? Or do I pass a 'language' parameter to the method in the first place? Do I use HTTP status codes so the client can localize the message?

A: Returning error codes is as bad with web services as it is in general, and for the same reason - if you require all callers to check error codes after calling the service, then some callers will fail to do so.
You should throw exceptions in the service. Those exceptions will be turned into SOAP Faults. On the client, these will appear as exceptions (for .NET clients, at least). If you choose to display the Message property of these exceptions, that's up to you. If you choose to display it, then it is also up to you to localize it - on the client.
Consider - otherwise, you have to tell the service the culture of the client, just to the service can send localized text back to the client. It's better to simply keep that information on the client.


text:
Q: Delete rows older than 14 days in MySQL
Summary

I need to purge the history of a table from rows that are older than 14 days.
Being no MySQL Expert, my searches lead me to this:
delete
    from SYS_VERROUS_POLICE
    where idModificationPolice not in (
                select distinct idModificationPolice
                    from SYS_VERROUS_POLICE
                    where date(dateHeureModification)
                            between curdate() and curdate() - interval 14 day
            );

Thrown Exception

But then I'm stuck with this error message:
Error Code: 1093. You can't specify target table 'SYS_VERROUS_POLICE' for update in FROM clause.
What the...

Context

MySQL seems to be operating in safe mode, so I just won't be able to perform a DELETE where matching dates.
In safe-mode, if I try to delete using only the date field, it doesn't comply.
delete
  from SYS_VERROUS_POLICE
 where date(dateHeureModification) < curdate() - interval 14 day

Error Code: 1175. You are using safe update mode and you tried to update a table without a
WHERE that uses a KEY column
To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
0,00071 sec

Am I missing something?

A: I understand your point about using safe mode. If you try to use UPDATE or DELETE against a non-indexed expression, it complains, because it can't make an estimate of whether you will accidentally delete your whole table.
Using an expression on DATE(dateHeureModification) > ...
 is naturally unindexed. MySQL can't do an index lookup against the result of a function.
You can use LIMIT in your delete query to make it satisfy the safe-updates mode. MySQL treats it as sufficient protection against accidentally deleting all the rows in the table, if you use LIMIT.
DELETE
    FROM SYS_VERROUS_POLICE
    WHERE DATE(dateHeureModification) < (curdate() - INTERVAL 14 DAY)
    LIMIT 1000;

It's a good idea to run the delete in limited-size batches anyway, so it doesn't create too many locks or add too much to the undo segment.
Just keep doing DELETE in a loop, deleting batches of 1000 rows at a time, and check rows-affected after each batch. Stop the loop when rows-affected reaches 0.
Another idea: I don't think you really need the DATE() function in your WHERE clause. So you might be able to do the DELETE like below, and it will be able to use an index. Besides, it should be faster to the query to check for any rows if you have an index on dateHeureModification.
DELETE
    FROM SYS_VERROUS_POLICE
    WHERE dateHeureModification < (curdate() - INTERVAL 14 DAY)
    LIMIT 1000;

A: I don't understand why do you complicate it :
delete
    from SYS_VERROUS_POLICE
    where date(dateHeureModification)
                           <(curdate() - interval 14 day);

A: @Jean Dous is the correct answer. But just to explain what is the problem in your query. You try to check a condition for the same table you are updating and is like creating a circular reference.
Instead you materialize the table as a subquery so you can use it.
delete
from SYS_VERROUS_POLICE
where idModificationPolice not in (
              select distinct T.idModificationPolice
              from (SELECT *
                    FROM SYS_VERROUS_POLICE) as T
              where date(T.dateHeureModification)
                    between curdate() and curdate() - interval 14 day
         );


text:
Q: events on the where ignore items that matches So i have this in my controller
@events = Event.where(id: popular.map(&:impressionable_id))

Basically at the moment it i have this in an each statement in my view. However, at the moment its showing up like this:
alex,
Sam,
Sam,
billy,
billy

What im wanting it to return like is this
alex,
sam,
billy

I've tried using .distinct and .unique on the end to no prevail
Any help?

A: @events = Event.where(id: popular.map(&:impressionable_id).uniq)


text:
Q: Python Date format conversion to UK I have a CSV file which has a date column with some dirty data i.e. dates stored in different formats (US and UK). I'd like to create another CSV file with the dates converted so they are consistently stored in the UK format enabling me to import correctly into my SQL database.
I'd like the dates to be converted to the following format:
'05-12-2017'
'07-11-2017'
'24-04-1999'
'28-01-1987'..
I tried the following code:
df = F.pd.read_csv('Book1.csv', parse_dates = [0], dayfirst = True)
df['Date'] = df['Date'].apply(F.pd.to_datetime, format = '%m/%d/%Y')
df['date_eu'] = df['Date'].dt.strftime('%m-%d-%Y')
df

, but it throws an error while trying to convert the US dates

ValueError: time data '20/01/2018' does not match format '%m/%d/%Y' (match)

Can someone please help?
Thanks

A: You could use a Try-Parse-Else-Approach:
from datetime import datetime

def normalizeDateString(ds):
    '''normalizes a date of format "d / d / dddd " to "dd/dd/dddd"'''
    sp = ds.replace(" ","").split("/")
    if len(sp[0])==1:
        sp[0]="0"+sp[0]
    if len(sp[1])==1:
        sp[1]="0"+sp[1]

    return sp[0]+"/"+sp[1]+"/"+sp[2]

def parseDT(dateString):
    ''' parses "dd/dd/yyyy" as US (month/day/year). Fallback: day/month/year on error'''
    try:
        repl =  normalizeDateString(dateString)
        return datetime.strptime(repl, "%m/%d/%Y").date()
    except:
        return datetime.strptime(repl, "%d/%m/%Y").date()

print(parseDT("14/12/2018"))
print(parseDT("2/5/2018")) # ok for US
print(parseDT("22/5/2018")) # not ok for US
print(parseDT("12/2/2018"))
print(parseDT("2/1/2018"))

Output:
2018-12-14
2018-02-05  # US ok
2018-05-22  # EN by except
2018-12-02
2018-02-01

HTH


text:
Q: Git database changes in schema.rb So there are 2 relevant branches. notifications and shipping_options.
I checked notifications out of master, then made 2 significant database changes:

*

*Created GeneralNotice model

*Modified existing Notice model, by adding a boolean dismissed
Then shipping_options was also checked out of master at the same state as notifications, and no database changes were made, only minor code changes.
I ran rake db:migrate the first time switching from notifications to shipping_options and the same vice versa.
At the moment, when I am in notifications, and run rails c I get the following:
2.0.0-p451 :001 > Notice
 => Notice(id: integer, title: string, description: text, created_at: datetime, updated_at: datetime, kind: string, general_notice_id: integer, shop_id: integer, dismissed: boolean)

2.0.0-p451 :002 > GeneralNotice
 => GeneralNotice(id: integer, title: string, description: text, created_at: datetime, updated_at: datetime)
2.0.0-p451 :003 >

*

*Notice has dismissed (as expected)

*GeneralNotice exists (as expected)

Then i switch to shipping_options and I hope you have been following because here comes the confusing part...
2.0.0-p451 :001 > Notice
 => Notice(id: integer, title: string, description: text, created_at: datetime, updated_at: datetime, kind: string, general_notice_id: integer, shop_id: integer, dismissed: boolean)

2.0.0-p451 :002 > GeneralNotice
NameError: uninitialized constant GeneralNotice
    from (irb):2
    from /Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
    from /Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
    from /Users/marcoprins/.rvm/gems/ruby-2.0.0-p451/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
2.0.0-p451 :003 >

*

*GeneralNotice doesn't exist, so apparently git is being very nice and helpful by changing the database according to my branch

*Notice still has a boolean dismissed ... Whaaaat???? Is git being nice or not?? HELP!!!!!!

A: *

*Since you've run the migration in the first branch (notifications), the column was added to the database table, hence it'll show if you inspect. inspect method works with the database table directly, reflecting the columns (attributes).

*GeneralNotice: if you check your database, it would contain the table (general_notices) but since the file general_notice.rb in which GeneralNotice is defined is not present in this branch, it throws uninitialized constant error.
Have a look at this and this for some ideas to put your db under version control.

A: Whenever you switch branch, and branches might contain set of different migrations it is wise to run rake db:reset which reloads database schema from schema.rb file.
In order to be sure your schema.rb is up-to-date in all branches it is good idea to run rake db:migrate:reset whenever you merge branches with new migrations. This rake task runs all your migrations from the very beginning and writes resulting database scheme to a file.


text:
Q: jQuery not working on Windows Server 2008, IIS 7 I am deploying an ASP.NET MVC to Windows Server 2008. I have installed ASP.NET MVC 1, but jQuery is not working on any of the pages. Anyone had this problem?

A: I suspect a problem with the path being used to load the scripts.  Is your web site at the root or in a subdirectory on the server?  See this question and see if the answers there don't help.
jQuery library location wants to be referenced differently on server


text:
Q: Startup oracle database 12c manually with SQL*Plus command not when OS loads I changed oracle instance to manually start from services.msc (service name is "OracleServiceORCL"), Because I want to start it up manually with SQL*Plus commands whenever I want, not with OS load.
Now I can't do that in SQL*Plus and I got this error:

ORA-12560: TNS:protocol adapter error

So I start it manually from services.msc and when database got ready I shut it down with SQL*Plus command. After that I realize that the service is still running, with very low consuming of resources.
I think this called "idle instance".
How can I automatically be in an idle instance state after I logged in to my Windows 8.1 to start oracle database whenever I want with SQL*Plus commands, not manually from services.msc?

A: You can configure this behaviour through the Administration Assistant, where you can choose to start (or not to start) the database instance with the Windows service.
Alternatively, you can do this with oradim, e.g:
oradim -edit -sid ORCL -startmode manual

The Windows service should be set to start automatically, and with the above setting, the database instance will not start with it.


text:
Q: Select Into error SELECT
xfqti_virtuemart_products_pt_pt.virtuemart_product_id,
xfqti_virtuemart_product_medias.virtuemart_media_id
INTO #tempTable
FROM xfqti_virtuemart_products_pt_pt

Gives syntax error, I'm about to pull my hair off

A: Insert Into and Selecthave these sintax
  Insert into your_Table (col1,col2)
  SELECT
  xfqti_virtuemart_products_pt_pt.virtuemart_product_id,
 xfqti_virtuemart_product_medias.virtuemart_media_id

  FROM xfqti_virtuemart_products_pt_pt

for create table
  Create  your_Table as
  SELECT
  xfqti_virtuemart_products_pt_pt.virtuemart_product_id,
 xfqti_virtuemart_product_medias.virtuemart_media_id

  FROM xfqti_virtuemart_products_pt_pt

A: Being Virtuemart, I'm guessing this is a MySQL database. If so, the correct syntax for creating a temp table is:
CREATE TEMPORARY TABLE IF NOT EXISTS tempTableName AS
(
   SELECT field1, field2
   FROM yourtable;
)

That being said, your SELECT statement has two fields from two different tables, but only one of those tables is mentioned in the FROM clause of your statement. They should really both be in there and JOINed. Something like:
CREATE TEMPORARY TABLE IF NOT EXISTS tempTableName AS
(
   SELECT
      t1.virtuemart_product_id,
      t2.virtuemart_media_id
   FROM
      xfqti_virtuemart_products_pt_pt as t1
      INNER JOIN xfqti_virtuemart_product_medias as t2 ON
          t1.product_id = t2.product_id
)

Or something.. I can't see your tables and it's been years since I used Virtuemart, so it's just a guess at the table relationship.


text:
Q: How can I use recursion to find increments of a number in python? I have the following code, but it just doesn't work when I run it. I would like it to return something like: [5,10,15,20] if the inputed value for n is 4. Any advice is very appreciated.
def MultipleRecursive(n):
    multiples=[]
    if n==0:
        multiples.append(n)
    else:
        Total=5*MultipleRecursive(n-1)
        multiples.append(Total)
    return multiples

A: A trivial version is:
def mr(n):
    if n == 0:
        return []
    return mr(n-1) + [5*n]

A: You can try this:
def rek(n):
    list = []
    if n == 0:
        return list
    else:
        list = rek(n-1)
        list.append(5*n)
        return list

print rek(4)
>>> [5, 10, 15, 20]


text:
Q: Use CSS custom properties at SCSS variables $color:        var(--primary-color, #333);

I tested this code by use SCSS web essential compiler and didn't work, but just wonder anyone else had used CSS custom properties in this way before or not. If I can do this, I don't have to change lots of code use this $color.


text:
Q: How do I merge text in visual studio 2010? To preface this I am an Emacs refugee on Visual Studio 2010's shores and am certain that I am working against the tool.  Please could someone point me in the right direction.  My problem is the MyProject.csproj file is kept under version control using TFS and my coworkers have made a number of changes that no longer get along with my version.  Not a problem, I can just merge the changes and make things right.  But I can't, or rather I don't know how to.  The compare tool in VS only taunts me, it won't let me pick and choose differences like I need to.
What I would love to do is just use Merge in Emacs, run through the file hitting L(eft), R(ight), B(oth) and be done with it in no time.  What I don't understand is why there are certain changes that are accepted by default, that I cannot alter.  I think that what it is doing is identifying changes that I made to the ancestor document and forcing those to be made while providing me the option of merging the changes from my coworkers.  My issue is that these things are contradictory and I would like to ignore my change to Line 12 while accepting the Repository's Line 42 but applying my Line 106.
But I cannot figure out how to tell it "no" to Line 12.
This has to be common, what does one do in VS to get this to work?
Thanks!

A: The standard diff tool that comes with Visual Studio ... blows.  Its not intuitive and doesn't work all that well.
But its very easy to integrate different diff tools.  I'm using this one:
http://visualstudiogallery.msdn.microsoft.com/en-us/dace3633-0b51-4629-85d4-c59cdce5bb3b?SRC=VSIDE
(no affiliation; its free so don't ding me for spam kthx).  Works pretty damn good.  You might find one out there better suited for your tastes, in which case you can integrate it into visual studio. (again, not associated with me!)

A: I advise you to use WinMerge to compare or merge files with VS
You can define as Will said.