text:
Q: Cannot load external API's in index.html I am trying to run the following code in Spotify apps but gapi.client is considered undefined. I do not have this problem when running in chrome. Does anyone know why or how this is happening.
<!doctype html>
<html>
  <head>
    <title>Vidify</title>
  </head>

  <body>
    <!--Add a button for the user to click to initiate auth sequence -->
    <button id="authorize-button" style="visibility: hidden">Authorize</button>
    <script type="text/javascript">

      var clientId = '591751286145-ktngvf2s76uiuuevan6mo1fft0kchl8l.apps.googleusercontent.com';

      var apiKey = 'AIzaSyB0mteDV5vDKFR-iAv4Fx4OC2gp1Yhqe9U';

      var scopes = 'https://www.googleapis.com/auth/youtube';

      function handleClientLoad() {
        console.log('API key provided - authorizing client...');
        // Step 2: Reference the API key
        gapi.client.setApiKey(apiKey);
        gapi.auth.init(checkAuth);
      }

      function checkAuth() {
        console.log('entered checkAuth - authorizing...');
        setTimeout(function() {
            console.log("requesting auth");
            gapi.auth.authorize({
                client_id: clientId,
                scope: scopes,
                response_type:'token',
                immediate: true
            }, handleAuthResult);
        }, 100);
      }

      function handleAuthResult(authResult) {
        console.log('received authResult');
        var authorizeButton = document.getElementById('authorize-button');
        if (authResult && !authResult.error) {
          console.log("auth. successful");
          authorizeButton.style.visibility = 'hidden';
          makeApiCall();
        } else {
          console.log('auth failed.');
          authorizeButton.style.visibility = '';
          authorizeButton.onclick = handleAuthClick;
        }
      }

      function handleAuthClick(event) {
        // Step 3: get authorization to use private data
        console.log('retry');
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
        return false;

      }

      // Load the API and make an API call.  Display the results on the screen.
        function makeApiCall() {
            console.log("loaded client");
            gapi.client.setApiKey(apiKey);
            // Step 4: Load the Google+ API
            gapi.client.load('youtube', 'v3', function() {
                console.log('youtube API loaded...');
                // Step 5: Assemble the API request
                var qVar = "Kanye West Amazing"
                // changed. added: type
                var request = gapi.client.youtube.search.list({
                    type: 'video',
                    part: 'id',
                    q: qVar
                });
                // Step 6: Execute the API request
                request.execute(function(resp) {

                    console.log(resp);
                    var vid = document.createElement('vid');
                    vid.value = resp.items[0].id.videoId;
                    console.log(vid.value);
                    var youtube_url = "http://www.youtube.com/watch?v=";
                    youtube_url += vid.value;
                    youtube_url += "&rel=0";
                    window.open(youtube_url);
                });
              });
          }
    </script>

    <script src="https://apis.google.com/js/client.js?onload=makeApiCall"></script>

  </body>
</html>

Do you think this has something to do with loading external API's or is it just that google API's are just special :)


text:
Q: Calling / faking a "Workbook_Open" event in VBA in Excel? So I have a VBA project that it would be useful to be able to restart as though it had just been opened. However, I don't want to actually restart the workbook. I have tried to close then reopen the file to trigger the "Workbook_Open" event but Excel keeps randomly opening the project in a new instance.
So I'm wondering if it is possible for me to call/fake the Workbook_Open event?
Thanks.

A: You can just call the Workbook_Open event-handler directly.  It will not in any sense "re-open" the workbook, but as event-handlers are just subroutines, you can of course call them like any other subroutine.
However, this is somewhat "tricky" and ill-advised because later programmers may add things that should be done at  Workbook_Open but that have nothing to do with your specific need so, as @sous2817 noted in the comments, a better way to do this is to move the Workbook_Open code to its own subroutine and then have both your code and Workbook_Open call it there.

A: Even though the event is private, ThisWorkbook.Workbook_Open will run the Workbook_Open event.

A: I believe these event handlers, if declared public, are ordinary subs.  You should be able to call them from your main module with Worksheet("Name").Workbook_Open.  If that failed for some reason (I cannot fathom), just empty Workbook_Open into public sub myCoolBeans() and call myCoolBeans() from Workbook_Open and where-ever.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Send value from activity to its fragment i'm trying to send data from my activity class to its tab fragment, but in the fragment adapter it received no data and produced error nullPointerException.
here is my code
from activity
Intent receivedIntent = getIntent();
    String tenant = null;
    if ((bundle = receivedIntent.getExtras()) != null) {
        tenant = (String) bundle.get("tenant");
    }

    TabFragment tabFragment = new TabFragment();
    bundle.putString("tenant", tenant);
    tabFragment.setArguments(bundle);

to fragment
Bundle getTenant = this.getArguments();
    if(getTenant != null) {
        tenant = getTenant.getString("tenant");
        System.out.println("Tab fragment: " + tenant);
    }else {
        System.out.println("Tab fragment: null");
    }

pager adapter
case 0:
            TabFragment tabFragment = new TabFragment();
            tabFragment.setArguments(bundle);
            return tabFragment;

A: In your fragment do this
if(getArguments() != null) {
    tenant = getArguments().getString("tenant");
    System.out.println("Tab fragment: " + tenant);
}else {
    System.out.println("Tab fragment: null");
}

instead of
Bundle getTenant = this.getArguments();
if(getTenant != null) {
    tenant = getTenant.getString("tenant");
    System.out.println("Tab fragment: " + tenant);
}else {
    System.out.println("Tab fragment: null");
}

A: Use below code:
 Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");
    return inflater.inflate(R.layout.fragment, container, false);
}

Another way You are able to pass data using Interface like Below:
1 step: I created public interface in my Activity and setter for it:
    Private OnAboutDataReceivedListener mAboutDataListener;
      public interface OnAboutDataReceivedListener {
        void onDataReceived(YourModelClass model);
    }

     public void setAboutDataListener(OnAboutDataReceivedListener listener) {
        this.mAboutDataListener = listener;
      }

2 step: I implemented this interface in my Fragment and set listener:
public class YourActivity extends BaseFragment implements YourBaseActivity.OnAboutDataReceivedListener

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            mActivity = (YourActivity) getActivity();
            mActivity.setAboutDataListener(this);
        }

3 step: I overrided interface's method:
    @Override
    public void onDataReceived(YourClassModel model) {
    }


text:
Q: How does Gitlab's "pages" job work internally? I have a Gitlab project like this (.gitlab-ci.yml):
# Sub-jobs listed as comments
stages:
  - check-in-tests
      # shellcheck
      # pylint
      # unit-tests
  - several-other-things
      # foo
      # bar
      # baz
  - release
      # release

# Run some shell code static tests and generate logs/badges
shellcheck:
  stage: check-in-tests
  script:
    - bash run_shellcheck.sh
  artifacts:
    paths:
      - logs/shellcheck.log
      - logs/shellcheck.svg

# Run some python code static tests and generate logs/badges
pylint:
  stage: check-in-tests
  script:
    - bash run_pylint.sh
  artifacts:
    paths:
      - logs/pylint.log
      - logs/pylint.svg

# <snip>

On my project page I'd like to render the .svg files produced during check-in-tests as badges.
The Gitlab badges tool requires a URL to an image file.  It is incapable of loading images from URLs with query strings.  Unfortunately, the syntax for accessing specific job artifacts ends in a query string.  This effectively means that we can't link to job artifacts as badges.
The most popular workaround is to abuse Gitlab's pages feature to store artifacts as static content.  From there we can get clean URLs to our artifacts that don't contain query strings.
My confusion involves the underlying mechanism behind the "pages" job defined in .gitlab-ci.yml.  The official documentation here is very sparse.  There are a million examples for deploying an actual webpage with various frameworks, but I'm not interested in any of them since I'm just using my project's "page" for file hosting.
The assumption seems to be that I want to deploy my page at the end of the pipeline.  However, I want to upload the shellcheck and pylint artifacts near the beginning of the pipeline.  Furthermore, I want those artifacts to be uploaded even if the pipeline stages fail.
Syntactically the pages job looks identical to any other job.  There's nothing there to describe how it's magically picked up by Gitlab's internals.  This leaves me with the following questions:

*

*Can I change the stage from "deploy" to "check-in-tests", or is the deploy stage specifically part of the hidden magic that Gitlab looks for when parsing for a pages job?

*If I'm tied to the deploy stage, can I re-arrange the stages to make it come earlier in the pipeline without breaking the magic?

*Does the pages job deploy artifacts from the local machine (default behavior for a job), or are the listed paths coming from artifacts which have already been uploade to the Gitlab pipeline by earlier jobs?

*If the pages job is only looking for artifacts locally how can I ensure that it runs on the same machine as the earlier jobs so that it finds the artifacts which they produced?  Let's assume that the Gitlab executors all come from a pool with the same tag and aren't tagged individually.

*Is there any chance of getting the pages job to run within the same Docker container that originally produced the artifacts?

A: The magic around GitLab pages is in the name of the job. It has to be named "pages", and nothing else. It is possible to move the job to different stages. As soon as the job "pages" has finished successfully, there's a special type of job that is called "pages:deploy". This job is shown in the deploy stage even if you change the stage that the "pages" job is run in.
If you have the pages job in an early stage, jobs in the later stages can fail but the "pages:deploy" job will still run and update GitLab pages.
Other than that, the "pages" job is just like a normal job in GitLab. If you need artifacts from other jobs, you can get these by using artifacts and dependencies:
https://docs.gitlab.com/ee/ci/yaml/#dependencies
The "pages" job should create a folder named "public" and give that folder as an artifact.


text:
Q: prove inequlity about cardinality power sets I need to prove the following inequlity:$$ |P([0,1]) \backslash P((0,1))| > |P(N)| $$
Now I have the intuition that in the left side of the inequlity there is all the subsets of [0,1] that contain the elements 0 or 1 and that is in the same cardinality is P[0,1] witch is greater then the right hand side (as Cantor proved) but I dont know how to write it down.
Thank you

A: HINT: The map
$$\wp\big((0,1)\big)\to\wp\big([0,1]\big)\setminus\wp\big((0,1)\big):A\mapsto\{0\}\cup A$$
is an injection.


text:
Q: What's a paronym? I really want to know what a paronym is because we're supposed use them in class.

A: The answer is a click away at Answers.com

"Two words are paronyms when their phonemic representations are similar but not identical.
(Salvatore Attardo, Linguistic Theories of Humor. Walter de Gruyter, 1994)

You should read the whole entry.

A: A paronym word is a word that derives from another word, and that has a related meaning.
It is also used for words originated from a word in a different language.

