text:
Q: Workflow not firing for new documents uploaded to a document library I have a doc lib that has several meta fields in it. I have a workflow that processes the doc based on these fields. Everything runs fine when the doc already exists in the library.
If we add a new one by uploading (I havent tried New) the workflow doesn't fire properly. Looking at the debugger, when I click Upload, browse to select the file then click OK, the workflow fires. At this point, my meta data is empty as it's a new upload.
Then SP sends me to the edit properties page for the doc (editform.aspx). I now fill out my meta data and click ok. The workflow doesn't fire again. If I go back into edit properties and click OK, it fires.
We need this to fire on the first edit page. As a work around I'm instructing my customer to upload it, then close it then edit it again. Not cool.
Any ideas?

A: When you add a document to a Document Library, there are two steps, as you know: Upload and Edit.  The Upload step is like the New step in other lists; that's when the document item is actually created.  It sounds like you want your workflow to run on the item change instead.  If you only want the workflow to do its thing on the first edit of the item, then make sure to set a value that indicates it has already run or compare the Created and Modified dates, etc.
M.

A: I've seen his behavior too.
As a workaround, how about checking whether the metadata is empty and, if it is, delaying for a few minutes before rechecking the metadata?

A: The workaround we ended up using is to require content to be checked out, that way on upload, the file is checked out and the WF doesn't run. Then they can fill in the meta data then click Check In and then the WF fires properly. Thanks all

A: Use an on Item changed activity in your workflow, if you have a task changed activity later in your workflow then this will break. Work around is to use a sequence activity and inside it put an initializeworkflow activity followed by the on item changed activity both using the correlation token from the sequence activity

A: We have the same issue. Actually we needed a Workflow to create an item in a list when a document was added to a library.
What I had to do was run the workflow when an Item is changed, the first check was for one of the Meta Data fields to not be empty and the Version is 2.0


text:
Q: Following c# code doesn't display the certificates present in local machine public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }
    public string Name { get; set; }
    public string HasPrivateKey { get; set; }
    public string Location { get; set; }
    public string Issuer { get; set; }

    private void button1_Click(object sender, EventArgs e)

    {
        var stores = new Dictionary<StoreName, string>()
        {
            { StoreName.My,"Personal"},
            { StoreName.Root,"Trusted roots"},
            { StoreName.TrustedPublisher,"Trusted Publishers"}
        }.Select(s => new { store = new X509Store(s.Key, StoreLocation.LocalMachine), Location = s.Value }).ToArray();
        foreach (var store in stores)
            store.store.Open(OpenFlags.ReadOnly);
        var list = stores.SelectMany(s => s.store.Certificates.Cast<X509Certificate2>().Select(mCert => new Form1
        {
            HasPrivateKey = mCert.HasPrivateKey ? "Yes" : "No",
            Name = mCert.FriendlyName,
            Location = s.Location,
            Issuer = mCert.Issuer
        })).ToList();

    }
}

I have used windows form application in c#.
If I click the button it has to display the available certificates present in local machine onto listbox. But I don't know how to display the available certificates.. Pls give suggestions.

A: *

*You create a new Form1 instance for each certificate.

*You do not refer to any existing listbox

try this:
public partial class Form1 : Form
{

    //declare new listbox
    ListBox lbCerts;

    public Form1()
    {
        InitializeComponent();
        //add a listbox to the form
        lbCerts = new ListBox();
        lbCerts.DisplayMember = "Name";
        this.Controls.Add(lbCerts);
    }

    //class represent certificate
    class myCer
    {
        public string Name { get; set; }
        public string HasPrivateKey { get; set; }
        public string Location { get; set; }
        public string Issuer { get; set; }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var stores = new Dictionary<StoreName, string>()
            {
                { StoreName.My,"Personal"},
                { StoreName.Root,"Trusted roots"},
                { StoreName.TrustedPublisher,"Trusted Publishers"}
            }.Select(s => new { store = new X509Store(s.Key, StoreLocation.LocalMachine), Location = s.Value }).ToArray();
        foreach (var store in stores)
            store.store.Open(OpenFlags.ReadOnly);
        //create list of myCer
        var list = stores.SelectMany(s => s.store.Certificates.Cast<X509Certificate2>().Select(mCert => new myCer
        {
            HasPrivateKey = mCert.HasPrivateKey ? "Yes" : "No",
            Name = mCert.FriendlyName,
            Location = s.Location,
            Issuer = mCert.Issuer
        })).ToList();
        //populate listbox
        lbCerts.DataSource = list;

    }
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Render filter component in a dialog I'm trying render filter(s) in a mat-dialog, I came to a point where it is rendered correctly, but functionally not usable and I'm not sure if this is the right way or not.
here is the code
here is how I create and open the dialog:
  public lol(colDef: ColDef): void {
    console.log(colDef);

    this.gridApi?.getFilterInstance(colDef.field, (foo) => {
      console.log(foo.getModel());
      foo.setModel(foo.getModel());

      this.dialog.open(FilterWrapperDialogComponent, {
        data: {
          filterHtml: foo.getGui()
        },
        panelClass: 'ag-custom-component-popup'
      }).afterClosed().subscribe((applyOrNot) => {
        if (applyOrNot) {
          this.gridApi.onFilterChanged();
          console.log(foo.getModel());
        }
      });
    })
  }

the dialog content:

<mat-dialog-content>

</mat-dialog-content>
<mat-dialog-actions>
  <button mat-raised-button i18n [mat-dialog-close]="true" color="primary">Apply</button>
</mat-dialog-actions>

it renders correctly, but it looses functionality.
My goal is to set a filter without actually adding to the ag-grid table, just through a dialog and ag-grid API.

A: The problem was that I was using [innerHTML]="data.filterHtml?.innerHTML | safeUrl: 'html' " which strips any functionality for safety reasons ( XSS ).
The solutions was to give an id to the div and append the html from getGui()
Dialog HTML:
<mat-dialog-content>

</mat-dialog-content>
<mat-dialog-actions>
<button mat-raised-button i18n [mat-dialog-close]="true" color="primary">Apply</button>
</mat-dialog-actions>

Appending HTML to the div; dialog logic:
import { Component, ChangeDetectionStrategy, Inject, AfterViewInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
  selector: 'app-filter-wrapper-dialog',
  templateUrl: './filter-wrapper-dialog.component.html',
  styleUrls: ['./filter-wrapper-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.Default
})
export class FilterWrapperDialogComponent implements AfterViewInit {

  constructor(
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {}

  ngAfterViewInit(): void {
    document.querySelector('#second').appendChild((this.data.filterHtml as HTMLElement));
  }

}

With these changes I was able to render the filter correctly and functionally.


text:
Q: Is there a faster way to check an attribute value in all nested objects? I currently this code working, but its performance is very poor — 1.45 seconds seems a bit too much for a simple recursive if statement that only checks attribute values.
def _check_delete_status(self, obj) -> bool:

    obj_name = obj._sa_class_manager.class_.__name__
    self.visited.append(obj_name)

    if getattr(obj, 'status', 'deleted').lower() != 'deleted':

        children = [parent for parent in self._get_parents(self._get_table_by_table_name(obj_name)) if parent not in self.visited]

        for child in children:
            if (child_obj := getattr(obj, child, None)) and child not in self.visited:
                if self._check_delete_status(child_obj):
                    return True
    else:
        return True
    return False

Although self._get_parents seems like a counterintuitive name, in this case it is still very useful to this solution: It returns a list with all possible attribute names that object might have as children. For example, an object named appointment will have ['patient', 'schedule'] as response; of which patient will have [] since it doesn't have any children, and schedule will have ['physiotherapist', 'address', 'patient', 'service'] returned.
When those values are then used on getattr(object, child_name) it returns the object corresponding to the child.
I tried to think on how to do this iteratively, but couldn't up come with any solutions.
PS: The reason for the self.visited list, is that sometimes an object might have the exact same object nested inside, and since they have the same values they can be skipped.

A: I should've done this before, but I ran cProfile on my function and discovered that what was making it slow was totally unrelated to it being recursive or anything: SQLAlchemy was performing lazy-loading so it had to send some requests to get all relationships it needed which slowed my function down quite a bit.
After I added lazy='immediate' to my mapper parameters it ran smoothly under 0.0006 seconds.


text:
Q: He must regret his decision vs He must be regretting his decision
(1) He must regret his decision.
(2) He must be regretting his decision.

If you're sure that "he" regrets his decision, can you say either (1) or (2)?
In other words, can (2) be interpreted as not having a progressive meaning to it?

A: To answer your last question first, it will always be interpreted as having a progressive meaning, that doesn't change.  Sometimes, though, that distinction isn't very meaningful in describing certain situations.  In this example, you can say either 1 or 2 and as a practical matter, the difference in meaning is just a nuance.
Example 1 might describe someone who regrets the decision, but it is not a continuous emotion, the regret is only when he happens to think about it.  Example 2 describes someone who is actively thinking about the decision and regretting it.  The "continuing" aspect does describe something that is different, but it is only a subtle difference in this case.
Your comment mentions another example: "What do you do?" vs. "What are you doing?"  That's a case where the two forms result in an entirely different meaning.  The degree to which the progressive form describes something substantially different in real life is very much a function of the specific word and the context.
You added an interesting additional question in a comment: can (1) also mean "I'm sure that he will regret his decision in the future" instead of "I'm sure that he regrets his decision now"?  Wording your question that way, which is consistent with the comparative meanings in the original question, the answer is no.  You used "must" in the sense of "it is likely".
However, a different meaning of "must" could turn it into a future reference.  If you use "must" to mean a requirement or obligation, "he must regret his decision" could refer to an action expected in the future.  But that's different from what you asked.


text:
Q: Compiling OpenCV 3.3 with CUDA 9.0RC I'm currently trying to compile OpenCV 3.3 with CUDA 9.0RC, but can't manage to make it all work. (Compiling on Windows, with CMake 3.9 and Visual Studio 2017, for x64 Windows)
First of all, if I try to compile OpenCV without CUDA, everything works fine.
After that, i added the "WITH CUDA" option in CMake, with all the correct paths, and Visual Studio give me this error:
9>------ Build started: Project: opencv_world, Configuration: Release x64 ------
9>Building NVCC (Device) object modules/world/CMakeFiles/cuda_compile.dir/__/core/src/cuda/Release/cuda_compile_generated_gpu_mat.cu.obj
9>nvcc fatal   : Unsupported gpu architecture 'compute_20'
9>CMake Error at cuda_compile_generated_gpu_mat.cu.obj.cmake:206 (message):
9>  Error generating
9>  C:/OpenCV-3.3.0/opencv-3.3.0/build/modules/world/CMakeFiles/cuda_compile.dir/__/core/src/cuda/Release/cuda_compile_generated_gpu_mat.cu.obj

Thinking it's an "ARCH" problem, i tried to change, in CMake :
CUDA_ARCH_BIN : 2.0 3.0 3.5 3.7 5.0 5.2 6.0 6.1

to :
CUDA_ARCH_BIN : 6.0 6.1

(Since i'm using a 1080)
and Visual Studio give me now this error :
6>------ Build started: Project: opencv_world, Configuration: Release x64 ------
6>Building NVCC (Device) object modules/world/CMakeFiles/cuda_compile.dir/__/core/src/cuda/Release/cuda_compile_generated_gpu_mat.cu.obj
6>gpu_mat.cu
6>'bin' is not recognized as an internal or external command,
6>operable program or batch file.
6>CMake Error at cuda_compile_generated_gpu_mat.cu.obj.cmake:206 (message):
6>  Error generating
6>  C:/OpenCV-3.3.0/opencv-3.3.0/build/modules/world/CMakeFiles/cuda_compile.dir/__/core/src/cuda/Release/cuda_compile_generated_gpu_mat.cu.obj

I don't know where this "bin" is comming from, and I really don't know what I should do to make it work..
Thanks for you replies !

A: The error is because the path to the host compiler is wrong. It's specified in CMake as CUDA_HOST_COMPILER: $(VCInstallDir)/bin. As this is a path to a folder (in fact it's a non existing folder), and not an exe, the build fails.
This is likely because MSVC 2017 has a new, much more convoluted, path to the bin folder. It used to be:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin
The new path is something like this, and will vary depending on which version of MSVC you have:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64
More info here. There is a good logical argument for the change, but it's probably broken a ton of build scripts which haven't been updated yet.
You can brute force it by setting the variable to, for example:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\cl.exe
You may get an error that the target OS is unsupported (even though it should be with CUDA 9).
7>nvcc fatal   : Host compiler targets unsupported OS.
There are two fixes for this.
1) If you have the latest MSVC 2017, you need to trick CUDA into accepting it because it's version 1911, not 1910.
Open up C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\include\crt\host_config.h and find this line:
#if _MSC_VER < 1600 || _MSC_VER > 1910
Change 1910 to 1911.
2) In CMake, add --cl-version=2017 to CUDA_NVCC_FLAGS. I'm not sure whether it's required, but it won't hurt.
That seems to have done the trick for me. You may also need to disable perf tests. You will also find that ncuvid.h doesn't exist at the moment, whether it's changed location or not I don't know. This prevents building opencv_cudacodec, but I suspect that's not a problem for most people.

