text:
Q: In a Git repo how can I efficiently remove local tracking branches for deleted remote branches? In a Git repo how can I efficiently remove local tracking branches for deleted remote branches?
If I create a Github repo, then create a feature branch off master, then the Git cli shows this
user@workstation C:\Home\Development\Workspaces\Scratch\GitTest1
$ git branch -vv
* feature1 e1f5c4e [origin/feature1] Stuff added on branch feature1
  master   d7a1ee8 [origin/master] Initial commit

user@workstation C:\Home\Development\Workspaces\Scratch\GitTest1
$ git branch -a
* feature1
  master
  remotes/origin/feature1
  remotes/origin/master

I can see what remote branches my local branches are tracking and everything is good.
If I delete the feature branch from Github and fetch --prune.
user@workstation C:\Home\Development\Workspaces\Scratch\GitTest1
$ git fetch --prune
From https://github.com/Neutrino-Sunset/git-test
 - [deleted]         (none)     -> origin/feature1

But now git branch -vv still shows the deleted remote branch, even though git branch -a no longer lists it.
user@workstation C:\Home\Development\Workspaces\Scratch\GitTest1
$ git branch -vv
* feature1 e1f5c4e [origin/feature1: gone] Stuff added on branch feature1
  master   d7a1ee8 [origin/master] Initial commit

user@workstation C:\Home\Development\Workspaces\Scratch\GitTest1
$ git branch -a
* feature1
  master
  remotes/origin/master

Because of this the only way I have to keep my local repository synchronised with my remote is to run git branch -vv in one console, git branch -a in another console. Then manually compare which of my local branches that say they are tracking a remote branch are actually tracking a branch that doesn't even exist, and then in a third console manually delete the extraneous branches.
For a large repo it's astonishingly cumbersome, and very easy to make a mistake.
Does Git really not provide a more intelligent way to do this?

A: I agree with torek's comment and would like to elaborate on the why.
Conceptually, let's start with a more generalized question:

In a Git repo how can I efficiently remove local branches that I no
longer need?

Because everyone's workflow might be different, there isn't a good catch-all for determining which you branches you no longer need. The standard answer that Git supports is:

*

*If a branch is fully merged into another branch (typically a permanent shared branch such as main, master, or develop), then you no longer need it. This is because there is no information on that branch that isn't already stored elsewhere (except for the branch name). You can re-create the branch in the future if you decide you need it again.

When I say that Git supports deleting branches that are fully merged, by this I mean when you delete a branch you can specify -d to perform the delete if the branch is fully merged (into either your currently checked out branch or another specified branch), or you can use -D to delete the branch regardless.
There are other reasons you may no longer need a branch, that don't meet the criteria in #1, some of which may be:

*Throwaway branches for testing or playing around.

*Potential code that was rejected and will never be used. (For example if you tried something 3 different ways on different branch names and moved forward with the best implementation. If you're certain of your pick, the other 2 branches can be deleted now, and the "good" branch can be deleted once it's fully merged.)

*Branches with code that is fully merged but with different commit IDs due to rebasing or amending. This might happen if your PR tool has an option called "Semi-linear merge" (Azure DevOps) or "Rebase, merge" (Bitbucket) which will potentially change the commit IDs on the fly at PR completion, meaning your local branch will have different IDs. Another way it could happen is if someone else rebased or amended a commit on your branch, perhaps to make a minor tweak before completing your PR. (I regularly do this when my co-workers ask me to PR their stuff and set the PR to auto-complete. If I see some minor issues I might comment it in the PR, but then just fix it for them, force-push it out and then approve it. Now they'll certainly need to use -D instead of -d when they delete their branch.)

Now to your specific question (paraphrased):

In a Git repo how can I efficiently remove local branches for deleted remote branches?

One obvious way would be to use the method you suggested, but with the word "gone" next to it. This should catch most of the branches you can delete in #1 and #4, but it's still not perfect. It doesn't catch the case where you added a commit to your local branch and forgot to push it out before the PR was completed! If you aren't worried about that possibility, then your approach should work, and can probably be automated. (See VonC's answer for some ideas.)
If you don't want to risk deleting extra commits on your branches that were never pushed, then the one thing Git supports is the one thing that you know with certainty is safe, which is deleting fully merged branches. So given that, you could safely iterate through every one of your local branches, use the -d argument against a permanent branch such as develop or main, and sleep well at night. The issue with that is that you'll probably still have many more branches leftover that you can delete.
If you have a rebase on-the-fly workflow, then you can also use this algorithm:

*

*Select a branch to compare with (where most of your PRs would go, e.g. main)

*For each local branch X,

*Create a temp branch T from X.

*Rebase T onto main

*Diff T and main. If they are identical, you can delete branch X.

Now for the remainder of your branches, you'll just have to look at them manually. I suggest listing your local branches a few times per day and keeping them purged all the time, since you'll know which PRs have recently been completed. If you wait too long it gets messy. (Sort of like an Email Inbox, or perhaps more analogous is the Email Drafts Folder. I think I have over 50 drafts in mine, and there might be 1 or 2 I don't want to delete for some reason, and therefore they all will stay until I dedicate time to purging them.)


text:
Q: Java Regex Find All Between But Last Character Not Preceded Or Followed By I have a string: "stuffhere{@ name="productViewer" vars="productId={{id}}"}morestuff"
How can I find everything between the beginning { and last }.
Pattern.compile("\\{@(.*?)\\}" + from, Pattern.DOTALL); //Finds {@ name="productViewer" vars="productId={{id}

How can I verify that the ending } is not preceded or followed by another }? The string may also be surrounded by other characters.
Id like for the regex to only return:  name="productViewer" vars="productId={{id}}"

A: You can use this pattern:
\\{@(.*)(?<!\\})\\}

(?<!..) is a negative lookbehind that checks your condition (not preceded by })
Note that closing curly brackets don't need to be escaped, you can write:
\\{@(.*)(?<!})}

A: Try this:
 ^[^{]*\\{@(.*?)\\}[^}]*$

