text:
Q: React Redux Action Creator Dispatch Issue with Fetch API and Promise I am writing action creator in react app. where in when i do some api call i need to show the Progress Loader on screen. So, my action creator looks like this.
export const fetchData = (actionType, param) => (dispatch) => {
  dispatch(Action(ActionConstants.SHOW_PROGRESS_LOADER)); // Show Loader Action
  return fetchDataRequest(actionType, param) // Here is Fetch APi Call
    .then(responseData => {
      dispatch(Action(ActionConstants.HIDE_PROGRESS_LOADER));
      dispatch(Action(recd(actionType), { data: responseData, receivedAt: Date.now() }));
    }).catch((error) => {
      dispatch(Action(ActionConstants.HIDE_PROGRESS_LOADER)); // Hide Loader Action
    });
};

When i write this piece of code its working as expected, i am dispatching the action as dispatch(fetchData(data)) from component and i am able to show the loader in my Parent Component. What i understand is fetch is returning me the promise. Once the fetch gets completed then i am hiding the loader which is working as expected.
Now, There is scenario where in i need to do some validation where in i don't have to make any api call but all the validation are performed locally.
Here also i want to do the same thing like i need to show loader in my parent component as well when all the validation are done i need to hide the loader.
I have written the same piece of code even actions are getting called but my render function is not getting called.
My Code Looks like:
// This my action creator which will actually do the validation
export const validateAndSaveData = () => {
  return ((dispatch, getState) => {
    return new Promise((resolve, reject) => {
      let saveRecommendDetailsFlag = true;
      // here i am dispacthing some action and storing data in my store
      saveRecommendDetailsFlag = canSaveData(getState());
      if (saveRecommendDetailsFlag) {
        resolve('SUCCESS');
      } else {
        reject('ERROR');
      }
    });
  });
};

And there is one more action creator which i am calling it from from UI Component which will first initiate the show loader action and then perform validation and based on the result of validation i have to hide the loader.
export const saveData = () => {
  return ((dispatch) => {
   dispatch(Action(ActionConstants.SHOW_PROGRESS_LOADER)); // Show Loader Action
    return dispatch(validateAndSaveData())
      .then(() => {
       // Here i m dispatching an action to do some more processing.
 dispatch(Action(ActionConstants.HIDE_PROGRESS_LOADER)); // Hide Loader Action
      })
      .catch(() => {
       dispatch(Action(ActionConstants.HIDE_PROGRESS_LOADER)); // Hide Loader Action
      });
  });
};

Everything is working fine but my loader are not coming on the screen. i am not able to figure it out where am i doing wrong.
Can anyone suggest something how can i solve this issue?
I got some workaround using setTimeout func but i don't think that is right approach.
export const saveData = () => {
  return ((dispatch) => {
   dispatch(Action(ActionConstants.SHOW_PROGRESS_LOADER)); // Show Loader Action
    setTimeout(()=>return dispatch(validateAndSaveData())
      .then(() => {
       // Here i m dispatching an action to do some more processing.
 dispatch(Action(ActionConstants.HIDE_PROGRESS_LOADER)); // Hide Loader Action
      })
      .catch(() => {
       dispatch(Action(ActionConstants.HIDE_PROGRESS_LOADER)); // Hide Loader Action
      });
},10);
  });
};

A: Your code looks reasonable, my suspicion is that your validateAndSaveData promise finishes so quickly that there is no visible loader on the screen.
In that case, a timeout is totally reasonable. However, in order to do it properly, I would keep a state on if the loading screen is visible + if it's been shown long enough. You can then remove the loading screen once it is both up for long enough, and the actual event expires.
I'm not sure which action package you're using, so I can't post exact code, but the pseudocode would look something like this:
const delay = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds));

let loadingCounter = 0;
const showLoadingScreen = () => (dispatch) => {
  const counter = loadingCounter;
  loadingCounter++;

  delay(5).then(() => {
    if (getStore().loadingScreen.counter === counter) {
      dispatch(Action(ActionConstants.PROGRESS_LOADER_DELAY_ELAPSED))
    }
  })

  return dispatch(Action(ActionConstants.SHOW_PROGRESS_LOADER, counter))
}

Basically, you would keep track of 3 pieces of state for the loader:
{
  counter: 0,
  taskCompleted: false,
  canHide: false,
}

Counter is saved so that you can disambiguate what happens if you get SHOW_PROGRESS_LOADER while an existing SHOW_PROGRESS_LOADER is in progress.
taskCompleted keeps a record of whether the thing you're waiting on is done, and canHide keeps track if the loader has been visible on the screen long enough.
When you dispatch PROGRESS_LOADER_DELAY_ELAPSED it sets canHide to true, and when you dispatch HIDE_PROGRESS_LOADER it sets taskCompleted to true. (although you may want to rename the latter action). When both canHide and taskCompleted are set to true, only then can the loader go away.
This is a pretty common UI pattern - Try to complete a task quickly. If it takes more than a short amount of time, then throw up a loading dialog. However, the loading dialog is guaranteed to stay up a minimum amount of time to prevent flickering. So the more advanced version of this kind of pattern would be to add another state which doesn't show the progress loader at all unless the call takes more than Y milliseconds.
Hope this makes sense, leave a comment if not :-)


text:
Q: How to fill in every nth row with values from another column with dplyr? Hi supposed I have a dataframe as such
temp <- data.frame(value = sample(c ( 1:312), 20 ), value2 = sample(c ( 1:312), 20 )  )

   value value2
1    217    270
2    299    155
3     77    249
4    116     89
5     54     18
6    248    228
7    154    273
8    218    146
9    149    131
10   134     68
11   282     47
12   169    196
13    20    276
14   233    240
15   222     92
16   102      1
17   297     49
18     9     65
19   289    118
20    75    255

What I like to do is  fill in every 3rd row with the data from value2. So for example, all rows above rows 1 & 2 would be 0 and the third row would 249, rows 5 &6 are 0 and row 7 would be 273 and so fourth.
Would be great if I can do with dplyr. thanks in advance.

A: You may use if_else -
set.seed(123)
temp <- data.frame(value = sample(c(1:312), 20), value2 = sample(c(1:312), 20))

temp %>%
  mutate(value3 = if_else(row_number() %% 3 == 0, value2, 0L))

#   value value2 value3
#1    179    211      0
#2     14     78      0
#3    195     81     81
#4    306     43      0
#5    118    143      0
#6    299     32     32
#7    229    109      0
#8    244    263      0
#9    311     23     23
#10   153    135      0
#11    90    224      0
#12    91    166    166
#13   256    217      0
#14   197    290      0
#15   301     69     69
#16   137     72      0
#17    26     76      0
#18     7     63     63
#19   297    141      0
#20   254    210      0

redpajama_set_name: RedPajamaStackExchange


text:
Q: A conflation of modes On the one hand, we have a set of property values.   Among these are declarative, interrogative and imperative.   On the other hand, we have a separate set of property values.   These include indicative and subjunctive.   On the gripping hand, we have the label mode, which is generally used for either property.
The properties seem distinct, if not quite orthogonal:

We can do that.   -- declarative and indicative
  We could do that.  -- declarative and subjunctive
Can we do that?   -- interrogative and indicative
  Could we do that?   -- interrogative and subjunctive
Hey you, do that!   -- imperative, probably neither indicative nor subjunctive

Please understand that, in the context of this question, I don't care whether "can" is denotatively dynamic, alethic, or anything else.   I'm looking at mode as marked by grammar.   Or, alternately, I'm looking for some category other than mode that describes one set while ignoring the other.
Do we have a way to label the separate sets?   We can see what distinguishes the interrogative from the declarative, as a given clause can employ no more than one of those modes.   What distinguishes the interrogative mode from the subjunctive mode, given that both modes can be employed by the same clause?

Edit:
The site Linguistic Girl proposes the label sentence purpose to describe that property of which declarative, interrogative and imperative are values.   Unfortunately, it also lists exclamatory as a purpose, despite the fact that whatever property it represents is clearly orthogonal to the rest.   The site K12 Reader gives no better label than sentence type to this same group of four.   The relevant Wikipedia page is titled sentence function.
The moment we stumble across a tag question, we should immediately realize that it is not the sentence but the clause which has this property.   Still, function, type, purpose -- is this really the best we can do?

