text:
Q: Two versions of library dependency in Maven In my pom.xml I have
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20170516</version>
</dependency>

And my Program needs and uses this version om JSON.
import org.json.JSONObject;

When I put in
final JsonObject jsonObject = new JsonObject();
System.out.println( jsonObject.getClass().getPackage().getImplementationVersion());

I get
20170516

Okay, alright. (Note: This is a class of the program, not the test!)
Now I run my Unittest (Mockito, JUnit) with mvn test. I get an error, which is related to the JSONObject version. And the log says:
0.0.20131108.vaadin1

I found out, that this version comes from this dependency
<dependency>
    <groupId>org.skyscreamer</groupId>
    <artifactId>jsonassert</artifactId>
    <version>1.5.0</version>
    <scope>test</scope>
</dependency>

If I delete it, my test works fine.
But now other tests fail, which uses this dependency
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

and in pom.xml
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.4.RELEASE</version>
</dependency>

How can I configure maven, that the program uses JSON version 20170516, but spring-test can still use jsonassert?
Even if almost the same name, I don't think this is a duplicate of

*

*two versions of dependencies in maven
-- Edit 1
mvn dependency:tree | grep json
[INFO] +- org.skyscreamer:jsonassert:jar:1.5.0:test
[INFO] |  \- com.vaadin.external.google:android-json:jar:0.0.20131108.vaadin1:test
[INFO] +- com.jayway.jsonpath:json-path-assert:jar:2.2.0:test
[INFO] |  +- com.jayway.jsonpath:json-path:jar:2.2.0:test
[INFO] |  |  \- net.minidev:json-smart:jar:2.2.1:test
[INFO] +- org.json:json:jar:20170516:compile

A: you need to add the dependencies that you want to enforce specific version when there is conflict in dependencyManagement. This ensures the maven uses 20170516 version of json dependency even though jsonassert depends different version.
    <dependencyManagement>
    <dependencies>
        <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20170516</version>
        </dependency>
        <dependency>
            <groupId>org.skyscreamer</groupId>
            <artifactId>jsonassert</artifactId>
            <version>1.5.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    </dependencyManagement>

Please see Differences between dependencyManagement and dependencies in Maven
or you can use <exclusions> to exclude a child dependency.

A: Unless spring-test or jsonassert will shade the org.json:json dependency internally in the future version you are stuck having to use one version of org.json:json across the classpath.
Not all Java dependencies are compatible, see classpath hell.
You can try defining a Dependency Exclusion for the problematic version but this can potentially brake jsonassert dependency:
<dependency>
  <groupId>org.skyscreamer</groupId>
  <artifactId>jsonassert</artifactId>
  <version>1.5.0</version>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>com.vaadin.external.google</groupId>
      <artifactId>android-json</artifactId>
    </exclusion>
  </exclusions>
</dependency>


text:
Q: Change meta theme-color in dark mode with javascript? How can I merge this two script into one function,
<script>//<![CDATA[
function LMcheckCheckbox(){
    document.querySelectorAll(".checkbox").forEach(function(e) {
       "darkmode"===localStorage.getItem("mode")?e.checked=!0:e.checked=!1
        })
    }
function darkMode(){
     localStorage.setItem("mode","darkmode"===localStorage.getItem("mode")?"light":"darkmode"),
     "darkmode"===localStorage.getItem("mode")?document.querySelector("body").classList.add("darkmode"):document.querySelector("body").classList.remove("darkmode"),
     LMcheckCheckbox()
 }
 function darkModeHide(){
      document.querySelectorAll(".darkmode-switch").forEach(function(e){
           e.parentNode.removeChild(e)
      })
 }
LMcheckCheckbox(),
"undefined"==typeof AzidBloggerSetting
 &&(AzidBloggerSetting={tombolDarkmode:!0}),
 0==AzidBloggerSetting.tombolDarkmode&&darkModeHide();
    //]]>
</script>

and here the script to change meta theme color
$("meta[name='theme-color']").attr('content', '#333333');

how can I insert the second script in to the first script? I want to change the meta theme-color when the first script is active.

A: You need to find where the darkmode is being activated and put your code in there.(unminify the code to see whats going on first)
i suggest you get a basic understanding of javascript before jumping into code!
as far as i understood, this is what you wanna do:
function LMcheckCheckbox() {
  document.querySelectorAll(".checkbox").forEach(function(e) {
    "darkmode" === localStorage.getItem("mode") ? e.checked = !0 : e.checked = !1
  })
}

function darkMode() {
// this is seemingly where the dark mode is being applyed so :
$("meta[name='theme-color']").attr('content', '#333333');
  localStorage.setItem("mode", "darkmode" === localStorage.getItem("mode") ? "light" : "darkmode"), "darkmode" === localStorage.getItem("mode") ? document.querySelector("body").classList.add("darkmode") : document.querySelector("body").classList.remove("darkmode"), LMcheckCheckbox()
}

function darkModeHide() {
  document.querySelectorAll(".darkmode-switch").forEach(function(e) {
    e.parentNode.removeChild(e)
  })
}
LMcheckCheckbox(), "undefined" == typeof AzidBloggerSetting && (AzidBloggerSetting = {
  tombolDarkmode: !0
}), 0 == AzidBloggerSetting.tombolDarkmode && darkModeHide();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Although tor is the default proxy, it does not work as default! I installed tor using apt and it started to work on port 9050 as a socks proxy automatically.
So I set my Network Proxy to be on Manual mode:
FTP, HTTP, HTTPS: 127.0.0.1:8118
SOCKS: 127.0.0.1:9050
I rebooted my system and I expected that my requests don't reveal my real public IP address, but they did. So I installed Foxy Proxy extension from
the chrome webstore and set it to use the SOCKS proxy from port 9050 for requests. It worked! But I don't have any solution for using tor in terminal. I want it to be my default, and it should be!


text:
Q: Validity of Arithmetic Progression Given the sum of arithmetic progression and number of terms . We have to determine whether the arithmetic progression exists or not . First term and common difference should be natural numbers .
e.g - if n = 10 and S = 265 ; then answer should be "true" as the AP would be - 4 , 9 , 14 , 19 , 24 , 29 , 34 , 39 , 44 , 49 .
if n = 4 and S = 24 ; then answer should be "true" as the AP would be - 3 , 5 , 7 , 9 .

A: Let the sum be $s$, the number of terms be $n$, the common difference be $d$ and the first term be $a_1$. We have the following:
$$s=\frac{n(2a_1+(n-1)d)}{2}$$
Multiply both sides by $\frac 2 n$:
$$\frac{2s}{n}=2a_1+(n-1)d$$
Subtract both sides by $(n-1)d$ and divide by $2$:
$$a_1=\frac{2s-(n^2-n)d}{2n}$$
Since $a_1$ is an integer, this means that:
$$2s-(n^2-n)d \equiv 0 \pmod {2n}$$
$$2s \equiv (n^2-n)d \pmod {2n}$$
$$2s \equiv n(n-1)d \pmod {2n}$$
Now, since the right side is a multiple of $n$ and $n$ is a factor of $2n$, this means that the left side is also a multiple of $n$.

*

*If $n$ is odd and $2s$ is a multiple of $n$, then the $2$ isn't helping since it's not a factor of $n$, so $s$ has to be a multiple of $n$.

*If $n$ is even and $2s$ is a multiple of $n$, then the $2$ is helping since it is a factor of $n$, so $s$ only has to be a multiple of $\frac n 2$.

In both cases, either $d=1$ or $d=2$ solves the equation. Thus, we substitute both $d=1$ and $d=2$ into the equation:
$$a_1=\frac{2s-n(n-1)d}{2n}$$
If for $d=1$ or $d=2$, we get a natural number for $a_1$, then we have found the arithmetic sequence necessary to create sum $s$ and number of terms $n$. Otherwise, no such sequencer exists.


text:
Q: Typescript: Remove an attribute from an object safely I'd like to write a typescript function that takes an object that includes the parameter foo and outputs the same object without the parameter foo.  I want to do this all in a typesafe manner.  Seems pretty simple, but I'm stumbling.  Here is the code I have so far:
interface FooProp {
    foo: string;
}
type WithFooProp<P extends object> = P extends FooProp ? P : never;
type WithoutFooProp<P extends object> = P extends FooProp ? never: P;

function withoutFooProp<P extends object>(input: WithFooProp<P>): WithoutFooProp<P> {
    // How do I get rid of these any's
    const {foo, ...withoutFoo} = input as any;
    return withoutFoo as any;
}

This isn't great because I use any a bunch.  I'd sorta expect the code to work as is without any, but TS complains that input isn't an object and can't be destructured.  How could I improve this method?
In addition, when I use this function, TS forces me to provide the generic types explicitly.  I wish it would infer the types implicitly. Is there any way I could write the function to implicitly grab the parameters.
// Compiles - but I have to specify the props explicitly
withoutFooProp<{foo: string, bar: string}>({
    foo: 'hi',
    bar: 'hi',
});

// This doesn't compile - I wish it did!  How can I make it?
withoutFooProp({
    foo: 'hi',
    bar: 'hi',
});

Thanks in advance!

A: You can let the parameter type be simply P, where P is constrained to contain the foo property, so that type inference will work: it will just set P to the argument type.  Then use Pick and Exclude to generate the type of the output object containing all properties of P except foo.
interface FooProp {
    foo: string;
}
type WithoutFooProp<P> = Pick<P, Exclude<keyof P, "foo">>;

function withoutFooProp<P extends FooProp>(input: P): WithoutFooProp<P> {
    const {foo, ...withoutFoo} = input as any;
    return withoutFoo;
}

You won't be able to get rid of the any unless/until this suggestion is implemented.  I wouldn't worry about it.
This withoutFooProp function should work on any concrete input type and give you a concrete output type.  If you are using withoutFooProp on objects of generic types, then you may run into problems because of TypeScript's limited ability to reason about Pick and Exclude, and you may wish to use intersections instead (even though doing so is technically unsound), as demonstrated in this answer in the context of React higher-order components.

A: You can also use this typesafe function which works as generic and can be used for any object:
export function deleteProperty<TObject, TProp extends keyof TObject>(object: TObject, prop: TProp): Omit<TObject, TProp> {
 const {
    [prop]: toDelete,
    ...newObject
 } = object

 return newObject;
}


