text:
Q: Update nested JSONB in postgresql using sequelize I am using NodeJS to update a nested info in the database but I can't seem to figure this out.
Data in database
 {
            "id": 1,
            "data": {
                "__v": 0,
                "_id": "5887e1d85c873e0011036889",
                "text": "you have to change this text",
                "type": "cat",
                "used": true,
                "user": "5a9ac18c7478810ea6c06381",
                "source": "user",
                "status": {
                    "feedback": "",
                    "verified": true,
                    "sentCount": 1
                },

My code to update:
UpdateFacts: async function (req, res, next) {
    const {text} = req.body
    const {id} = req.params

    if(!id){
      return res.status(400).send({message:'please provide id'})
    }

    if(!Object.keys(req.body).length){
      return res.status(400).send({message:'please provide text'})
    }

    const checkIfFactExist = await Facts.findOne({
      where: {
        id
      }
    })

    if(!checkIfFactExist){
      return res.status(404).send({message:'this id does not exist'})
    }

    try {
      if(text){
        checkIfFactExist.data.text = text
      }

      checkIfFactExist.save()
      return res.status(200).send({message:'updated'})
    } catch (error) {
      return res.status(500).send(error.message)
    }

Data is the column and text is the field am trying to change but it's not working.


text:
Q: What's the atonym for related information? I can't remember this word, it's been on the tip of my tongue for days. I am sure that this word exists but there's no synonym results I could find on Google. It means something like the inverse of correlation/evidence, "freak occurrence" possibly.
It's a word used to say something to the effect of, "you're referring to something as though it's connected". But that word describes the claim in a single word: "X information". A great example is something like;- person A sees person B in a car with a dog and then goes on to conclude that many people might drive with dogs in the car. The observation is "unrelated" to the reality or something similar, yet person A took it to have a connection and for there to be some underlying explanation. This event itself (not the observation) is an X. Talking about the event is using X information and is not very scientific.
edit: I found it. (anecdotal/anecdote, "anecdotal information")
http://www.macmillandictionary.com/thesaurus-category/british/Not-definite-or-based-on-fact
anecdotal adjective
based on someone's personal experience or information rather than on facts that can be checked

A: The first word that comes to mind for me is "irrelevant." You might also be thinking of "superfluous" which conveys a bit more of the idea that the information is unnecessary noise. If you count "non-germane" as a single word it probably fits your description pretty well also. A thesaurus hit might give you other words like "extraneous" or "peripheral" that may also get at your desired meaning.

A: Mistaken / false inference is one possibility; or perhaps coincidence, unrelated event / phenomenon, presumption, generalization, extrapolation or jumping / leaping to conclusions.

A: The example provided in the question is insufficient. One can draw such an incorrect inference for various reasons:

*

*generalization

*conjecture

*drawing false inference from true premises (invalidity)

*misinfer something in general.

A: Your disparate example sounds  like a syllogism:

"conclusion," "inference") is a kind of logical argument that applies
  deductive reasoning to arrive at a conclusion based on two or more
  propositions that are asserted or assumed to be true.
In its earliest form, defined by Aristotle, from the combination of a
  general statement (the major premise) and a specific statement (the
  minor premise), a conclusion is deduced. For example, knowing that all
  men are mortal (major premise) and that Socrates is a man (minor
  premise), we may validly conclude that Socrates is mortal. Syllogistic
  arguments are usually represented in a three-line form (without
  sentence-terminating periods):
All men are mortal.
Socrates is a man.
Therefore, Socrates is mortal
The word "therefore" is usually either omitted or replaced by the
  symbol "∴"

https://en.wikipedia.org/wiki/Syllogism

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I check whether parameter of function is nil or not? I made Sender class and sender object:
Sender *sender = [[Sender alloc] init];

Then, I wrote test:
// should success
[sender upload:[UIImage imageNamed:@"test2.jpg"] withName:@"test2.jpg"];
// should fail
[sender upload:nil withName:@"test2.jpg"];

Then, I wrote nil check code:
- (void)upload:(UIImage *)image withName:(NSString *)name
{
    if ([image isEqual:nil]) {
        ...
    }
    ...
}

But nil check is ignored.
How can I check whether the image parameter is nil or not?
Thank you for your kindness.

A: Try
if(!image)

or
if(image == nil)

A: Short answer, replace [image isEqual:nil] with image == nil.
Long answer, when you write:
[image isEqual:nil]

you are asking for the message isEqual: to be sent to the object whose reference is stored in the variable image.
However you don't wish to send a message to an object, you wish to determine whether the variable image contains a reference to an object or not. To do this you need to compare the value of your reference with the "no reference" value - which is written nil. The value comparison operator in Objective-C (and C et al) is == so you need to test:
image == nil

Now you might ask why did the code you have execute without error, just not producing the result you expected, given that there is no object to send a message to? Objective-C supports sending messages to "no object", aka nil, and returns the "zero" value for the result type, i.e. 0, nil etc. When converted to a boolean value, as in your if statement, a "zero" value produces NO.
HTH

A: @yeesterbunny's answer is on point as to what you should do in this situation, but it's also good to know why.
Remember that every objc method call is a message. When you call
[objA isEqual:objB]

you're sending a message to objA asking whether it considers itself "equal" to objB.
If the "image" parameter to your method is nil, there's nothing there to send a message to. By definition, any message to nil returns nil. (And "nil" is the same as zero in an if statement.)
Moral of the story: test pointer equality with == (or !=, or implicitly as in "if (!image)") if you're looking for nil. Use isEqual: only when you want to test whether two objects (known to exist and of similar type) are semantically equal (e.g. when you want to know if two instances of NSString contain the same text).


text:
Q: RoR ruby -- undefined method `model_name' for NilClass:Class I'm having a trouble with the update on a class.
This is the view:

        <%= form_for @list do |form| %>
        <%= render 'shared/error_messages', object: form.object %>

         <%= form.text_field :name, placeholder:

and this is the controller:
     def update
         if @list.update_attributes(params[:list])
            flash[:success] = "List updated"
         else
            render 'edit'
         end
         redirect_to @list
    end

The routes are:
       resources :lists, only: [:create, :show, :destroy,:edit]

Now the problem is it keeps raising
      "undefined method `model_name' for NilClass:Class"
           in line 2  --->   <%= form_for @list do |form| %>

And I can't seem to figure out why.
Thanks in advance
Leo

A: You have to load the @list before you update its attributes.
def update
  @list = List.find_by_id(params[:id])
  if @list.update_attributes(params[:list])
    flash[:success] = "List updated"
  else
    render 'edit'
  end
  redirect_to @list
end

And by the way, the problem you see is not caused by your update action but by your edit action that redirects to this view.
You have to load the @list in both actions. In edit action in order to render the view, in update action in order to update the appropriate object.


text:
Q: Xamarin IOS how to create a Stroy Board from exisitng files? I found this navigation bar that i want to use but a Cant seem to find the story board for it? or am i looking in the wrong place, How would i generate a story board for it?
here is the link to the bar: https://components.xamarin.com/view/flyoutnavigation

A: You don't generate a storyboard for it. You put a generic view into your storyboard and set it's class to be a custom subclass of FlyoutNavigationController, and set it as the root view. You can then grab all of the ViewControllers that are controlled by the FlyoutNavigationController by using something similar to the following Objective-C code:
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myViewController"];

or, in C#
UIStoryboard sb = UIStoryboard.FromName("MainStoryboard", null);
UIViewController vc = sb.InstantiateViewController("myViewController");

Here's the link for storyboarding
http://developer.xamarin.com/guides/ios/user_interface/introduction_to_storyboards/


text:
Q: javascript getting a websocket error on onopen event I am getting an error about:
Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
Is there an event I can check to make sure the socket is fully connected before I can send a message.
My code is as follows:
        this.contextWS = new WebSocket(socketAddress);

        this.contextWS.onopen = () => {
            console.log('Websocket is open !!!');
            this.contextWS.send('payload');
        }

Am I making an obvious mistake here?

A: After the MDN - WebSocket description:

An event listener to be called when the WebSocket connection's
  readyState changes to OPEN; this indicates that the connection is
  ready to send and receive data. The event is a simple one with the
  name "open".

I'd use onerror event handler to check if there are no errors on the way..
contextWS.onerror = function (event) {
   console.log(event.data);
};

... and onclose event handler to check the reason of unexpectedly closed connections:
contextWS.onclose = function(event) {
      if (event.code == 1000) {
        console.log('WebSocket closed normally');
      } else {
          console.log('WebSocket closed unexpectedly: ' + event.code);
      }

Here's the list of all possible result codes - MDN CloseEvent
You can try to queue your messages and send them when the readyState == 1. Please see the answer from the similar question - proxy function


text:
Q: Embedded Http server jump seconds on videos where located local I need to play video files which are located under client pc.
For this I need to use embedded http server which will be setup on client.
embedded http server is taken from here
If there is more advanced one I would like to learn.
I'm using jwplayer to play mp4 files.
I couldn't make it play and jump on mp4 files.
I have spent lots of time on it,
need help

A: You can use the Html5 Video tag to play mp4 videos in any current web browser. And that's easy too. Try this
http://www.w3schools.com/html/html5_video.asp

A: This works in all current browsers - IE11, FF 36, Chrome 41:
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Video Tag</title>
</head>
<body>
<video width='640' height='360' controls poster='file:///C:/Users/JT/Videos/Samples/wildlife.jpg'>
<source src='file:///C:/Users/JT/Videos/Samples/wildlife.mp4'>
</video>
</body>
</html>


text:
Q: Importing defined functions from one .py file to another .py file in Django I am trying to create a website and I have my html working 100% on a local host using django.
At the moment my code is not associated with the html so if I put in a username and password, the page does nothing, which makes sense.
I am at the point where I am trying to import a defined function from my .py file with all my code(b.py) and I have another file (a.py) which essentially should take the information from the defined functions of b.py, use the information, then display it on the localhost webpage.
But my issue is that it is saying ImportError: cannot import name 'definedfunctionname'. Both a.py and b.py are in the same directory as each other.

A: Try this in your a.py file:
from b import definedfunction

# Call
definedfunction()

Alternatively:
import b

# Call it as below
b.definedfunction()


text:
Q: Label rotation in PlotCirc (DescTools package) I am using the PlotCirc() function of the DescTools R package to visualize a contingency table:
library(DescTools)

tab <- matrix(c(2,5,8,3,10,12,5,7,15), nrow=3, byrow=FALSE)
dimnames(tab) <- list(c("ABCDEFG","BCDEFGH","CDEFGHI"), c("D","E","F"))

PlotCirc( tab,
          acol = c("dodgerblue","seagreen2","limegreen","olivedrab2","goldenrod2","tomato2"),
          rcol = SetAlpha(c("red","orange","olivedrab1"), 0.5)
)

Question:
How can I rotate all the labels (left and right side) so that they spread from the circle (text base line pointing to the middle of the circle) ? I.e. the first label "ABCDEFG" should be rotated by almost -90 degrees pointing upwards, whereas the "CDEFGHI" should be rotated by roughly 45 degrees pointing a bit down and so on.

A: I could not figure out how to do it within that package. However, it is still possible:
tab <- matrix(c(2,5,8,3,10,12,5,7,15), nrow=3, byrow=FALSE)
dimnames(tab) <- list(c("A","B","C"), c("D","E","F"))

PlotCirc( tab,labels = NA, cex.lab = 1.0,acol = c("dodgerblue","seagreen2","limegreen","olivedrab2","goldenrod2","tomato2"),rcol =   SetAlpha(c("red","orange","olivedrab1")))

text(3,15,"ABCDEFG",srt=80)
text(11,10,"BCDEFG",srt=40)
text(13,-5,"CDEFG",srt=-30)
text(-5,-12,"DEFG",srt=60)
text(-12,-5,"EFG",srt=30)
text(-9,11,"FG",srt=-45)

http://i.stack.imgur.com/sK6Kr.png

A: DescTools v0.99.8 now offers a function argument las, which does exactly the job (thanks to the author Andri Signorell).


text:
Q: How exactly does mapping a home folder via AD work? In a 2012 R2 environment, how does mapping a home folder via Active Directory using the "Connect:" box on the profile tab work? I'm not referencing or concerned about GPO, this is only for AD mapping. Specifically, how does the drive map on the users computer? What is the process that occurs when that drive is mapped? Is there any way to manually force it to sync and map the drive like you can with gpupdate? I've been Googling for a while now and can't find anything on it, so any knowledge you can share would be greatly appreciated.

A: The UNC path provided is mapped to the drive letter given, very similar to a NET USE x: \\server\share\path\to\subdir command.
It has the same failure modes as NET USE: If there is a local device using the drive letter, it will not be mapped.  If the server, share, or folder cannot be accessed, it will not be mapped.
On DOS and classic Windows (3.x, 9x, ME) clients, it would always map to the root of the share, not any specified subdirectory.
This feature is not handled by the Group Policy engine -- it dates back to the earliest days of Windows NT.  It is processed by the same codepaths that handle legacy logon scripts.  As far as I know, there is no way to "refresh" it, short of logging back off and on again.
What problem are you trying to solve?


text:
Q: Wordle code doesn't work properly? Python 3.10.7 I'm currently writing a small Wordle game, which analyzes a guess word against a randomly selected word from a dictionary; however, there's an issue with it.
Here's my code:
SQUARES = {
    'correct_place': '',
    'correct_letter': '',
    'incorrect_letter': '⬜'
}

def check_guess(guess: str, word: str):
    guessed = []
    wordle_pattern = []
    for i, letter in enumerate(guess):
        if word[i] == guess[i]:
            guessed.append(letter)
            wordle_pattern.append(SQUARES['correct_place'])
        elif (word.count(guess[i]) == 1 and guess[i] not in guessed and guess.count(guess[i]) == 1) or (word.count(guess[i]) > 1 and guessed.count(guess[i]) < word.count(guess[i])):
            guessed.append(letter)
            wordle_pattern.append(SQUARES['correct_letter'])
        else:
            guessed.append(letter)
            wordle_pattern.append(SQUARES['incorrect_letter'])
    return ''.join(wordle_pattern)

This code mostly works, but it has a problem, in which it breaks down whenever the guess word has a repeated letter; for example:
print(check_guess(guess='burbs', word='urban'))

Prints ⬜⬜⬜ instead of the intended ⬜⬜.
I've tried adding many conditions to fix it; however, none of them seem to work.

A: This is the best I came up with (2.0):
SQUARES = {
    'correct_place': '',
    'correct_letter': '',
    'incorrect_letter': '⬜'
}

def check_guess(guess: str, word: str):
    wordle_pattern = []
    word_list = [*word]
    temp = ''
    for i, letter in enumerate(guess):
        if __is_correct_place(word[i], letter):
            wordle_pattern.append(SQUARES['correct_place'])
            word_list[i] = '/'
            temp += '_'
        else:
            wordle_pattern.append(SQUARES['incorrect_letter'])
            temp += letter
    for i, letter in enumerate(temp):
        if letter in word_list:
            wordle_pattern[i] = SQUARES['correct_letter']
            word_list.remove(letter)
    return ''.join(wordle_pattern)

def __is_correct_place(letter: str, guessed_letter: str):
    return letter == guessed_letter

A: I cannot reproduce your mentioned output, as running your code returns your desired EGEGG on my machine.
However, as @Sembei Norimaki mentioned, YGEGG should be the correct output, where E is incorrect letter, G is correct place and Y is incorrect place.
It seems like your conditions to check for incorrect place are unnecessary complicated, as you only need to check whether the current letter of the guessed word appears anywhere in the word.
Here is a refactored version that delivers the desired output YGEGG for
print(check_guess(guess='raver', word='pager'))

SQUARES = {
    'correct_place': '',
    'correct_letter': '',
    'incorrect_letter': '⬜'
}

def check_guess(guess: str, word: str):
        wordle_pattern = []
        for i, letter in enumerate(guess):
            if __is_correct_place(word[i], letter):
                wordle_pattern.append(SQUARES['correct_place'])
                continue
            if __is_correct_letter(word, letter):
                wordle_pattern.append(SQUARES['correct_letter'])
                continue
            wordle_pattern.append(SQUARES['incorrect_letter'])
        return ''.join(wordle_pattern)

def __is_correct_place(letter: str, guessed_letter: str):
    return letter == guessed_letter

def __is_correct_letter(word: str, guessed_letter: str):
    return word.count(guessed_letter) >= 1

Hope this helps.


text:
Q: How to update a modal DOM object after method call with JS on Rails 5.2? I am trying to achieve something that sounds simple, but that fails in this particular context.
A Task instance is displayed in a modal window. The modal Show view includes a form which, when submitted, triggers the verify method in the tasks_controller. The method updates a field, and the change should be reflected in the current Show view.
Unfortunately, Rails raises an UnknownFormat error, claiming for a html template.
I also tried to render the javaScript snippet directly inside the method with: render js: "document.getElementById('task-git-hash').value = ('#{ @task.git_hash }');"  but the code is rendered literally as new html page, instead of being executed in the current view.
show.html.erb modal view (extract)
  <%= form_with model: @task, url: :verify_task, method: :post, html: {id: "verify_form"}, remote: true do |f| %>

          <%= t('tasks.show.GitHash') %>

        <input id="task-git-hash" class="mat-input-element" readonly
          value="<%= @task.git_hash %>" />

          <%= f.label :verify_on_technology_id, t('tasks.show.Technology'), class: "mat-form-field-label" %>
          <%= f.grouped_collection_select :verify_on_technology_id,
              values_options_for('Technologies', 1, @task.technology_id), # group
              :subs,                                 # descendants
              :code,                                 # group label
              :id, :code,                            # option key & label
              {:include_blank => false},
              { class: "mat-input-element select2-candidate" } %>

          <%= f.label :git_hash, t('tasks.show.GetHash'), class: "mat-form-field-label" %>
          <button class="mat-flat-button mat-button-base mat-primary">
            <%= t('Verfiy') %>
          </button>

  <% end %>

tasks_controller method
  def verify
    ### Retrieved by Callback function
    @task.update_attribute(:git_hash, Time.now.strftime("Tested at %H:%M"))
  end

verify.js.erb view
document.getElementById("task-git-hash").value = ("<%= @task.git_hash %>");

How can I manage to update this field in the current view when the form is validated?


text:
Q: Keyword search using PHP MySql? I have title (varchar), description (text), keywords (varchar) fields in my mysql table.
I kept keywords field as I thought I would be searching in this field only. But I now require to search among all three fields. so for keywords "word1 word2 word3", my query becomes
SELECT * FROM myTable
WHERE (
name LIKE '%word1%' OR description LIKE '%word1%' OR keywords LIKE '%word1%'
OR name LIKE '%word2%' OR description LIKE '%word2%' OR keywords LIKE '%word2%'
OR name LIKE '%word3%' OR description LIKE '%word3%' OR keywords LIKE '%word3%')
AND status = 'live'

Looks a bit messy but this works. But now I need to implement synonym search. so for a given word assuming there are a few synonyms available this query becomes more messy as I loop through all of the words. As the requirements are getting clearer, I will need to join this myTable to some other tables as well.
So

*

*Do you think the above way is messy and will cause problems as the data grow?

*How can I avoid above mess? Is there any cleaner solution I can go by? Any example will help me.

*Is there any other method/technique you can recommend to me?

With thanks
EDIT
@Peter Stuifzand suggested me that I could create one search_index table and store all 3 fields (title,keyword,desc) info on that and do full text search. I understand that additionally this table will include reference to myTable primary key as well.
But my advanced search may include joining mytable with Category table, geographic_location table (for searching within 10, 20 miles etc), filtering by someother criteria and of course, sorting of search results. Do you think using mysql fulltext will not slow it down?

A: When your queries are getting out of hand, it's sometimes better to write parts of it in SQL and other parts in your programming language of choice.
And you could also use fulltext search for searching. You can create separate table with all fields that you want to search and add the FULLTEXT modifier.
CREATE TABLE `search_index` (
    `id` INT NOT NULL,
    `data` TEXT FULLTEXT,
);

SELECT `id` FROM `search_index` WHERE MATCH(`data`) AGAINST('word1 word2 word3');

A: One more way (sometimes it's better but it depends...)
SELECT
    id, name, description, keywords
FROM
    myTable
WHERE
    name REGEXP '.*(word1|word2|word3).*' OR
    description REGEXP '.*(word1|word2|word3).*' OR
    keywords REGEXP '.*(word1|word2|word3).*'
;

PS: But MATCH(cols) AGAINST('expr') possibly is better for your case.

A: If at all possible, you should look into fulltext search.

A: Given the expanded requirements, you might want consider using apache solr (see http://lucene.apache.org/solr/) it is a faceted search engine, designed for full text searching.  It has a RESTful interface that can return XML or JSON.  I am using it with a few projects - works well.
The only area I see you hitting some problems is potentially with the proximity search, but with some additional logic for building the query it should work.


text:
Q: Is there a way to generate a signal on QSlider value increased I'm trying to trigger a distinct signal from a QSlider for when it increases or decreases. Unfortunately due to restrictions in the program i'm creating outside of my control I cannot track the value of the slider and just do a comparison.
Is there a way to do this?

A: If I understand you correctly, you can't use valueChanged(int) to decide if the value increased or decreased, since you can't track the value. However, you need to do this, since QSlider doesn't have distinct signals for an increased / decreased value.
Use this helper class to keep track of the current value. It remaps the signal valueChanged(int) of the provided target object to the new signals valueIncreased(int) and valueDecreased(int) telling the (absolute) difference.
class ValueChangeTracker : public QObject
{
    Q_OBJECT
    int v;
public:
    ValueChangeTracker(QObject *target) :
        QObject(target)
    {
        connect(target, SIGNAL(valueChanged(int)), SLOT(changed(int)));
        v = target->property("value"); // or ->value() if you specifically use QSlider* instead of QObject* as the target type
    }
signals:
    void valueIncreased(int);
    void valueDecreased(int);
private slots:
    void changed(int newValue) {
        int diff = newValue - v;
        v = newValue;
        if(diff > 0) emit valueIncreased(diff);
        if(diff < 0) emit valueDecreased(-diff);
    }
};

To use it, simply create a new instance of this class and connect to its signals. In the QObject tree, it becomes a child of the target object, so you don't have to keep the pointer to an instance.
QSlider *mySlider = ...
ValueChangeTracker *tracker = new ValueChangeTracker(mySlider);
connect(tracker, SIGNAL(valueIncreased(int)), ...);
connect(tracker, SIGNAL(valueDecreased(int)), ...);

A: QSlider emits the signal valueChanged, just connect it to a slot:
mySlider.valueChanged.connect(self.on_mySlider_valueChanged)

and to your tests there and emit a custom signal if you like.

A: I don't fully understand the question, maybe an example would help. But if you look at the documentation for QSlider, it emits signal valueChanged(int) when the value of the slider changes.


text:
Q: I Am Facing an Issue with Google IMAPs I am working on a project which is capable of sending emails, however, the main function which is to send emails is facing a few issues, I did a few cross references between my coding and my colleagues and found that they match, however I am still incapable of sending said emails.
I tried looking online and applied their solution, but it is yet to be solved. Is it my coding that is problematic or the SMTP Server which I set up?
Imports System.Net.MailImports System.IOImports System.DataImports System.Data.OdbcImports System.Web.UI.PagePartial Class _DefaultInherits System.Web.UI.Page

Private Sub Button_Redirect_Click(sender As Object, e As EventArgs) Handles Button_Redirect.Click
    Response.Redirect("excel_upload.aspx")
End Sub

Private Sub submit_Click(sender As Object, e As EventArgs) Handles submit.Click
    Response.Write(tmail.Text)
    Response.Write("
")
    Response.Write(fmail.Text)
    Response.Write("
")
    Response.Write(customerRequest.Text)
    Response.Write(kin.Text)
    Response.Write("
")
    Response.Write(kul.Text)
    Response.Write("
")
    Response.Write(icpsp.Text)
    Response.Write("
")
    Response.Write(fname.Text)
    Response.Write("
")
End Sub

Function SendEmail() As Boolean
    Dim SmtpServer As New SmtpClient()
    Dim mail As New MailMessage()
    Dim msg As String = ""

    Try
        SmtpServer.Credentials = New Net.NetworkCredential("ausm6228@gmail.com", "nxbciglfckwinxiz")
        SmtpServer.Host = "smtp.gmail.com"
        SmtpServer.Port = 143
        SmtpServer.EnableSsl = True

        mail = New MailMessage()
        mail.From = New MailAddress(fmail.Text)
        mail.To.Add(tmail.Text)
        mail.Bcc.Add("")
        'mail.Subject = "Permohonan Pengaktifan ePayment@USM"
        mail.IsBodyHtml = True
        mail.Body = customerRequest.Text

        'If FileLoc <> "" Then
        '    If File.Exists(FileLoc) Then mail.Attachments.Add(New Attachment(FileLoc))
        'End If

        mail.Priority = MailPriority.High
        SmtpServer.Send(mail)

        msg = "Emel telah dihantar."
        Return True
    Catch ex As SmtpFailedRecipientsException
        For i As Integer = 0 To ex.InnerExceptions.Length - 1
            Dim status As SmtpStatusCode = ex.InnerExceptions(i).StatusCode

            If status = SmtpStatusCode.MailboxBusy OrElse status = SmtpStatusCode.MailboxUnavailable Then
                msg = "Delivery failed - retrying in 5 seconds."
                System.Threading.Thread.Sleep(5000)
                SmtpServer.Send(mail)
            Else
                msg = "Failed to deliver message to {0}" + ex.InnerExceptions(i).FailedRecipient
            End If
        Next
    Catch ex As Exception
        msg = "Exception caught in RetryIfBusy(): {0}" + ex.ToString()
    End Try

    Return False
End Function

Image of the website layout
Image of IMAP setup
I changed the SMTP Server Host and Port.
I set up a new Windows MAIL IMAP account.


text:
Q: Parser Error Debugging VS2008 When I create new VS2008 asp.net application it builds fine.  But when I start debugging I get below error in browser.  I've rebuilt the app.  The Inherits clause of the markup page matches the class in the code-behind C#.  Any clues?
Server Error in '/' Application.
--------------------------------------------------------------------------------

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'WebApplication3._Default'.

Source Error:

Line 1:  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication3._Default" %>
Line 2:
Line 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Source File: /Default.aspx    Line: 1

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4952; ASP.NET Version:2.0.50727.4927

A: Try removing the namespace from the Inherits attribute:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_Default" %>

A: This is usually because the code-behind class name / namespace has changed, but the .aspx page hasn't been updated (or visa versa).
You should open up the code behind of your page and make sure that the namespace and class name match whats in your .aspx page (and that the class is marked as public).
 namespace WebApplication3
 {
     public class _Default
     {
         // ...


text:
Q: How to Change Default Bootstrap Fluid Grid 12 Column Gutter Width I am looking to know if there is any simple solution known to change the gutter with on the fluid default 12 grid bootstrap system (2.3.0).
I am not familiar with LESS but if that is the answer, please also describe how to could be changed.  The same with Sass.
Please note that it is perfectly acceptable to change the gutter width, by half or one fourth, for example if that may make things simpler.
The following goals must be met:

*

*Must be able to update bootstrap in the future.  This means not editing the actual bootstrap files.

*Functionality should remain for all other objects.

*Must be simple.  Less than 10 lines of CSS.  For example, an added class or something.

I have searched throughout Stack Overflow and still have no idea how I may go about doing something like this.  To the best of my understanding, downloading a customized Bootstrap only renders custom gutter widths for non-fluid grids. I have coded my own fluid grid system before, so I understand the math, but I am worried there may be consequences and it would be helpful if any known issues on class overrides could be shared.
I promise to give credit where it is due.
UPDATE:
Changing the less variables as described in Yoda's answer is the way to go.  Does anyone have any experience changing these less variables?  For example, I believe the variables that have to be changed are the following:
// Fluid grid
// -------------------------
@fluidGridColumnWidth:    percentage(@gridColumnWidth/@gridRowWidth);
@fluidGridGutterWidth:    percentage(@gridGutterWidth/@gridRowWidth);

// 1200px min
@fluidGridColumnWidth1200:     percentage(@gridColumnWidth1200/@gridRowWidth1200);
@fluidGridGutterWidth1200:     percentage(@gridGutterWidth1200/@gridRowWidth1200);

// 768px-979px
@fluidGridColumnWidth768:      percentage(@gridColumnWidth768/@gridRowWidth768);
@fluidGridGutterWidth768:      percentage(@gridGutterWidth768/@gridRowWidth768);

How does one go about changing something like this? Perhaps:
@fluidGridGutterWidth768:      percentage(1.5);

If anyone has done this before, I would appreciate a shove in the right direction.

A: I think you might be over thinking it. The problem with changing the LESS variables is that it will change it for all gutters. So if I like the 15px gutter for arranging the over all layout but want the gutter to be 5px for a form inside that grid it won't work.
Just create 2 css classes to override the areas you want to change the gutter.
Apply this at the "row" level.
.row-5-gutter{
    margin-left: -5px;
    margin-right: -5px;
}

Apply this at the "column" level.
.col-5-gutter{
    padding-left: 5px;
    padding-right: 5px;
}

demo: http://jsfiddle.net/tg7Ey/

A: The easiest way is probably to use the Customizable download that Twitter Bootstrap provides. Change the @fluidGridGutterWidth variable to suit your needs in the form. Download the less files from here. You can access the variable.less file from the github bootstrap project and then change this piece of code:
    // Fluid grid
// -------------------------
@fluidGridColumnWidth:    percentage(@gridColumnWidth/@gridRowWidth);
@fluidGridGutterWidth:    percentage(@gridGutterWidth/@gridRowWidth); // <= this one

I thought you had access to less files at first, then I realized you are using the customized gui on the website. Just download the less files, and make your changes. Then compile the less files to give you a css file or use less for development. You can use css or min.css for deployment.

A: I was looking for a simple solution for this problem, too. My goal was to use simple CSS, not LESS. This answer as like any other i found, based on compiling LESS or using the online compiler of bootstrap. So i tried to find my own solution.
Reading the documentation you will find the following about the gutter-width: Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and last column via negative margin on .rows.
Based on this i tried the following:
.container {padding-left:1px;padding-right:1px;}
.row {margin-left:-1px;margin-right:-1px;}
.row > div {padding-left:1px;padding-right:1px;}

From now the gutter width was only 2 pixel. My next problem was, that my intended width was an odd number. My solution was to remove the paddings and margins on the left and put them completely on the right:
.container {padding-left:0;padding-right:5px;}
.row {margin-left:0;margin-right:-5px;}
.row > div {padding-left:0;padding-right:5px;}

Now i have a 5 pixel gutter width.
I did not tested this in all possible scenarios you can use bootstrap. Especially you have to  pay attention to use only column-div's inside a row-div inside a container-div. But in my case it was a very effective solution without touching the origin source code of bootstrap or using a LESS compiler.


text:
Q: what operation repeated $n$ times results in the addition operator? I had a difficult time in phrasing my question. But I was wondering if there is an operation that, when repeated n times, results in the addition operator. Same way as repeating addition n times results in the multiplication operator, and repeating multiplication n times results in the exponentiation operator etc.
So $n$ times addition of a number $x$ results in $x\times n$.
And $n$ times multiplication of a number $x$ results in $x^n$
Then my question is $n$ times ...what... results into the number $x+n$.
Let's call this operator: $@$.
For example, the following would then hold:
$$a\times a=a^2$$
$$a+a=a\times 2$$
$$a@a=a+2$$
My question is, does it make any sense thinking of such an operator, is there anything known about it, can it be followed through even further like $a\sim a = a@2$?

A: If we could use multiplication operator '$\times$' and division operator '$/$' to get this @ operator, then
$\underbrace{x@x@...@x}_n=n \times ((x/n) +1)=x+n$ for $n \neq 0,1$.
Discrepancies will occur at $n=0$ and $n=1$ as for $n=1$ we will get $x=x+1$
and at $n=0$, $ x/n$ will be undefined.

A: You want an operator $@$ such that for all $n\in\Bbb N$,
$$\underbrace{a\mathop @a\mathop @\ldots\mathop @ a}_n = a+n.$$
The first problem with this is the case $n=1$ (not to mention $n=0$), where you demand $a=a+1$ (in analogy to $a = a\cdot 1$ and $a=a^1$).
So we need drop the case $n=1$.
The next problem is that we did not specify whether $@$ should be associative. And if not: Do we mean $(a\mathop @ a)\mathop @ a = a+3$ or $a\mathop @ (a\mathop @ a) = a+3$? Let's attempt to actually achieve associativity.
Then we need
$$\begin{align}a\mathop @a&=a+2 \\
(a+n)\mathop @a &= a+n+1&\text{for }n\ge 2\\
a\mathop @(a+n) &= a+n+1&\text{for }n\ge 2\\
\end{align}$$
This in fact allows us to extract a complete definition for $@$:
$$a\mathop @ b=\begin{cases}
\max\{a,b\}+1&\text{if }a\ne b\\
a+2&\text{if }a=b\end{cases} $$
(where the cases with $b=a\pm 1$ are irrelevant).

A: There are already amazing answers!
But I'll try to give some additional info since this question was asked a lot of times in the past (and it will be asked again in the future right?) and I gave some answers too.

As Hagen von Eitzen and Brevan Ellefsen said $$a\circ b:= \max (a,b)+1+\delta_{ab}$$ is one of the solutions of the equation $a*(a+n)=a+n+1$ , where $a$ and $n$ range over some restricted domains.
This particular solution was called Zeration by Rubtsov and Romerio: you can easily find the details of the story in the Zeration thread that was linked by Brevan Ellefsen.
Another solution is $\max(a,b)+1$ which is commutative and is not discontinuous, but in the linked thread, a user, Tetration Forum's founder, also noticed that it is possible to find a non-commutative solution too.
You can find an updated discussion of the topic in this thread:
Zeration Update @Tetration Forum
Also here at MSE, similar questions were answered: for example, this one is almost identical
Does anything precede incrementation in the operator "hierarchy?"
and also remark 1 of this answer I wrote 2 years ago:
More info on Zeration - Go to remark 1

A: Yes there is.
The successor $s$ function do that where:
$$\forall n\in\mathbb Z,\quad s(n)=n+1$$
and $s(0)=0$.
You can have more information here.
Thanks to a comment, you also might be interested in this.
Though you can not define this operator as a binary relation as you would like it to be defined.

A: This is a well studied topic in certain circles, and is referred to as Zeration. It is considered the $0$-th level of the extended Hyperoperation family. Often we simply see Zeration simply defined to be the Successor Function as defined in the Peano Axioms.
However, other definitions of Zeration have been studied. A great start is to look on the Tetration Forums; in particular, I reccomend this post. Some snippets from that page include:

At the very simple common sense level, zeration is an attempt for finding an operation filling the gap in the following operations' sequence:
$a ^ a = a [3] a = a [4] 2 = {}^2a \implies$ exponentiation $\leftrightarrow$ tetration
  $a\times a = a [2] a = a [3] 2 = a ^ 2 \implies$  multiplication $\leftrightarrow$ exponentiation
  $a + a = a [1] a = a [2] 2 = a \times 2\implies$  addition $\leftrightarrow$ multiplication
which should be logically completed by a new operation that we may call zeration (indicating it by the infixed operation sign "$\circ$") and that should at least have the following "strange" property:
$a \circ a = a [0] a = a [1] 2 = a + 2\implies$ zeration $\leftrightarrow$ addition.

Note that the notation $a[n]b$ is common Hyperoperation notation, ${}^2a$ is Tetration. I have edited the quotes to add MathJax formatting. The symbol "$\circ$" is your @ symbol. Continuing in that link, we find the following:

The theoretical way for justifying such new operation is provided by the Ackermann Function. In fact, the definition of Ackermann Function (AF) can be summarised [sic] as follows:
$A(0, n) = n + 1$
  $A(s, 0) = A(s-1, 1)$
  $A(s, n) = A(s-1, A(s, n-1))$

Continuing further, we get to the crux of the post

With the provisional exception of row $s=0$, we could re-define Ackermann's Function as follows:
$A(s, n) = 2 [s] (n + 3) – 3$, or:
  $2 [s] n = A(s, n-3) + 3$
For $s=0$ we have:
  $A(0, n) = 2 [0] (n + 3) – 3 = n + 1$ (zeration)
  which gives: $2 \circ (n+3) = n + 4$
  therefore: $2 ° n = n + 1$, (for: $n \ge 3$)
  to which we may add: $2 \circ 2 = 2 + 2$
  and: $n \circ n = n + 2$
We can start using these expressions in order to find out the first properties of the "zeration" operation, which can be described as follows:
$a \circ b = a + 1$ , if $a > b $
  $a \circ b = b + 1$ , if $a < b  $
  $a \circ b = a + 2 = b + 2$ , if $a = b$

If you continue reading the page I linked you will find an extensive discussion of other interpretations and definitions of Zeration, including the different properties such a function could be expected to hold (in particular, having an inverse!). Note that much of the Tetration Forums are a contentious subject at best, but seems to be the best treasure trove of information on this topic you will find. Other proposed definitions include
$$ a\circ b =
\begin{cases}
b+1,  & b>a+1 \\
a+2, & b \le a+1
\end{cases}$$
As well as the classic
$$ a\circ b =
\begin{cases}
\max(a,b)+1,  & a \neq b \\
a+2=b+2, & a=b
\end{cases}$$
The second of which is covered in @Hagen's post


text:
Q: Button with image using React Typescript I am using React Typescript.

*

*How do I add image to my button?
I tried doing it and there are no errors, but I am getting a blank button.

*How do I style my button element using Emotion CSS here?

import React from "react";

function PostButton(props){
    let style = {
        width:24,
        height:24,
        src: "../images/abc.png"
    };
    return(
        <button style={style} onClick={() => props.handleClick()}>{props.label}</button>
    );
}

return (
    <div style={style}>
        <PostButton src={"../images/abc.png"} handleClick = {props.incrementScore}/>
    </div>
);
}

A: src would be  background:url(../images/abc.png)
Perhaps you're confusing the src prop that an img HTML element would have?
Perhaps you should include a nested img component inside your button.
Working example: https://stackblitz.com/edit/react-emotion-hello-u9qyaa

A: Damian's answer is technically correct however if you're using webpack you'll need to import the image like this:
import abc from "../images/abc.png";

And use it like this:
function PostButton(props){
    let style = {
        width:24,
        height:24,
        background: `url(${abc})`,
    };
    return(
        <button style={style} onClick={() => props.handleClick()}>{props.label}</button>
    );
}


text: Q: Why does it exist? I can show that $\lim_{a \rightarrow \infty} \int_{-\infty}^{a} (\cos(tu)-e^{-\frac{t^2}{2}})e^{-\frac{u^2}{2}}du$ converges to 0 but I am not sure why this implies the convergence of $$\lim_{b \rightarrow -\infty} \int_{-\infty}^{b} (\cos(tu)-e^{-\frac{t^2}{2}})e^{-\frac{u^2}{2}}du$$ and moreover it is also converges to zero.


text:
Q: Specifying values in stretched raster histograms of ArcMap? I am trying to use the stretched color option with a topography raster. I have a color bar that I painstakingly make in arc and I am basically trying to set values of the topography equal to certain colors using the histogram. The problem (I think) is the histogram doesn't have a break where I need it - it has a -40 then jumps to 19. I want a break at 0 so sea level will align with my shift from blue to green in my color bar.
Is there a way to set these values?
Or is there just a better way to do this altogether?
I would use classified color, however it doesn't seem to have a way of ramping the color between the bounds. Its just a single color for a range, and with only a maximum of 32 intervals it doesn't look very good.
Here is a picture of my best result using stretched. You can see the areas on the coast that are green.

A: You still want to used a stretched classification.  You can adjust the classification using the custom histogram settings:

You will have to play with the settings until you get the colors displaying the way you want.  Click the 'Histograms' button:

Here is an example - standard deviations vs my custom histogram:
Std Dev:

Custom histogram:


text:
Q: Why Cygwin blew up my HD? I needed to use Cygwin in a single desktop machine.
I got the latest installation.
I chose the install from internet and chose a directory from the local file system as repository.
I selected only a couple of things: Devel, Shell and Utils.
I choose install and as I saw it downloaded all the packages and then started installing.
My problem is that even for this minimum installation, my HD went low on space (machine has already a lot of stuff and the repository folder was more than 1GB!)
I am planning to install to a new machine (aborted installation due to space) so I will do the installation in another machine instead of this (1 machine will have cygwin).
My question is, is there a way to avoid this? Should I choose as repository some network drive for example? Then after the installation is done, can I erase the packages in the repository?

A: Yes, you should always make sure you have enough disk space to download something before you start. It's true that the Setup.exe GUI doesn't appear to summarize the space for you, but that just means you need to be more careful. Sysadmin can be tough job sometimes, like when you're given installers that don't use MSI format.
Is this a server? A production Windows server should have more than one volume, and you shouldn't be storing anything on C:\ that you don't have to. (PS - If this is a single desktop system, you should be asking this question over on SuperUser, not here. Read the FAQ if you're not sure why.)
If you're going to be installing Cygwin for multiple machines (servers or rolling out to multiple desktops), then it definitely makes sense to have a single network location to store this stuff rather than have the install files needlessly duplicated on all your servers.
You should not erase your local repository, especially if you're going to be using this for more than one machine.

A: Selecting the entire 'Devel', 'Shell', and 'Utils' categories does NOT result in a minimum installation. In particular, Devel contains chunky compilers/interpreters and runtime environments for numerous programming languages, and it also contains the development packages for many libraries, which in turn pull in the actual libraries.
If you want a slimline Cygwin install, go with the default install (which currently is about 20 MB to download and 80 MB installed), and only add packages you actually need. You can always run setup.exe again later to add more. Just in case this isn't obvious, you need to click on the '+' next to each category to see the packages within.
As an example, here are some of my essential add-ons:

*

*Shells: mintty

*Net: openssh, inetutils

*Utils: util-linux, diffutils, patch

*Editors: nano

*Devel: gcc4-g++, make, subversion

You can rely on dependency resolution to pull in any packages your selection depends on, e.g. gcc4-g++ also pulls in gcc core and binutils.


text:
Q: Is there any reason for using if(1 || !Foo())? I read some legacy code:
if ( 1 || !Foo() )

Is there any seen reason why not to write:
if ( !Foo() )

A: if (1 || !Foo() ) will be always satisfied. !Foo() will not even be reached because of short-circuits evaluation.
This happens when you want to make sure that the code below the if will be executed, but you don't want to remove the real condition in it, probably for debug purposes.
Additional information that might help you:

*

*if(a && b) - if a is false, b won't be checked.

*if(a && b) - if a is true, b will be checked, because if it's false, the expression will be false.

*if(a || b) - if a is true, b won't be checked, because this is true anyway.

*if(a || b) - if a is false, b will be checked, because if b is true then it'll be true.

It's highly recommended to have a macro for this purpose, say DEBUG_ON 1, that will make it easier to understand what the programmer means, and not to have magic numbers in the code (Thanks @grigeshchauhan).

A: The two are not the same. The first will never evaluate Foo() because the 1 short-circuits the ||.
Why it's done - probably someone wanted to force entry in the then branch for debugging purposes and left it there. It could also be that this was written before source control, so they didn't want the code to be lost, rather just bypassed for now.

A: 1 || condition

is always true, regardless whether the condition is true or not. In this case, the condition is never even being evaluated. The following code:
int c = 5;
if (1 || c++){}
printf("%d", c);

outputs 5 since c is never incremented, however if you changed 1 to 0, the c++ would be actually called, making the output 6.

A usual practical usage of this is in the situation when you want to test some piece of code that is being invoked when the condition that evaluates to true only seldom is met:
if (1 || condition ) {
    // code I want to test
}

This way condition will never be evaluated and therefore // code I want to test always invoked. However it is definitely not the same as:
if (condition) { ...

which is a statement where condition will actually be evaluated (and in your case Foo will be called)

A: The question was answered properly - the difference is the right side of the or operation is short-circuited, suggesting this is debug code to force entry into the if block.
But in the interest of best practices, at least my rough stab at a best practice, I'd suggest alternatives, in order of increasing preference (best is last):
note:  noticed after I coded examples this was a C++ question, examples are C#.  Hopefully you can translate.  If anyone needs me to, just post a comment.
In-line comment:
if (1 /*condition*/) //temporary debug

Out-of-line comment:
//if(condition)
if(true) //temporary debug

Name-Indicative Function
//in some general-use container
bool ForceConditionForDebug(bool forcedResult, string IgnoredResult)
{
      #if DEBUG
          Debug.WriteLine(
              string.Format(
                  "Conditional {0} forced to {1} for debug purposes",
                  IgnoredResult,
                  forcedResult));
          return forcedResult;
      #else
          #if ALLOW_DEBUG_CODE_IN_RELEASE
              return forcedResult;
          #else
              throw new ApplicationException("Debug code detected in release mode");
          #endif
      #endif
}

//Where used
if(ForceConditionForDebug(true, "condition"))...

//Our case
if(ForceConditionForDebug(true, "!Foo()"))...

And if you wanted a really robust solution, you could add a repository rule to source control to reject any checked in code that called ForceConditionForDebug.  This code should never have been written that way because it obviously doesn't communicate intent.  It never should have been checked in (or have been allowed to be checked in) (source control?  peer review?)  And it should definitely never be allowed to execute in production in its current form.


text:
Q: How to find all comments with Beautiful Soup This question was asked four years ago, but the answer is now out of date for BS4.
I want to delete all comments in my html file using beautiful soup. Since BS4 makes each comment as a special type of navigable string, I thought this code would work:
for comments in soup.find_all('comment'):
     comments.decompose()

So that didn't work.... How do I find all comments using BS4?

A: You can pass a function to find_all() to help it check whether the string is a Comment.
For example I have below html:

The Science & Safety Behind Your Favorite Products

Just a brand

      Google

Code:
from bs4 import BeautifulSoup as BS
from bs4 import Comment
....
soup = BS(html, 'html.parser')
comments = soup.find_all(string=lambda text: isinstance(text, Comment))
for c in comments:
    print(c)
    print("===========")
    c.extract()

the output would be:
Branding and main navigation
============
test comment here
============

BTW, I think the reason why find_all('Comment') doesn't work is (from BeautifulSoup document):

Pass in a value for name and you'll tell Beautiful Soup to only consider tags with certain names. Text strings will be ignored, as will tags whose names that don't match.

A: Two things I needed to do:
First, when importing Beautiful Soup
from bs4 import BeautifulSoup, Comment

Second, here's the code to extract comments
for comments in soup.findAll(text=lambda text:isinstance(text, Comment)):
    comments.extract()


text:
Q: pandas merge by coordinates I am trying to merge two pandas tables where I find all rows in df2 which have coordinates close to each row in df1. Example follows.
df1:
   x  y val
0  0  1   A
1  1  3   B
2  2  9   C

df2:
    x    y  val
0  1.2  2.8   a
1  0.9  3.1   b
2  2.0  9.5   c

desired result:
   x  y val_x val_y
0  0  1     A   NaN
1  1  3     B     a
2  1  3     B     b
3  2  0     C     c

Each row in df1 can have 0, 1, or many corresponding entries in df2, and finding the match should be done with a cartesian distance:
(x1 - x2)^2 + (y1 - y2)^2 < 1

The input dataframes have different sizes, even though they don't in this example. I can get close by iterating over the rows in df1  and finding the close values in df2, but am not sure what to do from there:
for i, row in df1.iterrows():
    df2_subset = df2.loc[(df2.x - row.x)**2 + (df2.y - row.y)**2 < 1.0]
    # ?? What now?

Any help would be very much appreciated. I made this example with an ipython notebook, so which you can view/access here: http://nbviewer.ipython.org/gist/anonymous/49a3d821420c04169f02

A: I found an answer, though I am not real happy with having to loop over the rows in df1. In this case there are only a few hundred so I can deal with it, but it won't scale as well as something else. Solution:
df2_list = []
df1['merge_row'] = df1.index.values  # Make a row to merge on with the index values
for i, row in df1.iterrows():
    df2_subset = df2.loc[(df2.x - row.x)**2 + (df2.y - row.y)**2 < 1.0]
    df2_subset['merge_row'] = i # Add a merge row
    df2_list.append(df2_subset)
df2_found = pd.concat(df2_list)

result = pd.merge(df1, df2_found, on='merge_row', how='left')


text:
Q: Pandas validate date format Is there any nice way to validate that all items in a dataframe's column have a valid date format?
My date format is 11-Aug-2010.
I saw this generic answer, where:
try:
    datetime.datetime.strptime(date_text, '%Y-%m-%d')
except ValueError:
    raise ValueError("Incorrect data format, should be YYYY-MM-DD")

source: https://stackoverflow.com/a/16870699/1374488
But I assume that's not good (efficient) in my case.
I assume I have to modify the strings to be pandas dates first as mentioned here:
Convert string date time to pandas datetime
I am new to the Python world, any ideas appreciated.

A: If you know your format, you can use boolean slicing
mask = pd.to_datetime(df.columns, format='%d-%b-%Y', errors='coerce').notna()
df.loc[:, mask]

Consider the dataframe df
df = pd.DataFrame(1, range(1), ['11-Aug-2010', 'August2010, I think', 1])
df

   11-Aug-2010  August2010, I think  1
0            1                    1  1

I can filter with
mask = pd.to_datetime(df.columns, format='%d-%b-%Y', errors='coerce').notna()
df.loc[:, mask]

   11-Aug-2010
0            1

A: (format borrowed from piRSquared's answer)
if pd.to_datetime(df['date'], format='%d-%b-%Y', errors='coerce').notnull().all():
    # do something

This is the LYBL—"Look Before You Leap" approach. This will return True assuming all your date strings are valid - meaning they are all converted into actual pd.Timestamp objects. Invalid date strings are coerced to NaT, which is the datetime equivalent of NaN.
Alternatively,
try:
    pd.to_datetime(df['date'], format='%d-%b-%Y', errors='raise')
    # do something
except ValueError:
    pass

This is the EAFP—"Easier to Ask Forgiveness than Permission" approach, a ValueError is raised when invalid date strings are encountered.


text:
Q: Как задать относительный путь в Asp.Net Core к папке .git Подскажите, пожалуйста, как прописать относительный путь в web приложении (Asp.net core) к папке, в которой находится .git? Например если создать консольное приложение, то относительный путь получается прописать так:
(@"../../../../../")

Это получается путь идет относительно .exe, который находится например в C:\Project\App\App.UI\bin\Debug\netcoreapp3.1, где .git находится в папке Project, а если так же пройтись из веб-приложения, то ошибка пути. Относительно чего же надо идти? И как правильно прописать относительный путь к папке .git (веб-приложение находится в C:\Project\App\App.Web)
P.S. Работаю с библиотекой LibGit2Sharp, там нужно путь к репозиторию прописать, .git уже лежит там. Писать абсолютный путь не вариант, потому что нужно, чтоб у остальных разработчиков находило по этому пути.

A: Оказывается плясать надо от папки с веб-приложением, получается в моем случае относительный путь будет таковым: (@"../../").


text:
Q: Detetar data do utilizado com PHP Como é que detecto através de php a data do utilizador?
Ou seja, eu sei como detetar a data, mas fazer a comparação com a data do servidor, logo não fica certo devido aos diferentes fusos horários.
Deixo em baixo o meu codigo:
<?PHP
    $current = date("d/m");
    $date    = "14/02";
    if ($current == $date){
        echo "qualquer coisa";
    }
?>

A: DateTime::getTimezone() - Retorna o fuso horário corresponde a um DateTime informado
DateTimeZone::__construct() - Cria um novo objeto DateTimeZone
Para mais informações consulte os links a baixo
http://php.net/manual/pt_BR/datetime.settimezone.php
https://www.w3schools.com/php/func_date_default_timezone_set.asp


text:
Q: toggle() not working for content loaded with ajax? $('.slideArrow').toggle(function (event) {
  //some code
}, function (event) {
    //some code
});

This works fine for content which are loaded on page-load.But the same function does not work for content loaded with ajax.It just does not intercept the click.
What should I do?
In an other scenario,i faced a same problem(not for toggle,for click) and sorted it this way.I dont know what to do for toggle?
$('.common-parent').on('click','.target-of-click',function(){
//some code
})

A: The flag method :
var flag = false;

$(document).on('click', '.slideArrow', function(event) {
    if (flag) {
        // do one thing
    }else{
        // do another thing
    }
    flag = !flag;
});

the data method
$(document).on('click', '.slideArrow', function(event) {
    if ( $(this).data('flag') ) {
        // do one thing
    }else{
        // do another thing
    }

    $(this).data('flag', !$(this).data('flag'));
});


text:
Q: Function that returns a string representing a worksheet row I'm trying to create a function (named CreateRowRange) that will take a string having the form "$A$5" and produce a string having the form "A5:M5". Similarly, if I call the function with "$A$14", it will return "A14:M14". I have an Excel spreadsheet with data in columns "A" through "M". I found a similar post on Stack Overflow (Concatenating Variables Into String to be Set to a Range in VBA), but it seems overly complicated. The code written thus far for the function is:
Function CreateRowRange(CellAddress) As String
    CreateRowRange = Range(CellAddress).Row
End Function

A: This should return what you want:
Function CreateRowRange(CellAddress) As String
    CreateRowRange = Range(Range(CellAddress),Range("M" & Range(CellAddress).Row)).Address(False,False)
End Function

A: Ok, try this:
Function CreateRowRange(CellAddress as String) as String
    CreateRowRange = Replace(CellAddress, "$", "")
    CreateRowRange = CreateRowRange & ":" & Replace(CreateRowRange, "A", "M")
End Function

A: Excel already has built in properties and methods to modify ranges. If you're going to use it like
Range(CreateRowRange("$A$14")).Value = "X"

then you can achieve the same thing with
Range("$A$14").Resize(1,13).Value = "X"

If you're building a formula like
ActiveCell.Formula = "=SUM(" & CreateRowRange("$A$14") & ")"

then you can achieve the same thing with
ActiveCell.Formula = "=SUM(" & Range("A14").Resize(1,13).Address(0,0) & ")"

The 0,0 part makes the address relateive - no dollar signs


text:
Q: How to prove $a_1^Ta_1+a_2^Ta_2\le b_1^Tb_1+b_2^Tb_2.$ Let $p,q > 0$, $a_1, b_1\in \mathbb{R}^m, a_2,b_2\in\mathbb{R}^n$ be vectors. Given that
$$\frac{2}{p}\|a_1\|_2^2+\frac{2}{q}\|a_2\|_2^2-\frac{2}{p}a_1^Tb_1-\frac{2}{q}a_2^Tb_2\\+\|b_1-a_1\|_2\frac{2}{\sqrt{pq}}\|a_2\|_2+\|a_1\|_2\frac{2}{\sqrt{pq}}\|b_2-a_2\|_2\le 0.$$
How to show that $a_1^Ta_1+a_2^Ta_2\le b_1^Tb_1+b_2^Tb_2.$
I first try to assume that $p=q$, and then I can cancle $\frac{2}{q},\frac{2}{p}$ and $\frac{2}{\sqrt{pq}}$.
$$\|a_1\|_2^2+\|a_2\|_2^2-a_1^Tb_1-a_2^Tb_2\\+\|b_1-a_1\|_2\|a_2\|_2+\|a_1\|_2\|b_2-a_2\|_2\le 0.$$ I think there is no counter example for the above equation.
Then suppose $a_1^Ta_1+a_2^Ta_2\le b_1^Tb_1+b_2^Tb_2$ holds.  The following should hold,
$$-a_1^Tb_1-a_2^Tb_2+\|b_1-a_1\|_2\|a_2\|_2+\|a_1\|_2\|b_2-a_2\|_2\le  b_1^Tb_1+b_2^Tb_2.$$
Any hint? Thanks in advance.

A: You cannot prove that because the assertion is not true. Consider the scalar case $m=n=1$ with
$$
p=1,\,\ q=64,\,\ a_1=1,\,\ a_2=4,\,\ b_1=b_2=2.
$$
Then
\begin{align*}
&\frac{2\|a_1\|^2}{p}+\frac{2\|a_2\|^2}{q}-\frac{2a_1^Tb_1}{p}-\frac{2a_2^Tb_2}{q}+\frac{2\|a_2\|\|b_1-a_1\|}{\sqrt{pq}}+\frac{2\|a_1\|\|b_2-a_2\|}{\sqrt{pq}}\\
=&\frac{2}{1}+\frac{32}{64}-\frac{4}{1}-\frac{16}{64}+\frac{8}{8}+\frac{4}{8}\\
=&2+\frac{1}{2}-4-\frac{1}{4}+1+\frac{1}{2}=\frac{-1}4<0,
\end{align*}
but $a_1^Ta_1+a_2^Ta_2 = 17 > 8 = b_1^Tb_1+b_2^Tb_2$.


text:
Q: Vue.js inline template error I'm trying to use inline-template with vue.js 2.0.
I use it with Laravel blade 5.4:
<users inline-template>

        @foreach($users as $user)

                    {{ $user->name }}

                    {{ $user->last_name }}

                    {{ $user->created_at->diffForHumans() }}

                @if($user->isActive())

                        Ja

                @else

                        Nee

                @endif

                    Admin

        @endforeach

</users>

Vue component:

App.js:
Vue.component('users',                          require('./components/user/Users.vue'));

But I get the error as follows:

Uncaught TypeError: Cannot read property 'type' of undefined
      at genInlineTemplate

What could be wrong here? Any suggestions?

A: The inline template doesn't seem to latch onto
 tags very well.
I couldn't find any explaination in the docs but solved the issue by wrapping in a
 tag.
<component inline-template>

             Something
             something
             something

</component>


text:
Q: google sheets checkbox increment counter I am making a checkbox inventory counter that auto increments
I have tried many if then statements to increase a cell value when a box or multiple boxes is check. The best I could do was display a number but it disappears once the checkboxes are unchecked. So I would like and cell to auto increase by 1 after the last or all boxes are checked


text:
Q: Powershell and path environment variable I would like powershell to use the environment variable "PATH" to resolve executables. I'm sure it should be able to do this, but here is what I get.
PS C:\> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

PS C:\> ${ENV:PATH} = "C:\WINDOWS\System32\"
PS C:\> ls ${ENV:PATH}\cmd.exe

Directory: C:\WINDOWS\System32

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        22/08/2013   8:03 PM     355840 cmd.exe

PS C:\> & cmd.exe
& : The term 'cmd.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:3
+ & cmd.exe
+   ~~~~~~~
+ CategoryInfo          : ObjectNotFound: (cmd.exe:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

A: Run Get-Command -Type Application to see what PowerShell is seeing as valid executables.
You may find a clue as to what's going on, such as all of the listed applications have (or don't have) a certain extension, which could indicate a problem with the PATHEXT environment variable.


text:
Q: Clear data after ajax request succes I'm sending data from form' to database with ajax post request. After request succes, pushing data to an array in storage. In order not to load all from Backend API again. It works fine.
But, after pushing data to an array I need to clear form, to let user add another data. And it clears form before pushing it to array.
AddToDB.vue
<template>

    <form @submit.prevent="add">
         Name
        <input type="text" v-model="form.name"/>

         Price
        <input type="number" v-model="form.price"/>

        <button>Add</button>
    </form>

</template>

and store.js
export default {
state: {
    list: []
},
getters: {
    getList(state){
        return state.list;
    }
},
mutations: {
    addList(state, $data){
        state.list.push($data);
    }
} }

A: This should work for you.

// Your current code (not working)...
/*
  axios.post('http://test.com', this.$data.form, {
      headers: {
          "Authorization": `Bearer ${this.$store.getters.currentUser.token}`
      }
  })
  .then((response) => {
      this.$store.commit('addList', this.form);
  })
  .finally(() => this.clearForm())
*/

// Updated code...
axios.post('http://test.com', this.$data.form, { headers: { 'Authorization': `Bearer ${this.$store.getters.currentUser.token}` } })
  .then((response) => {
    this.$store.commit('addList', this.form);

    return Promise.resolve();
  })
  .then(() => this.clearForm());


text:
Q: How do I return a negative value based on a separate cell? I have a button that submits information and that works. All the numbers will be positive when entered by clients. The question at hand is:
If A4 = "Sell", cells A16, A18, and A20, return those numbers as negative values instead of positive. If A4 = "Buy", then return as is (positive).
Here's what I currently have. I don't know where to input this IF statement, or even how.
function SubmitBuy() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var formS = ss.getSheetByName("Front Sheet"); //Data entry sheet
  var dataS = ss.getSheetByName("Front Sheet"); //Data Sheet

  var values = [[formS.getRange("A2").getValue(),
                 formS.getRange("A4").getValue(),
                 formS.getRange("A6").getValue(),
                 formS.getRange("A8").getValue(),
                 formS.getRange("A10").getValue(),
                 formS.getRange("A12").getValue(),
                 formS.getRange("A16").getValue(),
                 formS.getRange("A18").getValue(),
                 formS.getRange("A20").getValue(),
                 formS.getRange("A28").getValue(), ]];

  dataS.getRange(dataS.getLastRow() +1, 3, 1, 10 ).setValues(values);
  ClearCells();
}

A: Get all of Column A's values and manipulate them using Array.map  and Set:
function SubmitBuy() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const frontSheet = ss.getSheetByName('Front Sheet'); //Data entry sheet
  const valuesA1A28 = frontSheet.getRange('A1:A28').getValues();
  const rowsNeeded = [2, 4, 5, 8, 10, 12, 16, 18, 20];
  const criteriaRow = 4;
  const rowsToModify = new Set([16, 18, 20]);
  const valuesNeeded = [
    rowsNeeded.map((thisRow) => {
      const thisValue = valuesA1A28[thisRow - 1][0];
      if (
        rowsToModify.has(thisRow) &&
        valuesA1A28[criteriaRow - 1][0] === 'Sell'
      )
        return -thisValue;
      else return thisValue;
    }),
  ];

  frontSheet
    .getRange(frontSheet.getLastRow() + 1, 3, 1, 10)
    .setValues(valuesNeeded);
  ClearCells();
}


text:
Q: individual string length in array javascript I need to create a function that takes in four strings and returns an array containing the length of each string. I was given this:
function stringLengths(str1, str2, str3, str4) {
  //
}

I've created an array of strings and I've searched google for so long all words are starting to look the same.

A: You can use Rest Paremeters to convert arguments in to array and then map them to get your required result. Below is my snippet.

function stringLengths(...strings){
  return strings.map(string => string.length);
}
console.log(stringLengths("","something","something else"))

A: You can use rest syntax and .map() function to get an array of string's length:

const stringLengths = (...str) => str.map(({ length }) => length);

console.log(stringLengths('lorem', 'ipsum'));
console.log(stringLengths('lorem', 'ipsum', 'sit', 'amet'));

A: If you don't want to change your function definition, you can also use the arguments object.

function stringLengths(str1, str2, str3, str4)
{
    return [...arguments].map(x => x.length);
}

console.log(stringLengths("hello", "cruel", "world", "of", "darkness"));

Or like this:

function stringLengths(str1, str2, str3, str4)
{
    return Object.values(arguments).map(x => x.length);
}

console.log(stringLengths("hello", "cruel", "world", "of", "darkness"));

A: There are excellent answers already to make stringLengths work with any number of parameters. However, all (so far) assume that each parameter is a string.
Which can lead to unexpected results:

*

*Both arrays and functions have a length property

*Any objects can be crafted with a length property

Or even errors:

*

*Things like null or undefined will throw an error when attempting to read properties from them.

const stringLengths = (...strs) =>
  strs.map(s => s.length);

console.log(
  stringLengths(1, 2)
);

console.log(
  stringLengths({length: ''}, [''], (a, b) => '')
);

console.log(
  stringLengths(null, null)
);

You can write a decorator filterStrings which you can apply to stringLengths so that it gets only strings:

const stringLengths = (...strs) =>
  strs.map(s => s.length);

const filterStrings = fn => (...args) =>
  fn(...args.filter(arg => typeof arg === 'string'));

const safeStringLengths = filterStrings(stringLengths);

console.log(
  safeStringLengths(1, 2)
);

console.log(
  safeStringLengths({length: ''}, [''], (a, b) => '')
);

console.log(
  safeStringLengths(null, null)
);

console.log(
  safeStringLengths("foo", "bar", "foobar")
);

filterStrings is the function that actually gets all the parameters, it keeps only strings and pass them on to stringLengths.
Why do it this way?
It depends on your context really. The nice thing about the decorator is that it allows you to move the validation of the parameters outside of stringLengths and let the function do just one thing.
In some scenarios you can simply trust your parameters and having validation in your function would be useless. In other scenarios, you can't. Being able to combine functions allows you to keep things separated and organised.

A: here is your code
function stringLengths(str1, str2, str3, str4) {
  return [str1.length, str2.length, str3.length, str4.length]
}

console.log(stringLengths('1','bb','ccc','dddd'))


text:
Q: ReactJS: How to display selected value from dropdown in input fields? I am trying to do following:
The user can select a calculation from the dropdown menu. The selected numbers(from calculation) appear in the input fields and the user can change the calculation. The modified calculation is displayed after pressing the "Add" button. Also the modified calculation should shown in red color in the dropdown menu.
I managed to get the calculation right, but the selected numbers doesn't appear in the input fields. What I have to do to update the values to the input fields?
Here is my code:
import React from 'react';

export default class Lisatehtava1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num1: 0,
            num2: 0,
            total: 0,
            results: [],
        }
    }

    handleChange = (e) => {
        const { name, value } = e.target;
        this.setState({
            [name]: value
        })
    }

    add = () => {

        const { num1, num2 } = this.state;

        this.setState({
            total: (parseInt(num1) + parseInt(num2))

        }, () => {

            let result = { num1: this.state.num1, num2: this.state.num2, total: this.state.total };

            const t = [...this.state.results, result];

            this.setState({ results: t }, () => {
                this.setState({ num1: "" }, () => {
                    this.setState({ num2: "" });

                });
            });
        })
    }

    render() {

        let dropdown = this.state.results.map((item, id) => {
            return <option key={id}>{item.num1} + {item.num2} = {item.total}</option>
        });

        return (

                    Numero 1
                    <input type="text" name="num1" onChange={this.handleChange} />

                    Numero 2
                    <input type="text" name="num2" onChange={this.handleChange} />

                <button onClick={this.add}>Add</button>

<select onChange={this.handleChange}>{dropdown}</select>

        );
    }
}

A: <input type="text" name="num2" onChange={this.handleChange} />

Here in the input, you are not assigning the value you get after calling onChange function. So it's always empty.
Write it as:
<input type="text" name="num2" onChange={this.handleChange} value={this.state.num1} />

A: There are a few things you have to change.
1.In the input tag you must include a value attibute
<input type="text" name="num1" onChange={this.handleChange} value={this.state.num1} />

similar to 2nd input tag
2.You can use split on the value from the select tag event.
<select onChange={(e)=>{
                      this.setState({
                        num1:e.target.value.split(" ")[0],
                         num2:e.target.value.split(" ")[2]
                      })
                }}>{dropdown}</select>

You can check out live example https://stackblitz.com/edit/react-fm8wd4


text:
Q: PHP Warning: PHP Startup: Unable to load dynamic library 'pdo_mysql.so' - module installed I've searched on thousand posts and still did not find a solution for my issue. Other posts there's no answer. Please do not mark as duplicate, because it isn't. In my case, the file exists on directory but is not recognized.
I am getting the error PHP Warning: PHP Startup: Unable to load dynamic library 'pdo_mysql.so' when I type the command:
php -v

I got this output:
PHP Warning:  PHP Startup: Unable to load dynamic library 'pdo_mysql.so' (tried: /usr/lib/php/20190902/pdo_mysql.so (/usr/lib/php/20190902/pdo_mysql.so: undefined symbol: mysqlnd_allocator), /usr/lib/php/20190902/pdo_mysql.so.so (/usr/lib/php/20190902/pdo_mysql.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP 7.4.3 (cli) (built: Mar  2 2022 15:36:52) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies

I have reinstalled php-mysql several times, tried to install the module pdo-mysql itself and nothing.
With the command php -m , i got all module (but missing pdo_mysql)
PHP Warning:  PHP Startup: Unable to load dynamic library 'pdo_mysql.so' (tried: /usr/lib/php/20190902/pdo_mysql.so (/usr/lib/php/20190902/pdo_mysql.so: undefined symbol: mysqlnd_allocator), /usr/lib/php/20190902/pdo_mysql.so.so (/usr/lib/php/20190902/pdo_mysql.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
[PHP Modules]
bz2
calendar
Core
ctype
curl
date
dom
exif
FFI
fileinfo
filter
ftp
gd
gettext
hash
iconv
imagick
json
libxml
mbstring
openssl
pcntl
pcre
PDO
Phar
posix
readline
Reflection
session
shmop
SimpleXML
sockets
sodium
SPL
ssh2
standard
sysvmsg
sysvsem
sysvshm
tokenizer
xml
xmlreader
xmlwriter
xsl
Zend OPcache
zip
zlib

[Zend Modules]
Zend OPcache

But the file itself exists on directory mentioned on the error:
/usr/lib/php/20190902  ls -la                                                                                 ✔  4 ⚙  3444  19:35:10
total 9,9M
drwxr-xr-x 2 root root 4,0K Mar  5 18:46 .
drwxr-xr-x 4 root root 4,0K Mar  5 18:46 ..
-rw-r--r-- 1 root root  31K Mar  2 12:36 bz2.so
-rw-r--r-- 1 root root  43K Mar  2 12:36 calendar.so
-rw-r--r-- 1 root root  15K Mar  2 12:36 ctype.so
-rw-r--r-- 1 root root 103K Mar  2 12:36 curl.so
-rw-r--r-- 1 root root 167K Mar  2 12:36 dom.so
-rw-r--r-- 1 root root  91K Mar  2 12:36 exif.so
-rw-r--r-- 1 root root 159K Mar  2 12:36 ffi.so
-rw-r--r-- 1 root root 5,5M Mar  2 12:36 fileinfo.so
-rw-r--r-- 1 root root  67K Mar  2 12:36 ftp.so
-rw-r--r-- 1 root root 115K Mar  2 12:36 gd.so
-rw-r--r-- 1 root root  19K Mar  2 12:36 gettext.so
-rw-r--r-- 1 root root  51K Mar  2 12:36 iconv.so
-rw-r--r-- 1 root root 448K Mar  2  2020 imagick.so
-rw-r--r-- 1 root root  47K Mar  2 12:36 json.so
-rw-r--r-- 1 root root 1,1M Mar  2 12:36 mbstring.so
-rw-r--r-- 1 root root 143K Mar  2 12:36 mysqli.so
-rw-r--r-- 1 root root 254K Mar  2 12:36 mysqlnd.so
-rw-r--r-- 1 root root 543K Mar  2 12:36 opcache.so
-rw-r--r-- 1 root root  35K Mar  2 12:36 pdo_mysql.so
-rw-r--r-- 1 root root 111K Mar  2 12:36 pdo.so
-rw-r--r-- 1 root root 275K Mar  2 12:36 phar.so
-rw-r--r-- 1 root root  43K Mar  2 12:36 posix.so
-rw-r--r-- 1 root root  39K Mar  2 12:36 readline.so
-rw-r--r-- 1 root root  15K Mar  2 12:36 shmop.so
-rw-r--r-- 1 root root  55K Mar  2 12:36 simplexml.so
-rw-r--r-- 1 root root  99K Mar  2 12:36 sockets.so
-rw-r--r-- 1 root root  89K Feb 28  2020 ssh2.so
-rw-r--r-- 1 root root  23K Mar  2 12:36 sysvmsg.so
-rw-r--r-- 1 root root  15K Mar  2 12:36 sysvsem.so
-rw-r--r-- 1 root root  19K Mar  2 12:36 sysvshm.so
-rw-r--r-- 1 root root  27K Mar  2 12:36 tokenizer.so
-rw-r--r-- 1 root root  39K Mar  2 12:36 xmlreader.so
-rw-r--r-- 1 root root  55K Mar  2 12:36 xml.so
-rw-r--r-- 1 root root  51K Mar  2 12:36 xmlwriter.so
-rw-r--r-- 1 root root  35K Mar  2 12:36 xsl.so
-rw-r--r-- 1 root root  71K Mar  2 12:36 zip.so

I'm on a Linux Mint 20, latest version of php, mysql and apache.
Does anybody know how to install pdo_mysql and get rid of this issue?

A: For those with same issue, I just found a solution. When it's unable to load dynamically, in my case meant I probably had a broken php installation (e.g. corrupted file), so I had to reinstall it, but just installing it again the issue remained. In this case I had to completely remove the php files and then reinstall it again. Here are the steps I took:

*

*First uninstall only the php related files. The command below search and purge for those specific php files.
sudo apt-get purge dpkg -l | grep php| awk '{print $2}' |tr "\n" " "
If everything ok, jump to step 2. During this process, I found another error:
sub-process /usr/bin/dpkg returned an error code (1)
dpkg: error processing package phpmyadmin (--configure): installed phpmyadmin package post-installation script subprocess returned error exit status 127
So I completely removed phpmyadmin files
sudo apt-get purge phpmyadmin
rm -r /var/lib/dpkg/info/phpmyadmin.*
sudo apt-get clean
&& sudo apt-get update
&& sudo apt-get remove phpmyadmin
&& sudo apt-get purge phpmyadmin
After that I was able to completely remove php:
sudo apt-get purge dpkg -l | grep php| awk '{print $2}' |tr "\n" " "

*After that, reinstall php again, then all should be running smoothly (ref: https://www.digitalocean.com/community/tutorials/how-to-install-php-7-4-and-set-up-a-local-development-environment-on-ubuntu-20-04)
sudo apt-get update
sudo apt -y install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt -y install php7.4
php -v (check php working)

*And finally install phpMyAdmin again:
sudo apt update
sudo apt install phpmyadmin php-mbstring php-zip php-gd php-json php-curl
sudo phpenmod mbstring
sudo systemctl restart apache2


text:
Q: Hibernate Spring - @OneToMany - Foreign key is not getting stored in database Requirement - For Recipe application, user can input Recipe Name and Ingredients. User can input more than one ingredient of a recipe on the JSP page.
Database Model: Created 2 tables. (Recipe can have more than one Ingredient)
Recipe -
   recipe_id (primary key)
   name

Ingredient
  ingredient_id (primary key)
  recipe_id (foreign key to recipe(recipe_id))
  quantity
  ingredient

Issue - For this case, @OneToMany (as shown below) is used for Hibernate mapping but when user save the form, foreign key (i.e. recipe_id) is not getting stored in the Ingredient table.
Say user inputs following:
Recipe -  Sandwich
Ingredient - 250g(as quantity) Salt (as ingredient)

After saving following is getting saved (i.e. No value in the recipe table)
**Recipe**
recipe_id - 1
name - Sandwich

**Ingredient**
ingredient_id - 50
recipe_id - NULL
quantity - 250g
ingredient - Salt

There is no error while saving form.
Following is saved in log by Hibernate when user save the data:
Hibernate: select seq_recipe.nextval from dual
Hibernate: select seq_ingredient.nextval from dual
Hibernate: insert into RECIPE (NAME, RECIPE_ID) values (?, ?)
Hibernate: insert into ingredient (COMMENTS, INGREDIENT, RECIPE_ID, INGREDIENT_ID) values (?, ?, ?, ?)

Oracle table
create table ingredient(ingredient_id number(4) primary key,
                    quantity varchar2(20),
                    ingredient varchar2(40),
                    recipe_id number(4),
                    constraint recipe_fk foreign key (recipe_id)
                    references recipe(recipe_id));

create table recipe(id number primary key,
                    name varchar2(25) unique,
                    ingredient_id number(4),
                    constraint ingredient_fk foreign key(ingredient_id)
                    references ingredient(ingredient_id));

Ingredient and Recipe POJO
@Entity
@Table(name = "ingredient", uniqueConstraints={
        @UniqueConstraint(columnNames="INGREDIENT_ID")
})
public class Ingredient implements Serializable {
    private static final long serialVersionUID = -2489479702169761646L;

    @Id
    @Column(name = "INGREDIENT_ID", unique=true, nullable=false)
    @SequenceGenerator(name="seq_ingredient", sequenceName="seq_ingredient")
    @GeneratedValue(strategy=GenerationType.AUTO, generator="seq_ingredient")
    private Integer ingredientId;

    @Column(name = "QUANTITY")
    private String quantity;

    @Column(name = "INGREDIENT")
    private String ingredient;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="RECIPE_ID", nullable=false)
    private Recipe recipe;

    //getter and setters

@Entity
@Table(name = "recipe")
public class Recipe implements Serializable {
    private static final long serialVersionUID = 4398676897855994030L;

    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="recipe")
    private List<Ingredient> ingredients;

//getters and setter
}

MVC that will map the /add url and also handle POST method, when user save the data
@RequestMapping("/add")
public String newRecipe(Model model) {
    Recipe recipe = new Recipe();
    recipe.setIngredients(new AutoPopulatingList<Ingredient>(Ingredient.class));

    model.addAttribute("recipe", recipe);
    return "recipes/new";
}

@RequestMapping(value = "add", method = RequestMethod.POST)
public String addRecipe(@Valid Recipe recipe, BindingResult result,
        Model model) {
    if (result.hasErrors()) {
        return "recipes/new";
    }
    recipeServices.addRecipe(recipe);
    return "redirect:/recipe/" + recipe.getId();
}

**DAO to save Recipe objec **
public class RecipeDaoImpl implements RecipeDao {
    public void addRecipe(Recipe recipe) {
        getSession().save(recipe);
    }
}

JSP code

    <s:url value="/recipe/add" var="recipe_new" />

    <sf:form modelAttribute="recipe" action="${recipe_new}" method="POST">

                Recipe Name:
                <sf:input path="name" id="recipeName" />

                        <sf:errors path="name" cssClass="error" />

Ingredients
 <INPUT type="button" value="+"
                    onclick="addRow('dataTable')" /> <INPUT type="button" value="-"
                    onclick="deleteRow('dataTable')" />

                            Quantity
                            Ingredient

                            <input type="checkbox" name="chk" />
                            <sf:input type="text" path="ingredients[0].quantity"
                                    title="Quantity" placeholder="Quantity" />
                            <sf:input type="text" path="ingredients[0].ingredient"
                                    title="Ingredient" placeholder="Ingredient" />

    </sf:form>

Humble request to help me as I have been trying to fix this issue from past 2 days and not able to understand why foreign key not getting stored in database.

A: mappedBy is generally for bidirection relationship, to save extra queries for updation/insertion.
Basically for OneToMany on Parent side and ManyToOne on Child Side.
In your case, mappedBy means that Parent does not hold responsibility to save references to Child.
So try using @JoinColumn in your case.


text:
Q: Nmap can't find saved text file I am learning to use nmap an zenmap for collage. I need to save the resoult to file. First i thought there is something wrong whit my code. Then I used cat and the file is saved ok. But i cant find it, they are not in my home folder, they are not in my data or anywhere else.

nmap -oN somerandom.txt -sS -O 192.168.1.103

Plus where can i find /proc/net/arp directory in linux

A:
it was in /root that i cant acces. Can u tell me how can i acces if ?

Presumably you haven't access permissions for /root (one wouldn't have to guess if you provided the error message); you could switch to the user whom /root belongs to (usually root).


text:
Q: Images are uploading with only 777 permission We are using Ubuntu and we are uploading images through a php site. The images were uploading to this path:
/var/www/html/sbdev2/php/site6/upload

The "upload" folder has the permissions 755 but now its showing the below error. When we change the permissions to 777 on the upload folder, it works fine. As this is not recommended is there any solution for this?
Warning:

move_uploaded_file(/var/www/html/sbdev2/php/site6/upload/1581008501582d7f6be83fe0.85542989.jpg): failed to open stream: Permission denied in /var/www/html/sbdev2/php/site6/class.user.php on line 114
Warning: move_uploaded_file(): Unable to move '/tmp/phpOCj6Kp' to '/var/www/html/sbdev2/php/site6/upload/1581008501582d7f6be83fe0.85542989.jpg' in /var/www/html/sbdev2/php/site6/class.user.php on line 114

Edit
When I upload an image with 777, it is displaying like this:

A: Check the permissions of the upload folder and the uploaded files with ls -l.
Afterwards change the folder owner to the owner of the files: chmod user:group upload.
Now you should be able to set 755 permissions.


text:
Q: Ruby on Rails helper prints out odd stuff I want to create a helper which iterates thru the list of user's communities and creates as many thumbnails as the number of comunities available. So I created these 2 helper methods
def print_admined_group_thumbs
    @user_groups_hash[:admined_groups].each {
        |group_hash|

        name            = group_hash[:name]
        group_id        = group_hash[:group_id]
        photo           = group_hash[:photo]
        members_count   = group_hash[:members_count].to_i

        concat(get_group_thumbnail_html(group_id, name, members_count, photo))
    }
end

# creates a small preview for the selected comunity group
def get_group_thumbnail_html(group_id, name, members_count, photo)
    content_tag(:div, :class => "col-md-55") do
       concat(content_tag( :div, :class => 'thumbnail') do
            concat(content_tag(:div, :class => 'image view view-first') do
                concat(image_tag(photo, :class => "group_thumb_image"))
                concat(content_tag(:div, :class => "mask") do
                    concat(content_tag :p, "Your text")
                    concat(content_tag(:div, :class => "tools tools-bottom") do

                    end)
                end)
                concat(content_tag(:div, :class => "caption") do
                    concat(content_tag(:p, name))
                end)
            end)
       end)
    end
end #end get_group_thumbnail_html

So I simply add this call to my view
<%= print_admined_group_thumbs %>

It all works almost correctly and creates all thumbnails just like I want, except for one thing. It also prints out the entire contents of "group_hash" variable right after the thumbnails. Maybe I'm just too exhausted today, but I can't seem to figure out why? I'd be greateful if somebody helped me solve this problem and explain what am I doing wrong with it?

A: @some_hash.each {} automatically returns the hash after it completes. So your function print_admined_group_thumbs() adds your thumbnails to the template and returns the hash.
The problem is here:
<%= print_admined_group_thumbs %>

That = means "take whatever value is returned and add it to the template. So you're accidentally adding the hash to the template after printing the thumbnails to the template. You can easily fix it by removing the =:
<% print_admined_group_thumbs %>

This tells rails to run the function without adding its return value to the template.


text:
Q: rdlc print auto generate I am developing the window application using C#. I am using the reportviewer to display rdlc. I just require following things:
1). Print rdlc without viewing it Client will click on print button and print should go System default printer.
2). if System default printer is not available/working then it will prompt for alternative.
i don't want to use xml file

A: Here is what you need to do is load your report and data into the report viewer and then render the report pages into list of memory streams and print them using then PrintDocument Class here as an expample how it is done link. For the part where it asks the user if it doesn't find default printer change
if (!printDoc.PrinterSettings.IsValid)
        {
            throw new Exception("Error: cannot find the default printer.");
        }

in the Print()method with the showing of PrintDialog for user to select printer.


text:
Q: how to expand system path using ruby? I'm trying to require modules in my app without using require ./module or require_relative.
I know that in python you can do:
import sys

sys.path.append("whatever")

Then, you can import every module in the "whatever" path.
I guess it is possible to do it in ruby as well, but couldn't figure out a better way than:
ENV["PATH"] += ':whatever'

A: What about
$LOAD_PATH.unshift('whatever')
$LOAD_PATH.append('whatever')

https://thoughtbot.com/blog/following-the-path


text:
Q: Do not update linked Excel cell based on a timestamp First question: two Excel cells are linked (A6 = A3). When I update A3, A6 gets updated.
How can I register to the change event of A6?
By using the following VBA code, I register to the change event of A3, but I cannot find how to register for the automatic change of A6.

*

*Any idea how to do this?

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Target.Worksheet.Range("A14:A15"))_
            Is Nothing Then
        MsgBox "Cell " & Target.Address & " has changed."
    End If
End Sub

Here's the broader scenario that I am trying to achieve: Depending of the value of a timestamp, I would like the second cell to update itself, or keep its current value.
Here's the current behavior. A6 and A7 reference A3. If I update A3 to "2", A6 and A7 gets updated to "2" as well. Regardless what the timestamp says (the C column just contains the formula used in the B column, for explanation purpose):

What I would like to achieve is the following.

The timestamp B6 is one minute in the past and B7 one minute in the future. After updating A3 to "2", I want A6 to remain "1", and B7 to update itself to "2".
In order to do this, I thought I can use the change event described above and block the update event after I tested the timestamps in a macro.

*Any better idea on how to achieve this?


text:
Q: error in .local (obj, ) cannat derive coordinates from non-numeric matrix I am using adehabitatHR in R,  trying to calculate home range overlap. I have successfully loaded two .tsv files with location data for two different animals (individuals 70F and 153F respectively). The .tsv files have 5 columns, 2 of which are the latitude and longitude data (DDE and DDS); in decimal degrees. However, when I try to convert to coordinates I get the following error:

coordinates (locs153M) < - c ("DDE", "DDS")
  Error in .local(obj, ...) :
    cannot derive coordinates from non-numeric matrix

Here is my script:
> locs07F <- read.delim("C:\\Users\\cpickering\\Documents\\Black Rhino\\Management Plan 2015\\Maps\\Sightings_07F.tsv", header = TRUE)
> library(adehabitatHR)
Loading required package: sp
Loading required package: deldir
deldir 0.1-9
Loading required package: ade4
Loading required package: adehabitatMA
Loading required package: adehabitatLT
Loading required package: CircStats
Loading required package: MASS
Loading required package: boot
> library (maptools)
Checking rgeos availability: TRUE
> library(rgeoos)
Error in library(rgeoos) : there is no package called 'rgeoos'
> library (rgeos)
rgeos version: 0.3-13, (SVN revision 508)
 GEOS runtime version: 3.4.2-CAPI-1.8.2 r3921
 Linking to sp version: 1.2-0
 Polygon checking: TRUE

Warning message:
package 'rgeos' was built under R version 3.2.2
> class (locs07F)
[1] "data.frame"
> coordinates (locs07F) < - c ("DDE", "DDS")
Error in .local(obj, ...) :
  cannot derive coordinates from non-numeric matrix
> locs153M <- read.delim("C:\\Users\\cpickering\\Documents\\Black Rhino\\Management Plan 2015\\Maps\\Sightings_153M.tsv", header = TRUE)
> class (locs153M)
[1] "data.frame"
> coordinates (locs153M) < - c ("DDE", "DDS")
Error in .local(obj, ...) :
  cannot derive coordinates from non-numeric matrix
> locs153M(,)
Error: could not find function "locs153M"
> head("locs153M", n = 10)
[1] "locs153M"
> head(locs153M)
  SightingID       Date       DDS      DDE     RhinosAtSighting
1       2489 24/08/2015 -27.85235 32.29086 161, 07, 07-C-2014,
2       2472 15/08/2015 -27.84257 32.30194           160, 161,
3       2447 09/07/2015 -27.85831 32.29140                161,
4       2438 01/07/2015 -27.83754 32.31780           154, 160,
5       2424 06/06/2015 -27.84686 32.35096           154, 160,
6       2403 20/05/2015 -27.83959 32.30993                161,
> summary(locs153M)
   SightingID           Date         DDS              DDE         RhinosAtSighting
 Min.   :1032   15/04/2014: 2   Min.   :-27.87   Min.   :32.28   07,      :25
 1st Qu.:1378   01/07/2013: 1   1st Qu.:-27.85   1st Qu.:32.30   154,     :14
 Median :1645   01/07/2015: 1   Median :-27.85   Median :32.31   07, 161, : 7
 Mean   :1743   01/09/2011: 1   Mean   :-27.85   Mean   :32.32   161,     : 6
 3rd Qu.:2153   02/02/2012: 1   3rd Qu.:-27.84   3rd Qu.:32.32   160,     : 5
 Max.   :2489   02/04/2014: 1   Max.   :-27.83   Max.   :32.35            : 4
                (Other)   :76                                    (Other)  :22
> library (rgdal)
rgdal: version: 1.0-7, (SVN revision 559)
 Geospatial Data Abstraction Library extensions to R successfully loaded
 Loaded GDAL runtime: GDAL 1.11.2, released 2015/02/10
 Path to GDAL shared files: C:/Program Files/R/R-3.2.1/library/rgdal/gdal
 GDAL does not use iconv for recoding strings.
 Loaded PROJ.4 runtime: Rel. 4.9.1, 04 March 2015, [PJ_VERSION: 491]
 Path to PROJ.4 shared files: C:/Program Files/R/R-3.2.1/library/rgdal/proj
 Linking to sp version: 1.2-0
> coordinates (locs153M) < - c ("DDE", "DDS")
Error in .local(obj, ...) :
  cannot derive coordinates from non-numeric matrix

I'm stumped. Anyone have any ideas?

A: You're assigning a two-item character vector to the coordinates in this spot:
coordinates(locs153M) <- c("DDE", "DDS")

You need to assign it the actual columns, using eg a formula:
coordinates(locs153M) <- ~DDE + DDS