*

*wisdom with wise

*angelic with angel

*carry with carrus


text:
Q: AngularJS - scenario.js code In the application building tutorial on angularjs.org, step-8, testing part, what does the following lines of code mean-
element.all(by.css('.phones li a')).first().click();
expect(browser.getLocationAbsUrl()).toBe('/phones/nexus-s');

Thanks in advance!
PS:
The exact URL is- https://docs.angularjs.org/tutorial/step_08 and the code file (scenarios.js) is-
    'use strict';

// Angular E2E Testing Guide:
// https://docs.angularjs.org/guide/e2e-testing

describe('PhoneCat Application', function() {

  describe('phoneList', function() {

    beforeEach(function() {
      browser.get('index.html');
    });

    it('should filter the phone list as a user types into the search box', function() {
      var phoneList = element.all(by.repeater('phone in $ctrl.phones'));
      var query = element(by.model('$ctrl.query'));

      expect(phoneList.count()).toBe(20);

      query.sendKeys('nexus');
      expect(phoneList.count()).toBe(1);

      query.clear();
      query.sendKeys('motorola');
      expect(phoneList.count()).toBe(8);
    });

    it('should be possible to control phone order via the drop-down menu', function() {
      var queryField = element(by.model('$ctrl.query'));
      var orderSelect = element(by.model('$ctrl.orderProp'));
      var nameOption = orderSelect.element(by.css('option[value="name"]'));
      var phoneNameColumn = element.all(by.repeater('phone in $ctrl.phones').column('phone.name'));

      function getNames() {
        return phoneNameColumn.map(function(elem) {
          return elem.getText();
        });
      }

      queryField.sendKeys('tablet');   // Let's narrow the dataset to make the assertions shorter

      expect(getNames()).toEqual([
        'Motorola XOOM\u2122 with Wi-Fi',
        'MOTOROLA XOOM\u2122'
      ]);

      nameOption.click();

      expect(getNames()).toEqual([
        'MOTOROLA XOOM\u2122',
        'Motorola XOOM\u2122 with Wi-Fi'
      ]);
    });

    it('should render phone specific links', function() {
      var query = element(by.model('$ctrl.query'));
      query.sendKeys('nexus');

      element.all(by.css('.phones li a')).first().click();
      expect(browser.getLocationAbsUrl()).toBe('/phones/nexus-s');
    });

  });

});

A: It is testing of the routing to /phones/nexus-s.
It is written in Protractor.
The first line reads the DOM and finds all the .phones li a css rules. It then takes only the first one and calls click() on it.
element.all(by.css('.phones li a')).first().click();

The second line expects the output of the function browser.getLocationAbsUrl() to be the string /phone/nexus-s
expect(browser.getLocationAbsUrl()).toBe('/phones/nexus-s');

So all in all the test framework clicks a button and expects it to be routed to a new page.


text:
Q: Sorting results returned by Yarn's REST API I wanted to get every application that was run on the ResourceManager. I am using the REST API that comes with Yarn, specifically
http://<rm http address:port>/ws/v1/cluster/apps

This API call returns the results that I am looking for. But I would like to sort it by start time in descending order. The result that I get is not sorted in any particular order (I think it is sorted lexicographically using the application id, but I am not sure). The documentation gives a list of parameters that the API accepts but I don't see any method to sort the results. If the REST API does not support sorting, then is there any other way to sort the results?
The documentation I am following is this
https://hadoop.apache.org/docs/r2.7.0/hadoop-yarn/hadoop-yarn-site/ResourceManagerRest.html

A: Assuming you get the response in json format, you can sort it using python!
http://<rm http address:port>/ws/v1/cluster/apps |  python -c "import json,sys;from pprint import pprint; pprint(sorted(json.load(sys.stdin)['apps']['app'], key=lambda k: k['startedTime'], reverse=True))"|grep id

A: If you are using command line, you can use jq:
curl 'http://<rm http address:port>/ws/v1/cluster/apps' | jq '.apps.app | sort_by(-.startedTime)'


text:
Q: Leave Command Discord JS Leave command not working on my Discord bot which is written in JS.
This is the snippet of code I'm using.
if(command == 'leave') {
        client.leaveVoiceChannel;
However the command which should make the bot leave the voice channel does not seem to work. Here is how I'm using the code.

const Eris = require('eris');
const client = new Eris(require('./config.json').token, { maxShards: 1 });
fs = require('fs')
var stations = fs.readFileSync("./stations.txt", {"encoding": "utf-8"}).toString()
client.connect();
client.on('ready', () => {
 console.log('Ready to go!')
})
client.on('messageCreate', message => {
 if(message.author.bot) return;
 if(message.content.startsWith('!')) {
  let command = message.content.substring(1).split(" ")[0];
  let args = message.content.substring(2 + command.length);

        if(command == 'leave') {
        client.leaveVoiceChannel;
        } else if(command == 'streams') {
   message.channel.createMessage(stations);
  } else if(command == 'radio') {
   if(args == '') return message.channel.createMessage(`:exclamation: Please specify the radio stream example: **!radio <stream> or use command **!streams** to see list.`);
   if(require('./stations.json')[args]) {
    if(!message.member.voiceState.channelID) return message.channel.createMessage(`:exclamation: You need to be in a voice channel to play that stream.`);
    client.joinVoiceChannel(message.member.voiceState.channelID).then(vc => {
     if(vc.playing) vc.stopPlaying();
     message.channel.createMessage(`:radio: You are listening to Streaming station **${args}**. To change the stream use **!radio <stream>**`);
     vc.play(require('./stations.json')[args]);
    })
   } else {
    return message.channel.createMessage(`:frowning2: I cannot find a radio stream with that name. Make sure it has capitals and the correct spelling. Type **!streams** to see stream list.`);
   }
  }
 }
})

I'm not sure where I'm going wrong here.

A:

 if(command == 'stopstream') {
        client.leaveVoiceChannel(message.member.voiceState.channelID);
        message.channel.createMessage(`Thanks for tuning in!`); }


text:
Q: Does mark.js work in a Greasemonkey/Tampermonkey user script? I have this in the Tampermonkey script header section:
// @require      https://raw.githubusercontent.com/julmot/mark.js/master/dist/mark.js

My marking instance:
   for (var i=0; i<slotValuesRows.length; i++) {
     let targetToMark = new Mark(slotValuesRows[i]);
     targetToMark.mark(["e"],
     {"element": "span",
      "className": "highlight",
      "accuracy": "exactly"});
   }

The "e" do not get highlighted and the tab freezes on page load.
I am a beginner, but am suspecting mark.js just does not work with userscripts.
Is that assumption correct?

A: With the help of the documentation here > 4.2 and @wOxxOm input above, I was able to fix my loop and highlight all "[" in the target elements. Example:
for (var i=0; i<slotValuesRows.length; i++) {
  let targetToMark = new Mark(slotValuesRows[i]);
  targetToMark.mark("[");
}

Summarizing and answering question: Turns out you can add
// @require      https://raw.githubusercontent.com/julmot/mark.js/master/dist/mark.js

to your Greasemonkey/Tampermonkey script and use mark.js.
Hope this helps others.


text:
Q: determine file simularity between a few sets of 25k files each The git-scm lets you determine renames on the fly of the files stored in the same repository (e.g., git diff --find-renames).
What if I have about a dozen sets of files (e.g., about 10 sets in total (which may be independent branches of some somewhat-related software, e.g., *BSDs)), with about 25k files in each set.  (Each set may be updated daily, and represents a checkout with no history.)
Given a file from one set, I'd like to know what is the likely ancestor or descendant file (or files) in another set.  (Note that git itself is thus not involved at all, other than to illustrate the concept.)

A: Leveraging git might actually make sense here.  For example, commit each file set as a separate branch of a repository.  Then, you can do something like:
git diff -C --diff-filter=RC --name-status proj2..proj1

Which will produce output like:
R075       file2        file1

If file2 in proj2 is 75% similar to file1 in proj1.


text:
Q: How do I insert a blank row before specific cell values in Python? I am using the library Openpyxl
I have 15 functions that look identical to the one below just with different strings. I've tried combining them into a single function but this just makes the entire sheet blank rows. The only way I have found so far is to have an individual function for each of these with a break in it.
Is this the only way or is there a simpler, more efficient way to doing this?
import openpyxl

pws = openpyxl.load_workbook(filepath.xlsx)
pws_sheet = pws['Sheet']

def ans_call_by_agent():
    flag=False
    for row in pws_sheet.iter_rows():
        for cell in row:
            if cell.value == 'Ans. Call Distribution by Agent':
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet('Ans. Call by Agent')
                flag=True
        if flag:break
        else:
            continue
def all_calls_by_hour():
    flag=False
    for row in pws_sheet.iter_rows():
        for cell in row:
            if cell.value == 'All Call Distribution by Hour':
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet('All Calls by Hour')
                flag=True
        if flag:break
        else:
            continue
#call blank row functions
ins_agent_availability_detail()
ins_agent_missed_calls()
ins_all_calls_by_day()
ins_all_calls_by_day_of_week()
ins_all_calls_by_hour()
ins_all_calls_by_queue()
ins_all_service_level()
ins_ans_calls_agent()
ins_ans_calls_by_queue()
ins_ans_call_detail()
ins_ans_service_level()
ins_call_disconnection_cause()
ins_unans_calls_by_queue()
ins_unans_call_detail()
ins_unans_service_level()

The single function attempt is as follows, which only adds a single blank row at the top of the sheet and then stops.
def ans_calls_by_agent():
    #flag=False
    for row in pws_sheet.iter_rows():
        for cell in row:
            if cell.value == 'Ans. Call Distribution by Agent':
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet('Ans. Call by Agent')
                pws_sheet.delete_rows(cell.row, amount=1)
            elif cell.value == 'All Call Distribution by Hour':
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet('All Calls by Hour')
                pws_sheet.delete_rows(cell.row, amount=1)
            #flag=True
        #if flag:break
        else:
            continue

If I comment out the flag lines and add pws_sheet.delete_rows(cell.row,amount=1) then it will continue on but only when the cell.value is deleted and I'd rather that not be the solution.

A: Does;
def ans_calls_by_agent(compare_val, create_name):
    for row in pws_sheet.iter_rows():
        for cell in row:
            if cell.value == compare_val:
                pws_sheet.insert_rows(cell.row, amount=1)
                pws.create_sheet(create_name)
                pws_sheet.delete_rows(cell.row, amount=1)
                break

Not work?
The logic with flag is redundant. In your second example you have also put the flag=True part outside of the if statement, and so it will always be set to True, which you likely do not want.


text:
Q: Angular $http.post value from promises I would like to ask you how to send data through $http.post which I get from the function using $q.defer().
Here is the bit of code:
HTML
<input type='text' ng-model='name'/>
<input type='file' id='inputFile' />
<button ng-click='save'>Save</button>

JavaScript
file = document.getElementById('inputFile');

function imgToBase64(file_input) {
    var deferred = $q.defer();
    if (file_input.files && file_input.files[0]) {
        var fileReader = new FileReader();
        fileReader.onload = function (event) {
            result = event.target.result;
            deferred.resolve(result);
        };
        fileReader.readAsDataURL(file_input.files[0]);
    }
    return deferred.promise;
};

imgToBase64(file).then(function(result){
   $rootScope.result = result;
});

Post request
$http.post(apiURL, {
  name: $scope.name,
  image: $rootScope.result
}).success(function(data) {
      console.log(data);
})

The problem is, that when i hit save, then content of 'name' is sent, but the $rootScope.result is empty. Even though when I put $rootScope.result to console.log() I can see the result, but in the post it is empty?
What can be possibly doing wrong?
Thanks

A: I don't know if this is what you want:
$scope.save = function () {
    imgToBase64(file).then(function (result) {
        $rootScope.result = result;
        $http.post([...]);
    });
}


text:
Q: Drag and Drop with Angular JS and JQuery Couple of days ago I found this interesting post at http://www.smartjava.org/content/drag-and-drop-angularjs-using-jquery-ui  and applied it into my website. However when I progressively using it there is a bug I identified, basically you can not move an item directly from one div to another's bottom, it has to go through the parts above and progress to the bottom. Anyone can suggest where does it goes wrong? The example is at http://www.smartjava.org/examples/dnd/double.html
Troubling me for days already.....

A: I did this a bit differently. Instead of attaching a jquery ui element inside the directive's controller, I instead did it inside the directive's link function. I came up with my solution, based on a blog post by Ben Farrell.
Note, that this is a Rails app, and I am using the acts_as_list gem to calculate positioning.
 app.directive('sortable', function() {
  return {
    restrict: 'A',
    link: function(scope, elt, attrs) {

      // the card that will be moved
      scope.movedCard = {};
      return elt.sortable({
        connectWith: ".deck",
        revert: true,
        items: '.card',
        stop: function(evt, ui) {
          return scope.$apply(function() {

            // the deck the card is being moved to
            // deck-id is an element attribute I defined
            scope.movedCard.toDeck = parseInt(ui.item[0].parentElement.attributes['deck-id'].value);

            // the id of the card being moved
            // the card id is an attribute I definied
            scope.movedCard.id = parseInt(ui.item[0].attributes['card-id'].value);

            // edge case that handles a card being added to the end of the list
            if (ui.item[0].nextElementSibling !== null) {
              scope.movedCard.pos = parseInt(ui.item[0].nextElementSibling.attributes['card-pos'].value - 1);
            } else {
              // the card is being added to the very end of the list
              scope.movedCard.pos = parseInt(ui.item[0].previousElementSibling.attributes['card-pos'].value + 1);
            }

            // broadcast to child scopes the movedCard event
            return scope.$broadcast('movedCardEvent', scope.movedCard);
          });
        }
      });
    }
  };
});

Important points

*

*I utilize card attributes to store a card's id, deck, and position, in order to allow the jQuery sortable widget to grab onto.

*After the stop event is called, I immediately execute a scope.$apply function to get back into, what Misko Hevery call,s the angular execution context.

*I have a working example of this in action, up in a GitHub Repo of mine.


text:
Q: Video overlapping on Ipad I have added the video in background named "#supersize-background" with fixed position.
and header is absolute on the video.
While video is playing I am unable to click on header navigation. you can check on this link http://redzone.wordpressprojects.com/


text:
Q: Is it bad to have script tag inside div? What is bad about having a script tag inside div inside body?
I'm dynamically updating a div to reload a javascript code inside a div. Are there any issues to worry about ?

Edit
As @Bergi insisted on seeing the code. Here it is(see below). This div (along with other div(s) containing presentation HTML elements) are updated via AJAX. This script inside div contains maps to do processing of newly loaded HTML elements on page with raw data.

A: It is perfectly ok to place the  inside a DIV tag. Just check on w3c, it is valid HTML.

A: There is not much bad about it. Most widgets work this way. It is still valid HTML.
If you want to embed an AdSense unit in your page, you will need to do it. The same with Amazon widgets. That means majority of websites have a script tag inside div.

A: By SCRIPT inside
 still working.
But some annoy with your layout - shacking when scroll.
Best solution: put script inside  or  :D

A: It was always a good practice to try to put your  tags in . However, lately arguments appearead whether putting a  tags at the end of  tags, just before  made a page more faster.
I would recommend to put your  in  section of your HTML document, since it is more preffered. Additionally, putting a  inside a DIV is not a good practice.
You can post your example for a better answer abour organizing the structure of your document.
To sum up, there is no problem in what you are doing. But a more organized way is what I suggest.


text:
Q: Why do all the other faction leaders refuse to deal with me? For a number of turns now, all the other faction leaders have refused to consider any deals I might want to offer them. It doesn't matter whether I have a bad or good relationship with them, every single one is telling me they are not going to do deals with me at this time. They continue to offer me deals though.
Does anyone know why this is? What can I do to change this?

A: Oops, turns out this was a silly question. The reason I can't trade any more is because there are only a limited number of deals you can make, and I've hit my maximum.


text:
Q: Nokogiri scraper not sourcing properly I'm trying to build a scraper for a web page for data transfer, and hitting a sourcing issue.
require 'nokogiri'
require 'byebug'
require 'httparty'
require "open-uri"

def scraper
  url = "https://page text replaced for privacy"

  unparsed_page = HTTParty.get(url, verify: false)
  parsed_page = Nokogiri::HTML(unparsed_page, nil, Encoding::UTF_8.to_s)

  items = Array.new
  products = parsed_page.css("div.product-column > div.row")

  products.each do |product|
    product = {
      byebug
      summary: product.css("div.summary> a").value
      # image: product.css("div.photo>a.img-responsive").attribute("src").value,
      byebug

    }
    items << product
    puts "Added #{product[:summary]}"
    # puts "Added #{product[:image]}"
  end
end

scraper

When I run byebug on the first line of the .each loop  I get this error:
scraper.rb:18: syntax error, unexpected '\n', expecting =>
scraper.rb:21: syntax error, unexpected '}', expecting end
    }