A: how about
(?<=[{])[^{}]+

i have never used java, but regex is international isn't it :)
EDIT:
wait... regex has errors...

A: try this:
    String s = "stuffhere{@ name=\"productViewer\" vars=\"productId={{id}}\"}morestuff";
    Pattern p = Pattern.compile("\\{@\\s+(.*)\\}");
    Matcher m = p.matcher(s);
    if(m.find()){
        System.out.println(m.group(1));
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: c# equivalent to sql's "where value IN('a','b','c')" I basically need to change the row color of a Gridview depending of certain values.  Here's what I have:
if ((String)DataBinder.Eval(e.Row.DataItem, "STATUS") == "A" || (String)DataBinder.Eval(e.Row.DataItem, "STATUS") == "B" || (String)DataBinder.Eval(e.Row.DataItem, "STATUS") == "C")
{
    e.Row.BackColor = Color.Yellow;
}

I'm looking for a clearer (or should I say nicer) way, similar to what we have in sql, instead of having to use the || operator:
IF STATUS in('A','B','C')

A: Use LINQ Contains like:
if(new[] {"A", "B", "C"}
        .Contains((String)DataBinder.Eval(e.Row.DataItem, "STATUS")))

If you want to ignore case then:
if (new[] {"A", "B", "C"}
    .Contains((String) DataBinder.Eval(e.Row.DataItem, "STATUS"),
        StringComparer.InvariantCultureIgnoreCase))
{

}

A: You can try to use set for this task,
build it statically if it will not change at run time
or build it dynamically:
var statuses = new HashSet<string>
{
    "A",
    "B",
    "C"
}

and check like this:
statuses.Contains((String)DataBinder.Eval(e.Row.DataItem, "STATUS"))

A: One way to achieve your goal is to create a temporary List of items and use the Contains method of the List in your conditional:
var yellowStatuses = new List<string> { "A", "B", "C" };
var currentStatus = (String)DataBinder.Eval(e.Row.DataItem, "STATUS");
if (yellowStatuses.Contains(currentStatus))
    e.Row.BackColor = Color.Yellow;

Edit: @Habib beat me to the answer, and is cleaner too. :)

A: This is isn't a optimum way of approaching this, but I think that this linq query can help you.
if ((new string[] {"A","B","C"}).Any(x=>x==(String)DataBinder.Eval(e.Row.DataItem, "STATUS")))

A: You could use a Dictionary approach for this. The nice part is that you simply maintain it somewhere where that logic can be centralized and in one place.
var colorStatus = new Dictionary<string,Color>();
colorStatus["A"] = Color.Yellow;
colorStatus["B"] = Color.Yellow;
colorStatus["C"] = Color.Yellow;

And now later you can use this dictionary to test and then assign.
string status = (String)DataBinder.Eval(e.Row.DataItem, "STATUS");
if(colorStatus.ContainsKey(status))
{
    e.Row.BackColor = colorStatus[status];
}


text:
Q: How to update related products by api in wordpress?
Hey, I want to update products by their sku in wordpress and also i want to get that updated data to show into table by ajax. can you pls help me for this issue.

I have try many option but same data getting return which is already inserted into database. i want particular that data which is getting update.


text:
Q: PMF of Discrete Random Variables Prove that $$\frac{1} {(1-p)^2} = \sum_{x=2}^\infty x^2p^{x-2} \, .$$
The professor suggested that we start by taking the derivative of $$\frac{1} {(1-p)^2} = \sum_{x=1}^\infty xp^{x-1} \, .$$
So I have tried that, and then broken the derivative up into $$ \sum_{x=2}^\infty x^2p^{x-2} \, - \sum_{x=2}^\infty xp^{x-2} \, .$$ by taking apart x(x-1)
but I can't get any further and I am extremely confused.

A: From $$\frac{1}{(1-p)^2} = \sum_{x \geq 1} x \cdot p^{x-1} \tag{1} $$ you obtain by differentiating (with respect to $p$):
$$\begin{align} \frac{2}{(1-p)^3} &= \sum_{x \geq 2} x \cdot (x-1) \cdot p^{x-2} = \sum_{x \geq 2} x^2 \cdot p^{x-2} - \underbrace{\sum_{x \geq 2} x \cdot p^{x-2}}_{\frac{1}{p} \cdot \sum_{x \geq 2} x \cdot p^{x-1}} \\ &= \sum_{x \geq 2} x^2 \cdot p^{x-2} - \frac{1}{p} \cdot \left( \sum_{x \geq 1} x \cdot p^{x-1} -1 \right) \\ &\stackrel{(1)}{=} \sum_{x \geq 2} x^2 \cdot p^{x-2} - \frac{1}{p} \cdot \left(  \frac{1}{(1-p)^2} -1 \right) \end{align}$$
Hence
$$\sum_{x \geq 2} x^2 \cdot p^{x-2} = \frac{p^2-3p+4}{(1-p)^3}$$
(There has to be a mistake or typo in your claim, because if the equality $$\sum_{x \geq 2} x^2 \cdot p^{x-2} =\frac{1}{(1-p)^2}$$ holds, this would imply $$ 0 = \frac{1}{(1-p)^2} - \frac{1}{(1-p)^2} = \sum_{x \geq 2} x^2 \cdot p^{x-2} - \sum_{x \geq 1} x \cdot p^{x-1} = \sum_{x \geq 0} \underbrace{((x+2)^2-(x+1))}_{\geq 0} \cdot \underbrace{p^x}_{\geq 0}$$ by using (1). And this can only hold iff $$(x+2)^2-(x+1) = 0$$ for all $x \in \mathbb{N}$. And this is clearly not fulfilled.)

A: For $\,|p|<1\,$ it is well known that
$$f(p):=\frac{1}{1-p}=\sum_{x=0}^\infty p^x\Longrightarrow f'(p)=\frac{1}{(1-p)^2}=\sum_{x=1}^\infty xp^{k-1}$$
So in fact your first equality's right hand must begin from $\,x=1\,$ and with $\,x\,$ but not squared...check this.


text:
Q: Vimeo 'Replace' API Endpoint Not Changing Thumbnail I am using Vimeo's API for the users of my app to upload videos, or replace their existing video with a new one. I am using a Vimeo Client to help me make the calls in my Django Application. Uploading works without any issues, but when I try to replace an existing video with a new one, the thumbnail stays as the old video. If you play the video, it will play the new one, but the thumbnail never changes.
Model Method that Uploads/Replaces
def vimeo_upload(self):
        media_file = self.video_file
        if media_file and os.path.exists(media_file.path):
            v = vimeo.VimeoClient(token=settings.VIMEO_ACCESS_TOKEN, key=settings.VIMEO_API_KEY,
                                  secret=settings.VIMEO_API_SECRET)
            if self.video_url is None:
                try:
                    video_uri = v.upload(media_file.path)
                except AssertionError as exc:
                    logging.error('Vimeo Error: %s Video: %s' % (exc, media_file.path))
                else:
                    self.video_url = video_uri
            else:
                try:
                    v.replace(video_uri=self.video_url, filename=media_file.path)
                except Exception as exc:
                    self.video_url = None
                    logging.error('Vimeo Replace Error: %s Video: %s' % (exc, media_file.path))
            # set the video title, description, etc.
            if self.video_url:
                try:
                    # convert locale from en-us form to en
                    v.patch(self.video_url, data={'description': self.customer.full_name,     })
                except Exception as exc:
                    logging.error('Vimeo Patch Error: %s Video: %s' % (exc, media_file.path))

Vimeo Client Model, and UploadVideoMixin
class UploadVideoMixin(object):
    """Handle uploading a new video to the Vimeo API."""

    UPLOAD_ENDPOINT = '/me/videos'
    REPLACE_ENDPOINT = '{video_uri}/files'

    def upload(self, filename, upgrade_to_1080=False):
        """Upload the named file to Vimeo."""
        ticket = self.post(
            self.UPLOAD_ENDPOINT,
            data={'type': 'streaming',
                  'upgrade_to_1080': 'true' if upgrade_to_1080 else 'false'},
            params={'fields': 'upload_link,complete_uri'})

        return self._perform_upload(filename, ticket)

    def replace(self, video_uri, filename, upgrade_to_1080=False):
        """Replace the video at the given uri with the named source file."""
        uri = self.REPLACE_ENDPOINT.format(video_uri=video_uri)

        ticket = self.put(
            uri,
            data={'type': 'streaming',
                  'upgrade_to_1080': 'true' if upgrade_to_1080 else 'false'},
            params={'fields': 'upload_link,complete_uri'})

        return self._perform_upload(filename, ticket)

    def _perform_upload(self, filename, ticket):
        """Take an upload ticket and perform the actual upload."""

        if ticket.status_code != 201:
            raise UploadTicketCreationFailure(ticket, "Failed to create an upload ticket")

        ticket = ticket.json()

        # Perform the actual upload.
        target = ticket['upload_link']
        last_byte = 0
        # Try to get size of obj by path. If provided obj is not a file path
        # find the size of file-like object.
        try:
            size = os.path.getsize(filename)
            with io.open(filename, 'rb') as f:
                while last_byte < size:
                    try:
                        self._make_pass(target, f, size, last_byte)
                    except requests.exceptions.Timeout:
                        # If there is a timeout here, we are okay with it, since
                        # we'll check and resume.
                        pass
                    last_byte = self._get_progress(target, size)
        except TypeError:
            size = len(filename.read())
            f = filename
            while last_byte < size:
                try:
                    self._make_pass(target, f, size, last_byte)
                except requests.exceptions.Timeout:
                    # If there is a timeout here, we are okay with it, since
                    # we'll check and resume.
                    pass
                last_byte = self._get_progress(target, size)

        # Perform the finalization and get the location.
        finalized_resp = self.delete(ticket['complete_uri'])

        if finalized_resp.status_code != 201:
            raise VideoCreationFailure(finalized_resp, "Failed to create the video")

        return finalized_resp.headers.get('Location', None)

    def _get_progress(self, upload_target, filesize):
        """Test the completeness of the upload."""
        progress_response = self.put(
            upload_target,
            headers={'Content-Range': 'bytes */*'})

        range_recv = progress_response.headers.get('Range', None)
        _, last_byte = range_recv.split('-')

        return int(last_byte)

    def _make_pass(self, upload_target, f, size, last_byte):
        """Make a pass at uploading.

        This particular function may do many things.  If this is a large upload
        it may terminate without having completed the upload.  This can also
        occur if there are network issues or any other interruptions.  These
        can be recovered from by checking with the server to see how much it
        has and resuming the connection.
        """
        response = self.put(
            upload_target,
            timeout=None,
            headers={
                'Content-Length': str(size),
                'Content-Range': 'bytes: %d-%d/%d' % (last_byte, size, size)
            }, data=f)

        if response.status_code != 200:
            raise VideoUploadFailure(response, "Unexpected status code on upload")

class VimeoClient(ClientCredentialsMixin, AuthorizationCodeMixin, UploadMixin):
    """Client handle for the Vimeo API."""

    API_ROOT = "https://api.vimeo.com"
    HTTP_METHODS = set(('head', 'get', 'post', 'put', 'patch', 'options', 'delete'))
    ACCEPT_HEADER = "application/vnd.vimeo.*;version=3.2"
    USER_AGENT = "pyvimeo 0.3.10; (http://developer.vimeo.com/api/docs)"

    def __init__(self, token=None, key=None, secret=None, *args, **kwargs):
        """Prep the handle with the authentication information."""
        self.token = token
        self.app_info = (key, secret)
        self._requests_methods = dict()

        # Make sure we have enough info to be useful.
        assert token is not None or (key is not None and secret is not None)

    # Internally we back this with an auth mechanism for Requests.
    @property
    def token(self):
        return self._token.token

    @token.setter
    def token(self, value):
        self._token = _BearerToken(value) if value else None

    def __getattr__(self, name):
        """This is where we get the function for the verb that was just
        requested.

        From here we can apply the authentication information we have.
        """
        if name not in self.HTTP_METHODS:
            raise AttributeError("%r is not an HTTP method" % name)

        # Get the Requests based function to use to preserve their defaults.
        request_func = getattr(requests, name, None)
        if request_func is None:
            raise AttributeError(
                "%r could not be found in the backing lib" % name
            )

        @wraps(request_func)
        def caller(url, jsonify=True, **kwargs):
            """Hand off the call to Requests."""
            headers = kwargs.get('headers', dict())
            headers['Accept'] = self.ACCEPT_HEADER
            headers['User-Agent'] = self.USER_AGENT

            if jsonify \
                    and 'data' in kwargs \
                    and isinstance(kwargs['data'], (dict, list)):
                kwargs['data'] = json.dumps(kwargs['data'])
                headers['Content-Type'] = 'application/json'

            kwargs['timeout'] = kwargs.get('timeout', (1, 30))
            kwargs['auth'] = kwargs.get('auth', self._token)
            kwargs['headers'] = headers
            if not url[:4] == "http":
                url = self.API_ROOT + url

            response = request_func(url, **kwargs)
            if response.status_code == 429:
                raise APIRateLimitExceededFailure(
                    response, 'Too many API requests'
                )
            return response
        return caller

class _BearerToken(requests.auth.AuthBase):
    """Model the bearer token and apply it to the request."""
    def __init__(self, token):
        self.token = token

    def __call__(self, request):
        request.headers['Authorization'] = 'Bearer ' + self.token
        return request


text:
Q: mobile jquery onclick does not play audio file? This is my script
function playSound(soundfile) {

document.getElementById("ui-btn-text").innerHTML=document.getElementById("ui-btn-text").innerHTML +
"<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";

}

And this is a part of my code

I have no idea why the audio file does not play!
Or is there a better solution for what i am doing?

A: The way you have it written it should result in some HTML like:

    <embed src="image/button.mp4" hidden="true" autostart="true" loop="false" />

If it's going to be hidden already, why not just leave it someplace on the page and simply trigger the audio to play when the button is clicked. Set autostart="false" and then use JS/JQuery to play the mp4 when the button is clicked.
HTML

<embed src="image/button.mp4" hidden="true" autostart="false" loop="false" id="ui-btn-sound" />

JavaScript
function playSound(id) {
    var audioFile = document.getElementById(id);
    audioFile.Play();
    return false;
}

I personally would suggest using HTML5 audio tag and fall back to an embedded option if needed.
<audio controls>
    <source src="image/button.mp4" type="audio/mp4">

    <embed src="image/button.mp4" hidden="true" autostart="false" loop="false" id="ui-btn-sound" />
    Play
</audio>

The audio tag also has lots of ways to control it's look and function via JS/JQuery. You might want to look into things like audio.canPlayType('audio/mp4');.
Here is an older example, someone challenged me to make a piano that did not have lag between each note and allowed other notes to be stopped when a new note was played: http://www.yrmailfrom.me/projects/html5/piano.php
Edit:
After answering this, I was inspired to create a quick JQM HTML5 player: http://www.yrmailfrom.me/projects/html5/audioplay.php
Hope that helps you.


text:
Q: How to save a keras subclassed model with positional parameters in Call() method? import tensorflow as tf

class MyModel(tf.keras.Model):

    def __init__(self):
        super(MyModel, self).__init__()
        self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
        self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)

    @tf.function
    def call(self, enc_input, dec_input, training, mask1, mask2, mask3):
        x = self.dense1(enc_input)
        return self.dense2(x)

