text:
Q: How to adjust return values of map() function? I have been trying to make a excercise in the course I am taking. At the end, I did what was asked, but I personally think I overdid too much and the output is not convenient -- it's a nested array with some blank arrays inside...
I tried to play with return, but then figured out the problem was in the function I used: map always returns an array. But all other functions, which are acceptable for arrays (in paticular forEach and I even tried filter) are not giving the output at all, only undefined. So, in the end, I have to ask you how to make code more clean with normal output like array with just 2 needed numbers in it (I can only think of complex way to fix this and it'll add unneeded junk to the code).
Information
Task:

Write a javascript function that takes an array of numbers and a target number. The function should find two different numbers in the array that, when added together, give the target number. For example: answer([1,2,3], 4) should return [1,3]

Code

const array1 = [1, 2, 3];
const easierArray = [1, 3, 5] //Let's assume number we search what is the sum of 8

const findTwoPartsOfTheNumber = ((arr, targetNum) => {
  const correctNumbers = arr.map((num, index) => {
    let firstNumber = num;
    // console.log('num',num,'index',index);
    const arrayWeNeed = arr.filter((sub_num, sub_index) => {
      // console.log('sub_num',sub_num,'sub_index',sub_index);
      if (index != sub_index && (firstNumber + sub_num) === targetNum) {
        const passableArray = [firstNumber, sub_num] //aka first and second numbers that give the targetNum
        return sub_num; //passableArray gives the same output for some reason,it doesn't really matter.
      }
    })
    return arrayWeNeed
  })

  return correctNumbers;
  // return `there is no such numbers,that give ${targetNum}`;
})

console.log(findTwoPartsOfTheNumber(easierArray, 8));
console.log(findTwoPartsOfTheNumber(array1, 4));

Output
[[],[5],[3]]

for the first one

A: You can clean up the outpu by flatting the returned arrays :
return arrayWeNeed.flat();

and
return correctNumbers.flat();

const array1 = [1, 2, 3];
const easierArray = [1, 3, 5] //Let's assume number we search what is the sum of 8

const findTwoPartsOfTheNumber = ((arr, targetNum) => {
  const correctNumbers = arr.map((num, index) => {
    let firstNumber = num;
    // console.log('num',num,'index',index);
    const arrayWeNeed = arr.filter((sub_num, sub_index) => {
      // console.log('sub_num',sub_num,'sub_index',sub_index);
      if (index != sub_index && (firstNumber + sub_num) === targetNum) {
        const passableArray = [firstNumber, sub_num] //aka first and second numbers that give the targetNum
        return sub_num; //passableArray gives the same output for some reason,it doesn't really matter.
      }
    })

    return arrayWeNeed.flat();
  })

  return correctNumbers.flat();
  // return `there is no such numbers,that give ${targetNum}`;
})

console.log(findTwoPartsOfTheNumber(easierArray, 8));
console.log(findTwoPartsOfTheNumber(array1, 4));

However, using a recursive function could be simpler :

const answer = (arr, num) => {
  if (arr.length < 1) return;

  const [first, ...rest] = arr.sort();

  for (let i = 0; i < rest.length; i++) {
    if (first + rest[i] === num) return [first, rest[i]];
  }

  return answer(rest, num);
};

console.log(answer([1, 2, 3], 4));
console.log(answer([1, 3, 5], 8));

A: It looks like you are trying to leave .map() and .filter() beforehand, which you can't (without throwing an error). So I suggest a normal for approach for this kind of implementation:

const array1 = [1,2,3];
const easierArray = [1,3,5] //Let's assume number we search what is the sum of 8

const findTwoPartsOfTheNumber = (arr,targetNum) =>{
    for(let index = 0; index < arr.length; index++) {
        let firstNumber = arr[index];
        // console.log('num',num,'index',index);
        for(let sub_index = 0; sub_index < arr.length; sub_index++){
          const sub_num = arr[sub_index];
            // console.log('sub_num',sub_num,'sub_index',sub_index);
            if (index != sub_index && (firstNumber + sub_num) === targetNum){
                const passableArray = [firstNumber,sub_num]//aka first and second numbers that give the targetNum
                return passableArray; //passableArray gives the same output for some reason,it doesn't really matter.
            }
        }
    }

    return `there is no such numbers,that give ${targetNum}`;
}

console.log(findTwoPartsOfTheNumber(easierArray,8));
console.log(findTwoPartsOfTheNumber(array1,4));
console.log(findTwoPartsOfTheNumber(array1,10));

I've just grab your code and changed map and filter to for implementation.

A: There doesn't appear to be any requirement for using specific array functions (map, forEach, filter, etc) in the problem statement you listed, so the code can be greatly simplified by using a while loop and the fact that you know that the second number has to be equal to target - first (since the requirement is first + second == target that means second == target - first). The problem statement also doesn't say what to do if no numbers are found, so you could either return an empty array or some other value, or even throw an error.

const answer = (list, target) => {
  while (list.length > 0) { // Loop until the list no longer has any items
    let first = list.shift() // Take the first number from the list
    let second = target - first // Calculate what the second number should be
    if (list.includes(second)) { // Check to see if the second number is in the remaining list
      return [first, second] // If it is, we're done -- return them
    }
  }

  return "No valid numbers found" // We made it through the entire list without finding a match
}

console.log(answer([1,2,3], 3))
console.log(answer([1,2,3], 4))
console.log(answer([1,2,3], 7))

A: Map and filter are nice functions to have if you know that you need to loop into the whole array. In your case this is not necessary.
So you know you need to find two numbers, let's say X,Y, which belong to an array A and once added will give you the target number T.
Since it's an exercise, I don't want to give you the working code, but here is a few hints:

*

*If you know X, Y must be T - X. So you need to verify that T - X exists in your array.

*array.indexOf() give you the position of an element in an array, otherwise -1

*If X and Y are the same number, you need to ensure that their index are not the same, otherwise you'll return X twice

*Returning the solution should be simple as return [X,Y]

So this can be simplified with a for (let i = 0; i < arr.length; i++) loop and a if statement with a return inside if the solution exist. This way, if a solution is found, the function won't loop further.
After that loop, you return [] because no solution were found.
EDIT:
Since you want a solution with map and filter:
findTwoPartsOfTheNumber = (arr, tNumber) => {
    let solution = [];

    arr.map((X, indexOfX) => {
        const results = arr.filter((Y, indexOfY) => {
            const add = Y + X
            if (tNumber === add && indexOfX != indexOfY) return true;
            else return false;
        });

        if (results > 0) solution = [X, results[0]];
    })

    return solution;
}

A: You can also add all the values in the array to find the total, and subtract the total by the target to find the value you need to remove from the array. That will then give you an array with values that add up to the total.

let arr1 = [1, 3, 5]
const target = 6

const example = (arr, target) => {
  let total = arr.reduce((num1, num2) => {
    return num1 + num2
  })
  total = total - target
  const index = arr.indexOf(total)
  if (index > -1) {
    return arr.filter(item => item !== total)
  }
}

console.log(example(arr1, target))


text:
Q: Is It possible to change the property from hover to click during a specific break point using media queries in React? Right now my li tag has a mouseenter and mouseleave effect, but when I shrink my site down to mobile view, I want it to change to onClick instead.
So the code below shows my menu with the dropdown. Whenever I click on the hamburger menu in mobile view, it will trigger the active class on the
 and open up the mobile view. Then when I hover over the li tag it will display the dropdown menu.
Instead of it displaying when I hover, I need it to display when I click the ul tag only at the breakpoint of 960px.

        <Link to='/' className='nav-links' onClick={() => setClick(false)}>
          Home
        </Link>
        {dropdown && <Dropdown />}

        <Link
          to='/services'
          className='nav-links'
          onClick={() => setClick(false)}
        >
          Services
        </Link>

Is that something that is posssible to do? Or would I have to completely redo my code?

A: It most definitely is. And there are many options of how you could do it, these are some that come to my mind at first:
Option #1:
You could render 2 completely different things based on media query, something like this:

 {}}>

 {}} onMouseEnter={() => {}}>

Option #2:
You could disable certain functions based on current viewport
const onMouseEnter = () => {
   if (window.width > something) {
     return;
   }

   do something otherwise
}

const onClick = () => {
   if (window.width < something) {
     return;
   }

   do something otherwise
}

I would recommend taking a look at some of these articles & modules:
Medium post about media queries in React
react-media
react-responsive

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Play In-App Billing Security Here is part of Security and Design section of In-App Billing on Google's site:

Perform signature verification tasks on a server
If practical, you should perform signature verification on a remote server and not on a device. Implementing the verification process on a server makes it difficult for attackers to break the verification process by reverse engineering your .apk file. If you do offload security processing to a remote server, be sure that the device-server handshake is secure.

so here, does "makes it difficult" mean that no matter what, it will always be possible to hack in-app purchases?

A: This means your developed app, which you can upload to play store, is more secure from cracking it if you use a signature verficiation on a remote server. Almost every app can be decompiled, but if you store your verification process on a remote server, a cracker must get this too. He can not see it directly in the reverse enginneered source.
There are many possibilities to make your .apk more secure from cracking it.


text:
Q: meteor deps not reactive I've spent days trying to figure out why the template is not updating. Please help!  Below is the relevant code.
@Listings = new Meteor.Collection 'listings'

class Map
  constructor : (map_canvas=null, map_options=null) ->
    @listings = Listings.find()
    @observer = new Deps.Dependency()

  viewable_listings : ->
    @observer.depend()
    @listings

  set_listings : (listings) ->
    @listings = listings
    @observer.changed()

