text:
Q: Is it good practice to NULL a pointer after deleting it? I'll start out by saying, use smart pointers and you'll never have to worry about this.
What are the problems with the following code?
Foo * p = new Foo;
// (use p)
delete p;
p = NULL;

This was sparked by an answer and comments to another question. One comment from Neil Butterworth generated a few upvotes:

Setting pointers to NULL following delete is not universal good practice in C++. There are times when it is a good thing to do, and times when it is pointless and can hide errors.

There are plenty of circumstances where it wouldn't help. But in my experience, it can't hurt. Somebody enlighten me.

A: If there is more code after the delete, Yes.  When the pointer is deleted in a constructor or at the end of method or function, No.
The point of this parable is to remind the programmer, during run-time, that the object has already been deleted.
An even better practice is to use Smart Pointers (shared or scoped) which automagically delete their target objects.

A: Setting pointers to NULL after you've deleted what it pointed to certainly can't hurt, but it's often a bit of a band-aid over a more fundamental problem: Why are you using a pointer in the first place? I can see two typical reasons:

*

*You simply wanted something allocated on the heap. In which case wrapping it in a RAII object would have been much safer and cleaner. End the RAII object's scope when you no longer need the object. That's how std::vector works, and it solves the problem of accidentally leaving pointers to deallocated memory around. There are no pointers.

*Or perhaps you wanted some complex shared ownership semantics. The pointer returned from new might not be the same as the one that delete is called on. Multiple objects may have used the object simultaneously in the meantime. In that case, a shared pointer or something similar would have been preferable.

My rule of thumb is that if you leave pointers around in user code, you're Doing It Wrong. The pointer shouldn't be there to point to garbage in the first place. Why isn't there an object taking responsibility for ensuring its validity? Why doesn't its scope end when the pointed-to object does?

A: I've got an even better best practice: Where possible, end the variable's scope!
{
    Foo* pFoo = new Foo;
    // use pFoo
    delete pFoo;
}

A: I always set a pointer to NULL (now nullptr) after deleting the object(s) it points to.

*

*It can help catch many references to freed memory (assuming your platform faults on a deref of a null pointer).

*It won't catch all references to free'd memory if, for example, you have copies of the pointer lying around.  But some is better than none.

*It will mask a double-delete, but I find those are far less common than accesses to already freed memory.

*In many cases the compiler is going to optimize it away.  So the argument that it's unnecessary doesn't persuade me.

*If you're already using RAII, then there aren't many deletes in your code to begin with, so the argument that the extra assignment causes clutter doesn't persuade me.

*It's often convenient, when debugging, to see the null value rather than a stale pointer.

*If this still bothers you, use a smart pointer or a reference instead.
I also set other types of resource handles to the no-resource value when the resource is free'd (which is typically only in the destructor of an RAII wrapper written to encapsulate the resource).
I worked on a large (9 million statements) commercial product (primarily in C).  At one point, we used macro magic to null out the pointer when memory was freed.  This immediately exposed lots of lurking bugs that were promptly fixed.  As far as I can remember, we never had a double-free bug.
Update: Microsoft believes that it's a good practice for security and recommends the practice in their SDL policies.  Apparently MSVC++11 will stomp the deleted pointer automatically (in many circumstances) if you compile with the /SDL option.

A: As others have said, delete ptr; ptr = 0; is not going to cause demons to fly out of your nose.  However, it does encourage the usage of ptr as a flag of sorts.  The code becomes littered with delete and setting the pointer to NULL.  The next step is to scatter if (arg == NULL) return; through your code to protect against the accidental usage of a NULL pointer.  The problem occurs once the checks against NULL become your primary means of checking for the state of an object or program.
I'm sure that there is a code smell about using a pointer as a flag somewhere but I haven't found one.

A: I'll change your question slightly:

Would you use an uninitialized
  pointer? You know, one that you didn't
  set to NULL or allocate the memory it
  points to?

There are two scenarios where setting the pointer to NULL can be skipped:

*

*the pointer variable goes out of scope immediately

*you have overloaded the semantic of the pointer and are using its value not only as a memory pointer, but also as a key or raw value. this approach however suffers from other problems.

Meanwhile, arguing that setting the pointer to NULL might hide errors to me sounds like arguing that you shouldn't fix a bug because the fix might hide another bug. The only bugs that might show if the pointer is not set to NULL would be the ones that try to use the pointer. But setting it to NULL would actually cause exactly the same bug as would show if you use it with freed memory, wouldn't it?

A: If you have no other constraint that forces you to either set or not set the pointer to NULL after you delete it (one such constraint was mentioned by Neil Butterworth), then my personal preference is to leave it be.
For me, the question isn't "is this a good idea?" but "what behavior would I prevent or allow to succeed by doing this?" For example, if this allows other code to see that the pointer is no longer available, why is other code even attempting to look at freed pointers after they are freed? Usually, it's a bug.
It also does more work than necessary as well as hindering post-mortem debugging. The less you touch memory after you don't need it, the easier it is to figure out why something crashed. Many times I have relied on the fact that memory is in a similar state to when a particular bug occurred to diagnose and fix said bug.

A: Explicitly nulling after delete strongly suggests to a reader that the pointer represents something which is conceptually optional.  If I saw that being done, I'd start worrying that everywhere in the source the pointer gets used that it should be first tested against NULL.
If that's what you actually mean, it's better to make that explicit in the source using something like boost::optional
optional<Foo*> p (new Foo);
// (use p.get(), but must test p for truth first!...)
delete p.get();
p = optional<Foo*>();

But if you really wanted people to know the pointer has "gone bad", I'll pitch in 100% agreement with those who say the best thing to do is make it go out of scope.  Then you're using the compiler to prevent the possibility of bad dereferences at runtime.
That's the baby in all the C++ bathwater, shouldn't throw it out.  :)

A: In a well structured program with appropriate error checking, there is no reason not to assign it null. 0 stands alone as a universally recognized invalid value in this context. Fail hard and Fail soon.
Many of the arguments against assigning 0 suggest that it could hide a bug or complicate control flow. Fundamentally, that is either an upstream error (not your fault (sorry for the bad pun)) or another error on the programmer's behalf -- perhaps even an indication that program flow has grown too complex.
If the programmer wants to introduce the use of a pointer which may be null as a special value and write all the necessary dodging around that, that's a complication they have deliberately introduced. The better the quarantine, the sooner you find cases of misuse, and the less they are able to spread into other programs.
Well structured programs may be designed using C++ features to avoid these cases. You can use references, or you can just say "passing/using null or invalid arguments is an error" -- an approach which is equally applicable to containers, such as smart pointers. Increasing consistent and correct behavior forbids these bugs from getting far.
From there, you have only a very limited scope and context where a null pointer may exist (or is permitted).
The same may be applied to pointers which are not const. Following the value of a pointer is trivial because its scope is so small, and improper use is checked and well defined. If your toolset and engineers cannot follow the program following a quick read or there is inappropriate error checking or inconsistent/lenient program flow, you have other, bigger problems.
Finally, your compiler and environment likely has some guards for the times when you would like to introduce errors (scribbling), detect accesses to freed memory, and catch other related UB. You can also introduce similar diagnostics into your programs, often without affecting existing programs.

A: Firstly, there are a lot of existing questions on this and closely related topics, for example Why doesn't delete set the pointer to NULL?.
In your code, the issue what goes on in (use p). For example, if somewhere you have code like this:
Foo * p2 = p;

then setting p to NULL accomplishes very little, as you still have the pointer p2 to worry about.
This is not to say that setting a pointer to NULL is always pointless. For example, if p were a member variable pointing to a resource who's lifetime was not exactly the same as the class containing p, then setting p to NULL could be a useful way of indicating the presence or absence of the resource.

A: Setting a pointer to 0 (which is "null" in standard C++, the NULL define from C is somewhat different) avoids crashes on double deletes.
Consider the following:
Foo* foo = 0; // Sets the pointer to 0 (C++ NULL)
delete foo; // Won't do anything

Whereas:
Foo* foo = new Foo();
delete foo; // Deletes the object
delete foo; // Undefined behavior

In other words, if you don't set deleted pointers to 0, you will get into trouble if you're doing double deletes. An argument against setting pointers to 0 after delete would be that doing so just masks double delete bugs and leaves them unhandled.
It's best to not have double delete bugs, obviously, but depending on ownership semantics and object lifecycles, this can be hard to achieve in practice. I prefer a masked double delete bug over UB.
Finally, a sidenote regarding managing object allocation, I suggest you take a look at std::unique_ptr for strict/singular ownership, std::shared_ptr for shared ownership, or another smart pointer implementation, depending on your needs.

A: Let me expand what you've already put into your question.
Here's what you've put into your question, in bullet-point form:

Setting pointers to NULL following delete is not universal good practice in C++. There are times when:

*

*it is a good thing to do

*and times when it is pointless and can hide errors.

However, there is no times when this is bad! You will not introduce more bugs by explicitly nulling it, you will not leak memory, you will not cause undefined behaviour to happen.
So, if in doubt, just null it.
Having said that, if you feel that you have to explicitly null some pointer, then to me this sounds like you haven't split up a method enough, and should look at the refactoring approach called "Extract method" to split up the method into separate parts.

A: There is always Dangling Pointers to worry about.

A: Yes.
The only "harm" it can do is to introduce inefficiency (an unnecessary store operation) into your program - but this overhead will be insignificant in relation to the cost of allocating and freeing the block of memory in most cases.
If you don't do it, you will have some nasty pointer derefernce bugs one day.
I always use a macro for delete:
#define SAFEDELETE(ptr) { delete(ptr); ptr = NULL; }

(and similar for an array, free(), releasing handles)
You can also write "self delete" methods that take a reference to the calling code's pointer, so they force the calling code's pointer to NULL. For example, to delete a subtree of many objects:
static void TreeItem::DeleteSubtree(TreeItem *&rootObject)
{
    if (rootObject == NULL)
        return;

    rootObject->UnlinkFromParent();

    for (int i = 0; i < numChildren)
       DeleteSubtree(rootObject->child[i]);

    delete rootObject;
    rootObject = NULL;
}

edit
Yes, these techniques do violate some rules about use of macros (and yes, these days you could probably achieve the same result with templates) - but by using over many years I never ever accessed dead memory - one of the nastiest and most difficult and most time consuming to debug problems you can face. In practice over many years they have effectively eliminated a whjole class of bugs from every team I have introduced them on.
There are also many ways you could implement the above - I am just trying to illustrate the idea of forcing people to NULL a pointer if they delete an object, rather than providing a means for them to release the memory that does not NULL the caller's pointer.
Of course, the above example is just a step towards an auto-pointer. Which I didn't suggest because the OP was specifically asking about the case of not using an auto pointer.

A: "There are times when it is a good thing to do, and times when it is pointless and can hide errors"
I can see two problems:
That simple code:
delete myObj;
myobj = 0

becomes to a for-liner in multithreaded environment:
lock(myObjMutex);
delete myObj;
myobj = 0
unlock(myObjMutex);