text:
Q: AjaxControlToolkit 7.0123 breaks UpdatePanel asynchronous post-back I have an ASP.NET Web Application built against ASP.NET 4.5 in VS2012. Within the application are a number of forms containing ListView controls which in turn contain UpdatePanel controls so that any edit that takes place or new data that is added is carried out asynchronously and not repeated if the user refreshes the page.
This worked fine until today. Today I added the latest version of the AjaxControlToolkit (7.0123) to the project using NuGet and carried out the modifications to the scripts etc. as specified by Stephen Walther here.
Since the introduction of the AjaxControlToolkit to the project, the asynchronous post-backs appear to have become synchronous. If for example I edit an item in the ListView, when I then press F5 (in IE or Firefox) I am prompted that I will be resending the data.
The mark-up is pretty simple...
<asp:ListView ID="LocationList" runat="server" ItemType="Model.Location" DataKeyNames="ID" InsertItemPosition="LastItem" DeleteMethod="LocationList_DeleteMethod" InsertMethod="LocationList_InsertMethod" SelectMethod="LocationList_SelectMethod" UpdateMethod="LocationList_UpdateMethod">
  <LayoutTemplate>
    <asp:UpdatePanel ID="ListViewUpdatePanel" runat="server">
      <ContentTemplate>

                <asp:LinkButton ID="SortByDescription" runat="server" CommandName="Sort" CommandArgument="Name" Text="Description" />

          <asp:PlaceHolder ID="itemPlaceholder" runat="server" />

      </ContentTemplate>
    </asp:UpdatePanel>

      <asp:DataPager runat="server" />

  </LayoutTemplate>
  <ItemTemplate>

        <%#: Item.Name %>

        <asp:LinkButton ID="Edit" runat="server" CommandName="<%#: Global.CommandNames.Edit %>" CommandArgument="<%#: Item.ID %>" Text="Edit" />

  </ItemTemplate>
  <EditItemTemplate>

        <asp:TextBox ID="Description" runat="server" Text="<%#: BindItem.Name %>" />

        <asp:LinkButton ID="Update" runat="server" CommandName="<%#: Global.CommandNames.Update %>" Text="Update" />
        <asp:LinkButton ID="Cancel" runat="server" CommandName="<%#: Global.CommandNames.Cancel %>" Text="Cancel" />

  </EditItemTemplate>
  <InsertItemTemplate>

        <asp:TextBox ID="Description" runat="server" Text="<%#: BindItem.Name %>" />

        <asp:LinkButton ID="Insert" runat="server" CommandName="<%#: Global.CommandNames.Insert %>" Text="Add" />

  </InsertItemTemplate>
</asp:ListView>

The mark-up provided is within a ContentPanel and the page uses a MasterPage. The MasterPage has the ToolkitScriptManager control as outlined above.
As I have already stated, this worked fine prior to installing the AjaxControlToolkit.
I have also tried changing the layout of the page in as much as moving the UpdatePanel outside of the entire ListView (and then placing the pager under the UpdatePanel); this made no difference.
I am at a total loss as to what can be causing this other than some compatibility and/or configuration issue involving the AjaxControlToolkit. I have found other references to similar problems but I have yet to find any solution that work (for example, there are articles that indicate problems when using static client id's but as you will see from the mark-up provided I have already tried removing these and it makes no difference).


text:
Q: Custom ActionSheet doesn't work when getting in SplitView I want to implement a custom ActionSheet, everything works fine except one thing, when getting in split view with the action sheet opened the touch area of the button from my custom action sheet is wrongly positioned. As you can see in the demo(at the end of it) I press on the button but nothing happens, but if I press a little bit higher the button is pressed, it looks somehow the touch area of the button is not over the button as it is supposed to be.
Here is a demo representing the problem:

Here is my code:
import SwiftUI

struct ContentView: View {
    var body: some View {
        ModalContent()
    }
}

struct ModalContent: View {
    @ObservedObject var actionSheetViewModel = ActionSheetViewModel.sharedInstance

    @Environment(\.horizontalSizeClass) var horizontalSizeClass

    var body: some View {
        if horizontalSizeClass == .regular {
            if actionSheetViewModel.showActionSheetCompact != false && actionSheetViewModel.showActionSheetRegular != true {
                actionSheetViewModel.showActionSheetCompact = false
                actionSheetViewModel.showActionSheetRegular = true
            }
        } else {
            if actionSheetViewModel.showActionSheetCompact != true && actionSheetViewModel.showActionSheetRegular != false {
                actionSheetViewModel.showActionSheetRegular = false
                actionSheetViewModel.showActionSheetCompact = true
            }
        }

        return Text("")
        .sheet(isPresented: Binding.constant(true)) {
            ZStack(alignment: .bottom) {
                Color.green.opacity(0.3)
                VStack {
                    Text("Modal").padding(.bottom, 10)
                    Button(action: {
                        self.actionSheetViewModel.showActionSheetCompact = true
                    }) {
                        Text("Show ActionSheet").frame(width: 300, height: 50).background(Color.red)
                    }
                    .popover(isPresented: self.$actionSheetViewModel.showActionSheetRegular){
                        ActionSheetRegular()
                    }
                    Color.clear
                }
                ActionSheetCompact()
            }
        }
    }
}

struct ActionSheetCompact: View {

    @ObservedObject var actionSheetViewModel = ActionSheetViewModel.sharedInstance

    var body: some View {
        if actionSheetViewModel.showActionSheetCompact == true {
            return AnyView(
                VStack {
                    Color.clear
                    Button(action: {
                        print("Action sheet button was pressed")
                    }) {
                        Text("Action Sheet").frame(width: 100, height: 45).background(Color.yellow)
                    }
            })
        } else {
            return AnyView(EmptyView())
        }
    }
}

struct ActionSheetRegular: View {

    @ObservedObject var actionSheetViewModel = ActionSheetViewModel.sharedInstance

    var body: some View {
        if actionSheetViewModel.showActionSheetRegular == true {
            return AnyView(
                VStack {
                    Color.clear
                    Button(action: {
                        print("Action sheet button was pressed")
                    }) {
                        Text("Action Sheet").frame(width: 100, height: 45).background(Color.yellow)
                    }
            })
        } else {
            return AnyView(EmptyView())
        }
    }
}

class ActionSheetViewModel: ObservableObject {
    @Published var showActionSheetCompact = false
    @Published var showActionSheetRegular = false

    static let sharedInstance = ActionSheetViewModel()

    private init() {}
}


text:
Q: Lazy Evaluation in Python/Scipy I'm trying to add constraints to a mathematical model iteratively with Scipy using lambda function as below:
cons = []

for i in range(3):
    a = lambda x: np.array([x[i] - 600])
    cons.append({'type': 'ineq', 'fun': a})

But it executes only the last call, when i=2. How can I do to make this a full evaluation and execute all the elements in iteration? I read a couple of posts here without sucesss


text:
Q: why does it say that an error occurred when trying to deploy? I use GitHub Actions for automatic deployment to the host, if I specify the full path to the project, it gives an error
enter image description here
enter image description here


text:
Q: Capital letters to cells in column I'm trying to change all letters into capital letters in all cells holding data in column B2 and down. Got this VBA.
Sub CapitalLettersColumnB()

    'Capital Letters to names in column B (from B2 and down)
    'Column B holds headers!

    With Range("B2", Cells(Rows.Count, "B").End(xlUp))
        .Value = Evaluate("INDEX(UPPER(" & .Address(External:=True) & "),)")
    End With

End Sub

When my sheet holds 2 rows of data (and more), not counting headers, the vba works just fine.
But when my sheet only holds 1 row of data, not counting headers, name in column B (cell B2) is replaced with #VALUE!.
Anyone that can help spot what's wrong, and how to correct my vba?

A: The problem is INDEX. The funtion returns a position in a Range or Array, not a single value. If you would evaluate the formula it would come down to this:
=INDEX("VALUE",)

Instead of a correct:
=INDEX({"VALUE1","VALUE2"},)

Not feeding the INDEX a range or array will then return the error

To correct your code you need to make sure there is always a range object larger than one cell, so for example:
Sub CapitalLettersColumnB()

With Range("B1", Cells(Rows.Count, "B").End(xlUp))
    .Value = Evaluate("IF(ROW(" & .Address & ")>1,INDEX(UPPER(" & .Address & "),)," & .Address & ")")
End With

End Sub

This will now work from B1 onwards, but will leave that cell intact through the ROW test in our IF statement.
Another small note, I would definately use an explicit cell reference (including at least a worksheet)

A: Honestly not sure what is wrong. (I think it's the same reason as range("B2:B2"). You can't set a range spanning the same cell)
Your Cells(Rows.Count, "B").End(xlUp) returns the value of the last cell which I'm not sure how that works.
But you could change the code to do a with the range to lastrow.
But if the lastrow is 2 the code will fail, so the if goes to else and it only changes the Ucase of cell B2.
If Cells(Rows.Count, "B").End(xlUp).Row > 2 Then
    ' more than one row after B2
    With Range("B2:B" & Cells(Rows.Count, "B").End(xlUp).Row)
        .Value = Evaluate("INDEX(UPPER(" & .Address(external:=True) & "),)")
    End With
Else
    ' no rows past B2
    Range("B2").Value = UCase(Range("B2").Value)
End If


text:
Q: Blob to Base64 in javascript not returning anything from FileReader I am using FileReader in typescript to convert a blob to a base64 image that will then be displayed in the template of my application.
  adaptResultToBase64(res: Blob): string {
    let imageToDisplay : string | ArrayBuffer | null = '';

    const reader = new FileReader();

    reader.onloadend = function () {
      imageToDisplay = reader.result;
      return imageToDisplay;
    };

    reader.readAsDataURL(res);

    return imageToDisplay;
  }

Whilst the data logged inside the read.onloadend function displays the base64 string I cannot pass it out of the function.
I have tried adding a callback but where it is called elsewhere doesn't return anything but an empty string.

A: Please check this code
<input type="file" id="file">
<button id="click">click</button>

let data: string | ArrayBuffer;

document.getElementById('file').onchange = function (e: Event) {
  let files: FileList | null = (<HTMLInputElement>e.target).files;

  let reader: FileReader = new FileReader();
  reader.onload = function (e: ProgressEvent<FileReader>) {
    console.log(e.target.result);
    data = e.target.result;
  };
  if (files.length > 0) {
    reader.readAsDataURL(files?.[0]);
  }
};

document.getElementById('click').onclick = function () {
  console.log(data); // result if present otherwise null is returned
};

Using a separate method view. The return value is a Promise.
function adaptResultToBase64(res: Blob): Promise<string> {
    let reader: FileReader = new FileReader();

    return new Promise((resolve, reject) => {
        reader.onloadend = () => {
            resolve(reader.result as string);
        }
        reader.onerror = () => {
            reject("Error reading file.");
        }
        reader.readAsDataURL(res);
    })
}

To get the result
adaptResultToBase64(/* Blob value */)
    .then(resp => console.log(resp))
    .catch(error => console.log(error));

See here for specifics on Promise
MDN
learn.javascript.ru

A: The basic result I needed and did not realise that the reader.onload is actually a callback for read.readAsDataUrl and finishes everything inside it async.
adaptResultToBase64(res:Blob){

    const reader = new FileReader();

    reader.onload = function () {

    // Was missing code here that needed to be called asynchronously.

    adapterToNewObject(reader.result.toString())

    };

    reader.readAsDataURL(res);

  }
}

I was performing this in Angular so for anyone else who runs into this problem here it is using Angular syntax:
In your class:
export class Component {

adaptedResult:Result

 getBase64() {
    this.http.get().subscribe((result: Blob) => {

        const reader = new FileReader();

        reader.onload = () => {

          this.adaptedResult =  this.adapter(reader.result) // Assign or use  reader.result value, this is an example of using an adapter function.
        };

        reader.readAsDataURL(result);
      });
  }

