text:
Q: Document.querySelector returns a NULL value - script is at bottom of page I am trying to get the patientNumber (ClinicA100-PF-TR1-P1) using querySelector. I keep getting a NULL value.  The patientNumber is at the top of the page and the script is at the bottom.  Even after the page is loaded, I click a button that runs the function and it still returns a NULL value.
Here is a screenshot of the selectors (https://recordit.co/IypXuuXib0)

Thank you for any help you can provide.

ADDITIONAL HTML INFORMATION:
I am using Caspio (database management software) to create this HTML code.  I don't know if that may be the cause of the issue.  Here is the HTML CODE.

[@authfield:User_List_Sponsor_Name]

[@authfield:User_List_Site_Number]

[@authfield:User_List_Protocol_Number]

[@authfield:User_List_Patient_Number]

A: You are missing a dot.

var patientNumberNode = document.querySelector(".patientNumber");
var patientNumber = patientNumberNode.innerText;

A: Your selector is incorrect. It should be
var patientNumber = document.querySelector(".patientNumber");

Why is it failing:
When you use patientNumber as the selector, JavaScript looks for an element with a name of patientNumber. Since that's not the case, and you are looking for an element with a class of patientNumber, you need to use the . notation.

Addon Suggestion (can be ignored):
Since you are also using IDs, consider using document.getElementById() as it is faster than using document.querySelector().
Note that if you use document.getElementById(), your .patientNumber selector won't work. You need to write it as
document.getElementById('patientNumberID');
//ID based on the screenshot of the DOM you've shared

A: if you select the item with class".", if you select with id, you should use"#".
 var patientNumber = document.querySelector(".patientNumber"); // class select
 var patientNumber = document.querySelector("#patientNumber"); // id select

A: While the code is at the bottom of the page, and the element is at the top, it is not loaded asynchronously as it comes from a third party database. i put a delay in the getPatientNumber() and it works now.


text:
Q: keydown event multiple key hold odd behavior I have been running the following code using es6 babel on chrome:
window.hold = [];
window.addEventListener('keydown', (e) => {
  if (!window.hold.includes(e.key)) {
    setTimeout(() => {
      console.log("> - " + e.key);
      window.hold.push(e.key);
    }, 0);
  } else { e.preventDefault(); }
});

window.addEventListener('keyup', (e) => {
  setTimeout(() => {
    console.log("< - " + e.key);
    window.hold.splice(window.hold.indexOf(e.key), 1);
    e.preventDefault();
  }, 0);
});

If I hold ASDZ on the keyboard, it doesn't log the Z, but if I hold ASDK, it logs everything as it should, does anyone know why this is happening?

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS3 Wrapper Fading In/Out outside the box http://jsfiddle.net/Ru54p/
CCS3:
#wrapper {
    position: relative;
    width: 660px;
    max-width: 70%;
    background: #ccc;
    padding: 30px;
    margin: 0 auto;
    border-radius: 4px 4px 4px 4px;
    text-align: center;
}

.fade {
    opacity: 1;
    transition: opacity .25s ease-in-out;
    -moz-transition: opacity .25s ease-in-out;
    -webkit-transition: opacity .25s ease-in-out;
}

.fade:hover {
    opacity: 0.5;
}

html:

            BLAH

            BLAH

            BLAH

As you can see in the jsfiddle, for some reason it's fading when you hover the cursor outside out of the box... I think it has something to do with the width, any ideas?

A: thats because your inner div i.e. the div with class wrapper has width only 70% of the parent div i.e. div with class fade.
and you have applied opacity css i.e. .fade to the parent
so either increase the width of the inner div to 100% i.e.
#wrapper {
    position: relative;
    width: 660px;
    max-width: 100%;
    background: #ccc;
    padding: 30px;
    margin: 0 auto;
    border-radius: 4px 4px 4px 4px;
    text-align: center;
    }

or apply the hover property on wrapper i.e apply the .fade class on wrapper

         BLAH
BLAH
BLAH

fiddle

A: A div is block-level by default, so it will take up all the available width. You are applying your transition to the .fade class, but it appears you want only the #wrapper itself to fade.
Try applying a background-color to the .fade block to illustrate what's going on. The fix is to either add your opacity etc. to your #wrapper, or to set another property on your fade class to limit the width (e.g. set it to display: inline-block;).

A: I have updated code,
you were having wrong sequence of div,
check this fiddle http://jsfiddle.net/Ru54p/3/
I hope this will do :)
CSS
#wrapper {
    position: relative;
    width: 660px;
    max-width: 70%;
    background: #ccc;
    padding:0;
    margin: 0 auto;
    border-radius: 4px 4px 4px 4px;
    text-align: center;
}

.fade {
    width:100%;
    height:100%;
    padding:10px 10px;
    opacity: 1;
    transition: opacity .25s ease-in-out;
    -moz-transition: opacity .25s ease-in-out;
    -webkit-transition: opacity .25s ease-in-out;
}

.fade:hover {
    opacity: 0.5;
}

HTML

    BLAH
BLAH
BLAH


text:
Q: How can I replicate If...Then logic as a Web control? I have a designer working at the ASPX level.  He doesn't do C#, doesn't do code-behinds, doesn't compile, etc.  He's a pure designer, working with HTML and server controls.
I need a conditional control -- an If...Then-ish type thing.  Normally, I would do this:
<asp:Placeholder Visible='<%# DateTime.Now.Day == 1 %>' runat="server">
  It's the first day of the month!
</asp:PlaceHolder>

Is there any way to do something like this without the databinding syntax?  Something like:
<asp:If test="DateTime.Now.Day == 1" runat="server">
  It's the first day of the month!
</asp:If>

Is there some kind of way to extend a placeholder to allow this?  I've fiddled around a bit, but in the end, I have a conditional that I essentially have to compile.
Now, there's nothing wrong with the databinding syntax, but's just one more bit of...weirdness, the a designer is going to have to understand.  Additionally, it doesn't give me "else" statements.  Something like this would be great...
<asp:If test="DateTime.Now.Day == 1" runat="server">
  It's the first day of the month!
  <asp:Else>
    It's not the first day of the month!
  </asp:Else>
</asp:If>

A: Instead of writing control
asp:If

why not use:
<% if expression
       { %>
    Yellow
    <% } %>
    <% else
        {%>
    Red
    <% } %>

A: Taking into account that codebehind files are out as the designer probably not got VS, I think a simpler solution with less code may be more preferential:
<%@ Page Language="C#"%>

<asp:panel runat="server" id="DateTestPanelFirst" visible="false">
  It's the first day of the month!
<asp:panel>

<asp:panel runat="server" id="DateTestPanelOther">
    It's not the first day of the month!
<asp:panel>

the <asp:panel> could be changed to another type of web control, like <asp:label> etc.  I think almost all dot net controls have the visible property, so you can hide/show them at any time.

A: The data-binding syntax has two problems: first it's a little weirder for your designer vs. using plain text, and second it requires the designer to remember to invert the "if" test in your "else" block.
The first problem may annoy your designer a little, but the second problem is much more severe, because it forces your designer to think like a programmer (inverting boolean logic!) and makes every if/else block into a possible bug you need to test for after your designer hands over a template.
My suggestion: use data-binding syntax, but fix the more severe problem by creating custom controls that only require data-binding test code on the If control, but not on the Else control. Sure your designers will have to type a few more characters, but the other more severe problems won't apply and your performance won't suffer as it would if you had to dynamically compile code each time your page ran.
Here's an example I coded up to illustrate:
<%@ Page Language="C#"%>
<%@ Register Assembly="ElseTest" TagPrefix="ElseTest" Namespace="ElseTest"%>

    <ElseTest:IfControl runat="server" visible="<%#1 == 1 %>">
        This should be visible (in "if" area)
    </ElseTest:IfControl>
    <ElseTest:ElseControl runat="server">
        This should not be visible (in "else" area)
    </ElseTest:ElseControl>

    <ElseTest:IfControl runat="server" visible="<%#0 == 1 %>">
        This should not be visible (in "if" area)
    </ElseTest:IfControl>
    <ElseTest:ElseControl runat="server">
        This should be visible (in "else" area)
    </ElseTest:ElseControl>

Here's the underlying controls, which are simply wrappers around asp:Literal:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

[assembly: TagPrefix("ElseTest", "ElseTest")]
namespace ElseTest
{
    // simply renames a literal to allow blocks of data-bound-visibility
    [ToolboxData("<{0}:IfControl runat=\"server\"></{0}:IfControl>")]
    public class IfControl : Literal
    {
    }

    [ToolboxData("<{0}:ElseControl runat=\"server\"></{0}:ElseControl>")]
    public class ElseControl : Literal
    {
        public override bool Visible
        {
            get
            {
                // find previous control (which must be an IfControl).
                // If it's visible, we're not (and vice versa)
                for (int i = Parent.Controls.IndexOf(this)-1; i >= 0; i--)
                {
                    Control c = Parent.Controls[i];
                    if (c is IfControl)
                        return !c.Visible;  // found it! render children if the if control is not visible
                    else if (c is Literal)
                    {
                        // literals with only whitespace are OK. everything else is an error between if and then
                        Literal l = c as Literal;
                        string s = l.Text.Trim();
                        if (s.Length > 0)
                            throw new ArgumentException("ElseControl must be immediately after an IfControl");
                    }
                }
                throw new ArgumentException("ElseControl must be immediately after an IfControl");
            }
            set
            {
                throw new ArgumentException("Visible property of an ElseControl is read-only");
            }
        }
    }
}

If you want it more concise, you can easily shorten the tag name (by changing the class names and/or tag prefix). You can also create a new property (e.g. "test") to use instead of "Visible".
If you really want to get rid of the <%# %>, there are likley many different tricks you can use to leverage CodeDOM or other ways to dynamically compile code, although performance will be a challenge since you'll probably end up dynamically compiling code each time the page runs, it may introduce pesky security issues, and more.  I'd stay away from that.


text:
Q: How to commit some files on a branch and some others files to another branch? Scenario:
I have 2 existing branches:

*

*feature/A

*feature/B

I'm on feature/A branch and made some changes to 5 different files.
Not all those 5 files are related to the feature A, but very often when you change/develop/fix something you find other bugs or need to change things on file which is not strictly related with the feature you are coding in that moment.
So, suppose that:

*

*3 files are related to feature A

*2 files are extra changes and related to B

When I perform local commit (I'm using Tortoise but I suppose it's similar with other softwares) I can choose which file to commit, so suppose I commit the 3 files related to A on current branch feature/A, leeaving the remaining 2 files changed but not committed.
Now, the two other files should be commited on feature/B branch but obviouvsly I cannot switch branch while some changes are not commited.
Trivial solution may be copying files as backup, revert them, switch to feature/B then copy backuped files and commit.
Is there a more elegant solution to problems like this one?
I know it's quite bad practice, but sometimes it could happens.