The "best practice" of Don Neufeld don't apply always. E.g. in one automotive project we had to set pointers to 0 even in destructors. I can imagine in safety-critical software such rules are not uncommon. It is easier (and wise) to follow them than trying to persuade
the team/code-checker for each pointer use in code, that a line nulling this pointer is redundant.
Another danger is relying on this technique in exceptions-using code:
try{
   delete myObj; //exception in destructor
   myObj=0
}
catch
{
   //myObj=0; <- possibly resource-leak
}

if (myObj)
  // use myObj <--undefined behaviour

In such code either you produce resource-leak and postpone the problem or the process crashes.
So, this two problems going spontaneously through my head (Herb Sutter would for sure tell more) make for me all the questions of the kind "How to avoid using smart-pointers and do the job safely with normal pointers" as obsolete.

A: If you're going to reallocate the pointer before using it again (dereferencing it, passing it to a function, etc.), making the pointer NULL is just an extra operation.  However, if you aren't sure whether it will be reallocated or not before it is used again, setting it to NULL is a good idea.
As many have said, it is of course much easier to just use smart pointers.
Edit: As Thomas Matthews said in this earlier answer, if a pointer is deleted in a destructor, there isn't any need to assign NULL to it since it won't be used again because the object is being destroyed already.

A: I can imagine setting a pointer to NULL after deleting it being useful in rare cases where there is a legitimate scenario of reusing it in a single function (or object). Otherwise it makes no sense - a pointer needs to point to something meaningful as long as it exists - period.

A: If the code does not belong to the most performance-critical part of your application, keep it simple and use a shared_ptr:
shared_ptr<Foo> p(new Foo);
//No more need to call delete

It performs reference counting and is thread-safe. You can find it in the tr1 (std::tr1 namespace, #include < memory >) or if your compiler does not provide it, get it from boost.


text:
Q: Possible to make a zero be true? I have a string:
$string = '0';

And in an echo statement like this:
echo ($string ? 'true':'false');

I want the '0' to be true. It currently is false.
Is there a way to adjust the echo statement? I know I can for example add a space in the string:
$string = ' 0';

And it will be true. But I am hoping for a solution that doesn't require me adjusting the string.

A:
Is there a way to adjust the echo statement?

No - not without editing PHP's source code and rebuilding it yourself. The echo statement in PHP has 20-year-old  well-documented behaviour - it would be foolish to make your PHP environment incompatible with the rest of the PHP ecosystem just to save yourself a few keystrokes.
A better idea is just to add your own global function:
<?php

function zeroToBoolText( $str ) {
    if( !is_string( $str ) ) die( "Argument is not a string." );
    if( $str === '0' ) {
        return 'true';
    }
    else {
        return ( $str ? 'true' : 'false' );
    }
}

?>

Used like so:
$string = '0';

echo zeroToBoolText( $string );

A: Using the below condition you can change if string is 0 true..
    if($string === '0')
    {
        $string = true;
    }
    else
    {
        $string = false;
    }

Try it, i think you need this one thank you..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Salesforce: Contact sharing I do have an issue with sharing a contact with partner users. The objective of the trigger is that, if a partner tries to create a contact in our system and if the email he uses to create the new contact is already in a contact, then share that existing contact with the partner rather than creating new contact.
Below is trigger that I used.
trigger checkContactExists on Contact(before insert) {
    String us = userinfo.getUserType();
    String emailValue = '';
    List<ContactShare> sharesToCreate = new List<ContactShare>();

    if(us == 'PowerPartner' || us == 'CSPLitePortal' || us == 'CustomerSuccess' || us == 'PowerCustomerSuccess') {
        for(Contact c: Trigger.New){
            emailValue = c.Email;
            list<contact> contact1 = [SELECT Id FROM contact WHERE Email =:emailValue];
            if(contact1.size()>0) {
                for (Contact cont :contact1){
                    Contactshare cs = new ContactShare(ContactAccessLevel='Read', ContactId = cont.Id, userOrGroupId = UserInfo.getUserId());
                    sharesToCreate.add(cs);
                }
            }
            c.addError('Duplicate contact found with the same email. The existing contact has been shared with you.');
        }

    }
     if (!sharesToCreate.isEmpty()) {
        //Database.SaveResult[] insertResults = Database.insert(sharesToCreate,true);
        insert sharesToCreate;
    }
}

The code doesn't shows any error and debug log says it created a row on contactsshare.
    :57:25.0 (49336464)|STATEMENT_EXECUTE|[20]
16:57:25.0 (49337911)|STATEMENT_EXECUTE|[22]
16:57:25.0 (49400693)|DML_BEGIN|[22]|Op:Insert|Type:ContactShare|Rows:1
16:57:25.0 (49430731)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
16:57:25.0 (94617974)|DML_END|[22]

But when looking into the SOQL, I don't see any new rows of data being added. Any help appreciated.

A: You are using the SOQL inside the for loop. Please move outside of it.
First get all the email in a set
Set<String> emailSet = new Set<String>;
for(Contact c: Trigger.New)
{
    emailSet.put(c.Email);
}

Then query the for existing record and store in a set
Set<String> extEmailSet = new Set<String>;
for(contact con : [SELECT Id FROM contact WHERE Email IN :emailSet])
{
    extEmailSet.put(con.Email)
}

Now check the user type and ensure the set contains the existing email set then add error else create a share record.
if(us == 'PowerPartner' || us == 'CSPLitePortal' || us == 'CustomerSuccess' || us == 'PowerCustomerSuccess')
    {
        for(Contact c: Trigger.New)
        {
            //Check Duplicate email
            if(!extEmailSet.contains(c.Email))
            {
                Contactshare cs = new ContactShare(ContactAccessLevel='Read', ContactId = c.Id, userOrGroupId = UserInfo.getUserId());
                sharesToCreate.add(cs);
            }
            else
            {
                c.addError('Duplicate contact found with the same email. The existing contact has been shared with you.');
            }
        }

    }

then insert the share record.
if (!sharesToCreate.isEmpty()) {
        //Database.SaveResult[] insertResults = Database.insert(sharesToCreate,true);
        insert sharesToCreate;
    }


text:
Q: Does $\sum_{n=1}^\infty \left(\frac{1}{n} - 1\right)^n$ and $\sum_{n=1}^\infty \left(\frac{1}{n} - 1\right)^{n^2}$ converge? My task is this:
Determin whether $\sum_{n=1}^\infty \left(\frac{1}{n} - 1\right)^n$ and $\sum_{n=1}^\infty \left(\frac{1}{n} - 1\right)^{n^2}$ converge or diverge.
My thoughts:
For large $n$ one should expect $n^{-1} - 1 \to -1 \neq 0 $ raising that to $n$th power should yeald $\{-1,1\}$, again for big $n$, but I'm probably way off here and need some hints tips or better approach to this.
Thanks in advance!

A: Let $a_n = ( \frac{1}{n} - 1)^{n^2}$
Then $|a_n| = (1- \frac{1}{n})^{n^2} =\exp(n^2 \ln (1-\frac{1}{n})) \sim e^{-n+\frac{1}{2}}$
$ \sum e^{-n+\frac{1}{2}}$ converges so  $ \sum |a_n|$ converges then $ \sum a_n$ also converges.
So the second sum does converge.
For the first sum, as already mentioned by H Potter, the general term does not converge to 0 so the sum does not converge.

A: Note that $(1-\frac1n)^n \rightarrow e^{-1}$ as $n\rightarrow \infty$.
Hence, the terms in the first sum don't tend to 0 (they tend to $\pm e^{-1}$ whether $n$ is even or odd) so the sum cannot converge.
I'm currently thinking about the second sum.


text:
Q: Creating a C# VS2010 Visualizer that operates on all Object I'm attempting to create a C# debugging visualizer that can perform a visualization on all objects.  I can't seem to get the assembly attribute (above the namespace) to bind this visualizer to System.Object like I've been able to with other objects in the system. I've searched at length but haven't found any examples/discussion about creating a visualizer for all objects. Here is the code I'm trying to get working, it works well enough when bound to String or Int32, but not Object or object.
[assembly: System.Diagnostics.DebuggerVisualizer(
typeof(Visualizers.ObjectVisualizer), typeof(Visualizers.RawObjectScource),
Target = typeof(object), Description = "Object Visualizer")]
namespace Visualizers
{
public class ObjectVisualizer : DialogDebuggerVisualizer
{
    override protected void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
    {
        Console.Out.WriteLine("InShow");
        MessageBox.Show(objectProvider.GetObject().ToString());
    }
}

// handle any object, doesn't require that it's Serializable
public class RawObjectScource : VisualizerObjectSource
{
    public override void GetData(object target, Stream outgoingData)
    {
        if (target != null)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(outgoingData, target.ToString());
        }
    }
}
}

Being a former Java programmer that used IntelliJ I'm used to being able to see in debug mode what the heap address is that a specific reference is pointing to. This allows you to see at a glance if two objects are reference equal.  Also, there are a few other things that would be valuable to know, but they can be a bit lengthy to explain.  If I can get it working I'll post the final code.
So does anyone know how to get a visualizer to be active for all objects?

A: I dont know what is wrong whit your code.
however @Bismark, the target does not have tobe serialize able as you can use your own VisualizerObjectSource to sesialize it
I do suggest you serailise the .GetType().AsseblyQualifierName along whit it, this will allow you to what kind of object the stream contains, so at deserialisation you know that you object is acutaly an instance of class x, I used this technique one of my own visualizers as sometimes you might be serialising an sub-type of of the class whilke at the deserialisation you have no idea what time you are working with.


text:
Q: One who hates his own image Let us pretend the 'one who hates his own image' is a 'selfie-loather'.
If so, a sentence incorporating the term could be

He always said he hated mirrors and I had assumed he was a
  'selfie-loather' so I was shocked when I saw him apparently
  admiring his face in the glass!

A:
This body-image death spiral ends at universal self-hatred
"Up to one in five cosmetic surgery patients could suffer from body dysmorphic disorder" – again, the definition is sloppy. Body dysmorphic disorder is the irrational hatred of your body. You could easily argue that everybody having cosmetic surgery for reasons other than physical comfort has body dysmorphic disorder, just because it's irrational to hate yourself so much that you'd ask anyone to slice into you. Or you could argue that hating yourself that much is a maladaptive but understandable response to the pressures of your cultural environment.

Source: The Guardian

Body Dysmorphic Disorder (BDD)
But people who have body dysmorphic disorder (BDD) think about their real or perceived flaws for hours each day.
They can't control their negative thoughts and don't believe people who tell them that they look fine. Their thoughts may cause severe emotional distress and interfere with their daily functioning. They may miss work or school, avoid social situations and isolate themselves, even from family and friends, because they fear others will notice their flaws.
They may even undergo unnecessary plastic surgeries to correct perceived imperfections, never finding satisfaction with the results.

Source: ADAA (Anxiety and Depression Association of America)

A: Eisoptrophobia is the psychological condition of loathing to see one's own image, to see oneself in the mirror.  Incidentally, this is distinct from  spectrophobia, which is the fear of mirrors.