A: I have had to do several things to get VS 2017 + Cuda 9.0 + OpenCV 3.3.0 + CMake 3.10.0-rc2:

*

*Modify \cmake\FindCuda.cmake per instructions here:

https://devtalk.nvidia.com/default/topic/1024631/cuda-9-opencv-gt-building-errors/
Basically, you must add the newer npp libraries in Cuda 9... Keep in mind when following those instructions, nppic needs to read nppicc.

*Modify saturate_cast.hpp to handle the changes in __half with cuda 9, also in that doc.

*run cmake, and ensure that:
a. WITH_CUBLAS is checked
b. CUDA_NVCC_FLAGS set to "--cl-version=2017"
c. CUDA_HOST_COMPILER set to wherever on your system "cl.exe" is located.
   (probably c:\program files (x86)\Microsoft Visual Studio\2017\enterprise..."
   (don't forget the line above needs to use FORWARD slashes, not backwards!)

*Press Configure then Generate
You will get a LOT of errors. I don't know why, they seem unavoidable in Windows + Visual Studio.


text:
Q: Thread-safety work with static field Consider the code:
class InnerClass
{
    public int State { get; set; }

    public bool Equals(InnerClass other) => State == other.State;

    public override int GetHashCode() => State;

    public override string ToString() => State.ToString();
}

class TestClass
{
    private static InnerClass _innerClass;
    private static readonly object _syncObject = new object();

    public InnerClass Get()
    {
        lock (_syncObject)
        {
            return _innerClass;
        }
    }

    public void Set(InnerClass innerClass)
    {
        lock (_syncObject)
        {
            _innerClass = innerClass;
        }
    }
}

[Fact]
public void TestClassTest()
{
    var firstInnerClass = new InnerClass() {State = 1};
    var secondInnerClass = new InnerClass() {State = 2};

    Assert.NotEqual(firstInnerClass, secondInnerClass);

    for (int i = 0; i < 100000; i++)
    {
        var testClass = new TestClass();
        testClass.Set(firstInnerClass);

        var currentInnerClass = testClass.Get();
        Task.Run(() => testClass.Set(secondInnerClass));

        Assert.Equal(firstInnerClass, currentInnerClass);
    }
}

It does not work. I understand that it is related to _innerClass field. Looks like currentInnerClass pointer can be replaced later.
But why is the next code work fine then?
class TestClass
{
    private static InnerClass _innerClass;

    public InnerClass Get()
    {
        return Interlocked.CompareExchange(ref _innerClass, _innerClass, _innerClass);
    }

    public void Set(InnerClass innerClass)
    {
        Interlocked.CompareExchange(ref _innerClass, innerClass, null);
    }
}

So there are two questions:

*

*How exactly Interlocked works with memory so that it can work fine?

*How can I change the first code (with lock operator) to make it ok? Maybe MemoryBarrier can help me? I am not sure...

A: So lets look at what you are doing here in your loop:
// Here you are creating a new TestClass. Should be whole new state, right
//Maybe not...
var testClass = new TestClass();

// Here we set the field to firstInnerClass
testClass.Set(firstInnerClass);

// Here we get the field value. Should be firstInnerClass always, right? Maybe...
var currentInnerClass = testClass.Get();

// Here we create a task to run on another thread.
// This will asynchronously update the state.
// Might take a while though...
Task.Run(() => testClass.Set(secondInnerClass));

// Here we assert that the state we read is what we set
Assert.Equal(firstInnerClass, currentInnerClass);

So far, so good. We write a value, we read a value, we asynchronously kick off a change to that value, and then we confirm that what we read is what we wrote.
The problem lies here:
private static InnerClass _innerClass;

static here means that the field is associated with the type, not the instance. It is shared across all instances of the class. So what is happening is that on some iteration N, the async Task from iteration N-1 is taking long enough to complete that it performs it's update between the write and the read. So the read gets secondInnerClass, not firstInnerClass. The fact that you are creating a new TestClass is irrelevant- the content fields of that class are static and so shared with every other copy.
If you change TestClass to the following, the error should disappear:
class TestClass
{
    private InnerClass _innerClass;
    private readonly object _syncObject = new object();

    public InnerClass Get()
    {
        lock (_syncObject)
        {
            return _innerClass;
        }
    }

    public void Set(InnerClass innerClass)
    {
        lock (_syncObject)
        {
            _innerClass = innerClass;
        }
    }
}


text:
Q: Wireguard VPN Splitting This is my first time posting here i hope someone can help me. We have staff that is work from home and have Softphone installed on their computers. I would like to know if its possible to *tunnel split of my softphone phone (3cx) to my VPN but if they they to browse from website its not going to be via VPN. Im using WireGuard
Story
Majority of out staff are working remotely
Our FreePBX is cloud based the only way to connect to it  is via VPN which is whitelisted
It came on my idea of VPN Splitting because I cannot use all Traffic to get to the VPN just only the softphone in order to save bandwith

A: In your /etc/wireguard/wg0.conf [Peer] section, change the AllowedIPs from 0.0.0.0/0 to the local network(s) you want to be accessible via the VPN.


text:
Q: Adding space between radio buttons in JSF 2.0 and IceFace i have below code in JSF2.0, and i want output in proper alignment.
<ice:panelGrid columns="1">
    <ice:selectOneRadio styleClass="hpLabel planTdSecond" style="padding-left: 10px" value="#{dpsController.dpsVo.selectOne}" layout="pageDirection">
        <f:selectItem itemLabel="Employer" itemValue="emp" />
        <f:selectItem itemLabel="Member" itemValue="member" />
        <f:selectItem itemLabel="Broker/Sales Professional" itemValue="brkr" />
    </ice:selectOneRadio>
</ice:panelGrid>

I am getting output like below :
   0 Employer
       0 Member
0 Broker/SalesProfessional

I want output like :
0 Employer
0 Member
0 Broker/SalesProfessional

A: I suppose this is a simple aligment problem of your column, you could try something like this :
<style>
    .columnAlignLeft
    {
        text-align: left;
    }
</style>

<ice:panelGrid columns="1" columnClasses="columnAlignLeft">
    <!-- Your current code -->
</ice:panelGrid>


text:
Q: HAProxy http-request with DATAPLANE API I am fiddling around with dataplaneapi which is a great addition.
However, I cant find proper parameters for manipulating a http-request in my frontend. The rule needs to look like this:
http-request replace-header Host .* 1595708099.pages.domain.de if ACL_somename_de

My current request goes to http_request_rules endpoint: /services/haproxy/configuration/http_request_rules
The request body looks like this:
{ "cond": "if", "cond_test": "ACL_somename_de", "hdr_name": "Host", "index": 0, "type": "replace-header" }

The output is:
http-request replace-header Host if ACL_somename_de

However I am still missing the regex condition part. On the regular HAproxy docs its called and
See:
https://www.haproxy.com/documentation/aloha/12-5/traffic-management/lb-layer7/http-rewrite/
I cant find these values in the dataplane documentation.
https://www.haproxy.com/documentation/dataplaneapi/latest/#operation/createHTTPRequestRule
Is this even possible and if yes how?

A: I asked the folks over at github and they delivered the answer:
curl --request POST \ --url 'http://127.0.0.1:5679/v2/services/haproxy/configuration/http_request_rules?parent_name=test_2&parent_type=frontend&version=61' \ --header 'Authorization: Basic YWRtaW46YWRtaW4=' \ --header 'Content-Type: application/json' \ --data '{ "cond": "if", "cond_test": "ACL_somename_de", "index": 0, "type": "replace-header", "hdr_format": "1595708099.pages.domain.de", "hdr_match": ".*", "hdr_name": "Host" }'
source:
https://github.com/haproxytech/dataplaneapi/issues/149


text:
Q: How can I get only the bottom most nodes of a particular type containing text with xpath? Let's say I have the following xml:
<one>
  <two>
    <three>
      <three>
        foo
      </three>
      <four />
      <three>
        bar
        <four />
      </three>
    </three>
  </two>
</one>

What XPath query can I write that will return only these nodes:
<three>
  foo
</three>

and
<three>
  bar
  <four />
</three>

but not this one:
<three>
  <three>
    foo
  </three>
  <four />
  <three>
    bar
    <four />
  </three>
</three>

I've tried this:
//three/descendant-or-self::*/text()/ancestor::three

but it returns the one I don't want. I also can't assume that this is the exact structure of the xml, so I don't think that the .. operator will work. Essentially, I want the youngest ancestor of the text nodes that's of type three.
Any suggestions?

A: I think //three[text() and not (descendant::three)] will do what you want.


text:
Q: Column jumbling in gridview in asp.net i have a grid in which there are 16 columns and 15th column will be
hidden when the status=sent,match or completed else it will be
visible.  so when the 15th column is hidden(visible-false) then 16th
colum which is a checkbox is coming into 15th colmn.
code
Protected Sub gvPOItems_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvPOItems.RowDataBound

    If _po.Status = "Completed" OrElse _po.Status = "Matched" OrElse _po.Status = "Sent" Then
         e.Row.Cells(15).Visible = False

A: When you set the Visible property of the Cell to false, it dissapears from the HTML. That means that all the next cells shift one position to the left.
So it's better to just empty the cells or remove the controls, but keep them visible.
e.Row.Cells(15).Text = ""
//or
e.Row.Cells(15).Controls.Clear


text:
Q: I am trying to compile a bb recipe file in yocto. I am facing : make: *** No targets specified and no makefile found. Stop. erorr LICENSE = "CLOSED"

S = "${WORKDIR}/git"
FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"
SRCREV = "eb5499c2732fbf500c54fd5f1bded9e45793728e"
SRC_URI = "file://new.tar.gz"

S = "${WORKDIR}/git"
inherit autotoools

#this is the bb file
#after compiling i'm facing : make: *** No targets specified and no makefile found.  Stop. erorr.

A: S is probably incorrect. You need to set it to either ${WORKDIR} or ${WORKDIR}/subir where subdir is the only directory in your tarball.
SRCREV is a no-op (only used by the git fetcher (when one entry in SRC_URI starts with git://)).
FILESEXTRAPATHS_prepend is a no-op here, the path is already used by default.


text:
Q: Angular 4 async with loading and display when empty I have an Angular component that gets a service CatalogServiceinjected:
export class CatalogListComponent implements OnInit {
  catalog$: Observable<MovieResponseItem[]>;
  constructor(private catalogService: CatalogService) {}
  ngOnInit() {
    this.catalog$ = this.catalogService.userCatalog;
  }
}

This service returns an Observable<MovieResponseItem[]> on property userCatalog:
@Injectable()
export class CatalogService {
  get userCatalog(): Observable<MovieResponseItem[]> {
    return this._userCatalogSubject.asObservable();
  }
}

The MovieResponseItemis just a simple interface:
export interface MovieResponseItem {
  title: string;
}

Now I want to iterate the items and display a loading animation while the catalog queries the underlying service for data (that takes some time) - this works. This is the template used:

 0; else loading">
   <ng-container *ngFor="let item of catalog$ | async">

{{item.title}}

   <ng-container>

<ng-template #loading>loading animation...</ng-template>

This obviously displays the #loading template while the async is awaiting data. If the observable returns data, it iterates over the catalog values.
But now I want to separate this into this behaviour:

*

*while we await data, display the loading animation

*if we have a response from the service and the returned list is empty, show an information text (like "your catalog is empty") and do not iterate (as there is no data)

*if we have a response from the service and the returned list has values, iterate the items (as in current state)

How can I achieve this?

A:

  <ng-container *ngIf="catalog.length; else noItems">

{{item.title}}

  </ng-container>
  <ng-template #noItems>No Items!</ng-template>

 <ng-template #loading>loading animation...</ng-template>

This should do the trick. Better to use as few async pipes as possible and just declare it "as" a template variable you can use where ever. Otherwise the stream will be executed once per async pipe which is a bad practice and could create unneeded http calls if this is http backed.
*edit for the syntax error

A: hmmm.. https://github.com/angular/angular/issues/14479
Just throw in another ngIf - else condition.

      <ng-container *ngFor="let item of catalog$ | async">

{{item.title}}

      <ng-container>

   <ng-template #empty>empty animation...</ng-template>

<ng-template #loading>loading animation...</ng-template>


text:
Q: ctypes - Permanently changing Desktop Background via SystemParametersInfoW I have a Python script that utilizes the ctypes library to pass parameters to Window's SystemParametersInfoW() function in order to change my Windows 10 desktop background. I'm able to successfully change the background, however the changes aren't being applied permanently. Once I shut the computer down it'll revert to my previous background on the next boot instead of the one applied from the script.
image_path = "C:\\Users\\Jay\\source\\repos\\Nasa_Background\\Nasa_Background\\bg.png"
SPI_SETDESKWALLPAPER = 0x0014
SPIF_UPDATEINIFILE = 0x0001
SPIF_SENDWININICHANGE = 0x0002

ctypes.windll.user32.SystemParametersInfoW.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p, ctypes.c_uint]
ctypes.windll.user32.SystemParametersInfoW.restype = ctypes.wintypes.BOOL
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, image_path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE)

According to this dev blog passing SPIF_UPDATEINIFILE should make the change permanent:
https://devblogs.microsoft.com/oldnewthing/20160721-00/?p=93925
Everything else looks correct based on the docs:
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow
I've also tried this solution with no luck:
How do I set the desktop background in python? (windows)
So I'm not sure what I'm missing here, it seems like it should permanently update the background but it's not.


text:
Q: Implementing Linked Lists in Python I am trying to implement  both the solutions for the leetcode linked list problem found in this link:
https://leetcode.com/problems/middle-of-the-linked-list/solution/ but I cannot. What i wrote so far is the following:
1st soltution
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def middleNode(self, head):
        while arr[-1].next:
        arr.append(arr[-1].next)
    return arr[len(arr) // 2]

node =ListNode([1,2,3,4,5])

a.next = b

b.next = c

c.next = d

print(ListNode.middleNode())

2nd solution
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
   def middleNode(self, head)
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow

a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)

a.next = b
b.next = c
c.next = d

my_list = Solution()

print(my_list.middleNode([1,2,3,4,5]))

A: Maybe this will help.
class ListIsEmptyException(Exception):
    pass

class Node(object):

    def __init__(self, value, next=None):
        self._value = value
        self._next = next

    def __str__(self):
        return str(self._value)

class List(object):

    def __init__(self):
        self._head = self._tail = None

    def add_first(self, value):
        node = Node(value)
        if self._head is None:
            self._head = self._tail = node
        else:
            node._next = self._head
            self._head = node

    def add_last(self, value):
        node = Node(value)
        if self._tail is None:
            self._head = self._tail = node
        else:
            self._tail._next = node
            self._tail = node

    def get_first(self):
        if self._head is None:
            raise ListIsEmptyException
        return self._head

    def get_last(self):
        if self._tail is None:
            raise ListIsEmptyException
        return self._tail

    def remove_first(self):
        if self._head is None:
            raise ListIsEmptyException
        elif self._head._next is None:
            self._head = self._tail = None
        else:
            self._head = self._head._next

    def remove_last(self):
        if self._tail is None:
            raise ListIsEmptyException
        elif self._head._next is None:
            self._head = self._tail = None
        else:
            current = self._head
            while current._next != self._tail:
                current = current._next
            current._next = None

    def __len__(self):
        current = self._head
        i = 0
        while current is not None:
            i += 1
            current = current._next
        return i

    def __iter__(self):
        current = self._head
        while current is not None:
            yield current
            current = current._next

if __name__ == '__main__':
    lista = List()

    lista.add_first("A")
    lista.add_first("B")
    lista.add_last("C")

    for l in lista:
        print(l)


text:
Q: how to go back to some position already printed in C? let us have a situation in which the following program prints some 10 lines of #
for(i=0;i<10;i++)
prinf("\n#");

now how to go back to 5 th line and edit that # and change the color of it without clearing the screen or clearing the below 5 lines?
I have tried
window(5,0,20,20);
textcolor(GREEN);
cprintf("#");

but it is not editing that one but it is printing on the side of the original one.why?
is there any other way of doing it and changing the color of the already printed text dynamically?
please help me..my environment is turbo c on windows

A: It looks like you are mixing printf and another output library - this isn't recommended.  Printf expects to be sent to a character terminal, while the output library in question may falsly assume that it has exclusive access (and might misbehave.)
Based on one function, you're likely using conio.h.  The documentation can be found here, with a table of contents showing each available function.  From that index, you should be able to spot the function instantly.
The window function doesn't do what you want it to, since it only sets the area in which the cursor may change text - it doesn't move the cursor, you need to use the other library functions.

A: -1:  Some tips for posting homework questions:
1) Get the question right!  The posted code does not perform as the description states:
 for(i=0;i<10;i++)
    prinf("#");

This will print 10 # characters on one line, as there is no end-of-line character.  The original description talks about "printing 10 lines."
2) Give necessary details: What environment are you using: Windows?  Linux?  What compiler?  Is this a windowed or text-based environment?
3) STFW before posting. Look for "ANSI Escape Sequences" or "positioning the cursor."