x = tf.random.normal((10,20))

model = MyModel()

y = model(x, x, False, None, None, None)

tf.keras.models.save_model(model, '/saved')

when I try to save the model, throws an error even though i'm passing all the arguments.
tf__call() missing 4 required positional arguments: 'training', 'mask1', 'mask2', and 'mask3'
How to save the entire model and not just saving weights ?

A: I think doing this following change would work
 #def call(self, enc_input, dec_input, training, mask1, mask2, mask3):
 def call(self, enc_input, dec_input, training=False, mask1=None, mask2=None, mask3=None):

After digging, i think there is a sanity check that happens on function arguments, if positional arguments are not specified, the parameters after x will be taken as **kwargs arguments(I am not really sure about this).
but for the sake of it, if you don't want to set default mapping of arguments, you can just unpack them so each argument goes it its corresponding place as follow:
y = model(*[x,x,False,None,None,None])


text:
Q: Camera surface preview gives multiple errors on multiple devices The Problem:
In using the camera on the device, I'm getting a number of errors.  I have looked over many answers here on StackOverflow and I have tried many solutions to no avail.  I'm not sure what the problem is.  I have tried this on two different devices and I'm getting the same errors.  This is failing on multiple devices...  Samsung Galaxy S7 and a Vankyo Z4 Tablet.  The logs are from the tablet.
2020-01-27 06:51:43.571 4182-4182/ W/e.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2020-01-27 06:51:43.649 4182-4182/ D/OpenGLRenderer: Skia GL Pipeline
2020-01-27 06:51:44.474 4182-4182/ E/Camera: Error 2
2020-01-27 06:51:44.600 4182-4262/ I/mali_so: [File] : hardware/rockchip/mali_so_src_of_midgard/driver/product/base/src/mali_base_kbase.c; [Line] : 1095; [Func] : base_context_deal_with_version_affairs_rk_ext;
    arm_release_ver of this mali_so is 'r12p0-01rel0', rk_so_ver is '9@0 '.
2020-01-27 06:51:44.600 4182-4262/ I/mali_so: [File] : hardware/rockchip/mali_so_src_of_midgard/driver/product/base/src/mali_base_kbase.c; [Line] : 1101; [Func] : base_context_deal_with_version_affairs_rk_ext;
    mali_ver_property has been set to 'r12p0-01rel0-x-9@0', to return.
2020-01-27 06:51:44.601 4182-4262/ I/mali_so: [File] : hardware/rockchip/mali_so_src_of_midgard/driver/product/cmem/src/mali_cmem_hoard.c; [Line] : 559; [Func] : should_current_process_not_to_use_hoard;
    WOULD use hoard.
2020-01-27 06:51:44.617 4182-4262/ I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2020-01-27 06:51:44.618 4182-4262/ I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2020-01-27 06:51:44.618 4182-4262/ I/OpenGLRenderer: Initialized EGL, version 1.4
2020-01-27 06:51:44.618 4182-4262/ D/OpenGLRenderer: Swap behavior 2
2020-01-27 06:51:44.648 4182-4262/ D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2020-01-27 06:51:44.670 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:51:44.674 4182-4182/ D/Camera: Rotate 270
2020-01-27 06:51:44.675 4182-4182/ D/Camera: setDisplayOrientation Failed: set display orientation failed
2020-01-27 06:51:44.677 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:51:45.630 4182-4182/ D/Camera: Rotate 270
2020-01-27 06:51:45.818 4182-4182/ I/Choreographer: Skipped 76 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:51:46.014 4182-4262/ D/GRALLOC-ROCKCHIP: RK_GRAPHICS_VER=commit-id:69cd12f
2020-01-27 06:51:46.464 4182-4262/ I/OpenGLRenderer: Davey! duration=1946ms; Flags=1, IntendedVsync=15482245744667, Vsync=15483533880219, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=15483548307810, AnimationStart=15483548629227, PerformTraversalsStart=15483550124019, DrawStart=15483591003440, SyncQueued=15483639373153, SyncStart=15483640225986, IssueDrawCommandsStart=15483711543452, SwapBuffers=15484188006958, FrameCompleted=15484193184333, DequeueBufferDuration=14675000, QueueBufferDuration=3065000,
2020-01-27 06:51:46.491 4182-4182/ I/Choreographer: Skipped 39 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:51:46.539 4182-4262/ I/OpenGLRenderer: Davey! duration=709ms; Flags=0, IntendedVsync=15483558409277, Vsync=15484219426205, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=15484220349586, AnimationStart=15484220561045, PerformTraversalsStart=15484222148003, DrawStart=15484224182962, SyncQueued=15484224448962, SyncStart=15484224914753, IssueDrawCommandsStart=15484225396878, SwapBuffers=15484260477090, FrameCompleted=15484268449216, DequeueBufferDuration=11816000, QueueBufferDuration=3806000,
2020-01-27 06:53:10.381 4182-4262/ W/libEGL: EGLNativeWindowType 0xee0ea008 disconnect failed
2020-01-27 06:53:11.199 4182-4182/ I/Choreographer: Skipped 49 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:53:11.283 4182-4262/ D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2020-01-27 06:53:11.363 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:53:11.368 4182-4182/ D/Camera: Rotate 0
2020-01-27 06:53:11.369 4182-4182/ D/Camera: setDisplayOrientation Failed: set display orientation failed
2020-01-27 06:53:11.371 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:53:12.680 4182-4182/ D/Camera: Rotate 0
2020-01-27 06:53:12.691 4182-4182/ E/Camera: Error 2
2020-01-27 06:53:12.729 4182-4182/ I/Choreographer: Skipped 87 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:53:12.851 4182-4262/ I/OpenGLRenderer: Davey! duration=1608ms; Flags=1, IntendedVsync=15568971643421, Vsync=15570446219645, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=15570459148001, AnimationStart=15570459500626, PerformTraversalsStart=15570461186751, DrawStart=15570496844172, SyncQueued=15570546182510, SyncStart=15570546388427, IssueDrawCommandsStart=15570562532470, SwapBuffers=15570576764930, FrameCompleted=15570579908513, DequeueBufferDuration=7076000, QueueBufferDuration=956000,
2020-01-27 06:53:35.328 4182-4262/ W/libEGL: EGLNativeWindowType 0xd48dd008 disconnect failed
2020-01-27 06:53:36.017 4182-4182/ I/Choreographer: Skipped 39 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:53:36.096 4182-4262/ D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2020-01-27 06:53:36.175 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:53:36.178 4182-4182/ D/Camera: Rotate 270
2020-01-27 06:53:36.179 4182-4182/ D/Camera: setDisplayOrientation Failed: set display orientation failed
2020-01-27 06:53:36.181 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:53:36.978 4182-4182/ D/Camera: Rotate 270
2020-01-27 06:53:36.990 4182-4182/ E/Camera: Error 2
2020-01-27 06:53:37.040 4182-4182/ I/Choreographer: Skipped 58 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:53:37.160 4182-4262/ I/OpenGLRenderer: Davey! duration=1105ms; Flags=1, IntendedVsync=15593784036511, Vsync=15594767087327, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=15594770152361, AnimationStart=15594770423902, PerformTraversalsStart=15594772051694, DrawStart=15594807059573, SyncQueued=15594846584202, SyncStart=15594846778160, IssueDrawCommandsStart=15594869251079, SwapBuffers=15594887089997, FrameCompleted=15594889647331, DequeueBufferDuration=7349000, QueueBufferDuration=1031000,
2020-01-27 06:53:51.816 4182-4262/ W/libEGL: EGLNativeWindowType 0xd48dd008 disconnect failed
2020-01-27 06:53:52.497 4182-4182/ I/Choreographer: Skipped 39 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:53:52.568 4182-4262/ D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2020-01-27 06:53:52.655 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:53:52.659 4182-4182/ D/Camera: Rotate 0
2020-01-27 06:53:52.660 4182-4182/ D/Camera: setDisplayOrientation Failed: set display orientation failed
2020-01-27 06:53:52.661 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:53:53.166 4182-4182/ D/Camera: Rotate 0
2020-01-27 06:53:53.174 4182-4182/ E/Camera: Error 2
2020-01-27 06:53:53.209 4182-4182/ I/Choreographer: Skipped 38 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:53:53.333 4182-4262/ I/OpenGLRenderer: Davey! duration=781ms; Flags=1, IntendedVsync=15610280644733, Vsync=15610924712509, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=15610938505568, AnimationStart=15610938769527, PerformTraversalsStart=15610940187027, DrawStart=15610980021989, SyncQueued=15611021218452, SyncStart=15611021401618, IssueDrawCommandsStart=15611042124829, SwapBuffers=15611058239997, FrameCompleted=15611062475581, DequeueBufferDuration=8643000, QueueBufferDuration=1439000,
2020-01-27 06:54:33.415 4182-4262/ W/libEGL: EGLNativeWindowType 0xd48dd008 disconnect failed
2020-01-27 06:54:34.104 4182-4182/ I/Choreographer: Skipped 41 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:54:34.172 4182-4262/ D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2020-01-27 06:54:34.250 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:54:34.252 4182-4182/ D/Camera: Rotate 270
2020-01-27 06:54:34.254 4182-4182/ D/Camera: setDisplayOrientation Failed: set display orientation failed
2020-01-27 06:54:34.256 4182-4182/ D/Camera: setPreviewTexture failed
2020-01-27 06:54:34.761 4182-4182/ D/Camera: Rotate 270
2020-01-27 06:54:34.774 4182-4182/ E/Camera: Error 2
2020-01-27 06:54:34.805 4182-4182/ I/Choreographer: Skipped 38 frames!  The application may be doing too much work on its main thread.
2020-01-27 06:54:34.942 4182-4262/ I/OpenGLRenderer: Davey! duration=794ms; Flags=1, IntendedVsync=15651876176648, Vsync=15652520244424, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=15652534305206, AnimationStart=15652534506748, PerformTraversalsStart=15652537321040, DrawStart=15652583784419, SyncQueued=15652629034174, SyncStart=15652629455049, IssueDrawCommandsStart=15652650115843, SwapBuffers=15652667089970, FrameCompleted=15652670663762, DequeueBufferDuration=9324000, QueueBufferDuration=1607000,
2020-01-27 07:03:10.639 4182-4262/ W/libEGL: EGLNativeWindowType 0xd48dd008 disconnect failed