A: No need to get clinical about this answer. We have a perfectly good agent noun, 'self-hater', formed from 'self-hatred' (= 'self-hate'):

self-hatred n.
  Hatred of oneself, esp. of one's actual self when contrasted with one's imagined self.

["self-ˈhatred, n.". OED Online. December 2015. Oxford University Press. http://www.oed.com/view/Entry/175271 (accessed January 08, 2016).]
As the "esp." highlights, the hatred may be of an actual self contrasted with an imagined self. So, 'self-hater' works well in the OP's example:

He always said he hated mirrors and I had assumed he was a self-hater, so I was shocked when I saw him apparently admiring his face in the glass!

It should be stipulated, however, that what the subject of the example saw in the "glass" might've been something considerably stronger and more admirable than himself.


text:
Q: How can I rebase 3 commits with one merge of master into one commit? I always seem to stumble and completely mess up git commits when I run into this scenario. I'm hoping to avoid it this time around. Here is my scenario. I have the following 4 commits in my PR:
Commit 1: Remove unused routes for the projects controller
Commit 2: Add PR request changes and modify similar_by_tags_route
Commit 3: Merge Master and resolve git merge conflicts
Commit 4: Reinsert rubocop disablement for project.rb

I need these commits rebased into one commit.  Now I can't just do a rebase -i HEAD~4 because of the pesky merge from master. Is there a way where I can simply remove commit 3 and just merge commits 1, 2, and 4? I would really like some help on this because I always seem to make a HUGE mess when it comes to tricky merges like this.

A: You can try doing an interactive rebase of your branch and just remove the line containing the merge commit.  Running git rebase -i HEAD~4 should bring up a list of commits looking something like the following:
pick Commit 1: Remove unused routes for the projects controller
pick Commit 2: Add PR request changes and modify similar_by_tags_route
pick Commit 3: Merge Master and resolve git merge conflicts
pick Commit 4: Reinsert rubocop disablement for project.rb

Delete the line containing the merge commit, leaving you with this:
pick Commit 1: Remove unused routes for the projects controller
pick Commit 2: Add PR request changes and modify similar_by_tags_route
pick Commit 4: Reinsert rubocop disablement for project.rb

Now change the 2nd and 4th commit to squash, to tell Git to combine these commits into the single first commit:
pick Commit 1: Remove unused routes for the projects controller
squash Commit 2: Add PR request changes and modify similar_by_tags_route
squash Commit 4: Reinsert rubocop disablement for project.rb

Complete the rebase and you should be left with what you want.  Note that rebasing like this means rewriting the history of your branch.  As such, you should take precaution if this branch is publicly shared by other people.

A: If you haven't pushed to remote yet simply rebase: git rebase -i HEAD~4 then pick first commit, drop the third one and squash the others.
Here is some example I did in my console:

Note the commands that are available also, maybe you can choose something more appropriate now than you see all of them.
However, if you pushed to remote I'd suggest you just revert third commit and leave the others because rebase rewrites history and can be devastating for people that already pulled your commits so I'd rather not play with history of git.

A: Assume your 4 commits are on Branch B1 and that's the name of the branch that was used to create the PR.

*

*Create a local branch B2 (identical to B1)

*Delete local branch B1

*Create local branch B1 from origin/master

*Cherry-pick commits 1, 2, 4 (in order) onto branch B1 by looking at their hashes in B2.

*Squash them (interactive rebase)

*Force push B1 to origin

*Delete local branch B2

A: Squash several Git commits into a single commit
This note shows how to merge an ugly feature branch with multiple dirty WIP commits back into the master as one pretty commit.
Easy mode: Reset your feature branch to the master state
The easiest way to turn multiple commits in a feature branch into a single commit is to reset the feature branch changes in the master and commit everything again.
# Switch to the master branch and make sure you are up to date.

git checkout master

git fetch # this may be necessary (depending on your git config) to receive updates on origin/master

git pull

# Merge the feature branch into the master branch.

git merge feature_branch
# Reset the master branch to origin's state.

git reset origin/master

Git now considers all changes as unstaged changes.
# We can add these changes as one commit.

# Adding . will also add untracked files.

git add --all

git commit

Note that this is not touching the feature branch at all. If you would merge the feature branch into the master again at a later stage all of its commits would reappear in the log.
You may also do it the other way round (merging master into the branch and resetting to the master state) but this will destroy your commits in the feature branch, meaning you can not push it to origin.
Hard mode: Squash commits
This method is harder than using the get reset method above. Also it doesn't work well if you merged the master into the feature branch previously (you'll need to resolve all conflicts again).
What we are describing here will destroy commit history and can go wrong. For this reason, do the squashing on a separate branch:
git checkout -b squashed_feature

This way, if you screw up, you can go back to your original branch, make another branch for squashing and try again.
To squash all commits since you branched away from master, do
git rebase -i master

Note that rebasing to the master does not work if you merged the master into your feature branch while you were working on the new feature. If you did this you will need to find the original branch point and call git rebase with a SHA1 revision.
Your editor will open with a file like
pick fda59df commit 1

pick x536897 commit 2

pick c01a668 commit 3

Each line represents a commit (in chronological order, the latest commit will be at the bottom).
To transform all these commits into a single one, change the file to this:
pick fda59df commit 1

squash x536897 commit 2

squash c01a668 commit 3

This means, you take the first commit, and squash the following onto it. If you remove a line, the corresponding commit is actually really lost. Don't bother changing the commit messages because they are ignored. After saving the squash settings, your editor will open once more to ask for a commit message for the squashed commit.
You can now merge your feature as a single commit into the master:
git checkout master

git merge squashed_feature


text:
Q: Why function BCryptImportKey generate exeption? class Decrypt : Filefunc
{
public:
    Decrypt(std::string password)
    {
        fill_paths(paths);
        log.open("W:\\log.txt", std::ios::in | std::ios::out | std::ios::trunc);
        szPass = new TCHAR[passphrase.size() + 1];
        copy(passphrase.begin(), passphrase.end(), szPass);
        szPass[passphrase.size()] = 0;
        std::ifstream iFkey("W:\\key.key", std::ios_base::in | std::ios_base::binary);

        status = BCryptOpenAlgorithmProvider
        (
            &hAlg,
            BCRYPT_SHA256_ALGORITHM,
            NULL,
            NULL
        );
        log << test_status("BCryptOpenAlgorithmProvider", status);

        status = BCryptGetProperty
        (
            hAlg,
            BCRYPT_OBJECT_LENGTH,
            (PBYTE)&cbHashObject,
            sizeof(DWORD),
            &cbData,
            NULL
        );

        log << test_status("BCryptGetProperty", status);

        pbHashObject = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHashObject);
        status = BCryptCreateHash
        (
            hAlg,
            &hHash,
            pbHashObject,
            cbHashObject,
            NULL,
            NULL,
            NULL
        );
        log << test_status("BCryptCreateHash", status);

        status = BCryptHashData
        (
            hHash,
            (PBYTE)szPass,
            _tcslen(szPass) * sizeof(TCHAR),
            NULL
            );
        log << test_status("BCryptHashData", status);

        status = BCryptGetProperty
        (
            hAlg,
            BCRYPT_HASH_LENGTH,
            (PBYTE)&cbHash,
            sizeof(DWORD),
            &cbData,
            NULL
        );
        log << test_status("BCryptGetProperty", status);

        pbHash = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHash);

        status = BCryptFinishHash
        (
            hHash,
            pbHash,
            cbHash,
            0
        );
        log << test_status("BCryptFinishHash", status);

        status = BCryptOpenAlgorithmProvider
        (
            &hAlg,
            BCRYPT_AES_ALGORITHM,
            NULL,
            NULL
        );
        log << test_status("BCryptOpenAlgorithmProvider", status);

        status = BCryptGetProperty
        (
            hAlg,
            BCRYPT_OBJECT_LENGTH,
            (PBYTE)&cbKeyObject,
            sizeof(DWORD),
            &cbData,
            NULL
        );

        log << test_status("BCryptGetProperty", status);

        pbKeyObject = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbKeyObject);

        status = BCryptGenerateSymmetricKey
        (
            hAlg,
            &hKey,
            pbKeyObject,
            cbKeyObject,
            (PBYTE)pbHash,
            cbHash,
            NULL
        );
        log << test_status("BCryptGenerateSymmetricKey", status);

        iFkey.seekg(0, iFkey.end);
        length = iFkey.tellg();
        iFkey.seekg(0, iFkey.beg);
        impKeyBuf = new UCHAR[length];

        iFkey.read((char*)impKeyBuf, length);

         BCryptImportKey
        (
            hAlg,
            hKey,
            BCRYPT_AES_WRAP_KEY_BLOB,
            &hKeyImp,
            NULL,
            NULL,
            impKeyBuf,
            length,
            NULL
        );

        log << test_status("BCryptImportKey", status);
    }
}

I am creating a program that encrypts all files on a USB flash drive. At the stage of importing the key, I get an exception that I can't analyze in any way. Exception text in the memcpy.asm file:

An exception was raised at 0x7C103B3F (vcruntime140d.dll ) in Zed_TEst.exe : 0xC0000005: violation of access rights when reading at 0x01010101.

The test_status function simply returns a string in which the status of functions from bcrypt is written
when I try to display the status in the console I get something strange