A: window function will generally create a window from the 1st two coordinates pixel i.e, in your example (5,0) to the pixel pointed by next 2 coordinates. so your program should work try it out or else use gotoxy()

A: maybe-
cprintf("\b#");

'b' is for backspace


text:
Q: 3 kinds of objects, random in array javascript I have to make a function with parameter of a length of an array. The array should have some objects in it,in random order and random number of any kind of objects. I have 3 kinds of objects like below:
   var bestaccount=function(){
   var amount=0;
   this.pay=function(howmuch){amount+=howmuch;};
   this.widthdraw=function(howmuch){amount-=howmuch;};
   this.saldo=function(){return amount;};
   };

   var toGive= function(){
   var amount=0;
   this.pay=function(howmuch){amount+=howmuch;};
   this.saldo=function(){return amount;};
   };

   var toWithdraw=function(){
   var amount=0;
   this.withdraw=function(howmuch){amount-=howmuch;};
   this.saldo=function(){return amount;};
   };

How can I put random kind of object in the array?

A: This snippet illustrates how to do it for a single object, I hope it helps.
The idea is to create an array of references, then pick a random element of the array and construct it.
var objects = [
    bestaccount,
    toGive,
    toWithdraw
]

var RandomObject = new objects[Math.floor(Math.random()*objects.length)]();


text:
Q: Android App Crashes after splashscreen - Android Studio at the moment I am starting to build an android app and when I run it, after the splash screen it crashes.
Here is my error:

