text:
Q: Creating a CSV from date list output in Azure Databricks I am running the following script in Azure Databricks:
def daterange(date1, date2):
    for n in range(int ((date2 - date1).days)+1):
        yield date1 + timedelta(n)

start_dt = datetime.today() - timedelta(days=30)
end_dt = datetime.today() - timedelta(days=2)

for dt in daterange(start_dt, end_dt):
    df = print(dt.strftime("%Y-%m-%d"))
    display(df)

When I print or display the output I get a nice list of dates like this:
2021-04-19
2021-04-20
2021-04-21
2021-04-22
2021-04-23
2021-04-24
2021-04-25
2021-04-26
2021-04-27
2021-04-28
2021-04-29
2021-04-30
2021-05-01
2021-05-02

I need to use that list to create a CSV that I will subsequently load into Azure Storage. Any idea how I can create the CSV from the query in the Notebook?


text:
Q: Unexpected output in c I am new to c language. I just wanted to know why is my macro not working properly. It is giving me output as 13 where as my expected output is 24.?
#include<stdio.h>
#define mult(a,b) a*b
int main()
{
    int x=4,y=5;
    printf("%d",mult(x+2,y-1));
    return 0;
}

A: mult(x+2,y-1) expands to x +2 * y -1 that is equals to 4 + 2 * 5 -1 gives output: 13.
You might be expecting answer (4 + 2) * (5 -1) = 6 * 4 = 24. To make it expand like this you should write parenthesize macro as @H2Co3 also suggesting:
#define mult(a,b) ((a)*(b))

Read aslo: So, what's wrong with using macros? by Bjarne Stroustrup.

A: This is because C macros are simple textual substitutions, the macro writer must be sure to insert parentheses around every macro variable when it is substituted, and around the macro expansion itself, to prevent the resulting expansion from taking on new meanings.
If you observe your program: mult(a, b) is defined as a * b
mult(x + 2, y - 1) = x + 2 * y - 1 = 4 + 2 * 5 - 1 = 4 + 10 - 1 = 13

The Correct way would be:
mult(a, b) ((a) * (b))

A: Because it replaces the arguments literally:
mult(x+2,y-1) --> mult(4+2,5-1) --> 4 + 2*5 - 1 --> 13

Try changing the define to:
#define mult(a,b) (a)*(b)

In this case the result after pre-processing is this:
int main()
{
    int x=4,y=5;
    printf("%d",(x+2)*(y-1));
    return 0;
}

This will solve the problem but it's still not the best way to do it.
#define mult(a,b) ((a)*(b))

This version is considered as good practice because in other types of situation the first one would fail. See the bellow example:
#include<stdio.h>
#define add(a,b) (a)+(b)
int main()
{
    int x=4,y=5;
    printf("%d",add(x+2,y-1)*add(x+2,y-1));
    return 0;
}

In this case it would give an incorrect answer because it is translated by the pre-processor to the fallowing:
int main()
{
    int x=4,y=5;
    printf("%d",(x+2)+(y-1)*(x+2)+(y-1));
    return 0;
}

printing 34 instead of 100.

For the ((a)+(b)) version it would translate to:
int main()
{
    int x=4,y=5;
    printf("%d",((x+2)+(y-1))*((x+2)+(y-1)));
    return 0;
}

giving a correct answer.

A: Use parentheses in the macro definition
#include<stdio.h>
#define mult(a,b) ((a)*(b))
int main()
{
    int x=4,y=5;
    printf("%d",mult(x+2,y-1));
    return 0;
}

This is because different arithmetic operators have different precedence levels. Hence always use parentheses while defining the macro.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bulk update in Oracle gives error ORA-01779 I have a table which doesnot have any unique key column and I want to perform bulk update using self join.
Update
(
select t1.Col1 col1, t2.col1 col2
from table t1
inner join table t2 on <join condtn>
where <condtn>
)
Set col1 = col2

but as the table does not have unique key column, it gives error:

ORA-01779: cannot modify a column which maps to a non key-preserved
  table.

Is there any solution other than adding unique constraint :)

A: You should be able to refactor the query to do a correlated update
UPDATE table t1
   SET col1 = (SELECT col1
                 FROM table t2
                WHERE t1.<<some column>> = t2.<<some column>>)
 WHERE EXISTS( SELECT 1
                 FROM table t2
                WHERE t1.<<some column>> = t2.<<some column>>)


text:
Q: How to configure hangfire in asp.net core using structuremap targeting .net framework and resolve bi-directional dependency I've just been banging my head against the wall with this one not sure what's going on.
I've got an asp.net core web project targeting .NET 4.7.2 that I've been trying to configure hangfire.
public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("DocumentDbConnection");

            services.AddMvc(o =>
                {
                    o.Filters.Add(typeof(HttpGlobalExceptionFilter));

                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services
                .AddHangfire(x => x.UseSqlServerStorage(connectionString));

            // configure StructureMap Dependency Injection
            var container = new Container();
            container.Configure(config =>
            {
                config.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.AssembliesAndExecutablesFromApplicationBaseDirectory();
                    scan.WithDefaultConventions();
                    scan.AddAllTypesOf(typeof(IIntegrationEventHandler<>));
                });
// other configurations
                config.Populate(services);
            });

            // tried this too
//GlobalConfiguration.Configuration.UseStructureMapActivator(container);

            return container.GetInstance<IServiceProvider>();
        }

and my configure method:
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IContainer container)
        {
            //using Hangfire.StructureMap
GlobalConfiguration.Configuration.UseStructureMapActivator(container);

// exception is thrown on UsingHangfireServer()
            app
                .UseHangfireServer()
                .UseMvc();
        }

I keep getting an exception from StructureMap about a bi-directional dependency:
Bi-directional dependency relationship detected!
Check the StructureMap stacktrace below:
1.) Instance of Hangfire.Client.IBackgroundJobFactory ('Hangfire.Client.BackgroundJobFactory, Hangfire.Core, Version=1.7.0.0, Culture=neutral, PublicKeyToken=null')
2.) new BackgroundJobFactory(*Default of IJobFilterProvider*, *Default of IBackgroundJobFactory*)
3.) Hangfire.Client.BackgroundJobFactory ('Hangfire.Client.BackgroundJobFactory, Hangfire.Core, Version=1.7.0.0, Culture=neutral, PublicKeyToken=null')
4.) Instance of Hangfire.Client.IBackgroundJobFactory ('Hangfire.Client.BackgroundJobFactory, Hangfire.Core, Version=1.7.0.0, Culture=neutral, PublicKeyToken=null')
5.) Container.GetInstance(Hangfire.Client.IBackgroundJobFactory)
6.) Container.TryGetInstance(Hangfire.Client.IBackgroundJobFactory)

I've using packages Hangfire.AspNetCore, Hangfire.SqlServer, Hangfire.StructureMap, all v 1.7.0
I also tried just using the Hangfire package but am unable to configure it in my startup class because none of the extension methods were available.
Also note that this exact set up works just fine on a project targeting .net core.
Any advice would be greatly appreciated!

A: Turns out it was an issue with this line in the structuremap configuration:
scan.AssembliesAndExecutablesFromApplicationBaseDirectory();

I should have been using something like this instead:
scan.AssemblyContainingType<IThumbnailGenerator>(); // directing structuremap to scan the assembly containing this type

A: this problem is in 1.7+ hangfire version.
I downgraded the version to 1.6.27 and it solved


text:
Q: Set a delay in ajax call I am trying to add a small delay (2 sec) between the loader icon and the success with the data as html.
What I have tried to use is the setTimeout and put in a delay number. This is not working, so I was hoping you could show me what the correct way is.
My ajax code:
<script type="text/javascript">

$(function () {

    var delay = 2000;

    var res = {
        loader: $("<div />", { class: "loader" })
    };

    $('#search').on('click', function () {
        $.ajax({
            type: 'GET',
            url: "@Url.Action("Find", "Hotel")",
            datatype: "html",
            beforeSend: function () {
                $("#group-panel-ajax").append(res.loader);
                setTimeout(delay);
            },

            success: function (data) {
                $("#group-panel-ajax").find(res.loader).remove();
                $('#group-panel-ajax').html($(data).find("#group-panel-ajax"));
            }
        });
        return false;
    });
});

</script>

Right now it runs really fast. Hope someone can help.

A: here is something i found when i wanted to do the same :
function doStuff()
{
  //do some things
  setTimeout(continueExecution, 10000) //wait ten seconds before continuing
}

function continueExecution()
{
   //finish doing things after the pause
}

hope it will help ya

A: setTimeout should be used inside success function.

$(function() {
  var delay = 2000;
  var res = {
    loader: $("<div />", {
      class: "loader"
    })
  };
  $('#search').on('click', function() {
    $.ajax({
      type: 'GET',
      url: "@Url.Action("Find", "Hotel")",
      datatype: "html",
      beforeSend: function() {
        $("#group-panel-ajax").append(res.loader);
      },
      success: function(data) {
        setTimeout(function() {
          delaySuccess(data);
        }, delay);
      }
    });
    return false;
  });
});

function delaySuccess(data) {
  $("#group-panel-ajax").find(res.loader).remove();
  $('#group-panel-ajax').html($(data).find("#group-panel-ajax"));
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: Use setTimeout() like this:
<script type="text/javascript">

$(function () {

    var delay = 2000;

    var res = {
        loader: $("<div />", { class: "loader" })
    };

    $('#search').on('click', function () {
        $.ajax({
            type: 'GET',
            url: "@Url.Action("Find", "Hotel")",
            datatype: "html",
            beforeSend: function () {
                $("#group-panel-ajax").append(res.loader);

            },

            success: function (data) {
                setTimeout(function(){
                     $("#group-panel-ajax").find(res.loader).remove();
                     $('#group-panel-ajax').html($(data).find("#group-panel-ajax"));
                }, delay);

            }
        });
        return false;
    });
});

</script>


text:
Q: Spring JavaConfig for java.util.Properties field
Can you please tell me how to use Spring Javaconfig to directly load/autowire a properties file to a java.util.Properties field?
Thanks!
Later edit - still searching for the answer:
Is it possible to load with Spring JavaConfig a properties file directly into a java.util.Properties field?

A: declare a PropertiesFactoryBean.
@Bean
public PropertiesFactoryBean mailProperties() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("mail.properties"));
    return bean;
}

Legacy code had following config
<bean id="mailConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:mail.properties"/>
</bean>

Converting that to Java config is super easy as shown above.

A: It is an old subject but there are also a more basic solution.
@Configuration
public class MyConfig {
    @Bean
    public Properties myPropertyBean() {
        Properties properties = new Properties();
        properties.load(...);
        return properties;
    }
}

A: The XML base Way:
in spring config:
<util:properties id="myProperties" location="classpath:com/foo/my-production.properties"/>

in your class:
@Autowired
@Qualifier("myProperties")
private Properties myProperties;