output: ╢
¶    ╖
"     э$♦"♦`☼}☺╕
     ♣  ♣╣
    ║
§     ь$☺§☺⌂♦╗
a     ↕А♦a♦╝
<     ь$♣<♣╜
▼     ь$♣▼♣1!.┐
w     ☺w☺♦а     →ЁЖ☻└
¶     ☼¶☼☺┴
♦    ┬
   ├
♥     ь$♣♥♣─
☺     ь$♣☺♣┼
   ╞
     ь$♣♣╟


text:
Q: mysql php select a record that's similar to another I know this may seem like a duplicated, out of stackoverflow, etc question but here we go.
I'm trying to make an SQL sentence that can find a coincidence between two strings
        function getProductos($keyWords){
            $keyWords = addslashes(strtolower($keyWords));
            $keyWordsExploded = explode(" ",$keyWords);
            $sql = "SELECT * FROM PRODUCTOS WHERE HOMBRE_MUJER LIKE :keyWords OR CATEGORIA LIKE :keyWords" OR NOMBRE LIKE :keyWords;

            $query = self::$conn->prepare($sql);
            $query->execute(array(":keyWords"=> "%" . $keyWords . "%"));

        return $query;
        }

In other part of the page I have this code:
            <?php
            if(isset($_GET['buscar'])){
                require(PAGES_DIR . "queries_products.php");
                $consultaProducts = new QueryProductos();
                $productos = $consultaProducts->getProductos($_GET['buscar']);

                if($productos->rowCount()!=0){
                    $arrayProductos = $productos->fetchAll(PDO::FETCH_ASSOC);
                    echo "
Productos encontrados
";
                    foreach($arrayProductos as $fila){
                        echo $fila['NOMBRE'] . " " . $fila['HOMBRE_MUJER'] . "
";
                    }
                }else{
                    echo "
No results found " . $_GET['buscar'] . "";
                }
            }
        ?>

Everything works fine, In my database I store only 2 values in CATEGORIA which are: "hombres" and "mujeres", if i search for hombres I get all records which have a CATEGORIA of hombres but when i search for hombres y mujeres I get no results, I have tried using different sentences that i read but I haven't had any luck, I hope you can greatly save me by helping me solve this problem.

A: try this:
function getProductos($keyWords) {

     $keyWordsExploded = explode(" ",$keyWords);
      $sql = "SELECT * FROM PRODUCTOS WHERE ";
      $likes = array("HOMBRE_MUJER", "CATEGORIA", "NOMBRE"); // build up our columns which will be used in our condition in sql statment

      $params = array();
      // building up our sql statment and collecting our params
      foreach($likes as $like) {
        foreach($keyWordsExploded as $kw) {
          $sql .="$like like ? or ";
          $params[] = "%".$kw."%";
        }
      }

     $sql = rtrim($sql, "or "); // trim the last "or" condition in sql statment

     $query = self::$conn->prepare($sql);

     $query->execute($params);

     return $query;
}


text:
Q: Building git from sources, missing getopt library on debian jessie I'm following these instruction to build git from source:
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
I get the error "Unable to find packge getopt", also after an apt update.
Cannot find a package containing the library on debian packages archive.
Any idea on how to solve it?
I'm running it into a docker container:
from debian:latest

RUN apt-get update

# git installation

RUN apt-get install \
  dh-autoreconf \
  libcurl4-gnutls-dev \
  libexpat1-dev \
  gettext  \
  libz-dev \
  libssl-dev \
  asciidoc \
  xmlto \
  docbook2x \
  getopt

RUN wget https://github.com/git/git/archive/v2.13.0.tar.gz -P /tmp/src/git \
  tar -zxf /tmp/src/git/v2.13.0.tar.gz -C /tmp/bin/git \
  cd /tmp/bin/git \
  make configure \
  ./configure --prefix=/usr \
  make all doc info \
  make install install-doc install-html install-info

A: I had to use gnulib since there is not a getopt package.


text:
Q: TypeScript dynamic type access weird behavior I have factory which using function based on passed params,I decide to use object instead of switch for functions access.
Where key is one of passed param, value is function to call:
/* ------------ concept demo -------------- */

const creators = {
  'type1': function1,
  'type2': function2,
}

class Factory {
  create({ type, params }) {
    // getting creator by type as key
    creators[type](params);
  }
}

The problem is : In moment of reading function, TS set correct
possible params types, like: 'type1' | 'type2'.
But in moment of function call it changes params types to 'type1' & 'type2'.
So I'm getting types conflict:

Type 'BoxParams' is not assignable to type 'BoxParams & CircleParams'.

Type 'BoxParams' is missing the following properties from type 'CircleParams': cx, radius"

My code:
/* ------------ file 1 -------------- */

type BoxParams = {
  x: number,
  size: number
}

const createBox = ({ x, size}: BoxParams) => {
  // ... box creation
};

type CircleParams = {
  cx: number,
  radius: number
}

const createCircle = ({ cx, radius}: CircleParams) => {
  // ... box creation
};

/* ------------ file 2 -------------- */

type CreateBoxParams = {
  elementType: "Box";
  params: BoxParams;
};

type CreateCircleParams = {
  elementType: "Circle";
  params: CircleParams;
};

type BaseParams = {
  type: string;
  //...
};

type CreateParams = BaseParams & (CreateBoxParams | CreateCircleParams);

const elementsCreators = {
  Box: createBox,
  Circle: createCircle,
};

export default class CollisionElementFactory {
  static create({ type, elementType, params }: CreateParams) {
    // 'creator' type is correct: 'type1' | 'type2' (for each func in elementsCreators obj)
    const creator = elementsCreators[elementType];
    // 'creator' params type is wrong, become: (__0: BoxParams & CircleParams) => void
    const element = creator(params);
    // ...
  }
}


text:
Q: How do I delete a Windows partition? I tried to install Windows 10 with Boot Camp and I got an error. When I tried to reboot my MacBook and held Alt, I have two partitions: MacintoshHD and Windows. If I click on Windows I have a blue Windows screen with "Recovery". So how I can delete this partition?

A: *

*Close all open applications;

*Open Boot Camp Assistant (click Continue);

*Select Remove Windows 10 or later version;

*Click Restore if your Mac has one internal disk, otherwise select the Windows disk and select Restore disk to a single macOS partition, and then press Continue.

It is recommanded to do a backup before doing so.

A: Start all over again . This may help you to delete the partition.


text:
Q: install nvidia-driver418 and cuda9.2.-->CUDA driver version is insufficient for CUDA runtime version everyone,
My machine is ubuntu16.04
I got 2 Tesla P100 ,
Firstly,I install nvidia-driver 418, the result is good.
Then Then I install cuda9.2(The reason why I didn't choose cuda10.0 is that I want to use pytorch0.4 but it doesn't support cuda10.0).
I got this:
nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2018 NVIDIA Corporation
Built on Tue_Jun_12_23:07:04_CDT_2018
Cuda compilation tools, release 9.2, V9.2.148

nvidia-smi
But when I check ,
cd /usr/local/cuda-9.2/samples/1_Utilities/deviceQuery
sudo make
./deviceQuery

it gave me ->CUDA driver version is insufficient for CUDA runtime version.

I installed nvidia-driver by
sudo apt-get install nvidia-418

And I installed cuda by download the cuda_9.2.148_396.37_linux and use sudo sh cuda_9.2.148_396.37_linux,(without installing the driver and I have set the relevant PATH).
Can anyone help me ?
(After I installed the driver418, I installed the cuda9.0 firstly,but it didn't work because the same reason.Then I uninstalled it and tried the cuda9.2,)
Beg your help!

A: Many months late, but in order to help people out. For CUDA to work, you have to keep your eGPU plugged in while running CUDA. If it still doesn't work, check that your driver(NVIDIA drivers, not CUDA) are up to date/highest for your OS. If it doesn't work, it means that your GPU is not supported in your current OS. For example, in macOS you can only use up to the Geforce GTX 10 series.


text:
Q: How to read and write to NSTask I have it working. However, initially it appears to be waiting for input. How can I read what was output before it stops and is waiting for input?
task starts
stdout should post data for "sftp> " but nothing happens, its waiting for input
If I write "\n" to stdin
stdout notifies me of data available which ends up being "sftp> \n"

Here is how it's implemented:
[self.task = [[NSTask alloc] init];
[self.task setLaunchPath:executablePath];
[self.task setArguments: args];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(terminatedNotification:) name:NSTaskDidTerminateNotification object:self.task];

//reading
self.stdoutPipe = [NSPipe pipe];
self.task.standardOutput = self.stdoutPipe;
[self.stdoutPipe.fileHandleForReading waitForDataInBackgroundAndNotify];

//error
self.stderrorPipe = [NSPipe pipe];
self.task.standardError = self.stderrorPipe;
[self.stderrorPipe.fileHandleForReading waitForDataInBackgroundAndNotify];

/*
reading works perfect until I uncomment this section
//writing
self.stdinPipe = [NSPipe pipe];
self.task.standardInput = self.stdinPipe;
*/

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataAvailable:) name:NSFileHandleDataAvailableNotification object:self.stdoutPipe.fileHandleForReading];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataAvailable:) name:NSFileHandleDataAvailableNotification object:self.stderrorPipe.fileHandleForReading];

A: Data written to a NSFileHandle is buffered. Only after the buffer has been flushed it will be available for reading on the other end of the pipe. The buffer is flushed if

*

*it is full and no more data would fit into it.

*a newline character ("\n") is written to it (autoflush).

*you flush it explicitly by calling - (void)synchronizeFile


text:
Q: Play Framework for Scala - RESTful Web Service I looked through Play framework and I am struggling to find a good documentation/tutorial
for how to do a RESTful web service in Play ver. 2+.
Please recommend any reference if you have. Googling on keywords containing "Play" and "Rest" does not give me much :-)

A: You should check play-mini :
https://github.com/typesafehub/play2-mini

A: I'm building a backbone skeleton application, and for the backend webservice I used play 2.0 with scala.
It implements a nice json rest web service with cors, using an in-memory database
Have a look at it at:
https://github.com/opensas/BackboneBootstrap/tree/master/webservice
It support a couple of nice features, like filtering, paging, ordering and advanced queries...


text:
Q: Is it possible for Webpack to report the file name causing an error at runtime? Is it possible for Webpack to report the file name causing an error at runtime
In other words, it will report the an error thrown is coming from common.js bundle, which makes it hard to find the source. Is it possible to run webpack and have it NOT bundle anything just for testing or maybe have it report the original file name?
regards
Sean

A: If you are referring to source maps then this may help.
stackoverflow question
webpack devtool
If you are running webpack from the command line you can run it in 'development mode' mode by including the -d flag like so > webpack -d


text:
Q: Problem importing pandas_datareader in Python I want to get historic and current data stock prices from yahoo finance and/or google finance with python. To do so, I installed pandas and pandas_datareader on my machine. When I import pandas everything goes fine, but when I import pandas_datareader I get an error. More specifically, the following script
import pandas
import pandas_datareader

generates the following error
  File "a.py", line 5, in <module>
    import pandas_datareader
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas_datareader/__init__.py", line 2, in <module>
    from .data import (DataReader, Options, get_components_yahoo,
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas_datareader/data.py", line 14, in <module>
    from pandas_datareader.fred import FredReader
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas_datareader/fred.py", line 1, in <module>
    from pandas.core.common import is_list_like
ImportError: cannot import name 'is_list_like'

I tried to reinstall pandas_datareader, but It still doesn't work. Any idea what the problem might be? I use python3 on macBook Pro (beginning 2015) with macOS High Sierra Version 10.13.5.

A: Try this:
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader

and let me know if it worked :)


text:
Q: Spring cloud stream Special Chars in Message received from kinesis When I consume the message from kinesis stream. I get some junk chars with headers etc
    @StreamListener(Processor.INPUT)
    public void receive(String message) {
        System.out.println("Message recieved: "+message);
        throw new RuntimeException("Exception thrown");
    }

    @StreamListener("errorChannel")
    public void transform(ErrorMessage errorMessage) throws UnsupportedEncodingException {

        //original paylaod
        System.out.println("Error Oiginal Message Payload"+new String((byte[])errorMessage.getOriginalMessage().getPayload(), "UTF-8"));
        System.out.println("Error Original Message Stream channel"+errorMessage.getOriginalMessage().getHeaders().get("aws_receivedStream"));
    }

Aplication yml
spring:
  cloud:
    stream:
      bindings:
        input:
          group: abcd
          destination: stream
          content-type: application/json
          errorChannelEnabled: true
          consumer:
            headerMode: raw

I get output at the both the listener and errorChannel with junk characters
I am trying to extract the original message in errorChannel . Is this the right way to convert the bytes message?
Message recieved: ?contentType "application/json"{"aa":"cc"}

A: The AWS Kinesis doesn't provide any headers entity. So, to leverage such a functionality in Spring Cloud Stream, we are embedding headers into the body of the Kinesis record. For this purpose the headerMode is embeddedHeaders by default in the Kinesis Binder. And for symmetry between producer and consumer this option must not be changed.
The Framework provides out-of-the-box EmbeddedHeadersChannelInterceptor for the target @StreamListener channels and embedded headers are extracted and populated properly to the message to send.
When we handle errors in the errorChannel, we indeed have an errorMessage.getOriginalMessage() as non-transformed - original. And therefore the payload of that message is a byte[] from the record body containing embedded headers.
If you would like to parse them properly. you should use utility:
EmbeddedHeaderUtils.extractHeaders((Message<byte[]>) message, true);


text:
Q: Backbone svg cube events getting disabled on flip Just a bit of trivia: I have started using backbone just a month back and svg about a week back. Basically am still learning.
I mainly have a cube. On load the front face has a circle divided into sectors. Each sector is clickable. On clicking each sector the cube flips 90 degrees right and that particular sector is zoomed and displayed there.
Now there is a slider on the zoomed sector ranging from 0-10. This I have created again using svg circles on a line equidistantly. The problem is that the circles must be clickable so that the value on which it is clicked should be captured.
But once the cube flips none of the events are firing. I have been struggling with this for 3 days now but no luck. Any help from anybody please.
I understand that the delegateEvents() method needs to be called somewhere, but where am not able to make out. Or is it the css transforms that are disabling the events, I don't understand???
Below is my code:
The js file
var CircleView = Backbone.View.extend({
    model: this.model,
    xmlns: "http://www.w3.org/2000/svg",

    events: {
        'click path': 'handleClick',
    },

    handleClick: function(ev) {
        var id = $(ev.currentTarget).attr('id');

        var el = this.$el;
        model = this.model;

        var xAngle = 0, yAngle = -90;

        // Cube flips here

        (document.getElementById('cube')).style.webkitTransform = "rotateX(" + xAngle + "deg) rotateY(" + yAngle + "deg)";

        // view to display the zoomed sector

        var secView = new SectorView({el: $('#circleEdit2'), model: model, value: value, id: id});
        secView.render();
    },

    render: function(model) {
        // Code to draw svg circle with 12 clickable sectors goes here
        // On clicking any sector cube flips and zoomed sector is displayed there
        // This is working perfectly

        el.html($("#face1").html());

        return el;
    }
})

var SectorView = Backbone.View.extend({
    model: this.model,
    id: 0,
    value: 0,

    xmlns: "http://www.w3.org/2000/svg",

    events: {
        'click circle': 'handleDots'
    },

    handleDots: function(ev) {
        var id = $(ev.currentTarget).attr('id');
        var numID = parseInt(id);

        alert("Click Event Called");
    },

    render: function() {
        var id = this.id;
        var el = this.$el;
        model = this.model;

        // Code to draw zoomed Sector ranging from 0-10 goes here
        // method to draw slider using svg circles on a line equidistantly
        // On clicking each circle value should be captured
        // Here click event is not firing but all graphics are displayed correctly

        this.drawSlider(el, id, winWidth/2, oRadius, value, (winWidth/3 - oRadius/4.7));

        $("#face2").html(this.$el);

        $("#radios").css("top", winWidth/3.5);
        $("#radios").css("left", left);

        this.delegateEvents();
    }
})

The HTML:

    <link rel="stylesheet" href="circleEditTool.css">

            <svg id="circleEdit1"> </svg>

            <svg id="circleEdit2"> </svg>

                <input name='typeOfArea' type='radio' value="Strength" checked>Strength</input>
                <input name='typeOfArea' type='radio' value="OK">OK</input>
                <input name='typeOfArea' type='radio' value="Weakness">Weakness</input>

The css:
#experiment {
  -webkit-perspective: 1200px;
  -webkit-perspective-origin: 50% 300px;
}

#cube {
    position: center;
    margin: auto;
    height: 600px;
    width: 600px;
    -webkit-transition: -webkit-transform 2s linear;
    -webkit-transform-style: preserve-3d;
    border: 1px solid #ccc;
    background: rgba(255, 255, 255, 1);
}

.face {
    position: absolute;
    height: 600px;
    width: 600px;
    background-color: rgba(200, 200, 200, 0.7);
    -webkit-backface-visibility: hidden;
    background-color: #F2F2F2;
}
#cube .one {
    -webkit-transform: translateZ(200px);
    opacity: 1;
    box-shadow: inset 0 0 50px rgba(0, 0, 0, 0.5);
}
#cube .two {
    -webkit-transform: rotateY(90deg) translateZ(350px);
    opacity: 1;
    box-shadow: inset 0 0 50px rgba(0, 0, 0, 0.5);
}


text:
Q: Get upload progress with AWS S3 signed url I'm making an application that let user to upload their video to our end using AWS S3. I use a server to generate signed url and return it to client(web browser), then client uses that url to upload to our backend. It works pretty well, but I have a small problem that we can't keep track the progress of file upload which started from browser.
So are there any ways we can get progress of the uploads from our server?

A: Java Snippet for the Same
public void uploadtoS3(File file) throws AmazonServiceException, AmazonClientException, InterruptedException {
        logger.debug("Uploading the File => S3");
        ProfileCredentialsProvider credentialProviderChain = new ProfileCredentialsProvider();
        TransferManager tx = new TransferManager(credentialProviderChain.getCredentials());
        final Upload upload = tx.upload(env.getProperty("amazon.s3.media.bucket"), file.getName(), file);

        // You can poll your transfer's status to check its progress
        if (upload.isDone() == false) {
            logger.debug("Transfer: " + upload.getDescription());
            logger.debug("State: " + upload.getState());
            logger.debug("Progress: " + upload.getProgress().getBytesTransferred());
        }

        // Transfers also allow you to set a ProgressListener to
        // receive
        // asynchronous notifications about your transfer's progress.

        upload.addProgressListener(new ProgressListener() {
            // This method is called periodically as your transfer progresses
            public void progressChanged(ProgressEvent progressEvent) {
                logger.debug(upload.getProgress().getPercentTransferred() + "%");

                if (progressEvent.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE) {
                    logger.debug("Upload complete!!!");
                }
            }
        });

        // Or you can block the current thread and wait for your transfer to
        // to complete. If the transfer fails, this method will throw an
        // AmazonClientException or AmazonServiceException detailing the reason.
        upload.waitForCompletion();

        // After the upload is complete, call shutdownNow to release the
        // resources.
        tx.shutdownNow();
    }

Also works with the MultiPart uploads.


text:
Q: Using compiler directive to warn if a file is missing I have a file that is included on the bundle that has the following name:
databaseX.sqlite

where X is the app's version. If the version is 2.8, the file should be named database2.8.sqlite. I have to be sure to include this file when the app is submitted to Apple.
Is it possible to create a compiler directive to check if the file is in the bundle?
I have tried this, without success
#define fileInBundle [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"LoteriaMac%@.sqlite", [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"]]]

#if defined(fileInBundle)
#pragma message("file in bundle")
#else
#pragma message("file missing")
#endif

file in bundle is always shown even if the file is not in bundle.

A: This is not possible. You are trying to use a runtime check inside a compilation directive.
In general, when compiling you cannot know whether there is a file in a bundle or not because the files are usually added to the bundle independently on code, after compiling.
This is the same as checking whether there is a file present in the filesystem on another computer when compiling.
To check that during build time, you can create a custom build script (Build Phases => + button) in your target, something similar to:
APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}"

// there is probably some easier way to get the version than from the Info.plist
INFO_FILE="${APP_PATH}/Info.plist"
VERSION=`/usr/libexec/plistbuddy -c Print:CFBundleShortVersionString "${INFO_FILE}"`

// the file we want to exist
DB_FILE="${APP_PATH}/database${VERSION}.sqlite"

// if the file does not exist
if [ ! -f "${DB_FILE}" ]; then
   // emit an error
   echo "error: File \"${DB_FILE}\" not found!" >&2;
   // and stop the build
   exit 1
fi


text:
Q: How to create a SpatRaster from dataframe To create a SpatRaster from dataframe with large dataframe / Raster objects some tools like rasterize(), sp::gridded() seems very slow, any suggestions?

A: You can do
library(terra)
f <- system.file("ex/elev.tif", package="terra")
r1 <- rast(f)
r.df <- terra::as.data.frame(r1, na.rm = FALSE)

r2 <- setValues(r1, as.matrix(r.df))

Or depending on context first create the SpatRaster and then use values<- or setValues
r.df <- terra::as.data.frame(r1, xy=TRUE, na.rm = FALSE)
r3 <- rast(r1, nlyr=ncol(r.df))
values(r3) <- as.matrix(r.df)
names(r3) <- colnames(r.df)

r3
#class       : SpatRaster
#dimensions  : 90, 95, 3  (nrow, ncol, nlyr)
#resolution  : 0.008333333, 0.008333333  (x, y)
#extent      : 5.741667, 6.533333, 49.44167, 50.19167  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84 (EPSG:4326)
#source      : memory
#names       :        x,        y, elevation
#min values  : 5.745833, 49.44583,       141
#max values  : 6.529167, 50.18750,       547

A: Generate the dataframe from a SpatRaster
### Load a raster file
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
plot(r)
class(r)

### Convert the SpatRaster to a dateframe
r.df <- terra::as.data.frame(r, xy = TRUE, na.rm = FALSE)
class(r.df)
head(r.df)

To convert back from dataframe to SpatRaster, start with empty raster
### create empty raster
crs_ref <- "EPSG:4326"
empty_r <- rast(res=0.008333333, nlyr= 1, # number of layers according the number of cols of dataframe
                extent= ext(r), # can be other object extent like a shapefile, etc
                crs= crs_ref)

### fill the empty raster with cell values
rast_ <- init(empty_r, fun= r.df[, 3])

### adjust the name
names(rast_) <- names(r.df[3])

### plot
plot(rast_)


text:
Q: Gnu/Linux (Bash) Bulk Command for Multiple Files I am looking for a solution to run a command for multiple files at one.
Example for 1 file only:
dot -Tpng dummy.dot.modulename -o dummy.dot.modulename.png

Now example for all ".dot" (PSEUDO COMMAND)
dot -Tpng $(find . -name "*.dot*") -o $(find . -name "*.dot*").png

A: Loop over the *.dot file globbing pattern
#!/usr/bin/env bash

for dotfile in *.dot
do
  # Create the png file name by removing the trailing .dot
  # and replacing it with .png
  pngfile="${dotfile%.dot}.png"
  dot -Tpng "$dotfile" -o "$pngfile"
done

Rather than loop over a filename globbing expansion. You can have find execute a command/script like this:
find . -name '*.dot' \
  -execdir sh 'for f; do dot -Tpng "$f" -o "${f%.dot}.png" ;done' {} \;


text:
Q: Какое ещё бывает управление в гексагональных играх? Клик по гексагону знаю. А какое ещё бывает управление в играх с гексагональной сеткой? На квадратной сетке можно ещё кнопками управления кареткой, wsad, цифровым блоком. Но эти раскладки управления не лезут в гексагональную сетку.

A: Гексагональная сетка бывает 2-х видов:

Если взять цифровой блок клавиатуры, и принять цифру "5" как центральную точку отсчёта направления, то для первого типа можно использовать цифры: 9, 6, 3, 1, 4, 7; а для второго: 8, 9, 3, 2, 1, 7 (обозначения для кругового движения, начиная с правой верхней или верхней грани).
Блок WASD так же можно расширить до матрицы 3x3 из клавиш:
Q, W, E;
A, [S], D;
Z, X, C.
Или при желании, оставить только 4 клавиши (WASD и стрелки), но такой вариант требует, чтобы две клавиши были переключателями направления (например клавиша W или стрелка вверх для гексагональная сетки на первой картинке это селектор между направлениями левого верхнего и правого верхнего), но такой вариант вряд ли подойдет для Real-time игры, он больше присущ пошаговым стратегиям...
P. S. Уверен, что это далеко не все варианты, да и можно ли считать, что они вообще чем-то ограничены?


text:
Q: Flexiquery not working with employee group For my user I have added admingroup and employeegroup and I am trying to run any flexiquery which gives me below exception.
INFO   | jvm 1    | main    | 2020/06/02 01:54:13.839 | WARN  [hybrisHTTP5] [10.243.247.193] [DefaultHandlerExceptionResolver] Resolved exception caused by handler execution: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: while trying to invoke the method de.hybris.platform.catalog.model.CatalogVersionModel.getPk() of a null object loaded from local variable 'ctgVer'; nested exception is com.fasterxml.jackson.databind.JsonMappingException: while trying to invoke the method de.hybris.platform.catalog.model.CatalogVersionModel.getPk() of a null object loaded from local variable 'ctgVer' (through reference chain: de.hybris.platform.hac.data.dto.SqlSearchResultData["catalogVersionsAsString"])
INFO   | jvm 1    | main    | 2020/06/02 01:54:13.839 | WARN  [hybrisHTTP5] [10.243.247.193] [DefaultHandlerExceptionResolver] Resolved exception caused by handler execution: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: while trying to invoke the method de.hybris.platform.catalog.model.CatalogVersionModel.getPk() of a null object loaded from local variable 'ctgVer'; nested exception is com.fasterxml.jackson.databind.JsonMappingException: while trying to invoke the method de.hybris.platform.catalog.model.CatalogVersionModel.getPk() of a null object loaded from local variable 'ctgVer' (through reference chain: de.hybris.platform.hac.data.dto.SqlSearchResultData["catalogVersionsAsString"])
If I remove the employeegroup from my user then it is working fine. Could someone help me to understand what is the issue here.
Kind regards,
CHOLA


text:
Q: Slider Not Sliding More Than One Iteration Each Way (JavaScript) I have a slider that has 4 articles on it. I can get it to slide each way by 1 article, but can't seem to get it to repeat the action on the second time of clicking the 'left' button. I'm not sure if it's the counter that is the problem or the transform value? I do need to use transform instead of left or right because I need it execute at 60fps on the animation.
Codepen: https://codepen.io/emilychews/pen/vYXJyqZ

var leftButton = document.getElementById("left-button"),
  rightButton = document.getElementById("right-button"),
  article = document.querySelectorAll(".article"),
  counter = 0,
  articleWidth = article.offsetWidth;

if (counter <=1) {
  leftButton.addEventListener("click", function () {
    article.forEach(function (item) {
      item.style.transform = "translateX(-100%)";
      item.style.transition = "all 2s";

      counter += 1;
    });
  });
}

if (counter < article.length) {
  rightButton.addEventListener("click", function () {
    article.forEach(function (item) {
      item.style.transform = "translateX(0)";
      item.style.transition = "transform 2s";

      counter -= 1;
    });
  });
}
* {
  margin: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.row {
  width: 50%;
  background: red;
  overflow: hidden;
  margin-bottom: 2rem;
}

.article-wrapper {
  display: flex;
  width: 160%;
}

.article {
  width: 70%;
  background: blue;
  margin: 0 1rem;
  padding: 4rem 1rem;
}

p {
  color: white;
}

Article 1

Article 2

Article 3

Article 4

<button id="left-button">Left</button>
<button id="right-button">Right</button>

A: One issue is that you only need to add the event listeners once and there's no need to condition adding event listeners off of the counter. If you use the counter approach, you can return early in the click handler when the desired criteria is met.
The next issue is that your "left" handler isn't working more than once because your transform has to be 100 * counter transformed. The following code keeps pretty close to your initial design but generally works.

var leftButton = document.getElementById("left-button"),
  rightButton = document.getElementById("right-button"),
  article = document.querySelectorAll(".article"),
  counter = 0,
  articleWidth = article.offsetWidth;

leftButton.addEventListener("click", function () {
  if (counter === article.length) return;
  counter += 1;
  article.forEach(function (item) {
    item.style.transform = `translateX(-${counter}00%)`;
    item.style.transition = "all 2s";
  });
});

rightButton.addEventListener("click", function () {
  if (counter === 0) return;
  counter -= 1;
  article.forEach(function (item) {
    item.style.transform = "translateX(0)";
    item.style.transition = "transform 2s";
  });
});
* {
  margin: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.row {
  width: 50%;
  background: red;
  overflow: hidden;
  margin-bottom: 2rem;
}

.article-wrapper {
  display: flex;
  width: 160%;
}

.article {
  width: 70%;
  background: blue;
  margin: 0 1rem;
  padding: 4rem 1rem;
}

p {
  color: white;
}

Article 1

Article 2

Article 3

Article 4

<button id="left-button">Left</button>
<button id="right-button">Right</button>


text:
Q: Ng-grid get rid of cell padding So far I have tried to change the cell padding to 0, but ng-grid wants it to be 5 pixels.  I originally made a css class called test with the following definition
test {
    padding:0;
}

then i figured out that ng-grid is overriding it with the class called ngCellText so the only way to overwrite inline css is to add important
test{
    padding:0 !important;
}

and this didn't work either. By the way my jade (no bracket html)(it also has a little bootstrap) looks like this
div.test
    div.row-fluid.span12
        div(my ng-grid document)

so then, since that didn't work, I looked at cellTemplate.  Here is the default html for it

***0***

This is great and it gets rid of the padding, but as you can see "0" is hardcoded since this if from an inspected element using chrome.  How would I be able to do this using my ng-grid field?  Also, if you have any other ideas on how to fix this please feel free on pitching in.  Preferably I would like to get the !important working or anything else since the way I have ng-grid set up is so I can put it in different places of my website so custom css would be best!

A: This can help:
div.ngCellText[class*="col"] {
   padding: 0;
}

But seems you can just override it like this:
.ngCellText {padding: 0;}


text:
Q: Why is $x_1 i = i x_1$ for quaternions? According to Wikipedia,
$$x+y = (x_0+y_0)+(x_1+y_1) i+(x_2+y_2) j+(x_3+y_3) k$$
and
$$\begin{align}
x  y
&=( x_0 y_0 - x_1 y_1 - x_2 y_2 - x_3 y_3)\\
&+( x_0 y_1 + x_1 y_0 + x_2 y_3 - x_3 y_2) \mathrm i\\
&+( x_0 y_2 - x_1 y_3 + x_2 y_0 + x_3 y_1) \mathrm j\\
&+( x_0 y_3 + x_1 y_2 - x_2 y_1 + x_3 y_0) \mathrm k
\end{align}$$
It's clear how to get the addition, but how do you get the multiplication? Especially, why is
$x_1 \cdot \mathrm i \cdot y_0 = x_1 \cdot y_0 \cdot \mathrm i$ for $x_1, y_0 \in \mathbb{R}$
It might be a dumb question, but I really don't get it. I would appreciate if you use only what I know for your answer, if possible.
What I know
$$i^2 = j^2 = k^2 = -1$$
$$ijk=-1$$
which implies
$$\begin{align} ij &= k\\ ji &= -k\\ jk &= i\\ kj &= -i\\ ki &= j\\ ik &= -j \end{align}$$
and
$$\begin{align}
(-1) \cdot \mathrm i &= \mathrm i \cdot (-1)\\
(-1) \cdot \mathrm j &= \mathrm j \cdot (-1)\\
(-1) \cdot \mathrm k &= \mathrm k \cdot (-1)
\end{align}$$

A: One thing that should be said (that Tunococ has mentioned in the comments) is that

elements of $\Bbb F$ in any associative $\Bbb F$-algebra are essentially assumed to be central.

(The "elements of $\Bbb F$" are of course $\{\lambda 1\mid \lambda\in \Bbb F\}$, their usual embedding.)
This is hiding in the axiom of compatibility with scalars. For any $\Bbb F$ algebra $A$, and any $x\in A$, that axiom gives $\lambda x=((\lambda 1)x)1=(1(\lambda x))1=(\lambda x)1=x(\lambda 1)=x\lambda$.
The quaternions are, after all, an $\Bbb R$-algebra generated by $i,j$ with special relations. The historical perspective at the quaternion article does not really do a good job of explaining that point.
A common alternative definition of algebras makes this even more obvious. It goes something like "an $\Bbb F$-algebra is a ring $A$ and a ring homomorphism $r:\Bbb F\to Z(A)$" where $Z(A)$ is the center of $A$. Assuming this definition, one easily sees the "regular" algebra axioms are satsified by $r(\Bbb F)$, which is (isomorphic to, hence) identified with $\Bbb F$.

A: $ix_1=x_1i$ is only one contract and if we define $x=x_0+ix_1+jx_2+kx_3$ and $y=y_0+iy_1+jy_2+ky_3$(there is no reason that define $x=x_0+x_1i+x_2j+x_3k$ or $y=y_0+y_1i+y_2j+y_3k$ and one of them can be used), then we can define $xy$ as follows
$$\begin{align}
x  y
&=( x_0 y_0 - x_1 y_1 - x_2 y_2 - x_3 y_3)\\
&+i( x_0 y_1 + x_1 y_0 + x_2 y_3 - x_3 y_2) \\
&+j( x_0 y_2 - x_1 y_3 + x_2 y_0 + x_3 y_1) \\
&+k( x_0 y_3 + x_1 y_2 - x_2 y_1 + x_3 y_0)
\end{align}$$
and also note that
$$ix_1=(0,x_1,0,0)=x_1i,(x_1=(x_1,0,0,0),i=(0,1,0,0),j=(0,0,1,0),k=(0,0,0,1))$$
if we define
$$xy=(x_0 y_0 - x_1 y_1 - x_2 y_2 - x_3 y_3,x_0 y_1 + x_1 y_0 + x_2 y_3 - x_3 y_2,x_0 y_2 - x_1 y_3 + x_2 y_0 + x_3 y_1,x_0 y_3 + x_1 y_2 - x_2 y_1 + x_3 y_0).$$


text:
Q: Node.JS app running on AWS performance issues I have been experiencing ambiguous performance issues with a NodeJS with MYSQL app for a while,
In a nutshell, certain requests take a very long time to return a response to the browser.
up to 20 seconds in some cases
using chrome devtools to monitor timing, data in the Time column below shows significant variations between response time to the same endpoint.

To further investigate the issue, I set up the code below to one of the endpoints handlers to monitor delays in the console, In this example, I am running the app on my local PC, and connecting it to a remote production database on the server.

async function getSomething(param) {
  const start = new Date().getTime();
  const something = await Model.where({ field: param }).fetch();
  const end = new Date().getTime();
  console.log('delay: ', end - start, 'ms');
  return something;
}

I executed ten requests to one endpoint, data below shows delays logged to console VS time it takes to get data back to the browser.
numbers are in milliseconds

some responses return back to the browser with almost no or very minor delay as shown in the second and last row, whereas some other requests show a major difference in the time it takes data to be fetched from the database, and the time it needs to be sent to the browser. and this happens in most cases.
some other cases data takes a really long time to be fetched only from the database as shown in row number 3.
differences are arbitrary to me which made it hard to find a pattern to the problem.

here is a screenshot to the app instance metrics from my amazon console, It might help someone to spot something that could help.

furthermore, I am using PM2 process manager to manage the app on the server, and this is another screenshot of the app metrics analysis.

I would really appreciate if someone could point a finger on where else could I look to identify and fix the issue.
thanks in advance.

A: I suspect the nodejs application is running some long synchronous operations that stall the event loop. This can be seen in the relatively big event loop latency in the PM2 screenshot.
This can happen due to:

*

*The code is running time consuming computational operations using

*some sync functions for accessing external resources like for example fs.readFileSync

This can be while processing other parallel requests or timers not related to the request you are debugging.
A nodejs application runs in a single thread, and it depends that all code paths return fast to the event loop so it can process next event.
I suggest profiling the application (https://nodejs.org/en/docs/guides/simple-profiling/) and looking for longest running functions and concentrate on the functions taking long time.


text:
Q: TreeView Remove CheckBox by some Nodes I want remove CheckBoxes where the Node.Type is 5 or 6. I use this code:
private void TvOne_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
    int type = (e.Node as Node).typ;
    if (type == 5 || type == 6)
    {
        Color backColor, foreColor;
        if ((e.State & TreeNodeStates.Selected) == TreeNodeStates.Selected)
        {
            backColor = SystemColors.Highlight;
            foreColor = SystemColors.HighlightText;
        }
        else if ((e.State & TreeNodeStates.Hot) == TreeNodeStates.Hot)
        {
            backColor = SystemColors.HotTrack;
            foreColor = SystemColors.HighlightText;
        }
        else
        {
            backColor = e.Node.BackColor;
            foreColor = e.Node.ForeColor;
        }
        using (SolidBrush brush = new SolidBrush(backColor))
        {
            e.Graphics.FillRectangle(brush, e.Node.Bounds);
        }
        TextRenderer.DrawText(e.Graphics, e.Node.Text, this.TvOne.Font,
            e.Node.Bounds, foreColor, backColor);

        if ((e.State & TreeNodeStates.Focused) == TreeNodeStates.Focused)
        {
            ControlPaint.DrawFocusRectangle(e.Graphics, e.Node.Bounds,
                foreColor, backColor);
        }
        e.DrawDefault = false;
    }
    else
    {
        e.DrawDefault = true;
    }
}

The Problem is that then the Image and the Line to the Root Node is not there.
How can Remove the Checkbox and let the Image and the Line there?
This is wrong!

A: In the code you've shown, you are handling the drawing yourself for all of the nodes whose type is either 5 or 6. For the rest of the types, you're simply allowing the system to draw the nodes in the default way. That's why they all have the lines as expected, but the ones you're owner-drawing do not: You forgot to draw in the lines! You see, when you say e.DrawDefault = false; it's assumed that you really do mean it. None of the regular drawing is done, including the standard lines.
You'll either need to draw in those lines yourself, or figure out how to get by without owner-drawing at all.
From the code you have now, it looks like you're trying to simulate the system's native drawing style as much as possible in your owner-draw code, so it's not clear to me what exactly you accomplish by owner-drawing in the first place. If you're just trying to keep checkboxes from showing up for type 5 and 6 nodes (which, like the lines, are simply not getting drawn because you aren't drawing them!), there's a simpler way to do that without involving owner drawing.

So, you ask, what is that simpler way to hide the checkboxes for individual nodes? Well, it turns out that the TreeView control itself actually supports this, but that functionality is not exposed in the .NET Framework. You need to P/Invoke and call the Windows API to get at it. Add the following code to your form class (make sure you've added a using declaration for System.Runtime.InteropServices):
private const int TVIF_STATE = 0x8;
private const int TVIS_STATEIMAGEMASK = 0xF000;
private const int TV_FIRST = 0x1100;
private const int TVM_SETITEM = TV_FIRST + 63;

[StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
private struct TVITEM
{
    public int mask;
    public IntPtr hItem;
    public int state;
    public int stateMask;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpszText;
    public int cchTextMax;
    public int iImage;
    public int iSelectedImage;
    public int cChildren;
    public IntPtr lParam;
}

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam,
                                         ref TVITEM lParam);

/// <summary>
/// Hides the checkbox for the specified node on a TreeView control.
/// </summary>
private void HideCheckBox(TreeView tvw, TreeNode node)
{
    TVITEM tvi = new TVITEM();
    tvi.hItem = node.Handle;
    tvi.mask = TVIF_STATE;
    tvi.stateMask = TVIS_STATEIMAGEMASK;
    tvi.state = 0;
    SendMessage(tvw.Handle, TVM_SETITEM, IntPtr.Zero, ref tvi);
}

All of the messy stuff at the top are your P/Invoke declarations. You need a handful of constants, the TVITEM structure that describes the attributes of a treeview item, and the SendMessage function. At the bottom is the function you'll actually call to do the deed (HideCheckBox). You simply pass in the TreeView control and the particular TreeNode item from which you want to remove the checkmark.
So you can remove the checkmarks from each of the child nodes to get something that looks like this:

A: This is very good! The only modification I'd make is to pass only the TreeNode and not the TreeView to the HideCheckBox method. The TreeView can be retrieved from the TreeNode itself:
TreeView tvw = node.TreeView;

A: Using TreeViewExtensions.
Usage sample:
private void MyForm_Load(object sender, EventArgs e)
{
     this.treeview1.DrawMode = TreeViewDrawMode.OwnerDrawText;
     this.treeview1.DrawNode += new DrawTreeNodeEventHandler(arbolDependencias_DrawNode);
}

void treeview1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
    if (e.Node.Level == 1) e.Node.HideCheckBox();
    e.DrawDefault = true;
}

Here is the answer's code as an Extension method, using this you can do:
public static class TreeViewExtensions
{
    private const int TVIF_STATE = 0x8;
    private const int TVIS_STATEIMAGEMASK = 0xF000;
    private const int TV_FIRST = 0x1100;
    private const int TVM_SETITEM = TV_FIRST + 63;

    [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
    private struct TVITEM
    {
        public int mask;
        public IntPtr hItem;
        public int state;
        public int stateMask;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpszText;
        public int cchTextMax;
        public int iImage;
        public int iSelectedImage;
        public int cChildren;
        public IntPtr lParam;
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam,
                                             ref TVITEM lParam);

    /// <summary>
    /// Hides the checkbox for the specified node on a TreeView control.
    /// </summary>
    public static void HideCheckBox(this TreeNode node)
    {
        TVITEM tvi = new TVITEM();
        tvi.hItem = node.Handle;
        tvi.mask = TVIF_STATE;
        tvi.stateMask = TVIS_STATEIMAGEMASK;
        tvi.state = 0;
        SendMessage(node.TreeView.Handle, TVM_SETITEM, IntPtr.Zero, ref tvi);
    }
}


text:
Q: Python dash - How to highlight / bold specific words in a row I've created a table and for each row there is a specific word that needs to be highlighted.
So as an example the words in <b> should be bold (example underscored):

My code for creating a table and trying to make specific words bold is as follows:
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table
...

remove_common_words_list = ["iraq", "america"]
words = { "iraq": { "occurrences":63,
                    "documents":{ "doc3,txt", "doc2.txt", "doc1.txt", "doc5.txt",
                    "sentences":["And when all else fails, when Katrina happens, or the death toll in Iraq mounts, we've been told that our crises are somebody else's fault.", 'But all of this cannot come to pass until we bring an end to this war in Iraq.'] },
          "america": { "occurrences":46,
                    "documents":{ "doc3,txt", "doc1.txt", "doc5.txt",
                    "sentences":['And I accepted the job, sight unseen, motivated then by a single, simple, powerful idea that I might play a small part in building a better America.', 'It was here, in Springfield, where I saw all that is America converge farmers and teachers, businessmen and laborers, all of them with a story to tell, all of them seeking a seat at the table, all of them clamoring to be heard.'] }

remove_common_words = { "Word (Total Occurrences)":[], "Documents":[],  "Sentences containing the word":[] }
for index, word in enumerate(remove_common_words_list[0:1]):
    remove_common_words["Word (Total Occurrences)"].append(f"{word} ({words[word]['occurrences']})")
    remove_common_words["Documents"].append(", ".join(words[word]["documents"]))
    remove_common_words["Sentences containing the word"].append(re.sub(r"(" + word + ")", r"<b>\1</b>", "\n\n".join(words[word]["sentences"]), flags=re.IGNORECASE))

data = pd.DataFrame(remove_common_words)

app = dash.Dash(__name__)
app.layout = html.Div([
    dash_table.DataTable(
        id='table',
        columns=[{"name": i, "id": i} for i in data.columns],
        data=data.to_dict('records'),
        style_cell={
            'whiteSpace': 'pre-line',
            'textAlign': 'left',
            'vertical-align':'top'
        },
        style_data_conditional=[
            {
                'if': {'row_index': 'odd'},
                'backgroundColor': 'rgb(248, 248, 248)'
            }
        ],
        style_header={
            'fontWeight': 'bold'
        }
    )
])

app.run_server(debug=True)

HTML doesn't seem to be being passed, I can see markdown is an option but I've been unable to get it working and unsure how (if it can) be implemented.
So my questions is how can you make specific pieces of text bold or highlighted?

A: This answer uses Markdown in Dash, as I don't think HTML rendering is supported (see this Github Issue).
First, change line 23 in your example to
remove_common_words["Sentences containing the word"].append(re.sub(r"(" + word + ")", r"**\1**", "\n\n".join(words[word]["sentences"]), flags=re.IGNORECASE))

to follow the Markdown syntax for bolding.
Next, specify that the Table should parse the text as Markdown by updating line 31
columns=[{"name": i, "id": i, "type": 'text', "presentation": 'markdown'} for i in data.columns]

And those specified words should be bolded


text:
Q: How could I adjust the height of each azure service in Visual Studio Code? VS code capture image
As shown in the capture image(with red arrow in the image), I want to adjust the height of each Azure service.
Please let me know how to do this. Thanks.

A:
I want to adjust the height of each Azure service. Please let me know
how to do this

There is such  limitation in VS CODE to minimize and maximize up to certain level the Side bar Azure services ,
To  do that you can do the below steps:

*

*Hide  your azure service below which you want to adjust  as shown

*

*Drag down the line which is up in the LOGIC APPS (STANDARD) as shown :

Drag down according to your requirement

To know more about configuration in VS CODE please refer the below links :
. SO THREAD - # How can I customize the tab-to-space conversion factor?
VS CODE Blog : User and Workspace Settings
UPDATE:
Please make sure that you have update your VS Code version to 1.62.3 and then try. also check my settings.json file .
Go to settings if you haven't update you will get an option called restart to update instead of Check for update .


text:
Q: Piece of appscript code running slow? or is it Google Sheets? I have this piece of code below that when it goes to find a value of a current cell the run time is about 6.87 sec. It is making the run time on my code about 7-8 seconds. It also seems like Google Sheets is buffering a lot longer after the code has run. I can't seem to speed either of them up.
For the code, I've rewritten the code a few times trying to put arrays where I can. I've added a data validation clear in hopes it would find the value faster. For the Google Sheets issues, I've tried clearing my cached data and tried two different browsers. None seemed to work
function onEdit () {
var data = SpreadsheetApp.getActiveSpreadsheet();
var ordersheet =data.getActiveSheet();
var reference = ordersheet.getSheetName();
var cleared = ordersheet.getActiveCell().clearDataValidations();

if(reference == "Order Sheet") {

var ranged = ordersheet.getActiveRange();
var sheetName= ranged.getValue();
var pullName = data.getSheetByName(sheetName);
var datass = pullName.getRange(3, 1, pullName.getLastRow(),
1).getValues();

var validationRule =
SpreadsheetApp.newDataValidation()
.requireValueInList(datass).build();
ordersheet.getActiveCell().offset(1, 0,
15).setDataValidation(validationRule);

   var spreadsheet = SpreadsheetApp.getActiveSheet();
 var off = spreadsheet.getCurrentCell().offset(1, 5).activate();
 var row = spreadsheet.getCurrentCell().getRow();
 var col = spreadsheet.getCurrentCell().getColumn();

  var formulas = [

 ['=Iferror(INDEX(INDIRECT(R[-1]C[-5]&1),MATCH(R[0]C[-5],
  INDIRECT(R[-1]C[-5]&2),0),2),"Please Add Item to Customer Price
  List")'],
  ['=Iferror(INDEX(INDIRECT(R[-2]C[-5]&1),MATCH(R[0]C[-5],
  INDIRECT(R[-2]C[-5]&2),0),2),"Please Add Item to Customer Price
  List")'],
 ['=Iferror(INDEX(INDIRECT(R[-3]C[-5]&1),MATCH(R[0]C[-5],
 INDIRECT(R[-3]C[-5]&2),0),2),"Please Add Item to Customer Price
 List")'],
 ['=Iferror(INDEX(INDIRECT(R[-4]C[-5]&1),MATCH(R[0]C[-5],
 INDIRECT(R[-4]C[-5]&2),0),2),"Please Add Item to Customer Price
 List")'],
 ['=Iferror(INDEX(INDIRECT(R[-5]C[-5]&1),MATCH(R[0]C[-5],
 INDIRECT(R[-5]C[-5]&2),0),2),"Please Add Item to Customer Price
  List")'],
 ['=Iferror(INDEX(INDIRECT(R[-6]C[-5]&1),MATCH(R[0]C[-5],
 INDIRECT(R[-6]C[-5]&2),0),2),"Please Add Item to Customer Price
 List")'],
 ['=Iferror(INDEX(INDIRECT(R[-7]C[-5]&1),MATCH(R[0]C[-5],
 INDIRECT(R[-7]C[-5]&2),0),2),"Please Add Item to Customer Price
  List")'],
  ['=Iferror(INDEX(INDIRECT(R[-8]C[-5]&1),MATCH(R[0]C[-5],
  INDIRECT(R[-8]C[-5]&2),0),2),"Please Add Item to Customer Price
  List")'],
  ['=Iferror(INDEX(INDIRECT(R[-9]C[-5]&1),MATCH(R[0]C[-5],
  INDIRECT(R[-9]C[-5]&2),0),2),"Please Add Item to Customer Price
   List")'],
 ['=Iferror(INDEX(INDIRECT(R[-10]C[-5]&1),MATCH(R[0]C[-5],
 INDIRECT(R[-10]C[-5]&2),0),2),"Please Add Item to Customer Price
  List")'],
  ['=Iferror(INDEX(INDIRECT(R[-11]C[-5]&1),MATCH(R[0]C[-5],
   INDIRECT(R[-11]C[-5]&2),0),2),"Please Add Item to Customer Price
   List")'],
  ['=Iferror(INDEX(INDIRECT(R[-12]C[-5]&1),MATCH(R[0]C[-5],
   INDIRECT(R[-12]C[-5]&2),0),2),"Please Add Item to Customer Price
    List")'],
  ['=Iferror(INDEX(INDIRECT(R[-13]C[-5]&1),MATCH(R[0]C[-5],
  INDIRECT(R[-13]C[-5]&2),0),2),"Please Add Item to Customer Price
    List")'],
   ['=Iferror(INDEX(INDIRECT(R[-14]C[-5]&1),MATCH(R[0]C[-5],
   INDIRECT(R[-14]C[-5]&2),0),2),"Please Add Item to Customer Price
    List")'],
    ['=Iferror(INDEX(INDIRECT(R[-15]C[-5]&1),MATCH(R[0]C[-5],
    INDIRECT(R[-15]C[-5]&2),0),2),"Please Add Item to Customer
     Price List")']
    ];
   var area = spreadsheet.getRange(row,col,15);
   area.setFormulasR1C1(formulas);

      }};

The code works for how the sheet is set up but I just need it to run faster.


text:
Q: c# Insert boolean value into database I have problem inserting boolean value into database.
I have simple structure:
struct
{
   string name;
   bool isStudent;
}

and I want to insert it into data base like this:
 dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + people1.isStudent + ")";
 dbCommand.ExecuteNonQuery();

but i throws exception:

SQLite error no such column: True

A: Try using:
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', '" + people1.isStudent + "')";

Note that 'true' or 'false' will be quoted this way.
Or:
int val = isStudent ? 1 : 0;
dbCommand.CommandText = "INSERT INTO People (name, isStudent) VALUES ('" + people1.name + "', " + val + ")";

1 will be used for true values and 0 for false values.

A: Use parameters and you won't have to worry about quotes or format of the values (besides, it is a good practice to avoid SQL injection):
dbCommand.CommandText = "INSERT INTO People (name, isStudent)
                         VALUES (@name, @isStudent)";
dbCommand.Parameters.AddWithValue("@name", people1.name);
dbCommand.Parameters.AddWithValue("@isStudent", people1.isStudent);
dbCommand.ExecuteNonQuery();

A: SQLite doesn't have a bool column type and you're constructing the SQL statement yourself.  If you want to do that, then convert 1 and 0 back and forth.
I would also think the .net wrapper would do that 4 u.  But you would have to use SQL parameters and not build the string yourself to even give it a chance to do that.
Building parameterized queries (?) also let's SQL lite cache the compiled statements.


text:
Q: Applying SKShader to multiple layers In a game I am working on, I use multiple layers to manage the background scenery like so:

*

*Background

*Background Obstacles

*Foreground Obstacles

I am using a displacement shader to create a ripple effect, but I'm not sure how to apply it to the entire background section. Each layer is an individual SKNode where I add different SKSprites.
I want the ripple effect to affect all layers, but I can't apply a shader to a SKNode.

A: You cannot apply one shader effect to multiple layers, so what you would likely need to do is capture the state of the other layers by making then siblings in a parent node and capturing the output of the node, like this:
SKTexture *captureTexture = [skView textureFromNode:node];

Then assign this texture to one node and attach the shader to that Node. You may not be able to get full FPS updates with this capture approach, but I this may be the only way to get it working.


text:
Q: Destructuring with nested objects and default values I'm using destructuring to declare some variables like this:
const { a, b, c } = require('./something'),
    { e = 'default', f = 'default'} = c;

Is there a way to make this into single line?
I've tried something like :
const { a, b, c = { e = 'default', f = 'default'} } = require('./something');

But it gives me an error:

SyntaxError: Invalid shorthand property initializer

A: This example will help you to understand the destructing of array and object with fallback values.
You can use the = symbol for adding fallback or default value while destructing.

const person = {
  firstName: 'Nikhil',
  address: {
    city: 'Dhule',
    state: 'MH'
  },
  /*children: [
    {
      name: 'Ninu',
      age: 3
    }
  ]*/
}

const {
  firstName,
  address: {
    city,
    state
  },
  children: {
    0: {
      name='Oshin' // Fallback for name is string i.e 'Oshin'
    }={} // Fallback for 1st index value of array is blank object
  }=[] // Fallback for children is blank array
} = person;

console.log(`${firstName} is from ${city} and his first child name is ${name}`);

A: The above code will not work if the object does not have c in it

const { a, b, c: { e = 'default', f = 'default'}} = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)

This will print out an error.
For completion, you could as a simple "={}" as default

const { a, b, c: { e = 'default', f = 'default'} ={} } = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)

A: Just replace = with ::
const {a, b, c: {e = 'default', f = 'default'}} = require('./something')

Demo:

const { a, b, c: { e = 'default', f = 'default'} } = {a: 1, b: 2, c: {e: 3}}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)

It prints:
a: 1, b: 2, e: 3, f: default


text:
Q: Typescript string split remove quotes I have the following string, that needs to become an array of elements, by splitting it by comma character.
"Name1","Name2","Name3","Name4"

The result should be an array [Name1, Name2, Name3, Name4], without the quotes. I've tried to remove the quotes before I do the split, but somehow the result still have those quotes. Tried also to go through each array item after I did the split and remove the quote, and did not succeed. How can this be achieved?

A: Split then remove the first and last character of each string:

const str = '"Name1","Name2","Name3","Name4"';
console.log(
  str
  .split(',')
  .map(s => s.substring(1, s.length-1))
)


text:
Q: Possible to recreate LVM VG? frequent listener first time caller
A coworker in another department did an OS upgrade on a CentOS-based RAID NAS. Unfortunately the upgrade process recreated the PV that defined the VG. Basically LVM sees the PV on the RAID array, but does not see any VGs. This is an 80 TB array, with no backups. I have been brought over to help, but I don't use LVM that much so limited help.
Here's where we are at
$ pvs /dev/sda2
PV         VG  Fmt   Attr  Psize   Pfree   DevSize
/dev/sda2      lvm2  a--   76.40t  76.40t  76.40t

$ pvdisplay /dev/sda2
-- NEW Physical volume --
PV Name       /dev/sda2
VG Name
PV Size       76.4 TiB
Allocatable   NO
PE Size       0
Total PE      0
Free PE       0
Allocated PE  0
PV UUID       <UUID>

If I cat the raw partition I can see some filesystem data, so I am hoping that I can redefine the VG and reconstruct the partition from there. Its my understanding that LVM retains internal backups of the metadata, so I'm wondering if the old VG data is on the disk somewhere, even though the PV has been recreated?
Any other advice?
Thanks!