A:  git add file1A file2A file3A # add the changes for feature A
 git commit -m "feature A" # on branch A
 git stash # temporarily put your changes aside
 git checkout feature/B
 git stash pop # apply the changes that you put aside again.
 git commit -am "feature B"

for more advanced splitting into multiple commits, I recommend you take a look at git add -p which allows you to split your commits per patch and not per file

A:
Now, the two other files should be committed on feature/B branch but obviously I cannot switch branch while some changes are not committed.

But you can.  With any luck at all there won't be changes to files touched by your feature/A work on the B branch, and your sequence is
git checkout feature/B
git commit -- bfile1 bfile2
git checkout @{-1}       # @{-1} is "what I had checked out before",
                         # a.k.a. feature/A here. There's also @{-2}...

Drop-shipping work this way to the branches it should be recorded on is one of Git's best features.
If both branches do change some files, Git's got tools to help wrangle that too.  Easiest is often to just temporarily commit those files and reset them on the way back, but once you get familiar with the heavy artillery, aka
git checkout -m feature/B

you might not need the temporary-commit three-step. git checkout -m does a content merge with HEAD as the base and feature/B as the new tip.  If there aren't any conflicts at the hunk level you can then do the git commit -- bfile1 bfile2 to drop-ship the changes you want as before, if there are you'll have to resolve them, but no matter what you can always use three of Git's best-kept secrets:
git add -p         # `-p` is aka `--patch`, get comfy with using this
git reset -p       # option and you'll be using the shortcut gladly
git checkout -p    # ...

to selectively apply hunks from (add) your worktree to the index, (reset) HEAD aka @ or a named commit to the index, (checkout) the index to your worktree or a named commit to the index and worktree.
and then once you've got the index entries you want to commit on this branch looking the way you want, git commit -- bfile1 bfile2 as usual to commit just those, git checkout -m @{-1} and any -patchwork to fixup leftovers and orts.
Put some time into experimenting with how these work, perhaps how easy the the drop-shipping ritual is for trivial cases will suck you in, and many, many of git's less widely-used options will start to make sense.  It's been years for me now, and I'm still learning things that make me like Git more.

A: You can use version control of git to do the same. Go to version control in your IDE, there you can select specific files and commit and push to the branch("A") on which you are currently. After this you can checkout your other branch "B", and then do the same procedure of selecting and committing the files you want to this branch.


text:
Q: how to verify this time/date string in java? I have a string in the format of:
3:00 pm on Aug 28
What would be the best way to verify that a valid time and valid date is contained within this string? My first thought was to split the string and use two regexs to match a time and the other one to match that specfic date format (abbreviate month day). However I'm having a little bit of trouble with the second regex (the one for the specfic date format). How else could one go about verifying the string is in the correct format?

A: You can try this:
public boolean isValid( String dateStr ) {

    //    K: hour of the day in am/pm
    //    m: minute of a hour
    // 'on': static text
    //  MMM: name of the month with tree letters
    //   dd: day of the month (you can use just d too)
    DateFormat df = new SimpleDateFormat( "K:m a 'on' MMM dd", Locale.US );

    try {
        df.parse( dateStr );
        return true;
    } catch ( ParseException exc ) {
    }

    return false;

}

More about the format string here: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

A: Use java.text.SimpleDateFormat.  Use a format string something like HH:mm aa 'on' MMM dd.
You may have to add yyyy to the format string and 2012 to your input.

A: Use SimpleDateFormat and make sure it doesn't use lenient parsing:
try {
  DateFormat df = new SimpleDateFormat("h:mm a 'on' MMM dd", Locale.US);
  df.setLenient(false);
  Date dt = df.parse(s);
} catch (ParseException pe) {
  // Wrong format
}


text:
Q: How do I run code after a setTimeout() is run? I need the
event.target.innerHTML = FULL_HEART
event.target.setAttribute('class', 'like-glyph activated-heart')

after the displayError() setTimeout interval is completed in the scenario that the mimicServerCall() catches an error.
document.addEventListener('DOMContentLoaded', () => {
  const likeButtons = document.querySelectorAll('.like-glyph');
  const modal = document.getElementById('modal');

  function displayError() {
    modal.removeAttribute('class');
    setTimeout(function(){ modal.setAttribute('class','hidden') }, 3000);
  };

  function likifyMe(button) {
    button.addEventListener('click', (event) => {
      if (event.target.innerHTML === EMPTY_HEART) {
        mimicServerCall().then(() => {}).catch(() => {displayError()});
        event.target.innerHTML = FULL_HEART
        event.target.setAttribute('class', 'like-glyph activated-heart')
      } else {
        event.target.innerHTML = EMPTY_HEART
        event.target.setAttribute('class', 'like-glyph')
      }
    });
  };

  likeButtons.forEach(button => {
    likifyMe(button)
  });

});

Is there a way to achieve this?

A: That's what a callback is for:
document.addEventListener('DOMContentLoaded', () => {
  const likeButtons = document.querySelectorAll('.like-glyph');
  const modal = document.getElementById('modal');

  function displayError(callback) {
    modal.removeAttribute('class');
    setTimeout(function(){
        modal.setAttribute('class','hidden');
        callback();
    }, 3000);
  };

  function likifyMe(button) {
    button.addEventListener('click', (event) => {
      if (event.target.innerHTML === EMPTY_HEART) {
        mimicServerCall().then(() => {
            event.target.innerHTML = FULL_HEART;
            event.target.setAttribute('class', 'like-glyph activated-heart');
        }).catch(() => {
            displayError(function(){
                event.target.innerHTML = FULL_HEART;
                event.target.setAttribute('class', 'like-glyph activated-heart');
            });
        });
      } else {
        event.target.innerHTML = EMPTY_HEART
        event.target.setAttribute('class', 'like-glyph')
      }
    });
  };

  likeButtons.forEach(button => {
    likifyMe(button)
  });
});

A: Leverage the following behavior of promise chaining detailed by MDN:

It's possible to chain after a failure, i.e. a catch, which is useful to accomplish new actions even after an action failed in the chain.