JavaConfig Only
It looks like there is an annotation:
@PropertySource("classpath:com/foo/my-production.properties")

Annotating a class with this will load the properties from the file in to the Environment. You then have to autowire the Environment into the class to get the properties.
@Configuration
@PropertySource("classpath:com/foo/my-production.properties")
public class AppConfig {

@Autowired
private Environment env;

public void someMethod() {
    String prop = env.getProperty("my.prop.name");
    ...
}

I do not see a way to directly inject them into the Java.util.properties.  But you could create a class that uses this annotation that acts as a wrapper, and builds the properties that way.

A: There is also this approach for injecting properties directly using xml configurations. The context xml has this
<util:properties id="myProps" location="classpath:META-INF/spring/conf/myProps.properties"/>

and the java class just uses
@javax.annotation.Resource
private Properties myProps;

Voila!! it loads.
Spring uses the 'id' attribute in xml to bind to the name of variable in your code.

A: You can try this
@Configuration
public class PropertyConfig {

 @Bean("mailProperties")
 @ConfigurationProperties(prefix = "mail")
  public Properties getProperties() {
     return new Properties();
  }

}

Make sure to define properties in application.properties

A: application.yml:
root-something:
    my-properties:
        key1: val1
        key2: val2

Your type-safe pojo:
import java.util.Properties;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "root-something")
public class RootSomethingPojo {