11-07 20:11:55.344    1273-1273/com.patrickmelia.bcrfm E/AndroidRuntime﹕ FATAL EXCEPTION: main
      Process: com.patrickmelia.bcrfm, PID: 1273
      java.lang.OutOfMemoryError: Failed to allocate a 603288012 byte allocation with 1569794 free bytes and 61MB until OOM
              at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
              at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
              at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
              at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
              at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:973)
              at android.content.res.Resources.loadDrawableForCookie(Resources.java:2423)
              at android.content.res.Resources.loadDrawable(Resources.java:2330)
              at android.content.res.Resources.getDrawable(Resources.java:758)
              at android.content.res.Resources.getDrawable(Resources.java:724)
              at com.patrickmelia.bcrfm.CustomDrawerAdapter.getView(CustomDrawerAdapter.java:56)
              at android.widget.AbsListView.obtainView(AbsListView.java:2344)
              at android.widget.ListView.makeAndAddView(ListView.java:1864)
              at android.widget.ListView.fillDown(ListView.java:698)
              at android.widget.ListView.fillFromTop(ListView.java:759)
              at android.widget.ListView.layoutChildren(ListView.java:1673)
              at android.widget.AbsListView.onLayout(AbsListView.java:2148)
              at android.view.View.layout(View.java:15596)
              at android.view.ViewGroup.layout(ViewGroup.java:4966)
              at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:911)
              at android.view.View.layout(View.java:15596)
              at android.view.ViewGroup.layout(ViewGroup.java:4966)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
              at android.view.View.layout(View.java:15596)
              at android.view.ViewGroup.layout(ViewGroup.java:4966)
              at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:494)
              at android.view.View.layout(View.java:15596)
              at android.view.ViewGroup.layout(ViewGroup.java:4966)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
              at android.view.View.layout(View.java:15596)
              at android.view.ViewGroup.layout(ViewGroup.java:4966)
              at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
              at android.view.Choreographer.doCallbacks(Choreographer.java:580)
              at android.view.Choreographer.doFrame(Choreographer.java:550)
              at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
              at android.os.Handler.handleCallback(Handler.java:739)
              at android.os.Handler.dispatchMessage(Handler.java:95)
              at android.os.Looper.loop(Looper.java:135)
              at android.app.ActivityThread.main(ActivityThread.java:5221)
              at java.lang.reflect.Method.invoke(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:372)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Here is my activity code:
public class splashScreen extends Activity {

// Splash screen timer
private static int SPLASH_TIME_OUT = 6000;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);

    /*if(!isNetworkAvailable())
    {
        new AlertDialog.Builder(this)
                .setTitle("No Internet Access")
                .setMessage("Whoops, Internet Required. Please connect to the internet and try again")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();

    }else{*/

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            Intent mainIntent = new Intent(splashScreen.this, MainActivity.class);
            splashScreen.this.startActivity(mainIntent);
            splashScreen.this.finish();
        }
    }, SPLASH_TIME_OUT);
}}

Has anyone got this error before/can anyone help me with this error?

A: You should resize down the image you are loading in your Layout. Also, making several images for different densities will help you to avoid this kind of problems.

A: I had this trouble. You have to possible solutions: resize your image if high resolution is not mandatory or write this in AndroidManifest.xml on your application tag:
android:largeHeap="true"

Second one worked for me.


text:
Q: How do I change the color of the tooltip for only one component? How do I change the color of the tooltip for only one component?
I know you can do the following for changing tooltip colors:
UIManager.put("ToolTip.background", new ColorUIResource(255, 247, 200));

But this changes the tooltip background for all component, not just one.
Any easy solutions?

A: +1 to @MadProgrammer and @Reimeus for their advice and example.
These are both correct.
To add...
There is no default way to do this. You have to extend the ToolTip class, to create your own custom ToolTip with foreground and background color, and then extend JComponents class (JButton, JLabel, etc. are all JComponents ) and override itscreateToolTip() method and sets your custom ToolTip as the the JComponents ToolTip, like this :
Here is an example I made:

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JToolTip;
import javax.swing.SwingUtilities;

/**
 *
 * @author David
 */
public class CustomJToolTipTest {

    private JFrame frame;

    public CustomJToolTipTest() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CustomJToolTipTest();
            }
        });
    }

    private void initComponents() {
        frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        JButton button = new JButton("button") {
            //override the JButtons createToolTip method
            @Override
            public JToolTip createToolTip() {
                return (new CustomJToolTip(this));
            }
        };
        button.setToolTipText("I am a button with custom tooltip");

        frame.add(button);

        frame.pack();
        frame.setVisible(true);
    }
}

class CustomJToolTip extends JToolTip {

    public CustomJToolTip(JComponent component) {
        super();
        setComponent(component);
        setBackground(Color.black);
        setForeground(Color.red);
    }
}

A: You need to provide a custom JTooltip for the component.
Take a look at JComponent#createToolTip
From the Java Docs

Returns the instance of JToolTip that should be used to display the
  tooltip. Components typically would not override this method, but it
  can be used to cause different tooltips to be displayed differently.

A: There is no standard way to do this, but you could override JComponent.createToolTip(). Here is a button example:
MyButton testButton = new MyButton("Move Mouse Over Button");
testButton.setToolTipText("Some text");

class MyButton extends JButton {

   public MyButton(String text) {
      super(text);
   }

   @Override
   public JToolTip createToolTip() {
      return (new MyCustomToolTip(this));
   }
}

class MyCustomToolTip extends JToolTip {
   public MyCustomToolTip(JComponent component) {
      super();
      setComponent(component);
      setBackground(Color.black);
      setForeground(Color.red);
   }
}

A: I won't recommend this if you have access to the source code. But if you haven't, you can change the color by utilizing the HTML formatting capability.
JButton b = new JButton();
b.setToolTipText("
My Text
");

You need the negative margin, because there exist a standard margin which will not be colored otherwise. We make up for the margin by adding a padding. 3 px seems to work for the metal LAF.


text:
Q: Finding an upper bound for $\frac{1}{r^n} \int_{||\vec{u}|| \le n 2^n C} e^{-\pi ||(\vec{x} + \vec{u})/r||^2} d \vec{u}$ I am trying find an upper bound for the following integral, I know the expression is less than $1$, and I would prefer to find a bound that looks like $\frac{1}{2^{f(n)}}$. Where $f(n)$ is any function in $n$.
The integral is: $$\frac{1}{r^n} \int_{||\vec{u}|| \le n 2^n C} e^{-\pi ||(\vec{x} + \vec{u})/r||^2} d \vec{u}$$
We also know the following:
$n \in \mathbb{N}$
$\vec{x}$ and $\vec{u}$ are vectors in $\mathbb{R^n}$.
$C$ and $r$ are just constants.
$||\vec{x}|| \ge \sqrt{n} r$
$r > 2^{2n} C$
I am a bit stumped so any hints or tips would he gladly appreciated.
I've tried doing the substitution $\vec{y} = \vec{u} + \vec{x}$ and integrate over $\mathbb{R^n}$ instead of the ball, but the bound is $1$ in that case which is too high.
I've also tried using the reverse triangle inequality $-||\vec{x}+\vec{u}||^2 \leq -(||\vec{x} - \vec{u}||)^2$

A: As I indicated to you in chat, the most productive approach seems to be to make the change of variables $\vec y = \frac 1r (\vec x + \vec u)$. Setting $\delta = n2^nC/r<n/2^n$, you'll get
$$\frac 1{r^n}\int_{\|\vec u\|\le n2^n} e^{-\pi\|(\vec x+\vec u)/r\|^2} d\vec u =
\int_{\|\vec y-\vec x\|\le\delta} e^{-\pi\|\vec y\|^2}d\vec y < ke^{-\pi(\|\vec x\|-\delta)^2}\delta^n,$$
where the constant $k$ is the volume of the unit ball in $\Bbb R^n$. You should be able to get good estimates from this.


text:
Q: Reduction modulo p - common divisor Let $\mathbb{Z}[X]\longrightarrow \mathbb{Z}/p\mathbb{Z}[X]=\mathbb{F}_p[X], \sum c_iX^i\mapsto\sum \overline{c_i}X^i$ be the homomorphism "reduction modulo p" with $p$ being a prime. We furthermore have, $h(X^p)=f\cdot g$ where each polynomial is monomial. We also have $deg f=n$ and $p$ does not divide $n$.
My book states: "The equation $\overline{h}(X^p)=\overline f \cdot \overline g $ shows that $\overline h$ and $\overline f$ have a common divisor in $\mathbb{F_p}[X]$."
I can not figure out why this holds. I might have overseen something obvious, but I don't even have an idea.
EDIT: Also, $\zeta$ is a root of both $f$ and $h(X^p)$.

A: Interesting!

We just need to prove:
$$h(x^p)\in (\bar{h}(x)),$$
where $(\bar{h}(x))$ is an idea.
In fact, as Krish's comment, $\bar{h}(x^P)=(\bar{h}(x))^p$.
This is because we can use algebraic closed field to analysis. And
$h(x)=(x+\lambda_1)\cdots(x+\lambda_n), h(x^p)=(x^p+\lambda_1)\cdots(x^p+\lambda_n)$.
As fermat's small theorem :
$$ \lambda^p\equiv\lambda (mod\quad p)$$
Therefore,
$$(x^p+\lambda)=(x+\lambda)^p,$$
in $Z_p[x]$.So $\bar{h}(x^P)=(\bar{h}(x))^p$.


text:
Q: Inline list in python reallocate memory? I have a pairs of objects that I want to iterate over. Example:
contentA = [1, 2, ..... 100000]
lenA = 123.12

contentB = [1, 2, ..... 100000]
lenB = 123.12

contentC = [1, 2, ..... 100000]
lenC = 123.12

Now to iterate over them, I am using the following python syntax:
for (contType, contLen) in [(contentA, lenA), (contentB, lenB), (contentC, lenC)]:
  # Do something

This works just fine, but my question is:
Does declaring a inline list in a for loop first allocates memory and then iterates over them?
Since objects in question are huge and the number of iterations that I have to do this is also enormous, allocating memory again & again will consume memory as well as time.

A: The list you create to iterate over the elements contain only pointers on ContentA, ContentB and ContentC.
Since in that example there is only 3 element it will cost in you memory the size of a list of 3 tuple (float, pointer). Which is not so much.
If you want to be a little bit more efficient you can iterate over the tuple ((contentA, lenA), (contentB, lenB), (contentC, lenC)).


text:
Q: Printing 'Hello world' n number of times in R I'm trying to teach myself R and am experimenting with for loops, a basic construct in any imperative language.
At first, I used a for loop to increment a variable an arbitrary number of times:
x = 0
for (i in 1:1000) {
    x = x + 1
}

This works as expected. However, when I attempted to paste a simple message in this loop, I get no output. Specifically:
for (i in 1:1000) {
    paste('Hello world!')
}

Why is this?

A: In R you need to use print inside loops to get the output:
for (i in 1:1000) {
    print(paste('Hello world!'))
}

Best!

A: Or use the apply family!
like this for instance:
sapply(rep(1,100),FUN = function(x) print("hello world!"))


text:
Q: Running python file in google colab
Hello, it might be a dumb question, but as you can see in the image, I want to run datasets.py file. I am inside the mos4d folder. However, the error says it can not find the mos4d module in datasets.py. Can somebody help me to solve this error please?
I am trying to run this project : https://github.com/PRBonn/4DMOS#installation on my google-colab.
Thank you

A: When importing a custom module, you have to do the following steps:

*

*Mount your google drive to colab

from google.colab import drive
drive.mount('/content/drive')

*Append the path of mos4d module into colab path

import sys
sys.path.append('/content/drive/My Drive/4DMOS/src/')

Looks like you've managed to mount your drive. It should be able to import mos4d by appending the path.
Update at 2022-07-25
I've checked your path again and the append path should be modified to '/content/4DMOS/src/'.
In the beginning, I thought that you were trying to mount your Google Drive to the colab notebook. Sorry for the misunderstanding.
I've created a python file named utils.py and defined load_poses function inside
def load_poses():
    print("Load poses imported")

Here's the test in my colab notebook, it can be imported successfully as the following image

A: The reason I got this error was the MinkowskiEngine was not installed on GPU runtime properly. After installing MinkowskiEngine, the error was solved.


text:
Q: JMeter View Results Tree - filter results Is there a way to filter out all entries except just one or two particular threads in JMeter View Results Tree listener?

A: You can add a view results tree to the thread group directly.  View Results Trees which have a thread group as their direct parent will only show requests made by that thread group.
View Results Trees can also be added directly to a HTTP Sampler.  When added directly to a sampler that tree will only show results from that specific HTTP Sampler.

In the image View Results Tree will record requests from both thread groups.  View Results Tree 1  will only record HTTP Request Google and HTTP Request Bing, Tree 2 will record HTTP Request MSN and Tree 3 will record HTTP Request MSN and HTTP Request Yahoo.
Be careful though, View Results Tree should only be used for debugging and should not be enabled during an actual performance test according to best practices.


text:
Q: For $\phi$ as a homomorphism not onto show not normal subgroup I am just a little unclear about what I am supposed to do here.
Let $\phi: G $ to $J$ be a homomorphism onto all of $J$. Let $H$ be a normal subgroup of $G$ and let $K=\phi(H)$ be the image of $H$ under the homomorphism.
I have showed that K is normal to J. I now need to provide an example that K could not be normal to G if $\phi$ is not onto.
Do I need to find a G,J,K, and H such that it there is a homomorphism but it is not onto? Is this the right path? Because if it is then I have thought and thought and I am stuck.

A: Let $J$ be a group and let $G$ be a subgroup of $J$ that is not a normal subgroup. Then the inclusion homomorphism of $G$ with $H=G$ satisfies the condition. The inclusion homomorphism is the homomorphism $i:G\to J$ such that $i(g)=g$ for all $g\in G$.

A: Consider the inclusion of $A_4$ into $A_5$. Take any normal subgroup of $A_4$. Its image cannot be normal in $A_5$ because $A_5$ is simple.


text:
Q: How to scrape values on hovering highcharts using selenium python? I am trying to scrape the data from https://www.similarweb.com/website/zalando.de/#overview using Python and Selenium. The difficult part is that the data only appears when a point on the graph is hovered over.
Here's my code.
websites = ['https://www.similarweb.com/website/zalando.de/#overview']

    options = webdriver.ChromeOptions()
    options.add_argument('start-maximized')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)

    browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)
    delays = [7, 4, 6, 2, 10, 19]
    delay = np.random.choice(delays)
    for crawler in websites:
        browser.get(crawler)
        time.sleep(2)

        time.sleep(delay)

        tooltip = browser.find_element(By.XPATH, "//*[local-name() = 'svg']/*[local-name()='g'][8]/*[local-name()='text']")
        ActionChains(browser).move_to_element(tooltip).perform()
        month_value = browser.find_element(By.XPATH, "//*[local-name() = 'svg']/*[local-name()='g' and @class='highcharts-tooltip']/*[local-name()='text']")
        print('Are they here?', month_value.text)
        months = browser.find_elements(By.XPATH, "//*[local-name() = 'svg']/*[local-name()='g'][6]/*/*")
        for date in months:
            print(date.text)