You can rewrite the block in question to this (notice it's .catch().then()):
      if (event.target.innerHTML === EMPTY_HEART) {
        mimicServerCall().catch(() => displayError()).then(() => {
          event.target.innerHTML = FULL_HEART;
          event.target.setAttribute('class', 'like-glyph activated-heart');
        });
      } else {

Then, just have displayError() return a promise that resolves with the timeout:
  function displayError() {
    return new Promise((resolve,reject) => {
      modal.removeAttribute('class');
      setTimeout(() => {
        modal.setAttribute('class','hidden');
        resolve();
      }, 3000);
    });
  };

The resulting behavior is that your code to activate the heart is guaranteed to happen in the event of either success or failure, but if it did fail, it will wait the three seconds for the setTimeout to execute. This is thanks to promise chaining, which will wait for the promise returned by displayError() to resolve before executing the following .then() callback.


text:
Q: Rails - Updating a record? using heroku, I'm trying to update a record.
This is what I did:
@user = User.find(11)
@user.email = 'xxx@xxx.com'
@user.save
>> true

But then when I do User.find(11), the email isn't updated? Any ideas why?

A: I would recommend trying @user.reload after you hit @user.save. The suggestion above to try @user.save! (read - "@user dot save bang") is also a good one because it will throw an error if a validation fails when saving @user.
Hope that helps.

A: Also try @user.save! which will give a error if any validations go wrong. But if @user.save give true, then I dont see any reason why it is not saved into the db.

A: If you're getting true then you don't really have to worry about the record not being validated. True tells you it did get saved. But it is a good practice to use @user.save! like @rubyprince mentioned. That way, invalid update attempts will be raised.
Also, are you sure it's not getting updated? If you're using a database backend I'd go directly to the database rather than relying on an User.find()
You can also try doing User.find(11).reload to see if that works. You can find some info here about reload. So you can try something like this...
user = User.find(11).reload
puts user.email

And see if the email changed.


text:
Q: I am working on spring MVC and need help setting flag This is the source code i have
public Customer add(UI uI)
    {

        String url = "https://localhost:8080/api;
        System.out.println("url is "+url);
        RestTemplate restTemplate = new RestTemplate();
        Customer customer = restTemplate.getForObject(url, Customer.class);
        System.out.println(customer);
        customerDao.save(customer);
        return customer;

    }

I receive this JSON data from localhost api as response
{"id":"12","datetime":"08:39:02","status":good,"first_name":"ABC","last_name":"xyz"}

for status i have two values good and bad and my question is how can i raise a flag if the status is bad.

A:     JSOnObject resp = `{"id":"12","datetime":"08:39:02","status":good,"first_name":"ABC","last_name":"xyz"}`;
String status = resp.getAsString("status");
if(status.equalsIgnoreCase("good")){
  //set Flag
}

if(status.equalsIgnoreCase("bad")){
  //call function
}


text:
Q: cron create output file only if there is output I have a cronjob that calls a script. I want the output to be placed in a log file. The problem is that the log-file is created even if there is no output.
Since the job runs once an hour, and mostly has nothing to do. I am ending up with a lot of 0 byte files.
I could probably append to a single log file, but I wonder if there is a trick to use to prevent the log-file being created or to delete it if it is empty. (I don't really want to run a second cron-job to clean up after the first one)
A complication is the fact that the log filenames have a date/time appended to them. The line in crontab looks a bit like this:
/your/script.sh config.txt > outfilepath_`date +\%Y-\%m-\%d_\%H\%M`.html

I guess that means I have to store the date in a variable first and then check if that file was created/empty. So if I take Stone's answer I end up with something like:
logfile=outfilepath_`date +\%Y-\%m-\%d_\%H`; your/script.sh config.txt > $logfile; if [! -s $logfile]; then rm $logfile; fi

but I don't know if that's possible inside crontab

A: You can write something like this:
/your/script > /your/log/file; if [ ! -s /your/log/file ]; then rm /your/log/file; fi


text:
Q: Word classification? I am trying to understand what the word classification would be to name a variable for a program. I will have a label variable which will hold one of two values (correct/incorrect) but I don't how to describe these words. Such as: run is a verb, color is an adjective but what would be the words correct and incorrect fall under?

A: The Value of correct or incorrect is, in fact, boolean. The specifics of whether the values allowed are adjectives are unimportant in the use as a yes/no answer.

Mathematics: A quantity or number expressed by an algebraic term.

American Heritage Dictionary, 5th Ed.

A: I think that this would be the best classification of the word in the sense that I am trying to use it.
State:  A condition or mode of being, as with regard to circumstances
American Heritage Dictionary. 5th Edition


text:
Q: How to backup and restore the raven database by C# console application coding? i need to backup and restore raven database by c# console application.i don't want to achieve this by smuggler.it should be a pure c# console application coding.i tried my level best.can you give me a suggestion please?

A: Look at the Raven.Backup application


text:
Q: Non-negative random variables (ask about the definition) As I understand, a non negative random varialbe which takes non-negative values. But I've seen in that in many books the definition for non-negative random varialbles is a random variable $ X $ such that
$ \mathbb{P}\left(X<0\right)=0 $.
How come those two definitions equivalent? $ \mathbb{P}\left(X<0\right)=0 $ does not imply that $ X(\omega) \geq 0 $ for any $ \omega \in \varOmega $.
What is the acceptable definition between the two that  I mentioned?

A: You probably have heard about Murphy's law. Aside all the rhetoric and myths around it, the Murphy's law actually is quite important. An event can be possible or impossible. Probability is only defined over possible event. A possible event can be improbable, i.e., its probability can be zero, but it doesn't mean that it cannot occur.
But as you mentioned, it is customary to assign zero probability to impossible events. Even though it is ultimately a bad practice, it usually works. The good practice however, is to always make a clear distinction between impossible and improbable events.


text:
Q: google cloud logging not working while working with python python code.
    import google.cloud.logging
    client = google.cloud.logging.Client.from_service_account_json("file.config")
    client.setup_logging()
    import logging

    loggin.info("error")

traceback:
    Traceback (most recent call last):
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
        return callable_(*args, **kwargs)
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/grpc/_channel.py", line 923, in __call__
        return _end_unary_response_blocking(state, call, False, None)
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/grpc/_channel.py", line 826, in _end_unary_response_blocking
        raise _InactiveRpcError(state)
    grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
        status = StatusCode.PERMISSION_DENIED
        details = "The caller does not have permission"
        debug_error_string = "{"created":"@1612798593.245379000","description":"Error received from peer ipv4:142.250.71.42:443","file":"src/core/lib/surface/call.cc","file_line":1062,"grpc_message":"The caller does not have permission","grpc_status":7}"
    >

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last):
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/cloud/logging/handlers/transports/background_thread.py", line 123, in _safely_commit_batch
        batch.commit()
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/cloud/logging/logger.py", line 383, in commit
        client.logging_api.write_entries(entries, **kwargs)
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/cloud/logging/_gapic.py", line 121, in write_entries
        self._gapic_api.write_log_entries(
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/cloud/logging_v2/gapic/logging_service_v2_client.py", line 476, in write_log_entries
        return self._inner_api_calls["write_log_entries"](
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/gapic_v1/method.py", line 145, in __call__
        return wrapped_func(*args, **kwargs)
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/retry.py", line 281, in retry_wrapped_func
        return retry_target(
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/retry.py", line 184, in retry_target
        return target()
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
        return func(*args, **kwargs)
    File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
        six.raise_from(exceptions.from_grpc_error(exc), exc)
    File "<string>", line 3, in raise_from
    google.api_core.exceptions.PermissionDenied: 403 The caller does not have permission

Here i am trying to use google logging, But i am getting above error.
Please take a look
I am doing this using python. Is there any issue on generating service account creation

A: As John said, have you checked if the Service Account has the proper role assigned? As the official documentation says: "Using Cloud Logging library for Python requires the IAM Logs Writer role on Google Cloud. Most Google Cloud environments provide this role by default".
On the other hand, I am bit curious you used the "google-cloud-storage" tag, however you are not mention something related to it. Have you checked  if the issue is because you do not have the enough permissions (As Storage Admin) to access your bucket?

A: I was using :
 client = google.cloud.logging.Client()

(not ".from_service_account_json")
and  I was getting the exact same error message. I also had the proper role roles/logging.logWriter. I am using using cloud-logging 2.6.0
I found that when I ran the code above in Vertex AI training job, if I don't create a client using my project_id in the following way:
 client = google.cloud.logging.Client(project=<user project number>)

then google.cloud.logging use some kind of dummy project_id i.e "i285ca2410679d8f1p-tp" which don't have the necessay access. Putting my project_id and all the error messages are then gone.


text:
Q: Fetch all need to solve $db = new PDO("mysql:host=$dbHost;dbname=$db;charset=utf-8", $dbUser, $dbPass);
return $db;

# Get all users in pot
$stmt = $db->query('SELECT * FROM `currentPot`');
$currentPotArr = $stmt->fetchAll();

and I've got error like this :

[Fri Dec 11 07:57:35.260326 2015] [:error] [pid 2274] [client
  89.64.51.139:32356] PHP Fatal error:  Call to a member function fetchAll() on boolean in
  /home/admin/domains/csbox.pl/public_html/php/update.php on line 21,

referer: http://csbox.pl/
Why?
Php 5.6.16
Apache 2.4.17
DirectAdmin 1.49.1
MySQL 5.6.12
On the site also iv'e got an php/update.php 500 (Internal Server Error) error

A: Your PDO statement and fetching results seems to be all right.
one thing I noticed ,
$db = new PDO("mysql:host=$dbHost;dbname=$db;charset=utf-8", $dbUser, $dbPass); return $db;
why you writing  "return $db". Does it is inside function?
Just remove "return $db;" if it is not a fuction.

A: PDO::query() returns a PDOStatement object, or FALSE on failure.
Perhaps the query is returning false? (Your error: Call to a member function fetchAll() on boolean).
See: http://php.net/manual/en/pdo.error-handling.php


text:
Q: sql query group by departname with details in other table Table: Employee
EmpID: INTEGER NOT NULL
DeptID: INTEGER NOT NULL
Name: Char(40) NOT NULL
Age: INTEGER NOT NULL
Salary: INTEGER NOT NULL

Table: Department
DeptID: INTEGER NOT NULL
Name: CHAR(20) NOT NULL

We need to write an SQL query which outputs names of all the departments such that the average salary of the department is greater than 10,00,000. The output should contain only one column: DeptName.
Tried this:
SELECT AVG(Salary) AS avg_salary ,DeptID FROM ( SELECT DeptID, Salary FROM employee GROUP BY 1) DeptID GROUP BY DeptID HAVING avg_salary > 10;

Result: unable to join.

A: Here's the query:
SELECT
Department.name AS DeptName
FROM Department
INNER JOIN Employee ON Department.DeptID = Employee.DeptID
GROUP BY Department.DeptID
HAVING AVG(Employee.Salary) > 1000000;


text:
Q: arm assembly mutex strex, ldrex firstly thank you for watching my question and reply previously.
I'm making an os like software on banana-pi m1.
This platform is dual cortex a-7.
and also i'm implementing a mutex like below.
.global lock_mutex
lock_mutex:
    ldr     r1, =UNLOCKED
1:  ldrex   r2, [r0]
    cmp     r2, r1

    wfene                           @ wfe if locked

    read_cp32(r1, MPIDR)            @ MPIDR (ARMv7 only)
    strexne r2, r1, [r0]            @ Trying to lock
    cmpne   r2, #1                  @ if failed to lock acquire
    beq     1b                      @ branch to before 1 label if fail to lock

    dmb
    bx      lr

.global unlock_mutex                @ in the case of unlock,
                                  @there's no need to check the status of lock
unlock_mutex:
    ldr     r1, =UNLOCKED
    dmb
    str     r1, [r0]                @ clear the lock
    dmb
    sev                             @ sending the event to other processors that is wfe status
    bx      lr

in the line of "ldrex   r2, [r0]" this instruction, nothing happen and seems cpu die.
is there any advice before use ldrex & strex instruction


text:
Q: Dot at end of numbers in CSV file I have an excel file with some numbers followed by a dot, say:

12345.

I created a simple macro to convert and save the excel file into a .csv file.
The problem is the CSV file does not save the dot. The data comes out as 12345 and not 12345. I also tried manually adding the dot and saving the csv file, but the dot just dissappears.
Anyway to add the dot into the CSV file?
http://i.stack.imgur.com/UoboK.jpg

A: Add a single quote/apostrophe in front of the number (without a closing quote at the end), so that it reads it as text and does not auto-format it as number.
For example you have:
    12345.

Excel will auto-format that column as a number and drop the period unless you specify that it's a text only column.
Change it to:
    '12345.

Excel will read that value as a text column and will not save the apostrophe in a text-based CSV file.
Edit:
In testing this, I found that ff you save it as "12345.", Excel changes the CSV file to """12345.""".


text:
Q: Inter quartile range and outliers in boxplot with logarithmic y-axis Let's say I have a set of data which are lognormal-distributed and I want to
create boxplots. The part of the values which is symbolized by the box may lie somewhere around 1. In that case, the inter quartile range will also be single digit. With the lower values lying somewhere below 0.1, even the most extreme values will be covered by 1.5 times the IQR, and thus by the lower whisker. On the contrary, the upper whisker will be quite short, making every value of 10 or higher a possible outlier.
As I have up to 9000 observations in each plot, ranging from 10^-7 to 1, I always get plots with very long lower whiskers and a huge field of outliers to the top.
This makes me wonder:
1. Is there a rule (of thumb) for what should be considered an outlier
among logarithmically distributed data?
2. Is there a more elegant way to configure the whiskers for boxplots with logarithmic y-axis?
For R-users, this may serve as a minimal example:
    data <- rlnorm(50) # random-generated lognormal data
    IQR(data) # interquartile range
    boxplot(data, log='y')

A: Since none of your values are negative or zero, you can just take the log of the value and then do a boxplot of that. Given that you say your values are lognormal distributed, this seems like the easiest way to proceed.


text:
Q: Running sudo snap on WSL2 with ubuntu18.04 By following WSL: Am I running version 1 or version 2? I've verified that my WSL is version 2. Running uname -a outputs "Linux DESKTOP 4.4.0-18362-Microsoft"
I want to install microk8s on WSL2 so that I can use kubeflow. There seems to be many instructions on how to install microk8s by enabling sudo snap command by enabling sytemD however none of the instruction seem to work on mine.
1. following -> https://gist.github.com/djfdyuruiry/6720faa3f9fc59bfdf6284ee1f41f950
I got stuck on /tmp/install-sg.sh && rm /tmp/install-sg.sh running it outputs Error: Too many request
2. follwing -> https://wsl.dev/wsl2-microk8s/
I can't even run WSL command, when I do it outputs:
WSL
Wsman Shell commandLine, version 0.2.1

USAGE: wsl COMMAND [PARAMS...]

COMMANDS:
identify  - WS-Identify
enum      - WS-Enumerate
get       - WS-Get
put       - WS-Put
invoke    - WS-Invoke
xclean    - Delete all files generated by this tool set
xcred     - Create or display credential file
xcert     - Get server certificate (saved to <IPADDRESS>.crt)

PARAMS specification is specific to a COMMAND.

Output will be saved to ./response.xml. If you want to run parallel
executions in the same directory, define RTFILEPREFIX in the environment.
Doing so may significantly increase files generated.

Requires: curl, xmllint, GNU core utilities.
Optional: xsltproc for output formatting, gpg for encrypted credential.
Optional: wget as alternate for curl when not available.

and when I try to run apt install -yqq fontconfig daemonize it outputs:
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?

Thanks in advance!

A: Older question that bumped by another NATO today.
There were at least two problems going on in this question.
First, Snap requires Systemd, and WSL doesn't support Systemd at this time.  Instead, it uses its own /init as PID1.
There are some hacky workarounds available to start Systemd in a container/namespace.  See this answer for a deeper dive.
The second issue was that running wsl ran the "wrong thing".  You were expecting it to run the Windows Subsystem for Linux tool, but instead it ran the WSMAN command line tool.
Usually, the wsl command is run from PowerShell or CMD.  In the Windows environment, running wsl and wsl.exe are the same thing.
But if you are in WSL/Linux, you do have to specify the extension explicitly, i.e. wsl.exe.
Normally the Linux wsl (WSMAN tool) isn't installed by default in Ubuntu, so I'm guessing you actually did a sudo apt install wsl at some point.
Regardless, running wsl.exe will get you the tool you were looking for in the first place.


text:
Q: Flask/Flask-CORS: CORS header 'Access-Control-Allow-Origin' missing I'm trying to link a Flask backend, running locally on port 5000 with a Vue.js frontend, running locally on port 8080.
I'm able to successfully signup and login, but fail to submit an article in the app, with the following error in the browser console.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/articles. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

The Flask backend uses Flask CORS (initializes them for every blueprint) and I've provided the localhost/127.0.0.1 origins to the whitelist.
#settings.py
    CORS_ORIGIN_WHITELIST = [
        'http://0.0.0.0:4100',
        'http://localhost:4100',
        'http://0.0.0.0:8000',
        'http://localhost:8000',
        'http://0.0.0.0:4200',
        'http://localhost:4200',
        'http://0.0.0.0:4000',
        'http://localhost:4000',
        'http://localhost:8080',
        'http://0.0.0.0:8080',
        'http://127.0.0.1:8080',
        'http://192.168.100.6:8080',
        'localhost'
    ]

#app.py
def register_blueprints(app):
    """Register Flask blueprints."""
    origins = app.config.get('CORS_ORIGIN_WHITELIST', '*')
    cors.init_app(user.views.blueprint, origins=origins)
    cors.init_app(profile.views.blueprint, origins=origins)
    cors.init_app(articles.views.blueprint, origins=origins)

    app.register_blueprint(user.views.blueprint)
    app.register_blueprint(profile.views.blueprint)
    app.register_blueprint(articles.views.blueprint)

#extensions.py

cors = CORS()

Any help would be greatly appreciated.

A: Have you tried adding the port to the localhost entry?
#settings.py
    CORS_ORIGIN_WHITELIST = [
        'http://0.0.0.0:4100',
        'http://localhost:4100',
        'http://0.0.0.0:8000',
        'http://localhost:8000',
        'http://0.0.0.0:4200',
        'http://localhost:4200',
        'http://0.0.0.0:4000',
        'http://localhost:4000',
        'http://localhost:8080',
        'http://0.0.0.0:8080',
        'http://127.0.0.1:8080',
        'http://192.168.100.6:8080',
        'localhost:8080'
    ]


text:
Q: Gzip after exec() returns NULL I am trying run CLI command via php function exec():
gzip -1 -c files/original/file.txt > files/compressed/gzip/1/file.txt.gz 2>&1

But file is not created and var_dump() prints NULL.
Chmod is set to 0777. If I put this command to console (in path where is index.php and function exec()) everything is OK...
Any ideas or hints?


text:
Q: How to show a dropdown when you hover over a specific area an on image? (HTML, CSS) Is it possible to show a dropdown whenever you hover over some specific area on an image? For example, if my mouse is within 50,62 and 70,80. I already tried this with invisible boxes and divs, but the only way I could get them to overlay the image was with position properties, but they wouldn't stay in place if I reshaped or resized the screen. Any ideas?

A: Demo : http://jsfiddle.net/v8dp91jL/12/
The code is pretty self-explanatory.
Just two imp things:

*

*Everything should be in %

*the .dropdown is inside .hover-area so that when you move your mouse from .hover-area to .dropdown, .dropdown doesn't disappear because it is still technically inside .hover-area even tho it's visually not

A: You can add some hidden element (span) positioned on some specific area and it is going to trigger the hover:
HTML:

CSS:
.image-wrapper { position: relative; }
.image-hover-trigger { position: absolute; top: 20%; left: 20%; right: 20%; bottom: 20%; }
.dropdown { display: none; }
.image-hover-trigger:hover ~ .dropdown { display: block; }


text:
Q: Camera access in qr code scanner dont have access on firefox I use this qr code scanner: https://github.com/mebjas/html5-qrcode
In chrome everything works fine, but in firefox I have allert: AbortError: Starting videoinput failed.
My code:
function listcamera() {
    Html5Qrcode.getCameras().then(cameras => {
        if (cameras && cameras.length) {
            cameraId = cameras[cameras.length - 1].id;
            scan(cameraId);
        }

    }).catch(err => {
            // handle err
                alert(err);
    });
}

function scan(cameraId) {
const html5Qr = new Html5Qrcode("reader");
html5Qr.start(
   cameraId, // retreived in the previous step.
   {
      fps: 10,    // sets the framerate to 10 frame per second
      qrbox: 250  // sets only 250 X 250 region of viewfinder to
                  // scannable, rest shaded.
 },
 qrCodeMessage => {     // do something when code is read. For example:
     console.log(`QR Code detected: ${qrCodeMessage}`);
   [...]
                });
                //console.log(data);

//        $( "#erase" ).click(function() {
//   document.getElementById('text').value = '';
// });
 },
 errorMessage => {     // parse error, ideally ignore it. For example:
     console.log(`QR Code no longer in front of camera.`);
 })
 .catch(err => {     // Start failed, handle it. For example,
     console.log(`Unable to start scanning, error: ${err}`);
 });
};
listcamera();

Thanks for help with this issue in firefox.


text:
Q: Bubble sort not sorting properly in python I'm making bubble sort in Python but have no idea why it doesn't sort properly.
N = [80000, 20, 40 , 50, 10000, 50, 60, 90, 100, 5000, 22]
for i in range(len(N)-1):
    for j in range(len(N)-i-1):
        if(N[i] > N[i+1]):
            N[i], N[i+1] = N[i+1], N[i]
print(N)

This is result of this code
[20, 40, 50, 10000, 50, 60, 90, 100, 5000, 22, 80000]

A: You should use 'j' instead of 'i' in the body of the second loop. Otherwise it is pointless to have both loops. Only the outer loop is effectively executed.

A: You should compare N[j] with N[j+1], because you need repeatedly swapping the adjacent elements if they are in wrong order.
N = [80000, 20, 40 , 50, 10000, 50, 60, 90, 100, 5000, 22]
for i in range(len(N)-1):
    for j in range(len(N)-i-1):
        if(N[j] > N[j+1]):
            N[j], N[j+1] = N[j+1], N[j]
print(N)

Output
[20, 22, 40, 50, 50, 60, 90, 100, 5000, 10000, 80000]

A: I believe you mixed up your indices i and j. It should read:
N = [80000, 20, 40 , 50, 10000, 50, 60, 90, 100, 5000, 22]
for i in range(len(N)-1):
for j in range(len(N)-i-1):
    if(N[j] > N[j+1]):
        N[j], N[j+1] = N[j+1], N[j]
print(N)

Output:
[20, 22, 40, 50, 50, 60, 90, 100, 5000, 10000, 80000]


text:
Q: Weird C library linkage issues on Mac - Segmentation Fault I have a strange segmentation fault that doesn't exist when everything is in 1 .c file, but does exist when I put part of the code in a dynamically linked library and link it to a test file. The complete code for the working 1 .c file code is at the bottom, the complete code for the error system with 2 .c and 1 .h file come first.
Here is the error system:
example.h:
#include <stdio.h>
#include <stdlib.h>

typedef struct MYARRAY {
  int len;
  void* items[];
} MYARRAY;

MYARRAY *collection;

void
mypush(void* p);

example.c:
#include "example.h"

void
mypush(void* p) {
  printf("Here %lu\n", sizeof collection);
  puts("FOO");
  int len = collection->len++;
  puts("BAR");
  collection->items[len] = p;
}

example2.c:
This is essentially a test file:
#include "example.h"

void
test_print() {
  puts("Here1");
  mypush("foo");
  puts("Here2");
}

int
main() {
  collection = malloc(sizeof *collection + (sizeof collection->items[0] * 1000));
  collection->len = 0;
  puts("Start");
  test_print();
  puts("Done");
  return 0;
}

Makefile:
I link example to example2 here, and run:
example:
  @clang -I . -dynamiclib \
    -undefined dynamic_lookup \
    -o example.dylib example.c
  @clang example2.c example.dylib -o example2.o
  @./example2.o
.PHONY: example

The output is:
$ make example
Start
Here1
Here 8
FOO
make: *** [example] Segmentation fault: 11

But it should show the full output of:
$ make example
Start
Here1
Here 8
FOO
BAR
Here2
Done

The weird thing is everything works if it is this system:
example.c:
#include <stdio.h>
#include <stdlib.h>

typedef struct MYARRAY {
  int len;
  void* items[];
} MYARRAY;

MYARRAY *collection;

void
mypush(void* p) {
  printf("Here %lu\n", sizeof collection);
  puts("FOO");
  int len = collection->len++;
  puts("BAR");
  collection->items[len] = p;
}

void
test_print() {
  puts("Here1");
  mypush("foo");

  puts("Here");
}

int
main() {
  collection = malloc(sizeof *collection + (sizeof collection->items[0] * 1000));
  collection->len = 0;
  puts("ASF");

  test_print();

  return 0;
}

Makefile:
example:
  @clang -o example example.c
  @./example
.PHONY: example

Wondering why it's creating a segmentation fault when it is linked like this, and what I am doing wrong.
I have checked otool and with DYLD_PRINT_LIBRARIES=YES and it shows it is importing the dynamically linked libraries, but for some reason it's segmentation faulting when linked but works fine when it isn't linked.

A: Your problem is this, in example.h:
MYARRAY *collection;

Since both main.c and example.c include this file, you end up defining collection twice, which results in undefined behavior. You need to make sure you define each object only once. The details are relatively unimportant since anything can happen with undefined behavior, but what's probably happening is that main.c is allocating memory for one object, but the one example.c is using is still NULL. As mentioned in the comments, since you define collection in main.c your linker is able to build the executable without needing to look for that symbol in the dynamic library, so you don't get a link time warning about it being defined there too, and obviously there'd be no cause for a warning at the time you compile the library.
It works for you when you put everything in one file because obviously then you're not defining anything twice, anymore. The error itself is nothing to do with the fact you're using a dynamic library, although that may have made it harder to detect.
It would be better to define this in example.c and provide a constructor function, there's no need for main() to be able to access it directly. But if you must do this, then define it in example.c and just declare an extern identifier in the header file to tell main.c that the object is defined somewhere else.


text:
Q: How to check if resque job has finished I have a case scenario where I need to run multiple record updates in the background(using resque) and I want to give user visual indicator of how the task is running(eg started/running/finished).
One way of achieving this(which I can think of) is saving the current state into a table, then showing the state to user by simple page refresh.
Can anyone suggest a better solution of doing it?I want to avoid creating the whole migration, model, controller for this.
Thanks

A: As I've commented, resque-status gem could be useful for you. I am not sure if that is an answer but since you said that you do not want to create migration, model and controller for this. Thus, a gem might be the way to go.
From the job id you can get the status you are looking for, for example:
status = Resque::Plugins::Status::Hash.get(job_id)
status.working? #=> true

There is also a front-end called resque-web, check that out too.

A: You may use ruby's global variable $var_name = 'foo'. However I am not sure about it, because they are considered bad practice in rails, but in this case I see them reasonable, as soon as their name is very unique.
It can be done like (in case of resque):
class UpdateJob
  @queue = data

  def self.perform
    $my_job_name_is_running = true
    MyJobName.new.run
    $my_job_name_is_running = nil
  end
end

then you can access them from anywhere in the app:
while $my_job_name_is_running
  puts "job is running..." if $my_job_name_is_running
  sleep 3 # important to not overload your processor
end

Ruby global vars are not very popular. Check docs for more info https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/globalvars.html


text:
Q: List of parameters in JMH benchmark test I am writing performance tests for an HTTP server using my custom Java library that is sending REST requests to the server. At the beginning, I am performing data preparation stage in order to have a list of objects that I want to send in requests to my server.
Now, the problem is, that I can test a list of parameters that can be injected into the benchmark function using @Param annotation:
@Param({"param1", "param2", ...})

The problem is, I would like to achieve the same having Java List of parameters and to avoid having to iterate over them. Could you please give me any advice how I can do it?

A: I used a workaround using @Setup(Level.Trial) with a switch statement inside that initialized parameters as needed.
If you want an example: https://github.com/Imaskar/lettuce-threads/blob/master/src/main/java/fiddle/lettucethreadsbenchmark/LettuceThreads.java


text:
Q: Best option for sending Accounts and Contacts to another org? Currently I've designed an integration using a scheduled Batch Apex class and REST API callouts to sync certain Accounts and Contacts from one org to another org that represents the company's master data. In the receiving (master) org, I'm using a phonetic matching algorithm to see if the Account and Contact already exist. Depending on the match confidence the code may choose to use an existing Account and attach the Contact (or use an existing Contact). If the match confidence is too low for the Account, it will create the Account and the associated Contact. There's also some task creation logic depending on the match confidence for a rep to double check the created records for a duplicate.
My question is, what other options are out there that can automatically create records in another org with somewhat advanced duplication checking? I understand that there may be a number of paid tools out there to do this, but I'm looking to do the legwork myself here, as we're working with a limited budget.
Curious to know other's thoughts on what I've designed, any pitfalls I'm not seeing, or how you personally would accomplish it.
Thanks!


text:
Q: Python: converting list of lists to tuples of tuples A Python newbie! I need help converting a list of lists tuples of tuples.
I want to call the append_as_tuples function, but every time I return it, it says
it can only concatenate lists (not tuples) to lists
Here is what I have so far:
def append_as_tuple(t, l):
    ''' Convert list l to a tuple and append it to tuple t as a single value '''
    return t[:] + (tuple(l),)

def convert_lists(lol):
    t = []
    if type(lol) == a or type(lol) == tuple:
        return [convert_lists(lol) for i in t]
    return append_as_tuples(lol,a)

#- test harness#

a=[range(5), range(10,20), ['hello', 'goodbye']]
print a
print convert_lists(a)
print convert_lists([])

A: To convert list_of_lists to a tuple of tuples, use
tuple_of_tuples = tuple(tuple(x) for x in list_of_lists)

A: there is a python built in function:
list and tuple
list( the tuple)...to conver tuple to list
tuple( the list )....to convert list to tuple


text:
Q: How do I get only the new lines from a string (an EC2 box' console output) in Ruby? I am writing a Rake task that boots an EC2 instance and runs some commands on it.
AWS' Ruby SDK has:
instance.console_output, which returns a String of the full output (from the moment the machine booted until present).
What I really want is the "diff" between the last output and the current, so that I can just print the new lines to my local console.
I feel like there should be a tool for this somewhere in a Gem or Ruby library, but searching on Google has yielded nothing.
Any help, or am I stuck doing:
total = output.lines.length
new_lines = total - last
puts output.lines[-1..new_lines].to_a.join
last = total

in a loop?

A: Check out...

*

*differ

*diffy

*diff-lcs
These are just a few that I've come across.  There are many others.


text:
Q: Extending isomorphism on closed subschemes to open neighborhoods Let $X, Y$ be schemes, $Z, Z'$ closed subschemes of $X, Y$ respectively. Assume there is an isomorphism $f: Z\to Z'$, is it possible to find open neighborhoods $U, V$ of $Z, Z'$ respectively such that there is an isomorphism $F: U\to V$ extending $f$? Or under what mild condition such an extension always exists?
I guess we need to assume that $X, Y$ are regular schemes and the inclusion of $Z, Z'$ are regular immersions. In that case it's easily reduced to the case when $Y$ is the total space of the normal bundle $N_{Z/X}$ of $Z$ in $X$ and $Z'$ being the zero section. And then the result would be something like the tubular neighborhood theorem in differential topology. But I can't prove such a tubular neighborhood theorem for (regular closed immersion of) schemes.


text:
Q: Robot Framework: Rest call gives "unicode object has no attribute copy" error Below error occurring on my code
${resp}=  Post Request  sw3  https://sw3-   test.test1.com/api/v1/test1/patients
\  ...  Content-Type:application/json
\  ...  Authorization:authkey02    Accept=application/json

Error as follows
KEYWORD ${resp} = RequestsLibrary . Post Request sw3, https://sw3-test.test1.com/api/v1/test1/patients, Content-Type:application/json, Authorization:authkey02, Accept=application/json
Documentation:
Send a POST request on the session object found using the
Start / End / Elapsed:  20170315 12:08:21.283 / 20170315 12:08:21.285 / 00:00:00.002
12:08:21.283    TRACE   Arguments: [ 'sw3' | 'https://sw3-test.test1.com/api/v1/test1/patients' | 'Content-Type:application/json' | 'Authorization:authkey02' | 'Accept=application/json' ]
12:08:21.284    FAIL    AttributeError: 'unicode' object has no attribute 'copy'

This works ok if i do not use the third line of code - what gives?

A: You can give it a try like passing those key:value pairs as a dictionary Header variable.
&{Header}=   Content-Type:application/json    Authorization:authkey02
   Accept=application/json

${resp} = RequestsLibrary.Post Request  sw3   https://sw3-test.test1.com/api/v1/test1/patients    headers=${Header}


text:
Q: Java - enum - como crear un método que compruebe los valores He definido el siguiente enum con las posiciones de los jugadores en el campo.
Quiero asociar las posiciones a colores mediante getColor y lo hago de la siguiente forma:
public class Position {

    enum Position{
         GOALKEEPER, DEFENDER, MIDFIELDER, FORWARD;
    }

    public String getColor(Position position) {
        switch (position){
            case GOALKEEPER:
                return "BLACK";
            case DEFENDER:
                return "RED";
            case MIDFIELDER:
                return "GREEN";
            case FORWARD:
                return "BLUE";
        }
    }   // error - missing return statement
}

Los test que debo pasar son los siguientes:
void testGetColor() {

        position = Position.GOALKEEPER;
        assertEquals("BLACK", position.getColor());

        position = Position.DEFENDER;
        assertEquals("RED", position.getColor());

        position = Position.MIDFIELDER;
        assertEquals("GREEN", position.getColor());

        position = Position.FORWARD;
        assertEquals("BLUE", position.getColor());
}

Tengo un error missing return statement (que lo indico dentro del código) pero no entiendo por qué si en cada caso hago un return
Qué es lo que estoy haciendo mal?
Gracias.

A: Debes añadir un caso default: en el switch. Por ejemplo:
    switch (position){
        case GOALKEEPER:
            return "BLACK";
        case DEFENDER:
            return "RED";
        case MIDFIELDER:
            return "GREEN";
        case FORWARD:
            return "BLUE";
        default:
            return "NO-COLOR";// O throw new RuntimeException("Posicion no valida")

    }

Si no, el switch puede tener casos sin retorno, y es lo que provoca el error.
Saludos !


text:
Q: Debian: environment variable not available for script running from cron? I have this line:
echo $(date '+%Y %b %d %H:%m') Your output $HOSTNAME

When I do it manually from command line I can see my $HOSTNAME just fine.
However, when it's running from a script that's run by a cron job (root) the $HOSTNAME is always empty.
How can this be fixed?

A: $HOSTNAME is set by some shells (like bash), it is not an environment variable
Set your shell script to run under bash (put #!/bin/bash as the first line instead of #!/bin/sh) and try again


text:
Q: Best Android ORM to merging with remote REST servers After search, I found ORMLite is the first Android ORM
but I found ORMLite does not provide a solution for merging with remote REST servers.
How can I sync data between a webserver and an android app through ORMLite or other orm?

A: Basically on mobile platform we have very less open source frameworks which provides both ORM and RESTful service on all the major platforms (Android, iOS, Windows).
Based on my research, please find below some of the most popular frameworks available in different areas:
ORM

*

*Android: OrmLite, GreenDAO, Active Android

*iOS: FMDB

*Windows: dapper-dot-net, Simple.Data
RESTful

*

*Android: Restlet, Retrofit

*iOS: RestKit

*Windows: ServiceStack
You can also check Siminov Framework which provides both ORM and RESTful service. It is available on all the major platforms (Android, iOS and Windows 8.1).

A: Try to use https://github.com/Raizlabs/DBFlow
It has a Direct-to-database parsing for data such as JSON so you can easily do the mapping from web service response to local database.
Check this example:
https://github.com/Raizlabs/DBFlow/blob/master/usage/ModelContainers.md


text:
Q: Simple Java Program Strange Output This is my program...
import java.lang.Math;
class SquareRoot
{
  public static void main(String args[])
  {
    try
    {
      System.out.println("Enter A Number To Find its Square Root");
      System.out.flush();
      double x = (double) System.in.read();
      double y;
      y = Math.sqrt(x);
      System.out.println("Square Root of " + x + " is " + y);
    }
    catch (Exception e)
    {
      System.out.println("I/O Error! Humein Maaf Kar Do Bhaaya");
    }
  }
}

If I enter 75 as input it shows.. Square Root of  55.0 is <55's square root>
On entering 23 it shows Square Root of 50.0. Where am I wrong? No problems in compilation.
I am using DrJava IDE. JDK 7u25 Compiler. Windows 7 32 bit.

A: System.in.read() returns one character. Then its integer representation casted to double.
You may use BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
double number = Double.parseDouble(s);

Or Scanner:
Scanner scanner = new Scanner(System.in);
double number = scanner.nextDouble();

A: double x = (double) System.in.read();

Nope. I would recommend wrapping this up in a Scanner.
Scanner s = new Scanner(System.in);
double x = s.nextDouble();
String str = s.nextLine(); // <-- Just an example!

Just makes for much nicer code!
 Remember
Put import java.util.Scanner at the top of your page, otherwise Java will kick up a bit of a fuss!

A: The problem is that when you are casting as a double when getting the user input, it is converting the first character in the input into its ascii value. ('7' = 55, '2' = 50)

A: Use follows:
Scanner s = new Scanner(System.in);
double x = s.nextDouble();


text:
Q: Python send mails azure protection for i in range(3):
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.Subject = 'test ' + datetime.now().strftime('%#d %b %Y %H:%M')
    mail.To = "example@example.com"
    #attachment = mail.Attachments.Add(os.getcwd() + "\\")
    #attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "currency_img")
    mail.HTMLBody = r"""
    Dear Carrie,

    The highlighted of currencies exchange prices is as follow:

    For more details, you can check the table in the Excel file attached.

    Best regards,

    Yeung
    """
    mail.Attachments.Add(os.getcwd() + "\\example.xlsx")
    mail.Send()

Hi, I want do send a lot of mails via python in outlook (see code above).
Unfortunately for every loop outlook wants me to confirm the protection lvl (see picture below). Is there a way to avoid protection lvl or set up a default one e.g. "Öffentlichkeit"?

A: To set a sensitivity label in Outlook (MSIP) you need to add a user property by using the UserProperties.Add method to an item in the following format:
"MSIP_Label_" & guid_internal_use_only & "_Enabled"

But I'd suggest exploring internals of Outlook mail items using MFCMAPI or OutlookSpy to find the exact solution. Try to set it manually then explore internals using these tools.


text:
Q: How to fix maximum call stack size exceeded error in angular 11? I have 2 modules in angular 11

*

*CustomerModule

*AccountingModule

and declare some component as widget component in these modules that used in each other

*

*CustomerModule -> CustomerBlockInfoWidget

*AccountingModule -> AccountingBalanceWidget

now want to use CustomerBlockInfoWidget in AccountingModule
and AccountingBalanceWidget in CustomerModule
and finally, I have the infinity load and get Maximum call stack size exceeded error
now how I can use these widgets that fix the infinity load

A: Maximum call stack size exceeded error is always a symptom of an infinite loop. The provided information doesn't point to a possible place in the code that triggers it.
It might be a simple loop with no chance for an exit or a more complex scenario like Function A calls Function B which calls Function C which calls Function A and here it goes again.
If you have a call stack of the error, reading it should be enough to notice this infinite execution.

A: Please make sure that you did not add any components, directives, and pipes in the import array of modules.
NOTE
You can add standalone components, directives, and pipes in the import array of the module.

A: In may case, I accidentally included my component to import instead of export. the
commented part was causing the problem.
enter image description here


text: Q: How does a quark $u$ or $d$ turn into one another? The pseudo-explanation that the proton is stable because it has a lower mass than the rest is incomplete, because a particle formed by three u: uuu would have still a lower mass. I know that some answers will signal conservation of some physical quantities, but why must they be conserved or equivalently, why there exist the corresponding symmetries?


text:
Q: Is it possible to specify newline type while reading a file in ruby I frequently deal with UTF-16LE files encoded on windows which have a \r\n carriage return.  There is no problem converting the file to UTF-8 by using:
File.new(filepath, 'r:utf-16le:utf-8')

But this of course does not get rid of the \r.  The way I currently get rid of them is with
str.gsub("\r", "")

But it would be nice to take care of it while reading the file in.  String#encode has :cr_newline, :crlf_newline, and :universal_newline options which convert all newlines to a desired kind of newline.  Is there a way to apply these or similar options while reading in a file?

A: The method IO#gets takes an optional argument that allows you to pass a string to define how to separate the lines:
file = File.new(filepath, 'r:utf-16le:utf-8')
while (line = file.gets("\r\n"))
   ...
end


text:
Q: How can i add a modal multiple times in laravel9 Am trying to add a  modal at multiple locations in my view but only one occurrence of the modal works in my laravel view. The first occurrence of the modal works. The rest which happen to apper in the othe table rows are not working. Please help me resolve this error. I need the modal to repeat it self in all the table rows because i need them to perform an action on each of the rows in the table
this is the view

 --}}
                Create

                            Dish Id
                            Menu_name
                            Unit Cost
                            Dish Details
                            Action

                        @if ($menu->count())
                   @foreach ($menu as $index => $menu)

                    {{-- {{$index + $menu->firstItem()}}	 --}}
                    {{$menu->id}}
                    {{$menu->menu_name}}
                    {{$menu->unit_cost}}

                        @foreach ($menu->description as $description)
                        {{$description}}
                        @endforeach

                      id)}}" title="Show">show
                      id)}}" title="Edit">Edit
                      @include('menu.order_menu')
                      <form method="POST">
                        @csrf
                        @method('DELETE')
                        id)}}">
 Delete??

                      </form>

                   @endforeach

                  @endif

                this the modal

                {{-- {{$menu->links()}} --}}