scraper.rb:26: syntax error, unexpected end, expecting end-of-input

I think I'm struggling to grab it properly. Any ideas?


text:
Q: Retrieve an Akka actor or create it if it does not exist I am developing an application that creates some Akka actors to manage and process messages coming from a Kafka topic. Messages with the same key are processed by the same actor. I use the message key also to name the corresponding actor.
When a new message is read from the topic, I don't know if the actor with the id equal to the message key was already created by the actor system or not. Therefore, I try to resolve the actor using its name, and if it does not exist yet, I create it. I need to manage concurrency in regard to actor resolution. So it is possible that more than one client asks the actor system if an actor exists.
The code I am using right now is the following:
private CompletableFuture<ActorRef> getActor(String uuid) {
    return system.actorSelection(String.format("/user/%s", uuid))
                 .resolveOne(Duration.ofMillis(1000))
                 .toCompletableFuture()
                 .exceptionally(ex ->
                     system.actorOf(Props.create(MyActor.class, uuid), uuid))
                 .exceptionally(ex -> {
                     try {
                         return system.actorSelection(String.format("/user/%s",uuid)).resolveOne(Duration.ofMillis(1000)).toCompletableFuture().get();
                     } catch (InterruptedException | ExecutionException e) {
                         throw new RuntimeException(e);
                     }
                 });
}

The above code is not optimised, and the exception handling can be made better.
However, is there in Akka a more idiomatic way to resolve an actor, or to create it if it does not exist? Am I missing something?

A: Consider creating an actor that maintains as its state a map of message IDs to ActorRefs. This "receptionist" actor would handle all requests to obtain a message processing actor. When the receptionist receives a request for an actor (the request would include the message ID), it tries to look up an associated actor in its map: if such an actor is found, it returns the ActorRef to the sender; otherwise it creates a new processing actor, adds that actor to its map, and returns that actor reference to the sender.

A: I would consider using akka-cluster and akka-cluster-sharding. First, this gives you throughput, and as well, reliability. However, it will also make the system manage the creation of the 'entity' actors.
But you have to change the way you talk to those actors. You create a ShardRegion actor which handles all the messages:
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.cluster.sharding.ClusterSharding;
import akka.cluster.sharding.ClusterShardingSettings;
import akka.cluster.sharding.ShardRegion;
import akka.event.Logging;
import akka.event.LoggingAdapter;

public class MyEventReceiver extends AbstractActor {

    private final ActorRef shardRegion;

    public static Props props() {
        return Props.create(MyEventReceiver.class, MyEventReceiver::new);
    }

    static ShardRegion.MessageExtractor messageExtractor
      = new ShardRegion.HashCodeMessageExtractor(100) {
            // using the supplied hash code extractor to shard
            // the actors based on the hashcode of the entityid

        @Override
        public String entityId(Object message) {
            if (message instanceof EventInput) {
                return ((EventInput) message).uuid().toString();
            }
            return null;
        }

        @Override
        public Object entityMessage(Object message) {
            if (message instanceof EventInput) {
                return message;
            }
            return message; // I don't know why they do this it's in the sample
        }
    };

    public MyEventReceiver() {
        ActorSystem system = getContext().getSystem();
        ClusterShardingSettings settings =
           ClusterShardingSettings.create(system);
        // this is setup for the money shot
        shardRegion = ClusterSharding.get(system)
                .start("EventShardingSytem",
                        Props.create(EventActor.class),
                        settings,
                        messageExtractor);
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder().match(
                EventInput.class,
                e -> {
                    log.info("Got an event with UUID {} forwarding ... ",
                            e.uuid());
                    // the money shot
                    deviceRegion.tell(e, getSender());
                }
        ).build();
    }
}