As can be seen from the log, when the orientation changes, surfaceChanged callback gets called twice.  The first time, I get the setDisplayOrientation failed.  I'm not sure why I'm getting setPreviewTexture failed because I'm not even using TextureView.  I also don't know why I'm getting Error 2 for the camera either.  I have tried several solutions that I found here and elsewhere to no avail.  Here's the code in question:
    @Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    Display display;
    int rotation;
    int degrees = 0;
    int result;

    // If the holder is null, then just return.
    if (mHolder.getSurface() == null) {
        return;
    }

    // Stop the preview.
    try {
        if (isPreviewRunning) {
            mCamera.stopPreview();
            isPreviewRunning = false;
        }
    } catch (Exception e) {
        Log.d("Camera", "Stop Preview Failed: " + e.getMessage());
    }

    // Check the device orientation.
    display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    rotation = display.getRotation();
    switch (rotation) {
        case Surface.ROTATION_0:
            Log.d("Camera", "Rotate 0");
            degrees = 0;
            break;
        case Surface.ROTATION_90:
            Log.d("Camera", "Rotate 90");
            degrees = 90;
            break;
        case Surface.ROTATION_180:
            Log.d("Camera", "Rotate 180");
            degrees = 180;
            break;
        case Surface.ROTATION_270:
            Log.d("Camera", "Rotate 270");
            degrees = 270;
            break;
    }
    if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        result = (cameraInfo.orientation + degrees) % 360;
        result = (360 - result) % 360;  // compensate the mirror
    } else {  // back-facing
        result = (cameraInfo.orientation - degrees + 360) % 360;
    }

    // Not sure why this fails.  No reason given.
    try {
        mCamera.setDisplayOrientation(result);
    } catch (Exception e) {
        Log.d("Camera", "setDisplayOrientation Failed: " + e.getMessage());
    }

    // Restart the preview with the new changes.
    try {
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();
        isPreviewRunning = true;
    } catch (IOException e) {
        Log.d("Camera", e.getMessage());
    }
}

Despite the errors, it does work.  So should I just ignore the errors or continue to try to fix them?  I am writing for API level 19.  I know that Camera was depreciated in API 21, but older devices are still out there and I want this code to run on those as well.  As for the research, there seems to be two main solutions.  I have tried both and they do not work.  The one with the getParameters is telling me that getParameters failed that it returned null, which should not happen, but it does.
Research:
As for the research that I have done trying to fix this problem...
https://www.codeproject.com/Questions/626862/Android-Camera-setDisplayOrientation-Failed
Textureview/Surface view for Camera preview - Android
Problem with camera when orientation changes
Android Camera setDisplayOrientation does not work
android camera setDisplayOrientation(90) fails in different devices
Set display orientation failed


text:
Q: Symfony 4 Restful API login with JWT and facebook I have a question regarding authentication with JWT and Facebook for a restful API app.
I am using Symfony 4 and for authentication "lexik/jwt-authentication-bundle": "^2.6", to generate jwt tokens based on username and password.
Here is my configuration security.yaml:
security:
    encoders:
        App\Entity\User: bcrypt
    providers:
        database:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        login:
            pattern: ^/api/login
            stateless: true
            anonymous: true
            json_login:
                check_path: /api/login
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure

        register:
            pattern: ^/api/register
            anonymous: true
            methods: [POST]

        docs:
            pattern:  ^/api/docs
            anonymous: true
            methods: [GET]

        api:
            pattern: ^/api
            stateless: true
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator
    access_control:
        - { path: ^/api/docs, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api/profile/social-account, roles: ROLE_INFLUENCER }
        - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }

I am trying to add also login by facebook but I have no idea how to handle that with JWT, as I want to return after login a JWT token.
Is there any way to handle facebook login and JWT login?

A: You can have a good idea of how to implement it here : https://github.com/lexik/LexikJWTAuthenticationBundle/issues/295.
Basically after the user accept the Facebook login on your frontend :

*

*send a POST request with the user's token to your custom endpoint (for example login/facebook.