I can print the months data as:
Nov '20
Dec '20
Jan '21
Feb '21
Mar '21
Apr '21

But not able to print the values of each month- it gives an empty print -Are they here?
How do I ensure that it is hovered first and then scraped? Please help
EDIT : Here's the updated code
def website_monitoring():
    websites = ['https://www.similarweb.com/website/zalando.de/#overview']

    options = webdriver.ChromeOptions()
    options.add_argument('start-maximized')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)

    browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)
    for crawler in websites:
        browser.get(crawler)
        wait = WebDriverWait(browser, 10)
        months = []
        monthly_values = []
        charts = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="highcharts-0"]')))
        highchart = browser.find_elements_by_xpath('//*[@id="highcharts-0"]/svg/g[4]/g[1]')
        for elements in highchart:
            hover = ActionChains(browser).move_to_element(elements)
            hover.perform()
            month = browser.find_elements_by_css_selector('#highcharts-0 > svg > g.highcharts-tooltip > text > tspan:nth-child(1)')
            month_values = browser.find_elements_by_css_selector('#highcharts-0 > svg > g.highcharts-tooltip > text > tspan:nth-child(3)')
            months.append(month[0].text)
            monthly_values.append(month_values[0].text)
        print('Months', months)
        print('Monthly Values', monthly_values)

if __name__ == "__main__":
    website_monitoring()

The output that I get is:
Months []
Monthly Values []

A: When a site displays dynamic charts, it retrieves the underlying data from its databases or from external APIs. Then, the server sends this data, or makes this data available (Json, xml, plain, csv) for the graphical frameworks (d3js, highcharts...). Sometimes this data is integrated into the HTML by template engines or hard written in javascript files.
After some investigation, we see that here the data is stored in a script tag at the end of the html (See F12 -> Inspector). The variable that contains the data is preloadedData. It seems to contain all the data used in the animations of the page, including the one that interests you.
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import time
import json
import re

driver = webdriver.Firefox()
driver.get("https://www.similarweb.com/website/zalando.de")

html = driver.page_source

soup = bs(html, "html.parser")

# get all scripts tags and select the one of interest
balises_script = soup.find_all("script")
target_balise = [str(el) for el in balises_script if "Sw.preloadedData" in str(el)][0]

# use regex to extract dict like string
m = re.findall(r"Sw.preloadedData = (.+)\;", target_balise)[0]

# dict like string to dict
data = json.loads(m)

# explore data to see where data of interest is
sub_data_of_interest = data['overview']['EngagementsSimilarweb']['WeeklyTrafficNumbers']

for items in sub_data_of_interest.items():
    print(items)

driver.close()

which results in :
('2020-11-01', 29914593)
('2020-12-01', 27141507)
('2021-01-01', 26863605)
('2021-02-01', 22589520)
('2021-03-01', 24745220)
('2021-04-01', 26249414)

Note 1: Selenium is often misused, it is designed to test web pages, not to retrieve data. However it is sometimes easier to use this tool.
Note 2: I tried the classic requests + bs method, it's more complicated: the script tag that contains the data is generated by another javascript that uses a rimbambelle of cookies.
Note 3: Be careful, the site detects requests that are likely to be non-human (too fast). Think to put a time.sleep in your for loops (if you loop on several URL).

A: This is a bit tricky. But I noticed something that I think will help: the info is present on the DOM regardless if it is on the page, and there is a unique css selector for it ('tspan:nth-child(3)'). The thing is, it is just one element that displays the value dynamically when you move the mouse. So if you identify which points you want to scrape the values from, but here's a quick way to print just the value I believe you want:
for point in points_to_hover:
    driver.find_element_by_css_selector('tspan:nth-child(3)').get_attribute("innerText")


text:
Q: Output ArrayList has size of zero private static List<Integer> parseStringArrayList(List<String> input) {
    System.out.println(input.size());
    List<Integer> output = new ArrayList<Integer>(input.size());
    for (int index = 0; index < output.size(); index++) {
        output.set(index, Integer.parseInt(input.get(index)));
    }
    return output;
}

The output always has a size of zero.
Help?

A: Initializing the Arraylist with size will not set the size of the arraylist, the size will only be modified for adding or removing elements. the capacity which represents the number of nodes the list can have before allocating the memory is what you actually defined.
private static List<Integer> parseStringArrayList(List<String> input) {
System.out.println(input.size());
List<Integer> output = new ArrayList<Integer>(input.size());
for (int index = 0; index < input.size(); index++) {
    output.add( Integer.parseInt(input.get(index)));
}
return output;
}

while you are adding and incrementing you can use add instead , in your case will do the same thing.
and you want to add the content of the input so you better put ur limit to input.size()

A: You should read the documentation for ArrayList, there is a distinction between capacity and size:
Distinction between the capacity of an array list and the size of an array
new ArrayList(5).size() != new int[5].length

A: Since Eran mentioned what you are doing wrong, i would like to suggest an other way to implement the parseStringArray method.
private static List<Integer> parseStringArrayList(List<String> input)
{
    List<Integer> output = new ArrayList<Integer>();
    for (String data : input) {
        output.add(Integer.parseInt(data));
    }
    return output;
}


text:
Q: Why Are Ellipsis Appearing In My Textbox? On a request form I have a textbox that the user is entering information into.  Once they enter the information, they save it, and then they can come back and edit the information. For some reason, the user can enter however many characters they want (which is fine) but after they save the form and reopen it, the textbox has cut off all the characters after 255 and added an ellipsis. The text is being stored in a database as a type "text" which allows up to 2000 characters.
Here is a picture of when a user inputs 2000 characters:

Here is a picture of after the user saves and edits the form:

This is the code I used to make the textbox:
<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <TextBox Text="{Binding Description, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" TextWrapping="Wrap" CharacterCasing="Normal"/>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <TextBox Text="{Binding Description, UpdateSourceTrigger=LostFocus}" TextWrapping="Wrap" CharacterCasing="Normal"/>
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

Is this built in to the textbox? If not how can I get rid of this? I would like my user to be able to see everything that they have written.


text:
Q: Confused about Kotlin Coroutines This doesn't have compilation error :
suspend fun test() {
    runBlocking {

    }
}

This has a compilation error :
suspend fun test() {
    launch {

    }
}

Unresolved reference. None of the following candidates is applicable
  because of receiver type mismatch: public fun
  CoroutineScope.launch(context: CoroutineContext = ..., start:
  CoroutineStart = ..., block: suspend CoroutineScope.() -> Unit): Job
  defined in kotlinx.coroutines

I don't really understand what is the problem...

A: Coroutines are launched with launch coroutine builder in a context of some CoroutineScope:
fun test() = CoroutineScope(Dispatchers.Main).launch {
}