So viewable_listings() is set as a template helper
Template.listings.helpers
  listings : map.viewable_listings()

But when changing the value of @listings, the template does not update.  For example
map.set_listings Listings.find({}, {limit:3})

Does absolutely nothing.  No reactive from the listings template.  However changing values in the db via Listings.remove(...) works as usual.

A: The listings helper isn't a function so dependency tracking won't work. The helper will always be the result of the first call to  map.viewable_listings(). That value happens to be a cursor so it makes sense that something would render, but would not update when you want it to. Give this a try:
Template.listings.helpers
  listings: ->
    map.viewable_listings()


text:
Q: SQLite CREATE TRIGGER: What is the default if neither BEFORE nor AFTER has been specified? From SQLite documentation for CREATE TRIGGER, one can see that BEFORE, AFTER or INSTEAD OF may be ommited.
So, when is trigger fired when none is specified? Where is it documented?

A: sqlite> create table t(x, triggervalue);
sqlite> insert into t(x) values(1);
sqlite> create trigger tt
   ...> update of x on t
   ...> begin
   ...>   update t set triggervalue = x;
   ...> end;
sqlite> update t set x = 2;
sqlite> select triggervalue from t;
1

So the default happens to be BEFORE.
This is not documented anywhere, and the syntax without BEFORE/AFTER looks so ugly that I guess nobody thinks of using it.


text:
Q: Write elements to textarea using jQuery I want to get a text from a  and add some attributes to the text and show it in another  when a button is pressed.
Here is a part of my code - If I use console.log() the correct text will be logged, but the append(x) only writes the option[i] value without any HTML codes.
What should be the solution here?

var options;
$(function() {
  options = $('div#Thelper2_container textarea').val().split('\n');
  $.fillTextArea();

});

$.fillTextArea = function() {
  for (let i = 0; i < options.length; i++) {
    var y = i + 1;
    var x = String('' + options[i] + '\n');
    $('div#Thelper4_container textarea').append(x);
  }
}

  <textarea rows="5" cols="100">Line 1
Line 2
</textarea>

  <textarea rows="5" cols="100"></textarea>

A: Use val instead of append. Append is for non-form field container elements
Although you CAN append to a textarea, when you append, you append HTML and not text.
Also you have too many s and spans do not have values. I changed to  data-value
Lastly I filter empty lines

const $txtarea = $('#Thelper2_container textarea');
const $output =  $('#Thelper4_container textarea');
const splitLines = val => val
  .split('\n')
  .filter(line => line.trim() !== "") // drop empty lines
  .map((line,i) => `<span class="textToSelect" data-value="${i+1}">${line.trim()}</span>`)
  .join("\n");

$(function() {
  $output.val(splitLines($txtarea.val()));
});

  <textarea rows="5" cols="100">Line 1
Line 2
</textarea>

  <textarea rows="5" cols="100"></textarea>

A: Try this:
$('div#Thelper4_container textarea').append(document.createTextNode(x));

Please note the 'document.createTextNode'.

A: You're appending another \n at the end of the string without opening it anywhere.
Try this code and see if it works:
var x = String('' + options[i] + '\n');


text:
Q: Negative threshold in roc_curve and precision_recall_curve I am trying to find optimal threshold that can differentiate the two classes well but i am getting negative thresholds using roc_curve and precision_recall_curve.
I have build a CNN-LSTM architecture. I am not sure if these information are enough to find the solution, but i want to know what would be the first thing you will check if you get negative threshold.
Here are the functions
 def optimal_threshold_precision_recall_curve(self,gt, pmap):
    """Function to return an optimal thresholding value of the image
    """
    gt = gt.flatten()
    pmap = pmap.flatten()
    precision, recall, thresholds = precision_recall_curve(gt,pmap, pos_label=1)
    optimal_thresholds = sorted(list(zip(np.abs(precision - recall), thresholds)), key=lambda i: i[0], reverse=False)[0][1]
    # optimal_mask = np.where(pmap>optimal_thresholds,1,0)
    plt.figure()
    plt.plot(recall,precision)
    plt.savefig('test.png')
    return optimal_thresholds

def auc_thresh(self,label, pred,mode):
    fpr, tpr, thresholds = roc_curve(label.flatten(), pred.flatten())
    roc_auc = auc(fpr, tpr)
    gmeans = np.sqrt(tpr * (1-fpr))
    ix = np.argmax(gmeans)
    print('Best %s Threshold=%f, G-Mean=%.3f' % (mode,thresholds[ix], gmeans[ix]))
    return thresholds[ix]

This is how graph look like, code to plot this image is optimal_threshold_precision_recall_curve function


text: Q: Как делать zoom относительно позиции указателя мыши, можно пример? Доброго времени суток, есть панель, вложенная в JScrollPane, как сделать zoom содержимого панели, относительно позиции курсора мыши, а не верхнего левого угла(точки 0,0)? Можно пример?


text:
Q: Dangling branch? It's probably an already asked question, but I just don't know what are the right names to call the issue - so please guide me or answer (yes, I've seen this question but couldn't get too much from the answer).
I am trying to git pull but receiving the following message:
You asked me to pull without telling me which branch you
want to merge with, and 'branch.2012_05_09_my_branch.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.

If you often merge with the same branch, you may want to
use something like the following in your configuration file:
    [branch "2012_05_09_my_branch"]
    remote = <nickname>
    merge = <remote-ref>

    [remote "<nickname>"]
    url = <url>
    fetch = <refspec>

See git-config(1) for details.

It probably looks like my working directory is kinda "hanging" without being attached to any branch, am I right? If so - please advice on how to get it connected back to the proper branch (2012_05_09_my_branch for example). Probably I am even wrong with that (being a total GIT newbie), in this case please explain what's happening and what can I do about it.
Refined question: what do I need to do to run git push and git pull successfully without getting the message above?
Update: when I run git branch I get:
* 2012_05_09_my_branch
  master

Which kinda probably means that I am on my local 2012_05_09_my_branch branch which is not connected to any of the remote branches?
Update N2: Why do I need to do `--set-upstream` all the time? - very worth reading as a complementary material (found only now).

A: It is not that your working dir is not attached to a branch, but you do not have setup what is peer branch on the remote for your local branch. You can "connect" them together with:
git branch --set-upstream 2012_05_09_my_branch remotes/<your remote>/2012_05_09_my_branch

Where < your remote > is the server server as defined in .git/config, usually (when working with one server) is origin
EDIT: the safer way is to use remotes/<remote>/<branch> instead of <remote>/<branch>

A: git status

will help you find out on which branch you are (if any). The command
git branch

will give a list about the local branches you have (git branch -a lists the remote ones as well). And of course you can use
git checkout <branchname>

to turn your working copy to the chosen branch.

A: When you create a local branch, and want to put it on remote repository you need to run this command:
$ git push origin 2012_05_09_my_branch


text:
Q: failure in creating the client socket I'm trying to connect two emulators in android,one is considered the server and one the client.
I use a text view and a handler to post the state of client and the server.
The problem with my client is that I can get to create the socket and usually I get an error message posted on the text view.Not only that,but when I try to press buttons on the client app I get force close and I don't know why cause I have a different thread for client's connection:)
Can someone please tell me what I'm doing wrong?
Here is my code:
public class screen1 extends Activity {
private TextView clientState;
private String serverIpAddress="10.0.2.2";
public static final int ClientPort = 8080;
private boolean connected = false;
private Handler handler=new Handler();
Socket socket;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screen1);
    clientState = (TextView) findViewById(R.id.client_Status);

    Button b = (Button)findViewById(R.id.mainMenu);
    b.setOnClickListener(new View.OnClickListener() {
       public void onClick(View arg0) {
       Intent i = new Intent(screen1.this, screen2.class);
       startActivity(i);
       }
    });

   Thread cThread=new Thread(new ClientThread());
  cThread.start();
  }
public class ClientThread implements Runnable{
    public void run()
    {
        try
        {
            InetAddress serverAddr=InetAddress.getByName(serverIpAddress);
            handler.post(new Runnable(){
                public void run(){
                    clientState.setText(" try to connect!");
                }
            });
            socket=new Socket(serverAddr,ClientPort);

            handler.post(new Runnable(){
                public void run(){
                    clientState.setText("Connected!");
                }
            });

        }
        catch(Exception e){
            handler.post(new Runnable(){
                public void run(){
                    clientState.setText("Error");
                    }
            });

            e.printStackTrace();
        }

    }
}
protected void onStop() {
    super.onStop();
    try {
         // make sure you close the socket upon exiting
         socket.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
}

}

A: I'm not good at Android programming, but I see that you're entering an infinite loop in your code:
while(true){
        handler.post(new Runnable(){
            public void run(){
                clientState.setText("Connected!");
            }
        });
        }


text:
Q: PHP WebSocket Server using SSL I am trying to use websockets in my application which running in this environment :
- Debian 8
- Apache 2.4.10
- PHP 5.6.30
I use devristo/phpws package, and just trying to make their example works (time).
Everything is ok on a HTTP context website and ws:// protocol connection, but when i try to put it on an HTTPS website and using wss:// protocol, it fail.
I start the server via "php -q server.php", file content :
<?php
require_once("vendor/autoload.php");
use Devristo\Phpws\Server\WebSocketServer;

$loop = \React\EventLoop\Factory::create();

// Create a logger which writes everything to the STDOUT
$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);

// Create a WebSocket server using SSL
$server = new WebSocketServer("wss://X.X.X.X:9300", $loop, $logger);