@endsection

   <button id="myBtn">order</button>

{{$menu->menu_name}}

        @foreach ($menu->description as $description)
                        {{$description}}
                        @endforeach

{{$menu->unit_cost}}

        <form action="">
       <button>order</button>
       <button>customize</button>
        </form>

A: Tim inspired me to take another approach to solve this problem. And I am most grateful to him.
I realized that all the table entries had unique names and IDs in the database so I used the Ids and names as the button id and modals IDs. This way, all entries have unique modal and button Id's

   <button id="{{$menu->id}}">order</button>

menu_name}}" class="modal">

{{$menu->menu_name}}

        @foreach ($menu->description as $description)
                        {{$description}}
                        @endforeach

{{$menu->unit_cost}}

        <form action="">
            <button>order</button>
        </form>

        <form action="">
            <button>customize</button>
        </form>


text:
Q: Hot Chocolate GraphQL batching Queries and applying Selection and Filtering middleware to EF SQL Using HotChocolate Version: 10.5.5
And given the following Customer domain model:
public class Customer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string CompanyName { get; set; }
    public string SalesPerson { get; set; }
}

When exposing the Entity Framework Customers dbset in a query interface:
[UseSelection]
[UseFiltering]
public IQueryable<Customer> GetCustomers([Service] AdventureWorksContext ctx) => ctx.Customers;