So this Actor MyEventReceiver runs on all nodes of your cluster, and encapsulates the shardRegion Actor. You no longer message your EventActors directly, but, using the MyEventReceiver and deviceRegion Actors, you use the sharding system keep track of which node in the cluster the particular EventActor lives on. It will create one if none have been created before, or route it messages if it has. Every EventActor must have a unique id: which is extracted from the message (so a UUID is pretty good for that, but it could be some other id, like a customerID, or an orderID, or whatever, as long as its unique for the Actor instance you want to process it with).
(I'm omitting the EventActor code, it's otherwise a pretty normal Actor, depending what you are doing with it, the 'magic' is in the code above).
The sharding system automatically knows to create the EventActor and allocate it to a shard, based on the algorithm you've chosen (in this particular case, it's based on the hashCode of the unique ID, which is all I've ever used). Furthermore, you're guaranteed only one Actor for any given unique ID. The message is transparently routed to the correct Node and Shard wherever it is; from whichever Node and Shard it's being sent.
There's more info and sample code in the Akka site & documentation.
This is a pretty rad way to make sure that the same Entity/Actor always processes messages meant for it. The cluster and sharding takes automatic care of distributing the Actors properly, and failover and the like (you would have to add akka-persistence to get passivation, rehydration, and failover if the Actor has a bunch of strict state associated with it (that must be restored)).

A: The answer by Jeffrey Chung is indeed of Akka way. The downside of such approach is its low performance. The most performant solution is to use Java's   ConcurrentHashMap.computeIfAbsent() method.


text:
Q: Add forms dynamically in admin pages? I'm developing a WP plugin and I need that each time the user press a button in the metaboxes field, the form appears bellow the first one, so the user can add as many as they need WITHOUT RELOAD THE PAGE. I've been trying a lot for at least 3-4 days with no success :(
My metabox is:

My code in metaboxes.php is the following:
<?php
if (!defined('ABSPATH')) exit;

function cotizador_agregar_metaboxes()
{
    add_meta_box('cotizador_meta_box', 'Características del Vehiculo', 'cotizador_metaboxes', 'vehiculos', 'normal', 'high', null);
}
add_action('add_meta_boxes', 'cotizador_agregar_metaboxes');

function cotizador_metaboxes($post)
{
    cotizador_bootstrap();
    wp_nonce_field(basename(__FILE__), 'cotizador_nonce');
    $post_id = $post->ID;
    $query_result = cotizador_query_select($post_id);

    // echo "
";
    //    var_dump(cotizador_add_model($post));
    // echo "
";
?>

Shortcode:

            [cotizador id="<?php echo $post_id ?>"]

            <input type="submit" name="true" id="btn_add_model" value="Agregar Modelo" onclick="add_model();" />

    <form>
        <?php
        cotizador_add_model($post);
        ?>
    </form>
<?php
}

function cotizador_guardar_metaboxes($post_id)
{
    global $wpdb;
    $table_name = 'wp_cotiza_vehicles_list';

    if (!isset($_POST['cotizador_nonce']) || !wp_verify_nonce($_POST['cotizador_nonce'], basename(__FILE__))) {
        return $post_id;
    }
    if (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }
    if (isset($_POST['car_model'])) {
        $car_model = sanitize_text_field($_POST['car_model']);
    }
    if (isset($_POST['car_price'])) {
        $car_price = sanitize_text_field($_POST['car_price']);
    }
    if (isset($_POST['car_brand'])) {
        $car_brand = sanitize_text_field($_POST['car_brand']);
    }
    if (isset($_POST['car_year'])) {
        $car_year = sanitize_text_field($_POST['car_year']);
    }
    if (isset($_POST['car_type'])) {
        $car_type = sanitize_text_field($_POST['car_type']);
    }
    if (isset($_POST['car_basefee'])) {
        $car_basefee = sanitize_text_field($_POST['car_basefee']);
    }
    if (isset($_POST['car_basemodel'])) {
        $car_basemodel = sanitize_text_field($_POST['car_basemodel']);
    }
    if (isset($_POST['car_rcusa'])) {
        $car_rcusa = sanitize_text_field($_POST['car_rcusa']);
    }
    if (isset($_POST['car_bono'])) {
        $car_bono = 1;
    } else {
        $car_bono = 0;
    }

    /* sending data to custom table */
    if (cotizador_query_select($post_id) == null) {
        $wpdb->insert($table_name, array(
            'post_id' => $post_id,
            'car_model' => $car_model,
            'car_price' => $car_price,
            'car_brand' => $car_brand,
            'car_year' => $car_year,
            'car_type' => $car_type,
            'car_basefee' => $car_basefee,
            'car_basemodel' => $car_basemodel,
            'car_rcusa' => $car_rcusa,
            'car_bono' => $car_bono,
        ));
    } else {
        $wpdb->update($table_name, array(
            'car_model' => $car_model,
            'car_price' => $car_price,
            'car_brand' => $car_brand,
            'car_year' => $car_year,
            'car_type' => $car_type,
            'car_basefee' => $car_basefee,
            'car_basemodel' => $car_basemodel,
            'car_rcusa' => $car_rcusa,
            'car_bono' => $car_bono,
        ), array('post_id' => $post_id));
    }
}
add_action('save_post', 'cotizador_guardar_metaboxes', 10, 3);
?>

I Created a metabox_ajax.php file where the form is inside a function called in "metabox.php", I did this thinking that "when button is pressed, send a counter in order to add the counter in the next forms to be able to add all of them into db"
metabox_ajax.php
<?php
if (!defined('ABSPATH')) exit;

function cotizador_add_model($post)
{
    $post_id = $post->ID;
    $query_result = cotizador_query_select($post_id);
    $i = $_POST['counter'];
?>

                    Modelo:

                    <input value="<?php echo esc_attr($query_result['car_model']); ?>" type='text' placeholder='Modelo' id="vehicle_model" name="car_model" class="regular-text">

                    Precio:

                    <input value="<?php echo esc_attr($query_result['car_price']); ?>" type='number' step='0.01' placeholder='0000.00' id="vehicle_price" name="car_price" class="regular-text">

                    Marca:

                    <?php $brand = esc_html($query_result['car_brand']); ?>
                    <select id="vehicle_brand" name="car_brand" class="post-box">
                        <option value="" selected hidden>Selecciona una marca</option>
                        <option <?php selected($brand, 'Chrysler'); ?> value="Chrysler">Chrysler</option>
                        <option <?php selected($brand, 'RAM'); ?> value="RAM">RAM</option>
                    </select>

                    Año:

                    <?php $year = esc_html($query_result['car_year']); ?>
                    <select id="vehicle_year" name="car_year" class="post-box">
                        <option value="" selected hidden>Selecciona un año</option>
                        <option <?php selected($year, 2020); ?> value="2020">2020</option>
                        <option <?php selected($year, 2019); ?> value="2019">2019</option>
                    </select>

                    Tipo:

                    <?php $type = esc_html($query_result['car_type']); ?>
                    <select id="vehicle_type" name="car_type" class="post-box">
                        <option value="" selected hidden>Tipo de vehículo</option>
                        <option <?php selected($type, 'Auto'); ?> value="Auto">Auto</option>
                        <option <?php selected($type, 'PickUp'); ?> value="PickUp">PickUp</option>
                    </select>

                    Constante cuota base:

                    <input value="<?php echo esc_attr($query_result['car_basefee']); ?>" type='number' step='0.01' placeholder='0000.00' id="vehicle_basefee" name="car_basefee" class="regular-text">

                    Porcentaje base:

                    <input value="<?php echo esc_attr($query_result['car_basemodel']); ?>" type='number' step='0.000001' placeholder='0.000000' id="vehicle_basemodel" name="car_basemodel" class="regular-text">

                    RC USA:

                    <input value="<?php echo esc_attr($query_result['car_rcusa']); ?>" type='number' step='0.01' placeholder='0000.00' id="vehicle_rcusa" name="car_rcusa" class="regular-text">

                    BONO:

                    <?php if ($query_result['car_bono'] == 1) {
                        $checked = 'checked';
                    } else {
                        $checked = 'unchecked';
                    } ?>
                    <input <?php echo $checked ?> type='checkbox' id="vehicle_bono" name="car_bono" class="regular-text">

<?php
}
/* always add following actions in order to make ajax work */
add_action('wp_ajax_nopriv_cotizador_from_ajax', 'cotizador_from_ajax');
add_action('wp_ajax_cotizador_from_ajax', 'cotizador_from_ajax');
/* following function to show up forms if button clicked */
add_action('wp_ajax_nopriv_cotizador_add_model', 'cotizador_add_model');
add_action('wp_ajax_cotizador_add_model', 'cotizador_add_model');

I also created the script in order to use ajax in scripts.php file inside my plugin:
scripts.php
<?php
if (!defined('ABSPATH')) exit;

function cotizador_bootstrap()
{
    // CSS
    wp_register_style('cotizador_bootstrap_css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css');
    wp_enqueue_style('cotizador_bootstrap_css');

    // JS
    wp_register_script('cotizador_bootstrap_jquery', 'https://code.jquery.com/jquery-3.5.1.min.js');
    wp_register_script('cotizador_bootstrap_popper', 'https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js');
    wp_register_script('cotizador_bootstrap_js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js');
    wp_enqueue_script('cotizador_bootstrap_jquery');
    wp_enqueue_script('cotizador_bootstrap_popper');
    wp_enqueue_script('cotizador_bootstrap_js');
}
add_action('admin_enqueue_scripts', 'cotizador_bootstrap');

/* adding scripts into admin panel */
function cotizador_metabox_scripts(){
    wp_register_script('metaboxes_js', plugins_url('../assets/js/metaboxes.js', __FILE__), array('jquery'), 1.0, true);
    wp_enqueue_script('metaboxes_js');
    wp_localize_script('metaboxes_js', 'admin_url', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'ajax_nonce' => wp_create_nonce('any_value_here'),
    ));
}
add_action('admin_enqueue_scripts', 'cotizador_metabox_scripts');

as you can see at the end of this file i'm creating the ajax_url to use /wp-admin/admin-ajax.php
And finally this is my js file:
function add_model() {
    $('#btn_add_model').on('click', function (e) {
        e.preventDefault();
        let i = 1;
        /* creamos la conexion ajax, WP ya tiene esta funcionalidad por default */
        $.ajax({
            type: 'post',
            action: 'cotizador_add_model',
            url: admin_url.ajax_url,
            data: {
                counter: i,
                nonce: admin_url.ajax_nonce
            },
            complete: function (response) {
                console.log(`I got this from server: ${response}`)
            },
            error: function (err) {
                console.log(err);
            }
        });

    });
    return false;
};

And this is what I see in wp (also, when I press the button, the page reload):


text:
Q: Current sensing resistor placement I will be adding a current sensing resistor to a Buck-boost DC-DC converter. Based on the IC datasheet, the resistor is placed at the low-voltage side next to the power inductor.
But, as far as I know, high-side current sensing is much more accurate, without groud-loop issues.
My question is where to best place the resistor and why?