$loop->addPeriodicTimer(0.5, function() use($server, $logger){
    $time = new DateTime();
    $string = $time->format("Y-m-d H:i:s");
    $logger->notice("Broadcasting time to all clients: $string");
    foreach($server->getConnections() as $client)
        $client->sendString($string);
});

// Bind the server
$server->bind();

// Start the event loop
$loop->run();

In other hand, i have a time.html, which contain :

    <title>WebSocket TEST</title>

Server Time

The server start running without problems :
2017-11-24T11:47:57+01:00 NOTICE (5): phpws listening on ssl://X.X.X.X:9300
2017-11-24T11:47:57+01:00 NOTICE (5): Broadcasting time to all clients: 2017-11-24 11:47:57
2017-11-24T11:47:58+01:00 NOTICE (5): Broadcasting time to all clients: 2017-11-24 11:47:58
....

When i go on my page time.html in browser, the following JavaScript error comes in chrome :
VM725:164 WebSocket connection to 'wss://X.X.X.X:9300/' failed: Error in connection establishment: net::ERR_SSL_VERSION_OR_CIPHER_MISMATCH

At the same time, server produces this error output :
PHP Warning:  stream_socket_accept(): SSL_R_NO_SHARED_CIPHER: no suitable shared cipher could be used.  This could be because the server is missing an SSL certificate (local_cert context option) in /var/www/web/sofive/k-zam/web/vendor/devristo/phpws/src/Devristo/Phpws/Server/WebSocketServer.php on line 141

Warning: stream_socket_accept(): SSL_R_NO_SHARED_CIPHER: no suitable shared cipher could be used.  This could be because the server is missing an SSL certificate (local_cert context option) in /var/www/web/sofive/k-zam/web/vendor/devristo/phpws/src/Devristo/Phpws/Server/WebSocketServer.php on line 141
PHP Warning:  stream_socket_accept(): Failed to enable crypto in /var/www/web/wstest/vendor/devristo/phpws/src/Devristo/Phpws/Server/WebSocketServer.php on line 141

Warning: stream_socket_accept(): Failed to enable crypto in /var/www/web/wstest/vendor/devristo/phpws/src/Devristo/Phpws/Server/WebSocketServer.php on line 141
PHP Warning:  stream_socket_accept(): accept failed: Success in /var/www/web/wstest/vendor/devristo/phpws/src/Devristo/Phpws/Server/WebSocketServer.php on line 141

Warning: stream_socket_accept(): accept failed: Success in /var/www/web/wstest/vendor/devristo/phpws/src/Devristo/Phpws/Server/WebSocketServer.php on line 141

So i think i miss a certificate to pass to socket_context_create ? If yes, how to create this certificate, are there specs (ssl version ? etc), or do i need to pass the same as the one used for https website (generated with let's encrypt certbot) ?


text:
Q: Displaying spinner onclick I built a Spinner and animated it with CSS, and now I'm trying to hide the spinner and display it when the button has been clicked. So far,I  have written this code and it doesn't show up when I click the submit <button>
I hid the spinner with display:none and tried to use JavaScript to change the
 to display:block, but it doesn't work.
CSS:
* {
margin: 0;
padding: 0;
}

.loader {
   display: none;
   top: 50%;
   left: 50%;
   position: absolute;
   transform: translate(-50%, -50%);
}

.loading {
   border: 2px solid #ccc;
   width: 60px;
   height: 60px;
   border-radius: 50%;
   border-top-color: #1ecd97;
   border-left-color:  #1ecd97;
   animation: spin 1s infinite ease-in;
}

@keyframes spin {
   0% {
       transform: rotate(0deg);
   }
   100% {
       transform: rotate(360deg);
   }
}

JavaScript:
 function spinner() {
 document.getElementsByClassName("loader").style.display = "block";
 }

HTML:
<button type="submit" class="sbtn btn btn-secondary btn-c"
onclick="spinner()" >Log in</button>

I'm new with Javascript so I figured I'd get some pointers here.

A: If you want to add a style to your spinner you have to get the first element returned by the function getElementsByClassName.
getElementsByClassName returns a list with the elements with that specific class.
getElementById returns one element, with the given Id.
I sugest in your case, to give an ID to the loader and do getElementById.
But if you want to use getElementsByClassName you can do the following:
document.getElementsByClassName("loader")[0].style.display = "block";

Here's a working spinet:

* {
  margin: 0;
  padding: 0;
}

.loader {
  display: none;
  top: 50%;
  left: 50%;
  position: absolute;
  transform: translate(-50%, -50%);
}

.loading {
  border: 2px solid #ccc;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border-top-color: #1ecd97;
  border-left-color: #1ecd97;
  animation: spin 1s infinite ease-in;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
<button type="submit" class="sbtn btn btn-secondary btn-c" onclick="spinner()">Log in</button>

A: You didn't let us know where do you want to add the spinner so I created
 which will contain the spinner's animation like so:
HTML:
<button type="submit" id="btn" class="sbtn btn btn-secondary btn-c">Log in</button>

CSS:
* {
  margin: 0;
  padding: 0;
}

.loader {
  display: none;
  top: 50%;
  left: 50%;
  position: absolute;
  transform: translate(-50%, -50%);
}

.loading {
  border: 2px solid #ccc;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border-top-color: #1ecd97;
  border-left-color:  #1ecd97;
  animation: spin 1s infinite ease-in;
}

@keyframes spin {
  0% {
      transform: rotate(0deg);
  }
  100% {
      transform: rotate(360deg);
  }
}

JavaScript:
function spinner() {
    const spinnerDisplayer = document.querySelector('.spinner-displayer');
    const btn = document.getElementById('btn');

    btn.addEventListener('click', () => {
    spinnerDisplayer.classList.add('loading');
  })
}

spinner();

Check this working code sample.
I woud suggest you to not use inline event handlers on your HTML, it's a bad idea.

A: Try this approach  https://codepen.io/jmalatia/pen/HkmaA

<button type="button" class="btn btn-primary btn-lg " id="load" data-loading-text=" Processing Order">Submit Order</button>

<button type="button" class="btn btn-primary btn-lg" id="load" data-loading-text=" Processing Order">Submit Order</button>

$('.btn').on('click', function() {
    var $this = $(this);
  $this.button('loading');
    setTimeout(function() {
       $this.button('reset');
   }, 8000);
});

A: Without your full html code, it's hard to interpret what the loader class is even there for.

<button type="submit" class="sbtn btn btn-secondary btn-c"
onclick="spinner()" >Log in</button>

This approach works, I've added an ID of #spinner to your spinner image and have it display none. Then on button click it sets the display to block.


text:
Q: Google Chart Column chart to take whole month space I have a google column chart which I pass in a month and a year, and format the axis to display it in the MMM yyyy format. But on the actual chart and the grid-lines, the google chart inserts a default day as 1. Therefore, the chart doesn't look nice.
I want a whole column to cover a whole month and am not sure how to achive this.

My code is
static drawChartIssuesPerMonthForCompany(data) {
    let dataTable = new google.visualization.DataTable();

    dataTable.addColumn("date", "Months");
    dataTable.addColumn("number", "Issue Count");

    data.forEach(row => {
        console.log(data);
        dataTable.addRow([new Date(row.yearId, row.monthId - 1), row.issueCount]);
    });
    let chart = new google.visualization.ColumnChart(document.getElementById("detailedCharts"));

    let options = {
        title: "Monthly issues",
        hAxis: {
            title: "Months",
            gridelines: {
                count: -1
            },
            format: 'MMM yyyy'
        },
        vAxis: {
            gridlines: { color: 'none' },
            minValue: 0,
            title: "Issue Count",
            format: '#',
            maxValue: 4
        }
    };

    chart.draw(dataTable, options);

}

A: try using a "string" for the x-axis, instead of "date"
dataTable.addColumn("string", "Months");

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages:['corechart']
});

function drawChart() {
    let data = [
      {yearId: 2017, monthId: 2, issueCount: 9},
      {yearId: 2017, monthId: 3, issueCount: 2},
      {yearId: 2017, monthId: 4, issueCount: 8}
    ];

    let dataTable = new google.visualization.DataTable();

    dataTable.addColumn("string", "Months");
    dataTable.addColumn("number", "Issue Count");

    let formatDate = new google.visualization.DateFormat({
      pattern: 'MMM yyyy'
    });

    data.forEach(row => {
        dataTable.addRow([formatDate.formatValue(new Date(row.yearId, row.monthId - 1)), row.issueCount]);
    });
    let chart = new google.visualization.ColumnChart(document.getElementById("detailedCharts"));

    let options = {
        title: "Monthly issues",
        hAxis: {
            title: "Months",
            gridelines: {
                count: -1
            }
        },
        vAxis: {
            gridlines: { color: 'none' },
            minValue: 0,
            title: "Issue Count",
            format: '#',
            maxValue: 4
        }
    };

    chart.draw(dataTable, options);
}


text:
Q: What is the usage of the magic methods __construct() and __destruct(). Are they always required? What is the usage of the magic methods __construct() and __destruct(). Are they always required?
Need a nice simple answer to this, it's a little confusing.

A: They are not required.
Construct is called upon initialization, that is when the object is created/constructed.
Destruct is called on clean up.
Example:
class Foo
{
    function __construct()
    {
        echo "start";
    }

    function __destruct()
    {
        echo "end";
    }
}

$foo = new Foo(); // outputs start
echo ' : ';
unset( $foo );    // outputs end
echo ' ! ';

Above snippet outputs start : end !. If we don't use unset the destructor will still be called in the end of the script when cleaning up, the output would then be: start :  ! end
Link
http://php.net/manual/en/language.oop5.decon.php