And executing the following graphql query:
query {
  friendlyBikeShop: customers (where: { companyName: "Friendly Bike Shop"}){
    firstName,
    lastName
  },
  frontSportingGoods: customers (where: { companyName: "Front Sporting Goods"}){
    firstName,
    lastName
  }
}

Results in the following two SQL statements:
SELECT [c].[FirstName], [c].[LastName]
FROM [SalesLT].[Customer] AS [c]
WHERE [c].[CompanyName] = N'Front Sporting Goods'

SELECT [c].[FirstName], [c].[LastName]
FROM [SalesLT].[Customer] AS [c]
WHERE [c].[CompanyName] = N'Front Sporting Goods'

This isn't ideal as I would like to merge this into one SQL statement:
SELECT [c].[FirstName], [c].[LastName]
FROM [SalesLT].[Customer] AS [c]
WHERE [c].[CompanyName] in (N'Front Sporting Goods', N'Front Sporting Goods')

A first attempt to solve this problem using a GroupDataLoader is as follows:
[UseSelection]
[UseFiltering]
public Task<Customer[]> GetCustomersByCompanyName(IResolverContext resolverCtx, [Service] AdventureWorksContext ctx, string companyName) =>
    resolverCtx.GroupDataLoader<string, Customer>("customers", async keys =>
    {
        var customers = await ctx.Customers.Where(customer => keys.Any(key => key == customer.CompanyName)).ToListAsync();
        return customers.ToLookup(customer => customer.CompanyName);
    }).LoadAsync(companyName, default);