    private Properties myProperties;

Your container configuration:
@Configuration
@EnableConfigurationProperties({ RootSomethingPojo .class })
public class MySpringConfiguration {

This will inject the key-value pairs directly into the myProperties field.


text:
Q: SpeechRecognizer throws ERROR_NO_MATCH on first listening when googlequicksearchbox is in background The behavior is very similar to what is described here, but only happens when the googlequicksearchbox is in the background. I'm with Google APP 5.2.33.19.arm.
I created the SpeechRecognizer by calling
SpeechRecognizer.createSpeechRecognizer(myContext, new ComponentName("com.google.android.googlequicksearchbox", "com.google.android.voicesearch.serviceapi.GoogleRecognitionService"))

I got the following error message in Android Studio Logcat
GoogleRecognitionServic﹕ #startListening [es-MX]
WebAppState﹕ WebApp unloaded
MediaFocusControl﹕ AudioFocus  requestAudioFocus() from android.media.AudioManager@b4542c6com.google.android.voicesearch.a.a$1@11f9f287 req=4flags=0x0
MediaFocusControl﹕ AudioFocus  abandonAudioFocus() from android.media.AudioManager@b4542c6com.google.android.voicesearch.a.a$1@11f9f287
Greco3EngineManager﹕ create_rm: m=ENDPOINTER_DICTATION,l=en-US
Greco3EngineManager﹕ Brought up new g3 instance :/system/usr/srec/en-US/endpointer_dictation.config for: en-USin: 1 ms
ErrorReporter﹕ reportError [type: 211, code: 458760]: es-MX
ErrorProcessor﹕ onFatalError, ignoring error from engine(1): com.google.android.apps.gsa.shared.speech.a.f: es-MX
ErrorReporter﹕ reportError [type: 211, code: 458756]: GsaErrorCode: 458756, engine: 1
ErrorProcessor﹕ onFatalError, ignoring error from engine(1): com.google.android.apps.gsa.shared.speech.a.d: GsaErrorCode: 458756, engine: 1
GoogleSpeechRecognition﹕ onError No match

Here is the entire messages from the speech recognizer. There is also an ERROR_CLIENT near finish. Another thing is there is no onRmsChanged call when this happens. Usually, there are tons of this call during a normal recognition request.
googleRecognizer﹕ onError No match
googleRecognizer﹕ onReadyForSpeech
googleRecognizer﹕ onBeginningOfSpeech
googleRecognizer﹕ onPartialResults
googleRecognizer﹕ onPartialResults
googleRecognizer﹕ onPartialResults
googleRecognizer﹕ onPartialResults
googleRecognizer﹕ onPartialResults
googleRecognizer﹕ onEndOfSpeech
googleRecognizer﹕ onError Client side error
googleRecognizer﹕ onResults

A: You need to first understand what the SpeechRecognizer does.
The SpeechRecognizer sends a "waking call" to your default speech to text application on your phone ( This can be seeing on Settings->Language and Input ). The default app wakes up, converts your speech to text and then sends it back to you onResults. In your specific case, you are explicitly calling 'google search'.
SpeechRecognizer.createSpeechRecognizer(..."com.google.android.googlequicksearchbox"...)

I would say that while 'googlequicksearchbox' is running in the background your recognizer fails to uses it (Since there can be only one instance of this action) .
Try calling a different speech to text app, and see what happens.


text:
Q: Grid Search Applicable for TFF and FL.? I'm currently researching with TFF and image classification (Federated Learning for Image Classification) emnist.
I'm looking at hyper parameters for the model learning rate and optimizer. Is grid search a good approach here ? . In a real world scenario would you simply sample clients/devices from the overall domain and if so if I was to do a grid search would I have to fix my client samples 1st. In which case does it make sense to do the grid search.
What would be a typical real world way of selecting parameters, ie is this more a heuristic approach. ?
Colin . . .

A: I think there is still a lot of open research in these areas for Federated Learning.
Page 6 of https://arxiv.org/abs/1912.04977 describes a cross-device and a cross-silo setting for federated learning.
In cross-device settings, the population is generally very large (hundreds of thousands or millions) and participants are generally only seen once during the entire training process. In this setting, https://arxiv.org/abs/2003.00295 demonstrates that hyper-parameters such as client learning rate play an outsized role in determining speed of model convergence and final model accuracy. To demonstrate that finding, we first performed a large coarse grid search to identify promising hyper-parameter space, and then ran finer grids in the promising regions. However this can be expensive depending on the compute resources available for simulation, the training process must be run to completion to understand these effects.
It might be possible to view federated learning as very large mini-batch SGD. In fact the FedSGD algorithm in https://arxiv.org/abs/1602.05629 is exactly this. In this regime, re-using theory from centralized model training may be fruitful.
Finally https://arxiv.org/abs/1902.01046 describes a system used at Google for federated learning, and does have a small discussion on hyper-parameter exploration.


text:
Q: Rails view phone number example I'm trying to have a user enter their phone number in my Rails 4 app.  I'd like it to work like many of the sites that have it like this:
1 turns into (1
(111 turns into (111)
(111)2 then turns into (111) 2
(111) 2223 then turns into (111) 222-3
The end result being something like this: (111) 222-3333
Does the only way to do this involve using javascript on every key press for the input box, checking how many integers have been entered and putting parentheses, a space, and the dash where necessary?
EDIT:
It'd probably have to handle extra cases like where a number is pasted in.

A: Answering your question - yes on every keypress - the most straightforward method.
Also you could make use of ready plugin like this http://digitalbush.com/projects/masked-input-plugin/ and yes pasting is also supported. Give it a try.


text:
Q: ROW_NUMBER and Grouping of data I have a data that looks like this:

What I want is to have a row number that is group by GroupCode,Group Description,SubGroup and subgroup class and I want to retain the ordering by account code that will look like this:

What's the proper way of seting a row number at the same time grouping them?

A: You're looking for the DENSE_RANK window function:
SELECT
    rn = DENSE_RANK() OVER(ORDER BY GroupCode, GroupDescription, SubgroupClass),
    *
FROM tbl
ORDER BY rn, AccountCode

A: You are looking for dense_rank():
select dense_rank() over (order by GroupCode, GroupDescription, SubGroup)
. . .

However, this doesn't guarantee the ordering by accountCode.  That will require more work.  First, determine the minimum account code for each grouping, then use dense_rank() on that:
select t.*, dense_rank() over (order by minac)
from (select t.*,
             min(accountCode) over (partition by GroupCode, GroupDescription, SubGroup) as minac
      from t
     ) t

A: I Guess you need this
;WITH cte
     AS (SELECT groupcode,
                groupdescription,
                subgroup,
                subgroupclass,
                Min(accountcode) AS accountcode
         FROM   your_table
         GROUP  BY groupcode,
                   groupdescription,
                   subgroup,
                   subgroupclass),
     ordr
     AS (SELECT Row_number()OVER(ORDER BY accountcode) AS RN,
                *
         FROM   cte)
SELECT C.rn,
       A.*
FROM   your_table A
       INNER JOIN cte C
               ON A.groupcode = C.groupcode
                  AND A.groupdescription = C.groupdescription
                  AND A.subgroup = C.subgroup
                  AND A.subgroupclass = C.subgroupclass


text:
Q: I am unable to sort data in ascending order using ORDER BY ASC The query I am running is
select accountid from general order by accountid ASC

The result I get is
accountid
------------
1
1001
1002
10021
10026
1006
1007

Why is it not ordering correctly?  It's a simple query and I am completely lost at how I can resolve this matter.

A: The column type must be a numeric (int, number, bigint, etc) type..
Looks like right now it is a VARCHAR type column... which is sorted like a dictionary...

A: If SolutionID is the VARCHAR Column and if it has some thing like Sol0, Sol1, Sol2, ....
then if you have to sort the column... use the below code
cast (substring(SolutionID,4,10) as integer) desc

A: Try this, it works:
select accountid from general order by convert(int, accountid) ASC


text:
Q: Creating a menu consisting of multi-level structure, how to perform this more officiently? witout hard-coding limits? I was asked to modify existing code to allow multi-level page structure. Each page can have one parent, and one page can have multiple children.
I will present following code. My question is is there a more efficient way of doing this? I am hard-coding the number of levels that are reachable.
Is there easier way to do  this automatically without hard coding? Recursion perhaps?
function createMenu($parents) {
    foreach ($parents as $parent) {
        $parentName = $this->getPagefromID($parent);
        $kids = $this->areThereKids($parent);

        if ($kids == "yes") {
            echo "
\n";
            $query = "SELECT * FROM pages";
            $result = mysql_query($query) or die('Query failed: ' . mysql_error());
            while ($row = mysql_fetch_assoc($result)) {
                $thisparent = $row['Parent'];
                $name = $row['Name'];
                $id2 = $row['ID'];
                if ($thisparent == $parent) {
                    echo "
" . $name . "
\n";
                    if($this->areThereKids($id2) == "yes") {
                        $children = $this->getMyKids($id2);
                        foreach($children as $kid) {
                            $info = $this->getPersonInformation($kid);
                            $kidid = $info[0]["ID"];
                            echo "
" . $info[0]['Name'] . "
\n";
                            // more sub
                            if($this->areThereKids($kidid) == "yes") {
                                $children1 = $this->getMyKids($kidid);
                                foreach($children1 as $kid1) {
                                    $info1 = $this->getPersonInformation($kid1);
                                    $kidid1 = $info1[0]['ID'];
                                    echo "
-" . $info1[0]['Name'] . "
\n";
                                    if($this->areThereKids($kidid1) == "yes") {
                                        $children2 = $this->getMyKids($kidid1);
                                        foreach($children2 as $kid2) {
                                            $info2 = $this->getPersonInformation($kid2);
                                            $kidid2 = $info2[0]['ID'];
                                            echo "
--" . $info2[0]['Name'] . "
\n";
                                            // No need for 6 levels.
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            echo "
\n";
        }
        echo "
\n";
    }
}

A: This would be more efficiently done with recursion.
Identify the steps of the code that are repeated and turn them into a subroutine. From your code, we have the following repeated unit:
(...)
    if($this->areThereKids($id2) == "yes") {
        $children = $this->getMyKids($id2);
        foreach($children as $kid) {
            $info = $this->getPersonInformation($kid);
            $kidid = $info[0]["ID"];
            echo "
" . $info[0]['Name'] . "
\n";
            // more sub
            if($this->areThereKids($kidid) == "yes") {
(...)

Turn that into a function (assuming you're working with an object):
function dealWithKids($par) {
    if ($this->areThereKids($par) == 'yes') {
        $children = $this->getMyKids($par);
        foreach ($children as $kid) {
            $info = $this->getPersonInformation($kid);
            $kidid = $info[0]["ID"];
            echo "
" . $info[0]['Name'] . "
\n";
            // instead of repeating the same steps again,
            // call the dealWithKids function here
            $this->dealWithKids($kidid);
        }
    }
}

...and then call that function instead of the repeated units of code:
        while ($row = mysql_fetch_assoc($result)) {
            $thisparent = $row['Parent'];
            $name = $row['Name'];
            $id2 = $row['ID'];
            if ($thisparent == $parent) {
                echo "
" . $name . "
\n";
            //  instead of this:
            //  if($this->areThereKids($id2) == "yes") {
            //  do this:
                $this->dealWithKids($parent);
            }
         }


text:
Q: populate google chart datatable with arrayToDataTable in django template I have a list of tuples passed to the template.
I want to populate a datatable with it.
Here is the code.
Does anyone know what is wrong with it? Currently nothing shows on the webpage.
Thank you.
    var dt=new google.visualization.arrayToDataTable([
    ['Name','LastGPA','CurGPA','IntervalA','IntervalB','Major'],
    {% for d in data %}
    [{{d.0}},{{d.1}},{{d.2}},{{d.3}},{{d.4}},{{d.5}}]
    {% if not forloop.last %},{% endif %}
    {% endfor %}
    ]);
    summary_table.draw(dt);

A: Here's a helper module for using the Visualization API with Django queries.  You might find it easier to work with passing JSON, rather than building it in the template.


text:
Q: Set errors from code to xaml after calling a post method I'm using ValidationRules in my xaml forms like this
      <TextBox Name="email">
            <TextBox.Text>
                  <Binding Path="email" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                              <local:NotEmptyString  ValidationStep="RawProposedValue" />
                        </Binding.ValidationRules>
                  </Binding>
            </TextBox.Text>
      </TextBox>

In code, before my transaction begins i check for errors like this
email.GetBindingExpression(TextBox.TextProperty).UpdateSource();

if (Validation.GetHasError(item))
      return false;

I have classes that inherit ValidationRule for every validation i need, and this works fine.
But now, i need to call a post method and that method returns me an JSON error when the email already exists, I want to show that error as a validation error. is there a way to set the error to the TextBox?

A: If you want to stick to this quite unflexible binding validation, then the simplest solution would be to use Binding.ValidatesOnException:
<TextBox Name="email">
  <TextBox.Text>
    <Binding Path="email"
             UpdateSourceTrigger="PropertyChanged"
             ValidatesOnException="True">
      <Binding.ValidationRules>
        <local:NotEmptyString  ValidationStep="RawProposedValue" />
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
</TextBox>

Then validate your JSON response:
class ViewModel
{
  public string Email { get; set; }

  private ValidateJsonResponse(Json jsonObject)
  {
    if (!JsonIsValid(jsonObject))
    {
      throw new ArgumentException("Email already exists.");
    }
  }
}

But since exceptions can have some impact on the performance, you generally should avoid them. You can argue, if failed input validation is a good reason to throw an exception. I doubt it is.
Alternatively implement a second ValidationRule and trigger the binding to execute it. You must find a way to access the JSON response to check whether it is valid or not. Since the ValidationRule is instantiated in the XAML and can't have a DependencyProperty to allow binding, this could be slightly complicated. That's why binding validation is not very flexible. The ValidationRule instance of the binding is quite isolated from the rest of the code e.g., the view model.
The recommended pattern is to have your view model implement he INotifyDataErrorInfo interface. See this post for an example or links regarding the implementation: How to add validation to view model properties or how to implement INotifyDataErrorInfo


text:
Q: How to prevent polluting a rails object when using form_for and .new? I have a model:
class Activity < ActiveRecord::Base
    has_many   :activity_states
end

I want to render options for new activity states and render existing activity states.  However when I use this form_for:
<%= form_for activity.activity_states.new, :remote => true do |f| %>
    <%= f.hidden_field :state_type, :value => activity_state_type %>
    <%= f.hidden_field :activity_id %>
    <%= f.submit submit_label, :disable_with => 'sending...' %>
<% end %>

for creating new temporary activity_state models to use as the basis for new activity_states it pollutes the activity object with nil activity states so instead of Activity having the activity states:
[#<ActivityState id: 7353, activity_id: 2033, state_type: 0, created_at: "2012-05-31 11:06:50">,
#<ActivityState id: 7354, activity_id: 2033, state_type: 1, created_at: "2012-05-31 11:06:53">,
#<ActivityState id: 7355, activity_id: 2033, state_type: 2, created_at: "2012-05-31 11:06:59">]

It also has several these nil activity_state objects appended mid render because of the .new:
#<ActivityState id: nil, activity_id: 2033, state_type: nil, created_at: nil>

resulting in:
[#<ActivityState id: 7353, activity_id: 2033, state_type: 0, created_at: "2012-05-31 11:06:50">,
#<ActivityState id: 7354, activity_id: 2033, state_type: 1, created_at: "2012-05-31 11:06:53">,
#<ActivityState id: 7355, activity_id: 2033, state_type: 2, created_at: "2012-05-31 11:06:59">,
#<ActivityState id: nil, activity_id: 2033, state_type: nil, created_at: nil>,
#<ActivityState id: nil, activity_id: 2033, state_type: nil, created_at: nil>]

Which then messes things up when I loop over the activity_states for the activity and render them.  I tried a hacky way of getting around this using: <% activity.activity_states.pop %> after each form_for but this doesn't work when in production on Heroku as it complains about trying to modify a frozen array.
Any ideas on the "right" way of doing this please?  I know I'm failing to understand something pretty fundamental here and also know I've opened up a hole by inserting a hidden field for the id field (which can then be manipulated by malicious users).

A: I have one solution so far, in the show method of the activity controller, include:
@new_activity_state = @activity.activity_states.new
@activity.activity_states.pop

and in the view partial (which I pass @activity as the local variable activity):
<% new_activity_state = @new_activity_state || activity.activity_states.new %>
<%= form_for new_activity_state, :remote => true do |f| %>
    <%= f.hidden_field :state_type, :value => activity_state_type %>
    <%= f.hidden_field :activity_id %>
    <%= f.submit submit_label, :disable_with => 'sending...' %>
<% end %>

Heroku's production environment doesn't object to the .pop now which is great :D  But is there a better way?


text:
Q: Reading csv from the second line and creating output I want from a csv archive to read only one column. The problem is that I want to read this column from the second line and by using these commands:
[d1,tex]= xlsread(filename1);
name=tex(:,4)

it's reading from the first line.
Also, I would like to create a matrix that will inclue two columns that have come from commants (equations etc) in my Matlab code.

A: xlsread is deprecated by MathWorks. Try using readtable in the future.
To your original question, I'm assuming that you want to read everything in the 4th column from the second row onward. If so, your second line is incorrect:
name = tex(2:end,4)

Without further example code, I can't answer the rest of your question. Add some details and I'll see what I can do.


text:
Q: AWS API creation delay? I'm currently using aws-amplify for react native. I'm using the API command to do HTTP requests and I was able to call a GET method API that I created few months ago. The thing is when I call a function that's freshly made, it keeps telling me that the "Api 'API name' doesn't exist". I tried to see if there was any typo, but nothing. I also created a GET method API with the exact same code as the one that was working but same result (api doesn't exist). Has anyone also run into this issue?

A: Can you post your sample code including the object you're passing to Amplify.configure(object) and also the GET call which includes the name (API.get(name, path, options)()? You'll need to ensure that the name is in the endpoints[] array of your configuration object per the documentation and that this matches the name passed in your method call. For more information see this page: https://github.com/aws/aws-amplify/blob/master/media/api_guide.md


text:
Q: R Subset area NetCDF I'm having trouble trying to read a plus 2Gb NetCDF file from links in R
If I try to read the whole file R returns me a message that I don't have enough memory,
'Error: cannot allocate vector of size 31.3 Gb'

as it was reported by the post link
Following the this post advice, I decided to read only the part of the file based on the geographic coordinates of the a given area. Here is my code:
#load any packages

library(ncdf4)

set path and filename
ncpath <- "C:\Users\Me\Documents\Science\GIS\Global Land Cover\"

ncname <- "C3S-LC-L4-LCCS-Map-300m-P1Y-2018-v2.1.1"

ncfname <- paste(ncpath, ncname, ".nc", sep="")

dname <-"lccs_class"

open a netCDF file
ncin <- nc_open(ncfname)

print(ncin)

get longitude and latitude
lon <- ncvar_get(ncin,"lon")

nlon <- dim(lon)

head(lon)

lat <- ncvar_get(ncin,"lat")

nlat <- dim(lat) head(lat)

print(c(nlon,nlat))

#' create a bounding box to work with a subset
LonIdx <- c(841, 842, 844,845,846,847,848)

LatIdx <- c(93,94,95,96)

However, when I try to execute the code for the Subset:
Susbset <- ncvar_get(ncin, dname,
                start = c(LatIdx[1], LonIdx[1]),
                count = c(length(LatIdx),length(LonIdx)))

I get the error:
> Error in ncvar_get_inner(ncid2use, varid2use, nc$var[[li]]$missval,
> addOffset, : Error: variable has 3 dims, but start has 2 entries. They
> must match!

Can anyone help me? Much appreciated.

A: It seems like there is still a third dimension to specify before you can procceed.
Let's suppose it is a time variable:
start = c(LatIdx[1], LonIdx[1], DesiredTimeIdx),
count = c(length(LatIdx),length(LonIdx), 1))

This should read all lats an all lons in that specific time.


text:
Q: Can I make an "if" statement in jQuery to check for a class from one set AND a class from another? I'm trying to create an "if" statement in jQuery to check if an element has one (or more) of a list of classes AND one (or more) of another list of classes. I don't seem to be having success. My code I've created so far is:
if ( $("#jacket_text").is(".color-white,.color-black,.color-silver")
&& $("#jacket_text").is(".font-block,.font-script,.font-space") ) {

}
else {
}

Is there something I can do to make this work?
Any help greatly appreciated! Thanks!
**** EDIT ****
Here is a jsFiddle of more code that I am using: https://jsfiddle.net/4wajbutx/
I'm sorry if it's a bit complex, I wanted to include as much as possible to make sure any of my errors could be noticed, if there were any causing problems.
The point of my code here is that certain colors (such as white & black) should NOT be available when someone clicks the "neon" font option. I managed to handle that - it would deselect those colors and select "blue" when they clicked "neon." The problem is that if they have already selected "neon" and, say, the color "pink," if they click "neon" again (accidentally perhaps) then it changes their color selection to "blue." But this should ONLY happen if they have a different font option selected AND an invalid color option selected.
Wow I hope that makes sense to someone.

A: Your code is fine - it works as intended. You have a little example below how it works. This thread should help you as well: JQuery .hasClass for multiple values in an if statement

$(document).ready(function() {
  if ($("#a").is(".one,.two,.three") && $("#a").is(".small-font,.triangle")) {
    $('#a').addClass('selected');
  }

   if ($("#b").is(".five,.six") && $("#b").is(".square")) {
    $('#b').addClass('selected');
  }

   if ($("#c").is(".nine,.ten") && $("#c").is(".i-dont-know-that-class-name")) {
    $('#c').addClass('selected');
  }
});
div{
  display:inline-block;
  width:100px;
  height:100px;
  margin-right:5px;
  opacity:0.1;
  color:#fff;
  text-align:center;
  line-height:100px;
  font-family:sans-serif;
  text-transform:uppercase;
  border:3px dotted transparent;
}
#a{background-color:orange;}
#b{background-color:green;}
#c{background-color:blue;}

.selected{
  opacity:1 !important;
  border-color:red !important;
}

Triangle

Square

Circle

A: Time to flee the country, I found my stupid mistake.
I was removing the very classes that my "if" statement was looking for BEFORE the "if" statement occurred, so of course it couldn't find them and it didn't work.
I now put that line after the "if" statement, and it works as expected.
Thanks guys, hope I didn't waste too much of anyone's time!


text:
Q: Tips4All Stack Overflow ripoff?
Possible Duplicate:
Report sites that use SE content without following attribution rules here

I don't know if this site is somehow associated with Stack Overflow, but I found it today Googling some things and many  if not all of its answers and questions are taken from Stack Overflow: http://tips4all.net/.

A: There are a few other meta questions about sites that scrape SO / SE content.
Valued Associate Abby keeps an eye on that and contacts the sites to get them to comply with our attribution requirements . Thanks for the heads up; we'll add it to our list and look into it. Please continue to report any other scrapers you find that are not properly attributing content to SO.


text:
Q: Can't close activity finish(); does not work when pressing the back button a seccond time, only Visible and Invisible functioning currently in press button once
 @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK){
        final ImageView im = (ImageView)findViewById(R.id.imageView);
        final ScrollView scrol = (ScrollView)findViewById(R.id.scrollView);
        final LinearLayout layOut = (LinearLayout)findViewById(R.id.layout);
        final TextView text = (TextView)findViewById(R.id.textView);
        final VideoView videoview = (VideoView) findViewById(R.id.video_View);
        videoview.setVisibility(View.INVISIBLE);
        im.setVisibility(View.VISIBLE);
        scrol.setVisibility(View.VISIBLE);
        layOut.setVisibility(View.VISIBLE);
        text.setVisibility(View.VISIBLE);
        return false;
    } else {
        finish();
    }
    return super.onKeyDown(keyCode,event);

}

A: Can't build apk
@Override
public void onBackPressed(){
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == android.view.KeyEvent.KEYCODE_BACK){
            final ImageView im = (ImageView)findViewById(R.id.imageView);
            final ScrollView scrol = (ScrollView)findViewById(R.id.scrollView);
            final LinearLayout layOut = (LinearLayout)findViewById(R.id.layout);
            final TextView text = (TextView)findViewById(R.id.textView);
            final VideoView videoview = (VideoView) findViewById(R.id.video_View);
            videoview.setVisibility(View.INVISIBLE);
            im.setVisibility(View.VISIBLE);
            scrol.setVisibility(View.VISIBLE);
            layOut.setVisibility(View.VISIBLE);
            text.setVisibility(View.VISIBLE);
            return false;
        } else {
            finish();
        }
        return super.onKeyDown(keyCode, event);

    }
}


text:
Q: Why is a multivariable function satisfying the following conditions exact? I read this section in the book "Mathematics Methods for Physics and Engineering"

Determining whether a differential containing many variable $x_1,x_2,...,x_n$
exact is a simple extension of the above. A differential containing many variables can be written in general as
$$df=\Sigma^n_{i=1}g_i(x_1,x_2,...,x_n)dx_i$$
and the function will be exact if
$\frac{\partial g_i}{\partial x_j}=\frac{\partial g_j}{\partial x_i}$ for all pairs of i and n.

I can understand the situation when there are only two variables in the function, but when there are many variables, I am a bit confused about why this condition is already necessary  to prove that the function is exact, instead of requiring all partial derivatives of the function to be equal.

A: *

*By definition, an exact differential one form
$$
\omega=\sum^n_{i=1}g_i(x_1,x_2,...,x_n)\,dx_i
$$
arises from a function, aka $0$-form, $f$ by exterior differentiation $\omega=df\,.$

*Saying that the differential $\omega$ is exact amounts to showing that the function $f$ exists. Writing the differential from the beginning as $df$ is therefore confusing.

*The reason for this confusion is imho that the authors Riley, Hobson & Bence are trying to avoid the language of differential forms and mention the above result without proof or reference.

*By the Poincare lemma it is enough to show that $\omega$ is closed which means that
$d\omega=0\,.$

*By the exterior differential calculus rules,
\begin{eqnarray}
d\omega&=\sum^n_{i,j=1} \partial_j g_i(x_1,x_2,...,x_n)\,dx_j\wedge dx_i
\end{eqnarray}
which is zero because $\partial_j g_i$ is symmetric in $i,j$ and $dx_j\wedge dx_i$ is antisymmetric.

*In order that the Poincare lemma is applicable we need to assume that the domain of the $g_i$ functions is simply connected.

*Examples of inexact differentials arise in Thermodynamics: change in heat $Q$ and change in work $W$ and are usually denoted by
$\delta Q$ and $\delta W$ following Carl Gottfried Neumann. The first law of thermodynamics is then
$$
dU=\delta Q-\delta W
$$
where $U$ is the internal energy and has an exact differential.

A: The author shouldn't write $df$ there. Suppose $\Omega \subset \mathbb{R}^n$ is an open set. A one form is an object of the form
$$\omega = \sum_{i = 1}^{n}g_i(x)\,dx_i,$$
where each $g_i \in C^{\infty}(\Omega, \mathbb{R})$. The one-form $\omega$ is said to be exact if there exists a smooth function $f \in C^{\infty}(\Omega, \mathbb{R})$ such that
$$df := \sum_{i = 1}^{n}\frac{\partial f}{\partial x_i}dx_i = \omega.$$
The above equation is equivalent to
$$g_i = \frac{\partial f}{\partial x_i} \text{ for } i = 1, \dots, n.$$
Now if $\omega$ is exact, meaning that the above holds, then
$$\frac{\partial g_i}{\partial x_j} = \frac{\partial^2 f}{\partial x_i \partial x_j} = \frac{\partial^2 f}{\partial x_j \partial x_i} = \frac{\partial g_j}{\partial x_i}.$$
So exactness implies $\frac{\partial g_i}{\partial x_j} = \frac{\partial g_j}{\partial x_i}$ for $i, j \in \{1, \dots, n\}$. However, the converse is not true in general. It is true when $\Omega$ is simply connected though, which means roughly that any smooth closed curve in $\Omega$ is smoothly homotopic to a point through a family of closed curves.


text:
Q: How to deal with modifying large pandas dataframes I have a largish pandas dataframe (1.5gig .csv on disk).  I can load it into memory and query it.  I want to create a new column that is combined value of two other columns, and I tried this:
def combined(row):
    row['combined'] = row['col1'].join(str(row['col2']))
return row

df = df.apply(combined, axis=1)

This results in my python process being killed, presumably because of memory issues.
A more iterative solution to the problem seems to be:
df['combined'] = ''
col_pos = list(df.columns).index('combined')
crs_pos = list(df.columns).index('col1')
sub_pos = list(df.columns).index('col2')

for row_pos in range(0, len(df) - 1):
    df.iloc[row_pos, col_pos] = df.iloc[row_pos, sub_pos].join(str(df.iloc[row_pos, crs_pos]))

This of course seems very unpandas.  And is very slow.
Ideally I would like something like apply_chunk() which is the same as apply but only works on a piece of the dataframe.  I thought dask might be an option for this, but dask dataframes seemed to have other issues when I used them.  This has to be a common problem though, is there a design pattern I should be using for adding columns to large pandas dataframes?

A: I would try using list comprehension + itertools:
df = pd.DataFrame({
    'a': ['ab'] * 200,
    'b': ['ffff'] * 200
})

import itertools

[a.join(b) for (a, b) in itertools.izip(df.a, df.b)]

It might be "unpandas", but pandas doesn't seem to have a .str method that helps you here, and it isn't "unpythonic".
To create another column, just use:
df['c'] = [a.join(b) for (a, b) in itertools.izip(df.a, df.b)]

Incidentally, you can also get your chunking using:
[a.join(b) for (a, b) in itertools.izip(df.a[10: 20], df.b[10: 20])]

If you'd like to play with parallelization. I would first try the above version, as list comprehension and itertools are often surprisingly fast, and parallelization would require an overhead that would need to be outweighed.

A: One nice way to create a new column in pandas or dask.dataframe  is with the .assign method.
In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'x': [1, 2, 3, 4], 'y': ['a', 'b', 'a', 'b']})

In [3]: df
Out[3]:
   x  y
0  1  a
1  2  b
2  3  a
3  4  b

In [4]: df.assign(z=df.x * df.y)
Out[4]:
   x  y     z
0  1  a     a
1  2  b    bb
2  3  a   aaa
3  4  b  bbbb

However, if your operation is highly custom (as it appears to be) and if Python iterators are fast enough (as they seem to be) then you might just want to stick with that.  Anytime you find yourself using apply or iloc in a loop it's likely that Pandas is operating much slower than is optimal.


text:
Q: Sorting an array in which each item is a comma separated list of values in vb.net I have an array of values as given below
arr(0) = "US,20,10,true"
arr(1) = "Ind,22,8,true"
arr(2) = "UK,40,6,true"
arr(3) = "Chi,30,22,true"
arr(4) = "Jpn,50,18,true"
arr(5) = "Isr,18,15,true"

What I wanted to achieve now is to sort this array in the ascending order of 3rd value in each element(that is , Sort the entire array based on the values 10,8,6,22,18 and 15). After sorting I should get the array as given below
arr(0) ="UK,40,6,true"
arr(1) ="Ind,22,8,true"
arr(2) ="US,20,10,true"
arr(3) ="Isr,18,15,true"
arr(4) ="Jpn,50,18,true"
arr(5) ="Chi,30,22,true"

can anyone provide me the code please?
Thanks,
kdr

A: Input:
Dim arr(5) As String
arr(0) = "US,20,10,true"
arr(1) = "Ind,22,8,true"
arr(2) = "UK,40,6,true"
arr(3) = "Chi,30,22,true"
arr(4) = "Jpn,50,18,true"
arr(5) = "Isr,18,15,true"

arr = arr.Cast(Of String).Select(Function(a) a.Split(","c)).
                          Select(Function(a) New With {Key .State = a(0),
                                                           Key .No1 = a(1),
                                                           Key .No2 = a(2),
                                                           Key .Bool = a(3)}).
                          OrderBy(Function(o) CInt(o.No2)).
                          Select(Function(s) String.Concat(s.State, ",", s.No1, ",", s.No2, ",", s.Bool)).ToArray()

For Each item In arr
   Console.WriteLine(item)
Next

Output:
UK,40,6,true
Ind,22,8,true
US,20,10,true
Isr,18,15,true
Jpn,50,18,true
Chi,30,22,true

*

*Split input array elements by comma => split(0,0) = "US", split(0, 1) = "20", ... split(1,0) = "Ind",split(1,1) = "22", ....

*Create IEnumerable of anonymous type for each element of split

*Convert to integer and order by anonymous type .No2 (=3rd value in array)

*Transfer ordered IEnumerable of anonymous type back to array

A: Why you dont use a DataTable?
Dim Table1 As New DataTable

' Create four typed columns in the DataTable.
Table1.Columns.Add("Country", GetType(String))
Table1.Columns.Add("Num1", GetType(Integer))
Table1.Columns.Add("Num2", GetType(Integer))
Table1.Columns.Add("Bol", GetType(Boolean))

' Add some rows in the DataTable.
Table1.Rows.Add("IT", "123", "456", True)
Table1.Rows.Add("DE", "456", "789", False)


text:
Q: Whats the difference between spring-framework-bom and platform-bom? Ive been experimenting with Spring BOM and note there are two build managers - spring-framework-bom and platform-bom
<dependencyManagement>
    <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-framework-bom</artifactId>
                <version>${spring.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>

Or
<dependencyManagement>
     <dependencies>
        <dependency>
            <groupId>io.spring.platform</groupId>
            <artifactId>platform-bom</artifactId>
            <version>1.1.2.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Whats the difference? Or has spring-framework-bom been superceded? Personally I prefer the spring-framework-bom approach as i can control the spring version?

A: I had a hunt around on this question last week, and as M Deinum has stated the difference is that spring-framework-bom is just for the framework. I then raised an issue that how can i control the spring version if using platform-bom.
The answer is to check the spring boot dependencies project for spring version -
https://github.com/spring-projects/spring-boot/blob/master/spring-boot-dependencies/pom.xml
A summary of versions are -
Spring Platform BOM Version Spring Version
1.1.2.RELEASE               4.2.0.RC1
1.1.0.RELEASE               4.1.3.RELEASE
1.0.0.RELEASE               4.0.5.RELEASE
Reference -
https://glenware.wordpress.com/2015/06/05/spring-bom-bill-of-materials/


text:
Q: Docker: how to log out from all remote registries? I thought the docker logout command would log me out from the remote private docker registry I had just logged in but it doesn't.
Before trying to logout:
$ cat ~/.docker/config.json

{
    "auths": {
            "rg.nl-ams.scw.cloud": {
                    "auth": "da2kleGhoPNjVj...pLri69="
...

After the command
$ docker logout

$ cat ~/.docker/config.json

{
    "auths": {
            "rg.nl-ams.scw.cloud": {
                    "auth": "da2kleGhoPNjVj...pLri69="
...

This is problematic because when I then launch run commands, docker tries to pull an image from this remote registry but I don't want that to happen. I don't want docker to be aware of this registry anymore. What should I do?
I see now that docker logout by default logs you out from some "default server" that is apparently "https://index.docker.io/v1/". How do I logout from all servers? Do I really have to write a script for this?
I don't want to rely on a particular server name, I just want to make sure the docker client is not logged in anywhere so that I can run tests in a clean and repeatable way.

A: Use this and specify remote private registry
docker logout URL
for example docker logout localhost:8080 (to log out of a registry on your local host)


text:
Q: Ionic 3 Firebase Angular localstorage I am creating an app. The app show the percentage of clicks of all users . but there is problem coming when i click on question its shows the percentage on next question can any one can help. I want to show the percentage on the question user click. Can any one help need to submit the project .
newp.ts
import { Component, ViewChild, OnInit } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ActionSheetController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';
import { AngularFireDatabase } from 'angularfire2/database';
import { HttpClient } from '@angular/common/http';
import * as firebase from 'firebase';
import { LocalStorage } from '@ngx-pwa/local-storage';

@IonicPage()
@Component({
  selector: 'page-newp',
  templateUrl: 'newp.html',
})
export class NewpPage implements OnInit {

  @ViewChild('slides') slides: any;

  hasAnswered: boolean = false;
  score: number = 0;
  stateimage: any;
  slideOptions: any;
  cli: any;
  showclicks: boolean;
  hideMe: any;
  clickvalue1: number;
  clickvalue2: number;
  clickPercentage1: number;
  clickPercentage2: number;
  current_wouldclicks: number;
  current_ratherclicks: number;
  wouldclicks: number = 0;
  ratherclicks: number = 0;
  question_str: any;
  item_key: any;
  firebase_flag: boolean;
  // questions: Observable<any>;
  questions: any[];
  wouldquestion: any;
  ratherquestion: any;

  constructor(public navCtrl: NavController, private localStorage: LocalStorage,
    private alertCtrl: AlertController, public navParams: NavParams, public actionSheetCtrl: ActionSheetController, public afd: AngularFireDatabase, public http: HttpClient) {

    this.clickvalue1 = 0;
    this.clickvalue2 = 0;
    this.clickPercentage1 = 0;
    this.clickPercentage2 = 0;
    this.ratherclicks = 0;
    this.wouldclicks = 0;
    // this.questions = this.afd.list('Questions').valueChanges();       // <=====  Question is coming from there .
    this.cli = "";
    this.showclicks = false;
  }
  ionViewDidLoad() {
    console.log('ionViewDidLoad NewpPage');
  }

  ngOnInit() {
    this.afd.list('Questions').valueChanges()
      .subscribe(
        (qs: any[]) => {
          this.questions = [];
          console.log(qs);
          this.localStorage.getItem<any>('QUESTION')
            .subscribe(
              qsRead => {
                console.log(qsRead);
                if (qsRead) {
                  let index = qs.findIndex(x => x.rather === qsRead);
                  if (qs.length > index + 1) {
                    this.questions = qs.slice(index + 1);
                    console.log(this.questions);
                  }
                } else {
                  this.questions = qs;
                }

              });
        });

  }

  nextSlide() {
    this.showclicks = false;
    this.slides.lockSwipes(false);
    this.slides.slideNext();
    this.slides.lockSwipes(true);
  }

  presentPrompt() {
    let alert = this.alertCtrl.create({
      title: 'Add Your Question',
      inputs: [
        {
          name: 'would',
          placeholder: 'Would You ',
        },
        {
          name: 'rather',
          placeholder: 'Rather'
        }
      ],
      buttons: [
        {
          text: 'Add',
          role: 'add',
          handler: data => {
            this.wouldquestion = data.would;
            this.ratherquestion = data.rather;
            this.afd.list("Questions/").push({
              would: this.wouldquestion,
              rather: this.ratherquestion,
              ratherclick: this.ratherclicks,
              wouldclick: this.wouldclicks
            });
          }
        },
      ]
    });
    alert.present();
  }

  show(quest, index, type, typeText) {
    console.log(quest, index, type, typeText);
    this.localStorage.setItem('QUESTION', quest.rather)
      .subscribe(
        (result) => {
          if (result) {
            this.showclicks = true;
            this.clickedButton(type, typeText);
            setTimeout(() => {
              this.showclicks = false;
            }, 1000);
          }

        });
  }

  clickedButton(index, paramString) {
    this.question_str = paramString

    firebase.database().ref('Questions/').on('value', data => {
      data.forEach(item => {
        if (item.val().would == this.question_str) {
          this.item_key = item.key;
          this.firebase_flag = true;
          this.wouldclicks = item.val().wouldclick;
          this.ratherclicks = item.val().ratherclick;
          this.wouldclicks++;
        }
        else if (item.val().rather == this.question_str) {
          this.item_key = item.key;
          this.firebase_flag = false;
          this.wouldclicks = item.val().wouldclick;
          this.ratherclicks = item.val().ratherclick;
          this.ratherclicks++;
        }
      });
    });

    if (this.firebase_flag == true) {
      firebase.database().ref('Questions/' + this.item_key).child("wouldclick").set(this.wouldclicks);

    }
    else {
      firebase.database().ref('Questions/' + this.item_key).child("ratherclick").set(this.ratherclicks);
    }

    switch (index) {
      case 1:
        this.clickPercentage1 = Math.round(this.wouldclicks / (this.wouldclicks + this.ratherclicks) * 100);
        this.clickPercentage2 = Math.round(this.ratherclicks / (this.wouldclicks + this.ratherclicks) * 100);
        break;
      case 2:
        this.clickPercentage1 = Math.round(this.wouldclicks / (this.wouldclicks + this.ratherclicks) * 100);
        this.clickPercentage2 = Math.round(this.ratherclicks / (this.wouldclicks + this.ratherclicks) * 100);
        break;
    }
  }

}

newp.html
[![<ion-header color="grey">

  <ion-navbar color="grey" center>
    <ion-title>Would You Rather ?</ion-title>
    <ion-buttons class="bttn" right><button right class="bttn" (click)="presentPrompt()">
        <ion-icon color="light" name="md-more"></ion-icon>
      </button></ion-buttons>
  </ion-navbar>

</ion-header>

<ion-content class="background">

  <ion-slides #slides>
    <ion-slide *ngFor="let question of questions; let i = index;">

{{ clickPercentage1 }}%

{{question.would}}

OR

{{ clickPercentage2 }}%

{{question.rather}}

    </ion-slide>
  </ion-slides>
</ion-content>][1]][1]


text:
Q: Word for 'without being aware of doing'
He looked at the disaster in his office and, without being aware of it, patted the pocket where he kept his cigars.
He looked at the disaster in his office and [adverb] patted the pocket where he kept his cigars.

I'm looking for an adverb meaning "without being aware of doing" that would fit in the above sentence and make the two sentences mean the same thing both literal meaning-wise and connotation-wise.
More specifically, if the word has the correct meaning and connotations, then it should also do the same for the following sentences.

She glanced at the children playing in the park and, without being aware of it, drew a smile.
She glanced at the children playing in the park and [adverb] drew a smile.

Some possible choices I found so far but aren't quite satisfied with are:

*

*Unconsciously (not quite satisfied with the connotation "without consciousness")

*Unknowingly (not quite satisfied with the connotation "foolishly")

*Unintentionally (not quite satisfied with the connotation "accidentally")

*Instinctively (not satisfied with the connotation of "naturally/innately")

I would really appreciate any suggestions or counterpoints that could persuade me otherwise on the above three choices.
Thank you very much in advance.

A: Unconsciously or subconsciously would be my first choices.  In these contexts they don't suggest "asleep", but "without being aware of the reason".  You can do something "unconsciously" and later know that you did it, but you didn't consciously decide to do it.
Alternatives that you might consider:
"Absent-mindedly":  When applied to an action it is rather similar in meaning to "subconsciously". It works better for the "patted his pocket absent-mindedly" rather than the smiling example
"Unaware" or "Unawares" (from comment) this is an adverb (not a plural noun, despite the form) It is used to mean "without being aware"

I blessed them unaware (from an old poem)

In the smiling example, it might be easiest to say nothing. Most smiles are done unconsciously.  "Instinctively" also works well for the smiling example, since smiles are instinctive.

A: You dislike 'Unconsciously' because you dislike the inference that it means 'without consciousness', but I think you misconstrue what that means. In your example it means
he performs the action of patting his pocket without the action rising to the level
of his concious mind, not that the action itself lacks a consciousness.
As a British English speaker I'd use 'subconsciously' in both your examples: he's doing something he'd do consciously, but it's so automatic that it didn't even get
to his consciousness. 'Unconsciously' to me, adds the meaning that he didn't
necessarily want to pat his pocket eg: 'He unconsciously gave away the location
of his cigars'
The OED gives:
"Operating or existing (just) below the level of conscious perception or control" for subconsciously' and
"In an unconscious manner; without conscious action, effort, thought, or awareness; unknowingly" for 'unconsciously'.
So either would convey you meaning.


text:
Q: Sampling Bayes factors under the null hypothesis to estimate a threshold of "significance" for hypothesis testing Context: I have a psychology experiment with a 2 x 2 design (with Condition (label, no label) and ContrastType (head, tail) as my two factors) where I want to estimate whether the mean of each subgroup is different from zero, using Bayes factors. In the sample theory based framework I would do something like this in R:
library(lmer); library(emmeans)

model <- lmer(ChanceArcsin ~ ContrastType*Condition + (1 | Participant))
posthoc <- emmeans(model, ~ ContrastType | Condition,
                   options = list(infer = c(T, T),
                                  null = 0,
                                  level = .95))

Now, if I want to have Bayes factors instead of $p$-values, I would use brms::hypothesis like that:
library(brms)

p <- c(set_prior("uniform(-.8,.8)",
                 class = "Intercept"),
       set_prior("normal(0,.5)", class = "b"))
model <- brm(ChanceArcsin ~ ContrastType*Condition + (1 | Participant),
             prior = p, family = gaussian(),
             chains = 4, cores = 4, iter = 2000,
             save_all_pars = T)
hyp.test <- hypothesis(model,
                       c("Intercept > 0",
                         "Intercept + ContrastTypeTail > 0",
                         "Intercept + ConditionNo Label > 0",
                         paste("Intercept +",
                               "ConditionNo Label +",
                               "ContrastTypeTail +",
                               "ContrastTypeTail:ConditionNo Label",
                               "> 0")))

The problem here is that, with my data, I have Highest Posterior Density Intervals not far from zero and non-significant results from lmer + emmeans, but fairly high Bayes factors for a psychology experiment (between 10 and 46). I was a bit surprised and I ran some simulations on my design to get a better idea of the likelihood of observing such $b$-values under the null hypothesis (full code at the bottom). What I found was that the 95th percentile for Bayes factors was 14.5, and 25.5% of the Bayes factors from my simulations where above 3 (the somewhat common threshold value for results worth mentioning).
Questions: Is it okay/a good idea to use the 95th percentile (or whatever other value) as a threshold to interpret my null hypothesis test Bayes factors as being worth mentioning or not?
If I do so, is it better to run simulations with a larger sample size on my design, or use the actual sample size I have (that is, 69 observations, unequally divided between the different cells)?
I also saw this question but the link to the course is broken and I'm not very familiar with the idea of minimal Bayes factor. The reason why I want to report Bayes factors is that Bayesian analysis is not yet too widespread in psychology, and I'm not sure how publishable would be an article without any kind of explicit hypothesis testing, sadly...
Simulation code (a bit long):
# LIBRARY IMPORTS =======================================================================
library(lme4)
library(emmeans)
library(brms)
library(tidyverse)

# BAYESIAN POINT NULL HYPOTHESIS TESTING ================================================
H_naught.test <- function(N){
  # Generate random data
  # mean to 0, sd=.5 from real data
  new_old.sims <- replicate(100,
                            list(tibble(ChanceArcsin = rnorm(N*2, 0, .5),
                                        Participant = rep(1:N, each = 2),
                                        Condition = factor(rep(c("Label", "No Label"),
                                                               times = N/2, each = 2)),
                                        ContrastType = factor(rep(c("Head", "Tail"),
                                                                  times = N)))))

  # Define STB analysis function, returning emmeans analysis
  stb.analysis <- function(df.list){
    e <- lapply(df.list,
                function(df){
                  m <- lmer(ChanceArcsin ~ ContrastType*Condition +
                              (1 | Participant),
                            data = df)
                  t <- emmeans(m, ~ ContrastType | Condition,
                               options = list(infer = c(T, T), null = 0,
                                              level = .95)) %>%
                    as_tibble()
                  return(t)
                })
    return(bind_rows(e))
  }

  # Define Bayesian analysis function, returning hyp. test bf
  bayesian.analysis <- function(df.list){
    p <- c(set_prior("uniform(-.8,.8)",
                     class = "Intercept"),
           set_prior("normal(0,.5)", class = "b"))
    m.list <- brm_multiple(ChanceArcsin ~ ContrastType + Condition +
                             ContrastType:Condition +
                             (1 | Participant),
                           data = df.list, prior = p, family = gaussian(),
                           chains = 4, cores = 4, iter = 2000,
                           save_all_pars = T, combine = F)
    bf.list <- lapply(m.list,
                      function(m){
                        bf <- hypothesis(m,
                                         c("Intercept > 0",
                                           "Intercept + ContrastTypeTail > 0",
                                           "Intercept + ConditionNo Label > 0",
                                           paste("Intercept +",
                                                 "ConditionNo Label +",
                                                 "ContrastTypeTail +",
                                                 "ContrastTypeTail:ConditionNo Label",
                                                 "> 0")))
                        return(as_tibble(bf$hypothesis))
                      })
    bf <- bind_rows(bf.list)
    return(bf)
  }

  # Get evidence summary from simulations
  t <- proc.time()
  new_old.sims.stb.evid <- stb.analysis(new_old.sims)
  stb.time <- proc.time() - t
  t <- proc.time()
  new_old.sims.bayesian.evid <- bayesian.analysis(new_old.sims) %>%
    mutate(Condition = factor(ifelse(grepl("NoLabel", Hypothesis), "No Label", "Label")),
           ContrastType = factor(ifelse(grepl("Tail", Hypothesis), "Tail", "Head")))
  bayesian.time <- proc.time() - t

  return(list(BayesianEvidence = new_old.sims.bayesian.evid,
              SampleTheoryEvidence = new_old.sims.stb.evid,
}

new_old.sims.results.200 <- H_naught.test(N = 200)
bayesian.95 <- quantile(new_old.sims.results.200$BayesianEvidence$Evid.Ratio, .95)
stb.95 <- quantile(new_old.sims.results.200$SampleTheoryEvidence$p.value, .05)
bayesian.above3 <- sum(new_old.sims.results.200$BayesianEvidence$Evid.Ratio > 3) / 400
stb.bellow_dot05 <- sum(new_old.sims.results.200$SampleTheoryEvidence$p.value<.05) / 400


text:
Q: Accessing JS elements that loaded dynamically I'm trying to write a simple javascript to add more options to Google's search tools (the ones that are displayed when you press "More search tools". However, when I try to append the new element to an existing one, I receive an error. For example:
var yr = document.getElementById('qdr_y');
yr.parent.insertBefore(k,yr);

The second line throws an exception because yr is null. By examining the direct source code of a search results page, I've discovered that the basic results page contains only "All results", "More search tools", and the hidden "Less search tools". All the other options are injected in some other way.
How can I access these other elements so that I can add my new elements in the correct location?

A: there you have it:
// ==UserScript==
// @name           TESTE
// @namespace      TESTE
// @description    TESTE
// @include        http*://*.google.*
// ==/UserScript==

var k = document.createElement('div');
k.innerHTML = " bla bla "
var yr = document.getElementById('gbmm');
yr.insertBefore(k,yr.firstChild);

(It is just an example. You shouldnt use  and  tags anymore).

Unless you mean something like this

Then the code should look like this
// ==UserScript==
// @name           TESTE
// @namespace      TESTE
// @description    TESTE
// @include        http*://*.google.*
// ==/UserScript==

var k = document.createElement('li');
k.id = 'myoption'
k.className = 'tbou'
k.innerHTML = " Here is my option "
var yr = document.getElementById('clir_1');
yr.parentNode.appendChild(k);

Also, consider adding JQuery to your GM scripts.
// @require        http://code.jquery.com/jquery.min.js

It is much easier to code.
* EDIT *
Based on your comment

I'm looking to insert the node into the "All search tools" like in
  your second solution. However, what you've posted is precisely what
  I'm already doing, except with qdr_y instead of clir_1!

The following (very simple) code is the solution
// ==UserScript==
// @name           TESTE 3
// @namespace      TESTE 3
// @description    TESTE 3
// @require        http://code.jquery.com/jquery.min.js
// @include        http*://www.google.com/*
// ==/UserScript==

$(window).load(function(){
    $('.tbpc').click()
    $('.tbt').on('DOMNodeInserted', function() {
        if ($('#my_li').length) { $('#my_li').show() }
        else { $('#whv_').parent().append("
Now i am inside") }
    })
    $('.tbpo').on('click', function() { $('#my_li').hide() })
});

It is not as pretty as i would like to, but google make us do bad things :)

A: Note that parent in your code snippet should be parentNode.
Anyway, in general, for dynamic elements you need to check and wait for the target element(s).  And if something needs to be clicked, your script must click it. (It usually doesn't work well to try and use the pages JS functions on Google sites. Google pages are always extra "fun" to script for. ;) )
You need to make liberal use of polling to compensate for AJAX delays.  (Hooking into AJAX events or using mutation events both have a high pain-to-success ratio.  Polling works well.)
Finally, because it's Google, it's not enough to fire the poll once, because those search options are constantly getting overwritten.
Here's a sample script that works for me on US versions of Google search results (jQuery is required):
// ==UserScript==
// @name        _Google Search options add
// @include     http://www.google.com/*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==

if (window.top != window.self)  //-- Don't run on frames or iframes.
    return;

/*-- This script:
    1) Waits for the "More search tools" control.
    2) Clicks that control.
    3) Waits for the target element
    4) Adds our element before that one.
*/

waitForKeyElements ("#tbpi", clickMoreSearchToolsLink);

function clickMoreSearchToolsLink (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);

    waitForKeyElements ("#qdr_y", addOurExtraNodes);
}

function addOurExtraNodes (jNode) {
    jNode.before ("
Look at me, Ma!
");
}

/*--- waitForKeyElements():  A handy, utility function that
    does what it says.
*/
function waitForKeyElements (
    selectorTxt,    /* Required: The jQuery selector string that
                        specifies the desired element(s).
                    */
    actionFunction, /* Required: The code to run when elements are
                        found. It is passed a jNode to the matched
                        element.
                    */
    bWaitOnce,      /* Optional: If false, will continue to scan for
                        new elements even after the first match is
                        found.
                    */
    iframeSelector  /* Optional: If set, identifies the iframe to
                        search.
                    */
) {
    var targetNodes, btargetsFound;

    if (typeof iframeSelector == "undefined")
        targetNodes     = $(selectorTxt);
    else
        targetNodes     = $(iframeSelector).contents ()
                                           .find (selectorTxt);

    if (targetNodes  &&  targetNodes.length > 0) {
        /*--- Found target node(s).  Go through each and act if they
            are new.
        */
        targetNodes.each ( function () {
            var jThis        = $(this);
            var alreadyFound = jThis.data ('alreadyFound')  ||  false;

            if (!alreadyFound) {
                //--- Call the payload function.
                actionFunction (jThis);
                jThis.data ('alreadyFound', true);
            }
        } );
        btargetsFound   = true;
    }
    else {
        btargetsFound   = false;
    }

    //--- Get the timer-control variable for this selector.
    var controlObj      = waitForKeyElements.controlObj  ||  {};
    var controlKey      = selectorTxt.replace (/[^\w]/g, "_");
    var timeControl     = controlObj [controlKey];

    //--- Now set or clear the timer as appropriate.
    if (btargetsFound  &&  bWaitOnce  &&  timeControl) {
        //--- The only condition where we need to clear the timer.
        clearInterval (timeControl);
        delete controlObj [controlKey]
    }
    else {
        //--- Set a timer, if needed.
        if ( ! timeControl) {
            timeControl = setInterval ( function () {
                    waitForKeyElements (    selectorTxt,
                                            actionFunction,
                                            bWaitOnce,
                                            iframeSelector
                                        );
                },
                200
            );
            controlObj [controlKey] = timeControl;
        }
    }
    waitForKeyElements.controlObj   = controlObj;
}


text:
Q: ClamTK and Encrypted Home Directory I recently encrypted my home directory and since then I have realized Clam AV is not really scanning the file in my home directory. It is scanning the encrypted files. I am running the scan with the user who's home is encrypted (using ecryptfs-migrate-home).

How can I recursively scan my encrypted home directory now using ClamTK or freshclam?

A: The point is that when setup as a cron job to run at 2AM, as daily scans should be, the application needs the smarts to decrypt a home folder. Many users now encrypt the home folder or the whole disk. From the login, scanning just ~/.mozilla, ~/.thunderbird, and ~/Downloads (4.1GB) took significant time, maybe an hour, running about 50% CPU on a dual core machine and Ubuntu 18.04. That is not an efficient use of resources when you are logged in trying to get other tasks accomplished.


text:
Q: Do window monitoring tools exist? I'd like to find a tool that would monitor my windows (specifically across multiple virtual desktops), and popup an alert in, say, my currrent desktop whenever anything happens in another window anywhere (new mail in Outlook? New chat in FF gmail tab? File content auto-updating in NPP? etc etc).
The objective is to save cycling through all windows periodically to see if something has happened, and instead be notified of changes as they happen.
Do you know anything like this? (Freeware/Open-Source + Portable is a bonus, but I will gladly consider all options...
Thanks!

A: Sounds alot like you are looking for something like Growl. However that is a OS X application. There is a windows off-shoot which began a short time ago. However, I am not sure about running it in a client/server fashion across multiple machines. But maybe the info will be a jumping off point?
UPDATE - I did a little mote reading, and directly from Growl for Windows website:

Another option - growlnotify & GNTP
  libraries
If your favorite application doesn't
  support Growl yet but does offer an
  API, you can use the growlnotify
  command line script or one of the
  available GNTP libraries to send
  notifications. growlnotify
Send a Growl notification to a local
  or remote host via the command line
Download growlnotify>

Check out growlnotify at this link

A: At the risk of addressing your problem rather than your question - in your situation, I'd probably grab another video card & monitor so I could keep tabs on that host desktop while working on the virtual.


text:
Q: Script to restore db and close connections? Im looking for a scrip that I can just point at a .bak file and it will delete the current db and then restore the .bak file in its place. And will close all connections. Does anybody know of a script that will do this?
I want to do it in c#.

A: You should start by looking at SQL Server Management Object, in particular the Restore class.


text:
Q: Jwplayer for element inside kendo Editor i have used kendoui,In html editor of kendoui i add custom tool for audio integration and for audio i am using jwplayer,
when creating player for div inside editor it gives error Uncaught TypeError: Object #<Object> has no method 'setup'
i want to create jwplayer dive inside of kendo editor is it possible ?
if yes then how ?


text:
Q: What's the correct way to use Stubs and Mocks? Here's my example:
[TestMethod]
public void NewAction_should_return_IndexAction()
{
    NewViewModel viewModel = new NewViewModel()
    {
        Name = "José Inácio Santos Silva",
        Email = "joseinacio@joseinacio.com",
        Username = "joseinacio"
    };

    //IsUserRegistered is used to validate Username, Username is unique.
    _mockAuthenticationService.Setup(x => x.IsUserRegistered(viewModel.Username )).Returns(false);

    //IsUserRegistered is used to validate Email, Email is unique.
    _mockUsuarioRepository.Setup(x => x.GetUserByEmail(viewModel.Email));
    _mockDbContext.Setup(x => x.SaveChanges());
    _mockUsuarioRepository.Setup(x => x.Add(It.IsAny<User>()));

    _userController = new UserController(_mockUsuarioRepository.Object, _mockDbContext.Object, _mockAuthenticationService.Object);

    ActionResult result = _userController.New(viewModel);

    result.AssertActionRedirect().ToAction("Index");

    _mockAuthenticationService.VerifyAll();
    _mockUsuarioRepository.VerifyAll();
    _mockDbContext.VerifyAll();
}

I have read some tutorials and they say that we should use only one mock per test.
But look at my test, it use 3 mocks, to check if my Action is working the right way I need to check these 3 mocks, do not agree?
How do I make this test in the correct way?

A: Each unit test should test only one thing.
In your unit test you are testing three mock objects. If the mockAuthenticationService fails, this will be reported and the unit test will stop there. Any errors with the other Mock objects are not reported and are effectively hidden.
In this situation you should create three unit tests, and in each one verify only one of the Mock objects. The rest are just used as stubs. (A stub is exactly the same as a Mock object, except you dont call VerifyAll on it at the end)
To avoid duplication and wasted effort, you should refactor that unit test so that most of the code is in a separate method. Each of the three unit tests calls this method and then verifies a single Mock.
You also have a test to ensure the correct redirect is called. This should also be in a separate test.
Quite simply:
[TestMethod]
public void NewAction_should_checkUserRegistered()
{
    SetupTest();
    _mockAuthenticationService.VerifyAll();
}

[TestMethod]
public void NewAction_should_GetUserByEmail()
{
    SetupTest();
    _mockUsuarioRepository.VerifyAll();
}

[TestMethod]
public void NewAction_should_SaveDBContext()
{
    SetupTest();
    _mockDbContext.VerifyAll();
}

[TestMethod]
public void NewAction_should_return_Redirects_Action()
{
    var novoActionResult = SetupTest();
    novoActionResult.AssertActionRedirect().ToAction("Index");
}

A: Short answer: "only one mock per test." is ambiguous. Use as many fakes as you need to isolate the code under test to a "unit" that is testing one condition.
It should be phrased: Only test one thing per test. If you are checking the state of more than one mock object you are probably testing more than one thing.

Long answer:
There is a lot to answer here to get the unit test written according to the best practices I have come across.
Common terminology from (The Art of Unit Testing), which I hope will come to be common:
Fake - an object that isolates the code under test from the rest of the application.
Stub - a simple fake object.
Mock - a fake object that stores what is passed to it, that you can inspect to verify the test.
Stubs and Mocks are both types of fake.
"only one mock per test." is wrong. You use as many fakes as you need to fully isolate the code under test from the rest of the application. If a method takes no parameters, there's nothing to fake. If a method takes a simple data type e.g. int, string, that doesn't have any complex behaviour, you don't need to fake it. If you have 2 repositories, context, a service object passed in, fake all of them, so no other production methods are being called.
You should have one condition per test as @Mongus Pong has said.
Test naming convention: MethodUnderTest_Condition_ExpectedBehaviour in this case you cannot do that as you have got more than one condition tested.
Test pattern: Arrange, Act, Assert. From your test, it seems as that is what you have done, but you have are arranging using private members. You should replace these with variables in each test, since the running order of tests is not always enforced, the state of these variables cannot be guaranteed, making your tests unreliable.
Buy a copy of "The Art of Unit Testing" http://artofunittesting.com/ it will answer a lot of more of your questions and is a great investment; one of the books that I'd grab if the office caught fire.

A: IMHO mocks and stubs are not that unique defined - every author uses them slightly different.
As I understand stubs "mock" behavior or "output" while you use mocks for example to check "input" into the mocked object/interface (like the Verify-Methods in MOQ).
If you see it this way then yes I too think you should only use one Mock because you should only test one thing - if you see it more like the stubs to inject testable interfaces then it's impossible to do.
If the VerifyAll is really needed here you indeed use 3 mocks, but I don't think they are nedded.

A: The best way to use Mock and stubs with Dev Magic Fake, so you can mock the UI and the DB for more information see Dev Magic Fake on codePlex
http://devmagicfake.codeplex.com/
Thanks
M.Radwan


text:
Q: Creating correct date format for SELECT...BETWEEN query I have 2 variables which make up a date range which then needs to be searched in a MySQL database.
These are in the format 'Apr, 2011' and 'Mar, 2012' etc.
My SELECT...BETWEEN query requires '2011-04-01' and '2012-03-31', so whats the best way to provide this...
Convert the dates in PHP first?
Or is there a way to write the query to search using the original format?  I tried with date_format (date, '%b, %Y') but the query found nothing.

A: Try this:
SELECT * FROM tablename
WHERE dateCol BETWEEN DATE_ADD(DATE(STR_TO_DATE('Apr, 2011', '%b, %Y')), INTERVAL 1 DAY) AND LAST_DAY(STR_TO_DATE('Mar, 2012', '%b, %Y'));

Check the SQL FIDDLE DEMO


text:
Q: Spark Categorize ordered dataframe values by a condition Let's say I have a dataframe
val userData = spark.createDataFrame(Seq(
  (1, 0),
  (2, 2),
  (3, 3),
  (4, 0),
  (5, 3),
  (6, 4)
)).toDF("order_clause", "some_value")

userData.withColumn("passed", when(col("some_value") <= 1.5,1))
        .show()

+------------+----------+------+
|order_clause|some_value|passed|
+------------+----------+------+
|           1|         0|     1|
|           2|         2|  null|
|           3|         3|  null|
|           4|         0|     1|
|           5|         3|  null|
|           6|         4|  null|
+------------+----------+------+

That dataframe is ordered by order_clause. When values in some_value become smaller than 1.5 I can say one round is done.
What I want to do is create column round like:
+------------+----------+------+-----+
|order_clause|some_value|passed|round|
+------------+----------+------+-----+
|           1|         0|     1|    1|
|           2|         2|  null|    1|
|           3|         3|  null|    1|
|           4|         0|     1|    2|
|           5|         3|  null|    2|
|           6|         4|  null|    2|
+------------+----------+------+-----+

Now I could be able to get subsets of rounds in this dataframe. I searched for hints how to do this but have not found a way to do this.

A: You're probably looking for a rolling sum of the passed column. You can do it using a sum window function:
import org.apache.spark.sql.expressions.Window

val result = userData.withColumn(
    "passed",
    when(col("some_value") <= 1.5, 1)
).withColumn(
    "round",
    sum("passed").over(Window.orderBy("order_clause"))
)

result.show
+------------+----------+------+-----+
|order_clause|some_value|passed|round|
+------------+----------+------+-----+
|           1|         0|     1|    1|
|           2|         2|  null|    1|
|           3|         3|  null|    1|
|           4|         0|     1|    2|
|           5|         3|  null|    2|
|           6|         4|  null|    2|
+------------+----------+------+-----+

Or more simply
import org.apache.spark.sql.expressions.Window

val result = userData.withColumn(
    "round",
    sum(when(col("some_value") <= 1.5, 1)).over(Window.orderBy("order_clause"))
)


text:
Q: Custom post type, sort taxonomy terms by a meta box value I've have created a custom post type with a taxonomy. I need to sort the taxonomy posts by a meta value in my custom post type.
I am using the plugin Advanced Custom Fields to insert a separate meta value field to my posts in my custom post types. So far I've
been able to get posts taxonomies sort by its value. My problem is that I get "all" of my taxonomies post printing out on the front-end.
I would like to get the posts for each taxonomies it's related to, not ALL. I've been testing to get the term id by implement it on the
wp_query array but with no success. I simply want to display my taxonomies individually and grab its related posts, is this possible, what am I doing wrong?
Here's my code...
    <?php
get_header();

if( have_posts() ) {
?>

<?php
            // gets our taxonomy title
            global $wp_query;
            $term = $wp_query->get_queried_object();
            $title = $term->name;
?>

            <header id="<?php echo $term->slug;?>" class="col-md-12">

<a href="<?php bloginfo( 'url' ); ?>/?p=493"><?php echo $title; ?>

            `enter code here`
<?php

        // wp_query-loop for our custom post typ "Personal", sort by meta_value
        $wp_query = new WP_Query(array(
            'post_type'         => 'Personal',
            'posts_per_page'    => -1,
            'meta_key'          => 'sorterings_nummer',
            'orderby'        => '$term->term_id meta_value',
            'ordertax'       => 'DESC',
            'order'          => 'ASC'
        ));

        // gets our custom post type posts with a thumbnail, title and contact details
        while( $wp_query->have_posts() ) {
            $wp_query->the_post();

            $class = get_field('sorterings_nummer') ? 'class="sorterings_nummer"' : '';

            $titel = get_post_meta(get_the_ID(), 'titel');
            $telefon = get_post_meta(get_the_ID(), 'telefon');
            $mobil = get_post_meta(get_the_ID(), 'mobil');
            $mail = get_post_meta(get_the_ID(), 'mail');
            add_filter('the_content', 'wpautop');
?>

                        <?php the_post_thumbnail(); ?>

<?php the_title(); ?>

<?php echo $titel[0] ? $titel[0]: ''; ?>

<a href="tel:<?php echo $telefon[0] ?>"><?php echo $telefon[0] ? $telefon[0]: ''; ?>

                            <a class="mail" href="mailto:<?php echo $mail[0] ?>"><?php echo $mail[0] ? $mail[0]: ''; ?>
                            <a class="mobil" href="tel:<?php echo $mobil[0] ?>"><?php echo $mobil[0] ? $mobil[0]: ''; ?>

<?php
        } // while content
?>

<?php
} // if
get_footer();

A: Please try tax_query() for retrieving posts assigned to the particular taxonomy term.
Please find your updated $wp_query() code below:
$wp_query = new WP_Query(array(
            'post_type'         => 'Personal',
            'posts_per_page'    => -1,
            'tax_query'         => array(array('taxonomy' => 'taxonomy_slug_name', 'field' => 'id', 'terms' => $term->term_id )),
            'meta_key'          => 'sorterings_nummer',
            'orderby'           => 'meta_value',
            'ordertax'          => 'DESC',
            'order'             => 'ASC'
        ));

Please write your 'taxonomy_slug_name' in the taxonomy column of tax_query().
Hope, this may be helpful to you.


text:
Q: sweethome3d and easytether not working on ubuntu 15.04 I clicked the upgrade button from version 14.10 to 15.04. sweethome3d and EasyTether do not work. I went to Ubuntu Software Center uninstalled sweethome3d and reinstalled and it still will not start.
I also got the latest copy of EasyTether (easytether_0.7.4-1_amd64.deb) reinstalled it and it connects but it will not connect to the internet. I have a dual boot to 14.10 and both these programs work fine on 14.10 with the same hardware. Which is HP TouchSmart 14 Sleekbook and using HTC Droid DNA for the easyTether connection.

A: For easytether, autoconfig does not work because they upgraded network-manager.
Configure the network interface manually with dhclient, there should be instructions in the terminal when you run easytether.

A: This problem with SweetHome3D, which I also experience, may caused by the 'systemd' switchover in Ubuntu 15.04. A similar issue has been found with ESET Nod32 Antivirus and is solved for that specific app here...
http://kb.eset.com/esetkb/index?page=content&id=SOLN3723&locale=en_US
That worked for me with ESET but to compose an analogous script to put into /lib/systemd/system for SweetHome3D is well above my paygrade. Hopefully, if the solution does lie in that direction, someone may oblige?
EDIT - OK, so I thought I'd try opening Ubuntu 15.04 in Advanced Mode - 'Upstart' option. Because if the recent systemd switchover is the main cause, then this should work round the problem. But it still wouldn't launch. So back to normal boot and Terminal: sudo sweethome3d . Then it launched, after a delay and some comment about creating a particular folder for Java.
I haven't tried actually using it yet. So, who knows...

A: Easytether
I had the same problem with easytether, and running the recommended dhclient command did not correct the issue. My solution was to download instead the package intended for Mint 17.1 (v.0.8.3-1) and install it. From there, I ran from the terminal:
nohup sudo easytether-usb &
sudo dhclient tap-easytether

Which allowed me to connect, albeit easytether is no longer showing up as a network connection as it did when I ran Ubuntu 14.X. I haven't had much opportunity to test the stability or security of this - I frankly have a limited knowledge of the differences between Ubuntu and Mint, but I haven't had any issues so far.
Sweethome3d
I was able to download the newest version of Sweethome3d (v.4.6) from the download page and it ran without issue on my Ubuntu 15.04 installation. I then tried downloading and running the version from the Ubuntu Software Center (v.4.5+dfsg-3) and was unable to get it to run (it just throws a LOT of exceptions). I conclude, therefore, the issue lies in the version provided in the Ubuntu Software Center, which simply isn't compatible with 15.04.

A: Latest version of easytether apk latest version easytether deb .. Use steps that was posted above DNS does not get set so you must manually enter a DNS in /etc/dhcp/dhclient.conf .. Restart

A: This worked with easytether PRO on a Dell XPS 12 laptop and a fresh install of 15.04
1) Open the dhclient configuration file for editing
sudo gedit /etc/dhcp/dhclient.conf

2)Add the easytether-tap hard coded DNS
prepend domain-name-servers 192.168.117.1/24

save and close file, restart machine
3)Start easytether service
sudo easytether-bluetooth xx:xx:xx:xx:xx:xx

xx:xx:xx:xx:xx:xx being the bluetooth device address (which can be found through the bluetooth settings on the panel) or if your using a usb cable
sudo easytether-usb

4)Once connected, configure the network interface.
sudo dhclient easytether-tap

5)Test connection in your browser
*Note: Easytether is my only internet connection so I am unable to verify that the change to the dhclient.conf file doesn't effect the operation of other network setups in use.


text:
Q: Why don't errors get returned when calling properties that don't exist? Given the following snippet
$drives = Get-PSDrive

foreach($drive in $drives)
{
    Write-Host $drive.Name "`t" $drive.Root
    Write-Host " - " $drive.Free "`t" $drive.PropertyDoesntExist
}

The drive.PropertyDoesntExist property doesn't... erm... exist so I would expect an error to be thrown but instead it returns a null.
How can I get errors or exceptions?
EDIT - Me bad - I asked 2 questions in one so I moved one into a separate question.

A: The NextHop Blog provides a good solution to this problem. It doesn't give you an error, but instead a boolean. You can use Get-Member to get a collection of all of the real properties of the object's type and then match for your desired property.
Here's an example for strings:
PS C:\> $test = "I'm a string."
PS C:\> ($test | Get-Member | Select-Object -ExpandProperty Name) -contains "Trim"
True
PS C:\> ($test | Get-Member | Select-Object -ExpandProperty Name) -contains "Pigs"
False

If you explicitly want an error, you may want to look into Set-Strictmode as Set-StrictMode -version 2 to trap non-existent properties. You can easily turn it off when you're done with it, too:
PS C:\> Set-StrictMode -version 2
PS C:\> "test".Pigs
Property 'Pigs' cannot be found on this object. Make sure that it exists.
At line:1 char:8
+ "test". <<<< Pigs
    + CategoryInfo          : InvalidOperation: (.:OperatorToken) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

PS C:\> Set-StrictMode -off