A: About __construct(), it gives you the possibility to do some stuff with your newly created object and to overwrite the __construct() method of a parent class.
So it might not be required (neither are), but if a class extends another class, it might be required to add for example a constructor to avoid the automatic calling of a parent constructor.

A: The most common use I have for construct is to initialise class variables to a default value. I've not had a need to use destruct yet though.


text:
Q: SetLayoutParams null pointer execption I am getting a null pointer exeption when im trying to debug my app. I think its becuse in my fragment onCreateView() method, container is null and when android.view.View.setLayoutParams(android.view.ViewGroup$LayoutParams) is called there is an exeption. I dont know why container s null. I added the fragment to the activity in XML file and when i run the app in "run mode" the fragment is displayed in the activity. I only see this error when i try to debug.
Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
   // moviePosterFragment = new MoviePosterFragment();
    moviePosterFragment = (MoviePosterFragment)getSupportFragmentManager().findFragmentById(R.id.fragment);

   FetchMovies(1);

}

Activity xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout

android:id="@+id/container"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">

<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
    android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
        android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/fragment"
android:name="com.example.user.popmovie.fragments.MoviePosterFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:layout="@layout/fragment_main" />

</android.support.design.widget.CoordinatorLayout>

Fragment:
 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    mlayoutManager = new GridLayoutManager(getActivity(),NUM_COLUMNS);

   mRecyclerView = (RecyclerView)rootView.findViewById(R.id.pop_movies_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(mlayoutManager);
    //set adapter with empty data
    GridAdapter = new GridViewAdapter(getContext(),movieItemArray,mRecyclerView);
    mRecyclerView.setAdapter(GridAdapter);
  //  mProgressWheel = (ProgressWheel)  rootView.findViewById(android.R.id.progress);
   endlessScroll();
    Activity act =  getActivity();
    int a =0;
//      rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
    if (container == null) {
        Log.i("in movieposterfragment", "onCreateView(): container = null");
    }
    else
    {
        Log.i("in movieposterfragment", "onCreateView(): container != null");
    }
    return rootView;

}

Fragment XML:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id = "@+id/fragment"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
tools:showIn="@layout/activity_main"

tools:context=".MoviePosterFragment">

<!-- Add a RecyclerView to fragment layout-->
<android.support.v7.widget.RecyclerView
    android:id="@+id/pop_movies_recycler_view"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</FrameLayout>

Stack trace
03-06 20:33:20.675 27556-27556/? E/Zygote: MountEmulatedStorage()
03-06 20:33:20.675 27556-27556/? E/Zygote: v2
03-06 20:33:20.695 27556-27556/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime: FATAL EXCEPTION: main
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime: Process: com.example.user.popmovie, PID: 27556
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.popmovie/com.example.user.popmovie.activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setLayoutParams(android.view.ViewGroup$LayoutParams)' on a null object reference
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread.access$900(ActivityThread.java:177)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:145)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5951)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setLayoutParams(android.view.ViewGroup$LayoutParams)' on a null object reference
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.view.LayoutInflater.parseInclude(LayoutInflater.java:928)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:257)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:110)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at com.example.user.popmovie.activities.MainActivity.onCreate(MainActivity.java:38)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:6289)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread.access$900(ActivityThread.java:177)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:145)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5951)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
03-06 20:34:57.049 27556-27556/com.example.user.popmovie E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)


text:
Q: Dynamic localization of digits from a number from images in Python I am working on a dynamic digit localization problem from a number in images in Python. What I exactly mean is: if I have an image like this:

I want to separate all the digits like, 8, 0, 1 like this:

I have tried and explored with MSER, but did not get any far with. And the main problem is, the number can have any number of digits. Another example can be:

And the number should be separated as 2, 2 like this:

Is there any other approach that I can take using open cv or any other packages available in Python?


text:
Q: Get the string of the query that fired a trigger I am creating a control table in a PostgreSQL database, this table should register the query that fired a trigger in a specific table. For instance
if I do
insert into employees('bob');

I would like to be able to capture the string 'insert into employees('bob');' inside a trigger associated with employees table. It doesn't matter if the trigger is before or after.

A: Use the function current_query() in the trigger function.
insert into control_table(query_text)
select current_query();

The trigger should be for each statement.


text:
Q: como transformar e atualizar o valor de um dicionario para uma lista em python Eu tenho um dicionario no seguinte formato:
dicionario = {'/tmp/javac': '192.168.56.105', '/tmp/java': '192.168.56.105', '/opt/.java': '192.168.56.105', '/opt/testejava': '192.168.56.105'}

E eu queria transformá-lo para ficar assim:
dicionario = {'/tmp/javac': ['192.168.56.105'], '/tmp/java': ['192.168.56.105'], '/opt/.java': ['192.168.56.105'], '/opt/testejava': ['192.168.56.105']}

para que depois eu pudesse atualizar e mudar os valores:
dicionario = {'/tmp/javac': ['192.168.56.105', '192.168.56.106', '192.168.56.107'], '/tmp/java': ['192.168.56.105', '192.168.56.106', '192.168.56.107'], '/opt/.java': ['192.168.56.105', '192.168.56.106', '192.168.56.107'], '/opt/testejava': ['192.168.56.105', '192.168.56.106', '192.168.56.107']}


text:
Q: 'JSONKit.h' not found when I run 'Test' of my Project in Xcode 5 I used CocoaPods to add JSONKit to project.
Now I want to create a unit test of a function in my project which uses JSONKit function.
When I hit ⌘U to run the test, I got this error message:

I am positive the project can compile can run without problem when I hit ⌘R ('Run')
What is the reason for the error message? How can I fix it?
I am using XCode 5.0.2

A: It is actually a Pod file setup problem.
I need to add the following as the first line in my podifle.
link_with ['Questions', 'QuestionsTests']

Then rerun pod install and reopen workspace in xcode.


text:
Q: JOptionPane with file output I'm new to Java. I'm taking an online class this semester. The book which we are using isn't the greatest. I've tried searching around for answers online, but I'm coming up short. Maybe one of you guys can help me out :)
Basically the program below is suppose to prompt the user to enter info, the program then calculates the deductions and outputs the info to a .txt file. It runs and complies without error. The dialog boxes pop up, but no data is being written to the file. The .txt file is saved in the same folder btw. Any ideas?
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;

public class PaycheckCalculator
{

    static final double FEDERAL_TAX = .15, STATE_TAX = .035, SOCIAL_SECURITY = .0575, MEDICARE_MEDICAID = .0275,PENSION = .05;
    static final int HEALTH_INSURANCE = 75;

    public static void main (String[] args) throws FileNotFoundException
    {

        String employeeName;
        String inputStr;

        double grossPay, netPay, federal, state, social, medicare, pension;
        int healthInsurance;

        PrintWriter outFile = new PrintWriter ("paycalc.txt");

        employeeName = JOptionPane.showInputDialog ("Please enter your name: ");

        inputStr = JOptionPane.showInputDialog ("Please enter your monthly gross pay: ");
        grossPay = Double.parseDouble (inputStr);

        federal = (grossPay * FEDERAL_TAX);
        state = (grossPay * STATE_TAX);
        social = (grossPay * SOCIAL_SECURITY);
        medicare = (grossPay * MEDICARE_MEDICAID);
        pension = (grossPay * PENSION);

        netPay = (grossPay - federal - state - social - medicare - pension - HEALTH_INSURANCE);

        outFile.println (employeeName);
        outFile.printf ("Gross Amount: %.2f%n", grossPay);
        outFile.printf ("Federal Tax: %.2f%n", federal);
        outFile.printf ("State Tax: %.2f%n", state);
        outFile.printf ("Social Security Tax: %.2f%n", social);
        outFile.printf ("Medicare\\Medicaid Tax: %.2f%n", medicare);
        outFile.printf ("Pension Plan: %.2f%n", pension);
        outFile.printf ("Health Insurance: $" + HEALTH_INSURANCE);
        outFile.printf ("Net Pay: %.2f%n", netPay);

        System.exit(0);
        outFile.close();

    }
}

A: You have to close your PrintWriter before your application exits.
You can either remove the System.exit(0); line (which is useless) or put it after the close() operation.
This way the data will be flushed into your paycalc.txt file before the application exits.

A: import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.File;
import javax.swing.JOptionPane;

public class PaycheckCalculator
{

    static final double FEDERAL_TAX = .15, STATE_TAX = .035, SOCIAL_SECURITY = .0575, MEDICARE_MEDICAID = .0275,PENSION = .05;
    static final int HEALTH_INSURANCE = 75;