 adapter(base64:string){
  return {
   name:'image',
   image:base64'
   }
 }

}


text:
Q: Java - use wait() method until specific time reached I have a thread that runs in the background of my program and detects when a deadline (set by user input at the beginning of the program) occurs. I have implemented this in a while loop and using the sleep(1000) method.
It all works ok, but I would like to change it over from using sleep(1000) to using wait() and notifyAll() to be consistent with the rest of my code, and to make the alert happen in real-time rather than lagging by a part of a second until the thread re-awakens.
Here is what I currently have
    //Retrieve current date and time...
    Calendar now = Calendar.getInstance();

    //deadline not yet reached
    while(now.before(deadline))
    {
        try
        {
            //wait a second and try again
            sleep(1000);
        }
        catch (InterruptedException intEx)
        {
            //Do nothing.
        }

        //Update current date and time...
        now = Calendar.getInstance();
        //run loop again
    }

    ////////////////////////////
    ///alert user of deadline///
    ////////////////////////////

I have tried to change it over to use wait(), but had no success. Can anybody see a way of changing the existing code over to implement the methods I mentioned?
Thanks in advance,
Mark

A: So this question is, how can I use wait to act like sleep. If you want to use wait, you will have to use two threads. Use a ScheduledExecutorService (Tutorial).
 ScheduledExecutorService executor = newSingleThreadScheduledExecutor();

This can be done once and reused. Otherwise you have to shutdown the executor.
We'll set our deadline to be x minutes in the future, using Instant from the modern java.time framework (Tutorial).
final Instant deadline = Instant.now().plus(x, ChronoUnit.MINUTES);

Next we want to schedule a task so that our thread will wake in x minutes.
while(Instant.now().isBefore(deadline)){
    synchronized(deadline){
        executor.schedule(
            ()->{
                synchronized(deadline){
                    deadline.notifyAll();
                }
            },
            Duration.between(Instant.now(),deadline).toMillis(),
            TimeUnit.MILLISECONDS
        );
        deadline.wait();
    }
}

It is in a loop, just in case there is a spurious awake. It resubmits the task, just in case there was a spurious awake and in the meantime the other task completed and didn't wake the thread before the thread called wait again.
This above is a bit tongue in cheek. Really if you just used the following it would seem more ''realtime''.
long diff = deadline.getTimeInMillis()-now.getTimeInMillis();
if(diff>0)
    Thread.sleep(diff);

A: From oracle documentation page
public final void wait(long timeout)
                throws InterruptedException

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

Precondition: The current thread must own this object's monitor.
A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:
 synchronized (obj) {
     while (<condition does not hold>)
         obj.wait(timeout);
     ... // Perform action appropriate to condition
 }

A: Use the wait(long timeout) method.


text:
Q: Detect x-webkit-speech? I want to detect if the browser supports x-webkit-speech (speech to text in <input>s) using JavaScript, but it seems impossible. How can I achieve that?
(I want to display a message if the browser or its version does not support it.)

A: you can check whether the browser has a support for speech like this:
if( document.createElement('input').webkitSpeech==undefined )
{
  //no speech support
}

A: Detect on webkit browser (currently only Chrome) and maybe W3C in future ^_^
if ( !!("webkitSpeechRecognition" in window) || !!("speechRecognition" in window) )

       alert("yeah!")

}


text:
Q: Missing Initial Step from Step Plot D3.js This is an issue that I have not discovered a clean fix for.
Within my step plot below:
http://jsfiddle.net/q47r3pyk/7/
You can see that I have a vertical blue line at the start of the chart.
This is because I added an additional x-value and y-value so that the first step will show up in the step plot.
If you look at
http://jsfiddle.net/q47r3pyk/8/
where I remove the first dummy entry with
x-value of "12-Jul-14"
y-value of 0
The first step of my step plot will have a width of zero.
Is there a recommended approach within d3.js for having the first step show without losing the last step by using step-after? or a fix for removing the vertical blue line that shows up with my hack of adding a dummy value?
Step is specified in
var line = d3.svg.line()
        .x(function (d) {
               return x(d.x);
           })
        .y(function (d) {
               return y(+d.y);
           })
        .interpolate("step-after");

A: You could clip the path using SVG clip-path:
svg.append("clipPath").attr("id", "canvasClip")
.append("rect")
.attr("height", height)
.attr("width", width)

Then reference the clip-path on your line:
svg.append("path")
        .datum(formatted_data)
        .attr("class", "line")
        .attr("d", line)
        .attr("clip-path", "url(#canvasClip)")

Here's the fiddle, it seems to work fine:
http://jsfiddle.net/q47r3pyk/11/
But, ultimately, I think this is a case where the interpolator is acting as it should, and you really shouldn't be thinking about how to subvert it but rather whether it's the right interpolator for your data. In this case, I'd say no, and suggest you use "step" as your interpolator instead of "step-before" or "step-after". I think that would give you the result you're looking for and lines up well with your interactivity.

A: Is this help?
I have tried several times, i think it is the best result i have got, hope it helps!
x.domain(d3.extent(x_axis, function (d) {
    return parseDate(d);
})).nice(x_axis.length);

fiddle


text:
Q: socket.io событие эмитится слишком много раз Задача:
Получить имена пользователей
Проблема:
Для начала я добавляю макеты этих диалогов - первая строчка цикла.
Потом я отправляю JSONObject через этот emit (все работает!)
Далее, по логике, должен пройти socket.on, но он очень странно работает. Цикл идет только 4 раза, а лог, который я добавлял внутрь этого socket.on выполнялся куда больше кол-во раз и он находил только одного пользователя.
То есть работает бешено и не понятно по какой логике.
 Может это как-то можно синхронизировать?