launch - is an extension function on CoroutineScope object, it is defined like this:
public fun CoroutineScope.launch(...): Job {}

runBlocking - is not an extension function, so it can be called as a regular function, it is defined like this:
public fun <T> runBlocking(...): T {}


text:
Q: Drawing a responsive diagonal line This is what I want: a page split in two vertical parts: a red one with contents (200px in the fiddle) + the right part is a diagonal that goes top-left (200, 0) to bottom-right of the browser window.
I'd like this line to be responsive to any page changing: every time the page is resized, this line'd be always a neat diagonal between these points. (200, 0 - very bottom-right of the browser window)
I've been trying to manage the canvas function, but may be the wrong way.
Can anybody help me?

A: This will do the trick, check comments for info:

// Get the canvas and the context to draw in
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

function diagonalLineToBottomRight(){
  // Reset your canvas to the size of the window - this also clears the canvas
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  // Set a line color
  context.strokeStyle = 'red';
  // Set the point where you line starts
  context.moveTo(200, 0);
  // Draw the line to the bottom corner
  context.lineTo(window.innerWidth, window.innerHeight);
  // Actually draw the pixels to the canvas
  context.stroke();
}

// Set the function to execute when the window size changes
window.addEventListener('resize', diagonalLineToBottomRight, false);
// Execute the function on initial load
diagonalLineToBottomRight();
<canvas id="canvas"></canvas>

I am guessing, however, you don't want your canvas to overlap the content on the side. This can be done by combining some CSS and JS to make a canvas that is 200 pixels less wide than you page:

// Get the canvas and the context to draw in
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

function diagonalLineToBottomRight(){
  // Reset your canvas to the size of the window - this also clears the canvas
  canvas.width = window.innerWidth - 200;
  canvas.height = window.innerHeight;
  // dont draw when its not wide enough
  if(window.innerWidth - 200 < 200) return;
  // Set a line color
  context.strokeStyle = 'red';
  // Set the point where you line starts
  context.moveTo(0, 0);
  // Draw the line to the bottom corner
  context.lineTo(window.innerWidth - 200, window.innerHeight);
  // Actually draw the pixels to the canvas
  context.stroke();
}

// Set the function to execute when the window size changes
window.addEventListener('resize', diagonalLineToBottomRight, false);
// Execute the function on initial load
diagonalLineToBottomRight();
html, body {
  height: 100%;
}
nav {
  position: absolute;
  left: 0;
  top: 0;
  background: red;
  width: 200px;
  height: 100%;
}
canvas {
  position: fixed;
  top: 0;
  right: 0;
}
<canvas id="canvas"></canvas>
<nav></nav>


text:
Q: How do equal radii lie on concentric circles? This is a very interesting word problem that I came across in an old textbook of mine. So I know its got something to do with using greatest common divisor, but other than that, the textbook gave no hints really and I'm really not sure about how to approach it. Any guidance hints or help would be truly greatly appreciated. Thanks in advance :) So anyway, here the problem goes:

The jets (or holes) on a shower head are arranged in circles that are
  concentric with the rim. The jets are equally spaced on each circle and
  there is at least one radius of the shower head that intersects every circle
  at a jet.
The angular separation of two jets on a circle is the size of the angle
  formed by the two radii of the circle that pass through the jets. All angular
  separations are integers. For example, on the shower head shown,
  there are 10 jets on the inner circle. Hence the angular separation of
  adjacent jets on the inner circle is $360°/10 = 36°$.
a) A shower head has three circles of jets: an inner circle with $12$ jets, a middle circle with $18$ jets, and an outer circle with $36$ jets. How many radii of the shower head pass through just two jets?
b) Another shower head has three circles with $20, 30,$ and $45$ jets respectively. Explain why no diameter of the outer circle passes through six jets.
c) A shower head with three circles of jets has a different number of jets in each circle. Exactly two diameters of the shower head pass through six jets. If the total number of jets. If the total number of jets is $100$, how many jets are there in each circle? Find all combinations.
d) Find the maximum number of jets in a shower head with three circles if only one radius of the shower head passes through three jets, no radius passes through just two jets, and each circle has at least two jets.

A: A) The inner, middle, and outer rings have angular separations $10,20,30$ degrees respectively. $10$ divides both $20$ and $30$, so every jet on the inner and middle rings will automatically fall on the same radius as a jet from the outer ring. $LCM(20,30) = 60$, so the number we are looking for is $360/20 + 360/30 - (360/60)*2 = 18+12-12 = 18$
$LCM(20,30) = 60$, and $360/60 = 6$, so there are $6$ points where all 3 fall on the same radius.
This implies the total number of pairs is $18 - 6 = 12$
B) To pass through $6$ jets on a diameter, we would need the angular separations of all three rings to divide $180$. The angular separations are $18, 12, 8$, which clearly do not satisfy the criterion, as $8$ is not a factor of $180$.
C) Here, we need the angular separations of all three rings to be a factor of $90$ and satisfy $18(\frac1{\theta_1} + \frac1{\theta_2}+\frac1{\theta_3}) = 5$
Letting $\theta_j = 90/k_j $ for some factors of $90$, $k_j$, we get
$k_1+k_2+k_3 = 25$
Factors of $90$ are $1,2,3,5,6,9,10,15,18,30,45,90$
Letting $(k_1,k_2,k_3) = (2, 5, 18), (1,6,18), (6,9,10), (1,9,15)$ we see that $(\theta_1, \theta_2, \theta_3) = (45, 18, 5), (90, 15, 5), (15,10,9), (90, 10, 6)$ satisfy the criterion.
So there are $4$ such combinations, where the number of jets are $(8,20,72), (4,24,72), (24,36,40), (4, 36, 60) $.
D) personally, this part seems best fit for a simple python program, but I'll give it my best shot.
The factors of $360$ are $1,2,3,4,5,6,8,9,10,12,15,18,20,24,30,36,40,45,60,72,90,120,180,360$
Since there are at least $2$ in each circle, we can cross off $360$ as a possibility. We need to find the $3$ smallest numbers from this list which have pairwise LCM of $360$.
You can narrow the list steadily by working your way up from the bottom and noting that if $ab = 360$ and $a$ divides all (or all but one) factor greater than or equal to $b$, $a$ cannot be one of the desired angles. Using this thought, you can rule out $1,2,3,4,5,6$ as possibilities for angular separations. From here, it seems to be more of a brute force method, which I don't have the desire to do. As said before, I recommend writing a program for this part.
However, in the comments it was pointed out that using the prime factorization of $360$ will be a much more efficient way to do it by hand.

A: Hint:  In your figure there are $10$ jets in the inner circle, $12$ in the next circle, and $18$ in the outer circle.  That means the angular spacings are $36^\circ, 30^\circ, 20^\circ$.  They will line up when the total angles agree.  For example, the third jet in the middle circle is $2 \cdot 30^\circ$ from start and the fourth in the outer circle is $3 \cdot 20^\circ$ from start.  As these agree, they line up.  They will repeat at angles of the LCM of the spacings of two circles.

A: B) other than 0 and 360 there is no common multiple for 20, 30 and 45. If X is a multiple of all 3 and X +180 is also a multiple of all 3 only it will pass thru 6 jets. It is not the case here.
C) 2   180
3   120
5   72
6   60
9   40
15  24
18  20
30  12
45  8
60   6
90   4
A combination which will add up to 100  72+20+8
So 5 degrees, 18 degrees and 45 degrees.
D) Only one of the radii passes thru 3 points. Let's take that as 0 or 360. So we have to find points which not align other than 0 and 360. We have to find 3 angles which have no common multiple other than 360. 72(5 jets), 120 (3 jets) and 180(2 jets). In all 10.


text:
Q: Is there a way to export roles and permissions from marketing cloud? I am new to marketing cloud. I am trying to analyse our users' role and permission settings and it is troublesome to capture all settings from all roles pages.
Is there a way to export all roles and permissions from marketing cloud?

A: There is not a way to export directly out of the Marketing Cloud UI, but you should be able to accomplish what you need via the Account User object available to the SOAP API.
Account User - SOAP API Documentation


text:
Q: ng-include with ng-click raise submit - how to avoid it? I have html template:

  <form novalidate>
    Name: <input type="text" ng-model="user.name" />
    <button ng-click="greet(user)">GREET</button>
  </form>

And I add it like this:
"

"

This is function in MyController:
$scope.user = {}
    $scope.greet = function (user) {
        alert('hello ' + user.name)
    }

But when I click on button it makes submit it doesn't call greet function.
I also tried to add type="button" to it but it is the same.
Here is the working solution so I don't know what I am missing.

A: use type="submit" with the submit button, and input instead of button.