    public static void main (String[] args)
    {

        String n = JOptionPane.showInputDialog("enter file name");
        File fileObject = new File(n);
        while (fileObject.exists())
        {
            JOptionPane.showMessageDialog(null,"the file "+fileObject+ "already exists ","Error dialog",JOptionPane.ERROR_MESSAGE);
            JOptionPane.showInputDialog("enter file name again please");
            String g = JOptionPane.showInputDialog("enter file name");
            fileObject = new File(g);
        }
        PrintWriter outFile = null;
        String employeeName = JOptionPane.showInputDialog("Enter your name");
        String inputStr;
        double grossPay, netPay, federal, state, social, medicare, pension;
        int healthInsurance;

        try
        {
          outFile = new PrintWriter(new FileOutputStream(fileObject));
        }
        catch(FileNotFoundException e)
        {
            System.out.println("this file could not be opened");
            System.exit(0);
        }

          inputStr = JOptionPane.showInputDialog ("Please enter your monthly gross pay: ");


text:
Q: Partial method within partial class error (now with screen shots!) I'm getting an error on my partial method and I'm not sure why. I figure common errors relate to not naming the two partial classes exactly the same and what not, but that's not the case here.
So, I have some generated code, which can be seen here:

Well, that's not all of it, but I think it's the relevant part.
So, I wanted to create another partial class so I could house these partial methods and get them to have some functionality. So, I created a class and added just one of the functions, as can be seen here, to test:

Now as I've read the guides online, this should work. I mean obviously I've not understood everything, but I don't know. Oh, here's the error, by the way:

I guess that's a little hard to read. It says,

No defining declaration found for implementing declaration of partial method WCFServiceSQLAccess.DomainContext.HydraDomainDontext.UpdateClients (WCFServiceSQLAccess.DomainContext.Client).

Hopefully you can offer some suggestions.

A: It's very simple - you've got two different classes: HydraDomainContext and HydraDataContext. Either change the name of the generated class, or the name of the manually-written class - they'll have to match in order to create one complete class with the partial method implementation matching the declaration.

A: You have Hydra Data Context and Hydra Domain Context for the names of the partial class.


text:
Q: How to invert horizontal scrolling Apple Mouse I understand that I must disable Natural scrolling (but it inverses up and down scrolling as well) But it doesn't help I want just inverse left to right to left scrolling.

A: In this article, this software is suggested: Scroll Reverser


text:
Q: Customize UIButton to make compatible to iPhone 5 I am working on my app to customize button accordingly. However once I change my button accordingly, now it has became irresponsive. You could see my code as follows. By the way, this button still works when I run on iPhone 4. It is really strange!
once I change my button position it works, but it wont work the position I want!
   float screenSizeHeight=[UIScreen mainScreen].bounds.size.height;

   if(screenSizeHeight==568)
   [positionButton setFrame:CGRectMake(184,280,77,30)];

   if(screenSizeHeight==480)
   [positionButton setFrame:CGRectMake(184,240,77,30)];

Hand Bag button is not working!

A: Check your condition :
 if(screenSizeHeight==568)

In both cases you have used screenSizeHeight == 568 so replace one with screenSizeHeight = 480
Hope it helps you.

A: Check your Default-568h.png image get added or not. If it isn't added , you mainscreen returns bounds as 320x480.
Note : 1) If you rotate device , check your main screen bounds. It may lead to confusion. You can try Better way to use it.
2) This Default-568h.png is only allowed when building an app using Xcode 4.5 and the iOS 6 SDK
3) When you ask a UIScreen for it's Bounds you get the bounds of the screen, which is the whole device screen. (the status bar is part of the screen)


text:
Q: Using powershell I'd like to get a list of people who have admin privileges for a domain? I'd like to get a list of all people with admin privileges with powershell. What is the most optimal way to accomplish that?
Which user property should I look at?

A: get-adgroupmember 'domain admins' | select name,samaccountname
get-adgroupmember 'enterprise admins' | select name,samaccountname

A: I realize this question is old, and Noah's answer helped get me in the ballpark. I just want to expand on it a little bit more. If you have multiple domains in your environment you can do something like this:
Get-ADGroupMember -Server "domain-name-here" -Identity "Domain Admins" -Recursive | Select Name

If you want to also see if which accounts are enabled or disabled:
Get-ADGroupMember -Server "domain-name-here" -Identity "Domain Admins" -Recursive | Get-ADUser | Select Name, Enabled

Or if you only want to see enabled accounts:
Get-ADGroupMember -Server "domain-name-here" -Identity "Domain Admins" -Recursive | get-aduser -Properties Description | Where {$_.Enabled -eq $true} | Select Name

A: dsquery * -filter (samaccoutname="domain admin") | dsget group -members -expand >>RESULT.txt

A: The other examples show how to get the easiest display of who has "admin" access to a domain but don't overlook the fact that "admin" access can be directly assigned to any user or group object on the domain object itself.  Simply checking for members of "domain admins" and "enterprise admins" is not going to show you the whole picture.
As a starting point you could start with this and then investigate further:
(Get-ACL 'AD:\DC=MYDOMAIN,DC=local').Access | Format-Table IdentityReference,ActiveDirectoryRights,AccessControlType -AutoSize


text:
Q: Adding columns to an existing table I have two tables that look something like-
39.3278 2990.3 4503.98 0 -1859.37
35.7833 3014.8 1281.98 0 -3497.95

and
0.0255 28.6 -9.954 -2.612
0.0724 28.7 -1.031 -1.435

I am trying to generate a grand table by joining these two tables that should look something like this-
39.3278 2990.3 4503.98 0 -1859.37 0.0255 28.6 -9.954 -2.612
35.7833 3014.8 1281.98 0 -3497.95 0.0724 28.7 -1.031 -1.435

The code that I am using is-
data1 = {{39.3278, 2990.3, 4503.98, 0, -1859.37}, {35.7833, 3014.8,
1281.98, 0, -3497.95}};
data2 = {{0.0255, 28.6, -9.954, -2.612}, {0.0724,
28.7, -1.031, -1.435}};
data = Transpose@Join[Transpose@data1, data2];
TableForm[data]

But above code is showing the error that levels can not be transposed. What is the possible solution to this problem?

A: d1 = {{39.3278`, 2990.3`, 4503.98`, 0, -1859.37`}, {35.7833`, 3014.8`, 1281.98`,
    0, -3497.95`}};
d2 = {{0.0255`, 28.6`, -9.954`, -2.612`}, {0.0724`, 28.7`, -1.031`, -1.435`}};

Join[d1, d2, 2]

{{39.3278, 2990.3, 4503.98, 0, -1859.37, 0.0255, 28.6, -9.954, -2.612},
 {35.7833, 3014.8, 1281.98, 0, -3497.95, 0.0724, 28.7, -1.031, -1.435}}


text:
Q: Get week number where the weeks start counting from first Monday in April until the first Monday next April in PHP I am trying to achieve the following:
For reporting purposes our week numbers begin from the first Monday in April each year.
I am creating a calendar using PHP in the following format:
M T W T F S S
At the end of each row of that month I want to display the week number, starting at 1 where the first Monday in April will be week one all the way up to the next first Monday in April (next year) where it starts from one again.
I am struggling with the logic - can any one suggest a solution?
Thanks
EDIT see my code below, basically what I am trying to do is instead of having the week number from jan 01, have it from the first Monday in April:
<?php
$monthNames = Array("January", "February", "March", "April", "May",     "June", "July",
"August", "September", "October", "November", "December");
?>

<?php
if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("n");
if (!isset($_REQUEST["year"])) $_REQUEST["year"] = date("Y");
?>

<?php
$cMonth = $_REQUEST["month"];
$cYear = $_REQUEST["year"];

$prev_year = $cYear;
$next_year = $cYear;
$prev_month = $cMonth-1;
$next_month = $cMonth+1;

if ($prev_month == 0 ) {
    $prev_month = 12;
    $prev_year = $cYear - 1;
}
if ($next_month == 13 ) {
    $next_month = 1;
    $next_year = $cYear + 1;
}
?>

  <a href="<?php echo $_SERVER["PHP_SELF"] . "?month=". $prev_month . "&year=" . $prev_year; ?>" style="color:#FFFFFF">Previous
<a href="<?php echo $_SERVER["PHP_SELF"] . "?month=". $next_month . "&year=" . $next_year; ?>" style="color:#FFFFFF">Next

<?php echo $monthNames[$cMonth-1].' '.$cYear; ?>

M
T
W
T
F
S
S
Week No

<?php
$timestamp = mktime(0,0,0,$cMonth,1,$cYear);
$maxday = date("t",$timestamp);
$thismonth = getdate ($timestamp);
//$startday = $thismonth['wday'];
$startday = $thismonth['wday']-1;

$firstDateMonth = 0;

function roundToNearestW($int, $i) {
    return ceil($int / $i) * $i;
}

if ($startday == -1)
{
    $startday = 6;
}
$complete_cells = roundToNearestW($maxday+$startday,7);
for ($i=0; $i<($complete_cells); $i++) {
    if(($i % 7) == 0 )
    {
        echo "

        ";
    }
    if($i < $startday || $i >= $maxday+$startday)
    {
        echo "
        ";
    }
    else
    {
        if(($i - $startday + 1) > $firstDateMonth)
        {
            $firstDateMonth = ($i - $startday + 1);
        }
        echo "". ($i - $startday + 1) . "
        ";
    }
    if(($i % 7) == 6 )
    {
        $weekDate = $cYear."-".$cMonth."-".$firstDateMonth;
        $Caldate = new DateTime($weekDate);
        $week = $Caldate->format("W");
        echo "WK ".$week."
        ";
    }
    if(($i % 7) == 6 )
    {
        echo "
";
        //firstDateMonth = 0;
    }

}
?>

Partial credit for above calendar (tweaked code slightly myself) to: https://www.phpjabbers.com/how-to-make-a-php-calendar-php26-4.html

A: I hope the following logic will suit your needs.
<?php

$begin    = new DateTime(date('Y-m-d', strtotime('first Monday of April this year')));
$end      = new DateTime(date('Y-m-d', strtotime('last Monday of March next year')));
$interval = DateInterval::createFromDateString('1 week');

$weekNumberOfFirstMondayInApril = $begin->format('W');