for( i= contacts.size()-1; i >= 0; i--){
        data.add(new DialogInfo("null", contacts.get(i), "null", "null", contacts.get(i)));
        for( i= contacts.size()-1; i >= 0; i--){
            try {
                obj.put("id", contacts.get(i));
                socket.emit("info", obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            socket.on("user_info", new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    userInfo = (JSONObject) args[0];
                    try {
                        adapter.editItemByID(userInfo.getString("id"), new DialogInfo(userInfo.getString("nick"),
                                userInfo.getString("id"), "null", "null", userInfo.getString("id")));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

Надеюсь, вы сможете помочь решить мне эту проблему!

A: При выполнении команды socket.on каждый раз вешается листенер, который не убирает предыдущий. Т.е. после прохождения N раз по циклу будет висеть N листенеров. И они все одновременно будут вызываться по этому событию.
В данном случае более подходящим будет метод socket.once(). Этот метод добавляет единоразовый листенер OnceListener, который срабатывает только при первом эмите события.
Так же, как вариант решения проблемы, если предыдущие листенеры по этому ивенту не нужны, можно непосредственно перед socket.on("user_info", new Emitter.Listener(){}) делать socket.off("user_info"). Этот метод удалит все листенеры по ивенту "user_info". Так же можно убирать конкретный листенер, по конкретному ивенту, если использовать не анонимный класс листенера, а вполне определенный объект класса, вынесенный в переменную, следующим образом socket.off("user_info", onUserInfoListener)
Так же, для наблюдения за событиями, которые эмитятся, я настоятельно рекомендую использовать логи самой socket.io, вместо ручных логов в листенерах, следующим образом. Вспомогательный класс:
import android.util.Log;
import java.util.logging.*;

/**
 * Make JUL work on Android.
 */
public class AndroidLoggingHandler extends Handler {

    public static void reset(Handler rootHandler) {
        Logger rootLogger = LogManager.getLogManager().getLogger("");
        Handler[] handlers = rootLogger.getHandlers();
        for (Handler handler : handlers) {
            rootLogger.removeHandler(handler);
        }
        rootLogger.addHandler(rootHandler);
    }

    @Override
    public void close() {
    }

    @Override
    public void flush() {
    }

    @Override
    public void publish(LogRecord record) {
        if (!super.isLoggable(record))
            return;

        String name = record.getLoggerName();
        int maxLength = 30;
        String tag = name.length() > maxLength ? name.substring(name.length() - maxLength) : name;

        try {
            int level = getAndroidLevel(record.getLevel());
            Log.println(level, tag, record.getMessage());
            if (record.getThrown() != null) {
                Log.println(level, tag, Log.getStackTraceString(record.getThrown()));
            }
        } catch (RuntimeException e) {
            Log.e("AndroidLoggingHandler", "Error logging message.", e);
        }
    }

    static int getAndroidLevel(Level level) {
        int value = level.intValue();
        if (value >= 1000) {
            return Log.ERROR;
        } else if (value >= 900) {
            return Log.WARN;
        } else if (value >= 800) {
            return Log.INFO;
        } else {
            return Log.DEBUG;
        }
    }
}

Дальше непосредственно в месте применения в активити или фрагменте в onCreate инициализировать след. образом:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AndroidLoggingHandler.reset(new AndroidLoggingHandler());
    java.util.logging.Logger.getLogger("my.category").setLevel(Level.FINEST);
}

В таком случае будет видно реальное количество раз эмита всех событий.


text:
Q: Empty swapfile after using dd According to many tutorials available on the internet (like for example this one https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04 ), to generate a swapfile, i need to use a following command:
sudo dd if=/dev/zero of=/swapfile bs=1G count=4

However, for some reason, while that file should have 4GB of size, it has 0
root@vps:~# ls -sh /swapfile
0 /swapfile

I feel kind of helplessness because i'm not so-good superuser nor any of these tutorials provides a solution on how to deal with that. I'm also not able to find anything about that on the internet.

A: The tutorial you linked to seems complicated except for the Faster Way which says to use the fallocate program which is provided by the libextunix-ocaml package in Ubuntu 14.04. You can create a 4 GB swap file using: sudo fallocate -l 4G /swapfile


text:
Q: USB/bluetooth tether to Kubuntu 15.10 I am trying to provide Internet to laptop, from any of two phones.
I can do it only by wifi, but it drains battery quickly.
When same laptop had Linux Mint 17.1-3 XFCE it worked without problem (on both smartphones).
I am able to connect by bluetooth, and on phone popups message to authorize laptop to use Internet, which I accept, and phone says, that shares connection to 1 device (from this moment Linux Mint had Internet), however, laptop just loops between "retrying connection" and after each 10 seconds "connection failed".
I can send and receive files by bluetooth without problem.
Connecting any phone with usb, and clicking tether as in Mint, makes laptop to recognize connection as "ethernet" (it's okay I guess), but also Internet cannot be accessed.
I can access phone's files by usb without problem, and it gets recognized as right device.
I was trying on both phones with both bluetooth and usb to ping 8.8.8.8 and it gives me "Network unreachable".
Tether by wifi works fine.
How can I tether by usb and bluetooth?
EDIT:
I know, that 8.8.8.8 and 8.8.4.4 are Google's DNS, and they will know, which hostnames I want to resolve, if I use their DNS.
However, I have been trying to add 8.8.8.8 as name server in connection settings, and it didn't work - how is this file different?
But yes - adding "nameserver 8.8.8.8" and "nameserver 8.8.4.4" to this file solved issue for bluetooth.
I still cannot tether through usb - lapcop creates "Wired connection 1" with type of "Wired Ethernet", but it cannot really connect to it (last used: "never").
I am unable to force establishing this connection, in connection editor, option "connect" is disabled for this connection, and connection manager in tray doesn't even show it.
I have been trying to remove it, and also add from two separate phones - without luck.
It may be also worth a note, that before adding those nameservers to file, bluetooth couldn't even connect as Network Access Point, but now it works fine.
Remaining questions:
1. How to establish connection through usb?
2. How is nameserver in file different from DNS in connection settings?

A: I had the same problem. So try opening /etc/resolve.conf and where nameserver 127.*** change it to 8.8.8.8 then add nameserver 8.8.4.4 save it and reboot. Try your connection again.


text:
Q: Computing a logarithmic function Possibly this is a very lame question for this site.
There is a function $f(n)=-\ln(a*n); \space \Bbb Z \to \Bbb R$, and I want to define $a$ for pairs of values. For example:
$f_1(n_1)=15; f_1(n_5)=1.157$
$f_2(n_1)=454; f_2(n_8)=1.0042$
and so on. How can I write a function that could calculate $a$ values from the starting values?

A: I guess you want something like this, but not sure:
Solve[{-Log[a n] == x1, -Log[a (n + k)] == x2}, {a, n}]
(*
  a -> (-E^-x1 + E^-x2)/k
*)

Edit
More generally, for any invertible function f:
Solve[{f[a n] == x1, f[a (n + k)] == x2}, {a, n}]

$\left\{\left\{a\to \frac{f^{(-1)}(\text{x2})-f^{(-1)}(\text{x1})}{k},n\to -\frac{k
   f^{(-1)}(\text{x1})}{f^{(-1)}(\text{x1})-f^{(-1)}(\text{x2})}\right\}\right\}$


text:
Q: jQuery toggle on different elements without creating a new function for each id element Is there a way of making a jQuery toggle work on different elements on the same page without the need of having one function for each of the id elements.
This is what I have so far.
jQuery:
//Toggle-->
$('#clickme_info_1').click(function() {
$( '.toggle_info_1' ).animate({ "height": "toggle", "opacity": "toggle" }, "slow" )
});

$('#clickme_info_2').click(function() {
    $( '.toggle_info_2' ).animate({ "height": "toggle", "opacity": "toggle" }, "slow" )
});

HTML:

+

Info 1 shows

        Slide 1

+

Info 2 shows

        Slide 2

You can see it working in here http://jsfiddle.net/RaulMv/5FsPJ/

A: Add a class to the + element and on the animate add that class to the click function and on the animate change the toggle to $(this).next()
$('.yourclassname').click(function() {
    $( this ).next().animate({ "height": "toggle", "opacity": "toggle" }, "slow" )
});

Here is a working example: http://jsfiddle.net/5FsPJ/3/

A: Try:
$('#testSlider04 li > div').click(function() {
    $(this).next().animate({ "height": "toggle", "opacity": "toggle" }, "slow" )
});

jsFiddle example

A: you should use class on div
Demo
//Toggle-->
$('.clickme_info_1').click(function() {
    $( this ).next().animate({ "height": "toggle", "opacity": "toggle" }, "slow" )
});

//FlexSlider-->
$(document).ready(function () {
    $('#testSlider04').flexslider({
        animation: "slide",
        animationLoop: true,
        slideshow: false,
        slideshowSpeed: 7000,
        animationSpeed: 600,
        initDelay: 0,
        randomize: false,
    });
});


text:
Q: How to find which SQLite pragmas take effect during SQL compilations? According to the docs,

Some pragmas take effect during the SQL compilation stage, not the execution stage. This means if using the C-language sqlite3_prepare(), sqlite3_step(), sqlite3_finalize() API (or similar in a wrapper interface), the pragma may run during the sqlite3_prepare() call, not during the sqlite3_step() call as normal SQL statements do. Or the pragma might run during sqlite3_step() just like normal SQL statements. Whether or not the pragma runs during sqlite3_prepare() or sqlite3_step() depends on the pragma and on the specific release of SQLite.

Information in the last statement isn't given in documentation for specific pragmas. Assuming I am nonetheless interested in finding it, presumably I have to look at the source. But where exactly?

A: All pragmas that are implemented by the underlying VFS are executed while parsing.
(But none of the predefined pragmas are implemented in the VFS.)
Otherwise, the easiest way to find out is to look at the generated virtual machine instructions of the pragma.
Some pragmas do not do anything in the VDBE code, which implies that they were completely executed while parsing (and the EXPLAIN does not prevent that):

> EXPLAIN PRAGMA page_size = 16384;
addr  opcode         p1    p2    p3    p4             p5  comment
----  -------------  ----  ----  ----  -------------  --  -------------
0     Init           0     1     0                    00  Start at 1
1     Halt           0     0     0                    00

But note that unknown pragmas are simply ignored:

> EXPLAIN PRAGMA give_me_lots_of_money;
addr  opcode         p1    p2    p3    p4             p5  comment
----  -------------  ----  ----  ----  -------------  --  -------------
0     Init           0     1     0                    00  Start at 1
1     Halt           0     0     0                    00

Many pragmas that simply return a value generate code with the current value at parsing time:

> EXPLAIN PRAGMA page_size;
addr  opcode         p1    p2    p3    p4             p5  comment
----  -------------  ----  ----  ----  -------------  --  -------------
0     Init           0     1     0                    00  Start at 1
1     Int64          0     1     0     16384          00  r[1]=16384
2     ResultRow      1     1     0                    00  output=r[1]
3     Halt           0     0     0                    00

But some pragmas look up the value when they are executed:

> EXPLAIN PRAGMA user_version;
addr  opcode         p1    p2    p3    p4             p5  comment
----  -------------  ----  ----  ----  -------------  --  -------------
0     Init           0     1     0                    00  Start at 1
1     Transaction    0     0     0                    00
2     ReadCookie     0     1     6                    00
3     ResultRow      1     1     0                    00  output=r[1]
4     Halt           0     0     0                    00

And some pragmas can be implemented with VDBE code:

> EXPLAIN PRAGMA foreign_key_check;
addr  opcode         p1    p2    p3    p4             p5  comment
----  -------------  ----  ----  ----  -------------  --  -------------
0     Init           0     15    0                    00  Start at 15
1     OpenRead       0     2     0     2              00  root=2 iDb=0; MyTable
2     String8        0     3     0     MyTable        00  r[3]='MyTable'
3     OpenRead       1     3     0     k(2,,)         00  root=3 iDb=0
4     Rewind         0     14    0                    00
5       Column         0     1     8                    00  r[8]=MyTable.Parent
6       IsNull         8     13    0                    00  if r[8]==NULL goto 13
7       MakeRecord     8     1     7     A              00  r[7]=mkrec(r[8])
8       Found          1     13    7     0              00  key=r[7]
9       Rowid          0     4     0                    00  r[4]=rowid
10      String8        0     5     0     MyTable        00  r[5]='MyTable'
11      Integer        0     6     0                    00  r[6]=0
12      ResultRow      3     4     0                    00  output=r[3..6]
13    Next           0     5     0                    00
14    Halt           0     0     0                    00
15    Transaction    0     0     3     0              01  usesStmtJournal=0
16    Goto           0     1     0                    00

There are pragmas (e.g., default_cache_size) that execute both while parsed and while executed; this is typically for values that are recorded in the database file (such writes can be done only inside a transaction).
So the safest way is to look at the function sqlite3Pragma in the src/pragma.c file.


text:
Q: How does one force a stack to be removed in AWS Powershell I have stack called BasicWebServerStack in AWS from the tutorial. It is currently in a bad state of  ROLLBACK_COMPLETE state and can not be updated. Not that big a deal. Now I would like to be able to remove this stack by running this command
Powershell ...
 Remove-CFNStack -StackName 'BasicWebServerStack' -Force Yes

The problem is, I can not seem to get the proper syntax for the force switch statement

A: The -Force parameter is a switch, not a boolean, and just suppresses confirmation that you really want to perform the delete (it's not passed to the service). So the syntax you want is:
Remove-CFNStack -StackName 'BasicWebServerStack' -Force


text:
Q: Best way to stop Docker build Sometimes it happens to me that I have Dockerfiles that run forever to build. What would be the best way to stop such builds? If I just hit ctrl + C the build will stop but everything that was pulled up to that point will remain and I won't be able to remove it, because the image didn't finished building which means I can't delete the image. Correct?
If anyone is getting into similar situations, please advise.


text:
Q: When will question's last_activity_date be updated? I use Stack Exchange API to get information of questions, I noticed that some comments' last_activity_date is later than the question's last_activity_date, so my question is: when will the question's last_activity_date be updated?
If a comment is submitted, will the question's last_activity_date be updated? If a question is solved, will the question's last_activity_date be updated with the timestamp when it is solved?

A: Per the API "Date Formats" documentation:

*

*
All dates returned by the API are in properties ending _date.

Thus last_activity_date ==> "Last Activity"

*
All dates in the API are in unix epoch time, which is the number of seconds since midnight UTC January 1st, 1970.

Per the faq What can cause a question to be bumped?, a question is "bumped" (it's activity date changes) when:

*

*An answer is added.

*The question or an answer is edited.

*A bounty is started.

*The Community user bumps it.

*A couple of other less common reasons, see the linked question.

Comments and accepting an answer do not change the last activity date.
For example, this linked question currently has an activity date of: 2016-06-09 23:00:59Z.
And the API currently gives us: 1465513259 -- which is the unix time corresponding to 2016-06-09 23:00:59 UTC.


text:
Q: Get Current windows users-at Client side Index.js file is not returning the Client user id- who is accessing the Index.js, instead its returning server user id where Node.js is installed.
Node.js is installed on the windows server 2012
var http = require('http');
var path = require('path');
var userName = process.env['USERPROFILE'].split(path.sep)[2];
var loginId = path.join("domainName",userName);
console.log(loginId);

http.createServer(function (req, res)
{
res.writeHead(200, {'Content-Type': 'text/html'});

res.end('Hello :-) '+userName);
}).listen(3000);

when any user access the index.js file, it should return the userid.

A: to achieve this you can use express framework( easiest way) .
but if you want to stick to nodejs basic structure, then you can use this
request.connection.remoteAddress


text:
Q: HTML pattern vs forbiddenName I am attempting to do password validation with angular and can't see to find much information comparing HTML pattern vs angular forbiddenName. They both essentially accept regex(or a string that is regex).
Can someone please provide some clarity on when to use which and benefits? Thanks!

A: At least for me, I use regex for parsing an forbiddenName for validation, simply because it's directive.
ie: Do I need to block a set of inappropriate user names? => forbiddenName. This can also be done with regex, but I can apply forbiddenName to the div to save some SLOC.
Do I need to strip invalid characters like !@#$%? => regex it up, since I still want the user to be able to input and handle case-by-case as opposed to blocked fully / directly.
It may be personal choice since regex can do both, but forbiddenName saves some lines of boring validaiton code


text:
Q: while building apk showing APP not installed error in android apk I have generated a signed apk and given to client.Next time when i build apk using same signed apk .While installing it is showing as App not installed.Someone please tell me why is it so
Please find my gradle code.The version code was 1 and version name was 1.1 for previous build
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
    applicationId "net.abc.test"
    minSdkVersion 21
    targetSdkVersion 28
    versionCode 2
    versionName "1.1"
    vectorDrawables.useSupportLibrary = true
    multiDexEnabled true
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
configurations {
    all {
        exclude group: 'org.json', module: 'json'
    }
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/ASL2.0'
    exclude 'META-INF/rxjava.properties'
    exclude 'META-INF/proguard/androidx-annotations.pro'
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
 }

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.2.0-alpha02'
implementation 'com.android.support:design:28.0.0'
implementation 'uk.co.chrisjenx:calligraphy:2.3.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'com.miguelcatalan:materialsearchview:1.4.0'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.google.android:flexbox:0.3.0'
implementation 'net.gotev:uploadservice:3.0.3'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'joda-time:joda-time:2.9.9'
implementation 'com.github.mabbas007:TagsEditText:1.0.5'
implementation 'com.google.firebase:firebase-messaging:17.4.0'
implementation 'com.kbeanie:multipicker:1.1.31@aar'
implementation('com.amazonaws:aws-android-sdk-mobile-client:2.6.27') { transitive = true }
implementation 'com.amazonaws:aws-android-sdk-s3:2.7.4'
implementation 'com.amazonaws:aws-android-sdk-cognito:2.6.27'
implementation 'it.michelelacorte.elasticprogressbar:library:1.0.5'
implementation 'com.github.nkzawa:socket.io-client:0.3.0'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'cn.jzvd:jiaozivideoplayer:6.2.12'
implementation 'me.zhanghai.android.materialprogressbar:library:1.1.7'
implementation 'com.facebook.shimmer:shimmer:0.1.0@aar'
implementation 'com.applandeo:material-calendar-view:1.0.1'
implementation 'com.getbase:floatingactionbutton:1.10.1'
implementation 'com.evrencoskun.library:tableview:0.8.8'
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'
implementation 'com.github.yalantis:ucrop:2.2.2-native'
implementation 'com.github.bumptech.glide:glide:4.9.0'
implementation 'com.github.chinalwb:are:0.1.7'
implementation 'com.kyanogen.signatureview:signature-view:1.0'
implementation 'com.google.guava:guava:28.0-jre'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'org.jetbrains:annotations-java5:15.0'
 }

 apply plugin: 'com.google.gms.google-services'

A: There are few reasons why it may be occured:

*

*Previous version code is less than the current. Try to increase it or/and check also version name in app info screen on device

*The signatures don't match each other. Be careful with their data

*Turn off google play protect. May be the problem is somewhere in google services


text:
Q: Polymer 1.0 input validity observer I'm having some trouble watching for changes to input validity in polymer 1.0.  More precisely, an observer function that should fire on any changes to the bound 'invalid' property is not firing as I'd expect it to.  For instance, the function may fire when the control first becomes invalid, but if becomes valid again, the observer function is not being triggered (invalid not becoming false?).  In my current example, I happen to be utilizing Polymer 1.0's gold-email-input element as follows:
Extract from my custom element's local DOM template:
<paper-icon-item>
      <iron-icon icon="social:person"></iron-icon>
      <gold-email-input id="userEmail" bind-value="{{userEmail}}" required auto-validate invalid="{{invalidEmail}}" error-message="Invalid email address"></gold-email-input>
</paper-icon-item>

Extract from my custom element's script declaration:
properties: {
      invalidEmail: {type: Boolean, observer: 'emailValidityChanged'}
}

emailValidityChanged: function(newVal, oldVal) {
      console.log(this.nodeName + " emailValidityChanged observer fired\n");
}

I'm probably missing something straightforward here?  I've also tried observing changes on the userEmail property, and then checking the state of this.$.userEmail.invalid within the observer function, to no avail. It does appear that the invalid property is not being reset when the entry becomes valid. Any suggestions?  Maybe another approach altogether?

A: I think it might be a bug - I've created a new issue to seek clarification with the project owners on expected behavior. Currently, it seems that invalid is set up as a one-way bind from host to child, but I thought it shouldn't be. I can get your snippet working by making changes to paper-input-behavior, paper-input-container and gold-email-input, but until the project owners clarify on what invalid is really used for, don't.
As a workaround, use MutationObservers instead.
<template>
    My Email: {{myEmail}}

    Validity: {{validity}}

    <gold-email-input id="foo" bind-value="{{myEmail}}" required
                      auto-validate error-message="Invalid email address">
    </gold-email-input>
</template>

Working Jsbin: http://jsbin.com/resokidako/edit?html,output
Update 1
Observe the add-on-content node instead.
Updated Jsbin: http://jsbin.com/wivimovufi/1/edit?html,output


text:
Q: filling a cell with the sum of 2 other cells in R I need to fill a cell with the sum of multiple other cells.
For example (in a table called 'a'):
for(i on 1:nrows_data){
   if(a[i,"Column 1"]=="yes"){
      a[i,"Column 4"]=a[i,"Column 2"]+a[i,"Column 3"]
   }
}

Where the values in the referenced cells are all numeric (I checked). If I do this I get this error:

Error in [<-.data.frame(tmp, i, "Alpha", value = numeric(0)) :
  replacement has length zero

Any help would be greatly appreciated. My goal is to get the sum of the two numerical values contained in referenced cells displayed in the desired cell.

A: welcome to SO, its ALWAYS helpful to put a simple reproducible example to help us see your problem.  I made a fake little data set for you.  Here is a solution similar to your format, and an easier alternative that avoids the loop.
## Typically good notation in R is no spaces in variable names
col_1 <- c("yes","no","yes","yes","no")
col_2 <- c(1,4,2,5,6)
col_3 <- c(9,2,8,5,2)
a <- data.frame(col_1, col_2, col_3)

## This works, small fix
for(i in 1:nrow(a)){ ## note "in" instead of "on", and you can calculate nrow() right in here, dont have to do it ahead of time.
   if(a[i,"col_1"]=="yes"){
      a[i,"col_4"]=a[i,"col_2"]+a[i,"col_3"]
   }
}

## this works, easy one-liner
## Into column named col_4, for each row if col_1 = "yes", put col_2+col_4 into that cell, otherwise put NA
a$col_4 <- ifelse(a$col_1=="yes",a$col_2+a$col_3,NA)


text:
Q: Image autosubmitted form inside global form I have a form with several fields and one image.
The thing is that I want the image to be displayed when uploading the photo.
I manage to do it by putting the image inside another form that is autosubmitted when the image is uploaded. It works well.
My problem is that now, I have two separate form (because you can't nest them). One with all data. And one with the image. My html looks like (basically) :
<form>
 <input type="text"/>
 <input type="text"/>
 <input type="text"/>
</form>
<form>
 <input type="file"/>
</form>

Problem is the second form is below the first form and ideally, I want the image to be between the first and the second input of the first form.
My problem is more from a CSS point of view.
I did some workaround by adding a div in the first form and using javascript to reposition the second form in front of the div, using absolute position. It works but it is "crappy"
<form>
 <input type="text"/>

 <input type="text"/>
 <input type="text"/>
</form>
<form>
 <input type="file"/>
</form>

But now I am using responsive design and it is becoming a mess. Is there a way to say "this form must always be positioned on this div" ?"
Demo here : Demo

A: Continuing from the comments above:
function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            document.getElementById('blah').src = e.target.result;
        }

        reader.readAsDataURL(input.files[0]);
    }
}

document.getElementById("imgInp").onchange = function(){
    readURL(this);
};

and the html:
<form id="form1" runat="server">
    <input type='file' id="imgInp" />

</form>

http://jsfiddle.net/jonigiuro/jygT7/
This means you need to go a couple of steps back but should solve the problem at its root (pay attention to ie that might cause some problem, solution provided in the link in the comments)

A: You can use old time trick of hidden frame to handle the image upload, then you don't have to reload the whole page every time user selects an image.
Just inject such HTML anywhere in your page:

To have the auto submitted form use the frame just add such thing to it, nothing more:
<form target="ImageUploadFrame" ...>

Next step, don't use
 but rather just an <image> which is initially hidden:
<input type="text" />

<input type="text" />

Next step is the JavaScript, that will get triggered automatically when the frame is loading the submitted form:
function HandleImagePreview(oFrame) {
    var arrImages = oFrame.contentWindow.document.images;
    if (arrImages.length === 1) {
        var oUploadedImage = arrImages[0];
        var oPreviewImage = document.getElementById("imgPreview");
        oPreviewImage.src = oUploadedImage.src;
        oPreviewImage.style.display = "";
    }
}

Final step is tweaking your server side code handling the submitted image. To have the above work as-is, have the server side code generate such HTML in case of valid image upload:

And the JS will know to extract the image from the frame and show it in the proper place.
You can also handle errors this way e.g. outputting some text instead of image and reading the text, leaving this to you though.


text:
Q: Pseudo-R^2 Measures from QAP Logistic Regression in R (netlogit in sna package) I need to better understand the output from netlogit in the sna package in R. Below you find an example posted online (https://rpubs.com/pjmurphy/338798), which provide a basis for my questions:

*

*The results provide two Pseudo-R^2 Measures, (Dn-Dr)/(Dn-Dr+dfn): 0.4250345 and (Dn-Dr)/Dn: 0.5332452. Which are these? What's the difference? How do I interpret them? Is one better to use than the other?

*What is Total Fraction Correct: 0.875? How do I interpret it?

nlog<-netlogit(Padgett_Business, list(Padgett_Marriage, Padgett_Party),reps=1000)
summary(nlog)

## Network Logit Model
##
## Coefficients:
##             Estimate    Exp(b)    Pr(<=b) Pr(>=b) Pr(>=|b|)
## (intercept) -2.57893819 0.0758545 0.000   1.000   0.000
## x1           2.17792200 8.8279428 0.999   0.001   0.001
## x2          -0.02228475 0.9779617 0.517   0.483   0.972
##
## Goodness of Fit Statistics:
##
## Null deviance: 332.7106 on 240 degrees of freedom
## Residual deviance: 155.2943 on 237 degrees of freedom
## Chi-Squared test of fit improvement:
##   177.4164 on 3 degrees of freedom, p-value 0
## AIC: 161.2943    BIC: 171.7362
## Pseudo-R^2 Measures:
##  (Dn-Dr)/(Dn-Dr+dfn): 0.4250345
##  (Dn-Dr)/Dn: 0.5332452
## Contingency Table (predicted (rows) x actual (cols)):
##
##       0     1
## 0   210    30
## 1     0     0
##
##  Total Fraction Correct: 0.875
##  Fraction Predicted 1s Correct: NaN
##  Fraction Predicted 0s Correct: 0.875
##  False Negative Rate: 1
##  False Positive Rate: 0
##
## Test Diagnostics:
##
##  Null Hypothesis: qap
##  Replications: 1000
##  Distribution Summary:
##
##        (intercept)        x1        x2
## Min      -7.240807 -2.540211 -2.995598
## 1stQ     -6.537942 -0.820302 -1.010798
## Median   -6.266030 -0.328922 -0.103392
## Mean     -6.230127  0.049667 -0.006711
## 3rdQ     -5.947601  0.813030  0.899497
## Max      -4.705737  5.194956  4.716553


text:
Q: remove rows before specific values observed I try to remove rows with value == "no" observed before at least one "yes" value in the column.
DT <- data.frame(id = c(1,1,1,2,2,2,2,2,3,3,3,3,3,3),
                value = c("no","yes","yes","no","no","yes","yes","yes","no","yes","yes","yes","no","no"))

Desired output:
 id value
   1   yes
   1   yes
   2   yes
   2   yes
   2   yes
   3   yes
   3   yes
   3   yes
   3    no
   3    no

Please help???

A: We may do a group by filter
library(dplyr)
DT %>%
   group_by(id) %>%
   filter(cumsum(value == 'yes') > 0) %>%
   ungroup

-output
# A tibble: 10 × 2
      id value
   <dbl> <chr>
 1     1 yes
 2     1 yes
 3     2 yes
 4     2 yes
 5     2 yes
 6     3 yes
 7     3 yes
 8     3 yes
 9     3 no
10     3 no


text:
Q: Return object bound to a dynamic element when label for object is also dynamic I am using CKEditor.  Within my page, the user can dynamically add/remove the element containing the WYSIWYG ckeditor text editor.
CKEDITOR.instances returns an object which contains within it all the ck_editor objects on my page.
When the user clicks the add button, then the following code successfully grabs that element:
CKEDITOR.instances["my_textarea_0_body"]

The issue is when the user clicks delete to remove that element, and then reclicks add.  I now want to grab that new ckeditor element on the page.  However, now I need to grab it with this:
CKEDITOR.instances["my_textarea_1_body"]

Notice that the number changed.  So, the user is able to toggle the add/remove of this element any number of times.  Example: if they did it 100 times I would need to have a way to grab that object like so:
CKEDITOR.instances["my_textarea_100_body"]

The problem is that I never know what that number will be.  That number is vital for me to create the string in order to grab the appropriate object.
Question: How can I grab this dynamically labeled object that is contained within the CKEDITOR.instances object?  I know that my desired object will always be the LAST object appended within that CKEDITOR.instances object.

A: I assume that CKEDITOR.instancess a kind of a map (dictionary), so you can get all key names by Object.keys(). And then select the last/first/ or n-th instance name.
var mapping_length = Object.keys(CKEDITOR.instances).length;
var object_label   = Object.keys(CKEDITOR.instances)[mapping_length - 1];
CKEDITOR.instances[object_label];

This will return the desired object from within that dictionary object.

A: Regex indeed is your friend here. /^CKEDITOR\.instances\["my_textarea_\d+_body"\]$/.test(str) should get the job done. (if you copy and paste any of your initial examples to test, it will fail however since you've got an angled quote illegal character in there)

console.log(/^CKEDITOR\.instances\["my_textarea_\d+_body"\]$/.test('CKEDITOR.instances["my_textarea_0_body"]'))

I think I understand what you're getting at though - you know the vague structure of the key, but not exactly what it will be when you're trying to retrieve it. In that case, you'd want to search through the keys of the CKEDITOR.instances object for any that match that pattern. So, let matchingKeys = Object.keys(CKEDITOR.instances).filter(key => /^my_textarea_\d+_body$/.test(key)). That will return a set of all keys that match that pattern.

A: You can create a helper function which checks for a regex match. The regex for that field should be:
my_textarea_\d+_body

Then you can modify/add the new object key to instances


text:
Q: How to Command-X files on OS X El Capitan? I noticed that Command-X (cut and paste) is greyed out on finder in El Capitan.
Is there any way to get it back?
EDIT: WITHOUT Command-Option-V.
If possible, way to map command-option-v to command-x would be great....

A: Just copy the file as normal with command+c and then when you past use
command+option+v and it will paste the file, and also cut it from its original location


text:
Q: Different textbox values need to be seperated Random number = new Random();
int num = number.Next(0, 11);
textBox2.Text += num.ToString();

When the random numbers are being added to the textbox they are being connected, I need them to be seperate numbers. I tried fixing it by inserting a blank space after every button click so that it would register as different numbers but its still connecting the 2 numbers.
Later when I add the 2 numbers they register as one, this is the code i use for the addition of the 2 textboxes
decimal a, b;
a = Decimal.Parse(textBox1.Text);
b = Decimal.Parse(textBox2.Text);
textBox3.Text = (a + b).ToString();

A: private void btnShowNumbers_Click(object sender, EventArgs e)
        {
            Random number = new Random();
            int num = number.Next(0, 11);
            int c = 0;
            textBox2.Text += ($" {num.ToString()} 0169"); // ads random number and space

            decimal a, b;
            a = Decimal.Parse(textBox1.Text);
            b = Decimal.Parse(textBox2.Text); // cant parse if a decimal has " "

            string nr = b.ToString();

            label1.Text = b.ToString() ;

            lblContains.Text = nr.Replace("0169", " ");

        }
    }
}

Maybe converting decimal to string and then showing string and replacing (in this example) 0169 to space?
output

A: They are "being connected" because textBox2 can have only one value, and that value is a string.  Everything you do is either writing to or reading from that one string value.
So if you do this:
textBox2.Text = "1";

And then this:
textBox2.Text += "2";

Then textBox2 doesn't have two values, 1 and 2.  It has one value, "12".

You could create your own data serialization standard for this simple case.  For example, you mentioned including a blank space to separate the values.  In that case your immediate goal is for the value to be "1 2".  Each time you append to the text value, de-serialize what's already there and add to that data and then re-serialize it.  For example:
// generate your random number
Random number = new Random();
int num = number.Next(0, 11);

// de-serialize the text into an array of numbers
var values = textBox2.Text.Split(' ').ToList();

// add your new value
values.Add(num.ToString());

// re-serialize the data back to the text box
textBox2.Text = string.Join(' ', values);

Later, when you want to get that value to perform calculations, you would again de-serialize it.  For example:
var b = textBox2.Text.Split(' ').Select(x => Decimal.Parse(x));

Since b is multiple values then clearly you can't just add it to a value.  If your intent is to add all of them then you can add their sum:
textBox3.Text = (a + b.Sum()).ToString();


text:
Q: Create a transcation on Ethereum (Smart Contract) I am new in Ethereum. I am trying to create a DAPP using Smart Contract, I have created a function to create a transaction on Ethereum. How I did was I created a defaultGas with the coinBase to pass in as parameters. When I hit the button the on the UI, and it doesn't not prompt me the MetaMask, and the transaction was created successfully. I am just wondering this is the right way to create a transaction without prompting users the MetaMask to manipulate the Gas?
Please advice.
Cheers


text:
Q: Select query which sums two columns and want to use the result as a criteria for the select I'm using Oracle SQL Developer.
I want to multiply the values of two columns, price and quantity, and then use the sum as a criteria. The user needs to be able to determine what the minimum value of the sum field is, and the query should return all results where the sum of those two columns is higher than their specified minimum.
My query right now looks like this:
SELECT PROD_PRICE, PROD_QUANTITY, PROD_PRICE * PROD_QUANTITY AS "PROD_AMOUNT"
FROM PRODUCT
WHERE PROD_AMOUNT >= &PROD_AMOUNT

The Error message I get is that "PROD_AMOUNT" is an invalid identifier.
Thank you so much!

A: You can't use alias of computed columns in where clause you need to repeat the expression in order to perform filter using computed value
SELECT PROD_PRICE,
       PROD_QUANTITY,
       PROD_PRICE * PROD_QUANTITY AS "PROD_AMOUNT"
FROM PRODUCT
WHERE (PROD_PRICE * PROD_QUANTITY)>= &PROD_AMOUNT

A: any sql ex. oracle, MySQL , SQLite, SQLServer ... etc never use an alias in filer conditions (where or having)
SELECT PROD_PRICE,
   PROD_QUANTITY,
   PROD_PRICE * PROD_QUANTITY AS "PROD_AMOUNT"
FROM PRODUCT
WHERE (PROD_PRICE * PROD_QUANTITY)>= &PROD_AMOUNT


text:
Q: Парсинг JSON объекта JAVA Приходит сразу объект, я не знаю ключей.
{
"Ключ": Значение,
"Ключ2": Значение,
"Ключ3": Значение
}

Я не понимаю, как его парсить, помогите тугодуму :)
Мне нужно вывести и ключ и значение.

A: JSON может содержать значения и коллекции значений. Алгоритм парсинга в упрощенном виде такой:

*

*Берем следующий элемент

*Если он не коллекция - выводим его имя и значение

*Если коллекция - берем его вложенный первый элемент и повторяем с п. 1

Пример JSON с коллекцией:
{
"name" : "abc" ,
"email id " : ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]
}

JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
Map<String, Object> map = new HashMap<String, Object>();

// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});

System.out.println(map);

где json - это File, InputStream, Reader или String.

A: Создаете класс с ключом, пишите геттеры - сеттеры.
Помещаете их в лис и гоняете его через GSON.
Он будет сам парсить из распарсивать это в json из с json'a.


text:
Q: How to reuse the encoding part of an autoencoder in a new graph in Tensorflow? I can imagine two methods, but I don't know if there is a better one. The two methods that I imagine are:

*

*In the same session, after training the autoencoder, just build a new graph using the encoding subgraph of the autoencoder as the input

*After training the autoencoder, save the trained weights. This way, you don't have to train the autoencoder and the new other network in the same session. (kind of a variant of method 1)

A: The easiest think for you to do is to run the encoder as usual (training mode) but not supplying the sess.run()-function with the optimizer (which affects the weights of the trained encoder. That way you can reuse the encoder without the need to construct a second graph or plus you have the advantage, that you can already reused during training!


text:
Q: ANTLR Tool version 4.7.1 used for code generation does not match the current runtime version 4.5.3 Im working on an Android App, currently using DSL and some libraries, suddenly the build gave me this error.

Task :app:kaptDebugKotlin FAILED
ANTLR Tool version 4.7.1 used for code generation does not match the current runtime version 4.5.3ANTLR Runtime version 4.7.1 used for parser compilation does not match the current runtime version 4.5.3
FAILURE: Build failed with an exception.

What went wrong:

Execution failed for task ':app:kaptDebugKotlin'.
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
java.lang.reflect.InvocationTargetException (no error message)

i've been searching but with no success...
If you wanna see the issue you can clone the project. Project GITHUB
Im using Android Studio Canary 4.1.

A: So the solution was from the build.gradle
basically the import from ROOM was this
import(Room.compiler)

so i changed to this, and the issue was solved :)
kapt(Room.compiler)

A: Inside the build.gradle(Module:app) copypaste this code
configurations.all() {
        resolutionStrategy.force "org.antlr:antlr4-runtime:4.5.3"
        resolutionStrategy.force "org.antlr:antlr4-tool:4.5.3"
    }

A: For anyone still experiencing this issue, just update your Room to the latest version:
androidx.room:room-runtime:2.3.0-alpha04
androidx.room:room-compiler:2.3.0-alpha04

It's due to this bug: https://issuetracker.google.com/issues/155215201

A: The problem was fixed for me by changing this.
from:
implementation "androidx.room:room-runtime:$depVersion"
implementation "androidx.room:room-compiler:$depVersion"

to:
implementation "androidx.room:room-runtime:$depVersion"
annotationProcessor "androidx.room:room-compiler:$depVersion"

A: Removing suspend keyword from queries in DAO interface, solved my problem

A: I got similar error. I have all files in Java and I changed few files to Kotlin. Then this issue showed up.
I have a function in a Java file accessing static function in a Kotlin file. That's the point where the app crashed.
Code in Kotlin file:
companion object{
    @JvmStatic
    fun myStaticFunction(){
        // body of the static function
    }
}

I added the annotation @JvmStatic(see the above code) to the function and the error got resolved.
This is a very specific scenario in which this crash occurs and may not be applicable to all.

A: At lease for me, the root cause of this problem/error is because of the data binding not being handled properly.
Currently, Android Studio does not have a mechanism to show error message for unreferenced variables in .xml file.
For example,
In MyViewModel.kt, If I have a property name as,
var email

and you are mapping this property in xml as,
@={model.errEmail}

instead of @={model.email}
You get to see this error.
If you see this error, just go to layout xml file and check the binding names/mappings and correct it.

A: Had a similar issue. I was trying to implement bindingAdapters to a TextView of a ViewHolder in my recyclerview
I failed to implement a bindingAdapter for a TextView after adding the adding a unique app attribute
app:tDate="@{transaction}
in the xml layout file for my recylerView item.
<TextView
        android:id="@+id/trans_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/trans_category"
        app:layout_constraintTop_toTopOf="parent"
        app:tDate="@{transaction}"/>

Solved it by well.. implementing it.
@BindingAdapter("tDate")
fun TextView.setValue(item: Transactions){
    text = item.date.toString()
}


text:
Q: Print RichTextBox text that is longer than one page? I've got the following code, and looked at as many similar questions on here and google, but all solutions have the same flaw, when the content in the RTB is longer than one page, or more than one or two lines, it prints an infinite number of pages. What should be changed to only print the correct number of pages?
private void PrintButton_Click(object sender, EventArgs e)
    {
        if (MainTabSet.TabCount > 0)
        {
            RichTextBox textbox = (RichTextBox)MainTabSet.SelectedTab.Controls["TabTextBox"];
            PrintDocument docToPrint = new PrintDocument();
            docToPrint.PrintPage += new PrintPageEventHandler(PrintPageHandler);
            docToPrint.DocumentName = MainTabSet.SelectedTab.Text;
            PrintDialog.Document = docToPrint;

            if(PrintDialog.ShowDialog() == DialogResult.OK)
            {
                docToPrint.Print();
            }

        }
    }

    private void PrintPageHandler(object sender, PrintPageEventArgs e)
    {
        if (MainTabSet.TabCount > 0)
        {
            RichTextBox textbox = (RichTextBox)MainTabSet.SelectedTab.Controls["TabTextBox"];
            StringReader reader = new StringReader(textbox.Text);
            float linesPerPage = 0.0f;
            float yPosition = 0.0f;
            int count = 0;
            float leftMargin = e.MarginBounds.Left;
            float rightMargin = e.MarginBounds.Right;
            float topMargin = e.MarginBounds.Top;
            string line = null;
            Font printFont = textbox.Font; //maybe do selection font
            SolidBrush printBrush = new SolidBrush(textbox.ForeColor);//Maybe do selection color
            int charPos = 0;
            int xPosition = (int)leftMargin;

            linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);

            while (count < linesPerPage && ((line = reader.ReadLine()) != null))
            {
                xPosition = (int)leftMargin;
                yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
                count++;
                for (int i = 0; i < line.Length; i++)
                {
                    textbox.Select(charPos, 1);
                    if ((xPosition + ((int)e.Graphics.MeasureString(textbox.SelectedText, textbox.SelectionFont).Width)) > rightMargin)
                    {
                        count++;
                        if (!(count < linesPerPage))
                        {
                            break;
                        }
                        xPosition = (int)leftMargin;
                        yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
                    }
                    printBrush = new SolidBrush(textbox.SelectionColor);
                    e.Graphics.DrawString(textbox.SelectedText, textbox.SelectionFont, printBrush, new PointF(xPosition, yPosition));
                    xPosition += ((int)e.Graphics.MeasureString(textbox.SelectedText, textbox.SelectionFont).Width);
                    charPos++;
                }
            }

            if (line != null)
            {
                e.HasMorePages = true;
            }
            else
            {
                e.HasMorePages = false;
                printBrush.Dispose();
            }

        }
    }

Thanks in advance for the help.
//Nodnarb3

A: Add this code in PrintPageHandler
private void PrintPageHandler(object sender, PrintPageEventArgs e)
{

    int charactersOnPage = 0;
    int linesPerPage = 0;

    // Sets the value of charactersOnPage to the number of characters
    // of stringToPrint that will fit within the bounds of the page.
    e.Graphics.MeasureString(stringToPrint, font1,
        e.MarginBounds.Size, StringFormat.GenericTypographic,
        out charactersOnPage, out linesPerPage);

    // Draws the string within the bounds of the page
    e.Graphics.DrawString(stringToPrint, font1, Brushes.Black,
        e.MarginBounds, StringFormat.GenericTypographic);

    // Remove the portion of the string that has been printed.
    stringToPrint = stringToPrint.Substring(charactersOnPage);

    // Check to see if more pages are to be printed.
    e.HasMorePages = (stringToPrint.Length > 0);
}

And the PrintButton Code
   private void PrintButton_Click(object sender, EventArgs e)
    {
        stringToPrint = tabsProperties[tabsProperties.IndexOf(new TabProperties(this.tabControl1.SelectedIndex))].TabHtml;

        printDialog1.ShowDialog();
        printDocument1.Print();

    }


text:
Q: Avoid method being recalled before previous execution finished I use a webservice to post data to an external database.
The webservice usually takes approximately 2-6 seconds to finish execution.
In the same method I also insert the record in my own database.
Now, to avoid inserting duplicates I check before I use the method, if the record already exists in my own database.
But what happens is that the webservice sometimes keeps hanging for a few minutes and then inserts the record, and when the user refreshes his browser, or restarts the method at this point, I get duplicate records afterwards.
Could anyone please help me out how I can avoid duplicates in my databases cause this method gets called twice by refreshing/reloading/reclicking?
Is it possible to make this method unique per user so I know it is still executing/waiting for response?

A: I would fix the problem directly in the database instead of the source. You could easily set an database trigger (depends on your DBMS like MySQL, MSSQL) for the INSERT statement.
A good guide to database triggers would be:
http://www.sqlteam.com/article/an-introduction-to-triggers-part-i


text:
Q: get URL Parameter from Laravel blade to controller I already have provided my blade with a link that passes a parameter.
2]) !!}">{{$value}}