A: The best solution here is to refrain from regarding "declarative" and "interrogative" as moods.  They might be types of epistemic modality in a broad sense (see http://www.glossary.sil.org/term/epistemic-modality ), but they are not grammatical moods.  They are certainly not forms of inflection, nor do they have distinct modal verbs associated with them.
There are various schools of thought when it comes to "mood".  ("Modality" often has an even wider set of meanings.)
Traditional grammars count the indicative, subjunctive, and imperative as English moods.  Some count the infinitive as well.
The modal verbs, of course, are so named because they are generally used to express mood or modality in an even broader sense.
Huddleston and Pullum write in the Cambridge Grammar of the English Language: "Mood is a matter of grammatical form, modality a matter of meaning. ... The main markers of mood in English are the modal auxiliaries can, may, must, will, shall, together with a few less central ones."
It is not conventional to refer to "could" as a subjunctive.  The term "subjunctive" is generally reserved for certain verb forms used in mandative and optative expressions ("I asked that it be done"; "Long live the Queen"; "I wish she were here").


text:
Q: c#: Where to put my API and what should go into MyCOmpanyName.MyProduct.Core (core) namespace? can anyone help me with bit of refactoring advice.
I have my App which i have in the namespace - these namespaces i am happy with.
  MyCompany.MyProduct.Web (for the web app)

  MyCompany.MyProduct.Windows (for the windows app)

these apps need to call my API .. The API is specifically for this application but lives separately. Currently I have it in the following form.
  MyCompany.MyProduct.Api

But i really don't like it... i was thinking maybe better to put it in
  MyCompany.MyProduct.Core

Is this a good way?
Under Core i will have Enums, Exception Classes etc
So these would be actually
  MyCompany.MyProduct.Core.Enums.DaysOfWeek (DaysOfWeek is an example)

  MyCompany.MyProduct.Core.Exceptions.ConnectionException (just an example)

Is Core a good idea and what should go in there.????
If I have a command called CreateSchedule which is under the class Schedule which is part of my api then what would be a good idea for the complete namespace including method etc
             MyCompany.MyProduct.Core.Schedule.CreateSchedule   ???

I presume i put under the ROOT (i.e. CORE) all enums / exceptions that are globally specific to my api. Is it good practice that my app can use Enums /Exceptions from my API - this is how i currentlt have it. if i have an enum that is specific only to a class do i keep it there in ROOT (core) or better to put it
             MyCompany.MyProduct.Core.Schedule.Enums

I hope someone can help me on this
thanks in advance

A: *

*I think if an enum applies to only a specific class, then it makes sense to make the enum be within that class (i.e. not at the root level). For exampe, it makes sense for DaysOfWeek to be within the Schedule class.

*"Core" is certainly better than "Api", which sort of looks weird since it's an acronym.

*I am not sure about having a namespace for Exceptions (i.e. MyCompany.MyProduct.Core.Exceptions.xxx). I would rather put the exception classes as siblings of the class from which they are generated.


text:
Q: Thread Run not working properly I made a simple Java program that uses a Thread object to move a square around a JPanel. The square moves to a random position, changes its color and the JPanel changes its background color. And then the thread sleeps for 1000 ms. But then I added one more line of code that adds +1 to a JLabel and the square stopped moving (while the score was working and adding +1).
Here is the code:
@Override
public void run() {

    Random random = new Random();

    int width = 0;
    int height = 0;

    while(true) {

        width = random.nextInt(area.getSize().width) + 1;
        height = random.nextInt(area.getSize().height) + 1;

        width -= ((width - 45) > 0) ? 45 : 0;
        height -= ((height - 45) > 0) ? 45 : 0;

        this.square.setLocation(width, height);
        this.square.setIcon(new ImageIcon(getClass().getResource("/img/square" + (random.nextInt(4) + 1) + ".png")));
        this.area.setBackground(new Color(random.nextInt(255) + 1, random.nextInt(255) + 1, random.nextInt(255) + 1));

        //The following line works, but the setLocation method stops working.

        this.score.setText(Integer.toString(Integer.parseInt(this.score.getText()) + 1));

        try {

            sleep(1000);

        } catch (InterruptedException ex) {

            Logger.getLogger(RunThread.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

}

Any ideas?
Thanks.
Edit: this is how I create a Thread...
public Click() {

    initComponents();
    pack();
    setLocationRelativeTo(null);
    setVisible(true);

    RunThread run = new RunThread(jLabel1, jLabel2, jPanel1);
    run.run();

}

A:
invoke the run() method in

Which is wrong. That is not how to use a Thread. If you invoke the run() method then it is just treated like any other method and you are not using a Thread. Therefore, whenever you use Thread.Sleep(...) you are causing the Event Dispatch Thread(EDT) to sleep which means the GUI can't repaint itself.
To use a Thread. you need to invoke the start() method on the Thead, so the code should be:
run.start();


text:
Q: Increment and bitwise shift operator precedence? Increment suffix and prefix are both of higher operator precedence than bitwise left shift, but the following prints out different results.
int testValue = 1;
std::cout << ++testValue; //prints 2
//saw it as std::cout << (++testValue);

testValue = 1;
std::cout << testValue++; //prints 1
//thought it was std::cout << (testValue++);

Why does increment suffix as shown in the second example print 1 before incrmenting? I thought it was bound more tightly to testValue like in the increment prefix case, so I thought it'd be incremented first before being printed with std::cout.

A: << not bitwise operator, but insertion operator. cplusplus reference:

As an object of class ostream, characters can be written to it either
  as formatted data using the insertion operator (operator<<).

testValue = 1;
std::cout << testValue++; //prints 1

Post increment means the increment is done after the variable is read.

A: You misunderstand what testValue++ does.
It increments testValue but its evaluation is before the increment is made.
The line
std::cout << testValue++;

is equivalent to
std::cout << testValue;
testValue = testValue + 1;


text:
Q: Create a form that maintain value (filter on a rest api result) i would like to create a custom form on magento that request from a server on some document. The document will be displayed inside the page but i need to maintain the form with the filter already selected.
How can i solve?
ps: you can think about a sort of "filter form sidebar" where you apply filters and they remain when you press the submit button.


text:
Q: want to more classify about my RegEx (regular expression) I have the following regex:
var re = new RegExp(/\btranslate\b(\(([-+]?([0-9]+)(\.[0-9]+)?)\s([-+]?([0-9]+)(\.[0-9]+)?)\))/g);

It matches "translate(-0.24588 125.3)" from "kjgjhgjkg jgjgj kjgjkg hj translate(-0.24588 125.3) jjhkjghj" string.
Now what I have approached is shown below. I find a particular string but I want to further replace that matched string.
var re = new RegExp(/\btranslate\b(\(([-+]?([0-9]+)(\.[0-9]+)?)\s([-+]?([0-9]+)(\.[0-9]+)?)\))/g);
undefined
var string = "kjgjhgjkg jgjgj kjgjkg hj translate(-0.24588 125.3) jjhkjghj";
undefined
var firstelem = re.exec(string);
undefined
firstelem
["translate(-0.24588 125.3)", "(-0.24588 125.3)", "-0.24588", "0", ".24588", "125.3", "125", ".3"]

Here, ["translate(-0.24588 125.3)", "(-0.24588 125.3)", "-0.24588", "0", ".24588", "125.3", "125", ".3"].
I think it should be only one match and that would be
["translate(-0.24588 125.3)"].
So, I actually need to replace translate(-0.24588 125.3) with translate(-0.24588, 125.3) in the "kjgjhgjkg jgjgj kjgjkg hj translate(-0.24588 125.3) jjhkjghj" string. How can I do this?
Any suggestions how to improve my regular expression or other parts of code are welcome.

A: To add a comma inside the translate(value value) string, you may modify your code like this:

var re = /\b(translate\b(?:\((?:[-+]?(?:[0-9]+)(?:\.[0-9]+)?)))\s([-+]?(?:[0-9]+)(?:\.[0-9]+)?\))/g;
var str = 'kjgjhgjkg jgjgj kjgjkg hj translate(-0.24588 125.3) jjhkjghj';
var result = str.replace(re, "$1, $2");
document.write(result);

What I did is re-distributed the capturing groups so that there are just two of them. The first one (translate\b(?:\((?:[-+]?(?:[0-9]+)(?:\.[0-9]+)?))) matches translate(value, and the second one - ([-+]?(?:[0-9]+)(?:\.[0-9]+)?\)) - matches value).


text:
Q: SQL server - count distinct over function or row_numer with rows window function I am currently trying to get a distinct count for customers over a 90 day rolling period. I have got the amount using sum amount and over partition. However, when I do this with count distinct, SQL doesn't have functionality.
I have attempted to use row_number() with the over partition and use rows current row and 90 preceding but this also isn't available.
Would greatly appreciate any suggested work around to resolve this problem.
I have attempted to solve the problem using 2 approaches, both which have failed based on the limitations outlined above.
Approach 1
select date
       ,count(distinct(customer_id)) over partition () order by date rows current row and 89 preceding as cust_count_distinct

from table

Approach 2
select date
       ,customer_id
       ,row_number() over partition (customer_id) order by date rows current row and 89 preceding as rn
from table

-- was then going to filter for rn = '1' but the rows functionality not possible with ranking function windows.

A: The simplest method is a correlated subquery of some sort:
select d.date, c.nt
from (select distinct date from t) d cross apply
     (select count(distinct customerid) as cnt
      from t t2
      where t2.date >= dateadd(day, -89, d.date) and
            t2.date <= d.date
     ) c;

This is not particularly efficient (i.e. a killer) on even a medium data set.  But it might serve your needs.
You can restrict the dates being returned to test to see if it works.


text:
Q: HttpClient GetAsync disposes Webjob handler I'm implementing an Azure WebJob which, when triggered by a Service Bus Message, performs an async API call to an external web service. After executing the web request, something odd happens to my webjob and the inputMessage has been disposed before the end of the method.
Below is a basic example demonstrating the problem + output.
public async void HandleTestQueueMessage([ServiceBusTrigger("%TestQueue%")] BrokeredMessage inputMessage) {
    Console.WriteLine($"Received message {inputMessage.MessageId}.");

    Console.WriteLine("Starting web request.");
    await TestHttpClientAsync();
    Console.WriteLine("Finished web request.");

    await inputMessage.CompleteAsync(); // --> Exception occurs here
    Console.WriteLine($"Completed message {inputMessage.MessageId}.");
}

private async Task TestHttpClientAsync() {
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync("http://google.com");
    Console.WriteLine($"Got response, statuscode={response.StatusCode}.");
}

Console output:
Executing: 'ProblemTestHandler.HandleTestQueueMessage' - Reason: 'New ServiceBus message detected on 'TestQueue'.'
Received message a17cc4fce8c74b3c9f1b8f1a73b4ba1b.
Starting web request.
Executed: 'ProblemTestHandler.HandleTestQueueMessage' (Succeeded)
Got response, statuscode=OK.
Finished web request.

Unhandled Exception: System.ObjectDisposedException: BrokeredMessage has been disposed.
   at Microsoft.ServiceBus.Messaging.BrokeredMessage.ThrowIfDisposed()
   at Microsoft.ServiceBus.Messaging.BrokeredMessage.BeginComplete(AsyncCallback callback, Object state)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl(Func`3 beginMethod, Func`2 endFunction, Action`1 endAction, Object state, TaskCreationOptions creationOptions)
   at Microsoft.ServiceBus.Common.Parallel.TaskHelpers.CreateTask(Func`3 begin, Action`1 end, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Wkb.eInvoicing.Worker.Handlers.ProblemTestHandler.<HandleTestQueueMessage>d__1.MoveNext() in C:\Dev\eInvoicing\src\Wkb.eInvoicing.Worker\Handlers\ProblemTestHandler.cs:line 43
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

As you can see in the output, my JobHost container thinks the method successfully finished right after the execution of the httpClient.GetAsync() method:
Starting web request.
Executed: 'ProblemTestHandler.HandleTestQueueMessage' (Succeeded)
Got response, statuscode=OK.

When I replace the web request by a non-async alternative (e.g. using RestSharp), the problem does not occur. Any ideas what could be the root cause of this issue?

A: You should almost never use async void unless you are writing a event handler, you should be using async Task instead, this lets the system know that your webjob is not complete yet so it will not try and force shutdown the resource before it is complete.


text:
Q: Visual Studio Application Insights toolbar not showing events I'm new to Application Insights and testing the concept of sending custom data in a console application. I managed to see custom events in the search bar in the Azure portal, great.
My problem is in some of the tutorials I went through, there's a toolbar in Visual Studio that shows the number of events e.g. Application Insights (21) but mine just has Application Insights without a number next to it and clicking on it shows 0 events
My code is uber-simple:
static void Main(string[] args)
{
    TelemetryConfiguration.Active.InstrumentationKey = "APPLICATIONINSIGHTS_GUID";

    TelemetryClient TC = new TelemetryClient();
    TC.TrackEvent("My event");
    TC.Flush();
}

I'm got Visual Studio 2015. Should I install something to make this work?

A: You likely need to add the ApplicationInsights.config file to your project.
Make sure Build Action is Content and Output Directory is Copy if newer / Copy always so that it copies file to output directory on build

Also, make sure you at least have the <ApplicationInsights ... root tag in your config file. Something like this:
    <?xml version="1.0" encoding="utf-8"?>
    <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
    </ApplicationInsights>


text:
Q: Reading xml ref attribute in .NET I can do this in Xpath, but unfortunately for this particular project I am unable to use xpath.
I have the following node selected:
<client href="http://somewebsitehere.com" rel="needthisdata"></client>

clientnode.Attributes["href"].Value

correctly returns "http://somewebsitehere.com", but
clientnode.Attributes["rel"].Value

does not work?
What am I doing wrong here?
Full Usage:
foreach (XmlNode clientnode in clientnodelist)
{
    MessageBox.Show(clientnode.Attributes["rel"].Value);
}

The above gives a NullReferenceException, whereas replacing "rel" with "href" works fine.
I'm sure i've selected the correct node as well as innertext matches, as well as attribute.count returning 2.

A: Read your code. You are using clientnode as the loop variable, but you are referencing selectednode.

What if one particular node doesn't have a "rel" attribute? NullReferenceException.

A: I would add a break at the loop and take a look at what is in my Attributes collection. Also, for kicks, try changing "rel" to something else to see if it fixes the issue.


text:
Q: Is the Fractal Dimension of a Space-Filling Curve in a Plane Always 2? I have been playing around with space-filling curves that completely fill the unit square.  All of them that I have seen have a fractal dimensional of 2.  Makes sense that it would be 2, but a Google search hasn't turned up any comments on this at all.  So, is this a general result?  Thanks.

A: You seem unclear about the definitions. A curve that fills the unit square is a continuous map $\gamma : [0,1] \rightarrow [0,1]^2$ such that $\gamma([0,1])=[0,1]^2$. For a general curve (not necessarily filling the square), the Hausdorff dimension of that curve is simply the Hausdorff dimension of $\gamma([0,1])$, i.e. of the image of the curve. Since the Hausdorff dimension of the unit square is 2, then yes, by definition the dimension of a curve filling the unit square is 2.


text:
Q: Importing a csv file into database mysql Well my question seems simple
I have my csv file located in /etc/myData.csv
I have my code
USE assessment;

DROP TABLE IF EXISTS test_data;
CREATE TABLE test_data (
    ProductID int,
    ProductName varchar(255)
);

mysqlimport assessment  '/src/myData.csv';

SELECT * FROM test_data;

I tried msqlimport but it gives me syntax error.
I even tried this command
mysqlimport  --fields-terminated-by=, assessment  /src/test_data.csv ;

Again syntax error. What's wrong with it?
FYI: I already know LOAD command but I want to know other mysql command to import data.

A: mysqlimport is intended to be run from the shell command line nor via the SQL interface.
If you have an SQL interface you can use load data infile
 LOAD DATA LOCAL INFILE '/src/myData.csv' INTO TABLE test_data;

But you need to make sure the file is readable by the dbms uid.

A: I assume you know that you need to run mysqlimport -command from command line. It's not a SQL command that you can run with in your other SQL commands. Actually mysqlimport is just a command line interface to LOAD INFILE so you should use that.
If you want to use mysqlimport following command should work. Before running the command, you should change the file name to test_data.csv to get the data to test_data table.
mysqlimport -u root -ppassword --local assessment '/src/test_data.csv'


text:
Q: Using default popups to show Django Forms errors When defining a form using Django Forms, if I have an EmailField, I will get some neat popups like I show in the pictures:

But if I introduce a custom validation, I am unable to show errors to user in the same way (with a popup)
This is my forms.py:
from django import forms
from launcher.models import InterestedUser
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

class JoinForm(forms.ModelForm):
# this is the only field that is actually filled by the user
    email = forms.EmailField(max_length=128, help_text="Introduce la cuenta de gmail que tienes asociada a tu"
                                                   "dispositivo Android",
                         widget=forms.EmailInput(attrs={'class': "w-input email_input",
                                                        'placeholder': 'Tu email de Google'}),
                         required=True, validators=[RegexValidator(regex='^([a-zA-Z0-9_\.\-])+\@(gmail.com)+$',
                                                                   message="La dirección de email no es válida",
                                                                   code="invalid_gmail_address")])
print("atributos {0}".format(email.widget.attrs['class']))

# this other fields will have the same value and go hidden in the form
name = forms.CharField(widget=forms.HiddenInput(), initial="(not specified)")
subject = forms.CharField(widget=forms.HiddenInput(), initial="(no subject)")
via = forms.CharField(widget=forms.HiddenInput(), initial="Join")
content = forms.CharField(widget=forms.HiddenInput(), initial="no content")

def clean_email(self):
    email = self.cleaned_data.get('email')

    try:
        beta_tester = InterestedUser.objects.get(email=email)
    # Si el email no existiese entonces salimos del clean_email y devolvemos el valor (aunque no se haya modificado)
    except InterestedUser.DoesNotExist:
        return email
    # Si el email ya existía sacamos un error de Validación:
    raise forms.ValidationError("Ya estabas anotado como Beta Tester, introduce un email diferente!")

class Meta:
    model = InterestedUser
    fields = ('email', 'name', 'subject', 'via', 'content',)

And this is how I render it in the template:

                <form class="w-clearfix formulario_subscribe" name="email-form" id="join_form" method="post" data-name="Email Form" action="/">
                    {% csrf_token %}
                    {% for hidden in form.hidden_fields %}
                        {{  hidden }}
                    {% endfor %}
                    {% for field in form.visible_fields %}
                        {{ field.errors }}
                        {{ field.help_text }}
                        {{ field }}
                    {% endfor %}
                    <input class="w-button email_submit_button" type="submit" id="btn_send" value="Join" data-wait="Un momento!..."/>
                    {% if messages %}

                            {% for message in messages %}

{{ message }}

                            {% endfor %}

                    {% endif %}
                </form>

I have a RegexValidator and I would like to show the error message if the user input doesn't pass the validator in the same way (popups) that the default validator does it! Any ideas??
Thanks a lot in advance.

A: I think this popup is created by the browser validating the HTML5 email field(looks like chrome) you can disable this validation adding the novalidate attribute to the form field. Or more interesting you can use pattern to check for gmail.com addresses, something like:
<input type="email" pattern="/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@gmail.com$" />

If you want to validate on the client side you can use something like parsley
Also instead of validate emails with a regex you can check EmailValidator. There's a property domain_whitelist that you can use to restrict gmail.com domains.


text:
Q: Is there a way to know when the device's fingerprint sensor is touched in API 23? I think the title is pretty self-explanatory: I want to know when the fingerprint sensor on my device is being activated (usually this mean the user is now tapping his/her finger on the sensor).
I've tried looking at the list of system-wide broadcast on API 23 (in android/sdk/platforms/android-23/data/broadcast_actions.txt as specified by this question) but I didn't find any that is related to fingerprint or FingerprintManager on that matter.
The main reason why I think this feat is possible is you can actually wake-up a Nexus Imprint equipped device just by tapping on the sensor. That basically implies the device is listening for any input on the sensor at any given time, right?
I'm only interested at touch events regarding the sensor – not the fingerprint data itself.

For those who wondering, here are all API 23's system-wide broadcast as specified by the file I mentioned above:
android.app.action.ACTION_PASSWORD_CHANGED
android.app.action.ACTION_PASSWORD_EXPIRING
android.app.action.ACTION_PASSWORD_FAILED
android.app.action.ACTION_PASSWORD_SUCCEEDED
android.app.action.DEVICE_ADMIN_DISABLED
android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED
android.app.action.DEVICE_ADMIN_ENABLED
android.app.action.DEVICE_OWNER_CHANGED
android.app.action.INTERRUPTION_FILTER_CHANGED
android.app.action.LOCK_TASK_ENTERING
android.app.action.LOCK_TASK_EXITING
android.app.action.NEXT_ALARM_CLOCK_CHANGED
android.app.action.NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED
android.app.action.NOTIFICATION_POLICY_CHANGED
android.app.action.PROFILE_PROVISIONING_COMPLETE
android.app.action.SYSTEM_UPDATE_POLICY_CHANGED
android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED
android.bluetooth.a2dp.profile.action.PLAYING_STATE_CHANGED
android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED
android.bluetooth.adapter.action.DISCOVERY_FINISHED
android.bluetooth.adapter.action.DISCOVERY_STARTED
android.bluetooth.adapter.action.LOCAL_NAME_CHANGED
android.bluetooth.adapter.action.SCAN_MODE_CHANGED
android.bluetooth.adapter.action.STATE_CHANGED
android.bluetooth.device.action.ACL_CONNECTED
android.bluetooth.device.action.ACL_DISCONNECTED
android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED
android.bluetooth.device.action.BOND_STATE_CHANGED
android.bluetooth.device.action.CLASS_CHANGED
android.bluetooth.device.action.FOUND
android.bluetooth.device.action.NAME_CHANGED
android.bluetooth.device.action.PAIRING_REQUEST
android.bluetooth.device.action.UUID
android.bluetooth.devicepicker.action.DEVICE_SELECTED
android.bluetooth.devicepicker.action.LAUNCH
android.bluetooth.headset.action.VENDOR_SPECIFIC_HEADSET_EVENT
android.bluetooth.headset.profile.action.AUDIO_STATE_CHANGED
android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED
android.bluetooth.input.profile.action.CONNECTION_STATE_CHANGED
android.bluetooth.pan.profile.action.CONNECTION_STATE_CHANGED
android.hardware.action.NEW_PICTURE
android.hardware.action.NEW_VIDEO
android.hardware.hdmi.action.OSD_MESSAGE
android.hardware.input.action.QUERY_KEYBOARD_LAYOUTS
android.intent.action.ACTION_POWER_CONNECTED
android.intent.action.ACTION_POWER_DISCONNECTED
android.intent.action.ACTION_SHUTDOWN
android.intent.action.AIRPLANE_MODE
android.intent.action.APPLICATION_RESTRICTIONS_CHANGED
android.intent.action.BATTERY_CHANGED
android.intent.action.BATTERY_LOW
android.intent.action.BATTERY_OKAY
android.intent.action.BOOT_COMPLETED
android.intent.action.CAMERA_BUTTON
android.intent.action.CONFIGURATION_CHANGED
android.intent.action.CONTENT_CHANGED
android.intent.action.DATA_SMS_RECEIVED
android.intent.action.DATE_CHANGED
android.intent.action.DEVICE_STORAGE_LOW
android.intent.action.DEVICE_STORAGE_OK
android.intent.action.DOCK_EVENT
android.intent.action.DOWNLOAD_COMPLETE
android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED
android.intent.action.DREAMING_STARTED
android.intent.action.DREAMING_STOPPED
android.intent.action.EXTERNAL_APPLICATIONS_AVAILABLE
android.intent.action.EXTERNAL_APPLICATIONS_UNAVAILABLE
android.intent.action.FETCH_VOICEMAIL
android.intent.action.GTALK_CONNECTED
android.intent.action.GTALK_DISCONNECTED
android.intent.action.HEADSET_PLUG
android.intent.action.HEADSET_PLUG
android.intent.action.INPUT_METHOD_CHANGED
android.intent.action.LOCALE_CHANGED
android.intent.action.MANAGE_PACKAGE_STORAGE
android.intent.action.MEDIA_BAD_REMOVAL
android.intent.action.MEDIA_BUTTON
android.intent.action.MEDIA_CHECKING
android.intent.action.MEDIA_EJECT
android.intent.action.MEDIA_MOUNTED
android.intent.action.MEDIA_NOFS
android.intent.action.MEDIA_REMOVED
android.intent.action.MEDIA_SCANNER_FINISHED
android.intent.action.MEDIA_SCANNER_SCAN_FILE
android.intent.action.MEDIA_SCANNER_STARTED
android.intent.action.MEDIA_SHARED
android.intent.action.MEDIA_UNMOUNTABLE
android.intent.action.MEDIA_UNMOUNTED
android.intent.action.MY_PACKAGE_REPLACED
android.intent.action.NEW_OUTGOING_CALL
android.intent.action.NEW_VOICEMAIL
android.intent.action.PACKAGE_ADDED
android.intent.action.PACKAGE_CHANGED
android.intent.action.PACKAGE_DATA_CLEARED
android.intent.action.PACKAGE_FIRST_LAUNCH
android.intent.action.PACKAGE_FULLY_REMOVED
android.intent.action.PACKAGE_INSTALL
android.intent.action.PACKAGE_NEEDS_VERIFICATION
android.intent.action.PACKAGE_REMOVED
android.intent.action.PACKAGE_REPLACED
android.intent.action.PACKAGE_RESTARTED
android.intent.action.PACKAGE_VERIFIED
android.intent.action.PHONE_STATE
android.intent.action.PROVIDER_CHANGED
android.intent.action.PROXY_CHANGE
android.intent.action.REBOOT
android.intent.action.SCREEN_OFF
android.intent.action.SCREEN_ON
android.intent.action.TIMEZONE_CHANGED
android.intent.action.TIME_SET
android.intent.action.TIME_TICK
android.intent.action.UID_REMOVED
android.intent.action.USER_PRESENT
android.intent.action.WALLPAPER_CHANGED
android.media.ACTION_SCO_AUDIO_STATE_UPDATED
android.media.AUDIO_BECOMING_NOISY
android.media.RINGER_MODE_CHANGED
android.media.SCO_AUDIO_STATE_CHANGED
android.media.VIBRATE_SETTING_CHANGED
android.media.action.CLOSE_AUDIO_EFFECT_CONTROL_SESSION
android.media.action.HDMI_AUDIO_PLUG
android.media.action.OPEN_AUDIO_EFFECT_CONTROL_SESSION
android.net.conn.BACKGROUND_DATA_SETTING_CHANGED
android.net.conn.CONNECTIVITY_CHANGE
android.net.nsd.STATE_CHANGED
android.net.scoring.SCORER_CHANGED
android.net.scoring.SCORE_NETWORKS
android.net.wifi.NETWORK_IDS_CHANGED
android.net.wifi.RSSI_CHANGED
android.net.wifi.SCAN_RESULTS
android.net.wifi.STATE_CHANGE
android.net.wifi.WIFI_STATE_CHANGED
android.net.wifi.p2p.CONNECTION_STATE_CHANGE
android.net.wifi.p2p.DISCOVERY_STATE_CHANGE
android.net.wifi.p2p.PEERS_CHANGED
android.net.wifi.p2p.STATE_CHANGED
android.net.wifi.p2p.THIS_DEVICE_CHANGED
android.net.wifi.supplicant.CONNECTION_CHANGE
android.net.wifi.supplicant.STATE_CHANGE
android.nfc.action.ADAPTER_STATE_CHANGED
android.os.action.DEVICE_IDLE_MODE_CHANGED
android.os.action.POWER_SAVE_MODE_CHANGED
android.provider.Telephony.SIM_FULL
android.provider.Telephony.SMS_CB_RECEIVED
android.provider.Telephony.SMS_DELIVER
android.provider.Telephony.SMS_EMERGENCY_CB_RECEIVED
android.provider.Telephony.SMS_RECEIVED
android.provider.Telephony.SMS_REJECTED
android.provider.Telephony.SMS_SERVICE_CATEGORY_PROGRAM_DATA_RECEIVED
android.provider.Telephony.WAP_PUSH_DELIVER
android.provider.Telephony.WAP_PUSH_RECEIVED
android.speech.tts.TTS_QUEUE_PROCESSING_COMPLETED
android.speech.tts.engine.TTS_DATA_INSTALLED


text:
Q: Problem of understanding instructions on practice sheet Can someone help me understand the scalar product of problem 23 in the attached practice sheet? I should show that this defines a nondegenerated symmetric scalar product on the vector space of trivariate polynomials.
My problem is that I don't understand the argument of $P$. An example would be great!
Thank you.
The sheet is in german, but all you need to know is above :)
Practice Sheet

A: This is just a notation/formal calculation. Just plug in the differential operators into the polynomial $P$ and apply the resulting operator to $Q$ and evaluate at $(0,0,0)$.


text:
Q: While com JavaScript pegando imagens dentro de uma pasta Como fazer para pegar imagens dentro de uma pasta com laço de repetição em javascript e inserir juntamente com a estilização do Materialize Css
Observanndo que as imagens dentro da pasta já estão todas com numeração sequencial.

01 Apartamentos Cabine Elétrica

A: Em vez de usar while, você poderia usar for e inserir o HTML na div. No for abaixo, o valor 10 é a quantidade de imagens que você deseja inserir:

document.addEventListener("DOMContentLoaded", function(){ // aguarda o DOM ser carregado
   // seleciona a div com a classe .row
   var container = document.querySelector("#abate > .row");
   var html = '';
   for(var x=1; x <= 10; x++){
      html += `

`;
   }

   container.innerHTML = html;

});

01 Apartamentos Cabine Elétrica


text:
Q: Concatenate a Spark structured streaming dataframe with a static dataframe I've got a Spark structured streaming job that reads CSV files, runs some calculations and outputs a text file for use in a model downstream. The output is a single column made up from the original columns that have been concatenated (separated by a space). E.g:
1556951121 7.19 26.6 36.144 14.7402 1
1556951122 7.59 27.1 37.697 14.7402 1
1556951123 8.01 27.7 39.328 14.7403 0
etc.

The downstream model requires some extra header information at the top of the file. It needs the filename on the first line and the number of columns on the second line. E.g:
filename
6
1556951121 7.19 26.6 36.144 14.7402 1
1556951122 7.59 27.1 37.697 14.7402 1
1556951123 8.01 27.7 39.328 14.7403 0
etc.

Can this be done in Spark? I created the header information as a separate dataframe:
header = [('filename',), ('6',)]
rdd = sparkSession.sparkContext.parallelize(header)
headerDF = sparkSession.createDataFrame(rdd, schema=StructType([StructField('values', StringType(), False)]))

I've tried a union but a union between a streaming and static dataframe is not supported.
I also looked at join but I don't think that is going to give me what I need as this will add an extra column.
For info, this is the output query:
df.coalesce(1)\
  .writeStream\
  .outputMode("append")\
  .format("text")\
  .option("checkpointLocation", checkpoint_path)\
  .option("path", path)\
  .start()\
  .awaitTermination()

and this is the input source:
df = sparkSession.readStream\
                 .option("header", "true")\
                 .option("maxFilesPerTrigger", 1)\
                 .schema(schema)\
                 .csv(input_path)

The input CSVs just consist of a timestamp and some sensor values. E.g:
Timestamp,Sensor1,Sensor2,Sensor3,Sensor4,Sensor5
1556951121,7.19,26.6,36.144,14.7402,True
1556951122,7.59,27.1,37.697,14.7402,True
1556951123,8.01,27.7,39.328,14.7403,False

A: In the end I used the foreachBatch sink as this gives you a static dataframe which you can then join/union to other dataframes:
df.coalesce(1).writeStream.foreachBatch(foreach_batch_function).start()

And the foreach batch function:
def foreach_batch_function(df, epoch_id):
     complete_df = headerDF.union(df)
     complete_df.coalesce(1).write.text(os.path.join(output_path, str(epoch_id)))


text:
Q: Problema menu colapsable bootstrap Estoy creando un link colapsable en mi barra de navegación para que el usuario acceda a sus preferencias, cerrar sesión etc.
El ejemplo lo tomé de aquí, con algunas modificaciones.
Intenté que el menú se muestre flotante a la izquierda de la pantalla y por más opciones de Bootstrap que coloque no sucede.
Debería verse así:

Pero en mi caso se ve así:

Honestamente creo que se ve mejor hacia abajo, pero el verdadero problema es que al hacer clic me crea un scroll en el ancho de la pantalla.

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

                    Luna medina

                  Preferencias
                  Cerrar sesión


text:
Q: Verify password complexity against Active Directory in C# I am writing an installer that installs SQL, beforehand a user is prompted to enter the SA username/password which will be created for them.  When SQL installs it verifies this password against the Active Directory policy and will fail if it doesnt match.
What I want to do is verify the password input by the user is valid before proceeding to install SQL.
How can I validate a password is correct against Active Directory rules?
Note I do not have a login to verify as per this answer, but simply a password to verify.
I am currently trying this, but writing "password" which I know is not allowed doesnt throw an exception
try
{
    System.DirectoryServices.DirectoryEntry localMachine = new System.DirectoryServices.DirectoryEntry("WinNT://" + Environment.MachineName);
    ListPasswordPolicyInfo(Environment.MachineName);
    System.DirectoryServices.DirectoryEntry newUser = localMachine.Children.Add("localuser", "user");
    newUser.Invoke("SetPassword", new object[] { "3l!teP@$$w0RDz" });
    newUser.Invoke("SetPassword", new object[] { "password" });
    //newUser.CommitChanges();
    //Console.WriteLine(newUser.Guid.ToString());
    localMachine.Close();
    newUser.Close();
}
catch(Exception e)
{
    Console.WriteLine(e.Message);
}

A: After a lot of pain I have found the C# solution to this using NetValidatePasswordPolicy.  Use the supporting structs off of PInvoke and the following code
public static NET_API_STATUS ValidatePassword(string password)
{
    var outputArgs = new NET_VALIDATE_OUTPUT_ARG();
    var inputArgs = new NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG();

    IntPtr inputPointer = IntPtr.Zero;
    IntPtr outputPointer = IntPtr.Zero;

    try
    {
        inputArgs.PasswordMatched = true;
        inputArgs.ClearPassword = Marshal.StringToBSTR(password);

        // If using a secure string
        ////inputArgs.ClearPassword = Marshal.SecureStringToBSTR(secureStringPassword);

        inputPointer = Marshal.AllocHGlobal(Marshal.SizeOf(inputArgs));
        Marshal.StructureToPtr(inputArgs, inputPointer, false);

        NET_API_STATUS status = NetValidatePasswordPolicy(System.Environment.MachineName, IntPtr.Zero, NET_VALIDATE_PASSWORD_TYPE.NetValidatePasswordChange, inputPointer, ref outputPointer);

        if (status == NET_API_STATUS.NERR_Success)
        {
            outputArgs = (NET_VALIDATE_OUTPUT_ARG)Marshal.PtrToStructure(outputPointer, typeof(NET_VALIDATE_OUTPUT_ARG));

            if (outputArgs.ValidationStatus == NET_API_STATUS.NERR_Success)
            {
                // Ok
            }

            return outputArgs.ValidationStatus;
        }
        else
        {
            return status;
        }
    }
    finally
    {
        if (outputPointer != IntPtr.Zero)
        {
            NetValidatePasswordPolicyFree(ref outputPointer);
        }

        if (inputArgs.ClearPassword != IntPtr.Zero)
        {
            Marshal.ZeroFreeBSTR(inputArgs.ClearPassword);
        }

        if (inputPointer != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(inputPointer);
        }
    }
}

A: try{
var userName = "bob";
    using (var pc = new PrincipalContext(ContextType.Domain)
    {
          var user = UserPrincipal.FindByIdentity(pc, userName);
          user.ChangePassword(oldpassword, newpassword); //Checks password policy
          //or
          user.SetPassword(newpassword); //Not positive checks password policy but I believe it 2.
    }
}
catch(PasswordException ex)
{
//do something with ex
}


text:
Q: Java Swing or SWT: easy way to build a desktop UI "wizard" -- suggestions? I'm an experienced Java programmer.  Used to do a lot of Swing by hand with Eclipse, but been mostly into web stuff for the past couple years.
I have to build a desktop UI, a kind of wizard-y thing, choosing items from lists, typing in fields, next...next...next... that sort of thing.
Before I jump into building it by hand with Swing, I'm wondering if there's been any major developments in the Java world with regards to desktop UIs.  Is there something I should look at, maybe a drag-and-drop UI builder, or some kind of framework, that will make it easier?
Any advice is useful, thanks!
Rob

A: See WindowBuilder. It can build Swing or SWT GUI. WindowBuilder used to be a very profitable product of a company called Instantiations. Then Google bought the company and donated WindowBuilder to OSS community. It is now an eclipse.org project with many of the original developers contributing to it.

A: NetBeans has a really powerful and easy-to-use Swing GUI builder that comes with it.

A: I would suggest sticking to hand coding with Swing.  The NetBeans editor has improved in the last couple of years, but still generates code that is not easily read by humans or easily modified by hand.
There are some third party libraries that do have some wizard like components that you might be able to make use of.

A: Take a look at Windowbuilder Pro. You can create GUIs in both Swing and SWT. And GWT, if you want to.

A: Another option is to use the IWizard framework in Eclipse RCP, which works pretty well and is built for exactly what you're trying to do.  I'd recommend coding it by hand if you choose this option, as window builder probably won't make your life easier in the long run.  Of course, if you're a lot more comfortable with Swing already, you could just stick to that.


text:
Q: Converting a long number string into an array So, let's say I have a string composed a very large number, say "123456789101112131415" for example. How do I convert that string into an array with those values in it?

A: Quite Easily Done:
"123456789101112131415".split("")


text: Q: App works in debug mode, but crashes when downloading from Play Store So my app works perfectly in debug mode, however, when I download it from the play store, it crashes upon trying to open.  Can anyone help get a logical or stack trace so I can fix the issue?  Thanks!


text:
Q: .toggleClass not working inside function When I put $("header nav ul").toggleClass("open") outside of the on click function it works, but it doesn't when I put it inside. Why is that??
The alert method is running, so clicking the a tag works.

Blesto

Main Navigation

Our Story

Menu

Reservations

News

Reviews

$(document).ready(function(){
    $(".burger-nav").click(function(){
        alert("hi");
        $("header nav ul").toggleClass("open");
    });
});

A: You need to stop the default behavior of anchor element.
$(".burger-nav").click(function(event){
    event.preventDefault();
    alert("hi");
    $("header nav ul").toggleClass("open");
});

You are right about alert being run, but then the default behavior is run which is going to wherever href points to. In this case, the same page.


text:
Q: Android : How to get actual URL path for XML stored under res/xml? Hope the subject line makes it clear.
I want to get hold of the file path of the xml file which i store under the res/xml folder.
I'm aware of the InputStream approach by directly reading using the snippet.
... getResources().getXml(R.raw.testxml);
but my requirement is to just get the path of the stored file for the moment.
Any help appreciated
VATSAG

A: try as to get full path of file stored in res/raw folder
String fullpath = "android.resource://" +
                   YOUR_FULL_PACKAGE_NAME +
                   "/"+R.raw.testxml;


text:
Q: Calculate field based on a set value if optional parameter is not specified In my model, I have a Calculate Field which will populate the field with a certain integer (in this case, 0). I've added an optional integer model parameter Start ID, where the user can specify the integer if they want.

If Start ID is given a value by the user, this value must be used as the expression for Calculate Field, else Expression must be used. Since the tool can only take one expression as an input, would I have to create a copy of the Calculate Field with Start ID as the expression, and use Merge Branch with an if statement to test which branch must run i.e. the Start ID branch only runs if it has a value, else run the Expression branch?

A: I think this can be done much more simply using a model like this:

where the If/Then logic is part of the Calculate Field tool:

Think of the newValue = 123 + 456 part being your Expression.
In my test this will calculate a field to be 479 (= 123 + 456) if nothing is entered by the user for Start ID (which is an Optional parameter) or whatever integer value they enter otherwise.


text:
Q: Risk ratios in a Cox hazard model I'm reading a paper which gives "Risk ratios from Cox hazard models with time-varying covariates".
Time-varying covariates just means that, for example if $X_i$ is a covariate for person $i$ then it might be $0$ at some time and $1$ at another time.
I understand that we can specify this model by saying that the $i$-th person's hazard rate at time t, for the decrement we're interested in, is:
$$\lambda_i(t) = \lambda_0(t)e^{\beta X_i(t)}$$
(i.e. there is only one covariate in the model)
In this case, the hazard ratio is $e^{\beta X_i(t)}$ but it's not clear to me what the author means by giving a risk ratio.
Can anyone help?

A: A couple of weeks ago I had a similar problem. Why don't you take a look, it might help you Relative Risk with Log-rank test


text:
Q: Hot Reload doesn't reload libraries in VScode When I run the demo app through 'Run Without Debugging' (Ctrl+F5) and try to hot reload it, hot reload doesn't work. Every time I try to hot reload, I see this:
Reloaded 0 of 529 libraries in 244ms.
Reloaded 0 of 529 libraries in 117ms.
Reloaded 0 of 529 libraries in 123ms.

How can I fix it?

A: It turned out that Hot reload works perfectly if you use Ctrl+S instead of the lightning button. Try this.


text:
Q: How to update an array item in Firestore Per the new Firestore documentation, I see 2 new methods (arrayUnion, arrayRemove) for working with arrays nested within documents.  These methods allow you to add and remove an array item, but how would I update an existing element?

A: There is no update method because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, things are different than you might think.
Because we are creating apps that can be used in a multi-user environment, try to think what might happen if a user wants to edit a value at index 0, some other user wants to delete the value at index 0 and in the same time some other user might want to add another item at index 0. For sure, you'll end up having very different results and why not, get even an ArrayIndexOutOfBoundsException. So Firestore actions with arrays are a little bit different. So you cannot perform actions like, insert, update or delete at a specific index.
As Doug mentioned in his answer, if those two methods do not help you enough, you should get the entire document, get the array, modify it and add it back to the database.

A: If your array modification is not satisfied by arrayUnion or arrayRemove, you will have to read the document, modify the array values in memory, then update the array field with the new array in its entirety.


text:
Q: It's possible to communicate with google assistant using asp.net without dialogflow fulfillment? My intention is make custom layer between Google Assistant and Dilogflow, possibly using asp.net but not necessarily. It's possible?
I read all google assistant sdk documentation but I not foud nothing of useful.
I expect to be able to send message from my application to Google Assistant action and the other way around.


text:
Q: How to install python 2.7.12 on SLES 11? I have gone through this link https://stackoverflow.com/questions/10940296/installing-python-2-7-on-sles-11
and followed the instructions as suggested. I have created the bash file and executed that bash file somewhere between I got the error. So that I have executed the command step by step it was installed successfully. But while execute python in terminal it still showing python 2.6.9 version. Please let me know any other alternative solution to install python 2.7.12 in SUSE Machine.

A: Your /usr/bin/python might be a symlink and might be pointing to /usr/bin/python2.6 file. Change the symlink (/usr/bin/python) to point to your latest python in /usr/bin:
ln -sf /usr/bin/python2.7 /usr/bin/python


text:
Q: Use powershell remotely using version of hyperviser I'm facing an issue actually, i have to run a powershell script on all my VM but this one has to be runned with the minimum of version 3.
Our VM are using the version 2 ans the HyperV the version 4.
I attempt to use the remote access from powershell using "Enter-PSSession" but when i try to run the script this one is using the VM's powershell.
Is it possible to force the script to run on the VM using the powershell version of the HyperV ? Upgrading the version on the VMs is not feasible for the moment.
Thank you

A: No, this is not possible. PowerShell Remoting executes the code locally on the target computer.
If your code doesn't work and you can't upgrade WMF (PowerShell) on the target computers, then you would have to rewrite your code. Maybe you can use WMI, C#, legacy commandline utilities++ to achieve the same thing?


text: Q: Scaling transformation of nonzero initial condition I'm trying to find the self similar solution of the fractional heat equation ,$\frac{\partial^{\alpha} u}{\partial t^{\alpha}} = \frac{\partial^{2} u}{\partial x^{2}}+ k, 0<\alpha <1, t>0,$ with initial condition $u(x,0)=f(x)$. I'm using the following scaling transformation $t =\lambda \bar{t}, x = \lambda^{p} \bar{x}, u =\lambda^{q} \bar{u}$. Now i'm struggling to find the transformed initial condition. Can any one guide me to get through this problem?


text:
Q: Multithreaded Console Application array deadlock I have been struggling with a multi-threaded issue lately. I have a C# console application that trains neural networks. I spawn a thread via a task for each network I am going to train. I created a status update event for my trainer class that the parent class subscribe to. In that event handler, I update a status array with that model's new status. That array access is where I am seeing a 'deadlock' type of behavior. I understand that is not the canonical definition of a deadlock, but I can't think of a better term to describe the situation. Below is my code. I have condensed it as much as I am able to.
I appreciate any help. Thanks
Parent Code
public class TrainingEngine
{
    public enum UpdateStatus
    {
        Untrimmed = 0,
        Trimmed,
        Completed
    }

    private class TrainingStatus
    {
        public int Epoch { get; set; }
        public UpdateStatus UpdateStatus { get; set; }
    }

    private static readonly object printLock = new object();

    private ConcurrentDictionary<int, TrainingStatus> trainingStatus;

    ...other stuff...

    private void UpdateEpochCompleted(TrainingStatus newStatus)
    {
        trainingStatus[newStatus.ThreadId] = newStatus;
        PrintUpdate($"Model {newStatus.ThreadId + 1} completed epoch {newStatus.Epoch}.");
    }

    private void PrintUpdate(string trigger)
    {
        lock (printLock)
        {
            logger.Info(""); /***** DEADLOCKS HERE *****/

            logger.Info($"  {trigger}");
            foreach (TrainingStatus status in trainingStatus.Values)
            {
                if (status.Status == TrainingStatus.UpdateStatus.Completed)
                {
                    logger.Info(
                        $"    {status.Status.ToString()} model {status.ThreadId + 1}",
                        100);
                }
                else
                {
                    logger.Info(
                        $"    {status.Status.ToString()} model {status.ThreadId + 1} working on epoch {status.Epoch} / {epochCount}",
                        100);
                }
            }
        }
    }
}

Worker Definition
public class NetworkTrainer
{
    IProgress<TrainingStatus> UpdateCompleted { get; set; }

        private double TrainNetwork(ActivationNetwork network,
            int epochCount,
            int geneCount,
            double[][] inputData,
            double[][] outputData,
            int threadId,
            bool trimmedModel)
        {

            for (int idxEpoch = 0; idxEpoch < epochCount; ++idxEpoch)
            {
                error += teacher.RunEpoch(inputData,
                    outputData);

                UpdateCompleted?.Report(new TrainingStatus
                {
                    Epoch = idxEpoch,
                    Status =  (trimmedModel) ? TrainingStatus.UpdateStatus.Trimmed : TrainingStatus.UpdateStatus.Untrimmed,
                    ThreadId = threadId,
                });
            }

            return error;
        }
}

Deadlock screenshot

A: I found the issue. First, I would like to thank everyone who helped me, especially Panagiotis Kanavos and usr. Initially, I had a poorly written lock statement, which was vulnerable to reentrency. Looking at my code, I couldn't see how such a such a condition could occur. After all, each epoch of training would take approximately 30 minutes. After some investigation, I learned that when I click on a terminal window and leave a white square on the window (the marker), I have locked access the terminal. This meant my threads were no longer able to write to the terminal; I was causing the deadlock. Occasionally, I was doing other things on the laptop while it trained my models, and I would click on the terminal to see the current status.
tl;dr. If you click the terminal, press enter to release it back to the system.


text:
Q: Why won't the Python Tkinter Canvas Scroll? Why can't I get the python tkinter canvas to respond to the vertical and horizontal swiping/scrolling of Apple's Magic Mouse? The scrollbars for the canvas work properly (meaning the horizontal bar works when I swipe/scroll horizontally on the mouse but not when I swipe/scroll vertically, and the vertical scrollbar moves when I swipe/scroll vertically but doesn't react to any horizontal swiping/scrolling motion), but the canvas doesn't react to any swiping/scrolling of the mouse.
Here is my example/test code:
from tkinter import *
import tkinter.ttk as ttk
from PIL import Image, ImageTk
root = Tk()

h = Scrollbar(root, orient=HORIZONTAL)
v = Scrollbar(root, orient=VERTICAL)
canvas = Canvas(root, scrollregion=(0, 0, 1000, 1000), yscrollcommand=v.set, xscrollcommand=h.set)
h['command'] = canvas.xview
v['command'] = canvas.yview
theImage = ImageTk.PhotoImage(Image.open('example.png')) #Assume a very large image
canvas.create_image(0,0,image=theImage, anchor='nw')
canvas.grid(column=0, row=0, sticky=(N,W,E,S))
h.grid(column=0, row=1, sticky=(W,E))
v.grid(column=1, row=0, sticky=(N,S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.mainloop()

I'm a total novice when it comes to both Python and tkinter, but I feel like this should be really simple and obvious (or at least do-able). And yet I've looked all over and still can't find the answer (though I might be searching using the wrong jargon).
What does it take to make the canvas react to scrolling/swiping inputs from the Magic Mouse like the scrollbars do already?
Edit: I'm using Python 3.4, Tkinter 8.5.18, Mac OS X 10.9.5, and an Apple Magic Mouse

A: Assuming that the magic mouse's scroll and swipe inputs work like the scrolling regions on a standard trackpad, you need to bind the <MouseWheel> and <Shift-MouseWheel> events.
First the code, then some notes.
from tkinter import *
import tkinter.ttk as ttk
from PIL import Image, ImageTk

def on_vertical(event):
    canvas.yview_scroll(-1 * event.delta, 'units')

def on_horizontal(event):
    canvas.xview_scroll(-1 * event.delta, 'units')

root = Tk()
h = Scrollbar(root, orient=HORIZONTAL)
v = Scrollbar(root, orient=VERTICAL)
canvas = Canvas(root, scrollregion=(0, 0, 1000, 1000), yscrollcommand=v.set, xscrollcommand=h.set)
h['command'] = canvas.xview
v['command'] = canvas.yview
theImage = ImageTk.PhotoImage(Image.open('img'))
canvas.create_image(0,0,image=theImage, anchor='nw')
canvas.grid(column=0, row=0, sticky=(N,W,E,S))

canvas.bind_all('<MouseWheel>', on_vertical)
canvas.bind_all('<Shift-MouseWheel>', on_horizontal)

h.grid(column=0, row=1, sticky=(W,E))
v.grid(column=1, row=0, sticky=(N,S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.mainloop()

As you can see there are only 2 changes.

*

*There are two callback functions to handle the scroll events on_vertical and on_horizontal

*The canvas <MouseWheel> and <Shift-MouseWheel> events are bound to on_vertical and on_horizontal respectively.

A: Use ntk Canvas to create a scroll able Canvas, by default it works on mouse scroll, but if you create a ntk Scrollbar widget, and assign it to canvas, you are good to go.
ntk works on top of tkinter, to install it from pypi with pip
pip install ntk

use ntk widgets to get awesome design.
from ntk import Tk, Canvas, Scrollbar

def main():
    root = Tk()

canvas = Canvas(root)

    root.mainloop()

if __name__=='__main__':
    main()

this canvas is scroll able by mouse scroll, but if you want to set a bar with it, you can create a scroll bar widget and pass this canvas object as second param
scroll = Scrollbar(root, canvas)

you can change scroll able area from canvas by configure or pass it when canvas is creating
canvas = Canvas(root, scrollregion=[0,0,100,50]) # [x1, y1, x2, y2]

or configure it by
canvas.config(scrollregion=[0,0,100,50])

welcome to beautiful design in less code, happy codding.


text:
Q: Hammer.js (IE8)- Object doesn't support property or method 'addEventListener' I'm using hammer.js for a touch menu for a site, and getting:

"Object doesn't support property or method 'addEventListener'"
  hammer.js, line 247 character 13

with IE8.
The actual code from hammer.js that is not working:
/**
 * simple addEventListener
 * @param   {HTMLElement}   element
 * @param   {String}        type
 * @param   {Function}      handler
 */
bindDom: function(element, type, handler) {
    var types = type.split(' ');
    for(var t=0; t<types.length; t++) {
        element.addEventListener(types[t], handler, false);
    }
},

Any idea how I can fix this?
Jquery used to have a similar issue:
http://bugs.jquery.com/ticket/11127

A: Starting from here: addEventListener not working in IE8
You can fix the code function by checking the definition of addEventListener like :
bindDom: function (element, type, handler) {
    var types = type.split(' ');
    for (var t = 0; t < types.length; t++) {
        if (!element.addEventListener) {
            element.attachEvent(types[t], handler);
        } else {
            element.addEventListener(types[t], handler, false);
        }
    }
},

if it works we can eventually pull a request to the developers.
Docs: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener?redirectlocale=en-US&redirectslug=DOM%2FEventTarget.addEventListener

A: If you need support for IE8 or IE7 you should use the jquery version of Hammer plugin. You can download it here.

A: Try it.
https://github.com/egjs/hammerjs-compatible

<!--[if IE 8]>
<script type="text/javascript" src="../dist/hammerjs.compatible.js"></script> <- like this.
<![endif]-->
<script src="../bower_components/hammer.js/hammer.js"></script>


text:
Q: Locate multiple class pointers at a string Ok this is extremely hard to explain. I tried to write a 100 line explanation in here, after I saw I failed I tried to create an image to better explain it which also failed http://img208.imageshack.us/img208/7383/48821020.png
It seems impossible because the complexity it extremely high. In the most raw is, I need to assign Id's for each part of a string. Currently I can assign Id's for a string example:
He: hey
She: Hi
He: What's up
She: Not much, you?
He: I'm fine, i'm selling a <Scale Armor> wanna buy it?
She: Next time maybe.

I can return What's up by using the function CString szText = GetTextAtLine(3); because What's up is located on the third line of the chat. Each line has an Id, the Id is the line number. Each line also has a pointer to a class named CItemElem. CItemElem holds all the information about an item.
I Locate the pointer by using the following function CItemElem *pItem = GetItemAtLineId(5), it would return the a pointer stored at map<unsigned int,CItemElem*>mItemChat where unsigned int is the line indetifier. Everytime someone talks something in chat if an item has been input at the chat a new element is inserted into the STL map with it's line id.
CItemElem* CEditString::GetItemAtLineId( unsigned long uLine )
{

    for( map<unsigned int,CItemElem*>::iterator it = m_mItemChat.begin(); it != m_mItemChat.end(); ++it )
    {
        if( uLine == it->first )
            return( it->second );
    }

    return NULL;
}

So as you can see I can locate a CItemElem pointer by the line Id, but now my problem is I need to locate multiple items at the string because a max of 3 items can be input in a sentence at time:
He: Hey guys i'm selling <Scale Boots> <Wooden Sword> <Water Helmet> cool items!

Currently I can return only 1 item at a chat sentence at a time because I can locate the item by the line Id. I've been toasting my brain the past hours, please enlighten me how to be able to return more than one item at the same sentence Id.
Thanks a lot!

A: As the comments suggest, use a vector of CItemElem* as the  value in the map or, write another class that wraps it for more readability also considering the future need of adding any other type than CItemElem. Also if string position is a required key in finding the item, then a map can be used instead of avector. Set each string position that spans the item to the pointer to that particular item so it can be easily retrieved when you have the string position in which the mouse is over.
class CLineElem
{

public:
void AddItemElem( CItemElem* pElem_i, int nStrPos_i );
CItemElem* GetItemElemAt( int nStrPos_i );
void RemoveAllItemElems();

private:
    map<unsigned int, CItemElem*> m_Elems;
};

Then use CLineElem* in the map m_mItemChat instead of CItemElem*


text:
Q: Error in creating a custom run instances policy I am new to IAM in AWS. I have created a policy
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "TheseActionsDontSupportResourceLevelPermissions",
      "Effect": "Allow",
      "Action": "ec2:DescribeImages",
      "Resource": "*"
    },
    {
      "Sid": "TheseActionsSupportResourceLevelPermissions",
      "Effect": "Allow",
      "Action": "ec2:RunInstances",
      "Resource": [
         "arn:aws:ec2:us-east-1:109027:instance/*",
         "arn:aws:ec2:us-east-1:10927:image/*",
         "arn:aws:ec2:us-east-1:109027:security-group/Test_hin",
         "arn:aws:ec2:us-east-1:109027:subnet/subnet-b",
         "arn:aws:ec2:us-east-1:109527:key-pair/*",
         "arn:aws:ec2:us-east-1:10903527:network-interface/vpc-e4",
         "arn:aws:ec2:us-east-1:107:volume/*"
       ]
     }
   ]
}

whenever I am trying to launch an instance using console, It gives me an error that i am not authorized to perform this action.

Thanks

A: Try with the key pair and the network interface resources (Looks like you are trying to launch into a VPC). Also, allow the volume resources.
{
    "Version": "2012-10-17",
    "Statement": [
    {
       "Effect": "Allow",
       "Action": "ec2:RunInstances",
       "Resource": [
         "arn:aws:ec2:us-east-1:acct:instance/*",
         "arn:aws:ec2:us-east-1:acct:image/*",
         "arn:aws:ec2:us-east-1:acct:security-group/*",
         "arn:aws:ec2:us-east-1:acct:subnet/*",
         "arn:aws:ec2:us-east-1:acct:key-pair/*",
         "arn:aws:ec2:us-east-1:acct:network-interface/*",
         "arn:aws:ec2:us-east-1:acct:volume/*"
       ]
     }
   ]
}


text:
Q: Are 'role' attributes necessary in HTML5? In trying to keep up with HTML5, I've made sure to validate all of my markups by using the W3 validator tool. Recently, I've started to add the role attribute to elements. However, I've noticed the following warnings pop-up time and again:

The button role is unnecessary for element button.
The navigation role is unnecessary for element nav.

But on the same token, on the W3C website regarding ARIA in HTML, it states that the button role is applicable to the <button> element and that the navigation role is only applicable to the <nav> element.
This brings me to my question, are the role attributes necessary with the role out of HTML5? What would I have a scenario that I would need to use them?

A: The first rule of ARIA states:

If you can use a native HTML element [HTML51] or attribute with the
  semantics and behaviour you require already built in, instead of
  re-purposing an element and adding an ARIA role, state or property to
  make it accessible, then do so.

If you view the navigation role in WAI-ARIA, it states that HTML Nav is a related concept and that navigation=role is already the default role, so there is no need to set it manually yourself:

Allowed ARIA role attribute values:
      navigation role (default - do not set).

So the navigation role is applicable to the <nav>, but it's already set by default so you don't need to do it yourself.
In summary to your question, no, don't set roles if they are already implied within the semantics of HTML5. You can check out the website below which I think outlines some good points as to when you should/shouldn't use ARIA (it's not all about the role attribute, but it does cover that as well):
What is WAI-ARIA, what does it do for me, and what not?

A: The article may also be helpful On HTML belts and ARIA braces (The Default Implicit ARIA semantics they didn't want you to know about)


text:
Q: Nullpointer exception when loading texture in libgdx I get a nullpointer exception when loading splash.png. It works running on android, but throws an exception when running on the desktop even though the file is in android's asset folder and exists in the desktop's asset folder.
Any ideas what's happening? I did clean, restarted eclipse, re-imported the projects...

public class MainMenuScreen implements Screen {

@Override
public void show() {
    Texture background = new Texture(Gdx.files.internal("data/splash.png"));

    }

}

A: It should work like that, your assets folder is not correctly linked.
Taken from here:
https://github.com/libgdx/libgdx/wiki/Manual-project-setup#asset-folder-setup
"
-Click the Source tab, click Link Source, Browse, select the "assets" folder from your Android project and click OK.
-Specify "assets" for the folder name and click Finish then OK.
Note: If your desktop and Android projects are in the same parent folder, you can use "PARENT-1-PROJECT_LOC/gamename-android/assets" for the location of the linked assets folder, where "gamename-android" is the name of your Android project. This is better than a hard-coded path if you plan on sharing your projects with others."


text:
Q: Updating Enemy Health bar in unity 2d Why is this connecting all the health bars of my enemies together, even though their actual health is decreasing at its specified rate?
public class FillHealth : MonoBehaviour
{
    Image HealthBar;

    private NormalMonster normalMonster;
    // Start is called before the first frame update
    void Start()
    {
        HealthBar = GetComponent<Image>();
        normalMonster = GameObject.FindGameObjectWithTag("Normal Monster").GetComponent<NormalMonster>();
    }

    // Update is called once per frame
    void Update()
    {
        UpdateHealthLeft();
    }

    public void UpdateHealthLeft()
    {
        if (normalMonster.healthLeft > 0)
        {
            HealthBar.fillAmount = normalMonster.healthLeft / normalMonster.setHealth;
        }
    }
}

This is the script that is being referenced in FillHealth. As far as I understand it, since the variable isn't static, then the values should not be shared. It should find fill the health bar for each individual enemy.
public class NormalMonster : MonoBehaviour
{
    private float _normalSpeed = 2f;

    private float _BaseHealth = 20f;
    private float _HealthModifier;
    public float setHealth;
    public float healthLeft;

    // Start is called before the first frame update
    void Start()
    {
        UpdateHealth();
    }

    // Update is called once per frame
    void Update()
    {
        NormMonMov();
    }

    public void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Arrows")
        {
            healthLeft -= Arrows.Damage;
            Destroy(other.gameObject);

            if (healthLeft <= 0f)
            {
                Destroy(this.gameObject);
                EarnedGold.earnedGold += 7;
                Spawn_Manager.enemyCount--;
            }
        }
    }

    public void UpdateHealth()
    {
        if (StageMode.StageLvl > 5)
        {
            _HealthModifier = (StageMode.StageLvl * 0.01f) * _BaseHealth;
            setHealth = Mathf.Round(_BaseHealth + _HealthModifier);
        }
        else
        {
            setHealth = _BaseHealth;
        }
        healthLeft = setHealth;
    }

    public void NormMonMov()
    {
        transform.Translate(Vector3.left * _normalSpeed * Time.deltaTime);
        transform.position = new Vector3(Mathf.Clamp(transform.position.x, -7.0f, 10), transform.position.y, 0);
    }

}

Any help would be greatly appreciated for this guy who just start playing with unity this weekend.

A: Instead of getting the image, get the rect transform, like this
public RectTransform healthBar;

and change the length with:
healthBar.sizeDelta = new Vector2(normalMonster.healthLeft,healthBar.sizeDelta.y);

A: I believe the issue is with normalMonster = GameObject.FindGameObjectWithTag("Normal Monster").GetComponent<NormalMonster>();
If you have two Monsters
Both have two scripts attached, FillHealth and NormalMonster
Both the "FillHealth" scripts look for the FIRST gameobject in the scene that has a script with tag NormalMonster so both monsters are pointing to the exact same NormalMonster script (the first in the list)
Change "GameObject" capital G to "gameObject" lower case g
Still not the best way to code this, but that may work I think


text:
Q: Firebase ListView Search Function Implementation Android What I am trying to do here is that I have displayed a listview using populateView and I would like to filter it using a searchview but I am not sure on how to do it. Any help or suggestions would be great since I am new to firebase and android. I have also attached the code I used to display the listview.
MainMenu.java
public void makeItem ()
{
    lv = findViewById(R.id.listView);
    db = FirebaseDatabase.getInstance().getReferenceFromUrl("https://vsem-inventory.firebaseio.com/ItemList");
    FirebaseListOptions<ItemObject> options = new FirebaseListOptions.Builder<ItemObject>()
            .setLayout(R.layout.content_main_menu_list)
            .setQuery(db,ItemObject.class)
            .build();
    mAdapter = new FirebaseListAdapter<ItemObject>(options) {
        @Override
        protected void populateView(@NonNull View v, @NonNull ItemObject model, int position) {
            final TextView tvAmount = v.findViewById(R.id.amount);
            final TextView tvName = v.findViewById(R.id.name);
            final TextView tvSerial = v.findViewById(R.id.serialNo);
            final TextView tvSupplier = v.findViewById(R.id.supplierName);
            final ImageView more = v.findViewById(R.id.more);
            ImageView statusimg =  v.findViewById(R.id.status);
            Drawable paidIcon = v.getResources().getDrawable(R.drawable.succes);
            Drawable lateIcon = v.getResources().getDrawable(R.drawable.late);
            tvName.setText(model.getProductName());
            tvSerial.setText(model.getSerialNo());
            tvAmount.setText(model.getQuantity());
            tvSupplier.setText(model.getModel());
           final  String Remarks = model.getRemarks();
            final String cat = model.getCategory();
             if(model.getQuantity().equals("0"))
                statusimg.setImageDrawable(lateIcon);
            else
                statusimg.setImageDrawable(paidIcon);
            more.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v) {
                    String serialNo = tvSerial.getText().toString();
                    String itemName = tvName.getText().toString();
                    String quan = tvAmount.getText().toString();
                    String supplier = tvSupplier.getText().toString();
                    showMenu(itemName,more,serialNo,quan,supplier,cat,Remarks);
                }
            });
        }
    };
    lv.setAdapter(mAdapter);

}


text:
Q: I believe I am unable to configure MacBook Pro 2015 model to standby immediately, does anyone have the magic incantations (pmset)? I have an early 2015 model MacBook Pro and I notice that if I charge the battery to 100%, disconnect the power adapter and then close the lid, overnight it will use some of the battery, as though the unit is sleeping and not in standby.
I would very much like the MacBook to immediately dump memory to disk and turn itself completely off, whenever I close the lid.
I have tinkered with the pmset commands earlier, before Big Sur was released but I believe the addition of the "autopoweroff" setting has muddled the waters, and my tinkering + the changes introduced may have generated a configuration that isn't correct.
This is the output of pmset -g on my MacBook right now:
System-wide power settings:
Currently in use:
 lidwake              1
 autopoweroff         1
 standbydelayhigh     86400
 autopoweroffdelay    28800
 proximitywake        0
 standby              1
 standbydelaylow      10800
 ttyskeepawake        1
 highstandbythreshold 50
 powernap             0
 gpuswitch            2
 hibernatefile        /var/vm/sleepimage
 hibernatemode        25
 displaysleep         2
 sleep                10
 tcpkeepalive         1
 halfdim              1
 acwake               0
 disksleep            10

I have two questions:

*

*How can I verify that standby is properly configured?
I read on one page that if I close the lid, let it standby, and then open the lid and turn it on I should have a progress bar. If I do, it was in standby mode. This progress bar does not appear.

*If the above configuration is not correct for my goal, which is "dump memory to disk and turn off power immediately when I close the lid", does anyone know the correct pmset configuration I would need?
Note that this progress bar does not appear even overnight, which leads me to believe the MacBook isn't actually going to standby at all, instead just going to sleep mode and sitting there until battery drains out.

A: The man page for pmset provides all the relevant information. Notably:
hibernatemode supports values of 0, 3, or 25. Whether or not a hibernation image gets written is also dependent on
     the values of standby and autopoweroff

hibernatemode = 25 is only settable via pmset. The system will store a copy of memory to persistent storage (the
     disk), and will remove power to memory. The system will restore from disk image. If you want "hibernation" - slower
     sleeps, slower wakes, and better battery life, you should use this setting.

Also note from the man page that standbydelayhigh and standbydelaylow  specify the delay, in seconds, before writing the hibernation image to disk and powering off memory for Standby. Your values are 24 and 3 hours respectively.
autopoweroffdelay is also a large value, in seconds.
However, it's possible that an active process could be preventing sleep. For instance, here's the relevant output of pmset -g in my case:
 sleep                1 (sleep prevented by backupd-helper, sharingd, backupd, coreaudiod)

.
It's also possible that an old battery, reaching the end of its life, may not be reporting reliably, or not able to manage power optimally.


text:
Q: Accessing a decorated class I have inherited a project. I am not too good with decorators, but I am learning!
I have 2 classes, both of which are decorated. They are in separate files. I would like to call a class method from class2 in a method in class1. Something like this:
@class_decorator
class Class2(object):

    @classmethod
    def generator(cls):
    for s in my_stuff:
        yield s

@class_decorator
class Class1(object):

    def __init__(self):
        self.my_list = [1,2,3]

    def some_funct(self):
        for a,b in zip(self.my_list, Class2.generator()):
            print "{} {}".format(a,b)

I get an AttributeError, NoneType has no attribute generator
Is this because Class2 is decorated? Am I not able to call a classmethod on Class2?

A: It must be something the decorator does. Normally a decorator should not be getting in the way of this-- unless it's intentional. I extended your code with a trivial decorator (and a value for my_list), and it runs fine:
def class_decorator(cls):
    return cls

So track down class_decorator and see what it does.

A: @class_decorator
class Class2(object):

is (except for a technical caveat) exactly equivalent to
class Class2(object):
    ...
Class2 = class_decorator(Class2)

(The technical caveat is that if Class2 modifies class_decorator, then the two
could be different.)

The error message
AttributeError, NoneType has no attribute generator

suggests that when Python reaches Class2.generator(), Class2 is None, and therefore Python can not find its generator attribute.
Now you might wonder, how could Class2 be None? It could happen if class_decorator returns None, since that would cause Class2 to become equal to None:
Class2 = class_decorator(Class2)

So check that class_decorator returns a class:
def class_decorator(cls):
    # modify cls
    return cls      # The error could be due to this line being missing


text:
Q: Agent of passives introduced by "as to" Page 68 of Fowler's Dictionary of Modern English Usage reads

AS TO: used after certain preceding passive clauses, e.g. I am not much troubled as to its outward appearance—G. Gissing, 1903;
I am also simultaneously bemused…as to why people should sunbathe indoors.

Can the agents of passives introduced by "as to"?


text:
Q: List in class object not working, or more-accurately working wierdly I got really confused over functionality of lists working with classes.
class BasicClass:
    def __init__(self,money = [200]):
        self.money=money
    def add_money(self,value):
        self.money.append(value)
object=BasicClass()
object_2=BasicClass()
object.add_money(500)
object_2.add_money(300)
print(object.money)
print(object_2.money)

OUTPUT:
[200, 500, 300]
[200, 500, 300]

Version with class variable:
class BasicClass:
    money = [200]
    def __init__(self):
        pass
    def add_money(self,value):
        self.money.append(value)
object=BasicClass()
object_2=BasicClass()
object.add_money(500)
object_2.add_money(300)
print(object.money)
print(object_2.money)

OUTPUT:
[200, 500, 300]
[200, 500, 300]

Version with no default
class BasicClass:
    def __init__(self,money):
        self.money=money
    def add_money(self,value):
        self.money.append(value)
object=BasicClass([100])
object_2=BasicClass([100])
object.add_money(500)
object_2.add_money(300)
print(object.money)
print(object_2.money)

OUTPUT:
[100, 500]
[100, 300]

It looks like when I don't define my list through __init__ when I'm creating an object, python uses the same instance of list for both objects later. I'm just wondering what is goal of this functionality and how exactly it works.


text:
Q: Add some spheres in these particular positions?
I have a SCNBox below, I want to add some spheres in these position, how can I do that?

A: func addShape(pos: SCNVector3, to: SCNNode) {

    let radius = Float(0.05)

    let objectSph = SCNSphere(radius: CGFloat(radius))
    let object = SCNNode(geometry: objectSph)
    let position = SCNVector3Make(pos.x, pos.y, pos.z)

    object.position = position
    object.geometry?.firstMaterial?.diffuse.contents = UIColor.red
    to.addChildNode(object)
}

In playground:
import SceneKit
import PlaygroundSupport

func addShape(pos: SCNVector3, to: SCNNode) {

    let radius = Float(0.05)

    let objectSph = SCNSphere(radius: CGFloat(radius))
    let object = SCNNode(geometry: objectSph)
    let position = SCNVector3Make(pos.x, pos.y, pos.z)

    object.position = position
    object.geometry?.firstMaterial?.diffuse.contents = UIColor.red
    to.addChildNode(object)
}

let scene = SCNScene()
let view = SCNView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))

view.allowsCameraControl = true
view.autoenablesDefaultLighting = true
view.scene = scene

let box = SCNBox(width: 3.0, height: 3.0, length: 3.0, chamferRadius: 0)
let boxNode = SCNNode(geometry: box)

boxNode.geometry?.firstMaterial?.diffuse.contents = UIColor.white
scene.rootNode.addChildNode(boxNode)
scene.background.contents = UIColor.black

addShape(pos: SCNVector3Make(-1.5, 1.5, 1.5), to: boxNode)
addShape(pos: SCNVector3Make(-0.5, 1.5, 1.5), to: boxNode)
addShape(pos: SCNVector3Make(0.5, 1.5, 1.5), to: boxNode)
addShape(pos: SCNVector3Make(1.5, 1.5, 1.5), to: boxNode)

addShape(pos: SCNVector3Make(-1.5, 0.5, 1.5), to: boxNode)
addShape(pos: SCNVector3Make(-0.5, 0.5, 1.5), to: boxNode)
addShape(pos: SCNVector3Make(0.5, 0.5, 1.5), to: boxNode)
addShape(pos: SCNVector3Make(1.5, 0.5, 1.5), to: boxNode)

// and so on...

PlaygroundPage.current.liveView = view

If i got the idea...


text:
Q: Installation of imagemagick with BREW My problem is really simple :)
schovi@Saskia:~/tmp $ brew install imagemagick
Error: You must install
brew install git

schovi@Saskia:~/tmp $ brew install git
Warning: Formula already installed: git

schovi@Saskia:~/tmp $ brew install imagemagick
Error: You must install Git:
brew install git

Any idea? :)

A: Install git from http://git-scm.com/


text:
Q: visual studio express 2012 app.config remapping assembly I moved a project from MVC 3 to MVC 4 a while ago now.
when I build, I get the messages
1>  No way to resolve conflict between "System.Web.Mvc, Version=3.0.0.0 ..." and , Version=2.0.0.0
1>  Consider app.config remapping of assembly "System.Web.WebPages ..." from Version "1.0.0.0" to Version "2.0.0.0"  to solve conflict and get rid of warning.
1>  Consider app.config remapping of assembly "System.Web.WebPages.Razorfrom Version "1.0.0.0" [c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\System.Web.WebPages.Razor.dll] to Version "2.0.0.0" [C:\Users\OEM\documents\visual studio 2012\Projects\DabTrial\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.Razor.dll] to solve conflict and get rid of warning.

and so on.
When I look at references, they are all the later versions, and the web.config only refers to the later versions. When I search the entire solution directory by the public key token (in windows explorer) I find no XML type files with references to the earlier versions.
obviously the path to the files is different, but I cannot find where the compiler is being directed to the path for the earlier .dll file.
The project builds and runs fine, but I assume the compiler is suggesting these changes for a reason. Thanks for any help.

A: Your nuget dependencies are probably referencing the MVC3 version. You can try putting the following into your web config to force the MVC4 version:
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
</runtime>

You could also try running the following in the Package Manager Console
Update-Package -Reinstall

You have to have at least version 2.1 of nuget for this command but it will update your packages and retarget them if you have updated .NET. You can check this post for more information.
Retargeting solution from .Net 4.0 to 4.5 - how to retarget the NuGet packages?

A: I also had such problems. I did just two things:

*

*updated System.Web.Mvc and all dependencies to the last version (5.2.3)

*Rebuild all solution (I did using "Solution -> Clean Solution", then "Solution -> Build Solution")

A: Try setting AutoGenerateBindingRedirects to true in the project file.


text:
Q: Broadcom BCM4313 on 11.10
Possible Duplicate:
How to get Broadcom BCM 43XX Wireless card working

Okay so I've this afternoon updated the family laptop to 11.10. But our broadcom BCM4313 wireless card has stopped working. I tried googling and found someone saying you have to install a deb named 'b43-fwcutter_014-9_i386' and select the new driver but the driver did  not appear in my list.
The laptop is a compaq Cq56
***

lshw output http://pastebin.com/KNTj6fLt
rfkill 0: hp-wifi: Wireless LAN
    Soft blocked: no
    Hard blocked: yes

it's worth noting that I've pressed the wireless key that usually turns the colour of a little light on the key from orange to white. But it just stays orange now. Also after plugging in an ether cable and selecting it from network manager I still can't access the Internet on the laptop. Though that problem existed even on 11.04 when the wireless worked.

Okay I installed a driver that was older then the current one that was in use. After rebooting several times the wifi is now back on. When I installed it and rebooted once it didn't work. Wonder why it did after I did rebooted several times?
For a moment I thought to install Windows. Don't judge me. I was weak. I don't know what came over me.

A: Please have a look to my answer on the following question
How do I get the Broadcom BCM4313 wireless working on an Asus 1015PX?

A: PTbuntu answer does not do it for me, this one does http://drndivoje.wordpress.com/2011/07/31/how-to-enable-broadcom-wireless-bcm4311-card-on-linux-mint-11/


text:
Q: Laravel Blade Directive inside {{-blocks I have a custom blade directive for formatting DateTime-objects:
$blade->directive('datetime', function ($dateTime) {
    return "<?php echo ($dateTime)->format('Y-m-d\\TH:i:s') ?>";
});

This allows me to set a DateTime-object in an datetime-local input tag:
<input
    type="datetime-local"
    name="start_date"
    value="@datetime(now())"
>

However, I would like to also use the old-method to set the value from the previous request if it exists.
Only if old('start_date') returns null, I want to call @datetime.
The documentation about blade directives does not show any way to do this.
What I tried so far
Call the directive in PHP
The most obvious solution would be to just call @datetime inside the {{ block.
<input
    type="datetime-local"
    name="start_date"
    value="{{ old('start_date') ?? @datetime(now())"
>

This unfortunately does not work because the text inside the {{-block is PHP, and PHP does not know what to do with @datetime.
Blade::callCustomDirective
In the BladeCompiler-class, I found the method callCustomDirective.
Unfortunately though, the method is protected, so it leads to an error.
<input
    type="datetime-local"
    name="start_date"
    value="{{ old('start_date') ?? Blade::callCustomDirective('datetime', now()) }}"
>

Move the directive outside }}
I also tried this (without much hope):
<input
    type="datetime-local"
    name="start_date"
    value="{{ old('start_date') ?? }}  @datetime(now())"
>

As expected, this leads to a syntax error.

If anyone knows how to solve this issue, it would be greatly appreciated.


text:
Q: Mongoose findAndCount with where operator I had to rewrite some functionality which is using mongodb with mongoose. I have a function which doest findAndCount() from mongodb, but I'm not able to find id for mongoose. Right now I'm using this piece of code:
const [totalItems, items] = await Promise.all([
        model.estimatedDocumentCount(),
        model
            .find({
                ...where,
                ...(dateQuery && { createdAt: { ...dateQuery } }),
            })
            .skip(_limit * (_page - 1))
            .limit(_limit)
            .sort(sort)
            .populate(populate)
            .select(select),
    ]);

But I found out that the estimatedDocumentCount() is for the whole collection, lets say for example collection has 4 saved documents, but then comes some type of where filter and returned result from .find() is a single element, estimatedDocumentCount still returns 4 and i'm not able to calculate right pagination. To use .length it's not a option cuz there is skip and limit
My question is can I somehow get the count for all documents which are matching the filter? Thanks in advance!


text:
Q: Adding a member variable to my iterator class causes Aborted (core dumped) I have a templated iterator class:
template <class number_type, class label_type>
class DepthIterator {
public:
    // CONSTRUCTOR / COPY / ASSIGN / DECONSTRUCTOR
    DepthIterator() : ptr_(NULL) {}
    DepthIterator(Node<number_type, label_type>* n) : ptr_(n) {}
    DepthIterator(const DepthIterator& old) : ptr_(old.ptr_), visited(old.visited) {}
    ~DepthIterator() {}

    // OPERATORS
    DepthIterator& operator=(const DepthIterator& old) { ptr_ = old.ptr_; return *this; }
    const Point<number_type>& operator*() const { return ptr_->pt; }
    bool operator== (const DepthIterator& rgt) { return ptr_ == rgt.ptr_; }
    bool operator!= (const DepthIterator& rgt) { return ptr_ != rgt.ptr_; }

    // ++ DEPTH FIRST ITERATOR
    DepthIterator& operator++() {
        if (ptr_->children[0] == NULL && ptr_->children[1] == NULL) {
            // we're at a leaf, so go up one and back down and add to visited list
            visited.push_back(ptr_);
            ptr_ = ptr_->parent;
            return *this;
        }
        else {
            // do stuff
        }

private:
    Node<number_type, label_type>* ptr_;
    std::vector<Node<number_type,label_type>* > visited; // causes problem
};

When the second to last line std::vector<Node<number_type, label_type,>* > visited; is removed, my program compiles and runs fine (provided that the ++ operator is commented out). However, adding this line to private in this class causes my program to compile but crash halfway through running. Aborted (core dumped).
I did some testing and any std::vector variable I add to this class seems to cause it to crash regardless of what it is.
Why is a variable causing this? How do I go about fixing it?


text: Q: SDK for pdf sticky slip and text highlighter IOS I need to integrate the pdf reader in my application, In that I need to add sticky notes and highlighting the text I have gone through examples like fast pdf kit and iannotate pdf, But it is very expensive for me to go with it. Please suggest any SDK build with a free library and how can implement this?