text:
Q: Unable to load symbols for dll in c# project I have a main application which loads drivers from their compiled dll files. I am running into a problem where I want to be able to debug these dll files but the symbols are not being loaded by the project.
The dll files are part of the solution but have to be built separately from the main application. The main application then at runtime loads these dlls from a directory. I am having an error in one of these loaded dll files (not an exception, just unexpected results) but cannot debug the files. Can anyone give me an idea on how to proceed with debugging these?
EDIT:
To give a better idea of how the dlls are loaded here is the code from the main project:
public List<BaseClass> getObjects(string objectName)
{
    List<BaseClass> availableDrivers = new List<BaseClass>();

    string currentDir = Directory.GetCurrentDirectory();
    currentDir = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath); //Use this to find path even when running as service

    if (Directory.Exists(currentDir + "\\Objects"))
    {
        string[] files = Directory.GetFiles(currentDir + "\\Objects", "*.dll");
        foreach (string file in files)
        {
            Console.WriteLine("LOOKING AT:"+ file);
            try
            {
                Assembly dll = Assembly.LoadFrom(file);
                Type[] types = dll.GetTypes();  // .Where(x => x.BaseType.Name == "BaseClass");
                foreach (Type type in types)
                {

                    if (type.BaseType != null && (type.BaseType.Name == "BaseClass" || type.BaseType.Name == "PeriodicBaseClass"))
                    {
                        BaseClass ClassObj = (BaseClass)Activator.CreateInstance(type);

                        if (objectName == "" || objectsName == ClassObj.Name)
                        {
                            availableDrivers.Add(ClassObj);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Error.Log("Error reading driver:" + e.Message,MessageType.Error);
                //Console.WriteLine("Error reading driver:" + e.Message);
            }
        }
    }
    return availableDrivers;
}

So as you can see, when I run the program itself the drivers get loaded by retrieving their compiled dll files and when putting breakpoints in the dll code I get the message saying symbols cannot be loaded. I have tried checking Debug>Windows>Modules but the dlls don't show up there due to not being loaded directly in the application.

A: If the dlls in question are debug versions (that is, they were compiled for debugging) and their current .pdb files are in the same directory, you should be able to step through them just as if they were in your own project.
The other alternative is to open the solution that builds these dll and debug it by attaching to the process of the program you are running.
https://msdn.microsoft.com/en-us/library/3s68z0b3.aspx

A: So I ended up solving this problem. The way I did this was create a small console application in the solution that runs the same methods as the main application but right from the projects in the solution instead of loading the dlls dynamically.
I then set the startup project to the console application and was able to step through the relevant files properly.


text:
Q: xpath specific selection with condition this might be simple, but I would like to select everything within
 under the condition that it must belong to
, thereby uniquely identifying it. How can I do that with xpath? Thanks.

1.a

        text
        text

text texttext

A: If I modify your xml slightly, and take under the condition that it must belong to to mean that is a descendant of.... then this xpath works
//div[@class='definitionBox'][@id='meaning-1-2']//div[@class='rc-box-citations-body']
The XML is
<?xml version="1.0" encoding="utf-16"?>

1.a

        text
        text

          text

            text
            text

The tool I used is XPathVisualizer:


text:
Q: Apache2 ssl with ecc Is it possible to configure Apache2 to use elliptic curve crypto (ecc) with SSL? This bug https://issues.apache.org/bugzilla/show_bug.cgi?id=40132 appears (to me) to indicate that this is supported, but I can't find any instructions anywhere.

A: Or rather look here
http://httpd.apache.org/docs/2.4/mod/mod_ssl.html
Support for EC Key Exchange has been added here.

A: Apache supports ECC Certificates and Protocols as of version 2.2.26. Though if you are using an Apache server from a distro's repository it may be the same version. Ubuntu for example added support in version 2.2.22-1ubuntu1.9.
If you have a version that supports ECC certificates, it should be enabled by default. Assuming you're using OpenSSL, the commands to generate an ECC key and CSR are:
ECC P-256 Key:
openssl ecparam -out server.key -name prime256v1 -genkey

ECC CSR:
openssl req -new -key server.key -out server.csr

The installation steps for ECC certs in Apache are identical to RSA. You'd still specify the public key entry, private key entry, and the relevant intermediates. Just double check that your CA supports the issuance of ECC certificates. You can double check ECC compatibility to address any concerns with connecting clients.

A: It doesn't look like it. You can find a list of supported Ciphers here: http://httpd.apache.org/docs/2.0/mod/mod_ssl.html#sslciphersuite

A: Apache 2.4 has the support for ECC in the trunk and you could download or update or build those versions of Apache. Also, if you would like to use ECC then you would also need a OpenSSL version that provides the plumbing for it. Also the OpenSSL version should have the optimizations that Google engineers have contributed for speeding up ECC operations. For more details on Apache and OpenSSL (building with ECC), please see:
http://khanna111.com/wordPressBlog/2012/09/11/94087-2/


text:
Q: Remove quotes from Json output I need to remove double quotes in my json output, I will exlain more. I obtain this result:
[{"id":"1","nom":"Magasin Jardins 2","ville":"Paris","latlng":["36.85715,10.127245"]}

I need to remove quotes at the value of latlng I want to obtain that latlng":
[36.85715,10.127245]

This is my code
  $qry = "SELECT *FROM magasin";
    $result = mysql_query($qry);

  //  $promotions = array();
    $response = array();
    while($row = mysql_fetch_assoc($result)) {

   // $promotions[]= $row;
 $magasin = array();
        $magasin["id"] = $row["id"];
        $magasin["nom"] = $row["nom"];
        $magasin["ville"] = $row["ville"];
        $lat = $row[latitude];
        $long = $row[longitude];

       $magasin["latlng"][] =floatval($lat).",".floatval($long);;

// push single product into final response array
        array_push($response, $magasin);
    }
     mysql_close($con);

  echo json_encode($response);

A: Instead of
$magasin["latlng"][] = floatval($lat).",".floatval($long);

use
$magasin["latlng"] = array(floatval($lat), floatval($long));

If on PHP 5.4+ you can instead use
    $magasin["latlng"] = [floatval($lat), floatval($long)];

This will allow the lat and long values to be passed as floats in the array, instead of typecasting to a string by using the .",". to concatenate.


text:
Q: Watch.JS : callback is not getting called when I set variable dynamically. But works fine for array push I am using watchJS  to set things dynamically on my view. Dynamically pushing into an array is working fine but the assignment is not working.
UPDATE
I just updated the snippet. In that you can see there is another object I am watching with the noMore option set to true. When I unset, it works fine. But I need to set it to true to avoid infinite calls.

   var obj = {
  a :'a',
         b :'b'
    }

    watch(obj, function (a,b,c) {
  WatchJS.noMore = true;
         console.log("change in other ....",c);
    });
    obj.b = 'new'

    var newObj = {
        a: "a",
        b: "1",
        c: []
    }

    watch(newObj, "b", function (prop, ac, New, old) {
       console.log(" B set to ", New);
    }, 1,true)

    watch(newObj, "c", function (prop, ac,New, old) {
   console.log("C set to ", New);
    },1,true)

    newObj.b = "[inline] b" // this works
    newObj.c.push("[inline] c"); // this works

    setTimeout(function () {
     console.log('time')
        newObj.c.push("[timeout] c"); // this works
        newObj.b = "-[timeout ] b" // not working
    },5000)
<script src="https://cdn.jsdelivr.net/npm/melanke-watchjs@1.5.0/src/watch.min.js"></script>

A: Don't use noMore, once it's set to true it will never reset back to false. The array works because it uses a different watcher that does not check noMore.
Instead use WatchJS.suspend(obj, prop). suspend will prevent the next watcher from being called.

const obj = {
    a: 'a',
    b: 'b'
}

const newObj = {
    a: "a",
    b: "1",
    c: []
}

watch(obj, function (a, b, c) {
    console.log("Watch obj - newObj.b suspended!")
    // Next assign newObj.b call will not fire
    WatchJS.suspend(newObj, 'b')
});

watch(newObj, "b", function (prop, ac, newVal, old) {
    console.log("Watch newObj.b", newVal)
}, 1, true)

console.log('Assigning obj.b', obj.b = 'new')
console.log('Assigning newObj.b', newObj.b = "[inline] b")

setTimeout(function () {
    console.log('timer 1')
    console.log('Assigning newObj.b, will not fire watch', newObj.b = "-[timeout ] b")
}, 500)

setTimeout(function () {
    console.log('timer 2')
    console.log('Assigning newObj.b', newObj.b = "-[timeout ] b2")
}, 1000)
<script src="https://cdn.jsdelivr.net/npm/melanke-watchjs@1.5.0/src/watch.min.js"></script>


text:
Q: Formulário HTML não funciona na Alteração de Dados Os formulários de "Inserir" e "excluir" estão interagindo com os dados da tabela do banco de dados MySQL. Exceto O formulário gerenciador-registro que tem a função de "Alterar" registro:
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%
'Dados para a conexão com o banco de dados
 driver   = "{MySQL ODBC 3.51 Driver}" ' Driver para conexão ODBC
 servidor = "localhost"                ' Nome DNS ou do seu servido HTTP
 usuario  = "root"                     ' Nome de usuário para acesso ao MySQL
 senha    = "admin"                    ' Senha de acesso
 banco    = "integracao"               ' Nome do banco de dados

'Cria um objeto de conexão com banco de dados
Set cnnDB = Server.CreateObject("ADODB.Connection")

'Cria a string de conexão
connStr = "driver=" + driver + "; uid=" + usuario + "; "
connStr = connStr + "pwd=" + senha + "; database=" + banco

'Seta a string de conexão, e realiza a conexão
cnnDB.ConnectionString = connStr
cnnDB.Open

'Caso ocorra um erro, prossiga até o tratamento de erro
On error resume next

'Verifica se o arquivo foi chamado a partir de um formulário
If Request.QueryString("acao") = "adicionar" then
    sql = " INSERT INTO LIVROS (LIVRO, AUTOR, EDITORA) VALUES ( "
    sql = sql & "'" & Request.Form("FormNomeLivro") & "', "
    sql = sql & "'" & Request.Form("FormNomeAutor") & "', "
    sql = sql & "'" & Request.Form("FormNomeEditora") & "' "
    sql = sql & ")"

'Executa a expressão SQL no servidor
cnnDB.Execute sql

'Verifica o sucesso da operação, baseada ma variável 'err'
If err.number = 0 then
 Response.Write("Operação realizada com sucesso")
Else
 Response.Write("Erro: " + err.description)
 End if

'Executa a alteração do registro, se solicitada
Elseif Request.QueryString("acao") = "editar" then
    sql = "UPDATE LIVROS SET "
    sql = sql & "LIVRO = '" & Request.Form("FormNomeLivro") & "', "
    sql = sql & "AUTOR = '" & Request.Form("FormNomeAutor") & "', "
    sql = sql & "EDITORA = '" & Request.Form("FormNomeEditora") & "' "
    sql = sql & "WHERE ID = " & Request.Form("FormCodigoLivro")

'Executa a expressão SQL no servidor
cnnDB.Execute sql
'Response.Write "Query = " & sql

' Verifica o sucesso da operação, baseada na variável 'err'
If err.number = 0 then
    Response.Write("Operação realizada com sucesso")
Else
    Response.Write("Erro: " + err.description)
 End if

' Execute a exclusão do registro, se solicitada
Elseif Request.QueryString("acao") = "excluir" then
    sql = " DELETE FROM LIVROS WHERE ID = "
    sql = sql & Request.QueryString("buscacodigo")

' Ececuta a expressão SQL no servidor
cnnDB.Execute sql

'Verifica o sucesso da operação, baseada na variável 'err'
If err.number = 0 then
    Response.Write("Operação realizada com sucesso")
Else
    Response.Write("Erro: " + err.description)
 End if

End if

%>

Clique aqui para inserir um novo registro.

Clique aqui para visualizar os registros.

Ao executar uma alteração em um registro mostra.

Erro: [MySQL][ODBC 3.51 Driver][mysqld-5.7.13-log]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1


text:
Q: Chrome CSS3 3D Transform bug I've got css to do a card flip on a element in 3d space. It works great except for when you scroll up and down the page you randomly get white elements displaying on the page at certain places in Chrome. I've attached an image as an example inside a facebook tab. In chrome windows, the white "boxes" cover up content on occasion. When I comment out the 3d transform css, this doesn't occur. Here is a fiddle (http://jsfiddle.net/derekaug/QSEvs/) of the css that does the 3d stuff. Unfortunately, I can't link to the actual tab yet as it's not public.

A: I have a problem like this before, not saying that it will work for sure but how I fixed it is removing all the transform css properties from the elements when they are not been used.
This is, only apply transform properties while the animation is on. This would mean in your example creating 2 classes one for each animation with all the transform properties, removing the ones on the base classes. Then on click apply the appropiate class and as soon as the transformation is over remove the class. There is a javascript callback that is fired on the elements when the transition is over that would let you remove the class:
CSS3 transition events


text:
Q: Intersecção de 2 arrays com objetos e arrays na propriedade do objeto Resumindo , coloquei em formato de String para poder ilustrar aqui.
Eu tenho um array da seguinte forma :
 "[{"cp_57b326e91ac094817aaf37f2":"1.Folha(Ponto)"}]"

E também tenho o seguinte array de objetos
"[{"cp_57b326e91ac094817aaf37f2":["1.Folha(Ponto)","2.Relogio"]}]"

Eu gostaria de poder fazer uma função para verificar se o primeiro array dá match em alguma opção do segundo array. As chaves são as mesmas, mas no primeiro array terá sempre só uma string como propriedade, e no segundo array, o objeto vai ter um array de strings.
Neste exemplo em questão há intersecção , tentei usar Lodash usando intersectionWith , mas não consegui, imagino que seja pelo fato do segundo array ter um array dentro do obj.

A: Podes fazer isso assim:

*

*verifica se todas as entradas da array têm objetos cujas chaves têm o valor incluído na array correspondente no objeto comparado.

const A = [{
  "cp_57b326e91ac094817aaf37f2": "1.Folha(Ponto)"
}];

const B = [{
  "cp_57b326e91ac094817aaf37f2": ["1.Folha(Ponto)", "2.Relogio"]
}];

const includes = (included, arr) => included.every(entry => {
  return Object.keys(entry).every(key => {
    return arr.find(obj => obj[key].includes(entry[key]));
  })
});

console.log(includes(A, B)); // true


text:
Q: Regular Expression not work correctly according to the requirement I am confused about the pattern used in my Regular Expression. What I want is before decimal the max no of digit the user want to enter is three and the digit should not start with zero. After entering the digit before decimal point which can be three-digit or two-digit or one-digit but can not start with zero. I want to allow users to enter one digit after the decimal point and it should be no more than one. So what will be the pattern for these?
Example:
Number Allow to enter: 1.3, 22.3, 333.4, 999.6
Number Not allowed to enter: 0, 0.1, .1, 4444.67, 333.78
Code I have Used
tempEditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3,1)});
class DecimalDigitsInputFilter implements InputFilter
{
    Pattern mPattern;