The only problem I have now is how to get the parameter to the controller.
I do it like this
public function search(Request $request){
     $sid = $request->get('id');
}

But I'm not getting any value from $sid. How should I do it?
sorry I forgot to mention that there is already a route set.
Route::post('search', 'Search@search')->name('search');

A: because link are not post method .. this would work
2]) !!}">{{$value}}

then in your route
Route::get('search/{id}',BlahblahController@search);

in your controller
public function search(Request $request, $id)
{
    $id = $id;
}

A: if your routes /youroute/{id} this scheme then you need to pass one more param to your method in Controller like this
public function search(Request $request,$id){
 $sid = $id;
}

A: your trying to pass url bind parameter to function . Not passing query string get parameter . so you need to access the id like this
Method 1 :
Controller :
public function search(Request $request,$id){ $sid = $id; }

Your route should be like this
Route :
Route::get('search/{id}',BlahblahController@search);

Method 2 :
Or if don't want to bind parameter to url and want just $_GET parameter like url/?id=1
You may use it like this
Controller :
public function search(Request $request){
     $sid = $request->get('id');
}

Route :
 Route::get('search',BlahblahController@search);


text:
Q: Reset style properties of an HTML element to stylesheet-defined defaults? CSS code:
p.myparagraph {
  color: yellow;
}