A:
high-side current sensing is much more accurate, without ground-loop issues.

Not true. Ground-loop issues are avoided by using a differential measurement of the voltage across the current-sense shunt resistor, whether that resistor is on the positive or negative rail.
In a typical circuit where everything is referenced to the negative supply rail, high-side sensing has two additional sources of error:

*

*For a given common mode rejection ratio, more of the noise present on the positive supply rail remains unrejected, compared to the much lower level noise on the negative rail

*The transfer of an analog signal from the positive side to the negative reference introduces inaccuracies

Therefore, as far as accuracy goes, sensing the negative rail current is much better. The only reason we don't do it all the time is if we cannot because the power supply and the powered circuit must use the same ground.


text:
Q: Is there any difference between 'wondering whether that hadn't been Cedric's plan' and 'wondering whether that had been Cedric's plan'? I'm thinking a 'whether' clause with a negative sentence means the speaker thinks the situation is less likely. However, I can't find any explanation in dictionaries at hand. For example:

He snapped it shut again, worried that the sound would attract Filch, wondering whether that hadn't been Cedric's plan – and then, making him jump so badly that he dropped the egg, which clattered away across the bathroom floor, someone spoke.
(Harry Potter 4 [US Version]: p.461)[Bold font is mine]

N.B.: 'It' is a magical egg which is wailing loudly while being left open. Filch likes punishing students.
Why did the writer use a negative sentence in the whether clause? I'm wondering if it has some nuance in it.

A: The negation implies more hesitancy in the speculation (effectively here, a lesser degree of likelihood).
People quite commonly say things like I wonder if it's not better to [adopt my suggestion]. The negation there could be seen as more 'polite', in that it emphasises the speculative native of the statement.
Apart from politeness, the implied hesitancy may make it easier for a hearer to consider objectively what's being suggested, rather than immediately recognise and react to what is in effect a challenge to his existing thinking.


text:
Q: Disable Back Button press from fragment My application has an activity with so many fragments. I want to disable the back button press in some fragment. I tried with the below code. But it doesn't work.
In the main activity:
@Override
public void onBackPressed() {
        super.onBackPressed();
        OrderFragment.onBackPress();
}

In the fragment,
public static void onBackPressed()
{
    Log.d(TAG,"It listen");
}

I have the log message but, how can I disable the back button from my fragment.

A: You should keep a reference to the fragment you want to disable/handle back press event on your main activity:
class MainActivity{

    OrderFragment mOrderFragment;

    @Override
    public void onBackPressed() {
        if(mOrderFragment.isVisible())
            mOrderFragment.onBackPressed();
        else
            super.onBackPressed();
    }

}

In OrderFragment:
public void onBackPressed() {
    //handle back press event
}

A: In your oncreateView() method you need to write this code and in KEYCODE_BACk return should true then it will stop the back button option for particular fragment
View v = inflater.inflate(R.layout.xyz, container, false);
//Back pressed Logic for fragment
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

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

A: getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if( keyCode == KeyEvent.KEYCODE_BACK ) {

            // leave this blank in order to disable the back press

            return true;
        } else {
            return false;
        }
    }
});

A: I think you have to Override onResume method in fragments which you need to disable the back press.Tryout the following code.
@Override
public void onResume() {

    super.onResume();
    this.getView().setFocusableInTouchMode(true);
    this.getView().requestFocus();
    this.getView().setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (keyCode == KeyEvent.KEYCODE_BACK) {

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

A: Have you tried like this, Actually it works for me before.
you can set listener for Back key. if you add it, i guess it works.
youfragment.getView().setOnKeyListener( new OnKeyListener()
{
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event )
    {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            return true;
        }
        return false;
    }
}
);

A: super.onBackPressed in the activity is the default implementation. Remove this if you don't want it.

A: I know this is an old question and because of navigation components and new ways this situation rarely occurs, still, maybe my answer helps someone.
I came across a similar situation where I needed the back button to be disabled and I couldn't change the activity as well. So in a fragment, I added this code block.
Language: Kotlin
override fun onResume() {
    super.onResume()
    this.requireView().isFocusableInTouchMode = true
    this.requireView().requestFocus()
    this.requireView().setOnKeyListener { _, keyCode, _ ->
        keyCode == KeyEvent.KEYCODE_BACK
    }
}

This will disable your back press on that specific fragment

A: @Override
public void onBackPressed() {
    Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
    if (currentFragment instanceof YourFragment) {
         currentFragment.onBackPressed();
    } else
        super.onBackPressed();
}

A: override fun onBackPressed() {
    val currentFragment = findNavController(R.id.nav_host_fragment).currentDestination?.id
    if (currentFragment == R.id.YourFragment) {
        return
    }
    super.onBackPressed()

A: onBackPressed works like this:
public void More onBackPressed() {
    if (!mFragments.popBackStackImmediate()) {
        finish();
    }
}

Thus when you call super.onBackPressed() you pop the BackStack before finishing the activity. The best way to sort this out is to make sure you do not add the fragments to the BackStack. It is normally done like this:
fragmentTransaction.addToBackStack(TAG);

An alternative solution, but uglier since you have still useless code left, would be making onBackPressed() directly call finish() to end the activity.
I would strongly advise you not use getView().setOnKeyListener(...) since it is code smell.

A: If you don't want your fragment to be in the backstack you can do so, by not adding it to the backstack in the transaction. So do NOT call FragmentTransaction.addToBackStack(); on the fragments you do not want in your backstack.

A: Try this
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}else{
super.onBackPressed();}

}


text:
Q: l3fp "Number too big" error Consider the following example:
\documentclass{article}

\usepackage{pstricks-add}
\usepackage{expl3}

\ExplSyntaxOn
  \cs_new_eq:NN \calc \fp_eval:n
\ExplSyntaxOff

