text:
Q: Error: _util_useScrollPosition__WEBPACK_IMPORTED_MODULE_3___default(...) is not a function "use client";
import { useEffect, useState } from "react";

export const useScrollPosition = () => {
  const [scrollPosition, setScrollPosition] = useState(0);

  useEffect(() => {
    const updatePosition = () => {
      setScrollPosition(window.pageYOffset);
    };

    window.addEventListener("scroll", updatePosition);

    updatePosition();

    return () => window.removeEventListener("scroll", updatePosition);
  }, []);

  return scrollPosition;
};

export default useScrollPosition;```

im importing this in another file

```ts
import useScrollPosition from "../app/hooks/useScrollPosition";

export function Header() {
  const scrollPosition = useScrollPosition();
  console.log(scrollPosition);```

im getting the same error
**Error: **_app_hooks_useScrollPosition__WEBPACK_IMPORTED_MODULE_3___default(...) is not a function

i changed the file name to tsx, ts, js and its not working and the import file is correct when I hover on it it goes to the right file. I tested this code in my other project works fine.


text:
Q: Biggest Rectangle within one color I struggle to find a solution to the following problem :
I used opencv to mark all connected white pixels with a unique label.
Now i got a group of those elements.
Those objects often are 90% rectangular but most of the time contain some extra lines and stuff.
Im searching for a algorithm which does thr following :
-get biggest Rectangle out of image(within the same label)
- fast performance
-maybe even filter,  larget rectangle which contains at least xx% Pixels with the same label
Maybe someone can help me
Thanks a lot
Edit: Example Pictures(in this case fo licence plate location):
my desired output of the algorithm would be the rectangle of the plate(and of curse all other rectangles in the image, im gonna filter them later)
Important the rectangles may be rotated !

A: My suggestion

*

*make sure to fill small holes either by blob analysis or mathematical morphology;

*compute the distance map in the white areas;

*binarize the distance map with a threshold equal to the half plate height.
The rectangles will appear as line segments long as the plate width minus the plate height. You may locate them by fitting rotated rectangular bounding boxes; they must have a large aspect ratio.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transmit raw vertex information to XTK? We're using XTK to display data processed and created on a server.  In our particular case, it's a parallel isocontouring application.  As it currently stands we're converting to the (textual) VTK format and passing the entire (imaginary) VTK file over the wire to the client, where XTK renders it.  This provides some substantial overhead, as the text format outweighs in the in-memory format by a considerably amount.
Is there a recommended mechanism available for transmitting binary data directly, either through an alternate format that is well-described or by constructing XTK primitives inside the JavaScript code itself?

A: It should be supported to parse an X.object from JSON. So you could generate the JSON on the serverside and use the X.object(jsonobject) copy constructor to safe down cast it. This should also give the advantage that the objects can be 'webgl-ready' and do not require any clientside parsing which should result in instant loading.
I was planning to play with that myself soon but if you get anything to work, please let us know.
Just have in mind that you need to match the X.object structure even in JSON. The best way to see what is expected by xtk is to JSON.stringify a webgl-ready X.object.

A: XMLHTTPRequest, in its second specification (the last one), allows trans-domain http requests (but you must have the control of the php header on the server side).
In addition it allows to sent ArrayBuffer, or Blobs or Documents (look here). And then on the client side you can write your own parser for that blob or (I think it fits more in you case) that BinaryBuffer using binary buffer views (see doc here). However XMLHTTPRequest is from client to server, but look HTML5 WebSocket, it seems it can transfert binaryArrays too (they say it here : ).
In every case you will need a parser to transform binary to string or to X.object at the client side.
I wish it helped you.


text:
Q: Copying MySQL table to another table with no missing new changes I would like to recreate/copy a MySQL table (a actual new ibd file) - and most of the suggestions recommends the following :
CREATE TABLE mytbcopy LIKE mytb;
INSERT INTO mytbcopy SELECT * FROM mytb;

The suggestion works well - but from my understanding (correct me if I'm wrong), it does not insert/update records in the new table during the period of copying/recreating.
Example : During the copying, if record #45 is already inserted into the new table, and there was an update on record #45 on the original table - it won't be replicated over
Is there another way to ensure that after the full copying of data over, the data on the new table will be in the most updated state? I'm not sure using TRIGGERS is the solution for this.

A: The way you provide is a very simple and basic level's solution to create a backup copy of the table. Once copy done and someone made a change into the main table backup won't be updated with original tables so you have to do it again.
As far I understand you want to keep backup of your whole database which should be up to date with all changes being done till now.
To make this you can create a master-slave replica of the database, which will work as a master-slave database. Changes being done in the master will automatically reflect in the slave database.
Thank you.

A: Don't re-invent the wheel.  pt-online-query-digest takes care of all of that.  It does require a TRIGGER to keep the new table up to date, as you suggested.


text:
Q: HttpEroor 500 Backend Error and HttpError 403 using DoubleClick Bid Manager API in python I need to create and run some queries as well as get the last reports via DoubleClick Bid Manager API in python, after following the example get_last_report.py in Github step by step, I always got an HttpError 500, like:
Traceback (most recent call last):
  File "dbm.py", line 202, in <module>
    main(util.setup(args), args.output_directory, QUERY_ID, args.report_window)
  File "dbm.py", line 154, in main
    response = doubleclick_bid_manager.queries().listqueries().execute()
  File "//anaconda3/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "//anaconda3/lib/python3.7/site-packages/googleapiclient/http.py", line 856, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 500 when requesting https://www.googleapis.com/doubleclickbidmanager/v1.1/queries?alt=json returned "Backend Error">

Also when I tried to run the example download_line_items.py, I got another error HttpError 403:
Traceback (most recent call last):
  File "download_LI.py", line 81, in <module>
    main(util.setup(args), path, request_body)
  File "download_LI.py", line 57, in main
    handler.write(request.execute()['lineItems'].encode('utf-8'))
  File "//anaconda3/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "//anaconda3/lib/python3.7/site-packages/googleapiclient/http.py", line 856, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/doubleclickbidmanager/v1.1/lineitems/downloadlineitems?alt=json returned "You are not authorized to use DoubleClick Bid Manager API. Please contact dbm-support@google.com.">

I already tried different client secret files, but it didn't work. Any help will be appreciated.

A: Problem resovled, the account we connecte need access to DBM. Just need to add the google connection account to DBM for all service operation.

A: This error is very vague, but it always has to be with a tiny error in the request body.
For those in the future:
Check carefully how to create the query body:
https://developers.google.com/bid-manager/v1.1/queries#resource
More than one time I lost miserable hours debugging... and in the end it was:

*

*a typo in a key name

*an extra space like: .... "frequency": "ONE_TIME "
Hope it helps :)


text: Q: 2 outputs of same op amp gives different voltages I am using lm358p op-amp for 2 different heaters I connected both of them in a single op-amp and it didn't work firstly I thought that the problem was thermocouples I swapped them but the problem kept going then I made the connections in a breadboard when I used the first amplifier it worked just fine and then I swapped the amplifiers and 2nd amplifier gave a different value (note: I didn't change anything else and I tried with a 2.0v power supply too) I changed the resistors the capacitors checked all of them but it still doesn't works could you help me here is my schematic


text:
Q: Is it possible to draw a ShowCaseView on top of a dialogFragment? I've been looking for a way to do this for weeks, I've travelled hundreds of miles in search of an answer.
Is there any ShowCaseView that is capable of being drawn over a dialogFragment? Why do they all get drawn underneath it?
Example:
public class MyDialog extends AppCompatDialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireActivity(), R.style.MaterialAlertDialog_rounded);

        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.layout_dialog, null);

        Button buttonToShowcase = view.findViewById(R.id.myButton);
        buttonToShowcase.setOnLongClickListener(v -> {
            new BubbleShowCaseBuilder(getActivity()) //Activity instance
                .title("foo") //Any title for the bubble view
                .targetView(buttonToShowcase) //View to point out
                .show(); //Display the ShowCase
        });

        Dialog dialog = builder.create();
        return dialog;
    }
}

And in the activity that calls the dialogFragment:
MyDialog myDialog = new MyDialog();

myDialog.show(getSupportFragmentManager(), "My Dialog");


text:
Q: AWS certificate renewal I received an email from AWS that instructs me to renew my SSL certificate for my domain.
My certificate is managed by ACM and my DNS is hosted in Route 53.
I follow the instructions provided on this page (I'm using DNS verification):
https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-dns.html
However, after I follow the instructions I can see that the new certificate has appeared in ACM:
Status: Issued
In Use: No
Renewal eligibility: Ineligible

I can also see that in Route 53 a new CNAME record has been added.
Now, the document that outlines the steps to renew the certificate doesn't provide any next steps OR, if no extra steps are required, what the process is after the new certificate has been renewed.
My assumption is that once the old certificate expires that the new one automatically takes over, but, I have no way of telling if this is actually what is going to happen or not.
Are there any other steps I need to take after renewing a certificate in ACM with Route 53 CNAME validation?

A: It isn't apparent exactly why, but you didn't actually "renew" your certificate -- it appears you were issued a new one.
This is actually better than renewing because verifying the transition is easier.
You'll need to go to the services using the cert (Load Balancers, Beanstalk, CloudFront, API Gateway) and reconfigure them to use the new cert.  Once complete, "In use?" on the old cert changes to "No" and the new one says "Yes."


text:
Q: Matching a specific substring in a string with sed I have a folder with ebooks in epub format and their names are in the shape "title_of_the_book_-_name_of_the_author". I have to swap the two parts of the names of the ebooks so they become "name_of_the_author-title_of_the_book". I have written this command that works in almost every situations:
ls *.epub | sed 's/^\([^-]*\)-_\([^.]*\)/\2-\1/' | sed -E 's/.(.epub)$/\1/g'

I'm going to explain the code. First I list all the epub files in the folder, then I match the title of the book and the author of the book and I swap them and finally I delete the  _  that goes at the end of the title of the book.
This works in almost every situations, but when the title of the book contains a  -  this doesn't work. How can I match the substring  _-  instead of just this character  - ? I think that would solve my problem.

A: If I understand your problem/question correctly, this sed expression should do the trick:
sed -E 's/^(.*)_-_(.*)\.epub$/\2-\1.epub/'

This works under the assumption that every title is separated from author with a fixed 3-character string _-_. We use greedy capturing groups (.*), but anchor the beginning and end of the pattern, so we capture the title and author correctly.
For example:
$ echo "title_of_the_book_-_name_of_the_author.epub" | sed -E 's/^(.*)_-_(.*)\.epub/\2-\1.epub$/'
name_of_the_author-title_of_the_book.epub
$ echo "semi-title_of_the_book_-_name_of_the_author.epub" | sed -E 's/^(.*)_-_(.*)\.epub/\2-\1.epub$/'
name_of_the_author-semi-title_of_the_book.epub


text:
Q: Ext JS 3.2.1 Grid using Ext.fly to highlight a cell after that the original cell line and color not restore? I use below code to highlight a cell in an ExtJS grid
Ext.fly(TargetCell, "ID").highlight("CCFF33", {
                                            attr: "background-color",
                                            duration: 5
                                    });

It works well except that after highlight the cell will not return to original color and even the cell line were gone. Illustrated in below images, notice the second row Pending changed to Sold then the row line and background color became white
http://img231.imageshack.us/img231/2601/beforeextfly.jpg
http://img847.imageshack.us/img847/857/afterextfly.jpg
Any idea how to fix this?
Thanks!

A: You can use a css class. A quick rough example would be...
myGrid.on('rowclick', function (grid, rowindex) {

    var view = grid.getView();
    if (view.getRow(this.currentIndex)) {
        Ext.fly(view.getRow(this.currentIndex)).removeClass('highlight');
    }

    Ext.fly(view.getRow(rowindex)).addClass('highlight');

    this.currentIndex = rowindex;

}, this);


text:
Q: Linux traffic shaping for large bandwidth (more than 1Gig) I am doing an experiment between three computers that are connected with 10Gig interfaces and have RTT of 100 microseconds. Let's say these are machines A, B, and C. Machine A is communicating with B and C. Machines B and C do not communicate with one another.
I want to throttle bandwidth such that the machines A and B have 5Gbps bandwidth and 100 millisecond latency. Whereas, the machines A and C does not have any bandwidth and latency throttling. My goal is to emulate a wide area network with large bandwidth available.
I have tried using HTB and prio to throttle the bandwidth and latency. However, the maximum bandwidth reached is about 350 Mbps. I tested through iperf. My understanding is that we cannot have bandwidth more than 1Gig using TC.
Is there any way or any tool to throttle bandwidth above 1Gig?
I am using the following TC commands:
sudo tc qdisc del dev p4p1 root
sudo tc qdisc add dev p4p1 handle 1: root htb r2q 1000
sudo tc class add dev p4p1 parent 1: classid 1:3 htb rate 1000Mbps
sudo tc qdisc add dev p4p1 parent 1:3 handle 23: netem delay 50ms limit 100000000
sudo tc filter add dev p4p1 protocol ip prio 9 u32 match ip dst 10.96.0.1 flowid 1:3

A: I had the same trouble you found.  Eventually I found something that worked at the 2Gbps I needed to throttle at.  This is the script.  Modify as you require.
#!/bin/sh
#
# Incoming traffic control
#
DEV=eth0
RATE="2000mbit"

tc qdisc del dev $DEV root
tc qdisc add dev $DEV root handle 1: htb default 10
tc class add dev $DEV parent 1: classid 1:1 htb rate ${RATE} burst 15k
tc class add dev $DEV parent 1:1 classid 1:10 htb rate ${RATE} ceil ${RATE} burst 15k
tc qdisc add dev $DEV parent 1:10 handle 10: sfq perturb 10

echo;echo "tc configuration for $DEV:"
tc qdisc show dev $DEV
tc class show dev $DEV

#
# Outgoing traffic control
#
DEV=eth2
tc qdisc del dev $DEV root
tc qdisc add dev $DEV root handle 1: htb default 10
tc class add dev $DEV parent 1: classid 1:1 htb rate ${RATE} burst 15k
tc class add dev $DEV parent 1:1 classid 1:10 htb rate ${RATE} ceil ${RATE} burst 15k
tc qdisc add dev $DEV parent 1:10 handle 10: sfq perturb 10

echo;echo "tc configuration for $DEV:"
tc qdisc show dev $DEV
tc class show dev $DEV


text:
Q: how could I do some async thing in node-orm2's each function? I have some code like this:
req.models.order.find({})
  .each(function(order){
    req.models.food.find({orderId: order.id}{
      //...
      order.foods = ['...'];
      return order;
    })
  })
  .get(function(order){
    //the orders have no 'foods' attribute
  })

How could I fix it?

A: First of all, you can use associations (like one-to-many or many-to-many), which would be the most preferable path to go.
The other way to do it (maybe not too pro, but surely works) is to make a counter initialized with number of returned orders, decrementing with every next "each" iteration, and eventually firing "get" inside the "each" when the counter reaches 0.


text:
Q: Get JNDI resources programatically in spring I have a Tomcat servlet container that has a list of DataSources managed by Tomcat's connection pool. From my Spring application (Spring 3.2.3) I would like to get one of these datasources on runtime, something like:
public class MyService {
    @Autowired
    private JndiObjectLocator jndiLocator;

    public void myMethod(String jndiName) {
        DataSource myDataSource = jndiLocator.locate(jndiName);
    }
}

Any ideas on how to do that?

A: You can always do a JNDI lookup in your code, you can use the JndiDataSourceLookup for that and call the getDataSource() method.
public class MyService {
    @Autowired
    private JndiDataSourceLookup lookup;

    public void myMethod(String jndiName) {
        DataSource myDataSource = lookup.getDataSourcejndiName);
    }
}

Another option would be to make your bean aware of the BeanFactory and retrieve the DataSource from there.
public class MyService {
    @Autowired
    private BeanFactory factory;

    public void myMethod(String jndiName) {
        DataSource myDataSource = factory.getBean(jndiName, DataSource.class);
    }
}


text:
Q: Errors in phpMyAdmin I am getting these errors on phpMyAdmin.
I didn't do anything recently and I don't know why this is happening!
Error during session start; please check your PHP and/or webserver log file and configure your PHP installation properly. Also ensure that cookies are enabled in your browser.

session_write_close(): write failed: No space left on device (28)

session_write_close(): Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/www/tmp)

Here are the df function results:
devtmpfs         1929696        0   1929696   0% /dev
tmpfs            1940024       24   1940000   1% /dev/shm
tmpfs            1940024    25172   1914852   2% /run
tmpfs            1940024        0   1940024   0% /sys/fs/cgroup
/dev/sda1       39187808 37181080         0 100% /
tmpfs             388008        0    388008   0% /run/user/0


text:
Q: Strange behavior of Terminal PS1 value in Mac vs. Ubuntu On my mac and Ubuntu I have my PS1 values set to the below:
export PS1='\[\e[1;31m\]\d\[\e[0m\] \[\e[1;32m\]\u  \W\[\e[0m\] \[\e[1;36m\]>\[\e[0,\] \[$(tput sgr0)\]'

On Ubuntu the terminal prompt looks fine. But on my Mac an extra "B" is placed, like below:
Mon Jan 16 DrizzutoJr  ~ >B

I am assuming Mac and Ubuntu handle the value slightly differently. Can someone explain what's going on and how to fix it?

A: That \[\e[0,\] is suspect, since the enclosed text escape, does not correspond to a valid "ANSI" escape sequence (the comma is not a valid final byte).  It may happen to "work" with VTE (which has a lot of interesting cut/paste in its innards), but on other terminals, you're likely to get a stray character which will show up.
Perhaps you intended an adjacent key on the keyboard, m.
By the way, $(tput sgr0) is likely to produce the equivalent of \e[0m as well (using tput consistently throughout the expression would work as well, and though more verbose, perhaps more readable).
Further reading:

*

*Is there any objective benefit to escape sequences over tput?


text:
Q: Why are the data segment registers always null in gdb? Why do the data segment registers (ds/es/fs/gs) always seem to show up as 0x0 in GDB? For example, no matter what process or thread I look at, "info reg" always seems to give me output like this:
cs             0x33     51
ss             0x2b     43
ds             0x0      0
es             0x0      0
fs             0x0      0
gs             0x0      0

I am trying to debug glibc code where I see the fs segment prefix in the functions I am dissembling:
(gdb) disas __lll_lock_wait
Dump of assembler code for function __lll_lock_wait:
0x000000302800e240 <+0>:     push   %r10
0x000000302800e242 <+2>:     push   %rdx
0x000000302800e243 <+3>:     xor    %r10,%r10
0x000000302800e246 <+6>:     mov    $0x2,%edx
0x000000302800e24b <+11>:    xor    $0x80,%esi
0x000000302800e251 <+17>:    and    %fs:0x48,%esi
0x000000302800e259 <+25>:    cmp    %edx,%eax
0x000000302800e25b <+27>:    jne    0x302800e264 <__lll_lock_wait+36>
0x000000302800e25d <+29>:    mov    $0xca,%eax

I know that this is how glibc will reference the thread's TCB (tcbhead_t) for TLS and other important stuff. So wouldn't that mean that each thread would need to have a unique descriptor entry? Shouldn't each thread have a unique value for the fs register? I do not even believe 0x0 is a valid selector at all because the TI (table indicator) bit would indicate the GDT, and I thought there is no valid 0 GDT entry.
I know I must be missing something obvious, anyone know what it is?
Environment: CentOS 6.6, x86_64

A:
Shouldn't each thread have a unique value for the fs register?

No, each thread needs a unique FS segment base, but instead of requiring an LDT or GDT entry for each possible base, there's a mechanism for the kernel to simply set the FS base address directly in the internal segment descriptor without using a slower mov fs, eax instruction that loads a whole segment description including permissions and stuff.
The standard mechanism was writing an MSR (model-specific register); See Detail about MSR_GS_BASE in linux x86 64.
Intel since IvyBridge has supported the FSGSBASE feature, but apparently Linux is only just recently taking advantage of the wrfsbase instruction, which is faster than the WRMSR method.  See https://lwn.net/Articles/769355/.
As well as being faster than wrmsr, wrfsbase has the added feature that the kernel can let user-space execute it, so VMs in user-space (like Java) could maybe take advantage instead of needing to make a system call for an always-privileged WRMSR instruction.

A:
So wouldn't that mean that each thread would need to have a unique descriptor entry?

Yes.

Shouldn't each thread have a unique value for the fs register?

No. The value of fs register is the same, but the memory it points to is different in every thread. See arch_prctl(2) man page and code for setting this up in GLIBC source.

A: I think it's done by kernel:
Check the function start_thread_common(), then you will find the following:
    loadsegment(fs, 0);
    loadsegment(es, _ds);
    loadsegment(ds, _ds);
    load_gs_index(0);

For x86 64, _ds is 0. Why _ds is 0, since it's completely useless. The following is from Intel SDM v3.

3.2.4 Segmentation in IA-32e Mode
In IA-32e mode of Intel 64 architecture, the effects of segmentation depend on whether the
  processor is running in compatibility mode or 64-bit mode. In
  compatibility mode, segmentation functions just as it does using
  legacy 16-bit or 32-bit protected mode semantics. In 64-bit mode,
  segmentation is generally (but not completely) disabled, creating a
  flat 64-bit linear-address space. The processor treats the segment
  base of CS, DS, ES, SS as zero, creating a linear address that is
  equal to the effective address. The FS and GS segments are exceptions.
  These segment registers (which hold the segment base) can be used as
  additional base registers in linear address calculations. They
  facilitate addressing local data and certain operating system data
  structures.


text:
Q: CXF Timeout not working I created a web service client using cxf configured through Spring as shown below:
<!-- HTTP Conduit -->
<http-conf:conduit name="*.http-conduit">
    <http-conf:client ConnectionTimeout="30000"
        ReceiveTimeout="30000" />
</http-conf:conduit>

<!-- Client Proxies -->
<jaxws:client name="wsClient" serviceName="..."
    serviceClass="..."
    address="..." wsdlLocation="...">
</jaxws:client>

Now when the service is up, everything's working OK, But the problem is, when the service is down timeout values in the HTTPConduit are being ignored and I get the following error after 1 second:
org.apache.cxf.interceptor.Fault: Could not send Message.
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:64)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:570)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:479)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:382)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:335)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:136)

Caused by: java.net.ConnectException: Tried all: '1' addresses, but could not connect over HTTP to server: '192.168.80.55', port: '24004'
at weblogic.net.http.HttpClient.openServer(HttpClient.java:333)
at weblogic.net.http.HttpClient.openServer(HttpClient.java:425)
at weblogic.net.http.HttpClient.New(HttpClient.java:252)
at weblogic.net.http.HttpURLConnection.connect(HttpURLConnection.java:213)
at weblogic.net.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:279)
at org.apache.cxf.transport.http.HTTPCon2014-08-30 13:06:59 ERROR: javax.xml.ws.WebServiceException: Could not send Message.

Any clue why the consumer doesn't stay for the timeout duration before raising this error?

A: Timeout does not apply when the server is 'down'.
The ConnectionTimeout is how much to wait before connecting.
The ReceiveTimeout is how much to wait before receving a response.
In your case, there is no server listening on that port, so when your clients try to connect, the clients fails immediatly.

A: What do you mean by 'down'? Service responds with a 404? Closed port (connection refused)? Host is down (no connection possible due to timeout)?


text:
Q: Remove extra string characters in decimal formatting how do I remove just the ".00" in a data frame column: so that 5.00% /GP per tonne becomes 5% / GP per tonne ? I am trying something like the below but it is saying invalid regexp.

sched$duty_rate <- c("5.00% /GP per tonne","10.00% /GP per tonne")

for(i in 1:nrow(sched)){
  sched$duty_rate[i] <- gsub("[.]?[0-9]*(?=%)","\\%",sched$duty_rate[i])
}

A: You can use
sched$duty_rate <- gsub("\\.0+(%)", "\\1", sched$duty_rate)

Details:

*

*\. - a literal dot

*0+ - one or more 0 chars

*(%) - Group 1: a % char (so that we do not remove zeros from other contexts, only between . and %)

See the R demo:
duty_rate <- c("5.00% /GP per tonne","10.00% /GP per tonne", "5.0% /GP per 2.000 tonne","10.0000% /GP per 20.000 tonne")
gsub("\\.0+(%)", "\\1", duty_rate)
## => [1] "5% /GP per tonne"         "10% /GP per tonne"
##    [3] "5% /GP per 2.000 tonne"   "10% /GP per 20.000 tonne"

See the regex demo.

A: You can use sub, i.e.
sub('.00', '', sched$duty_rate, fixed = TRUE)
[1] "5% /GP per tonne"  "10% /GP per tonne"

A: Also, fairly simple and readable implementation can be derived with use of str_remove function offered via the stringr package.
x <- c("5.00% /GP per tonne", "10.00% /GP per tonne")
stringr::str_remove(string = x, pattern = ".00")
#> [1] "5% /GP per tonne"  "10% /GP per tonne"

Created on 2022-04-06 by the reprex package (v2.0.1)

A: Your pattern [.]?[0-9]*(?=%) matches an optional dot, optional digits and asserts % to the right which matches more than a mandatory dot and only zeroes.
You can make the positive lookahead work using perl=TRUE and match a dot and one or more zeroes using a more specific pattern [.]0+(?=%)
duty_rate <- c("5.00% /GP per tonne","10.00% /GP per tonne", "5.0% /GP per 2.000 tonne","10.0000% /GP per 20.000 tonne")
gsub("[.]0+(?=%)", "", duty_rate, perl=TRUE)

Output
[1] "5% /GP per tonne"         "10% /GP per tonne"
[3] "5% /GP per 2.000 tonne"   "10% /GP per 20.000 tonne"

See an R demo.


text:
Q: how to convert JSON to XML with Nodejs? i just know that the object Json can be an XMl file by the js2xml library,
so that's why I'm trying to convert the following  json to XML,
How can I achieve this in NodeJS?
i can't find an answer or a documentation that can help me?
here is the model JSON
const UserSchema = new mongoose.Schema({

email: {
type: String,
required: [true, "Please provide email address"],
unique: true,
match: [
  /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]
{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
  "Please provide a valid email",
],
},
password: {
type: String,
required: [true, "Please add a password"],
minlength: 6,
select: false,
 },

const User = mongoose.model("User", UserSchema);

module.exports = User;

i used this exemple that didn't work for me
  function groupChildren(obj) {
  for(prop in obj) {
  if (typeof obj[prop] === 'object') {
  groupChildren(obj[prop]);
   } else {
  obj['$'] = obj['$'] || {};
  obj['$'][prop] = obj[prop];
  delete obj[prop];
  }
  }

 return obj;
 }

 const xml2js = require('xml2js');
 const obj = {
 Level1: {
 attribute: 'value',
 Level2: {
  attribute1: '05/29/2020',
  attribute2: '10',
  attribute3: 'Pizza'
  }
  }
   };

   const builder = new xml2js.Builder();
  const xml = builder.buildObject(groupChildren(obj));
     console.log(xml);

A: When converting JSON to XML, one has to ask: what XML do you want to convert it to? Does it have to be a specific XML format, or will any old XML do?
If any old XML will do, then you can usually find some library to do the job, such as js2xml or js2xmlparser. The problem with these libraries is that they usually offer very little control over how the XML is generated, especially for example if there are JSON objects with keys that are not valid XML names (which doesn't apply in your case).
If you want a specific XML format then I would recommend using XSLT 3.0, which is available on node.js in the form of Saxon-JS. [Disclaimer: my company's product]. If you are interested in pursuing this approach, then tell us what you want the output to look like, and we can help you create it.

A: There are many different packages for XML serialization.

*

*Most of them enforce a specific XML and JSON mapping convention.

*Others require you to build the XML document in code.

Finally, there are solutions that do this with decorators. Those give you freedom in defining the structure without having to build the document entirely in code.
As an example: the xml decorators package.
It means that you define the XML mapping using a class. Next, you define decorators on top of each field, to define how it should be mapped to XML.
import { XMLAttribute, xml } from 'xml-decorators';

const NS = 'ns';

export class User {
  @XMLAttribute({namespace: NS})
  private email:string;

  @XMLAttribute({namespace: NS})
  private password: string;

  constructor(email: string, password: string) {
    this.email = email;
    this.password = password;
  }
}

And finally, to actually serialize
const user = new User('foo@bar.com', 'secret');
const xml = xml.serialize(user);

Conceptually, this is certainly a robust solution, since it strongly resembles how java xml binding (JAXB) and C# xml serialization work.


text:
Q: Re-arranging multiple divs on mobile devices? So I have a complicated setup.
I have 2 rows of three divs on large devices.
Similar to.

square 1

square 2

square 3

//some more html

square 4

square 5

square 6

When viewed on mobile I need to have the first 2 squares of each row in the top row. And the last square of each row in the bottom row. So it would like like the below

square 1

square 2

square 4

square 5

//some more html

square 3

square 6

What is the best way to do this?
I was thinking of using jquery to detect screen size and just moving the squares, but is this easiest?
Thanks

A: You can't move elements from one wrapper to another with CSS so JS would be your only option. You might be able to do something with CSS-Grid but it will depend on what your "more HTML" is.
For instance, leveraging display:contents to unbundle your wrappers and then using CSS-Grid to place the relevant children...
As I mentioned, this is highly specific and requires details of the "more HTML" which I have assumed for the sake of this example is a single div.

.row {
  display: contents;
}

body {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.row-2 :nth-child(1),
.row-2 :nth-child(2) {
  grid-row: 2;
}

.content {
  grid-row: 3;
  grid-column: span 2
}

div {
  outline: solid 1px lightgrey;
}

square 1

square 2

square 3

Lorem ipsum dolor sit amet consectetur adipisicing elit. Quod unde doloremque eum incidunt provident pariatur fugiat repellendus iste, vitae excepturi temporibus, illo voluptates rerum assumenda quo corrupti sapiente odit, labore tenetur dignissimos!
  Culpa, aliquam unde!

square 4

square 5

square 6

A: You could try doing something like this using flex box. This would mean removing the row div containers and just having one container. You would trigger the order css with a media query of course.
Link to fiddle

.cont {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  width: 100%;
}

.cont-2 .square:nth-child(1) {
  order: 1;
}

.cont-2 .square:nth-child(2) {
  order: 2;
}

.cont-2 .square:nth-child(3) {
  order: 5;
}

.cont-2 .square:nth-child(4) {
  order: 3;
}

.cont-2 .square:nth-child(5) {
  order: 4;
}

.cont-2 .square:nth-child(6) {
  order: 6;
}

.cont-2 .square {
  background-color: purple;
  color: #000;
}

.square {
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 1%;
  background-color: black;
  color: #fff;
}

square 1

square 2

square 3

square 4

square 5

square 6

square 1

square 2

square 3

square 4

square 5

square 6


text:
Q: React slick and React router Link doesn't distinguish click and drag I'm trying to make my slick slider slides link to an about page with react-router-dom. The problem is that it doesn't distinguish between a drag and a click. How would I make that happen, is there a way to do it with react router or would I need to add a JavaScript solution in with my own code? This is my code:
import React from "react";
import Slider from "react-slick";
import { Link } from "react-router-dom";
import "../node_modules/slick-carousel/slick/slick.css";
import "../node_modules/slick-carousel/slick/slick-theme.css";
import "./App.css";

class Movies extends React.Component {
  constructor() {
    super();
  }
  render() {
    const settings = {
      dots: false,
      infinite: false,
      speed: 500,
      slidesToShow: 5,
      slidesToScroll: 3,
      arrows: false,
      responsive: [
        {
          breakpoint: 1000,
          settings: {
            slidesToShow: 3,
            slidesToScroll: 3,
          },
        },
        {
          breakpoint: 600,
          settings: {
            slidesToShow: 2,
            slidesToScroll: 2,
          },
        },
      ],
    };
    return (

 Single Item

        <Slider {...settings}>

            <Link to="/about">

1

            </Link>

            <Link to="/about">

2

            </Link>

            <Link to="/about">

3

            </Link>

            <Link to="/about">

4

            </Link>

            <Link to="/about">

5

            </Link>

            <Link to="/about">

6

            </Link>

            <Link to="/about">

7

            </Link>

        </Slider>

    );
  }
}

export default Movies;

A: This can be achieved with simple built-in mouse events. A minimal example is given below.
import React, { useState } from "react";
import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";
import CardMedia from "@material-ui/core/CardMedia";
import { useHistory } from "react-router-dom";
import Link from "@material-ui/core/Link";

export default function Card() {
const history = useHistory();
const [mouseMoved, setMouseMoved] = useState(false);
// console.log(r)
const handleClick = () => {
    if (!mouseMoved) {
    history.push("/");
    }
};

return (
    <Card className={classes.root}>
    <CardHeader />
    <Link
        onMouseMove={() => setMouseMoved(true)}
        onMouseDown={() => setMouseMoved(false)}
        onMouseUp={() => handleClick()}
        style={{ textDecoration: "none", cursor: "pointer" }}
    >
        <CardMedia image="" title="">
        {" "}
        </CardMedia>
    </Link>
    </Card>
);
}

A: I fixed it by removing Link and linking with JavaScript instead. It checks start cursor position and end cursor position to see if it was dragged or clicked.
        let mousePosStart;
        let mousePosEnd;
        const mouseDownDetect = (e) => {
            mousePosStart = e.pageX;
        }
        const mouseUpDetect = (e) => {
            mousePosEnd = e.pageX;
        }
        const compareMouse = () => {
            console.log(`start: ${mousePosStart}   end: ${mousePosEnd}`);
            let diffrence = mousePosStart - mousePosEnd;
            if (diffrence === 0) {
                window.location.href = `./about`;
            }
        }

A: I had exactly the same problem, here is the best solution:
const onLinkMouseDown = (e) => {
    e.preventDefault();
}

 ...slideContent


text:
Q: Chart.js two categorical scales I have been trying to apply different datasets to a chart.js Chart but am having issues when I try to produce a plot with two categorical variables and make the scales categorical. Either all data is removed, or the x and y scales become mixed up/combined. I have mainly tried this with scatter plots as they should be able to visualize two categorical variables. Has anyone else experienced this issue or has a solution?
Preset/previously declared variables are:
dataset (object array),
xdata (string),
ydata (string)
My code is:
const myChart = new Chart(ctx, {

        type: "scatter",
        data: {
            datasets: [{
                display: false,
                data: dataset,
                pointBackgroundColor: ["#3e95cd"], // for scatter plot
            }],
            borderColor: "black",
        },
        options: {
            layout: {
                padding: 20,
            },
            parsing: {
                xAxisKey: xdata,
                yAxisKey: ydata,
            },
            responsive: false,
            scales: {
                y: {
                    display: true,
                    align: "center",
                    color: "black",
                    type: "category",
                    title: {
                        display: true,
                        text: ydata,
                        color: "black",
                        align: "center",
                        font: {
                            weight: "bold",
                        },
                    },
                },
                x: {
                    display: true,
                    align: "center",
                    color: "black",
                    type: "category",
                    title: {
                        display: true,
                        text: xdata,
                        color: "black",
                        align: "center",
                        font: {
                            weight: "bold",
                        },
                    },
                },
            },
            plugins: {
                title: {
                    display: true,
                    text: `Graph - ${ydata} vs ${xdata}`,
                    color: "black",
                    align: "center",
                    position: "top",
                    // This more specific font property overrides the global property
                    font: {
                        size: 16,
                        weight: "bold",
                    },
                },
                legend: {
                    display: false,
                },
            },

        },
    });
};

Thanks in advance!

A: 2 errors, type categorical does not exist. If you want a category axis you need to specify the type as: type:'category'. Also if you want a catergory Y axis you need to provide a labels array.
Also scatter plots don't display any category data by default. By default scatter plots have 2 linear axes.


text:
Q: Auto-Generate place holder format string for String.Format() Is there a way to tell the String.Format() function (without writing my own function) how many placeholders there are dynamically?  It we be great to say 15, and know I'd have {0}-{14} generated for me.  I'm generate text files and I often have more than 25 columns.  It would greatly help.
OK,
I will rephrase my question.  I wanted to know if it is at all possible to tell the String.Format function at execution time how many place-holders I want in my format string without typing them all out by hand.
I'm guessing by the responses so far, I will just go ahead and write my own method.
Thanks!

A: You could use Enumerable.Range and LINQ to generate your message string.
Enumerable.Range(0, 7).Select(i => "{" + i + "}").ToArray()

generates following string:
"{0}{1}{2}{3}{4}{5}{6}"

A: Adding a bit to AlbertEin's response, I don't believe String.Format can do this for you out-of-the-box.  You'll need to dynamically create the format string prior to using the String.Format method, as in:
var builder = new StringBuilder();

for(var i = 0; i < n; ++i)
{
  builder.AppendFormat("{0}", "{" + i + "}");
}

String.Format(builder.ToString(), ...);

This isn't exactly readable, though.

A: Why use string.Format when there is no formatting (atleast from what I can see in your question)?  You could use simple concatenation using stringbuilder instead.

A: There is a way to do this directly:
Just create a custom IFormatProvider, then use this overload of string.Format.
For example, if you want to always have 12 decimal points, you can do:
CultureInfo culture = Thread.CurrentThread.CurrentCulture.Clone(); // Copy your current culture
NumberFormatInfo nfi = culture.NumberFormat;
nfi.NumberDecimalDigits = 12; // Set to 12 decimal points

string newResult = string.Format(culture, "{0}", myDouble); // Will put it in with 12 decimal points


text:
Q: Multiplication function with recursion in Python I need to write the function mult( n, m ) that should output the product of the two integers n and m. I am limited to using addition/subtraction/negation operators, along with recursion.
This is what I have so far:
def mult( n, m ):
    if m == 0:
        return 0
    elif m < 0:
        return n - n(m+1)
    else:
        return n + n(m-1)

Can someone help me please because I can't figure it out!

A: You are trying to call n(m+1) in your elif and else block, since you say n is an integer, this is the problem, you should be calling mult() function recursively sending n and m+1 or m-1 as parameters.
Another issue is that you should convert the result of n - mult(n, m+1) to negative before returning.
Example -
...
    return - (n - mult(n, m+1))
else:
    return n + mult(n, m-1)

Demo with example changes -
>>> mult(5,-3)
-15
>>> mult(-10,-3)
30
>>> mult(5,3)
15

A: Recursion means, you have to call the function itself
def mul(a, b):
    def _mul(a, b, c=1):
        if a<c:
            return a, 0
        a, r = _mul(a, b + b, c + c)
        return (a - c, r + b) if a >= c else (a,r)
    return (_mul(a, b) if a<b else _mul(b, a))[1]

A: The simplest way to write in python by using recursion:
def mult(a, b):
   if a == 0:
      return 0
   elif a == 1:
      return b
   else:
      return b + mult(a-1, b)

A: Multiplication with Recursion in Python:
def multiplication(num_a, num_b):
   if num_a == 0 or num_b == 0:
     return 0
   return num_a + multiplication(num_a, num_b - 1)

A: Code:
def mult(a, b):
    if a == 0 or b == 0:
        return 0
    else:
        if a < 0 and b > 0:
            return a + mult(a, b - 1)
        elif a < 0 and b < 0:
            return -b + mult(-a - 1, -b)
        else:
            return b + mult(a - 1, b)

Test:
def test():
    x1 = mult(5, 3)
    x2 = mult(6, -3)
    x3 = mult(-3, 3)
    x4 = mult(-3, -33)

    print('5 * 3 = ', x1)
    print('6 * -3 = ', x2)
    print('-3 * 3 = ', x3)
    print('3 * -33 = ', x4)

test()

A: Cleanest code I could think of that accounts for negatives of either number:
def prod(m,n):
if n==0 or m==0:
    return 0
elif n<0:
    return -m+prod(m,n+1)
else:
    return m+prod(m,n-1)


text:
Q: Code 404 when calling APILayer currency conversion service I need to send a request to APILayer.
In the browser it works perfectly.
https://api.apilayer.com/currency_data/convert?to=USD&from=EUR&amount=5&apikey=
I want to send the request using Vertx.
    HttpClientOptions options = new HttpClientOptions();

    options.setLogActivity(true);
    options.setDefaultPort(8080);

    HttpClient client = routingContext.vertx().createHttpClient(options);

    client.request(HttpMethod.GET,"api.apilayer.com/currency_data/convert?to="+to+"&from="+from+"&amount="+amount+"&apikey=", response -> {
        System.out.println("Received response with status code " + response.statusCode());
        int code = response.statusCode();
        if (code == 200) {
            response.bodyHandler(bufferResponse -> {
                JsonObject httpResult = bufferResponse.toJsonObject();
                System.out.println("Received HTTP response with body " + httpResult);
            });
        } else {

            response.bodyHandler(bufferResponse -> {
                String httpResult = "{null}";
            });
        }

    }).putHeader(HttpHeaders.CONTENT_TYPE, "").end();

I always get error 404.
Anyone knows how to get the response ?
Thank you

A: HttpClientOptions options = new HttpClientOptions();

options.setLogActivity(true);
options.setDefaultPort(443);
options.setSsl(true);

HttpClient client = vertx.createHttpClient(options);

client.request(HttpMethod.GET, "api.apilayer.com", "/currency_data/convert?to=USD&from=EUR&amount=5&apikey=")
  .compose(HttpClientRequest::send)
  .onSuccess(response -> {
    System.out.println("Received response with status code " + response.statusCode());
    int code = response.statusCode();
    if (code == 200) {
      response.bodyHandler(bufferResponse -> {
        JsonObject httpResult = bufferResponse.toJsonObject();
        System.out.println("Received HTTP response with body " + httpResult);
      });
    } else {

      response.bodyHandler(bufferResponse -> {
        System.out.println("Received HTTP response with body " + bufferResponse.toString());
      });
    }

  }).onFailure(Throwable::printStackTrace);

The HttpClientOptions were incorrect. I fixed the configurations in the above code snippet and it worked on my local.


text:
Q: Using @Inject in Dagger to use values from one module into another I am relatively new to Dagger and I am trying to understand the usage of @Inject annotation between modules. Following is my code:
@Module
public class MyModule {

    @Provides
    @Named("myValue")
    @Singleton
    public String getRegion() {
        return System.getenv("myValue");
    }

}

@Module (includes = MyModule.class)
public class DependentModule {

    @Inject @Named("myValue") String myValue;

    @Provides
    @Singleton
    public MyClass myclass() {
        return myClass.builder()
            .stringValue(myValue)
            .build();
    }
}

@Component
public interface ApplicationComponent {
    MyClass provideMyClass();
}

Code using the Dagger module :
ApplicationComponent APPLICATION_COMPONENT = DaggerApplicationComponent.create();

MyClass classInstance = APPLICATION_COMPONENT.provideMyClass();

Now each time I try to run my code, my program fails in the fact that the Injected value for the String seems to be always null. I've verified that the environment variable being returned isn't null (I did a manual system.getenv() call inside my main function and that returned a non null value)
I can't understand whether the Inject annotation isn't supposed to be used that way? Should I not be using the @Inject annotation and be using it as a method parameter?


text:
Q: Set UINavigationController Title when presenting UIHostingController I have a SwiftUI view which is pushed to UINavigationController stack. I don't have any NavigationView inside SwiftUI and I want to show title text. How can I achieve this?
How can I create my controller:
let viewModel = SettingsViewModel()
let settingsView = SettingsView().environmentObject(viewModel)
let controller = UIHostingController(rootView: settingsView)
controller.title = "Settings"
return UIHostingController(rootView: settingsView)

What is inside SwiftUI
struct SettingsView: View {

// MARK: - Properties
@EnvironmentObject var viewModel: SettingsViewModel

// MARK: - View
var body: some View {
    List(viewModel.settingItems) { item in
        Text(item.rawValue)
    }
}

}

A: You returning settingsView as rootviewcontroller which has viewModel as a object but its empty like you declared to first let viewModel = SettingsViewModel() So below List has zero item.
var body: some View {
List(viewModel.settingItems) { item in
    Text(item.rawValue)
 }
}

On the other hand , you declare controller but it never used
let controller = UIHostingController(rootView: settingsView)
controller.title = "Settings"

I have a really smaller information about swiftUI but your problem must be one of these


text:
Q: Removing magnifying glass from image Added a function to add magnifying glass (.img-magnifier-glass) on button click. Now I want to remove the glass by clicking "cancel" button. I'm confused on how to write this function to work with the "magnify" function.
I tried to create a function that adds a class, and that class would be "display: none" on ".img-magnifier-glass".

function magnify(imgID, zoom)
{
    var img, glass, w, h, bw;
    img = document.getElementById(imgID);
    /*create magnifier glass:*/
    glass = document.createElement("DIV");
    glass.setAttribute("class", "img-magnifier-glass");
    /*insert magnifier glass:*/
    img.parentElement.insertBefore(glass, img);
    /*set background properties for the magnifier glass:*/
    glass.style.backgroundImage = "url('" + img.src + "')";
    glass.style.backgroundRepeat = "no-repeat";
    glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
    bw = 3;
    w = glass.offsetWidth / 2;
    h = glass.offsetHeight / 2;

    /*execute a function when someone moves the magnifier glass over the image:*/
    glass.addEventListener("mousemove", moveMagnifier);
    img.addEventListener("mousemove", moveMagnifier);
    /*and also for touch screens:*/
    glass.addEventListener("touchmove", moveMagnifier);
    img.addEventListener("touchmove", moveMagnifier);
    function moveMagnifier(e)
    {
        var pos, x, y;
        /*prevent any other actions that may occur when moving over the image:*/
        e.preventDefault();
        /*get the cursor's x and y positions:*/
        pos = getCursorPos(e);
        x = pos.x;
        y = pos.y;
        /*prevent the magnifier glass from being positioned outside the image:*/
        if (x > img.width - (w / zoom)) { x = img.width - (w / zoom); }
        if (x < w / zoom) { x = w / zoom; }
        if (y > img.height - (h / zoom)) { y = img.height - (h / zoom); }
        if (y < h / zoom) { y = h / zoom; }
        /*set the position of the magnifier glass:*/
        glass.style.left = (x - w) + "px";
        glass.style.top = (y - h) + "px";
        /*display what the magnifier glass "sees":*/
        glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "px";
    }
    function getCursorPos(e)
    {
        var a, x = 0, y = 0;
        e = e || window.event;
        /*get the x and y positions of the image:*/
        a = img.getBoundingClientRect();
        /*calculate the cursor's x and y coordinates, relative to the image:*/
        x = e.pageX - a.left;
        y = e.pageY - a.top;
        /*consider any page scrolling:*/
        x = x - window.pageXOffset;
        y = y - window.pageYOffset;
        return { x: x, y: y};
    }
}

function onClick()
{
    magnify("img1", 1.5);
    magnify("img2", 1.5);
    magnify("img4", 1.5);
}

      <button onclick = "onClick()" id="btn1" type="button" class="btn"> Zoom In</button>
        <button onclick = "zoomOut()" id= "btn2" type= "button" class="btn" >Cancel</button>

A: You need to find the added elements and delete them. Since the zoom script gives them all the class name of img-magnifier-glass you can do the following:
function zoomOut() {
   var zooms = document.querySelectorAll(".img-magnifier-glass");
   for(var x=0;x<zooms.length;x++) {
      zooms[x].parentNode.removeChild(zooms[x]);
   }
}

A: I ve already did that !
Thanks for the zoomOut function.
This is my external JScript

function magnify(imgID, zoom) {
    var img, glass, w, h, bw;
    img = document.getElementById(imgID);

    /* Create magnifier glass: */
    glass = document.createElement("DIV");
    glass.setAttribute("class", "img-magnifier-glass");

    /* Insert magnifier glass: */
    //img.parentElement.hidden(glass, img);
    img.parentElement.insertBefore(glass, img);

    /* Set background properties for the magnifier glass: */
    glass.style.backgroundImage = "url('" + img.src + "')";
    glass.style.backgroundRepeat = "no-repeat";
    glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
    bw = 3;
    w = glass.offsetWidth / 2;
    h = glass.offsetHeight / 2;

    /* Execute a function when someone moves the magnifier glass over the image: */
    glass.addEventListener("mousemove", moveMagnifier);
    img.addEventListener("mousemove", moveMagnifier);

    /*and also for touch screens:*/
    glass.addEventListener("touchmove", moveMagnifier);
    img.addEventListener("touchmove", moveMagnifier);
    function moveMagnifier(e) {
      var pos, x, y;
      /* Prevent any other actions that may occur when moving over the image */
      e.preventDefault();
      /* Get the cursor's x and y positions: */
      pos = getCursorPos(e);
      x = pos.x;
      y = pos.y;
      /* Prevent the magnifier glass from being positioned outside the image: */
      if (x > img.width - (w / zoom)) {x = img.width - (w / zoom);}
      if (x < w / zoom) {x = w / zoom;}
      if (y > img.height - (h / zoom)) {y = img.height - (h / zoom);}
      if (y < h / zoom) {y = h / zoom;}
      /* Set the position of the magnifier glass: */
      glass.style.left = (x - w) + "px";
      glass.style.top = (y - h) + "px";
      /* Display what the magnifier glass "sees": */
      glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "px";
    }

    function getCursorPos(e) {
      var a, x = 0, y = 0;
      e = e || window.event;
      /* Get the x and y positions of the image: */
      a = img.getBoundingClientRect();
      /* Calculate the cursor's x and y coordinates, relative to the image: */
      x = e.pageX - a.left;
      y = e.pageY - a.top;
      /* Consider any page scrolling: */
      x = x - window.pageXOffset;
      y = y - window.pageYOffset;
      return {x : x, y : y};
    }
  }
  function zoomOut() {
    var zooms = document.querySelectorAll(".img-magnifier-glass");
    for(var x=0;x<zooms.length;x++) {
       zooms[x].parentNode.removeChild(zooms[x]);
    }
 }

I used the steps from W3Schools [https://www.w3schools.com/howto/howto_js_image_magnifier_glass.asp][1]
In my Html file i used a switch to display several images :

function showmob(mob)
{
    document.getElementById("mymob").className = "img_show";

    switch (mob) {
     case "mob1":

        document.getElementById("mymob").src="iphone12.jpg";
        zoomOut();
        magnify("mymob", 3);
        break;

     case "mob2":

        document.getElementById("mymob").src="samsung.jpg";
        zoomOut();
        magnify("mymob", 3);
        break;
     case "mob3":

        document.getElementById("mymob").src="p40.jpg";
        zoomOut();
        magnify("mymob", 3);
        break;
     case "mob4":

        document.getElementById("mymob").src="xiaomiRedmi.jpg";
        zoomOut();
        magnify("mymob", 3);
        break;
    }
}

And also in HTML

    iphone 12
    128 GB
    TrueDepth
    LiDAR
    IOS 14
    1.229,00 €
    <button class="iconbtn" onclick="showmob('mob1')"></button>

    samsung galaxy s20
    128 GB
    40MP
    108MP(f1.8/PDAF) + 48MP(f3.5) + 12MP(f2.2)
    ANDROID 11
    1.399,00 €
    <button class="iconbtn" onclick="showmob('mob2')"></button>

    huawei P40
    256 GB
    32 MP
    50 + 40 + 12 + 3D Tof M
    ANDROID 11
    899,00
    <button class="iconbtn" onclick="showmob('mob3')"></button>

Thanks again.
I tried to distribute my solution


text: Q: Ubuntu 12.1 can't list [my] wifi modem I've changed my wifi modem , old one is Linksys new one is airties. Ubuntu listed my ex wifi modem on the wireless list, but it hasn't listed my new wifi modem. It still shows other wireless modem , but not mine. I set up my modem with same security methods. My NIC is Qualcomm Atheros AR9285. I could connect my old modem. Can you help me?


text:
Q: Retrieving Json data from external URL I'm having a hard time getting some json data from an API here. Basically I want to get the file contents, then assign the "meta_game" to a variable and I also want the "channel_count" to be assigned to a variable. As you can see here, I tried 2 different methods for both instances and neither work at the moment.
$json = file_get_contents($chan);
$json_data = unserialize($json);
$gameName = json_decode($json)->meta_game;
$viewerCount = $json_data['channel_count'];

Heres an example of a URL it would be taking this from: http://api.justin.tv/api/stream/list.json?channel= + channel name.

A: Why are you unserializing the data?  Its not required
$json = file_get_contents('http://api.justin.tv/api/stream/list.json?channel=' . $channelName);
$jsonData = json_decode($json);

$gameName = $jsonData->meta_game;

$viewerCount = $jsonData->channel_count;

Of course you may need to check the paths through the $jsonData object to find your final values as I didn't parse it and can't guarantee they are at the first node.
Update: Because I can't leave things alone, I checked this to see what the response from the API was
As it returns an array first, your paths will be
$jsonData[0]->channel->meta_game;

$jsonData[0]->channel_count;

Assuming you only have 1 channel in the response

A: you can try below code
<?php
$json = file_get_contents('http://api.justin.tv/api/stream/list.json?channel=');
$gameName = json_decode($json,true);
$new_arr = array();
foreach($gameName as $g){
print_r( $g['channel']['meta_game']);
 array_push($new_arr,$g['channel']['meta_game']);
}
?>

A: (function($){
    $.fn.fetch = function() {
        $.ajaxSetup({ cache: true });
        //var optionsWithDefaults = $.extend(defaults, options);
        return this.each(function() {
            var obj = [];
            $.getJSON(' http://api.justin.tv/api/stream/list.json?channel=xxx',
                function(data) {
                    $.each(data, function(i, feed) {
                        if(feed.channel_count !== undefined) {
                            obj.push(feed.channel_count);
                        }
                    });
                }
            );
        });
    };
})(jQuery);


text:
Q: \luatexluaescapestring{\unexpanded{ and % inside string problem I am passing code listings from latex to lua function for processing and formatting. Using "\luatexluaescapestring{\unexpanded{ code }}"  as main method to pass arbitrary code listing as is to lua, as string.
This works very well, except for one case I found. When the code contains a string itself and the string contains %, it fails. The code listing is cut off at the % start.
Is there a way to tell Latex to pass the string as is and not look inside it?
I thought that \unexpanded will prevent this. Here is a MWE (this is just an example. In actual code, I am doing much more than just putting verbatim around the code), I am using listing package and more.
\documentclass{article}
\usepackage{luacode}

\begin{luacode*}
function foo(myStr)
tex.print("\\begin{verbatim}"..myStr.."\\end{verbatim}")
end
\end{luacode*}

\begin{document}

\directlua{foo("\luatexluaescapestring{\unexpanded{%
x=10; plotTittle=sprintf("%a pi", 3);  y=20;
}}")}

\end{document}

lualatex gives

TL 2016.
The problem is not the string inside the string. As this works
\directlua{foo("\luatexluaescapestring{\unexpanded{%
x=10; plotTittle=sprintf("a pi", 3);  y=20;
}}")}

And gives

It is the % used in the code which is the problem.
Question is: What to do to prevent latex from looking at the content of the string in any way? All strings are source code listing, from different languages.

A: If for some reason you don't want to use luacode after having loaded the package then you can do

\documentclass{article}
\usepackage{luacode}

\makeatletter
\let\percent\@percentchar
\makeatother

\begin{luacode*}
function foo(myStr)
tex.print("\\begin{verbatim}"..myStr.."\\end{verbatim}")
end
\end{luacode*}

\begin{document}

\directlua{foo("\luaescapestring{%
x=10; plotTittle=sprintf("\percent a pi", 3);  y=20;}%
")}

\end{document}

or to use the package features:
\begin{luacode*}
foo('x=10; plotTittle=sprintf("%a pi", 3);  y=20;}')
\end{luacode*}


text:
Q: Arangoimp exception I have a csv file with the following structure:
h1_h2,hashtag1,hashtag2,coccurrence
39108234088393,9230981401776738405,11889764071793228909,2
48887306406636,2844752706633868157,14936885980370043276,2
...

There are 1028112 lines in file.
I tried to import it into collection via arangoimp
arangoimp --file E:\current_crawler\Data\edges\edges_for_graph_ep_83.csv --collection edges_temp4 --create-collection true
--create-collection-type edge --type csv --translate "hashtag1=_from" --translate "hashtag2=_to" --from-collection-prefix hashtags
--to-collection-prefix hashtags --translate "h1_h2=_key" --server.database "newDB" --server.username username --server.password password

and got the error:
Connected to ArangoDB 'http+tcp://127.0.0.1:8529', version 3.3.4, database: 'newDB', username: 'svm'
----------------------------------------
database:               newDB
collection:             edges_temp4
from collection prefix: hashtags
to collection prefix:   hashtags
create:                 yes
source filename:        E:\current_crawler\Data\edges\edges_for_graph_ep_83.csv
file type:              csv
quote:                  "
separator:
threads:                2
connect timeout:        5
request timeout:        1200
----------------------------------------
Starting CSV import...
2018-08-22T16:49:21Z [3012] INFO processed 1998848 bytes (3%) of input file
2018-08-22T16:49:21Z [3012] INFO processed 3964928 bytes (6%) of input file
2018-08-22T16:49:21Z [3012] INFO processed 5963776 bytes (9%) of input file
2018-08-22T16:49:22Z [3012] INFO processed 7929856 bytes (12%) of input file
2018-08-22T16:49:22Z [3012] INFO processed 9928704 bytes (15%) of input file
2018-08-22T16:49:22Z [3012] INFO processed 11894784 bytes (18%) of input file
2018-08-22T16:49:22Z [3012] INFO processed 13893632 bytes (21%) of input file
2018-08-22T17:09:23Z [3012] ERROR Caught exception Expecting item during import

What does thar error means? The file is OK, there is no empty lines and duplicated _keys in it. Moreover, when I rebooted the system and tried again, there was no such error, it imported successfully.
I'd appreciate all the help I can get.
Envoronment:
Storage Engine: RocksDB
Deployment Mode: Single Server
Configuration: Intel Xeon X5650 x2, 32GB RAM
Operating System: Windows 10


text:
Q: Java proxy - fetch outgoing request
It may be a common question, but:
I've app, which is making request to
elldmess.cz/api/...
But this api has gone.
Now I want "something", that catch request to elldmess.cz/api, reformat it and send it to
api.elldmess.cz
note, it has another format - from URI request to JSONbased, so
simple redirecting won't work
I've thought about some proxy, which wrap old application and remake request.
App is desktop, JavaFX based.

A: You may be interested in AspectJ. This enables you to catch the method calls which make the request to the original site and alter or completely replace them.


text:
Q: Firestore exists() method cannot access data immediately after creation TL;DR - I seem to be experiencing a lag between data being written to Firestore and that same data being available to the exists() method in my security rules.
I would love someone to, explain the issue / give me fix / suggest an alternative. Details below...

Detailed Version
I have a collection of groups and a collection of users. Any user can create a group and when they do so their ID is added to a sub-collection of that group called linkedUsers while the new group ID is added to a sub-collection of the user called linkedGroups.
The idea is that after a group is created it can only be read or updated by a user who's ID is on that group's linkedUsers list, or who has the group ID on their linkedGroups list.
I have this set up - groups and sub-collections are created as expected and all looks fine. I have an onSnapshot() listener maintaining a list of all my groups from users/{myUid}/linkedGroups. Access here is granted by the simple rule...
match /users/{user}{
   allow read, write: if user = request.auth.uid;
}

I can also navigate to a new page that retrieves all the details of a specific group. Here I have a rule to allow access to a group if the requesting user's ID is in that group's linkedUsers sub-collection...
match /groups/{group}{
   allow read, write:if exists(/databases/$(database)/documents/groups/$(group)/linkedUsers/$(request.auth.uid));
}

This also seems to work fine but here is the issue. When a new group is created I want to immediately navigate to a detail page for that new group. I have a listener set up that fires when the group data has (apparently) been written, and I then go to the detail page. This works about 50% of the time but the other 50% I get a Missing or insufficient permissions error. If I refresh the screen or even just wait a second or two then I can manually launch the detail page fine.
It all feels like there is a lag between the data being written to the backend and it becoming available to the exists() method in the security rules.

*

*Has anyone else come across this or similar?

*Am I going about this in some wrong way or coming to the wrong
conclusion?

*Is this a bug in Firestore (it is still in Beta after all)?

*And most importantly, can anyone suggest a way to get round this by
hack, bodge or any other means?

All these questions and more answered below (I really, really hope!)
Thanks all


text:
Q: How to match strings between two columns in R? I want to create a new column (MATCH) on the basis of string match between two existing columns. For example -

st_add
aa_add
MATCH

jai maa durga society
jai maa durga colony
MATCH

elph road highway 1
road highway 2 elph
MATCH

srinivan colony parel ist
srinivan bus depot
NOT MATCH

If there is a match in three or more words between column 1 and column 2 then then column 3(MATCH) should show "MATCH". But if there is less than 3 words matches or no match at all (example row 3) then the result should be "NO MATCH"
How can I do this using R??

A: You can try stringdist. You can set a string distance threshold for a match. It also offers multiple methods for computing distance. Thanks Ronak for the dataset code.
library(stringdist)

df$match <- ifelse(stringdist(df$st_add, df$aa_add) < 12, "MATCH", "NOT MATCH")
df

#                      st_add               aa_add     match
# 1     jai maa durga society jai maa durga colony     MATCH
# 2       elph road highway 1  road highway 2 elph     MATCH
# 3 srinivan colony parel ist   srinivan bus depot NOT MATCH

A: You can split the data into words in st_add and aa_add count the number of common words, if they are greater than equal to 3 assign 'MATCH' to it.
df$MATCH <- ifelse(mapply(function(x, y) length(intersect(x, y)),
                strsplit(df$st_add, '\\s+'),
                strsplit(df$aa_add, '\\s+')) >= 3, 'MATCH', 'NOT MATCH')
df

#                     st_add               aa_add     MATCH
#1     jai maa durga society jai maa durga colony     MATCH
#2       elph road highway 1  road highway 2 elph     MATCH
#3 srinivan colony parel ist   srinivan bus depot NOT MATCH

data
df <- structure(list(st_add = c("jai maa durga society", "elph road highway 1",
"srinivan colony parel ist"), aa_add = c("jai maa durga colony",
"road highway 2 elph", "srinivan bus depot")), row.names = c(NA,
-3L), class = "data.frame")


text:
Q: trigger asp:button's click event by clicking another asp:button i have two asp:buttons.. say button1 and button2, what i would like to do is fire button2's click event when I click button1.. is there a way to trigger click event on an asp:button through code behind? please help, newbie here.

A: Well, you can put the same event for both buttons, something like this:
<asp:Button ID="btn1" runat="server" Text="Button 1" CommandName="Save" />
<asp:Button ID="btn2" runat="server" Text="Button 2" CommandName="Cancel" />

and in code behind (vb.net):
Protected Sub btn_event(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn1.Click, btn2.Click

   Dim btn As Button = CType(sender, Button)

   'now you have the button instance on sender object, and you can check the ID property or CommandName property do solve what you want to do!

End Sub

C# code:
protected void btn_event(object sender, EventArgs e) {

    Button btn = (Button)sender;

    //now you have the button instance on sender object, and you can check the ID property or CommandName property do solve what you want to do!

}

If you're using C#, remember to set the event click on asp:button tag.


text:
Q: Push to bare git repository without cloning it beforehand I am currently trying to save some files in a bare git repository, as described here:
https://news.ycombinator.com/item?id=11071754
However, I am trying this with Git for Windows, and not on a Linux machine. The bare git repository gets created, but I am struggling to get the push working correctly. This is what I have done:
username@hostname MINGW64 ~/Desktop
$ mkdir .myconf

username@hostname MINGW64 ~/Desktop
$ git init --bare "/c/Users/username/Desktop/.myconf"
Initialized empty Git repository in C:/Users/username/Desktop/.myconf/

username@hostname MINGW64 ~/Desktop
$ alias config="git --git-dir='/c/Users/username/Desktop/.myconf' --work-tree='/c/Users/username/Desktop/'"

username@hostname MINGW64 ~/Desktop
$ config config status.showUntrackedFiles no

username@hostname MINGW64 ~/Desktop
$ config status
On branch master

Initial commit

nothing to commit (create/copy files and use "git add" to track)

username@hostname MINGW64 ~/Desktop
$ config add test.txt

username@hostname MINGW64 ~/Desktop
$ config commit -m "Added test file."
[master (root-commit) a587ec1] Added test file.
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt

Everything so far has worked correctly. However, when I try to push, this happens:
username@hostname MINGW64 ~/Desktop
$ config push
fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository using

    git remote add <name> <url>

and then push using the remote name

    git push <name>

Also a push to origin master does not work:
username@hostname MINGW64 ~/Desktop
$ config push origin master
fatal: 'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Apparently, git wants a push destination.
I have not seen that setting such a destination is a necessary step in the linked description (nor in any derived blog posts), and I am unsure how to do that with Git for Windows. How can this be solved?

A: You need to define a remote so Git knows where to push to. The default remote is called origin and will be the url for Git to push to.
For example, if you were trying to push to the Linux Kernel the command would be:
git remote add origin https://github.com/torvalds/linux.git

A: You need to tell git where the remote repository is. Use:
config remote add origin "<path>"

Where path is either a url or directory.
If you wish to understand why .myconfig is not a remote repo that you push to read through something like this: http://www.sbf5.com/~cduan/technical/git/

A: For distributed VCS such as git, the push is a synchronization mechanism between local branch and remote branch. you must specify the connection of local branch and remote branch before you do push, for which in git, it reference as "upstream" or "tracking".
If you want to push your commit to remote without clone. you can add the remote repository as a new remote, checkout the branch you want to commit to and make it track the remote branch, add your modification to this new branch and do push.


text:
Q: How to make a multi-color gradient effect in CSS? How would I go about creating moving gradient background?

A: A) CSS can do a blur, if you make a tiny image with for example just 5x4 pixels of random colors have this image stretched to 100% in height and width as the background of a DIV and apply a heavy blur on that, your result will probably look similar. However blur doesn't work on all browsers, so you would need a fallback solution for unsupported browsers.
B) Also you can define linear gradients in CSS. Theoretically, but I never tried this before, we could make multiple gradient DIV with minimal color differences layered on top of each other using opacity by CSS animation/transition to mix the layers over time.
The snippet below needs more tweaking because it doesn't work in all possible odd cases with browsers, also inside the snippet view there is some padding offset that was not visible in pure html because there is a body tag that's missing in the snippet. However you asked for getting some directions. I hope you can optimise this code and share your results with the community. It does work in macOS Safari as far as I could tell. Firefox and Chrome still jump to the end of transition directly. So I wish you happy tweaking!

function startTransitions() {
  document.getElementById('gradient-top-left').style.opacity = "0.1";
  document.getElementById('gradient-top-right').style.opacity = "0.1";
  document.getElementById('gradient-bottom-left').style.opacity = "0.1";
  document.getElementById('gradient-bottom-right').style.opacity = "0.1";
  document.getElementById('colors').style.opacity = "1.0";
}

document.addEventListener('DOMContentLoaded', function() {
  startTransitions();
});
#canvas {
  margin: 0px;
  padding 0px;
}

#colors {
  position: absolute;
  margin: 0px;
  background-image: url(http://testing.2x2p.com/gradient/colors.png);
  background-size: cover;
  min-height: 100%;
  min-width: 100%;
  filter: blur(120px);
  -webkit-filter: blur(120px);
  z-index: 1;
  opacity: 0.0;
  -webkit-transition: opacity 6s ease-in-out 1s;
  -moz-transition: opacity 6s ease-in-out 1s;
  -ms-transition: opacity 6s ease-in-out 1s;
  -o-transition: opacity 6s ease-in-out 1s;
  transition: opacity 6s ease-in-out 1s;
}

#gradient-top-left {
  margin: 0px;
  position: absolute;
  background-color: #000;
  min-height: 100%;
  min-width: 100%;
  background-image: linear-gradient(to bottom right, orange, white);
  z-index: 2;
  -webkit-transition: opacity 5s ease-in-out 2s;
  -moz-transition: opacity 5s ease-in-out 2s;
  -ms-transition: opacity 5s ease-in-out 2s;
  -o-transition: opacity 5s ease-in-out 2s;
  transition: opacity 5s ease-in-out 2s;
}

#gradient-top-right {
  margin: 0px;
  position: absolute;
  background-color: #000;
  min-height: 100%;
  min-width: 100%;
  background-image: linear-gradient(to bottom left, lightgreen, white);
  opacity: 0.7;
  z-index: 3;
  -webkit-transition: opacity 3s ease-in-out 4s;
  -moz-transition: opacity 3s ease-in-out 4s;
  -ms-transition: opacity 3s ease-in-out 4s;
  -o-transition: opacity 3s ease-in-out 4s;
  transition: opacity 3s ease-in-out 4s;
}

#gradient-bottom-left {
  margin: 0px;
  position: absolute;
  background-color: #000;
  min-height: 100%;
  min-width: 100%;
  background-image: linear-gradient(to top right, pink, white);
  opacity: 0.7;
  z-index: 4;
  -webkit-transition: opacity 4s ease-in-out 3s;
  -moz-transition: opacity 4s ease-in-out 3s;
  -ms-transition: opacity 4s ease-in-out 3s;
  -o-transition: opacity 4s ease-in-out 3s;
  transition: opacity 4s ease-in-out 3s;
}

#gradient-bottom-right {
  margin: 0px;
  position: absolute;
  background-color: #000;
  min-height: 100%;
  min-width: 100%;
  background-image: linear-gradient(to top left, lightblue, white);
  opacity: 0.7;
  z-index: 5;
  -webkit-transition: opacity 6s ease-in-out 1s;
  -moz-transition: opacity 6s ease-in-out 1s;
  -ms-transition: opacity 6s ease-in-out 1s;
  -o-transition: opacity 6s ease-in-out 1s;
  transition: opacity 6s ease-in-out 1s;
}


text:
Q: Can not compile to a native executable with Clozure CL on OS X 10.10 Yosemite I have created a simple hello world (hello.lisp) ,code:
(defun main ()
    (format t "Hello,World"))

, program to test CCL's native executable compilation. I proceed to compile and load buffer from the CCL GUI (using version Clozure Common Lisp Version 1.10-store-r16266  (DarwinX8664)).
When i test it:
    ? (main)
    Hello,World
    NIL
    ?

It finds the main function. When i proceed to compile it with:  (save-application "/tmp/h" :toplevel-function #'main :prepend-kernel t), it proceeds with the operation and CCL exits.
The file is created and is arround ~56MB. When i try to run it though I get the following output:

Error: There is no applicable method for the generic function:
           #
         when called with arguments:
           (# :NOTE-CURRENT-PACKAGE #)
  While executing: #, in process toplevel(6).
  Error: There is no applicable method for the generic function:
           #
         when called with arguments:
           (# :BREAK-OPTIONS-STRING T)
  While executing: #, in process toplevel(6).
  Error: There is no applicable method for the generic function:
           #
         when called with arguments:
           (# :BREAK-OPTIONS-STRING T)
  While executing: #, in process toplevel(6).
  Error: There is no applicable method for the generic function:
           #
         when called with arguments:

And the errors proceed. What do I do wrong? Is it a bug?
Thank you

A: I found the keywords :note-current-package and :break-options-string in the cocoa-ide of the sources.  Since prepend-kernel t prepends the kernel that was used in the current session, it seems that you would include the cocoa-ide startup in your application.  However, the methods dispatching on those keywords only dispatch on ´ns-application`s, which your new application seems not to be.
The solution might be to prepend a kernel without cocoa-ide, either by loading your code into a non-GUI image, or by using the pathname of such a kernel for the :prepend-kernel argument.

A: To create executables of Clozure CL on Mac OS X:

*

*for non-GUI applications, you need to install Clozure CL from the repository: Installing Clozure CL. You need to download CCL from there. This version comes with an executable Lisp (kernel + image), which hasn't the GUI loaded.

*for GUI applications you need to use the Application Builder. The corresponding function is ccl::build-application. GUI applications on Mac OS X need some infrastructure, which is created then. Note that CCL comes with a example application in ccl/examples/cocoa/currency-converter/. Personally I would also prefer to use CCL from the repository - it's usually a bit newer than the version in the Mac Application store.


text:
Q: Javascript builder pattern using private variables I'm trying to create a builder pattern in Javascript that uses private variables, while providing one public accessor (fullName) that returns a mashup of all the other properties. This question and answer suggests that I can use Object.defineProperty inside the person constructor in order to access private variables, but it doesn't work - instance.fullName is always undefined.
How can I get this working so that the builder pattern variables remain private, but the public accessor has access to them throughout the build chain?
var Person = function () {
    var _firstName, _lastName

    Object.defineProperty(this, "fullName", {
        get: function () {
            return _firstName + ' ' + _lastName;
        }
    });

    return {
        firstName: function (n) {
            _firstName = n
            return this
        },
        lastName: function (n) {
            _lastName = n
            return this
        }
    }
}

var x = new Person().firstName('bob').lastName('dole');

console.log(x.fullName); // always undefined

A: As per my comment, change the object passed to defineProperty():
var Person = function () {
    var _firstName, _lastName

    var _self = {
        firstName: function (n) {
            _firstName = n
            return this
        },
        lastName: function (n) {
            _lastName = n
            return this
        }
    }

    Object.defineProperty(_self, "fullName", {
        get: function () {
            return _firstName + ' ' + _lastName;
        }
    });

    return _self;
}

var x = new Person().firstName('bob').lastName('dole');

console.log(x.fullName); // bob dole

http://jsfiddle.net/mattball/peztf9qs/


text:
Q: Minimize xibs variety for localizations and iPhone 4/5 As I know from official sources, when we localize xib files we need to duplicate them and replace translated strings in Interface Builder.
And to support iPhone's 4" screen we need to make separate version of xib with height of 586 pixels (I had problems with autoresized top-level views without corresponding view controllers in common xib). In this case it's almost impossible to tune up interface in future updates.
How to minimize this variety (perfectly to single xib file)?

A: *

*Don't use an extra xib for every language, set the labels etc. in code (and use a Localizable.strings file)

*Learn how to use layout constraints in your xib to support 3,5" and 4" displays
That's how I do it, and it works


text:
Q: Sikuli Script IO Error on VisionProxy.dll when launching multiple instances simultaneously I have the following problem on Windows. I am using SikuliScript in interactive mode which is working fine. That's the commandline I use to launch it:
"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar "E:\APPS\Sikuli\Runtime\sikuli-script.jar" -i

However if I launch this command at least twice roughly at the same time (either manually or via Scheduled Tasks) I'll get a Java Exception because VisionProxy.dll already exists in my Temp Directory and cannot be overwritten because it's actively in use (by the other command of course):
java.io.FileNotFoundException: C:\Users\%USERNAME%\AppData\Local\Temp\2\tmplib\VisionProxy.dll (The process cannot access the file because it is being used by another process)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)