And executing the following graphql:
query {
  friendlyBikeShop: customersByCompanyName(companyName: "Friendly Bike Shop"){
    firstName,
    lastName
  },
  frontSportingGoods: customersByCompanyName(companyName: "Front Sporting Goods"){
    firstName,
    lastName
  }
}

Results in the following single SQL statement:
SELECT [c].[CustomerID], [c].[CompanyName], [c].[FirstName], [c].[LastName], [c].[SalesPerson]
FROM [SalesLT].[Customer] AS [c]
WHERE [c].[CompanyName] IN (N'Friendly Bike Shop', N'Front Sporting Goods')

The drawback to this approach is that Filtering and Selection isn't factored into the dynamically created SQL statement generated by EF, this is only applied AFTER the result set has returned from the database.
How do I return an IQueryable on the query interface so that the Filtering and Selection middleware will apply and be factored into the the SQL statement which is dynamically generated and still force this to be executed in a single batch?

A: The data API of HotChocolate and the Dataloaders do not work well together.
These are two different approaches that cannot be mixed in the same resolver.
Filtering works on the resolver level whereas data loaders do run outside of the resolver execution.
This query contains two resolvers:
query {
  friendlyBikeShop: customers (where: { companyName: "Friendly Bike Shop"}){
    firstName
    lastName
  }
  frontSportingGoods: customers (where: { companyName: "Front Sporting Goods"}){
    firstName
    lastName
  }
}

Therefor you can either go with filtering and projections and two queries or you go with data loaders and only execute one query.
As an alternative query you could also do this:
query {
  customers (
    where: {
        companyName_in: [
            "Friendly Bike Shop",
            "Front Sporting Goods"
      ]
  }){
    firstName
    lastName
  }
}

This would return both results in a single request


text:
Q: Implementing twitter login in Symfony 1.4 without sfGuard I've an existing project in symfony 1.4. Worse thing, project is not using sfGuard plugin but implemented custom user authentication.
As a new feature requirement, client requested to add login with twitter support in the app.
I went through twitter PHP libs which seems do not fit for symfony 1.4 without some level of customization.
I also went with one Symfony plugin (sorry but forget the link) but it also do not meet my requirements as (I guess) it is tightly coupled with sfGuard.
I started customizing tmhOAuth to match my requirements but I'd like to ask; is there is any symfony 1.4 plugin for twitter, which do not depends on sfGuard?