foreach (new DatePeriod($begin, $interval, $end) as $dt) {
    $phpWeekNum = $dt->format('W');

    $isFirstQuarter = ($phpWeekNum < $weekNumberOfFirstMondayInApril);

    $businessWeekNum = $isFirstQuarter
        ? ($phpWeekNum + (52 - $weekNumberOfFirstMondayInApril))
        : ($phpWeekNum - $weekNumberOfFirstMondayInApril) ;

    echo 'Date: ' . $dt->format('l, Y-m-d') . PHP_EOL;
    echo 'PHP week number: ' . $phpWeekNum . PHP_EOL;
    echo 'Business week number: ' . ($businessWeekNum + 1) . PHP_EOL;
    echo PHP_EOL;
}

It's output is as follows:
Date: Monday, 2017-04-03
PHP week number: 14
Business week number: 1

    <snip>

Date: Monday, 2017-12-25
PHP week number: 52
Business week number: 39

Date: Monday, 2018-01-01
PHP week number: 01
Business week number: 40

    <snip>

Date: Monday, 2018-03-26
PHP week number: 13
Business week number: 52

A: This seems less convoluted to me, with less processing inside the loop.  DateInterval('P7D') just means set the interval to 7 days (1 week) -- this may be the only part that is mildly confusing because of the syntax.  DatePeriod() does all the hard work for you.
Code (Demo)
$year=2018;  // $_GET['year'];
$next=$year+1;
$start=new DateTime(date('Y-m-d', strtotime("first Monday of April $year")));
$stop=new DateTime(date('Y-m-d', strtotime("first Monday of April $next")));
// there is a known behavior of DatePeriod to stop before $stop (...not contain it)
// See http://au2.php.net/manual/en/class.dateperiod.php for explanations & workarounds
$range=new DatePeriod($start,new DateInterval('P7D'),$stop);
echo "
";
    echo "
";
        echo "Financial Calendar $year-$next	";
    echo "
";
    echo "
";
        echo "M	T	W	T	F	S	S	#	";
    echo "
";
    foreach ($range as $i=>$date) {
        echo "
";
            echo "							",++$i,"(",$date->format("Y-m-d"),")	";
        echo "
";
    }
echo "
";

Output (unrendered):

        Financial Calendar 2018-2019

        M	T	W	T	F	S	S	#

        							1(2018-04-02)

        							2(2018-04-09)

        							3(2018-04-16)

    ...

        							50(2019-03-11)

        							51(2019-03-18)

        							52(2019-03-25)

Now, I don't want to rob you of the opportunity to develop this code for yourself, so I'll stop here.  This should give you a foothold to finish this project to your desired specification.


text:
Q: xls export problemusing params Is there any way or example to export xls on rails 2.3.5 without using gems and something complicated?
I'm trying to export to xls with conditions by ejectuve_id that i selected
i have this code
 *********It s in my controller********
      @search_ejecutive = params[:search_ejecutive].to_i
      @search_status = params[:status_id].to_i
      @list_ejecutives_comision = Ejecutive.find(:all)
      ejecutive_ids = []

      obj_user.ejecutives.each do |ejecutive|
        @list_ejecutives_comision << Ejecutive.find(ejecutive.id)
      end

      @list_policies_search = Policy.deleted_is(0)

      if params[:search_ejecutive].to_i!=0
        @list_policies_search = @list_policies_search.ejecutive_id_is(@search_ejecutive)
      end

      ejecutive_ids = []
      obj_user.ejecutives.each do |ejecutive|
         ejecutive_ids << ejecutive.id
      end

      if !ejecutive_ids.blank?
          @list_policies_search = @list_policies_search.ejecutive_id_in(ejecutive_ids)
      end

     @list_policies_search = @list_policies_search.deleted_is(0)
     @list_policies = @list_policies_search.paginate(:page => params[:page], :per_page => 10)

And here i'm showing links that i tried
    <% form_remote_tag :url=>{:action=>"generate_print_ejecutive_comercial"},:before=>"load_close('loading_search')",:success=>"load_off('loading_search')" do -%>

    Ejecutivo:
    <%= select_tag 'search_ejecutive',"<option value=\"\">Seleccione</option>"+options_for_select(@list_ejecutives_comision.collect {|t| [t.name.to_s+" "+t.lastname1.to_s,t.id]})%>

   <input name="Buscar" value="Buscar" type="submit" />
<% end %>
  <%= link_to("xls","http://localhost:3000/policy_management/policy/generate_print_ejecutive/generate_print_ejecutive.xls")%>

  <%= link_to "xls", :controller=>"policy_management/policy",:action=>"generate_print_ejecutive",:format=>"xls" ,:search => params[:search_ejecutive],:page => params[:page]    %>

  <%= link_to 'Imprimir', :controller=>"policy_management/policy",:action=>"generate_print_ejecutive", :format=>"pdf" %>

<%= render :partial=>"table2" %>

My :partial table2 is the result of @list_policies
My teacher doesn't want doesn't want to reveal me the secret ,told me that the trick is
@list_policies

I tried to export manually and i tried this
@list_policies.find(:all,:conditions=>"ejecutive id = 1")

Somebody can help me with this, my teache told me that i need to export :search_ejecutive params
I will appreciate all help

A: There is a way by which newest format of xls can be represented by an xml, you can read more about it here.
So your controller can answer .xls requests, and you can then have a view generate_print_executive.xls.erb like this one:
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:o="urn:schemas-microsoft-com:office:office"
          xmlns:x="urn:schemas-microsoft-com:office:excel"
          xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:html="http://www.w3.org/TR/REC-html40">
  <Worksheet ss:Name="Sheet1">

      <% @list_policies.each do |policy| %>
        <Row>
          <Cell>
            <Data ss:Type="String"><%= policy.column_data %></Data>
          </Cell>
        </Row>
      <% end %>

  </Worksheet>
</Workbook>

Notice this is just a dummy example on how to generate a .xls without using any gem, I wasn't able to understand what you need on your post, I'm mostly answering the title of the post :P


text:
Q: If a column value is between a range, get a corresponding value I have the two data frames -

*

*Dataframe 1:

df1 <- read.table(text = "
Numbers
40500
4400025
14515
51432", header = TRUE)

*

*Dataframe 2:

df2 <- read.table(text = "
ColumnA   ColumnB    ReturnC   ReturnD
32000       41400      rose      apple
51400       57389      orchid    orange
12523       16357      jasmine   grapes
10528       11034      lily      melon ", header = TRUE)

This is what I want -- Check if each value from Numbers in dataframe 1 is between ColumnA and ColumnB of dataframe 2. If it is, I want the corresponding ReturnC and ReturnD from dataframe 2 in the output.
If it is not, I want NA.
E.g. 51432 is in between column A and column B.  Orchid and orange are the corresponding values in dataframe 2 for that intersection. This is how the final dataset will look like:
Final:
Numbers     Output1      Output2
40500        rose        apple
4400025      NA          NA
14515        jasmine     grapes
51432        orchid      orange

How should I do this in R? -- Thank you for your help!

A: You can use left_join + join_by from dplyr:
library(dplyr)

left_join(df1, df2, by = join_by(between(Numbers, ColumnA, ColumnB)))

#   Numbers ColumnA ColumnB ReturnC ReturnD
# 1   40500   32000   41400    rose   apple
# 2 4400025      NA      NA    <NA>    <NA>
# 3   14515   12523   16357 jasmine  grapes
# 4   51432   51400   57389  orchid  orange


text:
Q: string in webclient class c# changed to uncorrect format I call my service in wcf as you can see :
  ClientRequest.Headers["Content-type"] = "application/json";
            string result = ClientRequest.DownloadString(ServiceHostName + "/NajaService.svc/GetCarData/" + plaque);

            var javascriptserializer = new JavaScriptSerializer();
            return javascriptserializer.Deserialize<NajaResult>(result);

But the returned data is like this :
{"CarColor":"آبي سير","CarModel":"1383","CarTip":"ال ايکس","CarType":"سواري","Chassis":"83844131","Family":"####","FuelType":1,"MotorNum":"12483068683","Name":"####","NationalCode":"0000000000","Plaque":"11-426د61","PlaqueCoded":110561426,"PlaqueType":"","SystemType":"سمند","VinNo":"IRFC831V3GJ844131"}

I converted it to UTF8 byte and again convert it to utf8 string but not solved.
The encoded data is in Persian language .
I traced the request in fiddler and i found that the data is come with the correct format as you can see ,But in my code is changed

A: The WebRequest contains the Encoding property you can set up before downloading the service reply. Details are here: https://msdn.microsoft.com/en-us/library/system.net.webclient.encoding(v=vs.110).aspx


text:
Q: Why IQueryable executes in Where clause? I have
public IQueryable<Guid> AccessibleCities
{
    get
    {
        return CityRepository
            .FindAll(a => <CONDITIONS>);
    }
}

CityRepository.FindAll is implemented as:
public virtual IQueryable<TLookup> FindAll(Expression<Func<TLookup, bool>> predicate)
{
  return DataContext.GetSet<TLookup>().Where(predicate);
}

And I call this
anotherRepository
    .FindAll(a => AccessibleCities.Any(b => ANOTHER CONDITION));

When I call the last one, it generates two queries instead of adding AccessibleCities as query.
Please help me :)

A: Your final query just doesn't work that way; it doesn't concatenate by default.
Try the PredicateBuilder class. That looks like it should work for what you're trying to achieve.


text:
Q: Draw custom region Google maps in Android Is it possible to draw a custom region using the Android Google maps API?
The currently available tiles in google maps are missing some information and I was wondering if it is possible to draw custom shapes on top of the Map using overlays?
Also do overlays occupy an entire layer on top of the existing map, or do they only occupy the region which is encompassed in the draw method?
I want only the custom drawn region(if possible) to be interactive to user touches and hence need only the drawn region to respond in a certain manner to user touches/gestures.
Help appreciated.


text:
Q: How to add ACE Editor highlighter rules in angular app? I try to add custom highlighter rules. My example based on this and this.
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

import * as ace from 'ace-builds';

import 'ace-builds/src-noconflict/mode-javascript';
import 'ace-builds/src-noconflict/theme-github';
import 'ace-builds/src-noconflict/ext-language_tools';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  @ViewChild('codeEditor') codeEditorElmRef: ElementRef;
  private codeEditor: any;

  constructor() { }

  ngOnInit() {
    var oop = ace.require('ace/lib/oop');
    var textHighlightRules = ace.require('ace/mode/text_highlight_rules').TextHighlightRules;

    const $rules = {
      start: [
        {
          regex: /sometext/,
          token: "keyword"
        },
        {
          regex: /othertext/,
          token: "keyword"
        }
      ]
    };

    const customHighlightRules = function CustomHighlightRules() {
      this.$rules = $rules;
    };

    oop.inherits(customHighlightRules, textHighlightRules);

    //exports.MyNewHighlightRules = customHighlightRules; //??
    const element = this.codeEditorElmRef.nativeElement;

    const options = {
      minLines: 14,
      maxLines: Infinity,
      highlightSelectedWord: true,
      enableBasicAutocompletion: true,
      enableSnippets: true,
      enableLiveAutocompletion: true
    };

    this.codeEditor = ace.edit(element, options);
    this.codeEditor.setTheme('ace/theme/github');
    this.codeEditor.getSession().setMode('ace/mode/text');
    this.codeEditor.setShowFoldWidgets(true);
  }
}