Assume that I've turned the color of <p> elements that use the myparagraph class to red. Is there a way to reset all style properties of paragraphs using this class (not limited to color) to their CSS-defined defaults?

A: Assuming you've been using elem.style (where elem is your element's DOM object), try elem.style.cssText="".

A: If you are using jQuery, you could toggle the class you want to remove with toggleClass.
 $("p").click(function () {
      $(this).toggleClass("highlight");
    });

Check more of that here: http://docs.jquery.com/Attributes/toggleClass#class

A: The following code will modify and class with the name borderParra
<script type="text/javascript">
            $(document).ready(function() {
                $(".borderParra").focus(function() {
                    $(this).addClass("blueBorder");
                    $(this).select();
                });
                $(".borderParra").blur(function() {
                    $(this).removeClass("blueBorder");
                });
            });
        </script>

where the styles are
.yellowBorder{ border:1px solid #FC3;}
.blueBorder{ border:1px solid #014165;}

A: No, you would have to define all the properties individually. CSS knows to apply the rule (and in what order), but the rule is a whitelist of properties to change, not a blacklist of things to undo.
May I ask why you want this?

A: There may be a way to inspect the css declarations if you enumerate the objects in the HEAD and try to find all the rules.  But I would consider one of two different approaches:

*

*Keep track of the original colour before you change it

*Don't change the colour of the elements, but instead toggle css classes on those objects.  Add and remove classes and have CSS rules which affect the new classes.  This allows you to easily override "default" styles and then un-override at will.  With JQuery this can be done using toggleClass().


text:
Q: Join based on condition? Is it possible to condition a join based on a condition?
For example, if @DoJoin is true then do the inner join. It would replace something like this:
declare @DoJoin bit = 1

if @DoJoin = 1
BEGIN
    select T.* from T inner join L on T.col = L.col
END
ELSE
BEGIN
    select T.* from T
END

A: If I'm understanding how your data might work, you probably don't need a join at all, because your just using the join as a filter. So if that's the case, you can just do this, and just have one query.
select T.* from T
where @DoJoin = 0 or exists(SELECT * FROM L where L.col = T.col)

A: DECLARE @DoJoin BIT = 1

SELECT
    T.*
FROM
    T LEFT JOIN L ON T.col = L.col
WHERE
    --Optional INNER/LEFT JOIN
    (
        --LEFT JOIN
        @DoJoin = 0
        OR
        --INNER JOIN
        (
            -- only return rows from T where they have a record in L
            @DoJoin = 1
            AND
            L.col IS NOT NULL
        )
    )


text:
Q: Uninstalled snapd with core system apps After installing Ubuntu 18.04 I noticed high bandwidth traffic with the process snapd and since I don't use snap apps I decided to remove snap.
I used this command
$ sudo apt purge snapd ubuntu-core-launcher squashfs-tools
and this is the output
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'ubuntu-core-launcher' is not installed, so not removed
The following packages will be REMOVED:
  gnome-software-plugin-snap* snapd* squashfs-tools*
0 upgraded, 0 newly installed, 3 to remove and 0 not upgraded.
After this operation, 57.4 MB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 317306 files and directories currently installed.)
Removing gnome-software-plugin-snap (3.28.1-0ubuntu4) ...
Removing snapd (2.32.5+18.04) ...
Removing squashfs-tools (1:4.3-6) ...
Processing triggers for man-db (2.8.3-2) ...
(Reading database ... 317244 files and directories currently installed.)
Purging configuration files for snapd (2.32.5+18.04) ...
Stopping snap-communitheme-97.mount
Stopping unit snap-communitheme-97.mount
Waiting until unit snap-communitheme-97.mount is stopped [attempt 1]
snap-communitheme-97.mount is stopped.
Removing snap communitheme and revision 97
Removing snap-communitheme-97.mount
Stopping snap-core-4486.mount
Stopping unit snap-core-4486.mount
Waiting until unit snap-core-4486.mount is stopped [attempt 1]
snap-core-4486.mount is stopped.
Removing snap core and revision 4486
Removing snap-core-4486.mount
Stopping snap-gnome\x2d3\x2d26\x2d1604-59.mount
Stopping unit snap-gnome\x2d3\x2d26\x2d1604-59.mount
Waiting until unit snap-gnome\x2d3\x2d26\x2d1604-59.mount is stopped [attempt 1]
snap-gnome\x2d3\x2d26\x2d1604-59.mount is stopped.
Removing snap gnome-3-26-1604 and revision 59
Removing snap-gnome\x2d3\x2d26\x2d1604-59.mount
Stopping snap-gnome\x2dcalculator-154.mount
Stopping unit snap-gnome\x2dcalculator-154.mount
Waiting until unit snap-gnome\x2dcalculator-154.mount is stopped [attempt 1]
snap-gnome\x2dcalculator-154.mount is stopped.
Removing snap gnome-calculator and revision 154
Removing snap-gnome\x2dcalculator-154.mount
Stopping snap-gnome\x2dcharacters-69.mount
Stopping unit snap-gnome\x2dcharacters-69.mount
Waiting until unit snap-gnome\x2dcharacters-69.mount is stopped [attempt 1]
snap-gnome\x2dcharacters-69.mount is stopped.
Removing snap gnome-characters and revision 69
Removing snap-gnome\x2dcharacters-69.mount
Stopping snap-gnome\x2dlogs-25.mount
Stopping unit snap-gnome\x2dlogs-25.mount
Waiting until unit snap-gnome\x2dlogs-25.mount is stopped [attempt 1]
snap-gnome\x2dlogs-25.mount is stopped.
Removing snap gnome-logs and revision 25
Removing snap-gnome\x2dlogs-25.mount
Stopping snap-gnome\x2dsystem\x2dmonitor-36.mount
Stopping unit snap-gnome\x2dsystem\x2dmonitor-36.mount
Waiting until unit snap-gnome\x2dsystem\x2dmonitor-36.mount is stopped [attempt 1]
snap-gnome\x2dsystem\x2dmonitor-36.mount is stopped.
Removing snap gnome-system-monitor and revision 36
Removing snap-gnome\x2dsystem\x2dmonitor-36.mount
Stopping snap-spotify-x1.mount
Stopping unit snap-spotify-x1.mount
Waiting until unit snap-spotify-x1.mount is stopped [attempt 1]
snap-spotify-x1.mount is stopped.
Removing snap spotify and revision x1
Removing snap-spotify-x1.mount
Final directory cleanup
Discarding preserved snap namespaces
umount: /run/snapd/ns/vlc.mnt: not mounted.
Removing extra snap-confine apparmor rules
Removing snapd cache
Removing snapd state

I noticed that it removed core system apps. How can I undo the process again to restore snap and those apps again.
thanks in advance

A: If you erroneously uninstall core packages on an Ubuntu system it's possible to put the deb packages back simply with one command:-
Note: This presumes you previously installed the stock Ubuntu product, and not one of the other flavours.
sudo apt install ubuntu-desktop^

Once snapd is re-installed (which it should be with the above command), you can re-install the snaps which come pre-installed with:-
sudo snap install gnome-calculator
sudo snap install gnome-characters
sudo snap install gnome-logs
sudo snap install gnome-system-monitor

Simply repeat this process, or use the graphical Ubuntu Software for the additional snaps such as communititheme, vlc and others.


text:
Q: Preferred approach for storing a reference to a file handle/DB handle, etc...? In the Learn You A Haskell book, there is a todo example that uses the do notation to assign the tempName and tempHandle:
do
    ...
    (tempName, tempHandle) <- openTempFile "." "temp"

Which means that tempName and tempHandle are accessible throughout the function, that means you can do whatever you like in between the openTempFile and having to hClose at the end. However, as do notation is apparently syntactic sugar for >>= I'm trying to transform the do into bind, and finding it difficult to maintain a reference to tempHandle.
With my limited understanding of Haskell, I see a couple of options:

*

*Store the tempHandle in the where clause so that it's accessible from the function;

*Pass the tempHandle reference in the >>= alongside other data that I need in each step of the bind: (return ("Transformed Data", tempHandle)!?).

How would you do this? Am I approaching this from the wrong angle?

Edit: How would I keep a reference to handle if you transformed the do notation to >>= in the following example:
main = do
    handle <- openFile "name.txt" (WriteMode)
    putStrLn "Enter your name: "
    name <- getLine
    hPutStr handle name
    hClose handle

When transformed to >>= how would I reference handle?
main =
    openFile "name.txt" WriteMode >>
    putStrLn "Enter your name: " >>
    getLine >>=
    (\name -> hPutStr handle?? name) >>
    hClose handle??

A: do
  (tempName, tempHandle) <- openTempFile "." "temp"
  ...

is the same as
openTempFile "." "temp" >>= \(tempName, tempHandle) ->
...

The second one is much harder to read, why would you want to use it ?
To complete your example :
main =
    openFile "name.txt" WriteMode >>= \handle ->
    putStrLn "Enter your name: " >>
    getLine >>=
    (\name -> hPutStr handle name) >>
    hClose handle

A: The direct way to de-sugar the do-notation would be:
main =
    openFile "name.txt" (WriteMode) >>= \handle ->
    putStrLn "Enter your name: " >>
    getLine >>= \name ->
    hPutStr handle name >>
    hClose handle

Note that the whole thing after \handle -> is part of the same function body so handle is in scope for all the following expressions.


text:
Q: parse json data into table with JAVASCRIPT ajax .net I want to parse json data into table
in the vb I write
Inherits System.Web.UI.Page

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    Dim conn As New SqlConnection()
    Dim cmd As New SqlCommand()
    conn.ConnectionString = "server=AIONSTUDENT01\SQLEXPRESS;Database=TestDB;User ID=sa;Password=1234;Trusted_Connection=False;"
    conn.Open()
    cmd.Connection = conn
    cmd = New SqlCommand("select WA01_CNTY_CD,WA01_CNTY_NM_C from WA01", conn)

    Dim da As New SqlDataAdapter(cmd)
    Dim ds As New DataSet
    Dim jason As String = ""
    Dim D As String = ""

    da.Fill(ds, "mytable")

    If ds.Tables("mytable").Rows.Count > 0 Then
        For Each dr As DataRow In ds.Tables("mytable").Rows
            Dim a As String = dr("WA01_CNTY_CD")
            Dim b As String = dr("WA01_CNTY_NM_C")

            jason += "{" + """Code"":""" + a.ToString + """," + """countryname"":""" + b.ToString + """}" + ","

                'C += a + ","
                'D += b + ","
            Next

        End If

        Dim jason2 As String = jason.Remove(jason.Length - 1)
        Dim jason3 As String = "[" + jason2 + "]"

        If "" & Request("AJAX") = "1" Then
            Response.Write(jason3)
            Response.End()
            conn.Close()
        End If
    End Sub