The DLL gets put there by Sikuli itself when the library gets loaded so I don't know how to prevent this. Has anyone had a similar problem and solved it?
Thanks & Regards

A: There's no quick and easy fix for this.
What's happening is that the sikuli-script jar is using a little trick to allow it to be packaged as a single self-contained jar.  The jar file contains all the native libraries that it might need, and when you run it, the code figures out which one you actually need (Windows_x86, maybe), pulls it out of the jar into the temp directory, and then dynamically links it.  Running two in a row as your doing makes the DLL extraction process fail because one process stomps on the others' files.
The only fix for this is changing the code.  You'll need to get the source code for Sikuli, find where it's performing the dynamic link trick, and remove that.  Then you'll need to build it yourself and manually link against the DLL.  That will allow you to run multiple instances at once (although I'm not sure how useful that will be).


text:
Q: facing an issue while executing ethernet example given in espressif IDF release/v4.2 problem:
I have used espressif esp32s ethernet example
trying to build basic and  build is successfuly generated
now while executing it is throwing error as given below :
hardware/software
chip used esp32-wrover-1
idf version -release/v4.2
build sysytem - msys/MINGW32
power supply - usb
Logs
E (470) emac_esp32: emac_esp32_init(308): **reset timeout**
E (470) esp_eth: esp_eth_driver_install(198): **init mac failed**