I need "sometext" to be highlighted. How to adapt this example for an angular and typescript? I could not find any working examples where integration with angular is used.

A: You need to create both Mode and HighlightRules like this:

var oop = ace.require("ace/lib/oop");
var TextMode = ace.require("ace/mode/text").Mode;
var TextHighlightRules = ace.require("ace/mode/text_highlight_rules").TextHighlightRules;

var CustomHighlightRules = function(){
    this.$rules = {
        'start': [
            {
              regex: /\b(sometext|othertext)\b/,
              token: "keyword"
            }
        ]
    };
};

oop.inherits(CustomHighlightRules, TextHighlightRules);

var Mode = function() {
    this.HighlightRules = CustomHighlightRules;
};
oop.inherits(Mode,TextMode);

(function() {
    this.$id = "ace/mode/custom";
}).call(Mode.prototype);

element = document.body
this.codeEditor = ace.edit(element, {
    value: "sometext not othertext",
    minLines: 14,
    maxLines: Infinity,
    highlightSelectedWord: true,
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true,
    theme: 'ace/theme/github',
    showFoldWidgets: true,
    mode: new Mode
});

A:  const oop = ace.acequire('ace/lib/oop');
    const TextMode = ace.acequire("ace/mode/text").Mode;
    const TextHighlightRules = ace.acequire("ace/mode/text_highlight_rules").TextHighlightRules;

    const customHighlightRules = function CustomHighlightRules() {
      this.$rules = {
        'start': [
          {
            regex: /\b(sometext|othertext)\b/,
            token: "keyword"
          }
        ]
      };
    };
    oop.inherits(customHighlightRules, TextHighlightRules);

    const Mode = function() {
      this.HighlightRules = customHighlightRules;
    };
    oop.inherits(Mode,TextMode);

    (function() {
      this.$id = "ace/mode/custom";
    }).call(Mode.prototype);

    this.editor.getEditor().getSession().setMode(new Mode)

blast from the future :) after some struggling started to work, thx


text:
Q: Optimized java Map/Dictionary for small number of entries w/o removals I have a specific usage of HashMap, where it just stores few entries (usually less then 5-10) for String keys. I just have to add entries, get them by key, and sometimes to iterate the entry set. Entries are never removed during the lifespan of the map. I have some operation where 5-6 such smaller maps are needed and allocated every time during single user usage, i.e. request.
I am using HashMap for this. However, I wonder if there is a better, optimized implementation of Map-alike structure that I might use for this? For example, one that would allocate less space and that might be faster for small number of elements. Or HashMap is simply good enough?
Note that I don't insist to follow Map interface for this.
My thoughts are going into direction of array-backed map, something like this implementation that caught my attention from JetBrains: SmartFMap (An immutable map optimized for storing few entries with relatively rare updates, as they say).
Does anyone know about such alternative implementations that would be a good HashMap replacement?
ADDON
My initial idea is what @Evgeniy Dorofeev said in his answer, to have sorted array of entries and use binary search, but with following modification. Since I need to add elements to this collection and to prevent re-creation of array I was thinking of using array with some empty spaces. First element is added eg in the middle of the array, second element is added in the middle of remaining half (below or under, depending on sorting order). If initial size of such array is good, we can (mostly) prevent recreation of this array and still be able to binary/radix search.

A: Have you considered using a Trie?
This will provide almost the same complexity as your hashmap to get an item. But in some cases it will be faster. For example, with the following strings: hello, world, house, foo, bar, balloon. Getting the value associated to hello only requires to compare the 2 first characters, only one for world and 3 for bar and balloon. Using a hashmap you would compute a hash using all characters.

A: You can make a custom map based on array
    Object[][] map = new Object[3][];
    map[0] = new Object[] {k1, v1};
    map[1] = new Object[] {k2, v2};
    map[2] = new Object[] {k3, v3};
    Arrays.sort(map);

how to search
int i = Arrays.binarySearch(map, key);
Object value = map[i];

A: Consider using an ImmutableMap from Guava. Creation of Map using it is like a charm:
Map<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");

There's another option for cases when you need to modify the entries of your map. You can use EnumMap from JDK. It's a little bit faster than HashMap.

A: You can use java.util.IdentityHashMap, provided you use identity keys. It's bit lighter than java.util.HashMap.


text:
Q: Not understanding read command in Python I'm trying to understand what's going on with my read function.  I'm simply doing a readline of a text document I created in canopy.  For some reason it only gives me w for whatever value I put in.  I'm new to the world of Python so I'm sure its an easy answer!  Thanks for your help!
import os

my_file = open(os.path.expanduser("~/Desktop/Python Files/Test Text.txt"),'r')

print my_file.readline(3)

my_file.close()

My Text document is below
w
o
r
d
s

A: my_file.readline(3) reads up to 3 bytes from the first line.
The first line contains a w and an end-of-line character.
If you want to read up to the first 3 bytes regardless of the line, use my_file.read(3). Note that end-of-line characters are included in the count.
If you want to print the first 3 lines, you could use
import os
with open(os.path.expanduser("~/Desktop/Python Files/Test Text.txt"),'r') as my_file:
    for i, line in enumerate(my_file):
        if i >= 3: break
        print(line)

or
import itertools as IT
with open(os.path.expanduser("~/Desktop/Python Files/Test Text.txt"),'r') as my_file:
    for line in IT.islice(my_file, 3):
        print(line)

For short files you could instead use
with open(os.path.expanduser("~/Desktop/Python Files/Test Text.txt"),'r') as my_file:
    lines = my_file.readlines()
    for line in lines[:3]:
        print(line)

but note that my_file.readlines() returns a list of all the lines in the
file.  Since this can be very memory-intensive if the file is huge, and since it
is usually possible to process a file line-by-line (which is much less
memory-intensive), generally the first two methods of reading a file are
preferred over the third.

A:

'readline([size]) -> next line from the file, as a string.Retain newline.  A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then).Return an empty string at EOF.

readline reads next line and so on.The argument size is for how many bytes should it read from the corresponding line.