the output looks is
[{"Code":"CN","countryname":"中國"},{"Code":"JP","countryname":"日本"},
 {"Code":"KR","countryname":"韓國"},{"Code":"TW","countryname":"台灣"},
 {"Code":"US","countryname":"美國"},{"Code":"CL","countryname":"阿囉哈"},
 {"Code":"ML","countryname":"馬來西亞"}]

and then I  have trouble
<title></title>

        code
        countryname

<button id="button1">Ajax</button>

I click the button but nothing happened.
I learn them by myself and my English is poor, so I think there are some ridiculous mistakes .
thank for your assistance

A: You should not append element in loop. Its a bad practice.
You can try something like this:

// Create html string for data received
function createHtmlString(data){
  var result = "";
  data.forEach(function(item){
    result += "
";
    result += "" + item.Code + "	";
    result += "" + item.countryname + "	";
    result += "
"
  });

  return result;
}

function getData(){
  var data = [{"Code":"CN","countryname":"中國"},{"Code":"JP","countryname":"日本"},
 {"Code":"KR","countryname":"韓國"},{"Code":"TW","countryname":"台灣"},
 {"Code":"US","countryname":"美國"},{"Code":"CL","countryname":"阿囉哈"},
 {"Code":"ML","countryname":"馬來西亞"}];

  return data;
}