ESP_ERROR_CHECK failed: esp_err_t 0xffffffff (ESP_FAIL) at 0x40083ee0
file: "../main/ethernet_example_main.c" line 125
func: app_main
expression: esp_eth_driver_install(&config, &eth_handle)
abort() was called at PC 0x40083ee3 on core 0

Backtrace:0x40084353:0x3ffb5610 0x400849fd:0x3ffb5630 0x4008845a:0x3ffb5650 0x40083ee3:0x3ffb56c0 0x400d44d9:0x3ffb56e0 0x400d2e9e:0x3ffb5750 0x40084a05:0x3ffb5780

ELF file SHA256: 6fadeffcb15e44d0

**Rebooting...**


text:
Q: netcat6 in IPv6 local network I have: [ Host A ] -- [ gateway ] -- [ Host B ], whereas A and B are in different subnets.
Gateway configuration:
ip -6 link set enp0s3 up
ip -6 link set enp0s9 up
ip -6 addr flush dev enp0s3
ip -6 addr flush dev enp0s9
ip -6 route flush dev enp0s3
ip -6 route flush dev enp0s9
ip -6 addr add ::ffff:5:7:1:1/126 dev enp0s3
ip -6 addr add ::ffff:5:7:2:1/126 dev enp0s9
echo 1 | tee /proc/sys/net/ipv6/conf/*/forwarding > /dev/null

Host A configuration:
  ip link set enp0s3 up
  ip -6 addr flush dev enp0s3
  ip -6 addr add ::ffff:5:7:1:2/126 dev enp0s3
  ip -6 route add default via ::ffff:5:7:1:1

Host B configuration:
  ip link set enp0s3 up
  ip -6 addr flush dev enp0s3
  ip -6 addr add ::ffff:5:7:2:2/126 dev enp0s3
  ip -6 route add default via ::ffff:5:7:2:1

I want IP to be a translated address from IPv4 (5.7.2.1 -> ::ffff:5:7:2:1).
The problem:
When I'm trying to ping host A from host B sometimes it pings sometimes it doesn't; from host A to host B the same behavior. When I'm trying to ncat -6 it doesn't work (gateway tcpdump says "Destination host is unreachable"). ping and ncat works only on and from gateway.
Route tables on the gateway:
::ffff:5:7:1:0/126 dev enp0s3 proto kernel metric 256 pref medium
::ffff:5:7:2:0/126 dev enp0s9 proto kernel metric 256 pref medium
fe80::/64 dev enp0s8 proto kernel metric 256 pref medium

The last fe80::/64 records are my ssh connections.
I suppose, the problem is in the route part, but the mystery for me is how to fix it.
EDIT:
I SOLVED my problem, which was in flushing addresses ip -6 addr flush dev enp0s3.

A: IPv4-mapped IPv6 addresses (i.e. addresses of the format ::ffff:192.168.0.1) are not supposed to be used on the wire. They are intended to be used as internal identifiers for IPv4 addresses on dual stack sockets. When a dual stack (IPv6/IPv4) server process accepts a connection on an IPv6 socket from an IPv4 host, say 192.168.0.1, it is internally converted to ::ffff:192.168.0.1.
If a network interface receives a packet with an address of this format, it is a bug if it does not drop it.


text:
Q: Why I have both HWE and non-HWE kernels in Ubuntu 18.04 In Ubuntu 18.04 I have both HWE and non-HWE kernels installed. I only use the HWE kernel (5.0) and in the past I had removed the non-HWE kernel (4.15, both images and headers). However, after some updates I noticed that 4.15 got installed again. Note that after each kernel update I also use apt autoremove to remove the older kernel.
Why is the non-HWE kernel installed again? Can I completely uninstall it? How?
Below are the linux images installed on my pc:
$ dpkg --list | grep linux-image
rc  linux-image-4.15.0-48-generic              4.15.0-48.51                                 amd64        Signed kernel image generic
rc  linux-image-4.15.0-50-generic              4.15.0-50.54                                 amd64        Signed kernel image generic
rc  linux-image-4.15.0-51-generic              4.15.0-51.55                                 amd64        Signed kernel image generic
rc  linux-image-4.15.0-52-generic              4.15.0-52.56                                 amd64        Signed kernel image generic
rc  linux-image-4.15.0-55-generic              4.15.0-55.60                                 amd64        Signed kernel image generic
ii  linux-image-4.15.0-58-generic              4.15.0-58.64                                 amd64        Signed kernel image generic
rc  linux-image-4.18.0-15-generic              4.18.0-15.16~18.04.1                         amd64        Signed kernel image generic
rc  linux-image-4.18.0-18-generic              4.18.0-18.19~18.04.1                         amd64        Signed kernel image generic
rc  linux-image-4.18.0-20-generic              4.18.0-20.21~18.04.1                         amd64        Signed kernel image generic
rc  linux-image-4.18.0-21-generic              4.18.0-21.22~18.04.1                         amd64        Signed kernel image generic
rc  linux-image-4.18.0-22-generic              4.18.0-22.23~18.04.1                         amd64        Signed kernel image generic
rc  linux-image-4.18.0-24-generic              4.18.0-24.25~18.04.1                         amd64        Signed kernel image generic
rc  linux-image-4.18.0-25-generic              4.18.0-25.26~18.04.1                         amd64        Signed kernel image generic
ii  linux-image-5.0.0-23-generic               5.0.0-23.24~18.04.1                          amd64        Signed kernel image generic
ii  linux-image-5.0.0-25-generic               5.0.0-25.26~18.04.1                          amd64        Signed kernel image generic
ii  linux-image-generic                        4.15.0.58.60                                 amd64        Generic Linux kernel image
ii  linux-image-generic-hwe-18.04              5.0.0.25.82                                  amd64        Generic Linux kernel image

And the headers:
$ dpkg --list | grep linux-headers
ii  linux-headers-4.15.0-58                    4.15.0-58.64                                 all          Header files related to Linux kernel version 4.15.0
ii  linux-headers-4.15.0-58-generic            4.15.0-58.64                                 amd64        Linux kernel headers for version 4.15.0 on 64 bit x86 SMP
ii  linux-headers-5.0.0-23                     5.0.0-23.24~18.04.1                          all          Header files related to Linux kernel version 5.0.0
ii  linux-headers-5.0.0-23-generic             5.0.0-23.24~18.04.1                          amd64        Linux kernel headers for version 5.0.0 on 64 bit x86 SMP
ii  linux-headers-5.0.0-25                     5.0.0-25.26~18.04.1                          all          Header files related to Linux kernel version 5.0.0
ii  linux-headers-5.0.0-25-generic             5.0.0-25.26~18.04.1                          amd64        Linux kernel headers for version 5.0.0 on 64 bit x86 SMP
ii  linux-headers-generic                      4.15.0.58.60                                 amd64        Generic Linux kernel headers
ii  linux-headers-generic-hwe-18.04            5.0.0.25.82                                  amd64        Generic Linux kernel headers


text:
Q: Received RunTimeError when using LoadOperation I have receive an Visual Studio Just-In-Time Debugger Error
An Unhandled Exception("Unhandled Error in Silverlight Application
Code: 4004
Category: MangedRuntimeError
Message: System.ServiceMode.DomainServices.Client.DomainOperationException:
once i loaded a line of code as
Public Sub New()
InitializeComponent()
Dim context As New OrganizationContext()
context.Load(context.GetTimeTablesQuery(), AddressOf LoadMonday, Nothing)

End Sub

Private Sub LoadMonday(ByVal obj As LoadOperation(Of TimeTable))

Dim btnMonday(20) As Button
For a As Integer = 0 To 19
            btnMonday(a) = New Button()
            btnMonday(a).Height = 23
            btnMonday(a).Width = 107
            btnMonday(a).Content = timeslot(a)
            btnMonday(a).Background = New SolidColorBrush(Colors.Magenta)

            ' Sets dependency properties
            btnMonday(a).SetValue(Grid.ColumnProperty, 1)
            btnMonday(a).SetValue(Grid.RowProperty, a + 1)
            LayoutRoot.Children.Add(btnMonday(a))
        Next
End Sub

Any Idea ?

A: You can check that your obj has error or not by check it HasError property. If LoadOperation HasError is true you can call MarkErrorAsHandled
Example code:
' if there is an error, mark is as handled.
If (obj.HasError) Then
    obj.MarkErrorAsHandled()
End If


text:
Q: post-hoc custom contrasts - glmmTMB with poly() I need to figure out how to run a set of custom contrasts for a glmmTMB model with a polynomial predictor. I followed the answer given here for allowing glht to work with theglmmTMB model, but I'm still failing, seemingly at two stages:
1) how do I define the contrasts for a polynomial predictor? I need to use the list() approach, since my actual model is quite complex and I'll definitely mess up the matrix approach
2) once the contrasts are set up - how do I run them for glmmTMB specifically?
library(contrast)
library(glmmTMB)

set.seed(1)
df <- structure(list(x = 1:20, y = c(4L, 7L, 11L, 12L, 23L, 21L, 42L,
56L, 70L, 80L, 95L, 120L, 152L, 187L, 224L, 280L, 326L, 374L,
438L, 500L), z = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L), .Label = c("a",
"b"), class = "factor"), group = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), class = "factor", .Label = "1")), class = "data.frame", row.names = c(NA,
-20L))

#just a toy example with a linear model and no poly()
m <- lm(y ~ x * z, data = df)
contrast(m,
        a = list(x = 1, z = "a"),
        b = list(x = 10, z = "b"))

# a (big) simplification of what I'm after:
m1 <- glmmTMB(y ~ poly(x, 3) * z + (1|group), data = df, family = poisson)
contrast(m1,
        a = list(x = 1, z = "a"),
        b = list(x = 10, z = "b"))

EDIT
One addition - since my actual model is zero-inflated, how does this approach handle that? I'm only interested in testing the "response" values (i.e., combined zero-inflation and counts).


text:
Q: When to use Mapper or Record in Lift? I would like to understand what are the use cases, advantages and inconveniences of choosing to use Record , Mapper or even both, in a Liftweb application.
This question came up when I tried to:

*

*create a tree like structure for the model classes

*create a similar tree like structure for rendering of the classes in a page

*ensure different classes in the tree can be in different states at the same time. One is in the EDIT or CREATE state and the other in the VISUALIZE state for example.

*model classes can be created, read or saved to a RESTful Web Service that is already functioning.

I'm putting the use cases here just for the record. You can answer in a more general way.

A: Well, the Mapper and Record libraries are only different abstractions for the database access in Lift applications. Record is the newer one and is considered to substitute Mapper one day. At the moment Record supports NoSQL databases like CouchDB and MongoDB. If your data model fits into the NoSQL world, try Record. Otherwise you can use Mapper in connection with a typical relational database.
I hopefully mentioned some interesting points for you.

A: Mapper has been part of Lift before Lift was Lift.  It's a simple "Active Record" style bridge between the database and Scala.  I built Mapper based on ideas outlined here:
http://web.archive.org/web/20070303054927/http://blog.lostlake.org/index.php?/archives/19-Keeping-the-meaning-with-the-bytes.html
Mapper is intimately tied to JDBC and thus relational databases.  Mapper has a reasonable mechanism for building simple queries, but for complex stuff one has to hand-write SQL.
Mapper is solid but crufty.
Record is a more generic abstraction between backing store and Scala.  It has weaker implementations of the ideas outlined in "Keeping the meaning with the Bytes"... and very few people notice or care.
There are Record implementations for MongoDB, CouchDB, Squeryl and other storage mechanisms.  Writing a new back-end is a few days of work.
Record has a lot of "anomalies" and each back end has its own quirks.  The current Record owner has embarked on a wholesale refactoring of Record.
I do not think either Record or Mapper will give you tree-like structures "out of the box" unless you're using the MongoDB backend and in that case, your tree structures will be based on JSON documents rather than relations.