A: Using f.readline does not give random access to the file.  I think you want to read the third (or maybe fourth if you're zero-indexing) line.  The argument that you're passing to f.readline is a maximum byte count to read, rather than a specific line to read.


text:
Q: Can a factless fact table be a bridge table? As for bridge tables, they can be a helper table both for facts and dimensions. But can the factless fact table be a bridge table?

A: Disclaimer, I'm not into DW, so I may have completely misunderstood the question. That said, a factless fact table sounds like an oxymoron, but I googled for it and according to Factless fact table | James Serra's Blog it's an intersection between two or more dimension tables. A bridge table is typically used to implement an n-n relationship:
CREATE TABLE d1
( d1key ... not null primary key
, ... )

CREATE TABLE d2
( d2key ... not null primary key
, ... )

CREATE TABLE f
( d1key ... not null references d1(d1key)
, d2key ... not null references d2(d2key)
,    primary key (d1key, d2key)
);

so I don't see any controversy in such table being both a bridge table and a factless fact table.


text:
Q: Determining piecewise function with a constant bounded area I am currently working on a structural design problem, but I have boiled it down enough that I feel it should be okay to post on Mathematics.
I have a linear function $f(x)$:
$$f(x)=\frac{12M}{BD^3}x-\frac{6M}{BD^2}+\frac{P}{BD}$$
where $\frac{P}{B}$ is equal to the integral of $f(x)$ from $0$ to $D$, $B$ and $M$ are constants, and $f(0)>0$. Obviously, changing $M$ will not affect the aforementioned bounded area.
If I introduce a value $U$ such that $f(x)$ must be less than or equal to $U$, the bounded area will decrease as $M$ increases. I am trying to determine a function where the area will always equal $\frac{P}{B}$. I know that this must apply beyond a certain value of $M$:
$$M=\frac{D(UBD-P)}{6}$$
so that $f(D)=U$. I also understand that the new function must approach the shape of a rectangle with a height $U$ and a side length $\frac{P}{BU}$, and that $f(0)$ no longer necessarily needs to be greater than $0$.
Does anyone have advice for where to begin? Every solution that I find is way out to lunch.


text:
Q: Speaker is treated as headphone Tried both ubuntu 20.04 and 21.10. On a Huawei Matebook 13s 2021 laptop, speaker is treated as a headphone. When the headphone is plugged in, the speaker and the headphone are playing sound at the same time. When the headphone is removed, the speaker doesn't play sound. What is more interesting: when headphone is unplugged, and select "Headphones(unplugged)" as the output from PulseAudio Volume Control, the speaker works! So it looks like speaker is treated as a headphone. Is there a way to redirect/reconfigure it as the speaker? Thank you in advance.

A: A lot of Huawei Matebooks have had this issue over the years. The solution is generally to add/edit a configuration file to your system.
Here's how you can do the same:

*

*Open Terminal (if it's not already open)

*Add a line to sound.conf:
sudo sh -c "echo 'options snd-hda-intel model=alc255-acer,dell-headset-multi' >> /etc/modprobe.d/sound.conf"

Note: If the file does not already exist, it will be created.

*Reset alsa:
sudo alsactl restore

Alternatively, a reboot will also work.
Sound should now work properly on your Matebook


text:
Q: Overhead of go routines in golang So I understand go routines have low overhead, but I'm wondering just how good they are. If I have a server that handles incoming messages how does creating a new go routine to process each incoming message compare to using the standard producer/consumer model with channels?
Like is it reasonable to have a high performance go server that spawns new go routines for ever incoming request.

A: We were actually doing stress testing with a similar approach. We spawned new threads for every http request. The concurrency was so good than within 10 seconds we had reached something like 100,000 requests. The only bottle neck you might face is memory because if all the processing isn't fast enough then you might run out of memory for that process.
I'm quite sure there is a work around for it, but that is one reason why you would want to throttle and nor spawn unlimited go routines. The problem we faced is we were trying to get data from another API which was just not able to keep up with this level of concurrency. Hence the throttling suggestion earlier.

A: The built-in http package uses a goroutine for each connection and there are numerous benchmarks showing it being able to handle thousands of concurrent users. So unless you have many connections with many messages each, I'd say it's reasonable to create a new goroutine for each message. And in any case, go has a nice benchmarking feature you can use to verify your assumptions.
https://golang.org/src/net/http/server.go#L2137


text:
Q: Can't authenticate with mongoDB from docker-compose service What I'm trying to do
I'm trying to set up a docker-compose definition, where I have a mongoDB container, and a nodeJS container that connects to it.
version: "3.9"

services:

  events-db:
    image: mongo
    volumes:
      - db-volume:/data/db
    environment:
      MONGO_INITDB_ROOT_USERNAME: $SANDBOX_DB_USER
      MONGO_INITDB_ROOT_PASSWORD: $SANDBOX_DB_PASS
      MONGO_INITDB_DATABASE: sandboxdb

  app:
    image: node:15.12.0
    user: node
    working_dir: /home/node/app
    volumes:
      - ./:/home/node/app:ro
    environment:
      MDB_CONNECTION: mongodb://$SANDBOX_DB_USER:$SANDBOX_DB_PASS@events-db:27017/sandboxdb
    command: node myapp
    depends_on:
      - events-db

volumes:
  db-volume:

Along with a .env file that declares the credentials (planning to use proper env variables when I deploy this to a production environment):
SANDBOX_DB_USER=myuser
SANDBOX_DB_PASS=myp4ss

Finally, my nodejs script, myapp.js is simply trying to connect, grab a reference to a collection, and insert a document:
require('dotenv').config()
const { MongoClient } = require('mongodb')

async function main () {
  console.log('Connecting')
  const client = new MongoClient(process.env.MDB_CONNECTION, {
    connectTimeoutMS: 10000,
    useUnifiedTopology: true,
  })
  await client.connect()
  const db = client.db()
  const events = db.collection('events')

  console.log('Inserting an event')
  await events.insertOne({
    type: 'foo',
    timestamp: new Date(),
  })

  console.log('Done.')
  process.exit(0)
}

if (require.main === module) {
  main()
}

Result
When I run docker-compose config I see the following output, so I would expect it to work:
$ docker-compose config
services:
  app:
    command: node myapp
    depends_on:
      events-db:
        condition: service_started
    environment:
      MDB_CONNECTION: mongodb://myuser:myp4ss@events-db:27017/sandboxdb
    image: node:15.12.0
    user: node
    volumes:
    - C:\workspace\dcsandbox:/home/node/app:ro
    working_dir: /home/node/app
  events-db:
    environment:
      MONGO_INITDB_DATABASE: sandboxdb
      MONGO_INITDB_ROOT_PASSWORD: myp4ss
      MONGO_INITDB_ROOT_USERNAME: myuser
    image: mongo
    volumes:
    - db-volume:/data/db:rw
version: '3.9'
volumes:
  db-volume: {}

However, when I run docker-compose up I see that my node container is unable to connect to the mongoDB to insert an event:
events-db_1  | {"t":{"$date":"2021-04-07T13:57:36.793+00:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}
app_1        | Connecting
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.811+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.27.0.3:34164","connectionId":1,"connectionCount":1}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.816+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn1","msg":"client metadata","attr":{"remote":"172.27.0.3:34164","client":"conn1","doc":{"driver":{"name":"nodejs","version":"3.6.6"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"4.19.128-microsoft-standard"},"platform":"'Node.js v15.12.0, LE (unified)"}}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.820+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.27.0.3:34166","connectionId":2,"connectionCount":2}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.822+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn2","msg":"client metadata","attr":{"remote":"172.27.0.3:34166","client":"conn2","doc":{"driver":{"name":"nodejs","version":"3.6.6"},"os":{"type":"Linux","name":"linux","architecture":"x64","version":"4.19.128-microsoft-standard"},"platform":"'Node.js v15.12.0, LE (unified)"}}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.822+00:00"},"s":"I",  "c":"ACCESS",   "id":20251,   "ctx":"conn2","msg":"Supported SASL mechanisms requested for unknown user","attr":{"user":"myuser@sandboxdb"}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.823+00:00"},"s":"I",  "c":"ACCESS",   "id":20249,   "ctx":"conn2","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-256","principalName":"myuser","authenticationDatabase":"sandboxdb","client":"172.27.0.3:34166","result":"UserNotFound: Could not find user \"myuser\" for db \"sandboxdb\""}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.824+00:00"},"s":"I",  "c":"ACCESS",   "id":20249,   "ctx":"conn2","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-1","principalName":"myuser","authenticationDatabase":"sandboxdb","client":"172.27.0.3:34166","result":"UserNotFound: Could not find user \"myuser\" for db \"sandboxdb\""}}
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.826+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn1","msg":"Connection ended","attr":{"remote":"172.27.0.3:34164","connectionId":1,"connectionCount":1}}
app_1        | /home/node/app/node_modules/mongodb/lib/cmap/connection.js:268
app_1        |           callback(new MongoError(document));
app_1        |                    ^
app_1        |
app_1        | MongoError: Authentication failed.
app_1        |     at MessageStream.messageHandler (/home/node/app/node_modules/mongodb/lib/cmap/connection.js:268:20)
app_1        |     at MessageStream.emit (node:events:369:20)
app_1        |     at processIncomingData (/home/node/app/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
app_1        |     at MessageStream._write (/home/node/app/node_modules/mongodb/lib/cmap/message_stream.js:42:5)
app_1        |     at writeOrBuffer (node:internal/streams/writable:395:12)
app_1        |     at MessageStream.Writable.write (node:internal/streams/writable:340:10)
app_1        |     at Socket.ondata (node:internal/streams/readable:750:22)
app_1        |     at Socket.emit (node:events:369:20)
app_1        |     at addChunk (node:internal/streams/readable:313:12)
app_1        |     at readableAddChunk (node:internal/streams/readable:288:9) {
app_1        |   ok: 0,
app_1        |   code: 18,
app_1        |   codeName: 'AuthenticationFailed'
app_1        | }
events-db_1  | {"t":{"$date":"2021-04-07T13:57:38.832+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn2","msg":"Connection ended","attr":{"remote":"172.27.0.3:34166","connectionId":2,"connectionCount":0}}
dcsandbox_app_1 exited with code 1

I've put the full output at https://pastebin.com/uNyJ6tiy
and the example code at this repo: https://github.com/akatechis/example-docker-compose-mongo-node-auth

A: After some more digging, I managed to figure it out. The issue is that the MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD variables simply set the root user's credentials, and the MONGO_INITDB_DATABASE simply sets the initial database for scripts in /docker-entrypoint-initdb.d.
By default, the root user is added to the admin database, so by removing the /sandboxdb part of the connection string, I was able to have my node app authenticate against the admin DB as the root user.
While this doesn't quite accomplish what I wanted initially (to create a separate, non-root user for my database, and use that to authenticate), I think this puts me on the right path to using an init script to set up the user accounts I want to have.


text:
Q: React Native Firebase storage - issues uploading images to storage I have tried uploading images to my bucket in firebase storage, I wasted a massive amount of time on this and tried all the available tutorials in the subject but nothing worked.
For some reason when I create a reference to the storage and execute the "putFile" method and supply the local path of the image from the emulator, it does not upload and does not execute anything.
I am not getting any response from the puFile promise, not in the 'then' and not in the 'catch' statements.
This is the function with which I upload to firebase storage.
import storage from '@react-native-firebase/storage'

uploadFile = async (path, imageName) => {
            await storage().ref(imageName).putFile(path).then(res => console.log(res)).catch(err => console.log(err)) ;
}

Am I missing something?