function appendElement(){
  var data = getData();
  var html = createHtmlString(data);

  // Perform bulk operation
  $("#tbl").html(html);
}

appendElement();
td{
  border:1px solid gray;
}


text:
Q: What does "*RECURSION*" mean when printing $GLOBALS? When I print $GLOBALS using this code:
<?php print_r($GLOBALS); ?>

I get this output:
Array ( [_GET] => Array ( ) [_POST] => Array ( ) [_COOKIE] => Array ( ) [_FILES] => Array ( ) [GLOBALS] => Array *RECURSION* )
What does "*RECURSION*" mean in this case, and why are $_SERVER, $_REQUEST, etc. not printed as well?

A: See this part of PHP Manual:

Keep in mind that $GLOBALS is, itself, a global variable. So code like this won't work:
<?php
    print '$GLOBALS = ' . var_export($GLOBALS, true) . "\n";
?>

This results in the error message: "Nesting level too deep - recursive dependency?"

You already have retrieved the whole list - you just cannot display part of it (the one containing a recursion, because you would have timeout rather than anything meaningful).
When it comes to $_REQUEST, it is a derivative from $_GET, $_POST and $_COOKIE, so its content is redundant.
EDIT:  There is an old bug / feature, that seems to be populating $GLOBALS with $_SERVER and $_REQUEST when they are accessed. So try to access $_REQUEST and hope it helps. Anyway, it can be found in $GLOBALS after that: ideone.com/CGetH

A: $GLOBALS contains itself as an array. In the PHP reference you can find the definition of $GLOBALS:

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

Therefore, it has to contain also itself, which leads to a recursion.
The other arrays are probably just empty, since nothing else has happened in your script.
There is an old joke about recursion: "To understand recursion, you must understand recursion".
BTW: It outputs _SERVER on my computer.