text:
Q: ASP.NET Core 2.0 service life time I have api application ,service & repository class library application . Service part i write business logic and repository only communicate for database. My question which type of dependency is best for repository and service .
services.AddScoped<ITicketRepository, TicketRepository>();
services.AddTransient<ITicketRepository, TicketRepository>();
services.AddSingleton<ITicketRepository, TicketRepository>();

A: Like always, it depends. My suggestion is the following:

*

*Scoped: in my opinion, there can be two main reasons for using this:

*

*Your dependency has a dependency which has a scoped lifetime. In this case, you cannot use singleton, but can use scoped or transient. Which one you should take is based on the other criteria.

*Your dependency has some state which makes it unsuitable to be used in singleton scope, but it is heavyweight enough that you don't want to register it as transient. Another possibility is that, again, it cannot be used in singleton scope, but it is fine to share the same instance per request (scope) and you don't want to add the overhead of constructing new ones if two types depend on the same thing and both of them are used to serve a single request.

*Transient: this is the simplest approach. Every time an instance of a dependency registered in this manner is required, a new instance is created. This is probably the most foolproof, but can cause serious overhead if its usage is not justified. @Tony Ngo pointed out in his answer, quoting from the official docs, that this works best for lightweight, stateless objects, but I'd argue that statelessness is a very good indicator that you may want to use singleton lifetime as statelessness guarantees that the same object can be used concurrently just fine. Whether you choose transient or singleton lifetime in this case really depends whether you care about such aspects of performance like GC cost, which is obviously much, much higher if you create a new instance every time such a dependency is required, even if you could avoid doing so. Having said that, transient is used by many developers in this scenario as well, probably due to its foolproofness, or simply because they tend to think about it as the default choice.

*Singleton: the points above basically summarize this one: you can choose this when there is absolutely no reason to create a new instance of the dependency for each request (scope) or to use an other dependent instance. Note that like said before, you cannot use singleton lifetime when the type has a dependency which is registered as scoped.

A:
Transient lifetime services (AddTransient) are created each time
  they're requested from the service container. This lifetime works best
  for lightweight, stateless services.
Scoped lifetime services (AddScoped) are created once per client
  request (connection).
Singleton lifetime services (AddSingleton) are created the first time
  they're requested (or when Startup.ConfigureServices is run and an
  instance is specified with the service registration).

So depend on what you need you can choose correct liftetime you can view it more here

A: I am assuming your TicketRepository is depend on your EF Core DbContext and your
EF Core DbContext is by default registered as ScopedSerivce  so here registering TicketRepository as SingletonService is out of consideration as because:

It's dangerous to resolve a scoped service from a singleton. It may cause the service to have incorrect state when processing subsequent requests.

For more details: Dependency injection in ASP.NET Core-Service lifetimes
Now you can choose between AddTransient<> and  AddScoped<> where:

Transient lifetime services (AddTransient) are created each time they're requested from the service container. This lifetime works best for lightweight, stateless services.
Scoped lifetime services (AddScoped) are created once per client request (connection).


text:
Q: Obtaining very high loss during fine tuning of ResNetV2 in keras I am fine-tuning ResNetV2 model trained previously using transfer learning on 320 images from 40 classes. I am adding 1 class containing 8 images to the model and trying to retrain the model, but I am getting a very high loss value during training. I got a good accuracy(~91%) when training on 40 classes. Please help
base_model = models.load_model('/content/drive/MyDrive/saved_model/resnetv2.h5')
base_model.trainable = True
preds=Dense(41,activation='softmax',name='main_output')(base_model.layers[-2].output)
model=Model(inputs=base_model.input,outputs=preds)

