text:
Q: Debug a DOMDocument Object in PHP I'm trying to debug a large and complex DOMDocument object in php.  Ideally it'd be nice if I could get DOMDocument to output in a array-like format.
DoMDocument:
$dom = new DOMDocument();
$dom->loadHTML("
Hello World
");
var_dump($dom); //or something equivalent
This outputs
DOMDocument Object ( )
whereas I'd like it to output
DOMDocument:
html
=>body
==>p
===>Hello World
Or something like that.  Why is there no handy debug or output for this?!?

A: This answer is a little late probably, but I liked your question!
PHP has nothing build-in directly to solve your problem, so there is not XML dump or something.
However, PHP has the RecursiveTreeIteratorDocs that comes pretty close to your output:
\-
  \-
    \-

      \-Hello World

(it will look better if your X(HT)ML structure looks more complicated.)
It's used quite simple (as most iterators) with a foreach:
$tree = new RecursiveTreeIterator($iterator);
foreach($tree as $key => $value)
{
    echo $value . "\n";
}

(You can wrap this inside a function, so you only need to call the function)
Even this looks simple, there's one caveat: it needs a RecursiveIterator over the DOMDocument tree. As PHP can not guess what you need, it needs to be wrapped into code. As written, I found the question interesting (and obviously you have not asked for XML output), so I wrote some little code that offers the recursive iterator needed. So here we go.
First of all you might not be familiar with iterators in PHP. That's no deal to make use of the code I'll show as I'll do it backwards, however, whenever you consider to run some code on your own, consider whether or not you can make use of the iterator capabilities PHP has to offer. I write that because it helps to solve common problems and to make components that are not really related with each other to work with each other. For example, the RecursiveTreeIteratorDocs is built-in, and it will work with anything you feed it with (and you can even configure it). However it needs a RecursiveIterator to operate upon.
So let's give it a RecursiveIterator that offers <tag> for DOMNodes that are tags (elements) and just the text if they are textnodes:
class DOMRecursiveDecoratorStringAsCurrent extends RecursiveIteratorDecoratorStub
{
    public function current()
    {
        $node = parent::current();
        $nodeType = $node->nodeType;

        switch($nodeType)
        {
            case XML_ELEMENT_NODE:
                return "<$node->tagName>";

            case XML_TEXT_NODE:
                return $node->nodeValue;

            default:
                return sprintf('(%d) %s', $nodeType, $node->nodeValue);
        }
    }
}

This DOMRecursiveDecoratorStringAsCurrent class (the name is exemplary only) makes use of some abstract code in RecursiveIteratorDecoratorStub. The important part however is the ::current function which just returns the tagName of a DOMNode in bracketsWikipedia (<>) and the text of textnodes as-is. That's what your output needs, so that's everything needed to code.
Actually this does not work until you have the abstract code as well, but to visualize the code how it's used (the most interesting part), let's view it:
$iterator = new DOMRecursiveDecoratorStringAsCurrent($iterator);
$tree = new RecursiveTreeIterator($iterator);
foreach($tree as $key => $value)
{
    echo $value . "\n";
}

As it's done backwards, for the moment we have the output specified based on which DOMNode is to be displayed by the RecursiveTreeIterator. Fine so far, easy to get. But the missing meat it is inside the abstract code and how to create a RecursiveIterator over all nodes inside a DOMElement. Just preview the whole code how it is invoked (as written before, you can put this into a function to make it easily accessible within your code for debugging purposes. Probably a function called xmltree_dump):
$dom = new DOMDocument();
$dom->loadHTML("
Hello World
");
$iterator = new DOMRecursiveIterator($dom->documentElement);
$iterator = new DOMRecursiveDecoratorStringAsCurrent($iterator);
$tree = new RecursiveTreeIterator($iterator);
foreach($tree as $key => $value)
{
    echo $value . "\n";
}

So what do we got here in addition to the code already covered? First there is a DOMRecursiveIterator - and that's it. The rest of the code is standard DOMDocument code.
So let's write about DOMRecursiveIterator. It's the needed RecursiveIterator that's finally needed within the RecursiveTreeIterator. It get's decorated so that the dump of the tree actually prints tagnames in brackets and text as-is.
Probably it's worth to share the code of it now:
class DOMRecursiveIterator extends DOMIterator implements RecursiveIterator
{
    public function hasChildren()
    {
        return $this->current()->hasChildNodes();
    }
    public function getChildren()
    {
        $children = $this->current()->childNodes;
        return new self($children);
    }
}

It's a pretty short class with only two functions. I'm cheating here as this class also extends from another class. But as written, this is backwards, so this class actually takes care of the recursion: hasChildren and getChildren. Obviously even those two functions don't have much code, they are just mapping the "question" (hasChildren? getChildren?) onto a standard DOMNode. If a node has children, well, say yes or just return them (and this is an iterator, return them in form of an iterator, hence the new self()).
So as this is pretty short, after choking it, just continue with the parent class DOMIterator  (the implements RecursiveIteratorDocs is just to make it working):
class DOMIterator extends IteratorDecoratorStub
{
    public function __construct($nodeOrNodes)
    {
        if ($nodeOrNodes instanceof DOMNode)
        {
            $nodeOrNodes = array($nodeOrNodes);
        }
        elseif ($nodeOrNodes instanceof DOMNodeList)
        {
            $nodeOrNodes = new IteratorIterator($nodeOrNodes);
        }
        if (is_array($nodeOrNodes))
        {
            $nodeOrNodes = new ArrayIterator($nodeOrNodes);
        }

        if (! $nodeOrNodes instanceof Iterator)
        {
            throw new InvalidArgumentException('Not an array, DOMNode or DOMNodeList given.');
        }

        parent::__construct($nodeOrNodes);
    }
}

This is the base iterator for DOMPHP, it just takes a DOMNode or a DOMNodeList to iterate over. This sounds a bit superfluous maybe, as DOM supports this sort-of with DOMNodeList already, but it does not support a RecursiveIterator and we already know that we need one for RecursiveTreeIterator for the output. So in it's constructor an Iterator is created and passed on to the parent class, which again is abstract code. Sure I'll reveal this code in just a minute. As this is backwards, let's review what's been done so far:

*

*RecursiveTreeIterator for the tree-like output.

*DOMRecursiveDecoratorStringAsCurrent for the visualization of a DOMNode in the tree

*DOMRecursiveIterator and DOMIterator to iterate recursively over all nodes in a DOMDocument.

This in terms of definition as all that's needed, however the code that I called abstract is still missing. It's just some sort of simple proxy code, it delegates the same method down to another object. A related pattern is called Decorator. However, this is just the code, first the Iterator and then it's RecursiveIterator friend:
abstract class IteratorDecoratorStub implements OuterIterator
{
    private $iterator;
    public function __construct(Iterator $iterator)
    {
        $this->iterator = $iterator;
    }
    public function getInnerIterator()
    {
        return $this->iterator;
    }
    public function rewind()
    {
        $this->iterator->rewind();
    }
    public function valid()
    {
        return $this->iterator->valid();
    }
    public function current()
    {
        return $this->iterator->current();
    }
    public function key()
    {
        return $this->iterator->key();
    }
    public function next()
    {
        $this->iterator->next();
    }
}

abstract class RecursiveIteratorDecoratorStub extends IteratorDecoratorStub implements RecursiveIterator
{
    public function __construct(RecursiveIterator $iterator)
    {
        parent::__construct($iterator);
    }
    public function hasChildren()
    {
        return $this->getInnerIterator()->hasChildren();
    }
public function getChildren()
{
    return new static($this->getInnerIterator()->getChildren());
}
}

That's nothing very magically, it's just well delegating the method calls to it's inherited object $iterator. It looks like repeating and well iterators are about repetition. I put this into abstract classes so I only need to write this very simple code once. So at least I myself don't need to repeat myself.
These two abstract classes are used by other classes which have been already discussed earlier. Because they are so simple, I left it until here.
Well, much to read until here but the good part is, that's it.
In short: PHP does not have this build in, but you can write this on your own quite simple and re-useable. As written earlier, it's a good idea to wrap this into a function called xmltree_dump so it can be easily called for debugging purposes:
function xmltree_dump(DOMNode $node)
{
    $iterator = new DOMRecursiveIterator($node);
    $decorated = new DOMRecursiveDecoratorStringAsCurrent($iterator);
    $tree = new RecursiveTreeIterator($decorated);
    foreach($tree as $key => $value)
    {
        echo $value . "\n";
    }
}

Usage:
$dom = new DOMDocument();
$dom->loadHTML("
Hello World
");
xmltree_dump($dom->documentElement);

the only thing needed is to have all the class definitions used included / required. You can put them in one file and use require_once or integrate them with an autoloader that you're probably using. Full code at once.
If you need to edit the way of output, you can edit DOMRecursiveDecoratorStringAsCurrent or change the configuration of RecursiveTreeIterator inside xmltree_dump. Hope this is helpful (even quite lengthy, backwards is pretty in-direct).

A: http://usphp.com/manual/en/function.dom-domdocument-savexml.php
$dom->formatOutput = true;
echo $dom->saveXML();

A: for a dom node, just use the following:
print_r(simplexml_import_dom($entry)->asXML());

A: Though I haven't tried it myself, check out Zend_Dom, part of the Zend Framework. Documentation and examples for most of the Zend Framework components is really thorough.

A: I just used DOMDocument::save.  It's lame that it has to write to a file, but whatever.

A: You can cheat and use JSON to inspect the structure by converting it to an array.
print_r(json_decode(json_encode($node), true));


text:
Q: Allow users to vote up, or down, or nothing I have made an app to create article. This is the model:
class Article(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.CharField(max_length=150)
    body = models.TextField()
    pub_date = models.DateTimeField(default=timezone.now)
    tags = models.ManyToManyField(Tag)
    article_image = models.ImageField(upload_to=get_upload_file_name, blank=True)

Here I want to setup a voting system for each app. There I would like give the users the feature to vote up, or vote down, or do nothing. Boolean field would have been great, but since an article can have 3 choices of votes  (vote up / vote down / or default = no vote ), how should I go about doing this? Your help and guidance will be very much appreciated. Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't import project to gitlab.com - Basic 101 issues How to view the contents of what appears to be a GitLab export?
Ultra-beginners who stumbled across a GitLab export (we think) of an employee that is no longer with us. Due diligence says we need to figure out if this is company IP or not. However, no one has any experience with GitLab. All we care about is what is code for? We don't care about branches, commits, etc. at this point.
Attempted:

*

*Found numerous *.tgz files, each contains a single *.tar with the following structure.

*Created a GitLab.com account and attempted to create a 'new project'... 'import project'... selected 'GitLab export' (best guess) and pointed to one of the *.tgz files

*Got error that it must be a .gz extension so tried different naming/unzipping to no avail

*Did download Portable Git and ran:
$ git verify-pack -v pack-foo.pack and it shows commits/blobs/trees as would be expected


text:
Q: Example of wicket atmosphere with channel
I just saw new features released at wicket 6.40. And I am interested
  to see example code of the atmosphere channel. Where can i find the
  example of this feature?

Thanks.

A: Here's a quickstart application of integrating Wicket and Atmosphere.
https://github.com/papegaaij/wicket-atmosphere-quickstart

*

*atmosphere.xml can be found under src/main/webapp/META-INF/

*web.xml under src/main/webapp/WEB-INF/

A: Here is a minimal example:
http://examples7x.wicket.apache.org/atmosphere/?0
It is similar to RJo's link. In addition:

*

*There is an online demo.

*Custom objects are pushed to the EventBus, so You'll see that everything might be transfered as long as it is Serializable.

Summary:

*

*An EventBus instance is initialized in AtmosphereApplication.java.

*This EventBus is used in HomePage.java to push messages.

*@Subscribe annotations in HomePage.java are used to receive messages.


text:
Q: can't edit a JFrame form anymore I have several JFrames which i have previously created, normally when i want to adjust anything related to the GUI i right click on the Frame name into my application -> Edit - and Start editing
Now suddenly all my JFrames became only CLASSES like if was created them from the begging as a Java Class not JFrame Form and i only have access to the generated code by netbeans GUI.
How can i roll them back to their previous type or extension so i can edit the GUI though the drag and drop features of netbeans?


text:
Q: Getting Bootstrap to work in Rails 2 I have worked with Rails 4 earlier and getting bootstrap and sass to work with a Rails 4 application was very easy by doing:

*

*Adding gem 'bootstrap-sass' and gem 'sass-rails', '~> 4.0.0' to the Gemfile and running bundle install

*Add //= require bootstrap line to application.js

*Adding config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif) line to application.rb

*Adding @import "bootstrap"; line to the top of the *.css.scss file

But the same when done with a Rails 2 application doesnt seem to get the Bootstrap and SCSS to work. Can anybody explain the steps involved in gettin bootstrap and scss to work with a Rails 2 application?
P.S : My application's exact Rails version is 2.3.18 and am using Ruby 1.8.7


text:
Q: Как поменять цвет выделения элемента в ListBox в фокусе и без? Имеется ListBox со списком элементов типа string. Выбрал элемент, он выделился серым цветом, все прекрасно. Затем, если ListBox неактивен (без фокуса), то соответственно цвет выделения элемента становится совсем блеклым, и глаза напрягаются для определения выделенного элемента в ListBox. А мне как раз надо чтобы цвет выделения элемента в ListBox не менялся не зависимо от фокуса.
Как этого добиться?

A: var res = listBox1.Resources;

//Устанавливаем цвет выделения активного ListBox'а
res.Add(SystemColors.HighlightBrushKey, new SolidColorBrush(Colors.Yellow));

//Устанавливаем цвет выделения неактивного ListBox'а
res.Add(SystemColors.InactiveSelectionHighlightBrushKey, new SolidColorBrush(Colors.Yellow));


text:
Q: Ui-select : dropdown larger than select I want to use the ui-select component. But I am getting a weird behaviour, the dropdown area is larger than the select.
I am not an expert in CSS, if someone can help me on this, that would be nice.
I am posting the css that goes with it (when I click on the dropdown via Chrome webtool, code inspector)
element.style {
}
.select2-drop.select2-with-searchbox.select2-drop-active {
}
.select2-drop-active {
border-color: #66afe9;
}
.select2-drop-active {
border: 1px solid #5897fb;
border-top: none;
}
.select2-drop {
width: 100%;
margin-top: -1px;
position: absolute;
z-index: 9999;
top: 100%;
background: #fff;
color: #000;
border: 1px solid #aaa;
border-top: 0;
border-radius: 0 0 4px 4px;
-webkit-box-shadow: 0 4px 5px rgba(0, 0, 0, .15);
box-shadow: 0 4px 5px rgba(0, 0, 0, .15);
}
.select2-container, .select2-drop, .select2-search, .select2-search input {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
user agent stylesheetdiv {
display: block;
}
Pseudo ::before element
*:before, *:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
Pseudo ::after element
*:before, *:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
Inherited from div.col-md-7.ui-select-container.select2.select2-container.ng-pristine.ng-valid.select2-allowclear.select2-container-active.select2-dropdown-open.open
.select2-container {
margin: 0;
position: relative;
display: inline-block;
zoom: 1;
vertical-align: middle;
margin-left: -12px;
}
Inherited from div#tab1.tab-pane.active
.tab-content > .active {
display: block;
visibility: visible;
}
.tab-content > .tab-pane {
display: none;
visibility: hidden;
}
Inherited from body.ng-scope.modal-open
body {
background-color: #e4e6e9;
min-height: 100%;
padding-bottom: 0;
font-family: 'Open Sans';
font-size: 13px;
color: #393939;
line-height: 1.5;
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333333;
background-color: #ffffff;
}
body {
background: #fafafa;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #333;
}
Inherited from html.js.flexbox.flexboxlegacy.canvas.canvastext.webgl.no-touch.geolocation.postmessage.websqldatabase.indexeddb.hashchange.history.draganddrop.websockets.rgba.hsla.multiplebgs.backgroundsize.borderimage.borderradius.boxshadow.textshadow.opacity.cssanimations.csscolumns.cssgradients.cssreflections.csstransforms.csstransforms3d.csstransitions.fontface.generatedcontent.video.audio.localstorage.sessionstorage.webworkers.applicationcache.svg.inlinesvg.smil.svgclippaths
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
html {
font-family: sans-serif;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}

code of the ui-select

                                                    {{$select.selected.nom}}

It seems that when I remove : class="col-md-7" the problem disappear. But I need it as I am working in a bootstrap grid.
Thanks in advance.


text:
Q: Special Gram's inequality For $1 \le s < k$ and $v_1$, $v_2,\dots,v_k$ vectors in $\mathbb{R}^n$, show that
$$\det G(v_1, v_2,\dots,v_k) \le \det G(v_1,v_2,\dots,v_s)\det G(v_{s+1}, v_{s+2},\dots,v_k).$$
Here, $G(v_1, v_2,\dots,v_k)$ is a Gram matrix of vectors $v_1, v_2,\dots,v_k$ with the standard inner product.
This is my homework problem, but I have no idea how to approach it. I found that this is one of the Gram's inequalities, but I can't figure out how it could be derived either from this:
$$\det G(v_1, v_2,\dots,v_k) \ge 0,$$
or Hadamard's inequality:
$$\det G(v_1, v_2,\dots,v_k) \le \prod_{i=1}^{k}\|x_i\|^2.$$
So any help would be much appreciated.

A: Here are some hints. This approach uses a lemma which is interesting by itself.
Let $A:=G(v_1,\ldots,v_k)$, $A_1:=G(v_1,\ldots,v_s)$, $A_2:=G(v_{s+1},\ldots,v_k)$. Note that these are positive semidefinite matrices.

*

*Note that $A=\pmatrix{A_1&B\\B^*&A_2}$ and we need to prove $\det A\leq \det A_1\cdot \det A_2$. Without loss of generality, we can assume that $\det A>0$, i.e. $\{v_1,\ldots,v_k\}$ are linearly independent, for otherwise the inequality is trivial.

*Lemma   For every linearly independent set $\{u_1,\ldots,u_m\}$ and every vector $x$ in $\mathbb{R}^n$, the Euclidean distance between $x$ and $V$ the span of $\{u_1,\ldots,u_m\}$ is given by
$$d(x,V)=\sqrt{\frac{\det G(u_1,\ldots,u_m,x)}{\det G(u_1,\ldots,u_m)}}$$
Sketch  Note that $d=d(x,V)=\|x-y\|$ where $y$ is the orthogonal projection onto $V$, which satisfies  $\|x\|^2=\|y\|^2+d^2$ and $\langle x,u_j\rangle =\langle y,u_j\rangle$ for every $j$. Then use the multilinearity of the determinant when inspecting the last column of $G(u_1,\ldots,u_m,x)$. $\Box$
Use the lemma a couple of times to get
$$
\det A=d(v_1,*)^2\det G(v_2,\dots,v_k)=\ldots=*****\det A_2
$$
and
$$
\det A_1=d(v_1,*)^2\det G(v_2,\ldots,v_s)=*****
$$
Then compare the $*$'s by observing the appropriate subspace inclusions.

A: Hint: By an orthogonal change of basis, we may assume that
$$
V=(v_1,v_2,\ldots,v_k)=\pmatrix{A_{s\times s}&0\\ B_{(k-s)\times s}&C_{(k-s)\times(k-s)}},
$$
so that the inequality in question is equivalent to $\det(V^TV)\le\det\left[(A^T,B^T)\pmatrix{A\\ B}\right]\det(C^TC)$.


text:
Q: Запуск Python скрипта через supervisor Нужно запустить скрипт питона через supervisor, при команде:
sudo supervisorctl start all
выходит ошибка:
worker: ERROR (spawn error)

Вот конфиг:
[program:worker]
command=/usr/bin/python3 /var/www/cdn/cgi-bin/hello.py
stdout_logfile=/var/log/worker.log
autostart=true
autorestart=true
user=designer
stopsignal=KILL
numprocs=1

Пути вроде правильные, при добавление конфига обновил супервизор...


text:
Q: How does memcached behave when data has changed? Reading this brief example of using memcached with PHP, I was wondering how memcached knows when a request for data needs to actually come from the database instead of coming from the cache.

A: It doesn't, you code does this. In most cases you will do something like this:
key = /* build cache key somehow */
data = memcache.get(key)
if data is null:
  data = /* read data from database */
  cached.set(key, data)

// now you can use the data

A: It doesn't. It comes down to your caching strategy. That is so with all forms of cache, a tradeoff between getting the latest data and getting some data quickly. If you need to have the data up to date, invalidate (delete) the cache when updating the original. If performance is more important, let the cache expire by itself, at which point it will be renewed. Or something somewhere in-between. It depends on your restrictions and goals.

A: I think you need to program that logic.
e.g. When you update the database then update the memcached value associated with that key, or make that key expire.


text:
Q: What does browserConnectionEnabled capability mean? I wonder what does browserConnectionEnabled capability param means. It is used in in chromedriver http://code.google.com/p/chromium/source/search?q=browserConnectionEnabled&origq=browserConnectionEnabled&btnG=Search+Trunk and is explained as "Whether the session can query for the browser's connectivity and disable it if desired.". But I dont understand what does it realy do.

A: It's used in mobile drivers where the state of connectivity can be manipulated (e.g. for testing offline web apps). As far as I know his is only available in the Android driver at the moment.


text:
Q: Using "are" or "were" for warnings Which of the following sentences is correct?

If you are caught stealing you will be fined.

If you were caught stealing you will be fined.

A: The first is fully grammatical, the second is at least dubious. However a third possibility is grammatical:

If you were caught stealing you would be fined.

The difference between your first example and mine is that the "... were ... would" is usually said to be hypothetical; but in fact these are both hypothetical.
There is a difference: the "If you are ... " implies that you are stealing, or that you are definitely intending to do so. "If you were ... " carries no such implication.

A: Foreign learners of English are taught that If you are caught stealing you will be fined is the First Conditional and that If you were caught stealing you would be fined is the Second Conditional. The First Conditional describes a situation that might very well happen. The Second Conditional describes a situation that is much less likely to happen. There is a Third Conditional, If you had been caught stealing you would have been fined. Of the three only this describes a truly hypothetical situation.


text:
Q: Sinatra (Ruby) - Posting with Ajax I'm attempting to submit some data on the fly to a route using $.post and I am currently faced with a mysterious error that I cannot get my head around.
Here's my route...
post "/share" do
    sid   = params[:sid]
    user  = (session[:level] == 1) ? params[:user] : session[:user]
    # Database
    require_relative "../../database/db.rb"
    db = DBShare.new
    db.share(sid, user)
end

Here's what I get when my $.post request is sent to the route...
!! Unexpected error while processing request: undefined method `close' for 1:Fixnum

The ajax call returns in the .fail(), but the database call is completed (I use Sequel for the database call which executes a stored procedure) - interestingly it calls the procedure twice on the first call, and only once on subsequent calls.
I thought it might be because my route was not returning a content header - so I added "success" after the db call.
This resulted in the jquery returning in the .success() block, but the database call was not completed.
Here's my jQuery call
// Share or unshare
$(document).on('click', '.share-unshare', function(event) {
    if (event.type == 'click') {
        var element     = $(this);
        var text        = $(this).text();
        var sid         = $(this).attr('sid');
        var r = '';

        // Unshared
        if (text == "Unshare") {
            r = confirm("Are you sure you want to unshare this?");
            if (r == false) {
                return false;
            }
            share(sid, element);

        // Shared
        } else {
            r = confirm("Are you sure?");
            if (r != false) {
                share(sid, element);
            }
        }

    }

    function share(sid, element) {
        var user = $('#details').attr('user');
        $.get('/share/', { 'sid' : sid, 'user': user })
            .success(function(data) {
               if (text == "Share") {
                   element.html("Unshare");
               } else {
                   element.html("Share");
               }
            })
            .fail(function() {
               alert("Something went wrong - unable to share / unshare");
            })
            .always();
    }

});

Here's the DB call (the procedure works fine through so not concerned with the PL/SQL)
    def share(sid, user)
        sql = "
        BEGIN
            pa_share.pr_share_handle(?, ?);
        END;
        "
        ds = $db_app[sql, sid, user]
    end

At this stage - I am thoroughly baffled! Does anyone have any ideas what it might be please?
Many thanks
Ash
UPDATE:
I managed to fix this issue by adding ds.insert after my params were bound in the db call..
def share(sid, user)
    sql = "
    BEGIN
        pa_share.pr_share_handle(?, ?);
    END;
    "
    ds = $db_app[sql, sid, user]
    **ds.insert**
end


text:
Q: Adding image over another image - bootstrap I want to add an image over an image.
For example, there's an image in the background and on top of that i need to add an image of a play button. Where the user can play the video by clicking on it. This is also shown on the Shopify homepage.

And the CSS is as follows:
.img-container {
    width: 100%;
    position: relative;
    display: inline-block;
    margin: 10px 5px 5px;
}

.img-text {
    width: 100%;
    display: block;
}

A: Use position: relative on .item and position: absolute on .img-text.
You should not need to use z-index on .img-text, but if it appears under .img-container, use it.
.img-text {
    /*position: absolute;*/ Wrong, see edit
    width: 100%;
    display: block;
    /*top: ?; bottom: ?; left: ?; right: ?; //to place it as you want.*/
}

.item{
    position: relative;
}

Edit : I misread your code, (badly indented :p)

So position: absolute on .img-container
.img-container {
    position: absolute;
    top: ?; bottom: ?; left: ?; right: ?; //to place it as you want.
}

Edit 2 :
A little jsFiddle, like the comment below :  http://jsfiddle.net/hsYwV/1/

A: The easiest way to do this is to set the image as a background.
html:

css:
        .item-active {
                width: 200px;
                height: 200px;
                background-image: url('http://roomista.com/uploads/hotel-gal/250_SunwayHotelHanoiSuperiorRoom.jpg');
    }

.img-text {
        position: relative;
        left: 75px;
        top: 75px;

        width: 50px;
        height: 50px;
      }

JScript:
$(".img-text").bind("click", function(){
          alert("play video");
           });

http://jsfiddle.net/J7qnF/2/


text:
Q: Unwanted space after figure environment When the figure environment directly follows a \[ ... \] environment an unwanted space occurs in the output. It obviously seems to be an endlinechar which is changed into a space.

\documentclass{article}
\begin{document}
\[ a  = b. \]
\begin{figure}
  figure
\end{figure}
Text\\
Text

\[ a  = b. \]
\begin{figure}
  figure
\end{figure}%
Text\\
Text

\end{document}

I know I can get rid of this adding a % after \end{figure} or generally by adding \ignorespaces to the figure environment with etoolbox's \AfterEndEnvironment.
My question is: is this a bug or expected behaviour? And if it is a bug who do I send a report?
EDIT: It seems my example was not really a minimal one. As it turns out the display environment is not necessary to get the space:
\documentclass{article}
\begin{document}
a%
\begin{figure}
  \caption{A}
\end{figure}
b

and

c\\
d%
\begin{figure}
  \caption{B}
\end{figure}
e

vs.

f%
\begin{figure}
  \caption{C}
\end{figure}%
g

\end{document}

In case I didn't make it clear enough: I am not interested in a way to avoid the space -- I know already how to do that. I admit that such information might be useful for other readers, though.
I rather want to know if this behaviour is to be expected of the figure environment or a bug?

A: Inserting the figure environment there is not the best idea. For example, even if you say \begin{figure}[htp] and the h option can be honored, the figure will not be printed just after the display.
A figure environment inserted in the mid of a paragraph cancels the space before it, rather than ignoring spaces after it. But in that case it has nothing to cancel out.
I always put my figure and table environment between paragraphs.
If you want to show a picture representing what's in the displayed formula, it's better to put the figure (not in a figure environment) inside the display: the environments available with amsmath allow for multiline displays.


text:
Q: How to split the data of NodeObject in Apache Flink I'm using Flink to process the data coming from some data source (such as Kafka, Pravega etc).
In my case, the data source is Pravega, which provided me a flink connector.
My data source is sending me some JSON data as below:
{"key": "value"}
{"key": "value2"}
{"key": "value3"}
...
...

Here is my piece of code:
PravegaDeserializationSchema<ObjectNode> adapter = new PravegaDeserializationSchema<>(ObjectNode.class, new JavaSerializer<>());
FlinkPravegaReader<ObjectNode> source = FlinkPravegaReader.<ObjectNode>builder()
    .withPravegaConfig(pravegaConfig)
    .forStream(stream)
    .withDeserializationSchema(adapter)
    .build();

final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<ObjectNode> dataStream = env.addSource(source).name("Pravega Stream");
dataStream.map(new MapFunction<ObjectNode, String>() {
        @Override
        public String map(ObjectNode node) throws Exception {
            return node.toString();
        }
    })
    .keyBy("word")    // ERROR
    .timeWindow(Time.seconds(10))
    .sum("count");

As you see, I used the FlinkPravegaReader and a proper deserializer to get the JSON stream coming from Pravega.
Then I try to transform the JSON data into a String, KeyBy them and count them.
However, I get an error:
 The program finished with the following exception:

Field expression must be equal to '*' or '_' for non-composite types.
        org.apache.flink.api.common.operators.Keys$ExpressionKeys.<init>(Keys.java:342)
        org.apache.flink.streaming.api.datastream.DataStream.keyBy(DataStream.java:340)
        myflink.StreamingJob.main(StreamingJob.java:114)

It seems that KeyBy threw this exception.
Well, I'm not a Flink expert so I don't know why. I've read the source code of the official example WordCount. In that example, there is a custtom splitter, which is used to split the String data into words.
So I'm thinking if I need to use some kind of splitter in this case too? If so, what kind of splitter should I use? Can you show me an example? If not, why did I get such an error and how to solve it?

A: I guess you have read the document about how to specify keys
Specify keys
The example codes use keyby("word") because word is a field of POJO type WC.
// some ordinary POJO (Plain old Java Object)
public class WC {
  public String word;
  public int count;
}
DataStream<WC> words = // [...]
DataStream<WC> wordCounts = words.keyBy("word").window(/*window specification*/);

In your case, you put a map operator before keyBy, and the output of this map operator is a string. So there is obviously no word field in your case. If you actually want to group this string stream, you need to write it like this .keyBy(String::toString)
Or you can even implement a customized keySelector to generate your own key.
Customized Key Selector


text:
Q: Use a Username from a Deleted Trailhead Playground I have a user that was on a Trailhead playground, i deleted the playground some time ago, and now i want to use a username name that was on that playground on a production org is possible?
Regards

A: When you remove a Trailhead org from your account, it is not deleted immediately. Instead, it will sit around waiting for the timeout period for reclaiming inactive orgs (between six and twelve months, last I checked), and then eventually be freed up. You can log in to that org via the normal login page, assuming you have, or can recover, the password, then manually change the user name, or wait until the org is deleted in about a year. Support may be able to reset your password for you if you ask, but they can only do so if it would go to the email address on the user account. You can also try the normal password reset function available from the main login page.


text:
Q: Change Shipping method TITLE after order in woocommerce I want change the shipping method title (view image) after create the order. I using hook "woocommerce_thankyou", but i can't change the title of existing shipping.
image with i want change
I find this code, but with this code add a new shipping method but it's not what i want, because after this code i have 2 shipping method.
$item = new WC_Order_Item_Shipping();
$item->set_method_title( "SEUR Estándar" );
$item->set_method_id( "seur" ); // set an existing Shipping method rate ID
//$item->set_total( $new_ship_price ); // (optional)
//$item->calculate_taxes($calculate_tax_for);

$order->add_item( $item );

$order->save();

Thanks for your help.

A: If I understand correctly, you want to change the shipping method TITLE only in admin area ?
For example :
=> In WC settings, shipping method title = SEUR Estándar (this title is displayed to customers during checkout and on emails)
=> In WC admin, when you handle the order, you want SEUR Estándar is changed to SEUR
For this, you can try something like that (not tested), hooking only the displayed title
add_filter( 'woocommerce_shipping_method_title', function( $method_title, $method_id ) {
    if ( ! is_admin() || ! 'shop_order' === get_post_type() ) { // change applied only on admin order page
        return $method_title;
    }
    if ( $method_id == 'seur' ) { // change condition to match what you need
        $method_title = 'SEUR'; // new method title
    }
    return $method_title;
}, 10, 2 );

If you want to change the shipping method title in other areas, think about what it is easier and need less job : change only for customer in front end, change only for admin, change in emails... ? Then adapt conditions in above snippet.

A: I find this solucion and thanks for all Jo Kolov
foreach($rates as $rate_id => $rate) {
    if ( 'seur' === $rate->method_id ) {
        $rates[$rate_id]->label = __( 'SEUR Estándar', 'woocommerce' );
    }
}


text:
Q: I deleted my Minecraft resource pack folder? I deleted my Minecraft resource pack folder, how do I get it back?
I'm using a Mac and Minecraft version 1.8.

A: Resource pack as in your texturepack folder?
Have you tried going into your game, going to options, Texture Packs, and clicking Open Folder? That is one sure way to get it to work. Otherwise, go into your ~/Library/Application Support/minecraft and make a new folder called resourcepacks.
Or one thing you can do is this.

*

*Open the Launcher

*Go down to Edit Profile

*Click Versions

*Click 1.7.10

*Click Update and then launch the game.

What this should do is put back any folders that were deleted or are missing. Afterwards, repeat the steps above, but change the 1.7.10 to 1.8 and you should be good to go. If you have any other problems, I will be willing to help you.

A: Simply recreate the folder yourself in the game directory:
~/Library/Application Support/minecraft/resourcepacks


text:
Q: How to change the overall Focus color for all the components? I want to change the focus color which is blue by default to some custom color? What is the simple way to do this? Thanks in advance.

A: you want to make a StateListDrawable and set it as the background colour View.setBackgroundResource(R.id.drawable_name): in XML it is:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@color/button_disabled"/>
<item android:state_pressed="true" android:drawable="@color/button_pressed"/>
<item android:state_selected="true" android:drawable="@color/button_selected"/>
<item android:state_focussed="true" android:drawable="@color/button_focussed"/>
<item android:drawable="@color/button_transparent"/>

the drawables can be defined colours in res/values/colors.xml e.g.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--  buttons -->
    <color name="button_enabled">#88000000</color>
    <color name="button_disabled">#88666666</color>
    <color name="button_pressed">#88ff8800</color>
    <color name="button_selected">#cc0088bb</color>
    <color name="button_focussed">#cc8800bb</color>
    <color name="button_transparent">#00000000</color>
</resources>

the drawable can be used the same way you would use any other drawable resource


text:
Q: ggplotly tooltip is showing data twice I have 2 datasets included in one chart using ggplot. I am using ggplotly to create a tooltip but the information in the tooltips for the 2 points is showing twice. The following code is a little lengthy but will recreate the chart:
AreaName <- c("A", "B", "C", "A", "B", "C")
Timeperiod <- c("2018", "2018", "2018", "2019", "2019", "2019")
Value <- c(11.5, 39.3, 9.4, 14.2, 40.7, 19.1)
df <- data.frame(cbind(AreaName, Timeperiod, Value), stringsAsFactors = F)
df$Value <- as.numeric(df$Value)

AreaName <- c("A", "A")
Timeperiod <- c("2019", "2020")
qtr <- c("Q1-Q2", "Q1-Q2")
Value <- c(15.6, 10.2)
df2 <- data.frame(cbind(Timeperiod, qtr, AreaName, Value), stringsAsFactors = F)
df2$Value <- as.numeric(df2$Value)

ggp <- ggplotly(ggplot(data = df, aes(x=Timeperiod, y=Value, group = AreaName, colour = AreaName, text = paste("Area name: ", AreaName, "
Time period: ", Timeperiod, "
Rate: ", round(Value,1), "per 100,000"))) +
  geom_line() +
  geom_point() +
  geom_point(data = df2, aes(shape = c(paste(AreaName, qtr, Timeperiod)),text = paste("Area name: ", AreaName, "
Quarter: ", qtr, "
Time period: ", Timeperiod, "
Rate: ", round(Value,1), "per 100,000"))) +
  scale_shape_manual(values = c(18, 17)) +
  theme(axis.text.x = element_text(vjust = 0.5), axis.title.x = element_blank()) +
  labs(y = "Crude rate per 100,000 persons all ages", colour = "Area", shape = "") +
  guides(shape = guide_legend(order = 2),colour = guide_legend(order = 1)) +
  expand_limits(y=0), tooltip = "text")

ggpNames <- unique(df$AreaName)
legs <- paste(df2$AreaName, df2$qtr, df2$Timeperiod)
ggpNames <- c(ggpNames,legs)

for (i in 1:length(ggp$x$data)) { # this goes over all places where legend values are stored
    n1 <- ggp$x$data[[i]]$name # and this is how the value is stored in plotly
    n2 <- " "
    for (j in 1:length(ggpNames)) {
        if (grepl(x = n1, pattern = ggpNames[j])) {n2 = ggpNames[j]} # if the plotly legend name contains the original value, replace it with the original value
    }
    ggp$x$data[[i]]$name <- n2 # now is the time for actual replacement
    if (n2 == " ") {ggp$x$data[[i]]$showlegend = FALSE}  # sometimes plotly adds to the legend values that we don't want, this is how to get rid of them, too
}

ggp %>% config(displaylogo = FALSE, modeBarButtonsToRemove = list("autoScale2d", "resetScale2d","select2d", "lasso2d", "zoomIn2d", "zoomOut2d", "toggleSpikelines", "zoom2d", "pan2d"))

ggp

Does anyone have an elegant solution to this?
Thanks

A: Do not define text in geom_point for the second dataframe df2.  Then you will get only one tooltip for those two points.
  ggp <- ggplotly(ggplot(data = df, aes(x=Timeperiod, y=Value, group = AreaName, colour = AreaName, text = paste("Area name: ", AreaName, "
Time period: ", Timeperiod, "
Rate: ", round(Value,1), "per 100,000"))) +
                    geom_line() +
                    geom_point() +
                    geom_point(data = df2, aes(shape = c(paste(AreaName, qtr, Timeperiod)) #,
                                               #text = paste("Area name: ", AreaName, "
Quarter: ", qtr, "
Time period: ", Timeperiod, "
Rate: ", round(Value,1), "per 100,000")
                                               )) +
                    scale_shape_manual(values = c(18, 17)) +
                    theme(axis.text.x = element_text(vjust = 0.5), axis.title.x = element_blank()) +
                    labs(y = "Crude rate per 100,000 persons all ages", colour = "Area", shape = "") +
                    guides(shape = guide_legend(order = 2),colour = guide_legend(order = 1)) +
                    expand_limits(y=0), tooltip = "text")

  ggpNames <- unique(df$AreaName)
  legs <- paste(df2$AreaName, df2$qtr, df2$Timeperiod)
  ggpNames <- c(ggpNames,legs)

  for (i in 1:length(ggp$x$data)) { # this goes over all places where legend values are stored
    n1 <- ggp$x$data[[i]]$name # and this is how the value is stored in plotly
    n2 <- " "
    for (j in 1:length(ggpNames)) {
      if (grepl(x = n1, pattern = ggpNames[j])) {n2 = ggpNames[j]} # if the plotly legend name contains the original value, replace it with the original value
    }
    ggp$x$data[[i]]$name <- n2 # now is the time for actual replacement
    if (n2 == " ") {ggp$x$data[[i]]$showlegend = FALSE}  # sometimes plotly adds to the legend values that we don't want, this is how to get rid of them, too
  }

  ggp %>% config(displaylogo = FALSE, modeBarButtonsToRemove = list("autoScale2d", "resetScale2d","select2d", "lasso2d", "zoomIn2d", "zoomOut2d", "toggleSpikelines", "zoom2d", "pan2d"))

  ggp


text:
Q: Conditional Formik Form Validation Using Yup I have a form field (shapes) that should be required when at least one of two other fields (colors & sizes) next to it are filled out. I've tried using a logical OR (||) operator, but it doesn't seem to be working. At the moment, the shapes field is only dependent on the colors field; however, if I were to switch the places of the 'colors' and 'sizes' in the OR condition, the shapes field is then only dependent on the sizes field.
This is how my code currently looks:
const formSchema = Yup.object().shape({
  colors: Yup.string().when('sizes', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
  sizes: Yup.string().when('colors', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
  shapes: Yup.string().when('colors' || 'sizes', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
}, ['colors', 'sizes']);

I have a hunch that the way how I structured the OR condition for shapes is the issue. I'd appreciate it if someone could help me understand why my code above isn't working the way I'm desiring.

A: The following code achieves what I was attempting earlier:
const formSchema = Yup.object().shape({
  colors: Yup.string().when('sizes', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
  sizes: Yup.string().when('colors', {
    is: (value) => Boolean(value),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
  shapes: Yup.string().when(['colors', 'sizes'], {
    is: (colors, sizes) => Boolean(colors) || Boolean(sizes),
    then: Yup.string().required,
    otherwise: Yup.string().nullable(),
  }),
}, ['colors', 'sizes']);


text:
Q: ERROR: Loading local data is disabled - this must be enabled on both the client and server sides I don't understand the responses that others have provided to similar questions except for the most obvious ones, such as the one below:
mysql> SET GLOBAL local_infile=1;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | ON    |
+---------------+-------+
1 row in set (0.01 sec)

By this I mean the exact code was provided. I'd greatly appreciate if someone could walk me through, step by step, what I need to do to enable local data on the "client" side and "server" side. It seems like I've enabled local data on the client side, but I don't know what instructions I need to give my computer to enable the "server side". I'm not tech savvy at all, and I just want to be able to get to the point where the data has been uploaded into MySQL workbench.
ERROR 3948 (42000): Loading local data is disabled; this must be enabled on both the client and server sides

CREATE TABLE toys (
uniq_id VARCHAR(1000),
product_name VARCHAR(1000),
manufacturer VARCHAR(1000),
price VARCHAR(1000),
number_available_in_stock VARCHAR (1000),
number_of_reviews INT,
number_of_answered_questions INT,
average_review_rating VARCHAR(1000),
amazon_category_and_sub_category VARCHAR(1000),
customers_who_bought_this_item_also_bought VARCHAR(1000),
description VARCHAR(1000),
product_information VARCHAR(1000),
product_description VARCHAR(1000),
items_customers_buy_after_viewing_this_item VARCHAR(1000),
customer_questions_and_answers VARCHAR(1000),
customer_reviews VARCHAR(1000),
sellers VARCHAR(1000)
);

LOAD DATA LOCAL INFILE '/Users/BruddaDave/Desktop/amazonsample.csv' INTO TABLE toys
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(uniq_id, product_name, manufacturer, price, number_available_in_stock, number_of_reviews, number_of_answered_questions, average_review_rating, amazon_category_and_sub_category, customers_who_bought_this_item_also_bought, description, product_information, product_description, items_customers_buy_after_viewing_this_item, customer_questions_and_answers, customer_reviews, sellers)
;

I just want to be able to import a .csv file into MySQL using the command line shell.

A: my.cnf file:
[client]
local_infile=1

From the official MySQL 8.0 documentation.

A: Type the following command on the terminal -
SHOW GLOBAL VARIABLES LIKE 'local_infile';

If it's 0 oe false then type the following command -
SET GLOBAL local_infile = TRUE;

A: For default installation of MySQL 8.0.20:
i) Look for the initialization file located at C:\ProgramData\MySQL\MySQL Server 8.0\my.ini.
ii) Open my.ini file with notepad.
iii) Look for the headers [client], [mysql] under the CLIENT section & [mysqld] under the SERVER section.
iv) Add the following statement under each header:
local_infile=ON
v) Save the file and restart MySQL80 service under the Windows local services.
It should work.

A: You may check the local_infile is disabled or enable. So, you try this-
mysql> show global variables like 'local_infile';

if it shows-
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  |  OFF  |
+---------------+-------+
(this means local_infile is disable)

then enable with this-
mysql> set global local_infile=true;

Then check again and quit from mysql server with this-
mysql> exit

Now you have to connect/login server with local_infile. For this run this code from terminal command line-
mysql --local_infile=1 -u root -ppassword DB_name

now load the data from local file-
mysql> load data local infile 'path/file_name.extention' into table table_name;

It's work on my pc. you may try this. thanks.

A: as the question said this must be enable in client and server both, so in my case i was able to enabled that in server side
SET GLOBAL local_infile = true;

using above(it was not permanent when restarting server again it was OFF state) so i add below in my.cnf
[mysqld]
local-infile

this works and server side is okay with that, so in the client side(mine was a spring application) i have to add
allowLoadLocalInfile=true

this at the end of connection string. after adding this worked fine
below is my connection string (you can see that in the end of string)
jdbc.url=jdbc:mysql://127.0.0.1:<port>/<dbname>?autoReconnect=true&zeroDateTimeBehavior=convertToNull&useUnicode=yes&characterEncoding=UTF-8&allowLoadLocalInfile=true

A: how global variables like 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | OFF   |
+---------------+-------+

set global local_infile=true;

exit

if you don't have any password for your mysql

$->>   sudo mysql --local_infile=1 -u root -p

if you have password for your mysql

$->>   sudo mysql --local-infile=1 -u root

now done your work

LOAD DATA LOCAL INFILE
'/home/soyanswartz/Documents/Study/My_Course/Learn_SQL/05_Day/machine-learning-with-sql/data/weather_data.csv'
INTO TABLE TBL_WEATHER
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

A: This is what I had to do fix this issue on Ubuntu 20.04 / MySQL 8:

*

*nano /etc/mysql/mysql.conf.d/mysqld.cnf

*in the [mysqld] section add this line:

local_infile    = 1

*add to the bottom of the file these two lines:

[client]

local_infile    = 1

*run this command from my client: SET GLOBAL local_infile=1;
NOTE: revised the above to include extra step to make sure local_infile=1 is added to the [mysqld] section. This saves me having to run SET GLOBAL local_infile=1; after each reboot.

A: If LOCAL capability is disabled, on either the server or client side, a client that attempts to issue a LOAD DATA LOCAL statement receives the following error message:
ERROR 3950 (42000): Loading local data is disabled; this must be
enabled on both the client and server side

I met the same issue when I want to load the text file pet.txt into the pet table following a tutorial of Mysql:https://dev.mysql.com/doc/refman/8.0/en/loading-tables.html
After searching online, I fixed it by these steps:

*

*set the global variables by using this command:

mysql> SET GLOBAL local_infile=1;
Query OK, 0 rows affected (0.00 sec)

*quit current server:

mysql> quit
Bye

*connect to the server with local-infile system variable :

mysql --local-infile=1 -u root -p1

This variable controls server-side LOCAL capability for LOAD DATA statements. Depending on the local_infile setting, the server refuses or permits local data loading by clients that have LOCAL enabled on the client side.
To explicitly cause the server to refuse or permit LOAD DATA LOCAL statements (regardless of how client programs and libraries are configured at build time or runtime), start mysqld with local_infile disabled or enabled, respectively. local_infile can also be set at runtime.

*use your Database and load the file into the table:

mysql> use menagerie
Database changed
mysql> load data local infile '/path/pet.txt' into table pet;
Query OK, 8 rows affected, 7 warnings (0.00 sec)

Does it work?
References:
https://dev.mysql.com/doc/refman/8.0/en/load-data-local-security.html
https://dev.mysql.com/doc/refman/8.0/en/source-configuration-options.html#option_cmake_enabled_local_infile
https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_local_infile

A: I just had this problem with PyMySQL and SQLAlchemy. Here are some things that got this to work...

*

*Here is how I connect to the DB Engine...
 connect_args = ssl_args
 connect_args['local_infile'] = True
 qry_engine = create_engine('mysql+pymysql://' + db_uid + ':' + db_pw + '@' + db_addr, connect_args=connect_args,
                            pool_recycle=3600, echo=False)

Note that ssl_args is a dictionary that contains my ssl parameters (you can leave this out if not connecting with SSL but connect_args is expecting a dictionary.)

*When loading data, I have to run the following...
 sql_stmt = 'SET GLOBAL local_infile = TRUE'
 common.qry_engine.execute(text(sql_stmt))
 sql_stmt = "LOAD DATA LOCAL INFILE '" + filepath + "' INTO TABLE " + self.tst_tbl.tbl.fullname
 common.qry_engine.execute(text(sql_stmt))

When I try this without that SET GLOBAL command I get that "must be enabled on both the client and server side" message.

A: After trying all the steps outlined above, I was still getting Error Code: 2068. LOAD DATA LOCAL INFILE file request rejected due to restrictions on access. The solution was to eliminate the word "LOCAL" in the SQL statement:
load data infile...

A: For those who are stuck at step 3:

mysql --local-infile=1 -u root -p1

like I was, this is what I did:

*

*type

cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"

in the command prompt.

*type

mysql --local_infile=1 -u root -pABC menagerie

where ABC is your password for MySQL and menagerie is the database you're working on
(replace ABC & menagerie with whatever is your password & database name respectively)

*MySQL will open in command prompt. You can type your commands like:

mysql> use menagerie

Database changed

mysql> load data local infile '/path/pet.txt' into table pet;

Query OK, 8 rows affected, 7 warnings (0.00 sec)

and it should work...

A: on Ubuntu 20.04 / MySQL 8:
This approach resolved the issue for me:

*

*systemctl stop mysql

*nano /etc/mysql/mysql.conf.d/mysqld.cnf

*unter [mysqld] add local_infile =1

*systemctl start mysql or restart mysql if you did stop it.

A: Executing this global setting change in SQL script should help
SET GLOBAL local_infile=1;


text:
Q: I get an error message when unlocking an APFS FileVault volume with an Institutional Recovery Key I'm testing an MDM solution (with an in house Server.app MDM instance), which enforces FileVault. It's setup with both an Institutional Recovery Key (IRK) and a Personal Recovery Key (PRK). The last one is also saved to MDM.
Basically, we generated a keychain like this, exported the certificate from the keychain, and added it to an MDM profile (we're using Server.app's MDM).
It's working great. When I do a diskutil apfs listCryptoUsers diskNxM, I get all the users I expect, including an user of type Institutional Recovery User and one with type Institutional Recovery External Key. Resetting password via Open Directory works fine. Unlocking the drive with the PRK works fine.
And now I'm testing to unlock the volume with the said IRK.
I booted via Recovery (cmd+R), and when I execute diskutil apfs unlockVolume /dev/diskNsM -recoveryKeyChain /Volumes/RecoveryDrive/FileVaultMaster.keychain (the keychain is unlocked, and the drive is correct), I get this error:
Error unlocking APFS Volume: The external-to-APFS security system's credential-unwrap
operation failed (-69534)

I checked unlocking the keychain using a different password, and that failed directly. Someone here suggested to remove the certificate from the keychain. This didn't work either. I double checked the volume was APFS. It was.
Any idea's (besides creating a new FileVault Master keychain and do the whole process one more time)?

A: The thing I forgot to mention was I didn't generate the Keychain myself. I started off with a keychain with a certificate and private key that I could unlock, and an MDM profile with the exported certificate.
Because I couldn't find another solution, I created a new Keychain. I used this Apple Support Document. I didn't remove the private key, because I deploy it by exporting the certificate, and distributing it via MDM.
However, I did use the "Use the private key to unlock a user's startup disk" procedure from this document to unlock the volume and it worked!
So this is not an actual answer to the asked question, but certainly a solution. I double checked the computer encrypted with the old keychain certificate with this procedure, but got the same error message. So probably there was something wrong with the keychain and/or certificate...


text:
Q: How can I make localStorage data persistent across pages? I'm building a sticky notes page. I want to save the created notes. The data is being saved with localStorage(), which make the data persistent on page reload, but not when a surfing to other pages. How can I make make the notes still being saved, when returning from another page?
   var notes, count = 0;

function saveNotes() {
    var notesArray = [];
    notes.find("li > div").each(function (i, e) {
        var title = $(e).find("input.note-title");
        var content = $(e).find("textarea.note-content");

        notesArray.push({ Index: i, Title: title.val(), Content: content.val() });
    });

    var jsonStr = JSON.stringify(notesArray);

    localStorage.setItem("notes", jsonStr);
}

function addNoteEvent(noteElement) {
    var div = noteElement.children("div");
    var closeIcon = div.find("i");

    div.focus(function () {
        closeIcon.removeClass("hidden");
    });

    div.hover(function () {
        closeIcon.removeClass("hidden");
    }, function () {
        closeIcon.addClass("hidden");
        saveNotes();
    })
}

function addNewNote(className, title, content) {

    notes.append("

" +
                    "<input class='note-title' placeholder='Untitled'/>" +
                    "" +
                    "<textarea class='note-content' placeholder='Your content here'/>" +
                "

");

    var newNote = notes.find("li:last");
    newNote.find("i").click(function () {
        newNote.remove();
        saveNotes();
    });

    addNoteEvent(newNote);

    if (title) {
        newNote.find("input.note-title").val(title);
    }
    if (content) {
        newNote.find("textarea.note-content").val(content);
    }
    saveNotes();
}

function loadNotes() {
    var storedNotes = localStorage.getItem("notes");
    if (storedNotes) {
        var notesArray = JSON.parse(storedNotes);
        count = notesArray.length;

        var i;
        for (i = 0; i < count; i++) {
            var storedNote = notesArray[i];
            addNewNote(storedNote.Class, storedNote.Title, storedNote.Content);
        }
    }
}

$(document).ready(function () {
    notes = $("#notities .container > .row");

    loadNotes();
    $(".btnNew").click(function () {
        addNewNote();
    });

    if (count === 0) {
        $(".btnNew").click();
    }
});

A: localStorage is persistent across pages in the same domain.  The normal same-origin rules are applied to DOM storage, so as long as your pages are on the same domain, the data will be accessible.


text:
Q: How to deploy  metadata? I am trying to deploy RecordTypes from one sandbox to another. Here's my XML
<types>
    <members>My_Opportunity</members>
    <name>RecordTypes</name>
</types>

Fails to deploy, any idea what is wrong with this?

A: Try the following:
<types>
    <members>Opportunity.My_Opportunity</members>
    <members>Opportunity.Other_Opportunity</members>
    ...
    <name>RecordType</name>
</types>


text:
Q: Solving an integer linear programming problem without a graph I am new to linear prorgramming and so far I have been solving LP problems with the help of a graph solution. However, when there are more than 2 variables obviously I can't plot them on the graph.
This is the case in this exercise:

I am tyring to at least make a a correct model before I attempt to solve it.
This is what I have done so far:
ao - orange % in 1 litre of A , bo - orange % in  1litre of B, ac - cranberry % in C etc....
a, b, c, d, e - represent a litre of each drink respectively
40ao + 5bo + 100co >=20
40ag + 10bg + 100dg >=10
20bc >=5

a<=200, b<=400, c<=100, d<=50, e<=800

a + b + c + d + e = 500

a, b, c, d, e > 0

minimise: 1.5a + 0.75b + 2c + 1.75d + 0.25e

Is this the correct model for the problem? If not, please let me know if I have made any mistakes or missed/skipped something important.

A: To define the variables was a good idea. You need additional relations between the variables a,b,c,d,e and the others. But it is not easy to find them, because of the different units. And it is hard to say, if the first three constraints  are right. To simplify your model, you can use only 5 variables.
$X$: Amount of drink X in the punch (in litres) $\ ,\forall \ X \in \{A,B,C,D,E\}$
Equivalent to your definition.
Constraint for orange juice:
$0,4A+0.05B+C\geq 100$
The punch contains at least $20\%$ orange juice. $20\%$ of 500 litres is 100 litres.
Constraint for grapefruit juice:
$0.4A+0.1B+D \geq 50$
Constraint for cranberry juice:
$0.2B \geq 25$
My other constraints and my pbjective function are identical to yours $\color{blue}{\checkmark}$.


text:
Q: Einstein summation with gamma matrices Given that
$$\gamma_{\mu}\gamma_{\nu}+\gamma_{\nu}\gamma_{\mu}=2g_{\mu\nu}I$$
Where I is the 4x4 identity matrix, and
$$\gamma^{\mu\dagger}=\gamma^0\gamma^{\mu}\gamma^0$$
Use $|\gamma^{\mu}p_{\mu}\psi|^2$ to show that from the Dirac equation $\gamma_{\mu}p^{\mu}\psi=m\psi$, the relation $E^2=p^2+m^2$ can be obtained.
The $\gamma$ matrices are 4x4 matrices and $\psi$ is a 'bi-spinor' which is an object I don't really understand, but is apparently a column matrix with four complex components. At a guess the way to find the magnitude is to multiply $\gamma^{\mu}p_{\mu}\psi$ by the Hermitian conjugate, which gives
$$(\gamma^{\mu}p_{\mu}\psi)(\gamma^{\mu}p_{\mu}\psi)^{\dagger}=\gamma^{\mu}(p_{\mu}\psi)\gamma^{\mu\dagger}(p_{\mu}^{\dagger}\psi^{\dagger})$$
$$=\gamma^{\mu}p_{\mu}\psi(\gamma^0\gamma^{\mu}\gamma^0)p_{\mu}^{\dagger}\psi^{\dagger}$$
Can't see what I can do from there, so I also tried rearranging the Dirac equation to:
$$(\gamma_{\mu}p^{\mu}-m)\psi=0$$
The multiplying that by $(\gamma^{\mu}p_{\mu}+m)$, which it seems like it might also possibly give me the magnitude:
$$=(\gamma^{\mu}\gamma_{\mu}p_{\mu}p^{\mu}-m\gamma^{\mu}p_{\mu}+m\gamma_{mu}p^{\mu}-m^2)\psi$$
Although I'm not entirely sure that's correctly multiplied out, because it doesn't give me what I'm after - in either of the approaches I've tried, where have I gone wrong?


text:
Q: Factorization of a map through a covering space Let $A\overset{f}{\to} B$ be a continuous map with $B$ sufficiently connected to admit a universal cover $\widetilde B$. Consider the covering map $\widetilde B/f_\ast\pi_1(A,a)\to B$. The fundamental group of the quotient is $f_\ast\pi_1(A,a)$, so the lifting criterion ensures $f$ factors as $A\to\widetilde B/f_\ast\pi_1(A,a)\to B$.
Why is the first factor of this factorization a 1-connected map (equivalently, why does it have connected homotopy fibers)?

A: I think $A$ should be path connected if we wish to use the lifting criterion.
So $\bar{f}$, the lift, induces a bijection on $\pi_0$ because the universal cover is path connected, hence this quotient is. On $\pi_1$, the map is surjective since the covering map induces the inclusion of $f_*\pi_1(A)$ and obviously $\pi_1(A)$ surjects onto $f_*\pi_1(A)$


text:
Q: Excluding certain fields from an SQL SUM query I am using the following SUM query with SQL
SELECT SUM(cost) as total FROM sales where passport =

How would I exclude certain records from the calculation, for example where paid = 1?

A: Do you mean like this ?
SELECT SUM(cost) as total FROM sales where (passport = $myPassport AND paid <> 1)

A: Simply
SELECT SUM(cost) as total
FROM sales
WHERE passport = ?
 AND paid <> 1

You may also be looking for a group by here
SELECT passport, SUM(cost) as total
FROM sales
WHERE passport = ?
 AND paid <> 1
GROUP BY passport

A: SELECT SUM(cost) as total FROM sales where passport = "12345" and paid <> 1

A: SELECT SUM(cost) as total
FROM sales
WHERE passport = 12345
AND paid <> 1

A: did you mean to get only total that equal to  1 ?
USE : HAVING total = 1

A: Sometimes it's useful to use IF statements like that:
SELECT COUNT(mct.id), SUM(mct.cost * IF(mct.status = 1, 0, 1))
FROM my_cool_table mct;

In that way when status field equals 1 cost will be multiplied by 0 and excluded from SUM but row will not be excluded for count function.
Another way is to use select inside SUM, but it will be not so useful.


text:
Q: Add options to a html  on content script Noobie here... trying to figure out something. I'm working on this chrome extension and I injected some html on the page and the next step would be to read all the page finding some text and adding it as options on the select input fields I injected. This is part of my manifest:

    "content_scripts" : [
        {
            "run_at": "document_end",
            "js" : [
                "js/main.js"
            ],
            "css" : [
                "css/main.css"
             ],
            "matches" : ["https://streamyard.com/*"]
        }

this is my content script:

var isHtmlDeployed = false;
var x=0;

//read the html file
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", chrome.extension.getURL('../includes/sceneSettings.html'), true);
xhr.send();
fillLayoutCombo();

//Inject the html file
function handleStateChange(){
    if (xhr.readyState=4 && xhr.responseText !='' &xhr.status==200 && isHtmlDeployed==false){
        var newHtml = document.createElement('div');
        newHtml.innerHTML = xhr.responseText;
        document.body.appendChild (newHtml);
        isHtmlDeployed = true;
    }
}

//add options
function fillLayoutCombo(){
    for(var i=0;i<=9;i++){
        var opt = document.createElement('option');
        opt.value = 'Solo Layout';
        opt.innerHTML = 'Solo Layout';
        console.log('select[id="cboSceneType'+i+'"]');
        select = document.querySelector('[id="cboSceneType'+i+'"]');
        select.appendChild(opt);
    }
}

I can't figure out why when I get to fillLayoutCombo() function the html I injected is still not loaded so I end up select = document.querySelector('[id="cboSceneType'+i+'"]'); being null and get a error. Even with my manifest saying the script should run at the end of the page load. What can I do to fix this situation (while writting I just realized that 'document_end' is doing nothing after all the html will only be injected when the script run so am I having a problem with assynchronous xmlhttprequest? How to solve it?)
Thx for your help.

A: Just to set people in the solution. I just moved the  the call to fillLayoutCombo as the last step of handleStateChange.
Problem was solved
Thank you guys!


text:
Q: New user roles typo3 neos I need to add new user roles, such as "TYPO3.Neos:Creator"
Typo3-neos Currently supported roles:"TYPO3.Neos:Editor", "TYPO3.Neos:Administrator". How can I do it?

A: Not sure, but it seems available roles are not stored in database, but rather are gathered from yaml configuration files (and stored in cache??).
So, add a role in any Policy.yaml file, like:
roles:
  'My.Package:CreatorOfDoomRole':
    privileges: []

After that you can use the flow CLI command ./flow user:addrole <username> <role> to add a new role to a user (the roles are stored as comma-separated list in table typo3_flow_security_account, field roleidentifiers).
(Some more info about how yaml is cached: "The yaml files are cached, in development context that cache should be purged on every request (and on master that's a bit optimized so they will only be flushed in development context if there was really a change to the yaml). Stored in file: Data/Temporary/Production/Configuration/ProductionConfigurations.php")


text:
Q: Having both value and placeholder possible in form input? I'm looking to have both value and placeholder at an input field... the value would be more like twitter's @mention... it's the text the user need to have to start the input, and the placeholder gives hint to what user needs to type.
It seems like this can't be accomplished with only html

But is there anyway to make this possible in javascript or other means?

A: Use either two input fields (one with value and one with hint) or just use a label to tell the user the string always starts with @mention (or something else).
In the code to handle the input you then append both strings.


text:
Q: File owner changed after editing it [root@MGWSDT_FEWS ~]# ll file
-rw-r--r-- 1 root bill 0 Aug 14 17:28 file
[root@MGWSDT_FEWS ~]# su - bill
$ vi /root/file

I edited this file and wq!
Now bill becomes the file owner:
$ ll /root/file
-rw-r--r-- 1 bill bill 16 Aug 14 17:29 /root/file

Why? So strange!

A: bill cant edit the file. hess part of the group which only has read access.
So switching to bill you would expect a permissions error when you try and write.
In this case bill is also the directory owner, so whats actually happening is the file is being removed, and recreated now with bill as the owner.
:w  !sudo tee %

would write as root and keep the permissions


text:
Q: Serilog outputTemplate for Microsoft.Extensions.Logging Category Samples in aspnet core docs have logger category in output (TodoApi.Controllers.TodoController). Which Serilog's outputTemplate use have same output? None of {Logger}{Category}{EventId} works.

A: {SourceContext} its name (https://github.com/serilog/serilog-extensions-logging/issues/9).


text:
Q: Finding minimum time from record and splitting it in LINQ We have a database of swimmers with their times.
To create a ranking we want to get the fastest time of each athlete.
var rankings = (
    from r in _db.Results
        orderby r.swimtime
        group r by r.athleteid into rg
        select new
        {
            AthleteId = rg.Key,
            FirstName = rg.Min(f2 => f2.Athlete.firstname),
            Swimtime = rg.Min(f8 => f8.swimtime),
            hours = rg.Min(f9 => f9.swimtime.Hours),
            minutes = rg.Min(f10 => ("00" + f10.swimtime.Minutes.ToString()).Substring(("00" + f10.swimtime.Minutes.ToString()).Length - 2)),    // to get 2 digits in minutes
            seconds = rg.Min(f11 => ("00" + f11.swimtime.Seconds.ToString()).Substring(("00" + f11.swimtime.Seconds.ToString()).Length - 2)),    // to get 2 digits in seconds
            milliseconds = rg.Min(f12 => (f12.swimtime.Milliseconds.ToString() + "00").Substring(0, 2)),    // because miliseconds are not always filled
        }
    );

Now the ranking is created correctly, however the time shown is not.
I know what the problem is, but don't know how to fix it:
In the database we have a swimmer that has 2 times : 00:01:02:10 (1min2sec10) and 00:00:56:95 (56sec95)
The result we get is the minimum for the minutes (=00), the minimum for the seconds (=02) and the minimum for the milliseconds (=10)
Resulting in a time of 00:00:02:10.
What we should get is the hours,minutes,seconds and milliseconds of the fastest time (=00:00:56:95)
Anyone any ideas on how to fix this ?

A: This should do the trick:
from result in db.Results
group result by result.AthleteId into g
let bestResult = (
    from athleteResult in g
    orderby athleteResult.SwimTime
    select athleteResult).First()
orderby bestResult.SwimTime
select new
{
    AthleteId = bestResult.Athlete.Id,
    FirstName = bestResult.Athlete.FirstName,
    BestTime = bestResult.SwimTime,
}

The query fetches the best result from a group (all results from a single athelete), orders by that result, and uses that result to populate the final result.

A: Stay away from calling .First on groups, as that can cause automatic requerying due to the difference between LINQ's group (key and elements) vs SQL's group (key and aggregates).
Instead, get the minSwimTime once and let it be.
var rankings =
  from r in _db.Results
  group r by r.athleteid into rg
  let minSwimTime = rg.Min(x => x.swimtime)
  select new
  {
    AthleteId = rg.Key,
    FirstName = rg.Min(f2 => f2.Athlete.firstname),
    Swimtime = minSwimTime,
    hours = minSwimTime.Hours,
    minutes = ("00" + minSwimTime.Minutes.ToString()).Substring(("00" + minSwimTime.Minutes.ToString()).Length - 2),    // to get 2 digits in minutes
    seconds = ("00" + minSwimTime.Seconds.ToString()).Substring(("00" + minSwimTime.Seconds.ToString()).Length - 2),    // to get 2 digits in seconds
    milliseconds = minSwimTime.Milliseconds.ToString() + "00").Substring(0, 2),    // because miliseconds are not always filled
  };

Also - don't do string formatting in the database.  Database servers have better things to do than turn datetimes into text.


text:
Q: Hiding admin nav bar in wordpress doesn't work anymore I used this for around a year to hide the admin nav bar
function remove_read_wpse_93843(){
    $role = get_role( 'subscriber' );
    $role->remove_cap( 'read' );
}
add_action( 'admin_init', 'remove_read_wpse_93843' );

All of a sudden doesn't work anymore - every kind of user sees the admin nav.
How should I change the code?

A: According to this site, all you have to do is add the below code into functions.php. They provide several other options as well.
/* Disable WordPress Admin Bar for all users */
add_filter( 'show_admin_bar', '__return_false' );


text:
Q: Hibernate, OneToMany association - select issue I have following entity classes:
User and Category. User might have multiple categories.
I need to compose a query to select a user with some specific email and fetch categories, which updated value is greater than specified by me.
Unfortunately, I get some weird ( from my point of view ) errors.
Here is a query:
String selectQuery = "from User as user left outer join user.categories as category with category.updated >= :after where user.email = :email";
User u = (User)sessionFactory.getCurrentSession().createQuery(selectQuery).
            setString("email", email).
            setCalendar("after", after).
            setResultTransformer(RootEntityResultTransformer.INSTANCE).
            uniqueResult();
return u;

I've also tried this query:
String selectQuery = "from User as user left outer join user.categories as category where category.updated >= :after and user.email = :email";

I get an error message:
java.lang.ClassCastException: Category cannot be cast to User

Does anybody have any clue? The error message seems weird to me, cause I am selecting from User, not from Category.
P.S Of course, query should work if user doesn't have any categories at all.
Here are the entities:
@Entity
@Table(name = "USER", uniqueConstraints = {
        @UniqueConstraint(columnNames = {"EMAIL"})
})
public class User extends AbstractTimestampEntity implements Serializable {

    public User() {

    }

    private Integer id;

    private String email;

    private Set<Category> categories = null;

    @Id
    @Column(name = "ID")
    @GeneratedValue
    public Integer getId() {
        return id;
    }

    @NotEmpty
    @Email
    @Column(name = "EMAIL")
    public String getEmail() {
        return email;
    }

    @Cascade( { org.hibernate.annotations.CascadeType.PERSIST } )
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
    public Set<Category> getCategories() {
        return categories;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setCategories(Set<Category> categories) {
        this.categories = categories;
    }
}

@Entity
@Table(name = "CATEGORY")
public class Category extends AbstractTimestampEntity implements Serializable {

    private Integer id;

    private User user;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    public User getUser() {
        return user;
    }

   public void setId(Integer id) {
        this.id = id;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

@MappedSuperclass
public class AbstractTimestampEntity {

    private Calendar created;

    private Calendar updated;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATED")
    public Calendar getCreated() {
        return created;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "UPDATED")
    public Calendar getUpdated() {
        return updated;
    }

    public void setCreated(Calendar created) {
        this.created = created;
    }

    public void setUpdated(Calendar updated) {
        this.updated = updated;
    }
}

Thank you in advance.
Any help would be highly appreciated.

A: The "FETCH" option will always retrieve all categories for an user and you'd have to filter it in Java:
String selectQuery =
            "from User as user " +
            "left join fetch user.categories as category " +
            "where " +
            "   user.email = :email";
User user = (User) session.createQuery(selectQuery).
        setString("email", email).
        uniqueResult();
return user;
//then filter the user.categories by the after criteria

The categories can't be filtered with this query, since the left join fetch doesn't allow you to use the alias in a where clause.
For a more efficient query you would need to let go the "FETCH" and this way you can filter the categories too, but this time you won't be able to retrieve an user with a "partial" view of his categories. You either fetch all children or none.
String selectQuery =
            "select user, category " +
            "from User as user " +
            "left join user.categories as category with category.updated >= :after " +
            "where " +
            "   user.email = :email";
List userAndCategories = session.createQuery(selectQuery).
        setString("email", email).
        setCalendar("after", after).
        list();
//userAndCategories contains Object[] entries where the User is the Object[0] is the user and Object[1] is the Category


text:
Q: How can I rebase branches that are protected with "Require approvals" in Github? My organization wants feature branches to require approval before new content can be merged into them. We have a branch protection rule that applies "Require a pull request before merging" and "Require approvals" to branches named feature/*. We ALSO enabled the setting "Allow force pushes" for everyone.
If some unrelated work is merged to master after a feature branch is created, then the feature branch has fallen behind. It must be rebased, so that we know that all the contents of the feature branch will operate correctly when applied to all the contents of master.
However, despite the settings above, we cannot force push a rebase of the feature branch. Rebasing and force-pushing yields the following errors from git:
remote: error: GH006: Protected branch update failed for refs/heads/feature/my-feature.
remote: error: At least 1 approving review is required by reviewers with write access.
To github.com:MyOrg/repo-name.git
 ! [remote rejected] feature/my-feature -> feature/my-feature (protected branch hook declined)
error: failed to push some refs to 'github.com:MyOrg/repo-name.git'

How can we do both of:
a) require approvals on PRs targeting feature/*
b) allow feature branches to be rebased (which requires force-pushing)
I don't see any alternative to rebasing the branch. The builds we produce from feature/* branches MUST include all contents in master, or they can't be accurately tested. Furthermore the contents on master must be a PARENT to the feature branch commits, not a child; to do it the other way around is incorrect git practice, and pollutes the feature branch with irrelevant changes.
We only want PRs that target feature/* branches to require approvals. We must allow the feature branch to be rebased, which as far as I know requires us to force push. Rebasing should at least be possible to do somehow, even if that process requires approval. But it seems there is no way at all to rebase the feature branch; the only mechanism for applying changes to the feature branch are through a PR, which only add new commits to the branch, and cannot change the root commit so that master is its parent.
I understand that force-pushing a rebase is an opportunity for unreviewed changes to enter the feature branch. However we cannot avoid the requirement that feature branches are up to date with master.
How can I allow rebasing a feature branch while still requiring that PRs targeting the branch require approval?

Note: The wording of the "Require a pull request before merging" and "Require approvals" do not imply that force pushing will be prevented; they only discuss merges involving the feature branch. Yet enabling these rules prevents force pushing.

Require a pull request before merging: When enabled, all commits must be made to a non-protected branch and submitted via a pull request before they can be merged into a branch that matches this rule.

I'm not trying to merge into the branch, I'm trying to rebase and force push

Require approvals: When enabled, pull requests targeting a matching branch require a number of approvals and no changes requested before they can be merged.

I'm not creating a pull request, it can't change the parent commit and therefore can't rebase

A: One option would be to push to a new branch: my_feature:my_feature_force
From there, a GitHub Action, on push, could:

*

*detect the special naming scheme _force of the pushed branch

*use, as mentioned here a personal access token from an admin account.

env:
GITHUB\_TOKEN: ${{ secrets.GITHUB_TOKEN_PHIL }}

Then, that action could force push the renamed branch to its original and intended one.


text:
Q: What is the cause of the memory leak in c? I was creating a linked list in c and I came across this memory leak. Valgrind is telling that the source of the problem is on line 15 but I still can't see the problem. I feel very stupid not knowing where the problem occurred but it would be nice if you could help me! thanks in advance!
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

typedef struct node
{
    int number;
    struct node *next;
}
node;

int main(void)
{
    node *list = malloc(sizeof(node));
    if (list == NULL)
    {
        return 1;
    }
    list = NULL;
    // create link list
    for (int i = 0; i < 3; i++)
    {
        node *n = malloc(sizeof(node));
        if(n == NULL)
        {
            free(list);
            return 1;
        }
        n->number = i+1;
        n->next = NULL;

        n->next = list;
        list = n;
    }
    //print link list
    for (node *tmp = list; tmp != NULL; tmp = tmp->next)
    {
        printf("%d - ", tmp->number);
    }
    printf("\n");
    //free link list
    while (list != NULL)
    {
        node *tmp = list->next;
        free(list);
        list = tmp;
    }

}

this is my valgrind output:
==3895== Memcheck, a memory error detector
==3895== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3895== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==3895== Command: ./temp
==3895==
3 - 2 - 1 -
==3895==
==3895== HEAP SUMMARY:
==3895==     in use at exit: 16 bytes in 1 blocks
==3895==   total heap usage: 4 allocs, 3 frees, 64 bytes allocated
==3895==
==3895== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3895==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==3895==    by 0x401168: main (temp.c:15)
==3895==
==3895== LEAK SUMMARY:
==3895==    definitely lost: 16 bytes in 1 blocks
==3895==    indirectly lost: 0 bytes in 0 blocks
==3895==      possibly lost: 0 bytes in 0 blocks
==3895==    still reachable: 0 bytes in 0 blocks
==3895==         suppressed: 0 bytes in 0 blocks
==3895==
==3895== For lists of detected and suppressed errors, rerun with: -s
==3895== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

A: Pointer is just a variable that stores a memory address. You got the memory address with malloc malloc(sizeof(node)) but you put null in it list = NULL and you lost the address. Isn't this what you want?
    node** list;
    size_t i;

    list = malloc(sizeof(node*));
    *list = NULL;

    for (i = 0; i < 3; i++)
    {
        node* n = malloc(sizeof(node));

        n->number = i + 1;
        n->next = *list;

        *list = n;
    }

    /* print node... */
    /* release node... free(n) */
    free(list);
    list = NULL;

A: It is evident that this allocation of memory
node *list = malloc(sizeof(node));
if (list == NULL)
{
    return 1;
}
list = NULL;

is redundant and produces a memory leak because the pointer list is reassigned after the memory allocation. As a result the address of the allocated memory is lost.
Just write
node *list = NULL;

Also in this code snippet
    n->number = i+1;
    n->next = NULL;

    n->next = list;
    list = n;

this statement
    n->next = NULL;

is redundant.
In the for loop
for (int i = 0; i < 3; i++)
{
    node *n = malloc(sizeof(node));
    if(n == NULL)
    {
        free(list);
        return 1;
    }
    //...

you need to free all the allocated memory.
For example
for (int i = 0; i < 3; i++)
{
    node *n = malloc(sizeof(node));
    if(n == NULL)
    {
        while ( list )
        {
            node *tmp = list;
            list = list->next;
            free( tmp );
        }
        return 1;
    }
    //...

To avoid code duplication you could write a separate function that frees the allocated memory. For example
void free_list( node **list )
{
    while ( *list )
    {
        node *tmp = *list;
        *list = ( *list )->next;
        free( tmp );
    }
}

and call it like for example
for (int i = 0; i < 3; i++)
{
    node *n = malloc(sizeof(node));
    if(n == NULL)
    {
        free_list( &list );
        return 1;
    }
    //...

Or at the end of the program like
free_list( &list );


text:
Q: Problema com Imagem Responsiva img {
background-image: url(../img/slides/11.jpg);
max-width:100%;
height:auto;
}

Quando coloco o código acima, acontece o seguinte erro:

A imagem (como na foto) vai para cima.
Sendo que sem o código fica assim:

O que posso fazer?

   #home .bg-img {
 padding: 100px;
 -webkit-box-sizing: content-box;
 -moz-box-sizing: content-box;
 box-sizing: content-box;
 position: absolute;
 top: -50px;
 left: -50px;
 width: 100%;
 height: 100%;
 -webkit-background-size: cover;
 -moz-background-size: cover;
 background-size: cover;
 background-position: center center;
 }

    #home .bg-img-1 {
 background-image: url(../img/slides/11.jpg);}

A: Trabalhe o background-image somente no pai da tag img.
No caso da tag img, deixe o caminho da imagem no atributo src normalmente,
e no CSS, retire a opacidade completamente, assim a tag img se encarrega de preencher o espaço necessário da imagem, enquanto o pai, com o background-image, se encarrega de exibir a imagem de forma responsiva dentro dos limites.
No seu exemplo, o único espaço disponível era o padding de 100px. por isso o background-image tentou preencher somente esse espaço.
Código CSS:
#home .bg-img {
padding: 100px;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
position: absolute;
top: -50px;
left: -50px;
width: 100%;
height: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
background-position: center center;
}

#home .bg-img-1 { background-image: url(../img/slides/11.jpg); }
#home .bg-img img{ opacity: 0; }

Código HTML:


text:
Q: how to clone heroku app which was created by button and now dont have access to that button few months back i deployed a web app on heroku using heroku deploy button, now i want to clone that app and deploy it to another account because i have lost access to that repo from which i had deployed that app.
so when i search for cloning, i came to know that i can clone app which was deployed using CLI commands, but deployed from github or using button cant be cloned.
i also tried heroku slugs:download -a APP_NAME command but not successful.
So please help me to get the entire app and code so that i can deploy it to another account.

A: First download and install heroku CLI.
Then run this command:
heroku login

Login by using your username and password.
Then git clone by using:
heroku git:clone -a NAME-OF-YOUR-APP

**** OR ****

*

*Login to heroku : https://id.heroku.com/

*select your app.

*Select Deploy option.
Here you will get all the details with commands for getting the source code.


text:
Q: How to find the time needed to traverse the curve $r(t)=(\cos t, \sin t, t)$ from the origin to $8$ meters?
Given the curve $r(t)=(\cos t, \sin t, t)$ and that a body starts moving from $t=0$, after how much time will the body be positioned at the distance of 8 meters from the axis origin $(0,0,0)$?

One can think of 2 points in 3d space: the first point $(0,0,0)$ and the second point $(x,y,z)$ which is the point where the body will be situated after $8$ meters. Then I could find the distance like this:
$$
\sqrt{(x-0)^2+(y-0)^2+(z-0)^2}=8
$$
But not only is this an equation with 3 unknowns, I can't find the $t$.

A: $|r(t)| = 8 \Leftrightarrow \sqrt{(x(t)-0)^2+(y(t)-0)^2+(z(t)-0)^2}=8 \Leftrightarrow \sqrt{\cos^2(t) + \sin^2(t) + t^2} = 8 \Leftrightarrow \sqrt{1+t^2} = 8 \Leftrightarrow 1 + t^2 = 64 \Leftrightarrow t = \sqrt{63}=3\sqrt{7}$
We reject the mathematically correct solution $t = -\sqrt{63}=-3\sqrt{7}$ because time cannot be negative.

A: Write $x(t), y(t), z(t)$ for $x,y,z$; these are the three coordinate functions of $r$, i.e., $x(t)  = \cos t$. Then go from there.

A: The point lies on a sphere of radius $8$ units, on a top circle cut by a cylinder(of helix)  of radius $1$ and cone lateral length (vertex to top circle) $8$  units.
$$ z^2 + 1^2 = 8^2; \, t^2 + 1^2 = 8^2; \, \rightarrow t= \sqrt {63}. $$


text:
Q: how do I set folder permissions on windows Magento 2.2 install? I'm using laragon in a windows 10 machine for a 2.2.3 Magento install. What folder permissions do I have to set?
By default, all folders are read-only (or so it seems). Currently, I set writable folders (and files):
/var/
/pub/media
/pub/static

A: You can give write permission by running below command in your CLI.
takeown /F <folder name>

For Example:
 takeown /F C:\wamp\www\Magento\www\pub\static

A: Check the below link it will help you out
https://devdocs.magento.com/guides/v2.0/install-gde/prereq/file-system-perms.html

A: I hope so below link is use full for you.

Magento 2 folder/file permissions


text:
Q: Using non-english characters breaks listings Problem:
When using non-English characters, the listings package breaks in terms of creating a space in the line next to code numbers.
Minimal Working Example (MWE):
\documentclass{scrreprt}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[swedish]{babel}
\usepackage{listings}
\usepackage{xcolor}

\makeatletter
% ----------------------------------------------------------------------
%  Definition of colors
% ----------------------------------------------------------------------
\definecolor{editorPurple}{cmyk}{0.5, 1, 0, 0}
\definecolor{editorOrange}{cmyk}{0, 0.8, 1, 0}
\definecolor{editorBlue}{cmyk}{1, 0.6, 0, 0}
\definecolor{editorPink}{cmyk}{0, 1, 0, 0}

% ----------------------------------------------------------------------
%  Definition of HTML5
% ----------------------------------------------------------------------

\lstdefinelanguage{HTML5}{
  language=html,
  sensitive=true,
  tagstyle=\color{editorBlue},
  markfirstintag=true,
  morecomment=[s]{<!-}{-->},
  alsoletter={!-},
  keywords={}
}

% ----------------------------------------------------------------------
%  Setup for listings
% ----------------------------------------------------------------------

\lstset{%
  % General design
  inputencoding=utf8,
  backgroundcolor=\color{white},
  basicstyle=\tiny\ttfamily\upshape,
  frame=l,
  comment=[l]{;},
  escapeinside={;@}{\^^M},
  escapeinside=`',
  % line-numbers
  xleftmargin={14pt},
  numbers=left,
  stepnumber=1,
  firstnumber=1,
  numberfirstline=true,
  numberstyle=\color{black},
  % Code design
  identifierstyle=\color{editorOrange},
  keywordstyle=\color{editorPink},
  commentstyle=\color{editorGray},
  stringstyle=\color{editorPurple},
  % Code
  language=html,
  alsodigit={.:},
  tabsize=2,
  showtabs=false,
  showspaces=false,
  showstringspaces=false,
  extendedchars=true,
  breaklines=false,
  % German umlauts
  literate=
  {á}{{\'a}}1 {é}{{\'e}}1 {í}{{\'i}}1 {ó}{{\'o}}1 {ú}{{\'u}}1
  {Á}{{\'A}}1 {É}{{\'E}}1 {Í}{{\'I}}1 {Ó}{{\'O}}1 {Ú}{{\'U}}1
  {à}{{\`a}}1 {è}{{\`e}}1 {ì}{{\`i}}1 {ò}{{\`o}}1 {ù}{{\`u}}1
  {À}{{\`A}}1 {È}{{\'E}}1 {Ì}{{\`I}}1 {Ò}{{\`O}}1 {Ù}{{\`U}}1
  {ä}{{\"a}}1 {ë}{{\"e}}1 {ï}{{\"i}}1 {ö}{{\"o}}1 {ü}{{\"u}}1
  {Ä}{{\"A}}1 {Ë}{{\"E}}1 {Ï}{{\"I}}1 {Ö}{{\"O}}1 {Ü}{{\"U}}1
  {â}{{\^a}}1 {ê}{{\^e}}1 {î}{{\^i}}1 {ô}{{\^o}}1 {û}{{\^u}}1
  {Â}{{\^A}}1 {Ê}{{\^E}}1 {Î}{{\^I}}1 {Ô}{{\^O}}1 {Û}{{\^U}}1
  {œ}{{\oe}}1 {Œ}{{\OE}}1 {æ}{{\ae}}1 {Æ}{{\AE}}1 {ß}{{\ss}}1
  {ç}{{\c c}}1 {Ç}{{\c C}}1 {ø}{{\o}}1 {å}{{\r a}}1 {Å}{{\r A}}1
  {€}{{\EUR}}1 {£}{{\pounds}}1
}

% ----------------------------------------------------------------------
%  Check keywords within code
% ----------------------------------------------------------------------

\gdef\lst@BeginTag{%
    \lst@DelimOpen
        \lst@ifextags\else
        {\let\lst@ifkeywords\iftrue
         \lst@ifmarkfirstintag\lst@firstintagtrue\fi\color{editorBlue}}}
\gdef\lst@EndTag{\lst@DelimClose\lst@ifextags\else\color{editorBlue}}

\makeatother

\begin{document}

\begin{lstlisting}[language=HTML5,numbers=left,firstnumber=1]
<!DOCTYPE html>

    <title>Kod med indentering</title>
    <meta charset="utf-8">

Artiklar om frukt

Äpple

Text

Apelsin

Text

\end{lstlisting}

\end{document}

Results:

Desired outcome:
Make sure that the break in code line does not occur.

A: LINESPACING
On a lark, I tried changing the literate table to {Ä}{{\smash{\"A}}}1 and it seems to work.  Don't know if it is kosher.
COLOR
On the issue of color of the diacritics, I tried a strategy of first extending the change to the literate table to read {Ä}{{\smash{\color{\CLR}\"A}}}1 and then had to figure out how and where to save the color named \CLR.  Those changes included
\lstdefinelanguage{HTML5}{...
  tagstyle=\color{editorBlue}\gdef\CLR{editorPink},
...}

and
\lstset{...
  identifierstyle=\color{editorOrange}\gdef\CLR{editorOrange},
  keywordstyle=\color{editorPink}\gdef\CLR{editorPink},
  commentstyle=\color{editorGray}\gdef\CLR{editorGray},
  stringstyle=\color{editorPurple}\gdef\CLR{editorPurple},
...}

and
\gdef\lst@EndTag{\lst@DelimClose\lst@ifextags\else\color{editorBlue}%
                 \gdef\CLR{editorOrange}}

With those changes, and adding a "Ä" to lines 2, 5, 11, and 12 of the listing for test purposes, it seems to work, though I am no expert on listings.
Here is the MWE.
\documentclass{scrreprt}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[swedish]{babel}
\usepackage{listings}
\usepackage{xcolor}

\makeatletter
% ----------------------------------------------------------------------
%  Definition of colors
% ----------------------------------------------------------------------
\definecolor{editorPurple}{cmyk}{0.5, 1, 0, 0}
\definecolor{editorOrange}{cmyk}{0, 0.8, 1, 0}
\definecolor{editorBlue}{cmyk}{1, 0.6, 0, 0}
\definecolor{editorPink}{cmyk}{0, 1, 0, 0}

% ----------------------------------------------------------------------
%  Definition of HTML5
% ----------------------------------------------------------------------

\lstdefinelanguage{HTML5}{
  language=html,
  sensitive=true,
  tagstyle=\color{editorBlue}\gdef\CLR{editorPink},
  markfirstintag=true,
  morecomment=[s]{<!-}{-->},
  alsoletter={!-},
  keywords={}
}

% ----------------------------------------------------------------------
%  Setup for listings
% ----------------------------------------------------------------------

\lstset{%
  % General design
  inputencoding=utf8,
  backgroundcolor=\color{white},
  basicstyle=\tiny\ttfamily\upshape,
  frame=l,
  comment=[l]{;},
  escapeinside={;@}{\^^M},
  escapeinside=`',
  % line-numbers
  xleftmargin={14pt},
  numbers=left,
  stepnumber=1,
  firstnumber=1,
  numberfirstline=true,
  numberstyle=\color{black},
  % Code design
  identifierstyle=\color{editorOrange}\gdef\CLR{editorOrange},
  keywordstyle=\color{editorPink}\gdef\CLR{editorPink},
  commentstyle=\color{editorGray}\gdef\CLR{editorGray},
  stringstyle=\color{editorPurple}\gdef\CLR{editorPurple},
  % Code
  language=html,
  alsodigit={.:},
  tabsize=2,
  showtabs=false,
  showspaces=false,
  showstringspaces=false,
  extendedchars=true,
  breaklines=false,
  % German umlauts
  literate=
  {á}{{\'a}}1 {é}{{\'e}}1 {í}{{\'i}}1 {ó}{{\'o}}1 {ú}{{\'u}}1
  {Á}{{\'A}}1 {É}{{\'E}}1 {Í}{{\'I}}1 {Ó}{{\'O}}1 {Ú}{{\'U}}1
  {à}{{\`a}}1 {è}{{\`e}}1 {ì}{{\`i}}1 {ò}{{\`o}}1 {ù}{{\`u}}1
  {À}{{\`A}}1 {È}{{\'E}}1 {Ì}{{\`I}}1 {Ò}{{\`O}}1 {Ù}{{\`U}}1
  {ä}{{\"a}}1 {ë}{{\"e}}1 {ï}{{\"i}}1 {ö}{{\"o}}1 {ü}{{\"u}}1
  {Ä}{{\smash{\color{\CLR}\"A}}}1 {Ë}{{\"E}}1 {Ï}{{\"I}}1 {Ö}{{\"O}}1 {Ü}{{\"U}}1
  {â}{{\^a}}1 {ê}{{\^e}}1 {î}{{\^i}}1 {ô}{{\^o}}1 {û}{{\^u}}1
  {Â}{{\^A}}1 {Ê}{{\^E}}1 {Î}{{\^I}}1 {Ô}{{\^O}}1 {Û}{{\^U}}1
  {œ}{{\oe}}1 {Œ}{{\OE}}1 {æ}{{\ae}}1 {Æ}{{\AE}}1 {ß}{{\ss}}1
  {ç}{{\c c}}1 {Ç}{{\c C}}1 {ø}{{\o}}1 {å}{{\r a}}1 {Å}{{\r A}}1
  {€}{{\EUR}}1 {£}{{\pounds}}1
}

% ----------------------------------------------------------------------
%  Check keywords within code
% ----------------------------------------------------------------------

\gdef\lst@BeginTag{%
    \lst@DelimOpen
        \lst@ifextags\else
        {\let\lst@ifkeywords\iftrue
         \lst@ifmarkfirstintag\lst@firstintagtrue\fi\color{editorBlue}}}
\gdef\lst@EndTag{\lst@DelimClose\lst@ifextags\else\color{editorBlue}%
                 \gdef\CLR{editorOrange}}

\makeatother

\begin{document}

\begin{lstlisting}[language=HTML5,numbers=left,firstnumber=1]
<!DOCTYPE html>

    <title>Kod med indentering</title>
    <meta charset="utf-8Ä">

Artiklar om frukt

        <Äh2>Äpple</Äh2>
        <pÄ>TexÄt</pÄ>

Apelsin

Text

\end{lstlisting}

\end{document}