*Then you can make an extra request with the user's token to Facebook api to get extra information as firstname, lastname or user's email (for example with https://graph.facebook.com/me/?fields=first_name,last_name,email).
The token needs to have correct permissions to get access to those information (https://developers.facebook.com/docs/facebook-login/permissions/overview).

*You can now create a user if the email is not in your database.
Finally just return the token with create method of JWTManager class.
$token = $this->jwtManager->create($user);

By using this logic, it is totally transparent for your frontend whether your user has already loged in with your app or not and it gets a token the same way a user would get with your /login endpoint.

A: I assume you have an frontend application (React/Angular/Vue...) that consumes your API.
I would handle the "login with Facebook" on the Frontend side. After the user accepts the authentication via Facebook, they will be send back to your frontend app. At that point you have access to all the information you need (e.g. e-mail, first name, last name, etc).
POST that information to a new endpoint (e.g. /api/facebook-login), which handles your registration and/or login process, and then return an JWT token with your newly created user. Lexik makes it possible to manually create tokens:
class ApiController extends Controller
{
    public function getTokenUser(UserInterface $user, JWTTokenManagerInterface $JWTManager)
    {
        // ...

        return new JsonResponse(['token' => $JWTManager->create($user)]);
    }
}


text:
Q: camel how to process json with streaming mode? In order to read json and unmarshal in streaming mode what options are available in Camel OOB ? If not out of box how can this be implemented ?
I found camel-xstream which might help. Is streaming mode a default of this or do we need to do something else to make it read in streaming mode ?
There is also jackson streaming api. Is that accessible with camel ?
Some examples would help.
Thanks

A: You can use the unmarshal with json format. like this:
.unmarshal().json(JsonLibrary.Jackson, YourClass.class)

or
.unmarshal().json(JsonLibrary.Jackson)

In the first example you can take it in your Pojo, for manipulate the datas in a process like this:
.process(new Processor() {
                        @Override
                        public void process(Exchange exchange) throws Exception {
                           YourClass yourClass = exchange.getIn().getBody(YourClass.class);
})

A: You can use JSON data format, to to marshal and unmarshal Java objects to and from JSON.
Some thing like .marshal().json(JsonLibrary.Jackson) which uses Jackson Library, You can use others as well.
Following is a sample configuration to stream csv file content and convert to JSON and then call publish method of MyBean class.
  CsvDataFormat csv = new CsvDataFormat();
  csv.setDelimiter(",");
  csv.setQuoteDisabled(true);
  csv.setUseMaps(true);
  csv.setLazyLoad(true);
  csv.setHeader(Arrays.asList("head1","head2","head3","message"));

from("file:///test/?fileName=test.csv&noop=true").split(body().tokenize("\n")).streaming().unmarshal(csv).marshal().json(JsonLibrary.Jackson).bean(MyBean.class,"publish").log("done.").end();


text:
Q: What actions/interactions cause a question to move to the top of the list? What actions or interaction on a question cause it to move up / timestamp refresh? For example, I know that for the following...

*

*Posting an answer (yes)

*Voting up a comment (no)

*Flagging the question (no)

*Voting to close the question (no)

*Accepting an answer (no)

Ok, what about these?

*

*Editing the question?

*Editing an answer?

*Posting a comment on the question?

*Posting a comment on an answer?

*Deleting an answer?

*Reopening the question?

What else have I missed? To be more concise, someone may just post a list of which actions cause a question to refresh/bump.


text:
Q: What is the proper way to get Three.js used within Webpack so I can use OrbitControls? In my webpack config:
resolve: {
      alias: {
        'three': path.resolve('node_modules', 'three/build/three.js'),
        'OrbitControls': path.resolve('node_modules', 'three/examples/js/controls/OrbitControls.js'),
        'OBJLoader': path.resolve('node_modules', 'three/examples/js/loaders/OBJLoader.js')
      }

In my module:
import * as THREE from 'three' // if I do import THREE from 'three' it fails with three being undefined
import OrbitControls from 'OrbitControls'
import OBJLoader from 'OBJLoader'

If I use import * THREE from 'three' all is well and I can get THREE to be defined and complete the cube tutorial without hassle. If I change to import * as THREE from 'three' three.js is loaded - so that's not the problem?
How do I get the OrbitControls and the OBJLoader to load? When I try to get them to load, I get Uncaught ReferenceError: THREE is not defined(…) within OrbitControls.js: THREE.OrbitControls = function ( object, domElement ) { THREE is undefined.
So there's a problem with the packaging of the modules? I installed this from https://www.npmjs.com/package/three
So what gives? Is it a problem how Three.js is packaged on npm or is it a misconfiguration in my webpack.config? Is there a way to tell webpack "let's package the root three.js file, and then package the OrbitControls.js file"?

A: I needed to install the three-orbit-controls and the three-obj-loader via npm.
Then in my module, it was simply requiring them:
var OBJLoader = require('three-obj-loader')(THREE)
var OrbitControls = require('three-orbit-controls')(THREE)

All set!


text:
Q: Node.js error on Azure Web App I have a node.js application which is running seemless on my locale machine. However i'm currently not able to make it run within azure because of the following error:
TypeError: Object #<Object> has no method '_extend'
    at Function.init (D:\home\site\wwwroot\node_modules\finalhandler\node_modules\debug\src\node.js:234:28)
    at createDebug (D:\home\site\wwwroot\node_modules\finalhandler\node_modules\debug\src\debug.js:124:13)
    at Object.<anonymous> (D:\home\site\wwwroot\node_modules\finalhandler\index.js:14:28)
    at Module._compile (module.js:446:26)
    at Object..js (module.js:464:10)
    at Module.load (module.js:353:31)
    at Function._load (module.js:311:12)
    at Module.require (module.js:359:17)
    at require (module.js:375:17)
    at Object.<anonymous> (D:\home\site\wwwroot\node_modules\express\lib\application.js:16:20)

I tried already several solutions since i assume the origin of the error lies within the node module version used on azure web app services. However even changing the node version to the same i have locally didn't do the trick. In addition to prevent package correlation issues with my local installs i using a npm-shrinkwrap.
Has anyone got into the same troubles and might has a solution or a hint where to look further?

A: This article may answer your question.

Azure App Service does not support all native modules and might fail at compiling those with very specific prerequisites. Two workarounds proved successful with almost all native modules available today:

*

*Run npm install on a Windows machine that has all the native module's prerequisites installed. Then, deploy the created node_modules folder as part of the application to Azure App Service.

*Azure App Service can be configured to execute custom bash or shell scripts during deployment, giving you the opportunity to execute custom commands and precisely configure the way npm install is being run. For a video showing how to do this, see Custom Website Deployment Scripts with Kudu.


text:
Q: ¿Error con JOIN? Buen día, trataré de explicarme. Tengo las siguientes tablas, 'entradas' y 'categorias':

Lo que estoy buscando es obtener una consulta en la que me arroje como resultado las categorías y, a un lado, el numero de ocasiones que se ha usado esa categoría en la tabla 'entradas'.
Esto ya lo he logrado con la función INNER JOIN, así:
SELECT categorias.nombre, COUNT(*)
FROM entradas
INNER JOIN categorias ON categorias.id = entradas.id_categorias
GROUP BY id_categorias;

El resultado es este:

Ahora lo que intento es hacer lo mismo, pero que el resultado también me arroje la categoría que aun no se ha usado, en este caso 'Plataformas', y junto, me marque un 0 o NULL, algo que me indique que es una categoría aun sin usar. Para esto tengo entendido que me servirían las funciones LEFT JOIN o RIGHT JOIN, y lo he hecho así:
SELECT categorias.nombre, COUNT(*)
FROM entradas
RIGHT JOIN categorias ON entradas.id_categorias = categorias.id
GROUP BY id_categorias;

Pero me arroja esto:

En la categoría 'Plataformas' me marca 1, cuando debería aparecer 0. Intenté probar a quitar el GROUP BY, y me arroja esto:

Aparece una suma de 11, cuando en mi tabla entradas hay solo 10 registros. Parece como si existiera un registro en la tabla 'entradas' con el id_categorias=5 pero en realidad no es así. No entiendo que es lo que puede estar pasando.

A: Me parece que tu consulta debería ser reacomodada de este modo, para poder trabajar con LEFT JOIN para que obtengas todas las categorias que si tienen una o mas entradas asociadas y además aquellas categorías que no tienen ninguna asociada
SELECT categorias.nombre, COUNT(entradas.id_categorias)
FROM categorias
LEFT JOIN entradas ON categorias.id = entradas.id_categorias
GROUP BY id_categorias;

ACLARACIONES

*

*Selecciono primero el nombre de la categoría al ser la tabla del lado izquierdo en mi representación

*Hago el count() pero de la columna id_categorias puesto que es la llave foránea que vincula ambas tablas y es la que indica si el nombre de una categoría ha sido o no registrado

*En el FROM coloco que sea desde categoría

*Hago un LEFT JOIN para mostrar los datos de ambas tablas que esten vinculados y además me muestre los datos de la tabla izquierda categorias que aún no han sido utilizados, es decir el nombre de la categoria en la tabla de la derecha entradas

*En el ON igualo en que columnas se hace la vinculación entre ambas tablas

*Finalmente se queda el GROUP BY() del id_categorias
Aqui tienes un enlace donde puedes corroborar lo que te menciono
RESULTADO DE LA CONSULTA


text:
Q: TFS Constant Error Output TF10121: The path '' is not found or not supported. Type or select a different path Using TFS in Visual Studio 2013, another Team member made many changes to the solution structure (moving files between projects, new projects, new dtsx files, updating most files, consolidating connection managers).  After getting latest, whenever I open the solution the Output window now pops up and continuously lists the same error:
TF10121: The path '' is not found or not supported. Type or select a different path.
(this error repeats about once per second)
There is a similar post here for VS 2013 with similar error, though apparently not with the near constant repetition of the error and no help.
Pinning the Output window helps by at least preventing the constant stream of repeating errors from changing the focus while I work.
No change after reinstalling software.
Closing the solution stops the errors. Unloading all the projects stops the errors, but they resume when reloading.
Opening a file in the soln sometimes temporarily halts the errors.
Opening a local solution is fine, adding the solution to source control causes error to start

A: This seems to be an error with the workspace mappings. It may be that your workspace mapping contains a drive which is no longer available or another issue that breaks the workspace. Possible issues:

*

*Drive no longer available

*Inaccessible network drive

*Permissions are blocking access to a folder

*Your mapping may require you to run with Elevated Privileges.

*The target mapping may be empty

From the File -> Source Control and edit the workspace. If editing doesn't solve it, try deleting the workspace completely and creating a new one.

A: We using VS SSIS 2012, in solution folder I have .vssscc file and it has very short config info. I saw two parameters have empty value like ""
"PROJECT_FILE_RELATIVE_PATH" = ""
"ORIGINAL_PROJECT_FILE_PATH" = ""
So I changed to
"PROJECT_FILE_RELATIVE_PATH" = "."
"ORIGINAL_PROJECT_FILE_PATH" = "."
And seems removed message.  As you can see I have no explanation. Just tried and worked for me.

A: This happen to me in Visual Studio 2017 with a solution that contained a python project. One of the python environments was an old environment I deleted before. Once I removed that environment from the project the repeating error stopped.


text:
Q: How to continue to the next iteration using let in Racket? I am trying to modify the code from bellow so that when (when (= i 6) (loop (+ 1 i))) appears the loop to move to the next iteration without continuing doing with the "do stuff" part.
(let loop ([i 0])
  (cond
    [(= i 10) (printf "end\n")]
    [else
     (when (= i 6) (loop (+ 1 i)))
       (define x (+ 1 2)) ; do stuff
       (printf "~a\n" i)
       (loop (+ 1 i))]))

Basically what I'm trying to obtain is something similar to "continue" from C# (like the code from bellow), but using let in Racket:
for (int i = 0; i < 10; i++)
{
    if (i == 6)
    {
        continue;
    }
    Console.WriteLine(i);
}

If that's not possible (or recommended) in Racket, what can I use as an alternative?

A: Rewrite without continue by negating the condition:
for (int i = 0; i < 10; i++)
{
    if (i != 6)
    {
        Console.WriteLine(i);
    }
}

then as while instead of for:
int i = 0;
while (i < 10)
{
    if (i != 6)
    {
        Console.WriteLine(i);
    }
    i += 1;
}

and then this has almost exactly the same form:
(let loop ([i 0])
  (when (< i 10)
    (unless (= i 6)
      (printf "~a\n" i))
    (loop (+ 1 i))))

A: You can get the desired effect by adding one extra case to the cond expression. This is equivalent to your C# example:
(let loop ([i 0])
  (cond [(= i 10) (printf "end\n")]
        [(= i  6) (loop  (add1 i))]
        [else
         ; do some other stuff
         (printf "~a\n" i)
         (loop (add1 i))]))

You can "do stuff" after each condition, as long as the last expression is either the exit to the recursion or the recursive call - just remember that only the value of the last expression will be returned, and if you need to pass values to the next iteration, you'll need to add parameters to the recursive call.


text:
Q: ATK4: Handling many to many relationships in CRUD - Adding subCRUD without breaking Add New I'm trying to gracefully handle extra many to many relationship data in an ATK4 CRUD object. I can manually add the current entry's linked tables as sub CRUD objects while isEditing(), but in doing so i break the 'Add New' button. Code as follows:
    function page_projects($p) {
            $crud = $this->add('CRUD');
            $crud->setModel('Project', null, array('Title', 'School'));
            if($crud->grid){
                    $crud->grid->addPaginator(10);
                    $crud->grid->addQuicksearch(array('Title','School'));
            }

            if($crud->isEditing()){

                    $vForm = $crud->form;

                    $keywords = $vForm->add('CRUD');
                    $keywords->entity_name = 'Keyword';
                    $keywords->setModel(
                            $crud->model->load($crud->id)->
                                ref("mProjectKeywords"));
                    //Other snipped m:m rels
            }

    }

The issue is simply that $crud->id is not populated (and shouldn't be) when generating a new entry, which means i can't spawn new sub cruds. A workaround is to use:
    if($crud->isEditing() && !is_null($crud->id)) {

when checking isEditing(), but this simply stops the sub CRUDS from being instantiated to avoid having load() throw an exception. I've tried looking at loadAny() and tryLoad() and neither do what i want in a many to many context: load a record if one exists, generate a new one otherwise.
Does anyone know a better way of handling this, and if there's not already one in the framework then what's the best angle for attacking this problem?

A: In this case that's normal behavior because you simply can't create mProjectKeywords record in database table before you INSERT referenced records in parent tables (Project and Keywords).
I do something like if($crud->isEditing() && !is_null($crud->id)) in my projects too.
That means you first have to save (insert) new record in Project and only then sub-CRUD shows up and you can add referenced records in Project edit form (which reloads automatically after you save new project).


text:
Q: $_SESSION Se pierde al pasar de mi login a index quisiera hacer una consulta, estoy intentando realizar un login, estoy seguro de que se está efectuando bien porque se está validando el usuario y la contraseña, el problema es de que cuando realizamos la redirección a "index.php" antes de eso creo $_SESSION con valores como "Nombre, Apellido, etc" pero cuando los intento acceder nuevamente estos aparecen vacíos o que no existen.
Código PHP AUTENTICAR.PHP
<?php
session_start();
include( 'acceso_db.php' );
global $wrongPwdErr, $accountNotExistErr, $emailPwdErr, $verificationRequiredErr, $email_empty_err, $pass_empty_err;
if ( isset( $_POST[ 'iniciar' ] ) ) {
  $usuario_login = $_POST[ 'username' ];
  $password_login = $_POST[ 'pwd' ];

  $pwd_cryp = mysqli_real_escape_string( $conn, $password_login );

  $sql = "SELECT * FROM usuarios WHERE usuario_email = '{$usuario_login}'";
  $query = mysqli_query( $conn, $sql );
  $rowCount = mysqli_num_rows( $query );
  if ( !$query ) {
    die( "Sql Query Failed" . mysqli_error( $conn ) );
  }
  if ( $rowCount <= 0 ) {
    $accountNotExistErr = '

            El usuario ingresado no existe.

';
  } else {
    while ( $row = mysqli_fetch_array( $query ) ) {
      $usuario_id = $row[ 'usuario_id' ];
      $usuario_nombre = $row[ 'usuario_nombre' ];
      $usuario_apellido = $row[ 'usuario_apellido' ];
      $usuario_email = $row[ 'usuario_email' ];
      $usuario_clave = $row[ 'usuario_clave' ];
      $is_active = $row[ 'is_active' ];
      session_regenerate_id();
      $_SESSION[ 'loggedin' ] = TRUE;
      $_SESSION[ 'usuario_id' ] = $usuario_id;

      $_SESSION[ 'usuario_nombre' ] = $usuario_nombre;

      $_SESSION[ 'apellido' ] = $usuario_apellido;

      $_SESSION[ 'emailDash' ] = $usuario_email;

      $_SESSION[ 'user_Active' ] = $is_active;
    }

    $password = password_verify( $password_login, $usuario_clave );

    if ( $is_active == '1' ) {
      if ( $usuario_login == $usuario_email && $password_login == $usuario_clave ) {

        echo "";
        //echo "";
      } else {
        $emailPwdErr = '

                Usuario y/o contraseña incorrectos.

';
      }
    } else {
      $verificationRequiredErr = '

                            Se requiere la verificación de la cuenta para iniciar sesión.

';
    }
  }
}
?>

Codigo Simple INICIO
<?php
session_start();
if ( isset( $_SESSION[ 'usuario_nombre' ] ) ) {
  ?>
<!doctype html>

<meta charset="utf-8">
<title>Sitio Ejemplo Datos</title>

<?php echo "{$_SESSION['usuario_nombre']}"; ?>1

 Logout

<?php
} else {
  echo "";
}
?>

Agradeceria que pudieran ayudarme, pues llevo mucho rato ya intentando solventarlo.


text:
Q: Como faço para uma janela não ser fechada? PySimpleGUI Preciso desativar as opções da janela feita no PySimpleGUI e possibilitar o fechamento somente se acertar a senha numa caixa de texto.
meu codigo:
sg.theme('DarkRed')
layout = [
    [sg.Text('Senha'), sg.Input(key='senha', password_char='*')],
    [sg.Button('Liberar')]
]

janela = sg.Window('', layout)

while True:
    eventos, valores = janela.read()
    if eventos == sg.WINDOW_CLOSED:
        Mbox('Titulo', 'Você não pode fechar', 0)
        continue
    if eventos == 'Liberar':
        if valores ['senha'] == '123456':
            Mbox('Titulo', 'Liberado', 0)
            break

        else:
            Mbox('Titulo', 'Senha errada', 0)

Abaixo do sg.WINDOW_CLOSED eu já tentei colocar um continue ou um pass mas não funcionou.
Alguma forma de desativar a função, esconder ou fazer o programa abrir toda hora que for fechado?

A: Para fazer isto, você pode adicionar o método enable_close_attempted_event=True na sua variável janela, exemplo:
janela = sg.Window('', layout, enable_close_attempted_event=True)

O recurso retornará um evento de confirmação de tentativa de fechamento da janela ao invés de fechá-la, exibindo uma mensagem personalizada e a janela continuará ativa. Então, adicione a verificação do evento na tentativa de fechamento da janela:
if eventos in (sg.WINDOW_CLOSED, sg.WINDOW_CLOSE_ATTEMPTED_EVENT):
   Mbox('Titulo', 'Você não pode fechar', 0)

Não se esqueça de terminar seu código com janela.close() para não gerar nenhum erro ao finalizar a estrutura de repetição e fechar a janela.
Mais sobre o método Window Close Confirmation Aqui


text:
Q: What is a possible strategy to save/restore a GUI with Qt? I want to implement the open/save functions of a GUI built with Qt and based on a QMainWindow. The whole GUI contains several QStandardItemModel, QLineEdit, QGroupBox, QSpinBox...
The first idea i have is to take all the widgets, class or model to be save and add a saveToFile / openFromFile methods, using QFile and QDataStream for data serialization.
The global architecture is a kind of implementation of the Smart UI approach however i am mixing MVC triads, and widgets inside the QMainWindow.
The GUI is not that big but i wonder if there are existing strategy to implement this open/save feature, in terms of software architecture.
I guess there are much clever ways to do so, and i am looking for any documentation or design pattern that can be used in general for this purpose.
Thanks.


text:
Q: How to display first page as a single page in a "Thesis" class I am writing a thesis and and I would like to view/see first page of my thesis as a single page in PDF and rest is Two pages.
I have seen this in Krishna Kumar template (https://gitlab.com/kks32/phd-thesis-template). But I have done so much that it is difficult for me to apply his template.
Problem - Currently, my first page is appears as two page. So, my each chapter title pages are starting from left side but it should start from right side. If I can print the first page (title page) as single page then my "chapter title pages" will start from right side.


text:
Q: Postgres cannot connect to server Super stumped by why Postgres isn't working on a new app I just started. I've got it working for one app already. I'm using postgres.app, and it's running.
I started a new app with
rails new depot -d postgresql

and then I went into the database.yml file and changed username to my $USER (which is what it is for the other app, which is working). So now my database.yml file has this development section:
development:
  adapter: postgresql
  encoding: unicode
  database: depot_development
  pool: 5
  username: <username>
  password:

But when I run "rake db:create" or "rake db:create:all" I still got this error (in full, cause I don't know what's relevant):
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "database"=>"depot_development", "pool"=>5, "username"=>"<username>", "password"=>nil}
could not connect to server: Permission denied
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `initialize'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `new'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `connect'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:329:in `initialize'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `new'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `postgresql_connection'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:309:in `new_connection'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:319:in `checkout_new_connection'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:241:in `block (2 levels) in checkout'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `loop'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `block in checkout'
/Users/<username>/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:233:in `checkout'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:96:in `block in connection'
/Users/<username>/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:95:in `connection'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:404:in `retrieve_connection'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:170:in `retrieve_connection'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:144:in `connection'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:107:in `rescue in create_database'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:51:in `create_database'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (3 levels) in <top (required)>'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `each'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (2 levels) in <top (required)>'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `call'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `block in execute'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `each'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `execute'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/Users/<username>/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/task.rb:144:in `invoke'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:116:in `invoke_task'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block (2 levels) in top_level'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `each'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block in top_level'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:88:in `top_level'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:66:in `block in run'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/gems/rake-0.9.2.2/bin/rake:33:in `<top (required)>'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/bin/rake:19:in `load'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/bin/rake:19:in `<main>'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `eval'
/Users/<username>/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `<main>'
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "database"=>"depot_test", "pool"=>5, "username"=>"<username>", "password"=>nil}

I have tried
createdb depot_development

I have tried going into the psql environment and listing users (which included my username among them). In the same psql environment, I tried
CREATE DATABASE depot;

I've made sure that the pg gem is installed with bundle install, I've run "pg_ctl start", to which I got this response:
pg_ctl: no database directory specified and environment variable PGDATA unset

I ran "ps aux | grep postgres" to make sure postgres was running, to which I got this in return (which looks like it's doing OK, right?):
<username>    10390   0.4  0.0  2425480    180 s000  R+    6:15PM   0:00.00 grep postgres
<username>     2907   0.0  0.0  2441604    464   ??  Ss    6:17PM   0:02.31 postgres: stats collector process
<username>     2906   0.0  0.0  2445520   1664   ??  Ss    6:17PM   0:02.33 postgres: autovacuum launcher process
<username>     2905   0.0  0.0  2445388    600   ??  Ss    6:17PM   0:09.25 postgres: wal writer process
<username>     2904   0.0  0.0  2445388   1252   ??  Ss    6:17PM   0:12.08 postgres: writer process
<username>     2902   0.0  0.0  2445388   3688   ??  S     6:17PM   0:00.54 /Applications/Postgres.app/Contents/MacOS/bin/postgres -D /Users/<username>/Library/Application Support/Postgres/var -p5432

The short of it, is I've been troubleshooting for a WHILE and have NO idea what's wrong. Any ideas? I'd really appreciate it, cause I'm pretty new to Rails, and this is a pretty disheartening roadblock.
Thanks!
EDIT -- Per request, posting the successful database.yml . It seems the difference is the inclusion of a password:
development:
  adapter: postgresql
  encoding: unicode
  database: *******_development
  pool: 5
  username: *******
  password: *******

EDIT2 -- When I add a password to the .yml file, then run rake db:create again, I get the same error. And I'm running Mac OSX Lion, and I did initdb and stuff when I first installed PostgreSQL.

A: In order to create a database , before starting the command pg_ctl start

*

*you have to initialize the database cluster then only pg_ctl start shall be success full*

this can be done in many ways
if you are running on Linux / centos with postgres 9.1

service postgresql-9.1 initdb

service  postgresql-9.1 start

or you can do like this
$ mkdir -p /var/pgsql/data; chown -R postgres /var/pgsql
$ su - postgres
$ initdb -D /var/pgsql/data

# Starting, testing:

$ postgres -D /var/pgsql/data > /var/pgsql/logfile 2>&1 &
$ createdb test
$ psql test

Initializing postgres initb differes from os to os and postgres versions , if the above command did not work please have a look at

A: Adding
host: localhost

to development works for me.


text:
Q: SVG in CSS is interpreted via webpack with "module.exports = 'data:...'" instead of valid svg I use webpack to compile scss. The scss also  contains url to svg files, which I need to process and link to css with correct url.
However, instead of a valid svg, I get a file (eebc108eb2b00c4b2784.svg) with the following content:
module.exports = "data:image/svg+xml,%3csvg width='30px' height='30px' xmlns=...'
which is linked to css like:
background-image: url(../eebc108eb2b00c4b2784.svg);
That is what i want basically, but svg obviously dont show. This SVG is not used anywhere in JS only in CSS.
My webpack config looks like this:

const webpack = require("webpack");
const path = require("path");
const AssetsPlugin = require("assets-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin")

let config = {
    watch: true,
    entry: {
        appAdmHomepage: "./_devapp/AppAdmHomepage.js",
        cssStyle: "../css/primary/style.scss",
        cssAdm: "../css/primary/administrace.scss",
        cssPrint: "../css/primary/print.scss",
        cssObjProces: "../css/primary/objednavkovy_proces.scss",
        cssDesign: "../css/primary/design.scss",
    },
    output: {
        filename: "[name].bundle.js",
        chunkFilename: "[name].[contenthash].js",
        path: path.resolve(__dirname, "assets", "bundle")
    },
    resolve: {
        extensions: [".js", ".jsx", ".json", ".ts", ".tsx", ".css", ".scss"]
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: path.resolve(__dirname, "node_modules"),
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: [
                            "@babel/preset-env",
                            ["@babel/preset-react",{
                                "runtime": "automatic"
                            }]
                        ],
                        plugins : [
                            ["@babel/plugin-proposal-decorators", { version: "legacy" }],
                            "@babel/plugin-syntax-dynamic-import",
                            "@babel/plugin-proposal-class-properties",
                            "@babel/plugin-proposal-private-methods",
                        ]
                    }
                },
            }, {
                test: /\.svg$/,
                use: [
                    {
                        loader: "svg-url-loader",
                        options: {
                            name: "./image/[name]--.[ext]"
                        },
                    },
                ],
            }, {
                test: /\.scss$/,
                include: [
                    path.resolve(__dirname, "../css/primary/")
                ],
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: "css-loader",
                        options: {
                            url: true,
                            import: true
                        }
                    },
                    "sass-loader"
                ]
            }, {
                test: /\.css$/, //pro datepicker
                use: [
                    "style-loader",
                    {
                        loader: "css-loader",
                        options: {
                            url: true
                        }
                    }
                ]
            }
        ],
    },
    plugins: [
        new webpack.DefinePlugin({
            "__DEV__" : JSON.stringify(true),
            "__API_HOST__" : JSON.stringify("http://127.0.0.1:8080/www/eshop/www"),
            "__PATH_HOST__" : JSON.stringify("/www/eshop/www"),
        }),
        new AssetsPlugin({
            prettyPrint: true,
            removeFullPathAutoPrefix: true,
            fullPath: true
        }),
        new MiniCssExtractPlugin({
            filename: "./css/[name].min.css"
        }),
        new CleanWebpackPlugin()
    ]
};

module.exports = config;

Is there a way to link correct form of SVG or am i making a mistake somewhere? Thanks for help


text:
Q: How can write physics in terms of local rest frame? Many times I saw that people wrote that we write the equations in terms of local rest frame, for example in the paper of Novikov and Thorne that calculated stress-energy tensor for Kerr blackhole among others, and they got some result for shear stress and all quantities, but no where I could find how people in practice do it? For example in Schwarzschild case, it's easy that is mentioned in Carroll lecture, but have you ever seen somewhere for other cases?

A: For this, we need to find the set of basis that they are orthogonal to each other and unit one. For example in polar coordinate we have $ds^2=dr^2+sin\theta d\theta^2$.
$|e_{\theta}|$ is not 1. we should divide it by $sin\theta$. Then we can introduce the new $e_\theta$ to be $1/sin\theta$ $e_{\theta}$ and so on.


text:
Q: How to format old disk after installing new boot disk? I just installed a 250 GB m.2 SSD as a Windows 10 boot drive on an Acer Aspire E15. The computer previously had Windows 10 installed on a 1 TB HDD.
This is what my current configuration looks like:

Disk 1 is the SSD boot drive running Windows 10. Currently, the EFI System Partition appears to be listed as a boot drive during restarts, which is a problem. How can I format Disk 0 (the old 1TB HDD) so that the drive contains a single partition with no strings attached?
I have tried the following DISKPART commands with no success (See errors below).
DISKPART> list disk

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
* Disk 0    Online          931 GB  1041 MB        *
  Disk 1    Online          232 GB      0 B        *

DISKPART> delete disk override

The disk you specified cannot be deleted.
Please select an empty missing disk to delete.

DISKPART> list disk

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
* Disk 0    Online          931 GB  1041 MB        *
  Disk 1    Online          232 GB      0 B        *

DISKPART> clean

Virtual Disk Service error:
Clean is not allowed on the disk containing the current boot,
system, pagefile, crashdump or hibernation volume.

A: You still have partitions on the disk, delete these first then try delete disk
You also need to 'select' the disk, before trying to delete anything.
list disk
select disk 1
list partition
select partition 1
delete partition
.... and so on.


text:
Q: How ActionScript Can Get Data From ASHX With This code I upload selected Files . That works without problem and at after uploading file i want to send "uploadedFilelist" as json or string to Actionscript . the problem is i don`t know how can i pass this data to Actionscript and also i dont know how can i get this data in ActionScript . ( That is My firs experience with AS )
ActionScript Code :
package
{
import flash.external.*;
import flash.net.FileReferenceList;
import flash.net.FileReference;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.system.Security;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.FileFilter;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;

public class MultiSelectClass extends MovieClip
{
    private var fileRefList:FileReferenceList=new FileReferenceList();
    private var myRequest:URLRequest;
    private var serviceUrl:String ="";
    private var metaData:String="";

    function MultiSelectClass()
    {
        Security.allowDomain("*");

        fileRefList.addEventListener(Event.SELECT,selectHandler);
        fileRefList.addEventListener(Event.COMPLETE,completeHandler);
        myButton.addEventListener(MouseEvent.CLICK,myButtonClick);

        serviceUrl=ExternalInterface.call("MultiFileUploaderFunc.GetServiceUrl");
        myRequest = new URLRequest(serviceUrl);

        metaData = ExternalInterface.call("MultiFileUploaderFunc.GetMetdaData")
    }

    function myButtonClick(ev:MouseEvent):void
    {
        var swfTypeFilter:FileFilter = new FileFilter("Text Files","*.txt; *.html;*.htm;*.php");
        var allTypeFilter:FileFilter = new FileFilter("All Files (*.*)","*.*");
        fileRefList.browse([swfTypeFilter,allTypeFilter]);
    }

    function selectHandler(e:Event):void
    {
        var vars:URLVariables = new URLVariables();
        myRequest.method = URLRequestMethod.POST;

        for each (var file:FileReference in fileRefList.fileList)
        {
            file.addEventListener(Event.COMPLETE, completeHandler);
            file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);

            vars.fileData = file.data;
            vars.metaData= metaData;
            myRequest.data = vars;

            file.upload( myRequest);
        }
    }

    function completeHandler(e:Event):void
    {
        ExternalInterface.call("alert","Ok!");
    }

    private function securityErrorHandler(event:SecurityErrorEvent):void
    {
        ExternalInterface.call("alert","Security Problem !");
    }

    private function ioErrorHandler(event:IOErrorEvent):void
    {
        ExternalInterface.call("alert","I/O Problem !");
    }
}
}

Generic Handler Code :
 public class Handler1 : IHttpHandler
 {

public void ProcessRequest(HttpContext context)
{
  if (context.Request.Params["metaData"] == string.Empty)
    return;

  var metaData = context.Request.Params["metaData"];

  var jss = new JavaScriptSerializer();

  var metadataDictionary = jss.Deserialize<dynamic>(metaData);

  var jsFileType = metadataDictionary["FileType"];

  var uploadedFilelist = new List<FileModel>();

  foreach (string file in context.Request.Files)
  {
    var httpFile = context.Request.Files[file];

    if (httpFile.ContentLength == 0)
      continue;

    string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,   "Upload\\", Path.GetFileName(httpFile.FileName));
    httpFile.SaveAs(savedFileName);

    var uploadedFile = new FileModel
    {
      Extension = System.IO.Path.GetExtension(httpFile.FileName),
      Id = ID,
      MimeType = httpFile.ContentType,
      Name = httpFile.FileName,
      FileType = jsFileType
    };

    uploadedFilelist.Add(uploadedFile);
  }

  context.Response.ContentType = "application/json";
  context.Response.Write(jss.Serialize(uploadedFilelist));

}

A: It's rather simple. You just add DataEvent.UPLOAD_COMPLETE_DATA event listener and get data.
fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadCompleteHandler);

private function uploadCompleteHandler(event:DataEvent):void {
    trace(event.data); //response data
}


text:
Q: C# unassigned static int results to zero while experimenting static variables I was amazed to know why the static "int" result to 0 (zero) and non-static result to compile time error.
Consider Case 1
  static int i;
  static void Main()
  {
     Console.Write("Value of i = " + i);
     Console.ReadKey();
  }

the output is
 Value of i = 0

Case 2 with removing static
  static void Main()
  {
     int i;
     Console.Write("Value of i = " + i);
     Console.ReadKey();
  }

And the output for this will result to compile time error
  Error 1   Use of unassigned local variable 'i'

question here is how do both cases differ i.e first one result to 0 and another get compiler error.

A: The existing answers all miss something important here, which is where the variable is declared. Is it a class variable or a local variable
In the first scenario
class Program
{
    static int i;
    static void Main()
    {
       Console.Write("Value of i = " + i);
       Console.ReadKey();
    }
}

The variable i is declared as a class variable. Class variables always get initialized, it doesn't matter if it's static or not. If you don't provide a default value, the variable is assigned default, which in the case of int is 0.
On the other hand, in the second example
class Program
{
    static void Main()
    {
        int i;
        Console.Write("Value of i = " + i);
        Console.ReadKey();
    }
}

Variable i is local variable. Unlike class variables, local variables are never initialized with a default value implicitly, but only when you explicitly initialize them. So the compiler error comes not from the variable being static or not, but from the difference in initialization between local and class variables.
The specification shares some more details on that: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables, especially sections 9.2 Variable Types and 9.3 Default Values.
The interesting parts are

9.2.2 The initial value of a static variable is the default value (§9.3) of the variable's type.

9.3.2.2 The initial value of an instance variable of a class is the default value (§9.3) of the variable's type.

9.2.8 A local variable introduced by a local_variable_declaration is not automatically initialized and thus has no default value. Such a local variable is considered initially unassigned.

9.3: The following categories of variables are automatically initialized to their default values:

*

*Static variables.

*Instance variables of class instances.

*Array elements.

The underlying reason for this has to do with memory management. When you initialize a class with new() the garbage collector zeros out all bytes on the heap, thus basically defaulting the value of the variable. In case of integers this is 0, for an object reference it would be a null.
Since local variables live on the stack, and the garbage collector doesn't live work on the stack, this guarantee does not exist, so we have explicitly initialize a variable before using it.

A: by definition of the C# language, types have "default values", which are assigned to them if you don't assign something else. numbers have a default value of 0, boolean - false, reference types - null, and structs - each member by it's type.

A: Based on my limited understanding, by declaring a variable as static, it becomes existing in memory and is assigned a default value of 0, and does not depend on an instance of the class it is in to exist.
If it is not defined as static, it needs to be initialized within the class(as in, given a value) before it can be used in any logic/math.
Now my confusion comes from being very new, and trying to understand exactly WHY you would choose to do something like this one way, instead of another. Perhaps this is a way to have some values that persist that may be necessary even when the class it is in is not existing, and making everything static would result in ineficient use of memory.

A: The fundamental reason why you do not get a compilation error for the static scenario is because the compiler has no way to be sure that it is not initialized before being read.
Indeed, a static class member without visibility modifier is internal by default. This means that another class of the same assembly could define it before the Main method is called.
And even if it were private, an external code could still define its value using classes in the System.Reflection namespace.
Whereas, for the local variable case, the compiler is sure that no other code could define the variable between its declaration and its first reading.
Indeed, local variables are not accessible outside their declaration scope to non debugging code.


text:
Q: Lombok Getter & Setter not working in bean having custom deserializer The issue is I use Lombok annotations @Getter and @Setter with beans which are used to parse JSON files.
The issue is I noticed for attribute with custom deserializer, Jackson is not using this custom deserializer and I get error like:
For boolean field, only true or false are recognized

while I'm receiving "no" for false, and "yes" for true.
@JsonProperty(value = "comment")
@JsonDeserialize(using = NoYesDeserializer.class)
private Boolean comment;

I put the annotation on the class level : @Data and @NoArgsConstructor
public class NoYesDeserializer extends JsonDeserializer<Boolean> {

@Override
public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        if (StringUtils.isNotBlank(p.getText())) {
            String text = p.getText();
            if (text.toLowerCase().indexOf("yes") >= 0) {
                return Boolean.TRUE;
            } else if (text.toLowerCase().indexOf("no") >= 0) {
                return Boolean.FALSE;
            }
        }

        throw new IOException("Unrecognized boolean value " + p.getText());
    }
}


text:
Q: java.security.AccessControlException: access denied ("java.awt.AWTPermission" "accessClipboard") When I load my applet I get the Exception
java.security.AccessControlException: access denied ("java.awt.AWTPermission" "accessClipboard").
Have googled for couple of hours and have seen the answers like,

*

*Adding the permissions in java policy - This is strictly internal process. But need to work in all machines.

*Adding applet tag instead of object - Didn't work for me.

*Keytool to be used to sign the applets - Have added the custom certificate to sign the applets. Still getting the exception.
Please help out guys.

A: You can try using Javascript within Java to get to the privileged methods:
http://blog.pengoworks.com/index.cfm/2008/2/19/Accessing-privileged-methods-in-a-Java-Applet-via-JavaScript

A: @yakovsh : The blog is really helpful. Just a small change worked for me...
java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction(){
            public Object run() {
                // execute the privileged command
                executeCommand(cmd);
                // we must return an object, so we'll return an empty string
                return new Object();
            }
        }
    );

The only change is with the return statement from return "" to return new Object()


text:
Q: Printing preview doesn't working laravel-dompdf I'm developing an aplication to manage multiples branches for a fast food locale, it's up in a shared hosting, and trying to use barryvdh/laravel-dompdf library to print in a thermal printer (client side) two tickets (one for invoice and other for order). The idea is when the invoice is registered, then show the options to print the two tickets. But right now the web print preview doesn't show, only register the invoice and log show this error 'PrinterController::pdf Invalid characters passed for attempted conversion, these have been ignored'. The aplication uses Laravel 5.8, php 7.3 and laravel-dompdf 0.8.5.
I would appreciate any help, I've been stuck for several days with this...
SalesController:
public function store(Request $request){

        try{

            $data = $request->all();
            $client = json_decode($data['client']);
            $till = Till::where('id', session('till'))->first();

            DB::beginTransaction();

            // ============================= INVOICE CREATION ==================================
            $branch_id = Branch::where('id', auth()->user()->branch_id)->pluck('code')->first();
            $user_code = (integer) substr((string) auth()->user()->ci, -3);
            $previous_id = Invoice::whereRaw("id = (select max(id) from invoices where id like '" . $branch_id . $user_code . "%')")->pluck('id')->first();

            if ($previous_id == null) {
                $pre_id = $branch_id . $user_code;
                $id = str_pad($pre_id, 10, "0", STR_PAD_RIGHT);
            }

            if ($previous_id != null)
                $id = $previous_id + 1;

            $invoice = new Invoice();
            $invoice->id = $id;
            $invoice->payment_id = 1;
            $invoice->client_id = $client->id;
            $invoice->received = $data['total_received'];
            $invoice->total = 0;
            $invoice->save();

            // ============================= INVOICE DETAIL ====================================

            $product_detail = $request->session('products')->all();
            $sum = 0;
            foreach ($product_detail['products'] as $item) {
                $detail = new InvoiceDetail();
                $detail->invoice_id = $invoice->id;
                $detail->product_id = $item->id;
                $detail->quantity = $item->quantity;
                $detail->sub_total = (integer) $item->quantity*(integer) $item->price;// modificar a sub total
                $detail->save();

                $sum += $detail->sub_total;

                $actual_stock = Stock::where('product_id', $item->id)->where('branch_id', auth()->user()->branch_id)->first();
                $new_stock = (integer) $actual_stock->quantity - (integer) $item->quantity;

                if ($item->quantity > $actual_stock->quantity)
                    return redirect()->back()->with('error', 'La cantidad solicitada supera el stock disponible');

                $stock = Stock::find($actual_stock->id);
                $stock->quantity = $new_stock;
                $stock->save();

                $stock_history = new StockHistory();
                $stock_history->stock_id = $stock->id;
                $stock_history->product_id = $item->id;
                $stock_history->type = 'sales';
                $stock_history->old_quantity = $actual_stock->quantity;
                $stock_history->new_quantity = $new_stock;
                $stock_history->ext_trans = $invoice->id;
                $stock_history->user_id = auth()->user()->id;
                $stock_history->save();
            }

            // ================================= ORDER =========================================

            $order = new Order();
            $order->invoice_id = $invoice->id;
            $order->status = 0;
            $order->save();

            // ================================= SALES =========================================

            $sales = new Sales();
            $sales->invoice_id = $invoice->id;
            $sales->client_id = auth()->user()->id;
            $sales->till_id = session('till');
            $sales->save();

            // ============================= TILL_TRANSACTION ==================================

            $invoice = Invoice::find($invoice->id);
            $invoice->total = $sum;
            $invoice->save();

            foreach (session('products') as $item) {
                $old_quantity = Stock::where('product_id', $item->id)->where('branch_id', auth()->user()->branch_id)->first();
                $update = Stock::find($old_quantity->id);
                $update->quantity = $old_quantity->quantity - $item->quantity;
                $update->save();
            }

            $till_transaction = new TillTransaction();
            $till_transaction->till_id = session('till');
            $till_transaction->type_id= 3;
            $till_transaction->detail_id = $sales->id;
            $till_transaction->cash_before_op = $till->actual_cash;
            $till_transaction->cash_after_op = $till->actual_cash + $invoice->total;
            $till_transaction->user_id = auth()->user()->id;
            $till_transaction->save();

            DB::commit();

            $branch = Branch::where('id', auth()->user()->branch_id)->pluck('name')->first();
            $change = $invoice->received - $invoice->total;

            $printer = new PrinterController();
            $printer->printPDF($invoice, $product_detail['products'], $branch, $change, $order);

            session(["products"=>[]]);

            return redirect()->back()->with('success', 'Se ha registrado la venta');

        } catch (\Exception $e){
            DB::rollBack();
            Log::error('SalesController::store ' . $e->getMessage(), ['error_line' => $e->getLine()]);
            return redirect()->back()->with('error', 'Oops parece que ocurrio un error, por favor intente nuevamente.');
        }
    }

PrinterController:
namespace App\Http\Controllers;

use Barryvdh\DomPDF\Facade as PDF;
use Illuminate\Support\Facades\Log;

class PrinterController extends Controller
{
    public function printPDF($invoice, $products, $branch, $change, $order){

        try{

            $data = [
                'invoice' => $invoice,
                'product_detail' => $products,
                'branch' =>  $branch,
                'change' => $change,
                'order' => $order
            ];

            $invoice = PDF::loadView('ticket.invoice', $data);
            return $invoice->stream('test.pdf');

        } catch (\Exception $e){
            Log::error('PrinterController::pdf ' . $e->getMessage(), ['error_line' => $e->getLine()]);
            return redirect()->back()->with('error', 'Oops parece que ocurrio un error al imprimir el ticket.');
        } catch (\Throwable $e) {
            Log::error('PrinterController::pdf ' . $e->getMessage(), ['error_line' => $e->getLine()]);
            return redirect()->back()->with('error', 'Oops parece que ocurrio un error al imprimir el ticket.');
        }

    }
}

Invoice view:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

Nro de Orden: {{ $order->id }}

Nro Factura: {{ $invoice->id }}

Fecha: {{ date( "d/m/Y", strtotime($invoice->created_at)) }}    Hora: {{ date( "H:i:s", strtotime($invoice->created_at)) }}

            Articulo
            Cant.
            Precio
            Sub Total

        @foreach($product_detail as $product)

                {{ $product->name  }}
                {{ $product->quantity  }}
                {{ $product->price }}
                {{ (integer) $product->quantity * (integer) $product->price  }}

        @endforeach

                Total:
                {{ $invoice->total }}

                Recibido:
                {{ $invoice->received }}

                Su Vuelto:
                {{ $change }}

Local: {{ $branch  }}

Cajero: {{ auth()->user()->name }}

Gracias por su compra!

--------------------------------------------

DOCUMENTO NO VALIDO COMO FACTURA

Order View:

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="{{ asset('fontawesome/css/all.css') }}" rel="stylesheet">

ORDEN N° 002517

=============================

=============================

Solicitado: 2019/12/30 -- 22:51:33

            Art.
            Cant.

            Producto de prueba
            10

A: The error you're seeing

Invalid characters passed for attempted conversion, these have been ignored

is a PHP error related to parsing content from the font metrics. This issue (ref #2003) should be addressed in the recently-released 0.8.4 version of Dompdf.
Since laravel-dompdf required Dompdf 0.8 you should be able to composer update your install and hopefully see a the issue go away.