    public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero)
    {
        mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)");
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
    {
        Matcher matcher = mPattern.matcher(dest);
        if(!matcher.matches())
        {
            return "";
        }
        return null;
    }
}

A: I think that the pattern you want is:
^[1-9]\d{0,2}\.\d?$

Explanation:
^        // Start of string
[1-9]    // First digit can't be 0
\d{0,2}  // Zero, one, or two more digits after first digit
\.       // Literal decimal point
\d?      // Optional single digit after decimal point
$        // End of string

In your code, it would be:
mPattern = Pattern.compile("^[1-9]\\d{0," + (digitsBeforeZero - 1)
           + "}(\\.\\d{0," + digitsAfterZero + "})?$");

The parentheses that you had around the decimal point and the trailing digit means that a number like "1." would fail to match. Here's a version that makes the decimal point required and the digit(s) afterwards optional:
mPattern = Pattern.compile("^[1-9]\\d{0," + (digitsBeforeZero - 1)
           + "}\\.\\d{0," + digitsAfterZero + "}?$");

A: Pattern.compile("[1-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)"

try this....

A: You have following problems:
"[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)"
 ^^^^^                                              ^
  1                                                 2

*

*Your pattern allows 0 at the start, but you don't want a leading 0

*You allow 0 digits after the dot, but you don't want it.

*You need anchors around your regex to avoid partial matches ("Foo123.4Bar" would be allowed)
So try this
mPattern = Pattern.compile("^[1-9][0-9]{0," + (digitsBeforeZero - 1) + "}((\\.[0-9]{1," + (digitsAfterZero - 1) + "})?)$");
                                                                                ^^^^
                                                                                really -1 ???


text:
Q: How to get only modified Items from WPF Data Grid I have binded a list with Editable WPF DataGrid
I want to get only the modified Items from the WPF Data Grid for updation.
Please let me know how to do this.

A: I have my WPF datagrid app set up as so:
1) Manually defined all the columns, set their bindings and for each binding specified that it notifies on source updates
2) Added an event handler for the datagrid's SourceUpdated event
3) In the event handler I have only the following code:
this.updatedItems.Add(BindingOperations.GetBindingExpression(e.TargetObject, e.Property).DataItem as MyClass);

updatedItems is a HashSet<> and MyClass is the type of objects bound to the datagrid's ItemsSouce.
4) When the user clicks on the save button I simply enumerate the hashset. Hashset is nice, because it only contains unique values. So if a row is edited multiple times or even if multiple cells in the same row are edited, the hashset will still only contain a single entry for the object.

A: Well there is a RowState property on your data row (there is also a RowChanged event), but make sure you need this. Am I under the wrong assumption that databinding automatically figures out which rows need to be updated?


text:
Q: repeated images outside I'm working on a web page, and I have the following CSS:
body {
    background: url('../images/numbers.png');
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
    width: 1024px;
    height: 900px;
}

And the following HTML:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Index</title>
    <link rel="stylesheet" href="css/common.css">

I've set up a size for body (1024x900), but I see that page on browser I see numbers.png everywhere (my monitor resolution is bigger than that).
How can I set background image only inside body (defined as 1024x900)?
How can centre body in the middle of web browser?
By the way, image numbers.png is smaller that 1024x900.

A: add background-repeat:no-repeat;
and for centering the body  using : margin:0px auto;

A: use this :
body {
background: url('../images/numbers.png') no-repeat center center;
display:block;
width: 1024px;
height: 900px;
margin:0 auto;
}

A: The easiest thing to do is to create a page wrapper:

Then adjust your styles:
#page {
  background: url('../images/numbers.png') no-repeat;
  width: 1024px;
  height: 900px;
  margin: 0 auto;
}

This is a common approach and will save headaches later if you do things with viewport, like 100% height.

A: the body is everything you see in the page "including white spaces on the left and right"
you need to have a container div like this
      body {
        font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
    }
    #container {
        background: url('../images/numbers.png');
        width: 1024px;
        height: 900px;
        margin: 0 auto;
    }

    <!DOCTYPE html>

        <meta charset="utf-8">
        <title>Index</title>
        <link rel="stylesheet" href="css/common.css">


text:
Q: l value required as left operand of assignment I'm trying to populate several arrays with the same randomly selected integer but I keep getting the error in the subject line. Here is my code:
while(i++ < arraySize){
        randInt = (int)random()%100;
        originalArray++ = randInt;
        ascendingOrderArray++ = randInt;
        descendingOrderArray++ = randInt;
    }

Why is this error occurring in this context? From my understanding this code is identical to assigning randInt to the three arrays and then incrementing their pointers at the end of the code.

A: Assuming that originalArray, ascendingOrderArray and descendingOrderArray are pointers of type int * and randInt is of type int, you have to de-reference the pointer when assigning. For example *originalArray++ = randInt;. That will de-reference the pointer yielding the "lvalue" you can assign to, assign the value of randInt to it (to whenver originalArray pointer points to), and increment the pointer afterwards.

A: Here, you are trying to assign a value to a number -- to the address of an array. A number is an rvalue, not an lvalue, so it fails.
originalArray++ = randInt;

Here, you are assigning a value to a memory location -- the address obtained by dereferencing a pointer. This is a lvalue, and so it succeeds:
*originalArray++ = randInt;

A: original++ is not an object, and so you can't store a value in it.


text:
Q: How to find inherited columns? I would like to get the list of inherited columns in a database. Is there any query that I can use to find this?
I am using PostgreSql 8.3

A: Here is a simple query to do this:
select relname as table_name, attname as column_name
from pg_class
join pg_inherits on pg_class.oid = pg_inherits.inhrelid
join pg_attribute on pg_inherits.inhparent = attrelid
where attnum > 0;


text:
Q: Stream audio files in php site I have a php site I am developing, I uploaded some audio files into a folder on my server and saved their location URL on my database, now I want to call up the audio file in one of my pages and stream it, my major problem here is the line of code I can use to stream out, and let it be functional on mobile browsers as well. thanks as you help me out.

A: On the PHP side, something like this should work - assuming you refer to mp3:
   header('Content-Type: audio/mpeg');
   header('Content-length: ' . filesize('/path/to/your/file.mp3'));
   print file_get_contents('/path/to/your/file.mp3');

On the front-end you will then need to look for a Javascript based solution that will actually play the file. You said, it needs to be cross-platform - that's more a front-end (Javascript) challenge than something that can be controlled by PHP.


text:
Q: How can the PHP send a file to Java api? I am currently working in a project that is to build a online judging system like codeforces. That is where someone can upload a file for a programming solution and our system will compile the code and generate the output and finally send the result that the solution is correct or not.
The front end is going to build in PHP and the compile engine will be in Java Rest api. This will take a http request, where the request containing which file to compile. The file is like A.cpp that is going to be compiled by the java api and response as a result(right/wrong).
Now my question is about the file that is send from PHP to Java api. How can the PHP send a file to Java api ? Will there be a file server needed ? Or do I need a file server at all ? If I need a file server what is the benefit I will get ? Actually I am not getting the point what is purpose of a file server.
Thank you.

A: How can the PHP send a file to Java api?
This can be done in several ways: HTTP post, a data stream etc.
Will there be a file server needed ? Or do I need a file server at all?
It depends.
If I need a file server what is the benefit I will get ?
The benefits of a file server is sharing storage resources. It's the same as having a network printer instead of everyone having a cheap desktop printer. With one file server, the PHP program could upload the source file to the file server and them send only the name of the file in a message to the Java API. The result or the process could be stored in the file server and you can download it with another API call. This actually makes the process to be asynchronous. And asynchronous processes are easier to debug and schedule for bulk processing.
Another benefit of it is that in can be managed by a team that takes care of backups, retention times, redundancy, disaster recovery, etc.
EDIT. Why asynchronous processes are easier to debug?

*

*The two layers don't have to be up and running in order to test one of them. For example for testing the PHP code that uploads the file to the file server, the Java API layer needs not to be up. To test the Java API you don't even have to mock the PHP call. You just put a file in the server and test the Java method that reads the file and compiles it.

*Basically it's easier to debug and test a bulk process that takes a bulk of files and processes it.

*I'll give you an example: for a phone call (a synchronous communication) to go through, there must be a person in the receiving end to pick up the call. On the other hand when you send an email (an asynchronous communication), the recipient needs not be connected to the internet, but as soon as he/she gets online he will receive a notificationo an email message in his/her inbox. You can test the sending part and the receiving part separatelly with no mocking.

*Also, less error handling code must be written, meaning less code to test and debug.