\newcommand*\SideLength[1]{\calc{sqrt(#1)}}
\newcommand*\Angle[1]{\calc{asin(1/sqrt(#1))}}

\begin{document}

\begin{pspicture}(-2.9,-3.5)(4.5,2.2)
  \multido{\iA = 2+1, \iB = 1+1}{16}{%
    \psRelLine[angle = \Angle{\iA}](0,0)(2,0){\SideLength{\iB}}{A}}
\end{pspicture}

\end{document}

When compiling, I get the error
! Number too big.
<argument> 7853981633
                     974483
l.17 ...ngle{\iA}](0,0)(2,0){\SideLength{\iB}}{A}}

How do I fix this?

A: You are passing the full set of digits from l3fp back to pstricks, but that's too many! (The LaTeX3 FPU is IEEE-compliant so works at 16 digit precision.) In common with many TeX packages, pstricks is expecting a number here with no more digits than TeX will accept as a \number. Probably the easiest fix is to round within the FPU:
\newcommand*\Angle[1]{\calc{round(asin(1/sqrt(#1)),5)}}

or
\ExplSyntaxOn
  \cs_new:Npn \calc #1 { \fp_eval:n { round ( #1 , 5 ) } }
\ExplSyntaxOff

depending on your use cases. (Five decimal digits is probably enough to pass back to most TeX end-uses.)


text:
Q: Referencing a field in a subform in ms access in ms access I have a form with a subform. In the subform in a field called "End_Date" in the main form I have a textbox that displays the end date if there is one and then "available" if there isn't any. I have been trying to use an iif statement for this. My problem however comes with trying to reference the field in the subform. Currently I am using the code "Forms![mainForm].[subform name].Form![End_Date]" I tried just using this statement to see if it would display the date at all, it will not. It displays "#name?". Microsoft online says this should successfully reference the field but I doesn't seem to work.
I need help, thank-you in advance for the help :)

A: I have referenced a subform field in the following way before, but is your reference to do with a query or a form?
=Forms![mainForm].[subform name].Form.[End_Date]

N.B. I have had previous issues where i've tried to mix a string and a number value.


text:
Q: Google Analytics analytics.js - Enhanced Ecommerce I am using https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce
to add enhanced analytics tracking to my application . When I am trying to add impression I got following error in the console in analytics console
VM17923 analytics_debug.js:10 Command ignored. Plugin "ec" has already been required on tracker "t0".
Can anyone help please ! I am using ga('require', 'ec') to register this plugin and when i removed it it tells me plugin not registered .
I also tried giving name to the trackor but not worked well


text:
Q: Javascript manipulation of display:none doesn't work properly I'm trying to make a JS price calculator and I'm stuck on one part, where I do not find a solution for a couple of hours. I will appreciate your help.
This is what I'm trying to do:

*

*Displaying part, where there are 3 product types (<input type="radio"). Clicking to one of them should appear with own LightBox and also hiding other parts of the <input> form.

Basic Price

        <?php include "/Templates/singleSpotLightBox.php"?>

        <?php include "/Templates/multiSpotLightBox.php"?>

        <?php include "/Templates/photoSilk.php"?>

    Transfer Type

            <input type="radio" name="type" id="sSpot" onclick="invisibleColors()"> SingleSpot

            <input type="radio" name="type"id="mSpot" onclick="invisibleColors()"> MultiSpot

            <input type="radio" name="type"id="pSilk" onclick="invisibleColors()"> PhotoSilk

*Javascript part for hiding (by style.display = "none";) the divs which do not belong to the chosen product:

function invisibleColors() {
    let sSpot = document.getElementsByName("type");
    let singleSpotLB = document.getElementById("singleSpotLB");
    let multiSpotLB = document.getElementById("multiSpotLB");
    let photoSilkLB = document.getElementById("photoSilkLB");

    if (sSpot[0].checked) {
        document.getElementById('colorDiv').style.display = "none";
        singleSpotLB.style.display = "block";
        multiSpotLB.style.display = "none";
        photoSilkLB.style.display = "none";
    } else if (sSpot[1].checked) {
        document.getElementById('colorDiv').style.display = "block";
        singleSpotLB.style.display = "none";
        multiSpotLB.style.display = "block";
        photoSilkLB.style.display = "none";
    } else if (sSpot[2].checked) {
        document.getElementById('colorDiv').style.display = "none";
        singleSpotLB.style.display = "none";
        multiSpotLB.style.display = "none";
        photoSilkLB.style.display = "block";

    }
}

**The problem:
When I'm testing the code it works well at the beginning but after a couple of clicks the label texts change properly, but the images just don't load.
Thanks, and I hope someone could help.
P.S Content of the PHP files from where the LighBox is loaded:
SingleSpot

Here is a video of the result

A: @Alexandar Dimov Your code in Html is owner than the code in javascript. add your style in other file CSS and try again.

A: I found that there is an ajax process loaded from the template, which conflicts with the plain JS script. Thank you all for your opinions and help.


text:
Q: AJAX não respeita forEach Tenho um banco com duas colunas, a saber: Atividade e status.
Tenho uma table na minha página com todas as Atividades, e desejo saber o status de cada uma delas.
Selecionei todas as tr's e uso um ajax dentro de um forEach, porém o AJAX não vê cada uma das tr's, ele vê apenas uma.
Além disso, ele retorna algumas vezes que o PHP não carregou, porém está sempre passando os mesmos dados pelo POST, como pode ora carregar e ora não, se não muda nada nos parametros?
Não sei se é relevante, mas antes desse ajax, eu estou rodando outro, no mesmo evento "change" de um select.
código javascript

function verificaVinculados() {
  formulario_vincular = document.querySelector("#formulario_vincular");
  formulario_vincular.funcao_vincular.value = "verificar";

  atividades = document.querySelectorAll(".atividade");

  atividades.forEach(function(atividade) {
    formulario_vincular.atividade_vincular.value = atividade.firstChild.id;

    xhr_atividadeVinc = new XMLHttpRequest();
    xhr_atividadeVinc.open("POST", "banco/banco-vision/pagina-cadastrar-empresas/vincular-atividades.php");

    console.log(formulario_vincular.atividade_vincular.value); //Aqui ele sempre mostra cada uma delas.
    xhr_atividadeVinc.addEventListener("load", function() {
      console.log(formulario_vincular.atividade_vincular.value); //Aqui ele sempre mostra a mesma atividade
      if (xhr_atividadeVinc.status == 200) {
        console.log("carregou com sucesso");
      } else {
        console.log("Falha ao carregar o php");
      }
    });
    xhr_atividadeVinc.send(new FormData(formulario_vincular));

  });

}

html
<form id="formulario_vincular">
  Empresa:

  <input type="hidden" name="cod_emp_vincular">
  <input type="hidden" name="tributacao_vincular">
  <input type="hidden" name="atividade_vincular">

  <input type="hidden" name="funcao_vincular">

  Departamento:
  <select name="dep_vincular">
    <?php
            while($linha_departamentos1 = mysqli_fetch_assoc($lista_departamentos1))
            {
           ?>
      <option value="<?php echo $linha_departamentos1[" DEPARTAMENTO "];?>">
        <?php echo $linha_departamentos1["DEPARTAMENTO"];?>
      </option>

      <?php
            }
           ?>

  </select>
</form>

    Atividade
    Status

código que uso pra preencher a tabela com as atividades

formulario_vincular.dep_vincular.addEventListener("change", function() {
  formulario_vincular.funcao_vincular.value = "listar";
  xhr_atividadePorDep = new XMLHttpRequest();
  xhr_atividadePorDep.open("POST", "banco/banco-vision/pagina-cadastrar-empresas/vincular-atividades.php");
  xhr_atividadePorDep.addEventListener("load", function() {
    if (xhr_atividadePorDep.status == 200) {
      tabela_vincular = document.querySelector("#tabela_vincularAtividades");
      tabela_vincular.textContent = "";
      atividades_disponiveis_vincular = JSON.parse(xhr_atividadePorDep.responseText);
      atividades_disponiveis_vincular.forEach(function(atividade) {
        montaTabelaVincular(atividade);
      });

    } else {
      console.log("Falha ao buscar php");
    }

  });

  xhr_atividadePorDep.send(new FormData(formulario_vincular));

  setTimeout(verificaVinculados(), 9000);

});

function montaTabelaVincular(atividade) {
  tabela_vincular = document.querySelector("#tabela_vincularAtividades");
  atividadeTr = document.createElement('tr');
  atividadeTr.classList.add("atividade");

  tipo_atividadeTd = document.createElement('td');
  tipo_atividadeTd.textContent = atividade.ATIVIDADE;
  tipo_atividadeTd.id = atividade.ATIVIDADE;

  statusTd = document.createElement('td');
  statusTd.textContent = "pendente";

  tabela_vincular.appendChild(atividadeTr);
  atividadeTr.appendChild(tipo_atividadeTd);
  atividadeTr.appendChild(statusTd);
}

A: Faça uma função recursiva que faz uma requisição após a outra quando a anterior foi processada.
Crie uma variável de controle com valor 0. Após uma requisição ter sido processada, incremente +1 a essa variável. Enquanto o valor dela for menor que o número de elementos em atividades a função será novamente chamada até chegar no último elemento.
var conta = 0; // variável de controle
function verificaVinculados(){
   formulario_vincular = document.querySelector("#formulario_vincular");
   formulario_vincular.funcao_vincular.value = "verificar";

   atividades = document.querySelectorAll(".atividade");

   var atividades_len = atividades.length; // conta o número de elementos

   formulario_vincular.atividade_vincular.value = atividades[conta].firstChild.id;

   xhr_atividadeVinc = new XMLHttpRequest();
   xhr_atividadeVinc.open("POST", "banco/banco-vision/pagina-cadastrar-empresas/vincular-atividades.php");

   console.log(formulario_vincular.atividade_vincular.value); //Aqui ele sempre mostra cada uma delas.
   xhr_atividadeVinc.addEventListener("load", function(){
      console.log(formulario_vincular.atividade_vincular.value); //Aqui ele sempre mostra a mesma atividade
      if(xhr_atividadeVinc.status == 200){
         console.log("carregou com sucesso");
      }else{
         console.log("Falha ao carregar o php");
      }

      conta++; // incrementa a variável
      if(conta < atividades_len){
         verificaVinculados(); // chama novamente a função
      }else{
         conta = 0; // ao terminar tudo, zera a variável novamente
      }
   });
   xhr_atividadeVinc.send(new FormData(formulario_vincular));
}


text:
Q: c# check if list contains an existing element (not null) Is there some equivalent to myTestList.Count that will only count not-nullable fields?
For example I want to do certain things when I know that between some null elements is one existing element.
This is the behaviour I want, but can this be achieved also with pre-existing functions?
if(myList.Count > 0){
    for(int i = 0; i < myList.Count; i++){
        if(myList[i] != null){
            DoSomething();
            break;
        }
    }
}

A: If you aren't fussed about checking a specific index of the list not being null and just want to check there is something in the list you could use this.
if(myList != null && myList.Any())
{
   DoSomething();
}

A: Use the linq Any method:
if (myList.Any(i => i != null))
{
    DoSomeThing();
}


text:
Q: Native Packager exception occurred I am getting below exception while building phone gap application for blackberry 10.
[BUILD]   Populating application source
[BUILD]   Parsing config.xml
[BUILD]   Generating output files
[WARN]    Failed to find debug token
[INFO]    Info: Package created: C:\Ex\hello\build\simulator\HelloWorld.bar
[ERROR]   Error: bar1558418047103827107.MF, Invalid manifest version.
[ERROR]   Native Packager exception occurred
[WARN]    Failed to find debug token
[INFO]    Info: Package created: C:\Ex\hello\build\device\HelloWorld.bar
[ERROR]   Error: bar1882161790050252236.MF, Invalid manifest version.
[ERROR]   Native Packager exception occurred

Can any one help me plaese.

A: You need to install the BlackBerry 10 Webworks SDK.
Make sure to restart your shell afterwards to have your environment variables updated.


text:
Q: Cassandra nodetool error I have a Cassandra cluster of two nodes. I am using Cassandra 3.10.
when I tried to run nodetool status, by default it is calling /usr/bin/nodetool and gives result You must set the CASSANDRA_CONF and CLASSPATH vars.
CASSANDRA_HOME and CASSANDRA_HOME/bin is already set in bashrc.
When I run CASSANDRA_HOME/bin/nodetool status It is showing correct result, both the nodes are up.
My problem is how can I make CASSANDRA_HOME/bin/nodetool as default. So that I can call it from any where.
PS: cqlsh is also showing same behavior.
Thanks.


text:
Q: How do I correct these "Expected Expression Before 'Stack'" and "Not Enough Arguments to Function 'Push'" errors? This is my first question ever asked on this site.  The program I'm working on is supposed to check a string to make sure that all delimiters found within the string match up ('(' and ')', '[' and ']', and so on).  While I'm rather certain it won't work right away once these errors get corrected, I'd like to at least be able to run the flawed program and go from there.
What I believe to be the relevant segments of code are located in the following section of my finite state machine subprogram, and my push and pop subprograms:
#include <stdio.h>

#include <stdlib.h>

#include "boolean.h"

typedef struct stacknode {

      char data;

      struct stacknode *next;

} *stack;

char fms(stack *, char); /*Prototypes for relevant subprograms*/

char fms(stack *s, char input){

   int state = 0;

   char i = -1, o, c;

   while(1) {

      switch(state) {

         case '0': i = i++;

                   if (isopen(input))

                      state = 1;

                   else {

                      if (isclose(input))

                         state = 2;

                      else {

                         if (input == '\0')

                            state = 3;

                         else

                            state = 4;

                      }

                   }

            break;

         case '1': push(stack *s, o); /*Two errors here. "Expected expression before 'Stack', and "Not enough arguments to function 'Push'".*/

                   state = 0;

            break;

         case '2': if(!is_empty) {

                      c = input;

                      o = pop(&stack *s); /*One error here. "Expected expression before 'Stack'".*/

                      if(!isbrother(o, c)) {

                         printf("Error: Pair does not match.");

                         return FALSE;

                      }

                   }

                   else {

                      printf("Error: Too many closing delimiters.");

                      return FALSE;

                   }

                   state = 0;

Please remember I decided to only show the part of my fms subprogram relevant to my errors.  It's quite lengthy otherwise.
void push(stack *s, char o) {

   stack temp;

   temp = (stack) malloc(sizeof(struct stacknode));

   temp->data = o;

   temp->next = (*s);

   (*s) = temp;

}

char pop(stack *s) {

   stack temp;

   char data_popped;

   temp = *s;

   data_popped = temp->data;

   *s = temp->next;

   free (temp);

   return data_popped;

}

Any help you all can graciously give me will be greatly appreciated.  I should be able to figure out the rest once these errors are disposed of.

A: case '1': push(stack *s, o); you should call functions with passing arguments (such as pass by value or reference) without data types.
You just need to pass the variable as,
push(s, o); //Where s holds the base address

A: Do not do:
push(stack *s, o)

do
push(s, o)

as you do not need to declare the type of variables when calling functions, only when declaring the function itself.


text:
Q: Include more than one media attribute in phtml I want to add multiple media image attributes in my phtml template but if I use more than one then none of them show :(
I'm using the following:
$product = $block->getProduct();

$productImageAttr = $product->getCustomAttribute( 'custom_image_1' );
$productImage = $this->helper('Magento\Catalog\Helper\Image')
    ->init($product, 'custom_image_1')
    ->setImageFile($productImageAttr->getValue());

and then I can include it as follows:
<img src="<?php echo $productImage->getUrl(); ?>" alt="<?php echo $block->escapeHtml($product->getTitle()); ?>"  />

If I want to add another I would assume that I need to do this:
$productImageAttr2 = $product->getCustomAttribute( 'custom_image_2' );
$productImage2 = $this->helper('Magento\Catalog\Helper\Image')
    ->init($product, 'custom_image_2')
    ->setImageFile($productImageAttr2->getValue());

but when I do, neither images show.
Can anyone help please?


text:
Q: Navigating between ContentPages with Prism in Xamarin Forms maintains NavigationParameters Using the NavigationParameters collection within Prism, we are passing an object from one ContentPage to another ContentPage which displays as a modal.
The modal allows a user to edit the data. If the user decides to cancel the edit form, we call:
NavigationService.GoBackAsync(null, true).

Once navigated back to the previous page, the original property that was passed through to the modal has updated with the edited values without setting it.
Are NavigationParameters passed as a reference within NavigateAsync? What's the best way of preventing this from happening?

A:
Using the NavigationParameters collection within Prism, we are passing an object [...] [Emphasis mine]

You are setting an object in the NavigationParameters. Instances of classes (objects) are passed by reference in C#, instances of structures are passed by value. For structures there are semantics to copy and compare values (i.e. all public properties are copied and compared respectively), but for classes there are no similar semantics.
Please see the documentation:

Because classes are reference types, a variable of a class object holds a reference to the address of the object on the managed heap. If a second object of the same type is assigned to the first object, then both variables refer to the object at that address.

In order to prevent the original object being updated, you'll have to copy the object before it is manipulated (I'd copy it before passing it, but you could copy it at the target site, too). If your class contains value type properties only, a shallow copy will suffice, i.e. you create a method (or property, but this might be misleading) that returns a new object of your class with all the values copied
class MyClass
{
    int Value1 { get; set; }
    float Value2 { get; set; }

    public MyClass Copy()
    {
        var copy = new MyClass()
                       {
                           Value1 = this.Value1,
                           Value2 = this.Value2
                       }
        return copy;
    }
}

If you object contains reference types itself, you might have to create a deep copy
class MyClass
{
    MyClass2 Reference { get; set; }

    public MyClass Copy()
    {
        var copy = new MyClass()
                       {
                           Reference = this.Reference.Copy()
                       }
        return copy;
    }
}

Of course, those will have to implement a Copy() method, too.


text:
Q: C# SignalR Client I'm using SignalR client version 2.2.0 nuget.
this._connection = new HubConnection(this._url);
this._connection.Closed += this.ConnectionOnClosed;
this._connection.Error += this.ConnectionOnError;
ServicePointManager.DefaultConnectionLimit = 250;
this._client = this._connection.CreateHubProxy(HubName);
this._connection.Start(new WebSocketTransport()).Wait();

Then I reuse the client every time (multi-threaded):
client.Invoke<bool>(nameof(this.AddIfNotExists), key, data, expireAfter)
Parallel.For(
            0,
            50000,
            new ParallelOptions
            {
                MaxDegreeOfParallelism = 10,
            },
            async (i) =>
            {
                var result = await client.ExecuteDistributedAsync(
                    (i % 2).ToString(),
                    TimeSpan.FromSeconds(5),
                    async () =>
                        {
                            await Task.Delay(500);
                            return $"Done: {i} [{(i % 2)}]";
                        });
                Console.WriteLine("--->" + (result ?? "TIMEOUT:" + i));
            });

This crashes almost immediately (1st addifnotexist works and then the next 8 it crashes). From what I've read everywhere the IHubProxy is supposed to be thread-safe...
Any suggestions?

A: Solution was to create an objectpool and threads would take it from the pool and put it back when done using. The SignalR client is not threadsafe for sure.


text:
Q: Assigning abilities in Laravel 5.1 Authorization Recently upgraded to Laravel 5.1 and have read the new features which is Authorization .  I was using Entrust before but decided to use this now as I was using a very basic permission/abilities anyway.  The doc explains how to define and check for abilities but I didn't find a line to attach this ability to a certain user.  Am guessing these abilities should be saved and pulled from the db, but not sure how to attach these.

A: Unfortunately the Authorization service doesn't assign abilities/permissions coming from a database. The docs seem to mislead us in that direction.
You can opt for a package to deal with this part, such as https://github.com/spatie/laravel-permission


text:
Q: Cannot convert double to double void load(int *n, double *x, double **arr, bool randomize)
{
    *arr = (double*)malloc((*n + 1) * sizeof(double));
    srand(time(NULL));
    for(int i = 0; i <= *n; i++)
    {
        if(! randomize)
        {
            scanf("%lf", *arr + i);
        }
        else
        {
            *(arr + i) = rand();
        }
    }
}

Based on the randomize parameter I want to fill the array with random or custom double numbers. This code however does not compile, it displays "invalid conversion from int to double" in else section.
Replacing rand() with any float value like 5.0 shows "cannot convert double to double" instead.
(double) rand() or (double) 5 throw similar errors.
*n of course is read earlier in this function, I just cut it off here.
What can be wrong here?

A: The error message you are quoting is incomplete. It's missing an asterisk after double: the type of *(arr + i) is double* rather than double, and you can't convert int or double to double*.
Presumably you mean
        *(*arr + i) = rand();

or
        (*arr)[i] = rand();

A: *(arr + i) = rand(); -> (*arr)[i] = rand();


text:
Q: Clunky/slow dragging functionality on my analog clock project I just finished my first Python project, an analog clock. I managed to reach a state where I implemented everything I had in mind and fixed the issues that followed. The last thing I added in is a dragging capability for my clock and while it works it seems slow or at least just unsmooth. Right now I lack the knowledge and experience to understand why its happening and let alone fix it.. Any help or ideas would be appreciated, Thanks in advance. :)
Here is my code:
# Imported tkinter for its methods
import tkinter as tk

# Imported turtle for drawing the clock's hands
import turtle

# Imported time to handle setting and updating the time
import time

# Declared and set the color used for transparency
transparent_clr = '#FB00FF'

# Setup a borderless window with transparent background
# and always on top flag
root = tk.Tk()
root.overrideredirect(True)
root.wm_attributes('-topmost', 1)
root.deiconify()
root.attributes('-transparentcolor', transparent_clr)

# Setup the clock's face using an image
Clock_bg = tk.PhotoImage(file='Clock_bg.png')
canvas = tk.Canvas(width=300, height=300, highlightthickness=0)
screen = turtle.TurtleScreen(canvas)
canvas.create_image(0, 0, image=Clock_bg)
canvas.pack()

screen.tracer(0)
screen.bgcolor(transparent_clr)

# Configure the pen used for the clock's hands
draw = turtle.RawTurtle(screen)
draw.hideturtle()
draw.speed(0)
draw.pensize(3)

# Retain Windows TaskBar visibility and function such as exiting
# the app
wn = tk.Toplevel(root)
wn.iconify()
wn.iconbitmap('Clock_icon.ico')
wn.attributes('-alpha', 0.0)

def wn_destroy():
    wn.protocol('WM_DELETE_WINDOW', exit_func)

def exit_func():
    root.destroy()

wn_destroy()

# Make the clock draggable

def draggable():
    root._offsetx = 0
    root._offsety = 0
    root.bind('<Button-1>', winclick)
    root.bind('<B1-Motion>', windrag)

def windrag(event):
    x = root.winfo_pointerx() - root._offsetx
    y = root.winfo_pointery() - root._offsety
    root.geometry('+{x}+{y}'.format(x=x, y=y))

def winclick(event):
    root._offsetx = event.x
    root._offsety = event.y

draggable()

# Draw the clock and its hands

def draw_clock(h, m, s, draw):

    # Draw the hours hand
    draw.penup()
    draw.goto(0, 0)
    draw.color('black')
    draw.setheading(90)
    angle = (h / 12) * 360 + (m / 60) * 30
    draw.rt(angle)
    draw.pendown()
    draw.fd(70)

    # Draw the minutes hand
    draw.penup()
    draw.goto(0, 0)
    draw.color('black')
    draw.setheading(90)
    angle = (m / 60) * 360 + (s / 60) * 6
    draw.rt(angle)
    draw.pendown()
    draw.fd(100)

    # Draw the seconds hand
    draw.penup()
    draw.goto(0, 0)
    draw.color('red')
    draw.setheading(90)
    angle = (s / 60) * 360
    draw.rt(angle)
    draw.pendown()
    draw.fd(60)

# Update the time in real time
while True:
    # Declared and set the hour, minutes and seconds
    h = int(time.strftime('%I'))
    m = int(time.strftime('%M'))
    s = int(time.strftime('%S'))

    draw_clock(h, m, s, draw)
    screen.update()

    time.sleep(1)

    draw.clear()

A: "You are using your own mainloop with time.sleep(1), therefore root.geometry( gets only called every second. –stovfl"
Thanks a billion, stovf1!


text:
Q: Drive API download without login I'm currently developing an application that acts as a file service for clients. The application is connected to one Google account that it retrieves files from. I've stored the access and refresh tokens for this account and have authorized everything necessary.
We're using Drive as a storage solution and we're giving clients access to certain folders within our Drive account through our application. From our application they can see a list of files and then download those files. The problem is that the standard Drive download methods all require that the user is logged into to a Google account and if they aren't it redirects them to a login page. Once they're logged in to Google the download works, but we need it to work without them being logged in to Google.
Is there any way around this? I've tried several ways to get around it (manual authorized cURL requests, authorized php-api httpRequests, etc) but haven't gotten anything to work.

A: This is what i did with an example php. (All the authentication stuff is stripped out.)
$service = new Google_DriveService($client);
$url="the_url_to_your_document_according_to_$service->files->listFiles";
$request = new Google_HttpRequest($url);
$response = $client->getIo()->authenticatedRequest($request);
$content = $response->getResponseBody();

Now you can pipe $content to the user (if there are no errors of course).
EDIT: I did some testing and you can download directly with Curl authentication. If you get a 401 error you are using an access token which expired. Just get a new one (new login with authentication) and do a curl directly (within 3600 or 1800 seconds):
curl -o testfile -v -H 'Authorization: Bearer ya29.yournewone' 'https://docs.google.com/feeds/download/xxx'

It worked for me. You can use the "downloadUrl" for this according to that page. No need to use getWebContentLink.
If you want long term tokens you need to request a "Refresh token". You can find some information on this page. There are some limits in numbers to request these mentioned on that page at the bottom.
EDIT #2: Just did another test. I could download directly from the downloadUrl by adding &access_token=ya29.xxxxxxxxxx. 'ya29.xxxxxxxxxx' being your latest access_token. No need for authentication via Curl and user does not have to be logged in Google if you use downloadUrl instead of getting a WebContentLink (only a recent access_token is needed). So i could set this link on a page where everybody could download the file(s) (for about half an hour after which the links/access_token needs to be refreshed)


text:
Q: How can I install the latest version of packages (e.g. Apache2) using a stable version of Debian? I'm managing a VPS server (I'm using Debian 10 Buster, the latest stable version), and I want to install the latest version of the essential web packages (for example: Apache 2.4.43, Bind 9.16.3), but when I use the default apt-repository, it installs a slightly old version (apache 2.4.38 and bind 9.11.5)..
I've found out that the version 2.4.43 of apache2 is only available for Debian Bullseye (testing version), but I don't want to install a testing version of Debian, I prefer stable versions.
In a nutshell: I want to install the "latest" version of apt packages (like apache2, bind9, postfix, etc.) without upgrading to an unstable version of Debian.

A: The reason Debian stable is called stable is because the software it contains, or rather, the external interfaces of all the individual pieces of software it contains, don't change during its lifetime. A consequence of this is that, barring a few exceptions, packaged software isn't upgraded to newer versions. So you can't — in general — install packaged versions of newer software while remaining on Debian stable.
Some packages are however made available as backports, and the apache2 package is one of them. You can install these by enabling backports and selecting that as the source of upgrades:
echo deb http://deb.debian.org/debian buster-backports main | sudo tee /etc/apt/sources.list.d/buster-backports.list
sudo apt update
sudo apt install -t buster-backports apache2

If other upgrades are already available in testing, and there's a particularly relevant reason to upgrade, you can try filing bugs requesting a backport.
Note however that you should only upgrade to backports of packages if you have a specific reason to do so: backported packages don't receive the same security support as packages in the stable repository, and while the stable distribution is tested as a coherent whole, no such testing is done with backports.

A: #!/bin/bash
# To add this repository please do:

if [ "$(whoami)" != "root" ]; then
    SUDO=sudo
fi

${SUDO} apt-get -y install apt-transport-https lsb-release ca-certificates curl
${SUDO} wget -O /etc/apt/trusted.gpg.d/apache2.gpg https://packages.sury.org/apache2/apt.gpg
${SUDO} sh -c 'echo "deb https://packages.sury.org/apache2/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/apache2.list'
${SUDO} apt-get update

# upgrade if you had the 2.4.38
apt-get upgrade -y

# If it wasn't already installed, at all
apt-get install apache2 -y

source: https://packages.sury.org/apache2/README.txt
from: https://deb.sury.org/


text:
Q: ModelSim SE 5.7: unexpected 'Z' and 'X' While getting my feet wet with an old Spartan2-Board I tried to setup a 1-bit full adder with the Verilog code and accompanying testbench as below:
module full_adder(s, cout, a, b, cin);
output s, cout;
input a, b, cin;

wire t1, t2, t3;

xor (t1, a, b);
xor (s, t1, cin);
and (t2, t1, cin);
and (t3, a, b);
or  (cout, t2, t3);
endmodule

Testbench:
module tb_full_adder;

// Inputs
reg a;
reg b;
reg cin;

// Outputs
wire s;
wire cout;

// Instantiate the Unit Under Test (UUT)
full_adder uut (
    .s(s),
    .cout(cout),
    .a(a),
    .b(b),
    .cin(cin)
);

initial begin
    // Initialize Inputs
    a = 0;
    b = 0;
    cin = 0;

    // Wait 100 ns for global reset to finish
    #100;

    //125 ns
    #25;    a = 1'b1;
    //150 ns
    #25;    a = 1'b0;   b = 1'b1;
    //175 ns
    #25;    b = 1'b0;   cin = 1'b1;

end
endmodule

I had to use ISE 10.1 and ModelSim SE 5.7 because the more recent versions of the ISE don't support any of the Spartan devices any more, IIUC (let alone Vivado).
The issue is that the 'Wave window' of ModelSim shows all the signals as either hi-Z or don't care 'X':

If I setup the exact same project in ISE 14.7, the code also compiles and the simulation, in this case it's the more recent ISim, shows the expected traces:

What is the difference between ModelSim and ISim, besides its age ?
What am I missing ?
best,
Chris

A: There is nothing different between Modelsim and ISim in this respect. With Modelsim you have not simulated your testbench. I can tell that because the signal names in the waveform viewer all start /full_adder/ rather than /tb_full_adder/uut/. I manged to get a similar waveform to your ISim waveform in Modelsim by simulating the testbench, too, ie by typing vsim tb_full_adder in the transcript window.


text:
Q: Are they the same? We usually define a verb of incomplete prediction as one not expressing a complete thought, hence its needing a complement. Thus, in the sentence "The baby seems", 'seems', being a verb of incomplete predication, requires a subject complement.
Now, if we consider the sentence " This is the house that Jack built", we say that 'Jack built' is a clause introduced by the relative pronoun 'that'. But the definition of a clause is that it's a part of a sentence with its own subject and predicate and expresses a complete thought. Doesn't the clause 'Jack built' seem to require, like verbs of incomplete predication, a complement to express a complete thought?


text:
Q: Can we execute the alert message using the following code? Can we alert the message using the following function ??
var run_databases = function() {
    alert('welcome');
};

window.setTimeout(run_databases, 1000);

A: No need for the other function wrapping (closure) :

var run_databases = function() {
  alert('welcome');
};

window.setTimeout(run_databases, 1000);

A: You need to name the function or assign it to a variable:

var run_databases = function() {
  alert('welcome');
};

// You need to name this function
function setTimeOutFoo() {

  window.setTimeout(run_databases, 1000);

};

// Or assign the unnamed function to a variable
var setTimeOutVar = function() {

  window.setTimeout(run_databases, 1000);

};

setTimeOutFoo(); // Calling the function
setTimeOutVar();

You can try something like this:

window.onload = function() {
  console.log('Page has finished loading');

  //I am adding a time out so you can see the loading
  // You can remove the "setTimeout(function () {"
  // And you can also remove the "}, 2000);"

  setTimeout(function () { // Remove this line

    document.getElementById('loading').innerHTML = "Page Loaded";

  }, 2000); // Remove this line

};

Page Loading...

The easiest way to add a tooltip to a button is:

var btn = document.getElementById("btn");

btn.setAttribute('title', 'This is the tool tip set in JavaScript');

<button id="btn">Hover here!</button>

<button id="btn" title="This is tool tip set in HTML">No! Hover here :)</button>

A: You're using a self invoking anonymous function, but your syntax is wrong:
var run_databases = function() {
  alert('welcome');
};

(function(){
   window.setTimeout(run_databases, 1000);
})();

Working example


text:
Q: Automatic Power Selection with MOSFET I need a circuit which will automatically disconnect the battery from LOAD when ext. DC power is connected so that the battery won't get damaged.
Theoretically a pair of diodes can solve this but since voltage drop is not a good thing for a portable device, so after reading few topics about an "ideal" diode (first and second) I came up with simply rotating MOSFETs (connecting SOURCE to actual drain and DRAIN to actual source) so body-diode will block unwanted reverse current flow:

Q1 Is preventing battery from discharging to DC IN when e.g. 5V source is connected and isolating DC IN positive wire from battery, so we can detect a ext. power supply is connected.
Q2 Is preventing DC IN 9-24V from going to battery and damaging it.
But probably a small amount of current will flow thru Q1's body-diode to battery at first moments after ext. power is connected (or contact bouncing) before Q2's gate has triggered, but I'm not sure if it's something to worry about.
Anyway I have a strong feeling I'm reinventing the wheel here, so I need  other standard solutions/ideas please. Requirements are:

*

*Automatic and fast switching. Actually a 2-position toggle switch
can be a good solution here but it will require manually selecting
the source:

*Loads up to 6A, voltage range: 4-30V

*Small, but as simple and cheap as possible (so two relays/SSRs @6A is too big and expensive)

*No diodes at load current flow please, since 0.4V@6A is 2.4W of heat and ~5-6% loss in efficiency (which is bad for a battery-powered device).

Or, if first circuit seems to work just fine and there's no significant errors I made, maybe I can use it?
Thanks for help!

Oh, it seems like I found a problem – Q1 won't open after external power supply is disconnected, because current from Q2's body-diode can flow thru Q1's SOURCE-DRAIN to Q3 BASE, keeping Q2 from closing and Q1 from opening.
Adding a diode can fix this. Yes, it will drop some voltage, but since it's true just for external power source, we won't lose any portable efficiency :)

A: Actually the dual-PNP circuit can be used to control the second PFET directly:

simulate this circuit – Schematic created using CircuitLab
Q1 and Q2 function as a differential pair — when one is conducting, the other is cut off.
Their state is determined by the relative voltage on their emitters. When "Line" is higher than "Load", Q1 is conducting and Q2 is off, which means that M2 is off and M1 is on. When "Line" drops below "Load", Q1 cuts off, turning Q2 on, which in turn switches M1 off and M2 on.


text:
Q: How to use the cssSelector :nth-child(n) to locate element in Python Selenium I'm using Python Selenium to locate element by using nth-child(n).
Below is my html code:

      FALAFEL

          (6)

          2.99

          (12)

          4.99

Now I want to locate the first a tag by using nth-child(n) so I tried:
driver.find_element_by_css_selector('div#iopoph a:nth-child(2)').click()

But there is an error says:
NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"div#iopoph a:nth-child(2)"}
(Session info: chrome=79.0.3945.88)

Any friend can help?

A: You were close but you need to consider a couple of things:

*

*div#iopoph will identify the parent node, i.e.

*So you need to traverse to it's grand child node:

*To locate it's child elements you can use the following Locator Strategies:

*

*Locating :
div.animated.zoomIn#iopoph a:nth-of-type(1)

*Locating :
div.animated.zoomIn#iopoph a:nth-of-type(2)

A: you can use this locator a:nth-of-type(2)

A: In your case example-
div#iopop a:nth-child(3) -> returns first a <anchor> tag i.e.  returns second a <anchor> tag i.e.  It points to tag  and it is not same as the tag you mentioned before : (colon). so it returns NOSUCHELEMENTEXCEPTION