train_datagen = ImageDataGenerator(rescale = 1./255,shear_range = 0.2,zoom_range = 0.2,horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory(train_path,target_size = (224,224),batch_size = 2, class_mode = 'categorical')
test_set = test_datagen.flow_from_directory(valid_path,target_size = (224,224),batch_size = 2,class_mode = 'categorical')

model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
training = model.fit_generator(training_set,validation_data=test_set,epochs=5,steps_per_epoch=1)


text:
Q: Wordpress: HTML sidebar at bottom, instead of right aligned with body I added HTML to my functions.php. After the
<?PHP get_sidebar(); ?>
and before
<?php get_footer(); ?>
while the CSS is added in my style.css Child theme. The result is my box of HTML under the main content on my home page instead of being on the right side of the main content. I am hoping someone may be able to help me?
I tried to add my HTML and CSS but it wouldn't let me post it.
I've spent about 3 hours on this by myself so far. First I tried reformatting a feature provided by the Minamaze Wordpress Theme, but I figured I may as well just right my own code as it may be easier to implement.

A: I fixed it! Here's how: The real problem was the fact that my front page articles were individually grouped instead of wrapped in a class. I found the index.php file (the copy from my child theme) and surrounded the homepage content in a named div class. Below is code from my index file. Put a div wrapper class between get_header and the php line below it. Close the div before the get_sidebar.

get_header(); ?>

            <?php while( have_posts() ): the_post(); ?>

                <article id="post-<?php the_ID(); ?>" <?php post_class('blog-article'); ?>>

                    <?php if ( has_post_thumbnail() ) {
                        $column1 = ' two_fifth';
                        $column2 = ' three_fifth last';
                    } else {
                        $column1 = NULL;
                        $column2 = NULL;
                    } ?>

                    <header class="entry-header<?php echo $column1; ?>">
                        <?php thinkup_input_blogimage(); ?>

                    <div class="entry-content<?php echo $column2; ?>">
                        <?php think_input_blogtitle(); ?>

                        <?php thinkup_input_blogmeta(); ?>

                        <?php thinkup_input_blogtext(); ?>

            <?php endwhile; ?>

            <?php thinkup_input_pagination(); ?>

        <?php else: ?>

            <?php get_template_part( 'no-results', 'archive' ); ?>

        <?php endif; ?>

  ?php get_sidebar(); ?>

Under get_sidebar, you can put in your HTML code for YOUR sidebar that you wish to add.
Once I wrapped them into the php into it's own class and wrapped my sidebar boxes into their own class, I used float: left and right respectively in my CSS child theme, successfully creating a sidebar. I also made their widths percentages to increase usability. You can use this same method in the content-page.php, content-single.php, if you wish to add a side bar to other pages besides just the home screen.


text:
Q: Assignments are not expressions, and only expressions are allowed in this context Spring Boot Kotllin
I use Kotlin and Springboot in my application . I want to set
problem.problemId=patient.patientId   in side a lambda function but
kotlin give error as response. I get Below type of error

Assignments are not expressions, and only expressions are allowed in this context Spring Boot Kotllin

patientservice.kt

package com.nillmani.hospitalmanagement.service

import com.nillmani.hospitalmanagement.entity.Patient
import com.nillmani.hospitalmanagement.exception.PatientNotFoundException
import com.nillmani.hospitalmanagement.model.ReqPatient
import com.nillmani.hospitalmanagement.repository.PatientRepository
import org.modelmapper.ModelMapper
import org.slf4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*
import java.util.function.Consumer

@Service
class PatientService {
    @Autowired
    private lateinit var patientRepository: PatientRepository
    private lateinit var modelMapper : ModelMapper
    private lateinit var logger: Logger

    fun PatientService(patientRepository: PatientRepository, modelMapper: ModelMapper, logger: Logger) {
        this.patientRepository = patientRepository
        this.modelMapper = modelMapper
        this.logger = logger
    }

    @Throws(Exception::class)
     fun findAll():List<ReqPatient>{
        try {
            var patient : List<Patient?>? = patientRepository.findAllByStatusEquelsOne()
            if (patient != null) {
                if (patient.size < 1){
                    logger.error("Here No patient Record available")
                    throw PatientNotFoundException()
                }
            }
            val dto : ReqPatient = modelMapper.map(patient,ReqPatient::class.java)
            val patientDto  : List<ReqPatient> = listOf(dto)
            patientDto.forEach{patient ->(patient.problems).forEach { problem ->(problem.problemId=patient.patientId ) }}
            return listOf(dto)
        }catch (e:Exception){
            throw Exception(e)
        }
     }
}

I get error at this line

val patientDto  : List<ReqPatient> = listOf(dto)
            patientDto.forEach{patient ->(patient.problems).forEach { problem ->(problem.problemId=patient.patientId ) }}

How can I assigb PatientId to ProblemID  if I Use assignment operator
kotlin gives exception

A: You need to remove the parentheses around the assignment
val patientDto  : List<ReqPatient> = listOf(dto)
patientDto.forEach{patient ->
    (patient.problems).forEach { problem -> problem.problemId = patient.patientId  }
}

In kotlin you can enclose an expression in parentheses to create a parenthesizedExpression. since
assignments are not expressions you get the error.


text:
Q: Solve minimization problem involving p-norms Consider the following minimization problem:
\begin{equation*}
\begin{aligned}
& \underset{}{\text{minimize}}
& & \nabla f(\hat{x})^Tp \\
& \text{subject to}
& & ||p||_\infty=1
\end{aligned}
\end{equation*}
I need to prove that the solutions to this problem are all vectors $p^*$ such that $||p^*||_\infty=1$ and $\nabla f(\hat{x})^Tp^*=-||\nabla f(\hat{x})||_1$.
Now, when the problem involves norm 2 I can consider the angle $\theta$ between $\nabla f(\hat{x})$ and $p$
\begin{equation*}
\nabla f(\hat{x})^Tp=cos(\theta)||\nabla f(\hat{x})||_2||p||_2=cos(\theta)||\nabla f(\hat{x})||_2
\end{equation*}
The second inequality is due to the fact that we assume $||p||_2=1$.
Clearly the minimizer is attained when $cos(\theta)=-1$ and $p=-\frac{\nabla f(\hat{x})}{||\nabla f(\hat{x})||}$.
How can I prove the original statement, involving $||p||_\infty$ and $||\nabla f(\hat{x})||_1$? I know there is some relationship between norms (mainly, that $||x||_\infty\leq ||x||_2 \leq ||x||_1$) but I'm not sure what to do next.

A: Let $$\nabla f(\hat x)=(a_1,a_2,\cdots ,a_n)$$then we need to minimize $$a_1p_1+\cdots +a_np_n$$subject to $$\max_n |p_n|=1$$this means that $$|p_k|\le 1\qquad,\qquad \forall k$$also $$-||\nabla f(\hat x)||_1=-|a_1|-\cdots-|a_n|\le a_1p_1+\cdots +a_np_n\le |a_1|+\cdots+|a_n|=||\nabla f(\hat x)||_1$$therefore the minimum is $-||\nabla f(\hat x)||_1$ and is attained when $$|p_k|=1\qquad,\qquad\forall k\\p_ka_k<0$$


text:
Q: cutting a wav file into segments I want to write a simple program that takes a moderately sized wav file (60 seconds or so) and cuts it into 1 second length segments of the same format (1.wav,2.wav,... etc) ... Is there a simple C++ or java library that could do this? I don't want to have to manipulate header information

A: Shell script wrapped around the ffmpeg command line utility. Also, sox.
http://sox.sourceforge.net/

A: You can use AudioInputStream class to do it. Also check this site for more info about AudioInputStream

A: Look at libsndfile. Also see this other post.
You will want to:

*

*remove the WAV headers to access the raw PCM sample data

*loop through sample_rate samples which will represent 1 second of audio and package these buffers into a new WAV file (with headers) until you reach EOF of the original.

HTH

A: ffmpeg has two flags that might be of us: -t which sets the duration of the target file, and -ss which sets the point at which you start reading in the input file.
So:
ffmpeg -t 2 -i input.mp3 output.mp3
ffmpeg -ss 2 -t 2 -i input.mp3 output2.mp3
Creates two files - one which contains the first two seconds of input.mp3, and one which contains two seconds of input.mp3 starting from the 2 seconds in (i.e. the second two seconds...).
Combinations of this can probably be achieved to get what you want from the file.


text:
Q: Not having to re-define atributes in class inheritance in Python I've got something like this:
Class Parent(object):
    def __init__(self, x=None):
        self.x = x

Class Child(Parent):
    def __init__(self, y):
        super(Child, self).__init__()
        self.y = y

test = Child(y=42)

That works nice: test.y equals 42 and test.x equals None. The problem comes when I try to define x:
test = Child(x=32, y=42)
That obviously doesn't work; x argument wasn't expected. I know a fix for this would be:
Class Child(Parent):
    def __init__(self, x, y):
        super(Child, self).__init__(x)
        self.y = y

But I would need to do this for lots of variables in quite deep parent-child inheritance, and writing all previous arguments in every new __init__ doesn't look pythonic, in my opinion. There's surely another way, but I don't know how.
Any ideas?

A: One way to do this would be to use kwargs:
class Parent(object):
    def __init__(self, x=None):
        print 'got', x
        self.x = x

class Child(Parent):
    def __init__(self, y, **kwargs):
        super(Child, self).__init__(**kwargs)
        self.y = y

The child automatically forwards it to the parent:
>> test = Child(y=42)
got None
>> test = Child(y=42, x=13)
got 13

This technically works, but I don't like it that much, though:

*

*The docstring of the subclass's ctor will not really explain what's expected. That's bad.

*If the number of arguments is small, the original question shouldn't be much of a problem. If the number is too large, perhaps the initialization parameters themselves need to form a class.


text:
Q: Link page bounded click handlers to Footer component Right now I have a Footer component with three different buttons. The onClick of two of those buttons depends on the page, and are defined in those pages. Currently I render the Footer component in the Page components separately, where the onClick functions are defined and handed as a prop, and is working great.
However I added the CSS element max-width to the pages, and is affecting the Footer too, which I don't want.
To solve this I need to render the Footer outside of the Page components, and in the Router component, just like the Header. But the issue is that I don't know how to link the click handlers of those two Footer buttons, which are defined in the Page components.
What would be the best way to solve this? Push the onClick functions in my Redux store?

Currently it's working like this:
Router.js

    <Switch>
        <Route path="/dashboard" component={DashboardPage} />
        <Route path="/settings" component={SettingsPage} />
    </Switch>

DashboardPage.js
const DashboardPage = () => (

        ...content

);

SettingsPage.js
const SettingsPage = () => (

        ...content

);

But how can I get it to work like this:
Router.js (new)

    <Switch>
        <Route path="/dashboard" component={DashboardPage} />
        <Route path="/settings" component={SettingsPage} />
    </Switch>

DashboardPage.js / SettingsPage.js
const DashboardPage = () => {

    // set the onClick of the footer somehow to myDashboardPageClickHandler()

    return (

            ...content

    );
};

A: I would recommend using the withRouter function of React Router to transform the Footer, like so:
const FooterWithRouter = withRouter(Footer);

then, inside the Footer component, define functions like so:
handleRightButtonClick() {
  const pathname = { this.props.location };

  if ( pathname === '/dashboard' ) {
    return myDashboardPageClickHandler;
  } else if ( pathname === '/settings' ) {
    return mySettingsPageClickHandler;
  }
}

and assign the onClick of the button to the return value of this function, like so:
<button class="right-arrow" onClick={handleRightButtonClick()}></button>

See if this works.


text:
Q: Are the ec2 T family instances objectively "worse" than the other ones? I wonder why the documentation seems to allude that the T instances should not be used in production. I am most concerned about advertised CPU performance and network availability.
Regardless of the cost and the credits thing, is there any reason to believe that the CPU performance of the T family ec2 instances is worse than other instance types with the same amount of cores and frequency?
Does the T instance have "access" to it's full non-baseline CPU performance as fast as other types? Or is there some kind of delay?
Can the performance of my instance be impacted by other customers putting more load on their instances?
Are latency spikes more likely to happen than with other types of instances?


text:
Q: Typescript initialize static variable of a class type I have two classes Foo and Bar. In class Bar I have a static variable called myFoo and I want it to be automatically initialized:
class Foo {
}

class Bar {
    static myFoo: Foo = new Foo();
}

However, I'm getting this error:

Uncaught ReferenceError: Foo is not defined

If I initialize that static variable in Bar's constructor then it works fine:
class Bar {
    static myFoo: Foo;

    constructor() {
         Bar.myFoo = new Foo();
    }
}

Why is that? What did I do wrong when I tried to initialize the static variable myFoo directly?

A: You can just have the call to initialize immediately follow the class declaration:
class MyClass {
    static initialize() {
        // Initialization
    }
}
MyClass.initialize();

A: You definitely don't want to do that second thing because that's going to overwrite myFoo every time you construct a new Bar and you certainly don't want that.
What you have here is a run time problem, not a compile time problem.  The Foo class has to be loaded before the Bar class is loaded otherwise the static initializer will fail.  If both classes are in a single file in the above order it works.  If the classes are in separate files and you tell TypeScript to compile to a single file it should figure out the correct order for you (though there are bugs in that area).  If you're compiling to separate files you'll need to include the scripts on the page in the correct order to satisfy the dependency.

A: As Jeffery Grajkowski said, your second approach is incorrect. You could just initialize in definition.
class Bar {
  static myFoo: Foo = new Foo();
}

A: This requires JQuery, but is what I do to have the equivalent of a 'static constructor'.
namespace SomeNamespace {
   $(() => SomeClass.StaticConstructor());

   export class SomeClass {
      public static StaticConstructor() {
      }
   }
}

This is also useful as the "entry point" of your application, for example.
namespace SomeNamespace {
   $(() => SomeClass.Start());

   export class SomeClass {
      private static sInstance: SomeClass;

      public static Start() {
         SomeClass.sInstance = new SomeClass();
      }
   }
}


text:
Q: missing values in sql I have table EMP which has only 1 column id
I have below input
1
3
4
6
10

I want output
2
5
7
8
9

I have written the below query
select level from dual connect by level<=10
minus
select id from emp;

Is there any other way to write this query? Can this be written without using connect by

A: Is there any other way to write this query. Can this be written without using connect by
Yes it can be written without connect by. The same thing can be done with CTE(it requires you some typing to do, but it's more generic in terms of code portability), which in this case does the same thing - generates a sequence of numbers. The idea is pretty much the same, different wording.
-- CTE. generates numbers from 1 to 10
with numbers(digit) as(
  select 1 from dual
  union all
  select digit + 1
    from numbers
   where digit < 10
)
select digit from numbers
minus
select id from emp;

A: Tricky one:
select rownum as id
from ALL_OBJECTS --(OR OTHER BIG TABLE)
where rownum <= 5
minus
select id from emp;

A: If you can take the results in a different form, then you can write this using lead():
select (id + 1) as first_missing_id,
       (next_id - 1) as last_missing_id,
       (next_id - id - 1) as num_missing
from (select e.*, lead(e.id) over (order by e.id) as next_id
      from emp e
     ) e
where next_id <> id + 1;

This shows the missing ranges of ids.  It is also probably faster than any version that creates a separate row for each id.

A: Public system varray sys.odcinumberlist:
select column_value
from   table(sys.odcinumberlist(1,2,3,4,5,6,7,8,9,10))
minus
select id from emp


text:
Q: Create data by combining query results in Django I have a 1-n relation in my models, e.g., 1 classroom - n students.
Classroom 1 - Joe

Classroom 1 - Tim

Classroom 1 - Julia

Classroom 2 - Bob

Classroom 2 - Alice

In my view I want to show a row for each classroom and a comma separated list for the students:
Classroom1 | Joe, Tim, Julia

Classroom2 | Bob, Alice

Right now, I find the records for each classroom and create the list of students and combine that to create a dictionary.
Is there a more efficient way to create this data?  Can I save the list of students with each Classroom?

A: For example you have
class Classroom(models.Model):
    name = models.CharField()

    def __str__(self):
        return self.name

class Student(models.Model):
    name = models.CharField()
    classroom = models.ForeignKey('Classroom')

    def __str__(self):
        return self.name

You can easily retrieve all students for Classroom like that
class_room1 = Classroom.objects.get(id=1)
class_room1.student_set.all()


text:
Q: Calculate percentage difference of 2 dates I need to calculate the completion percentage between two dates. I have two dates: date1 and date2. When date1 catches up to date2, it should be 100%. Any days the current date is after date1, there should be some progress. E.g. everyday until date2 is met, there should be some sort of progress.
I am having difficulty in finding the percentage of two dates and their differences.
This is related to
drawing a circle using bezier path swift
So currently, I have the following:
let percentFull = 1 - Double(min(Int(components.day!), 20) / 20)

A: You want to use DateInterval, it can do most of the work for you:
let duration = DateInterval(start: startDate, end: endDate).duration
let complete = DateInterval(start: startDate, end: currentDate).duration
let percentComplete = complete / duration

If you want it to be in the form of 0-100 rather than 0-1:
let adjustedPercent = percentComplete * 100.0


text:
Q: If I delete image A in MS Azure, will image B in the shared image gallery still work if it was based on A? To clarify in case the wording is unclear:

*

*Create image A from a VM

*Use image A to create image B in the shared images gallery (SIG)

*Delete image A

*Will image B still work?

Another way to phrase it is: do the images in the SIG require their source images to be maintained or can they be deleted? Are the images in the SIG pulling info from the source images or are they images themselves?

A: You can remove the source managed image since you create Azure VM from the image version in the shared images gallery (SIG) not directly from your source image.
However, you cannot update replication to another target region for your existing image version as it relies on the source image.
So, if you want to remove the source image, you'd better replicate the image to all the target regions where you want in the image version before you remove it or you could make a new image as the source image from existing VM at any time.

A: As @Gunny has commented before, you can replicate to other regions also if the source has been deleted