text:
Q: Case-Insensitive List Search I have a list testList that contains a bunch of strings. I would like to add a new string into the testList only if it doesn't already exist in the list. Therefore, I need to do a case-insensitive search of the list and make it efficient. I can't use Contains because that doesn't take into account the casing. I also don't want to use ToUpper/ToLower for performance reasons. I came across this method, which works:
    if(testList.FindAll(x => x.IndexOf(keyword,
                       StringComparison.OrdinalIgnoreCase) >= 0).Count > 0)
       Console.WriteLine("Found in list");

This works, but it also matches partial words. If the list contains "goat", I can't add "oat" because it claims that "oat" is already in the list. Is there a way to efficiently search lists in a case insensitive manner, where words have to match exactly? thanks

A: I realise this is an old post, but just in case anyone else is looking, you can use Contains by providing the case insensitive string equality comparer like so:
using System.Linq;

// ...

if (testList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Keyword Exists");
}

This has been available since .net 2.0 according to msdn.

A: Instead of String.IndexOf, use String.Equals to ensure you don't have partial matches. Also don't use FindAll as that goes through every element, use FindIndex (it stops on the first one it hits).
if(testList.FindIndex(x => x.Equals(keyword,
    StringComparison.OrdinalIgnoreCase) ) != -1)
    Console.WriteLine("Found in list");

Alternately use some LINQ methods (which also stops on the first one it hits)
if( testList.Any( s => s.Equals(keyword, StringComparison.OrdinalIgnoreCase) ) )
    Console.WriteLine("found in list");

A: Based on Adam Sills answer above - here's a nice clean extensions method for Contains... :)
///----------------------------------------------------------------------
/// <summary>
/// Determines whether the specified list contains the matching string value
/// </summary>
/// <param name="list">The list.</param>
/// <param name="value">The value to match.</param>
/// <param name="ignoreCase">if set to <c>true</c> the case is ignored.</param>
/// <returns>
///   <c>true</c> if the specified list contais the matching string; otherwise, <c>false</c>.
/// </returns>
///----------------------------------------------------------------------
public static bool Contains(this List<string> list, string value, bool ignoreCase = false)
{
    return ignoreCase ?
        list.Any(s => s.Equals(value, StringComparison.OrdinalIgnoreCase)) :
        list.Contains(value);
}

A: You can use StringComparer static variants with the Contains overload from LINQ for example, like this:
using System.Linq;

var list = new List<string>();
list.Add("cat");
list.Add("dog");
list.Add("moth");

if (list.Contains("MOTH", StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("found");
}

A: Based on Lance Larsen answer - here's an extension method with the recommended string.Compare instead of string.Equals

It is highly recommended that you use an overload of String.Compare that takes a StringComparison parameter.   Not only do these overloads allow you to define the exact comparison behavior you intended, using them will also make your code more readable for other developers. [Josh Free @ BCL Team Blog]

public static bool Contains(this List<string> source, string toCheck, StringComparison comp)
{
    return
       source != null &&
       !string.IsNullOrEmpty(toCheck) &&
       source.Any(x => string.Compare(x, toCheck, comp) == 0);
}

A: You're checking if the result of IndexOf is larger or equal 0, meaning whether the match starts anywhere in the string. Try checking if it's equal to 0:
if (testList.FindAll(x => x.IndexOf(keyword,
                   StringComparison.OrdinalIgnoreCase) >= 0).Count > 0)
   Console.WriteLine("Found in list");

Now "goat" and "oat" won't match, but "goat" and "goa" will. To avoid this, you can compare the lenghts of the two strings.
To avoid all this complication, you can use a dictionary instead of a list. They key would be the lowercase string, and the value would be the real string. This way, performance isn't hurt because you don't have to use ToLower for each comparison, but you can still use Contains.

A: Below is the example of searching for a keyword in the whole list and remove that item:
public class Book
{
  public int BookId { get; set; }
  public DateTime CreatedDate { get; set; }
  public string Text { get; set; }
  public string Autor { get; set; }
  public string Source { get; set; }
}

If you want to remove a book that contains some keyword in the Text property, you can create a list of keywords and remove it from list of books:
List<Book> listToSearch = new List<Book>()
   {
        new Book(){
            BookId = 1,
            CreatedDate = new DateTime(2014, 5, 27),
            Text = " test voprivreda...",
            Autor = "abc",
            Source = "SSSS"

        },
        new Book(){
            BookId = 2,
            CreatedDate = new DateTime(2014, 5, 27),
            Text = "here you go...",
            Autor = "bcd",
            Source = "SSSS"

        }
    };

var blackList = new List<string>()
            {
                "test", "b"
            };

foreach (var itemtoremove in blackList)
    {
        listToSearch.RemoveAll(p => p.Source.ToLower().Contains(itemtoremove.ToLower()) || p.Source.ToLower().Contains(itemtoremove.ToLower()));
    }

return listToSearch.ToList();

A: I had a similar problem, I needed the index of the item but it had to be case insensitive, i looked around the web for a few minutes and found nothing, so I just wrote a small method to get it done, here is what I did:
private static int getCaseInvariantIndex(List<string> ItemsList, string searchItem)
{
    List<string> lowercaselist = new List<string>();

    foreach (string item in ItemsList)
    {
        lowercaselist.Add(item.ToLower());
    }

    return lowercaselist.IndexOf(searchItem.ToLower());
}

Add this code to the same file, and call it like this:
int index = getCaseInvariantIndexFromList(ListOfItems, itemToFind);

Hope this helps, good luck!


text:
Q: awakeFromNimb doesn't get called on TableView reloadData Swift I have an iPad TabBar navigation app and in OrderViewController I have a tableview on left side and outlets on the right side of the view as in a sort of split view controller. When you click a tableView's cell it shows details on the other half screen. As I'm introducing two different color schemes for A/B testing, I use a switch to perform the change in color. The color switching dough doesn't succeed with tableView's cells. Adding a reloadData() in viewWillAppeardidn't solve the problem.
Everything gets updated except for the cells, they maintain the colors of when they got created the first time.
I added prints throughout the phases and I detected that cell's awakeFromNimbgets called only the first time. How do I get it to be called on tableView.reloadData()? As always many thanks.
awakeFromNib():
override func awakeFromNib() {
        super.awakeFromNib()
        configureUi()
    }

viewWillAppear():
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.configureFetchedResultsController()
        orderTableView.delegate = self
        orderTableView.dataSource = self
        configureUI()
        orderTableView.reloadData()
    }

A: Use the tableView delegate willDisplayCell
https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614883-tableview
class MyCustomVC: UITableViewDelegate {

    override func tableView(_ tableView: UITableView,
        willDisplay cell: UITableViewCell,
           forRowAt indexPath: IndexPath) {

           guard var cell = tableView.dequeueReusableCell(withIdentifier: "yourReuseIdentifier", for: indexPath) as? YourCustomCell else {
               return UITableViewCell()
           }

           cell.configureUi()
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Something about reading portions of data from file using a C++ istream_iterator Target: There is text file (on HDD) containing integers divided with some kind of delimiter.
Example:
5245
234224
6534
1234

I need to read them into STL container.
int main(int argc, char * argv[]) {
  using namespace std;

  // 1. prepare the file stream
  string fileName;
  if (argc > 1)
    fileName = argv[1];
  else {
    cout << "Provide the filename to read from: ";
    cin >> fileName;
  }
  unique_ptr<ifstream, ifstream_deleter<ifstream>> ptrToStream(new ifstream(fileName, ios::out));
  if (!ptrToStream->good()) {
    cerr << "Error opening file " << fileName << endl;
    return -1;
  }

  // 2. value by value reading will be too slow on large data so buffer data
  typedef unsigned int values_type;
  const int BUFFER_SIZE(4); // 4 is for testing purposes. 16MB or larger in real life
  vector<values_type> numbersBuffer(BUFFER_SIZE);
  numbersBuffer.insert(numbersBuffer.begin(), istream_iterator<values_type>(*ptrToStream), istream_iterator<values_type>());
  // ...

The main drawback of this code is how can I handle the issue when file size is extremely large, so I cannot store all of it's contents in memory ?
I also do not want to use push_back as it is non efficient in comparison to interval insert.

So, the question is: how can I read not more than BUFFER_SIZE elements from the file effectively using STL?

A: The approach to limit reading from input iterators is to create a wrapper which counts the number of elements processed so far and whose end iterator compares to this number. Doing this generically isn't quite trivial, doing it specifically for std::istream_iterator<T> shouldn't be too hard. That said, I think the easiest way to do it is this:
std::vector<T> buffer;
buffer.reserve(size);
std::istreambuf_iterator<T> it(in), end;
for (std::vector<T>::size_type count(0), capacity(size);
     it != end && count != capacity; ++it, ++count) {
    buffer.push_back(*it);
}

I realize that you don't want to push_back() because it is allegedly slow. However, compared to the I/O operation I doubt that you'll be able to measure the small overhead, especially with typical implementation of the I/O library.
Just to round things off with an example of a wrapped iterator: below is an example how a counting wrapper for std::istream_iterator<T> could look like. There are many different ways this could be done, this is just one of them.
#include <iostream>
#include <iterator>
#include <vector>
#include <sstream>

template <typename T>
class counted_istream_iterator:
    public std::iterator<std::input_iterator_tag, T, std::ptrdiff_t>
{
public:
    explicit counted_istream_iterator(std::istream& in): count_(), it_(in) {}
    explicit counted_istream_iterator(size_t count): count_(count), it_() {}

    T const& operator*() { return *this->it_; }
    T const* operator->() { return it_->it_.operator->(); }
    counted_istream_iterator& operator++() {
        ++this->count_; ++this->it_; return *this;
    }
    counted_istream_iterator operator++(int) {
        counted_istream_iterator rc(*this); ++*this; return rc;
    }

    bool operator== (counted_istream_iterator const& other) const {
        return this->count_ == other.count_ || this->it_ == other.it_;
    }
    bool operator!= (counted_istream_iterator const& other) const {
        return !(*this == other);
    }
private:
    std::ptrdiff_t           count_;
    std::istream_iterator<T> it_;
};

void read(int count)
{
    std::istringstream in("0 1 2 3 4 5 6 7 8 9");
    std::vector<int>   vec;
    vec.insert(vec.end(), counted_istream_iterator<int>(in),
               counted_istream_iterator<int>(count));
    std::cout << "size=" << vec.size() << "\n";
}

int main()
{
    read(4);
    read(100);
}

A: There is possible way to solve my problem:
// 2. value by value reading will be too slow on large data so buffer data
typedef unsigned int values_type;
const int BUFFER_SIZE(4);
vector<values_type> numbersBuffer;
numbersBuffer.reserve(BUFFER_SIZE);
istream_iterator<values_type> begin(*ptrToStream), end;
while (begin != end) {
  copy_n(begin, BUFFER_SIZE, numbersBuffer.begin());
  for_each(numbersBuffer.begin(), numbersBuffer.end(), [](values_type const &val){ std::cout << val << std::endl; });
  ++begin;
}

But it has one drawback. If input file contains the following:
8785
245245454545
7767

then 8785 will be read, but 245245454545 and 7767 will not, because 245245454545 cannot be converted to unsigned int. Error will be silent. :(


text:
Q: Resolving "Multiple Jar files" aka "scanned from multiple locations" I am working on a jetty service, and when starting it, I get a lot of:
SomeClass scanned from multiple locations: jar: jar1!Someclass.class, jar2!Someclass.class
So a single class is provided by two jars, and which I get on runtime is undefined, which is not good. Looking at other issues I found that tattletale can help diagnosing the problem. The report, in the Multiple Jar files section lists the same classes as jetty upon startup and which jars they were in.
A subset of the conflicts are:

And looking at
mvn dependency:tree -D verbose

I get:
+- ca.uhn.hapi.fhir:hapi-fhir-jpaserver-base:jar:3.7.0:compile
|  |                   ...
|  +- org.jscience:jscience:jar:4.3.1:compile
|  |  \- org.javolution:javolution:jar:5.2.3:compile

And so it seems that my fhir-base-jpaserver-base dependency pulls jscience that pulls javolution. But jscience and javolution supply some of the same classes. No other dependency to javolution exists.
My question is then, how do I go about solving this?
I could do some  stuff in pom.xml but I suppose jscience needs javolution, and might break?

A: Sounds like a bug in jscience with how they packaged their jar, might want to file an issue with them.
They should either  ...

*

*have a proper/focused jar and dependencies.

*or a standalone uber jar with no dependencies.

Not mixing the two concepts.
Meanwhile, just use the <dependency>/<exclusions> to exclude specific transitive dependencies that are causing you duplicate classes.
Also, you might want to run any of the various duplicate class/resource checker maven plugins to find any other cases you might have present on your project.


text:
Q: Accessing Memory Mapped I/O is slow I have a Terasic-SoCKIT(fpga & arm cortex a9) and I have Linux running on the HPS. I'm trying to access the memory mapped I/O, wrote a simple character driver with functions "request_mem_region" and "ioremap".
The memory mapped IO is an AXI bus, using which I can transmit data to the FPGA. I see that each write is taking almost 6us and for my application I need it to be less than 1us. Also, the driver stops writing to the mapped IO after a few writes(don't see the data being changed in the fpga; is the buffer in the driver getting full??).
The question is am I missing something or because the writes are happening from the virtual address to the physical address it cannot be anymore faster? If the writing from virtual address is slowing down, is there a way to speed it up? I know, that ARM has a DMAC but I haven't explored it yet.
Thank you,
Karthik
I'm sorry, I missed to tell that I was measuring the time in the user space code. Later, I checked the time it took to write in the driver and it was in nanoseconds. So, I figured most of the time taken was for the write from the userspace to kernel.
So, I did some further reading and understood that ioremap() maps the physical address to kernel virtual address and remap_pfn_range() maps the physical address/IO memory to the user virtual space (this is what I need; write to IO memory from user space). And I used the simple mmap example - http://web.cecs.pdx.edu/~jrb/ui/linux/examples.dir/simple/simple.c as the kernel driver. The following code is my userspace code:
    using namespace std;
    #include <iostream>
    #include <sys/mman.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <sys/mman.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <stdint.h>
    #include <ctime>

    #define PAGE_SIZE 4096
    #define HPS2FPGA_BRIDGE_BASE 0xc0000000
    #define BLINK_OFFSET 0x0

    volatile unsigned char *blink_mem;
    void *bridge_map;

    int main()
    {
        int fd, ret = EXIT_FAILURE;
        unsigned int i;
        unsigned char value;
        int dummy;
        off_t blink_base = HPS2FPGA_BRIDGE_BASE;
        clock_t start, stop;
        double duration;

        /* open the memory device file */
        fd = open("/dev/HPS2FPGA", O_RDWR|O_SYNC);
        if (fd < 0) {
            perror("open");
            exit(EXIT_FAILURE);
        }

        /* map the LWHPS2FPGA bridge into process memory */
        bridge_map = mmap(NULL, PAGE_SIZE, PROT_WRITE|PROT_READ|PROT_EXEC, MAP_SHARED,
                    fd, blink_base);
        if (bridge_map == MAP_FAILED) {
            perror("mmap");
            goto cleanup;
        }

        /* get the delay_ctrl peripheral's base address */
        blink_mem = (unsigned char *) (bridge_map + BLINK_OFFSET);

        start = clock();
        /* write the value */
        for(i = 0; i < 1000000; i++)
        {
            *blink_mem = i;
            dummy = *blink_mem;
        }
        stop = clock();
        duration = ( stop - start ) / (double) CLOCKS_PER_SEC;
        printf("%f", duration);

        if (munmap(bridge_map, PAGE_SIZE) < 0) {
            perror("munmap");
            goto cleanup;
        }

        ret = 0;

    cleanup:
        close(fd);
        return ret;
    }

I'm writing to the virtual address space mmap returns and I can verify the write by reading the value at that address but I don't see the value getting updated in the FPGA.
How does the physical address get written when I write to the user virtual space? Is there a way to debug and see if the physical address space is actually being written?

A: OK, it looks like the subject of this question is a furphy ... memory mapped I/O (done correctly) will be as fast as the processor can do it for the hardware being accessed and there will be no overhead for doing this from user mode as opposed to kernel mode (i.e. there is no "write from the userspace to kernel").
However, you still have to think about what is happening when you do a read from or a write to an address (this is where the question moved on to). In most architectures, there are two mappings - the virtual to the physical, and the physical to the device. The first is set up in the virtual memory hardware and the second is set up in the memory controller.
In addition to the mappings, all accesses usually go via cache hardware, so you have to decide whether you want the accesses to be cached or not. If the underlying device being accessed is RAM of some sort, then you usually want accesses to be cached. For other types of devices, generally you don't.
There may be a lot of other things to think about (e.g. whether the VM mapping is resident in the VM hardware, the width and timing of accesses, priority, permissions, etc) but cache is the first.
In @Karthik's case, because he had not turned off cache in his mapping, depending on the type of cache, either an entire cache line was being written when he wrote to the address (write-through), or the write was being delayed (write-back) (if you want some nitty gritty about cache, try this).
To answer the specific (follow up) questions, once the virtual address mapping is done and the cache has done its job, the access goes to the memory controller - this hardware decides which bus and/or device is being accessed and does the "right thing" for that hardware, usually involving asserting a chip select and/or a write enable signal, maybe copying a part or all of the physical address onto address lines, maybe some setup timing, etc.
... and the best way to debug this stuff is to have an analyser of some sort connected to your device or bus, or if this is too difficult/expensive, there might be some support for debugging in the memory controller.
One other minor but important point ... take note of the declaration of blink_mem in the code above - the volatile type qualifier is very important. It tells the compiler not to muck with accesses to the address. In addition to this, you should be aware of any special pipeline instructions to do with memory accesses (check out the eieio instruction in powerpc - someone has a sense of humour :-)
Finally, just to re-iterate what was said in the comments, which turned out to be the real answer to the question, when calling remap_pfn_range() you turn off cache by modifying the page protections specified in the last argument (prot) using the pgprot_noncached() macro. Also read this and this and particularly this. Cheers!


text:
Q: How can I get the tag name in Selenium Python? Is there a way to get the name of the tag of a Selenium web element?
I found, there is .getTagName() in selenium for Java, in How do I get a parent HTML Tag with Selenium WebDriver using Java?.
Example: In this HTML, if I iterate though class='some_class_name', how can I get the tag_name (h2,  p, ul or li)?

Some Random Heading 1

Lorem Ipsum is simply dummy text of the printing and typesetting industry

Some Random Heading 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Random list are:

Lorem

Ipsum

Dolor

The Python code may look like this...
content = driver.find_elements_by_xpath("//div[@class='some_class_name']//child::*")
for c in content:
    print(c.getTagName()) # Something like this to get the
                          # tag of inner content...

A: In Python, you have tag_name to get the tag name.
content = driver.find_elements_by_xpath("//div[@class='some_class_name']//child::*")
for c in content:
    print(c.tag_name)


text:
Q: stop wordpress revision and autosave to page Wordpress revision and autosave is keeping reverting my changes to a wordpress page. No matter how many changes I make always reverting to that point.
Is there some solution to stop doing that but not to disable revision to all site.

A: To Disable Autosave put the code below in your functions.php.
function disableAutoSave(){
     wp_deregister_script('autosave');
}
add_action( 'wp_print_scripts', 'disableAutoSave' );

To Disable Post Revisions put the code below in your wp-config.php file.
define( 'WP_POST_REVISIONS', false ); // no revisions

Note: Using the above code will disable the Autosave and/or Post Revisions
    throughout the site.

A: I believe the correct code should be as above code throws notification messages.
add_action( 'admin_init', 'disable_autosave' );
function disable_autosave() {
    wp_deregister_script( 'autosave' );
}


text:
Q: Solve the following initial value and boundary problem: $u_{tt} -c^{2}u_{xx} = 0$, $00$ with $u(0,t) = a(t)$, $u(L,t) = b(t)$, $t \geq 0$ Solve the following initial value and boundary problem.
$u_{tt} -c^{2}u_{xx} = 0$, $0<x<T$, $t>0$
$u(x,0) = \varphi(x)$, $u_{t}(x,0) = \psi(x)$, $0 \leq x \leq L$
$u(0,t) = a(t)$, $u(L,t) = b(t)$, $t \geq 0$
This problem models the motion of a vibrating string with the initial position given by $\varphi$ and initial velocity given by $\psi$, with free ends whose motion is controlled by functions $a$ at the left end and $b$ at the right end.
I solved this problem in the case in which the vibrating string is fixed at the ends, that is, when $u(0,t) = 0$ and $u(L,t) = 0$. In this case, I obtain the solution in terms of Fourier series and is given by
$$u(x,t) = \left[\sum_{n=1}^{\infty}{a_{n}\cos\left(\frac{n\pi ct}{L}\right) + b_{n}\sin\left(\frac{n\pi ct}{L}\right)}\right]\sin\left(\frac{n\pi x}{L}\right)$$
Where the Fourier coefficients are given by $$a_{n} = \frac{2}{L}\int_{0}^{L}{\varphi(\epsilon)\sin \left(\frac{n\pi \epsilon}{L} \right)}d\epsilon$$ and $$b_{n} = \frac{2}{n\pi c}\int_{0}^{L}{\psi(\epsilon)\sin \left(\frac{n\pi \epsilon}{L} \right)}d\epsilon$$
However, in the general case, when $u(0,t) = a(t)$ y $u(L,t) = b(t)$ I have not been able to find a solution yet.
How can I do this?
I need some help!


text:
Q: array of arrays visual basic I'm developing a module for capture Attlogs from a ZKSoftware Fingerprint Biometric and send it to MySQL database using the SDK that came with the CD, so far I manage to connect successfully to the clock, display the logs on a listview, but I got stuck pushing the values on a multidimensional array, i'm sure it's a matter of declaration but I better ask for help... the code is as follows:
Dim thisLog(1) As String
Dim allLogs()() As String = New String()() {}

afterwards where the iteration (i) load the Attlogs in the listview I got:
            thisLog = {sdwEnrollNumber, idwYear.ToString() & "-" + idwMonth.ToString() & "-" & idwDay.ToString() & " " & idwHour.ToString() & ":" & idwMinute.ToString() & ":" & idwSecond.ToString()}
            allLogs(i) = {thisLog(0), thisLog(1)}

The error I'm getting is related to the size of the array, so the question can be resumed in how can I create a rectangular array (2)(n) with every row of the captured data. Thanks in advance

A: I would highly suggest you create a class to store the data in. Have a List(Of LogEntry) afterward. This would make your code a lot easier to read.
Class LogEntry

    Public Property EnrollNumber As String
    Public Property EntryDate As DateTime

    Public Sub New(ByVal enrollNumber As String, ByVal entryDate As DateTime)

        Me.EnrollNumber = enrollNumber
        Me.EntryDate = entryDate

    End Sub

End Class

For adding a new record, you just need to create an instance of that class and add it to the list.
    Dim allLogs As New List(Of LogEntry)

    allLogs.Add(New LogEntry(sdwEnrollNumber, New DateTime(idwYear, idwMonth, idwDay, idwHour, idwMinute, idwSecond)))

Since you'll now have a valid date instead of a concatenation of string, it'll be easy to do manipulation afterward.
    Console.WriteLine(allLogs(0).EnrollNumber)
    Console.WriteLine(allLogs(0).EntryDate.ToString("yyyy-MM-dd HH:mm:ss"))

A:
how can I create a rectangular array (2)(n) with every row of the captured data?

Use a List:
Dim allLogs As New List(Of String())()

allLogs.Add(New String(1) {sdwEnrollNumber, _
     String.Format("{0}-{1}-{2} {3}:{4}:{5}", _
     idwYear, idwMonth, idwDay, idwHour, idwMinute, idwSecond)} )

I might also use the appropriate DateTime constructor and format string to format that 2nd part, depending on how you get those idw variables in the first place.


text:
Q: Send value of input using a function My application get the data from a input and store it in the state. So, now, when i click on the OK button from the modal, i get the data in the console.
I want to do next thing: when i will click on OK button not only to save the data, but in the same time to send another data, using Link from react router. Something like this:

<Link
    to={{
     pathname: `${my path}/demo}`,
    state: {my another data},
    }}
    >
  Send variable
</Link>

When i put the code above in

const handleOk = e => {
    setState(false);
    return(
       <Link
        to={{
         pathname: `${my path}/demo}`,
        state: {my another data},
        }}
        >
      Send
    )
     </Link>
};

How can i send the variable, through the Link, in my case, using OK button, and handle ok function?
my code: https://codesandbox.io/s/silly-https-bnf3i

A: Like this u can pass any value    onOk={() => handleOk(event, "hello")}

A: const handleOk = (e, text) => {
    setState(false);
    //thing you want to do with text
  };

<Modal
        title="Basic Modal"
        visible={visible}
        onOk={() => handleOk(event, "hello")}
        onCancel={handleCancel}
      >
        <input onChange={input} />
      </Modal>


text:
Q: $f(x)=e^x(x^2-5x+7)$. Calculate $\lim_{n\to\infty}\frac{1}{9^n}\int_{1}^{2}\big((e^x)(x^2-5x+7)\big)^n$ $$f(x)=e^x(x^2-5x+7)$$
Calculate $\lim_{n\to\infty}\frac{1}{9^n}\int_{1}^{2}\big((e^x)(x^2-5x+7)\big)^n$
It is supposed to be $0$. I know that $f(x)$ is decreasing over $(1,2)$ from $3e$ to $e^2$. That means when we raise it to any power it will approach $\infty$. So it is an indeterminate form ($\infty/\infty$). Do I apply L'hospital's Rule? How? Maybe distribute the limit? I would greatly appreciate any help!

A: $f'(x)=e^x (x-1)(x-2) < 0$ for $1<x<2$
Hence $\frac{f(x)}{9} \leq \frac{3e}{9}=\alpha <1$ so that $$
\int_1^2 (\frac{f(x)}{9})^n <\alpha^n\rightarrow 0$$

A: Hint:

*

*$$\int_{a}^b g(x)dx \leq (b-a)\cdot\max_{x\in[a, b]} g(x)$$

*if $0\leq a_n\leq b_n$ and $\lim_{n\to\infty} b_n=0$, what can you say about $\lim_{n\to\infty} a_n$?

*$$|\alpha|<9\implies \lim_{n\to\infty}\frac{\alpha^n}{9^n}=0$$


text:
Q: MultiAutoCompleteTextView custom adapter with custom object instead of String Object This code is working fine as I want only when I pass ArrayList<String> to the adapter. But when I add my object to adapter, in MultiAutoCompleteTextView it set object full name instead of object full name. I want only first_name from my JGETDATA object.
public class MyAutoComplete extends MultiAutoCompleteTextView implements OnItemClickListener {

    private final String TAG = "ChipsMultiAutoCompleteTextview";

    private Handler mHandler = new Handler()
    {
        public void handleMessage(Message paramAnonymousMessage)
        {
            if (paramAnonymousMessage.what == 0)
            {
                mHandler.removeMessages(0);
                String str = getText().toString().trim();
                Log.e("handler", "yes");

                if (str.length() >= 2) {

                    if(getText().toString().contains(",")) // check comman in string
                    {

                        String chips[] = getText().toString().trim().split(",");

                        Log.e("String", ""+chips[chips.length -1].trim());

                        makeAutoSearchText(chips[chips.length -1].trim());
                    }else{
                        makeAutoSearchText(str);
                    }
                }
            }
        }
    };
    @SuppressLint("NewApi")
    private void makeAutoSearchText(String paramString)
    {

        Log.e("makeAuto", "Yes");

        String[] ids={"search_name"};
        String[] params={paramString};

        GetDataTask getDataTask= new GetDataTask(ids, params);

        getDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    }

    public class GetDataTask extends AsyncTask<Void, Void, Void>{

        private String[] ids;
        private String[] params;
        private JGetDataList jGetDataList;
        private ArrayList<JGetData> updatedList;

        public GetDataTask( String[] ids, String[] params) {
            // TODO Auto-generated constructor stub
            this.ids=ids;
            this.params=params;
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            String response=Profiles.getDataFromServer(ids, params, "http://stopnswap.com/service/getAllUserlist.php");

            jGetDataList=Profiles.parseAllUserData(response);
            if(jGetDataList != null){
                if(jGetDataList.Success != null){
                    //      adapterList.clear();
                    updatedList= new ArrayList<JGetData>();
                    for(JGetData jGetData : jGetDataList.Success){
                        updatedList.add(jGetData);

                        //      adapterList.add(jGetData);
                        //  Log.e("name",jGetData.name );
                    }
                }else{
                    //  adapterList.clear();
                }
            }

            Log.e("Data", ""+response);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if(updatedList != null){
                ((SearchListAdapter)getAdapter()).setContactList(updatedList);
            }
            //  adapter.notifyDataSetChanged();

        }

    }

    TextWatcher searchViewTextWatch = new TextWatcher()
    {
        public void afterTextChanged(Editable paramAnonymousEditable) {}

        public void beforeTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {}

        public void onTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3)
        {
            String str=null;
            if (paramAnonymousCharSequence != null)
            {
                str = paramAnonymousCharSequence.toString().trim();
                if (str.length() < 2) {
                    //  break label99;
                }
                mHandler.removeMessages(0);
                Message localMessage = Message.obtain(mHandler, 0, str);
                mHandler.sendMessageDelayed(localMessage, 400L);
            }
            while (str.length() >= 1)
            {
                //      HomeSearchForMedicineScreen.this.mImageSearch.setVisibility(8);
                //       HomeSearchForMedicineScreen.this.mImageCross.setVisibility(0);
                return;
                //        label99:
                //      if ((HomeSearchForMedicineScreen.this.mSearchView.getAdapter() instanceof AutoCompleteSearchAdapter)) {
                //        HomeSearchForMedicineScreen.this.mAutoCompleteAdapter.notifyDataSetInvalidated();
                //     }
            }
            //     HomeSearchForMedicineScreen.this.mImageSearch.setVisibility(0);
            //     HomeSearchForMedicineScreen.this.mImageCross.setVisibility(8);
        }
    };

    /* Constructor */
    public MyAutoComplete(Context context) {
        super(context);
        init(context);
    }
    /* Constructor */
    public MyAutoComplete(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    /* Constructor */
    public MyAutoComplete(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }
    /* set listeners for item click and text change */
    public void init(Context context){
        setOnItemClickListener(this);
        addTextChangedListener(searchViewTextWatch);

         this.setThreshold(1);
            this.setTokenizer(new CustomCommaTokenizer());
    }
    /*TextWatcher, If user type any country name and press comma then following code will regenerate chips */
    /*private TextWatcher textWather = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(count >=1){
                if(s.charAt(start) == ',')
                    setChips(); // generate chips
            }
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
        @Override
        public void afterTextChanged(Editable s) {}
    };
     */

    public class CustomCommaTokenizer extends CommaTokenizer{
        @Override
        public CharSequence terminateToken(CharSequence text) {
            CharSequence charSequence = super.terminateToken(text);
            return charSequence.subSequence(0, charSequence.length()-1);
        }
    }

    /*This function has whole logic for chips generate*/
    public void setChips(){
        if(getText().toString().contains(",")) // check comman in string
        {

            SpannableStringBuilder ssb = new SpannableStringBuilder(getText());
            // split string wich comma

            Log.e("Auto", getText().toString().trim());

            String chips[] = getText().toString().trim().split(",");
            int x =0;
            // loop will generate ImageSpan for every country name separated by comma
            for(String c : chips){
                // inflate chips_edittext layout
                LayoutInflater lf = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
                TextView textView = (TextView) lf.inflate(R.layout.textview, null);
                textView.setText(c); // set text
                //      setFlags(textView, c); // set flag image
                // capture bitmapt of genreated textview
                int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
                textView.measure(spec, spec);
                textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
                Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(),Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(b);
                canvas.translate(-textView.getScrollX(), -textView.getScrollY());
                textView.draw(canvas);
                textView.setDrawingCacheEnabled(true);
                Bitmap cacheBmp = textView.getDrawingCache();
                Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
                textView.destroyDrawingCache();  // destory drawable
                // create bitmap drawable for imagespan
                BitmapDrawable bmpDrawable = new BitmapDrawable(viewBmp);
                bmpDrawable.setBounds(0, 0,bmpDrawable.getIntrinsicWidth(),bmpDrawable.getIntrinsicHeight());
                // create and set imagespan
                ssb.setSpan(new ImageSpan(bmpDrawable),x ,x + c.length() , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                setMovementMethod(LinkMovementMethod.getInstance());
                ClickableSpan clickSpan = new ClickableSpan() {

                    @Override
                    public void onClick(View view) {
                    //  deleteString();
                    //  Toast.makeText(this, "Hi", Toast.LENGTH_SHORT).show();
                        Log.e("Clic", "cl");

                        deleteString();
                    }

                };
                ssb.setSpan(clickSpan,x, x + c.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                x = x+ c.length() +1;
            }
            // set chips span
        //  setText(ssb);
            // move cursor to last
        //  setSelection(getText().toString().length());

            setSpannableText(ssb);
        }

    }
    public void setSpannableText(final Spannable ssb){
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                setText(ssb);
                setSelection(getText().toString().length());

            }
        }, 20);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    //  String myString= getText().toString() +"," +((JGetData)parent.getItemAtPosition(position)).first_name;

    //  setText(myString);
        setChips(); // call generate chips when user select any item from auto complete

        //  Contact contact = (Contact) parent.getItemAtPosition(position);
    //  SmsUtil.selectedContact.put(contact.num, contact.contactName);
    //  Compose.selectedContact.put(key, value)

    }

    private void deleteString(){
        int[] startEnd = getSelectionStartAndEnd();
        int i = startEnd[0];
        int j = startEnd[1];
        //isTextDeletedFromTouch = true;
    //  isTextAdditionInProgress = true;

        final SpannableStringBuilder sb = new SpannableStringBuilder(this.getText()
            );

        String deletedSubString = sb.subSequence(Math.min(i, j),
                Math.max(i, j)).toString();
    //  deleteFromHashMap(deletedSubString);

        boolean hasCommaAtLast = true;
        try {
            sb.subSequence(Math.min(i, j + 1), Math.max(i, j + 1))
                    .toString();
        } catch (Exception e) {
            hasCommaAtLast = false;
        }

        sb.replace(Math.min(i, hasCommaAtLast ? j + 1 : j),
                Math.max(i, hasCommaAtLast ? j + 1 : j), "");

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setText(sb);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub

                    //  isTextAdditionInProgress = false;
                    //  stringLength = CustomMultiAutoCompleteTextView.this.getText().toString().length();
                    //  isTextDeletedFromTouch = false;
                        //Log.i("I am replacing text","I am replacing text 4");
                        setMovementMethod(LinkMovementMethod.getInstance());
                    }
                },50);

            }
        }, 10);
    //    setChips();
    }

    private int[] getSelectionStartAndEnd(){
        int[] startEnd = new int[2];
        startEnd[0] = this.getSelectionStart()<0?0:this.getSelectionStart();
        startEnd[1] = this.getSelectionEnd()<0?0:this.getSelectionEnd();
        return startEnd;
    }
}

My Adapter
public class SearchListAdapter extends ArrayAdapter<JGetData>{

    private Context context;
    private ArrayList<JGetData> list;

    public SearchListAdapter(Context context, ArrayList<JGetData> list) {
        // TODO Auto-generated constructor stub
        super(context,  android.R.layout.simple_dropdown_item_1line,list);
        this.context=context;
        this.list=list;

    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }
    @Override
    public JGetData getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @SuppressWarnings("unchecked")
    public void setContactList(ArrayList<JGetData>list) {
        // this isn't the efficient method
        // need to improvise on this
        this.list = list;
    //  this.cloneContactList = (ArrayList<Contact>) this.contactList.clone();
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        Holder holder;
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.item_search_list, null);
            holder= new Holder();

            holder.Name=(TextView)convertView.findViewById(R.id.item_Search_list_Name);

            convertView.setTag(holder);
        }else{
            holder=(Holder)convertView.getTag();
        }

        holder.Name.setText(""+list.get(position).first_name);

    //  Log.e("Adapter", ""+list.get(position).first_name);

        return convertView;

    }

    private class Holder{

        public TextView Name;

    }

}

A: The right way to achieve that is implement Filterable interface with your adapter. Implement method getFilter() which will return your own implementation of convertResultToString(Object resultValue) method.


text:
Q: Vb.net image effect / colormatrix I'm currently using colormatrix in vb.net to apply filter like effects e.g negative, hue and brightness etc..
My question is, is colormatrix the best way to do this? Or is there another better way? Thanks


text:
Q: Refresh a remote URL with Gulp I have a gulp task that uploads changed files via FTP, and I'd like it to also trigger a refresh in my browser window. I know there are ways to do this for local sites with modules like browser-sync and live-reload, but I can't seem to find anything that would let me refresh a remote site. It's a minor thing, but it'd be such a nice little convenience.
Is this even possible?


text:
Q: observer is not firing on server but fired on local I had a look around the site but can't find any existing threads would solve my problem. I have an extension to exclude some products and categories before rendering the sitemap.xml. I use Mage::log to record if those methods are fired.
While I tested on local machine, everything works fine. They correctly excluded some specified categories and products and also generated log files in /var/log folder.
When I deployed the codes onto the server, only method beforeLoadLayout worked and logs generated.
The methods excludeProductsFromSitemap and excludeCategoriesFromSitemap are not working at all. Neither logs generate.

*

*Cache is flushed every time I update codes

*Compilation is always disabled

Here is my config.xml
<?xml version="1.0"?>
<config>
<modules>
    <My_Ext>
        <version>0.1.2</version>
    </My_Ext>
</modules>
<global>
    <!-- models -->
    <models>
        <myext>
            <class>My_Ext_Model</class>
        </myext>
    </models>
    <!-- helpers -->
    <helpers>
        <myext>
            <class>My_Ext_Helper</class>
        </myext>
    </helpers>
    <events>
        <sitemap_products_generating_before>
            <observers>
                <myext>
                    <class>myext/observer</class>
                    <method>excludeProductsFromSitemap</method>
                </myext>
            </observers>
        </sitemap_products_generating_before>
        <sitemap_categories_generating_before>
            <observers>
                <myext>
                    <class>myext/observer</class>
                    <method>excludeCategoriesFromSitemap</method>
                </myext>
            </observers>
        </sitemap_categories_generating_before>
    </events>
</global>
<frontend>
    <events>
        <core_block_abstract_prepare_layout_before>
            <observers>
                <myext>
                    <type>model</type>
                    <class>myext/observer</class>
                    <method>beforeLoadLayout</method>
                </myext>
            </observers>
        </core_block_abstract_prepare_layout_before>
    </events>
</frontend>

I also tried other way to write the <events> like below but result is the same as above:
    <events>
        <sitemap_products_generating_before>
            <observers>
                <myext>
                    <class>My_Ext_Model_Observer</class>
                    <method>excludeProductsFromSitemap</method>
                </myext>
            </observers>
        </sitemap_products_generating_before>
        <sitemap_categories_generating_before>
            <observers>
                <myext>
                    <class>My_Ext_Model_Observer</class>
                    <method>excludeCategoriesFromSitemap</method>
                </myext>
            </observers>
        </sitemap_categories_generating_before>
    </events>

Here is my Observer.php:
<?php
class My_Ext_Model_Observer {
public function excludeCategoriesFromSitemap( Varien_Event_Observer $observer ) {
    Mage::log( 'in excludeCategoriesFromSitemap', null, '000_debug.log' );
    $event      = $observer->getEvent();
    $collection = $event->getCollection();
    $items      = $this->getFilteredItems( $observer, 'category' );
    $collection->setItems( $items );
}

public function excludeProductsFromSitemap( Varien_Event_Observer $observer ) {
    Mage::log( 'in excludeProductsFromSitemap', null, '000_debug.log' );
    $event      = $observer->getEvent();
    $collection = $event->getCollection();
    $items      = $this->getFilteredItems( $observer, 'product' );
    $collection->setItems( $items );
}

private function getFilteredItems( $observer, $type ) {
    // Not called by event directly and works fine so not copied
    return $items;
}

public function beforeLoadLayout( Varien_Event_Observer $observer ) {
    Mage::log( 'in beforeLoadLayout', null, '000_debug.log' );
    // Works find on local and server so not copied
}

}
I also tried to writing the class like class My_Ext_Model_Observer extends Mage_Core_Model_Observer but problem remains the same.
I appreciate if anyone can come up with anything I haven't tried. Lots of thanks.

A: I found the solution with @adarsh-khatri's help.
First of all, using <rewrite> instead of firing an <event> before rendering the sitemap.xml. So I removed the events and methods then added rewrite as below:

app/code/local/My/Ext/config.xml

<conig>
...
<global>
    <!-- models -->
    <models>
        <canoupdater>
            <class>My_Ext_Model</class>
        </canoupdater>
        <sitemap_resource>
            <rewrite>
                <catalog_category>My_Ext_Model_Resource_Catalog_Category</catalog_category>
            </rewrite>
        </sitemap_resource>
        <sitemap_resource>
            <rewrite>
                <catalog_product>My_Ext_Model_Resource_Catalog_Product</catalog_product>
            </rewrite>
        </sitemap_resource>
    </models>
...
</global>
...
</config>

I then added two files:

app/code/local/My/Ext/Model/Resource/Catalog/Category.php

<?php
class My_Ext_Model_Resource_Catalog_Category extends Mage_Sitemap_Model_Resource_Catalog_Category {
/**
 * Get category collection array
 *
 * @param int $storeId
 * @return array
 */
public function getCollection( $storeId ) {
    /* @var $store Mage_Core_Model_Store */
    $store = Mage::app()->getStore($storeId);
    if (!$store) {
        return false;
    }

    $this->_select = $this->_getWriteAdapter()->select()
        ->from($this->getMainTable())
        ->where($this->getIdFieldName() . '=?', $store->getRootCategoryId());

    $categoryRow = $this->_getWriteAdapter()->fetchRow($this->_select);
    if (!$categoryRow) {
        return false;
    }

    $this->_select = $this->_getWriteAdapter()->select()
        ->from(array('main_table' => $this->getMainTable()), array($this->getIdFieldName()))
        ->where('main_table.path LIKE ?', $categoryRow['path'] . '/%');

    $storeId = (int)$store->getId();

    /** @var $urlRewrite Mage_Catalog_Helper_Category_Url_Rewrite_Interface */
    $urlRewrite = $this->_factory->getCategoryUrlRewriteHelper();
    $urlRewrite->joinTableToSelect($this->_select, $storeId);

    $this->_addFilter($storeId, 'is_active', 1);

    $entries = $this->_loadEntities();
    foreach ( $entries as $k => $v ) {
        $obj = Mage::getModel( 'catalog/category' )->load( $k );
        if ( // My logic is true ) {
            unset( $entries[$k] ); // Remove this entry from the array
        }
    }
    return $entries;
}

app/code/local/My/Ext/Model/Resource/Catalog/Product.php

<?php
class My_Ext_Model_Resource_Catalog_Product extends Mage_Sitemap_Model_Resource_Catalog_Product {
/**
 * Get product collection array
 *
 * @param int $storeId
 * @return array
 */
public function getCollection( $storeId ) {
    /* @var $store Mage_Core_Model_Store */
    $store = Mage::app()->getStore($storeId);
    if (!$store) {
        return false;
    }

    $this->_select = $this->_getWriteAdapter()->select()
        ->from(array('main_table' => $this->getMainTable()), array($this->getIdFieldName()))
        ->join(
            array('w' => $this->getTable('catalog/product_website')),
            'main_table.entity_id = w.product_id',
            array()
        )
        ->where('w.website_id=?', $store->getWebsiteId());

    $storeId = (int)$store->getId();

    /** @var $urlRewrite Mage_Catalog_Helper_Product_Url_Rewrite_Interface */
    $urlRewrite = $this->_factory->getProductUrlRewriteHelper();
    $urlRewrite->joinTableToSelect($this->_select, $storeId);

    $this->_addFilter($storeId, 'visibility',
        Mage::getSingleton('catalog/product_visibility')->getVisibleInSiteIds(), 'in'
    );
    $this->_addFilter($storeId, 'status',
        Mage::getSingleton('catalog/product_status')->getVisibleStatusIds(), 'in'
    );

    $entries = $this->_loadEntities();
    foreach ( $entries as $k => $v ) {
        $obj = Mage::getModel( 'catalog/product' )->load( $k );
        if ( // If my logic is true ) {
            unset( $entries[$k] ); // Remove the entry from the array
        }
    }
    return $entries;
}

This solved my problem and I hope this would help others who have the similar problems.


text:
Q: Are async functions that are used inside event listeners bottlenecked by the event themselves? Assume I have a function that logs to the console after each input. The usage of this is, for example, appending items to a list then setting a timer for them to be removed.

const getRandomInt = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const button = document.querySelector('#click-me');

async function removeSomething(after) {
  setTimeout(() => {
    console.log('I fired after' + after.toString());
  }, after);
}

button.addEventListener('click', () => {
  removeSomething(getRandomInt(500, 2500));
});
<button id="click-me">Click me.</button>

When I declare a function async, I assume it scopes out of the main event and is able to run behind to allow other things to run, but the thing is, if that function is used within an event listener, assume I clicked that button 50 times a second, what would be the bottle-neck? The CPU that can't handle the 50 click events or my function?
I'm trying to understand the interaction between blocking & non-blocking code.

A:
When I declare a function async, I assume it scopes out of the main event and is able to run behind to allow other things to run

No! There is no such thing as a "background". JS is single threaded². Making the function async is a no op here. It doesn't change anything.

if that function is used within an event listener, assume I clicked that button 50 times a second, what would be the bottle-neck? The CPU that can't handle the 50 click events or my function?

Um, all the code you write runs on your CPU?

I'm trying to understand the interaction between blocking & non-blocking code.

All code you write runs on the only thread JS has. Therefore all the code you write blocks that thread. If you however start an asynchronous task, the engine will offload that (the task, not your handler) to another thread / hardware that is out of your reach, therefore attaching a callback or await ing a promise is non-blocking, as execution of the current code ends, the engine can execute other code, and then if the async task finishes, it runs the callback or continues the async function execution (which itself is blocking too).

Example 1: A callback from a timer:
  console.log(1);
  setTimeout(() => console.log(3), 1000);
  console.log(2);

 // Chain of actions:
 // Execution of the global scope:
 console.log(1);
 setTimeout(/*...*/, 1000); // Send timer task to some underlying mechanism, e.g. hardware timers
 console.log(2);
 // Execution of global scope ends

 // Engine goes on with other stuff

 // Timer finishes, callback gets called:
 (() => console.log(3))()
 // Callback ends

Example 2: Awaiting a fetch call:
  (async function task() {
     const req = await fetch("http://example.com");
     const result = await req.json();
  })();

  // Chain of actions:
 // Execution of the global scope
 (async function task() {
    /* halted here */ await fetch("http://example.com"); // Offloaded to some IO thread
    // Implicitly return promise
 })();
 // Execution of global scope ends

 // Engine goes on with other stuff

 // Response arrived from the server via some IO thread, execution continues:
    const req = /*the result*/
    /*halted*/ await req.json();
 // Execution ends

 // Engine goes on with other stuff

 // Response parsed, execution continues
 const result = /*the result*/
 return result; // Promise resolves
 // Execution ends

² Actually it isn't, it does however have an "observably synchronous execution model". "JS is single threaded" is the (over)simplified version of that


text:
Q: Pass Crystal parameter from main report to command object I find lots of info about passing parameter into subreport, but nothing about passing it from main report into command object in main report.  (This is the closest I could find.)
The command object received from the vendor (names changed to reduce length) contains
left join LOC L on L.ID = P.Loc_ID

We add parameter "Area" to the main report.  {?Area} does what we expect in formulas, but it won't work in a record selection because it can't be matched to anything coming out of the command object.  If I replace table LOC in the cited line as
left join **(select * from LOC where A = {?Area})** L on L.ID = P.Loc_ID

then SQL Server complains of "syntax error, permission violation, or other nonspecific error" [sic]
If I create the parameter in the command object editor (even though it already exists outside), then the whole Crystal IDE crashes!
The command object already has parameters that it magically gets from the main report.  Must I remove it from the main report (proctalgia) before adding it to the command object?  I can't find anything on any menus to link the two parameters together, like I can for a subreport.
Version 2008, if that matters.

A: If you are using an SQL command, don't create the parameters in the main report.  The window where you put your SQL has a section called Parameter List.  Create all your parameters relating to the query there and it will be transfered to the main report.
In your coding you have {?Area}, create a parameter with the name Area.
I found a video demonstrating it.  It's an old version of Crystal Reports but still works the same.
http://www.youtube.com/watch?v=BHNHsIUbcn8

A: I found creating the command object and the parameter FIRST is the key.  The parameter (say it is InstNo), is then created in the subreport.  You can then use "Change SubReport Links" (right click on the subreport), and select that parameter as the parameter to link to.  So basically do it backwards, create the command object first, then link it back to the main report.  For whatever reason if you do it the other way it does not work (even if the name is the same).  Just my experience.


text:
Q: Express $f (z) = u + iv$ as a function of $ z = x + iy$? I have $u(x,y)=\sin(x)\cosh(y)$ and I got conjugate harmonic of $u(x,y)$ as $v(x,y) = \cos(x)\sinh(y)+c$.
So,
$f(z) = \sin(x)\cosh(y)+\mathrm i(\cos(x)\sinh(y)+c)$.
How to express $f(z) = u + iv$ as a function of $z = x + iy$ ?

A: Note that $\cos(ix)=\cosh(x)$ and $\sin(ix)=i\sinh(x)$, so that
$$f(z) = \sin(x)\cosh(y)+ i(\cos(x)\sinh(y)+c)=\sin(x)\cos(iy)+ \cos(x)\sin(iy)+ic$$
$$=\sin(x+iy)+ic=\sin(z)+ic$$

A: In this case the answer is $f(z)=\sin(z)=\frac{\mathrm e^{\mathrm iz}-\mathrm e^{-\mathrm iz}}{2\mathrm i}$.

A: The following identities hold:
\begin{align}
\sin(x) &= \frac1{2i}(\exp(ix)-\exp(-ix)) \\
\cosh(x) &=\frac12(\exp(x)+\exp(-x)) \\
\cos(x) &= \frac12(\exp(ix)+\exp(-ix)) \\
\sinh(x) &=\frac12(\exp(x)-\exp(-x))
\end{align}
Thus we have
\begin{align}
\sin(x)\cosh(y)& = \frac1{4i}(\exp(ix)-\exp(-ix))(\exp(y)+\exp(-y)) \\
i(\cos(x)\sinh(y))&=\frac{1}{4i}(\exp(ix)+\exp(-ix))(\exp(y)-\exp(-y))
\end{align}
And finally
\begin{align}
&\sin(x)\cosh(y)
+i(\cos(x)\sinh(y))\\
&=\frac{1}{4i}
(\exp(ix)\exp(y)+\exp(ix)\exp(-y)-\exp(-ix)\exp(y)-\exp(-ix)\exp(-y) \\
 &\quad +\exp(ix)\exp(y)+\exp(-ix)\exp(y)-\exp(ix)\exp(-y)-\exp(-ix)\exp(-y))\\
&=\frac1{4i}(2\exp(ix)\exp(y)-2\exp(-ix)\exp(-y)) \\
&= \frac{1}{2i}(\exp(y+ix)-\exp(-(y+ix))) \\
&=\sin(y+ix) = \sin(z)
\end{align}


text:
Q: How to import a TypeScript file as a library? So I have a personal "library" that I made that I call methlib, and I have it stored as a .ts file on my computer. Inside it tons of classes, interfaces, functions, etc. that I use a bunch and I like to just have in one place. Now my problem is I want to use the functions and stuff from there in another project that I have that I am making in typescript (as one would usually want to do with a library) but I don't know how. Before I had translated it into typescript I could just include it in the HTML file (usually by just going up into my main web directory and grabbing the local file so that if I made any changes to it it would take effect immediately) but now I don't know what to do. I am also not very familiar (at all) with any of the terminology and I am very new to typescript and more advanced javascript or web development at all. Now when I try to grab something from my library like
import { Collider } from "Methlib/methlib"

with my webpack config (which I mostly stole from a template and don't fully understand) set up like
const path = require('path');
module.exports = {
    entry: "./src/script.ts",
    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, 'dist')
    },
    resolve: {
        extensions: [".webpack.js", ".web.js", ".ts", ".js"],
        alias: {
            Methlib: "./../Methlib-js/"
        }
    },
    module: {
        rules: [{ test: /\.ts$/, loader: "ts-loader" }]
    }
}

with a file structure like
<root>
 | Methlib-js
 | | methlib.ts
 | <project folder>
 | | node_modules
 | | src
 | | | script.ts
 | | webpack.config.js
 | | package.json
 | | package-lock.json

running >node_modules\.bin\webpack gives me
ERROR in <root>\<project folder>\src\script.ts
./src/script.ts
[tsl] ERROR in <root>\<project folder>\src\script.ts(5,26)
      TS2307: Cannot find module 'Methlib/methlib' or its corresponding type declarations.

Also please mind the whole  and  thing, it's just so that I don't have to reveal my exact file structure where it isn't completely necessary. I would like to clarify that  isn't actually part of the project, just the root of my file structure.

A: You need to specify the path mapping for ts as well:
{
  "compilerOptions": {
    "baseUrl": ".", // This must be specified if "paths" is.
    "paths": {
      "Methlib": ["../Methlib-js/methlib.ts"] // This mapping is relative to "baseUrl"
    }
  }
}

Repl.it

A: The solution was to specify the full absolute path to the library in the webpack.config.js file, and upon further testing it would seem that you don't even need to include the path mapping in the tsconfig.json file either.


text:
Q: How might I take two random records from a list using Linq? How might I take two random records from a list using Linq?

A: Random rnd = new Random();
var sequence = Enumerable.Range(1, 2).Select(n => lst[rnd.Next(0, lst.Count)]).ToList();

A: For Linq-to-Objects and EF4 it's pretty simple
db.Users.OrderBy(r => Guid.NewGuid()).Take(2)

For Linq-to-SQL You can check this article
http://michaelmerrell.com/2010/03/randomize-result-orders-in-t-sql-and-linq-to-sql/
Add function Random mapped to SQL function NEWID to DataContext.
partial class DataContext
{
    [Function(Name = "NEWID", IsComposable = true)]
    public Guid Random()
    {
        throw new NotImplementedException();
    }
}

Usage
var qry = from row in DataBase.Customers
          where row.IsActive
          select row;

int count = qry.Count();
int index = new Random().Next(count);

Customer cust = qry.Skip(index).FirstOrDefault();

A: There is no direct way. You can try this, not pretty though.
int randomRecord = new Random().Next() % List.Count(); //To make sure its valid index in list
var qData = List.Skip(randomRecord).Take(1);
var qValue = qData.ToList().First();

A: This is what ended up working for me, it ensures no duplicates are returned:
public List<T> GetRandomItems(List<T> items, int count = 3)
{
    var length = items.Count();
    var list = new List<T>();
    var rnd = new Random();
    var seed = 0;

    while (list.Count() < count)
    {
        seed = rnd.Next(0, length);
        if(!list.Contains(items[seed]))
            list.Add(items[seed]);
    }

    return list;
}

A: Why do you want to use Linq to get two random records?
Create a Random instance and get two random number whose values are less than the length of the list.
List has Indexer property, so doing List[index] is not costly.
Keep it simple. Always prefer readability. If you just make things complicated, the programmers who are going to maintain your code will have hard time.
I am just curious to know why exactly you want to do this in Linq? That just seems like a overhead to me.
am I missing something?


text:
Q: How to set default value for input with type of date in jquery repeater? I use jquery repeater in my project. When I try set default value for input type date return error:

jquery.repeater.js:688 Uncaught TypeError: Cannot read property 'set'
  of undefined

Form code:
<form action="" class="repeater" enctype="multipart/form-data">
  <div data-repeater-list="users">
    <div data-repeater-item>
      <input type="text" name="name"/>
      <input type="email" name="email"/>
      <select name="sex">
        <option value="0" selected>Male</option>
        <option value="1">Female</option>
      </select>
      <input type="date" name="birthday"/>
      <input data-repeater-delete type="button" value="Delete"/>
    </div>
  </div>
  <input id="add" data-repeater-create type="button" value="Add User"/>
</form>

Javascript code:
$(document).ready(function () {
    'use strict';
    $('.repeater').repeater({
        defaultValues: {
            'name': 'User',
            'email': 'user@gmail.com',
            'sex': '0',
            'birthday': "1990-09-10"
        },
        show: function () {
            $(this).slideDown();
        },
        hide: function (deleteElement) {
            if(confirm('Are you sure you want to delete this element?')) {
                $(this).slideUp(deleteElement);
            }
        },
        ready: function (setIndexes) {

        }
    });
    $('#add').on('click', function(e){
      var users = $('.repeater').repeaterVal();
      console.log(users);
    });
});

When I don't set default value then I can't get all fields values.

A: For me I did it the old fashioned way using JQuery
 $(".mydiv-item-repeater").length && $(".mydiv-item-repeater").repeater({
            show: function () {
             $(this).find(".select").val(value);
                $(this).slideDown()
            }, hide: function (e) {
                $(this).slideUp(e)
            }
        });


text:
Q: Xamarin.iOS app - slower on iOS10 than iOS9 Our app has some performance issues. One particular area is the opening of a UITabBarController.
I have tested the app with Debug and Ad-Hoc builds built with VS 2015. I am using

*

*Xamarin 4.5

*Xamarin.iOS 10.10.0

I am testing on real devices

*

*iPhone 6 iOS 10.1.1

*iPhone 6 iOS 9.2

*Pad Air 2 iOS 9.3.1

*iPhone 5 iOS 10

I am seeing consistent and significant performance gains from the iOS 9 devices.
With the Ad-Hoc build, opening of the view, with a large dataset, takes just under 6 seconds (5.8). Opening the same View with the same data and same build takes just over 1 second on the iOS9 devices.
Can anyone suggest why iOS9 would be performing so much better?
We do not have anything that runs on iOS 10 only. The closest we have to that are calls like this:
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))

However that check would return true for 9 and 10.


text:
Q: Only the homepage redirects to www, the internal pages throw an error I have an issue with this Wordpress website:
http://www.pitahouse.com/
I want all the pages to redirect to the www version. Unfortunately, I can't accomplish this. Right now, only the homepage redirects to its www version (if I type pitahouse.com in the browser it will redirect to www). Whenever I try to type the path to an internal page in the browser without www (pitahouse.com/catering/), it throws either 404 or 403 error instead of redirecting to the www version.
I've tried all the solutions I could find, like adding these code snippets and similar to .htaccess:
RewriteEngine on

RewriteCond %{HTTP_HOST} ^example.com [NC]

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

But none of those have worked.
Do you have any idea what might be causing this issue and how can it be fixed?

A: It looks like the domains pitahouse.com and www.pitahouse.com are somehow hosted in different servers. When you ping for them, you get different IPs. See below:


text:
Q: Вопрос по корректировке скрипта Postgresql Пишу скрипт, который бы выводил список пользователей, у которых есть дубликаты учетных записей (с одного ip и устройства авторизация). Мне нужно, чтобы в выборку попадал только список тех пользователей, у которых дубликаты свежие (т.е. созданы недавно, за последний месяц).
Никак не могу понять, как встроить.
select
distinct user_id,
  status, created_at

from ...

where
  users.created_at >= (current_date - 2)

and (ip, device)
IN

(
select
ip, device

from
...

inner join ... on ...

inner join ... on ...

group by ip, device

having COUNT(distinct user_id) >=3

and /вот здесь не могу никак сообразить, как добавить условие про дату создания таких дубликатов/)

Пробовал добавить and created_at >= (current_date - 30) - не помогает, список не выгружается совсем.

A: Основная ошибка в ряде случаев - излишняя сложность.
На мой взгляд, вам надо иметь во WHERE комбинированную проверку на период и на уникальность пользователя (её - вложенным запросом). И всё.

*

*У вас же идея верная, но много лишнего (или это не описано в условии).

*Кроме того, вы условие проверки единичных записей (должно быть во WHERE) пытаетесь поместить в проверку агрегированных записей (HAVING), что принципиально не должно работать.

*И не могу судить о работе в postgresql синтаксиса created_at >= (current_date - 30) - в mySQL это работать не будет точно.

Синтаксис postgresql я не знаю, так что проверил работу кода ниже на mySQL.
Основной принцип - рабочий, можете подправить, что надо, и проверить у себя.
Сам код - последние 7 строк, все остальное - создание тестового примера.
CREATE TABLE calls(
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id VARCHAR (25),
    status_1 VARCHAR (25),
    ip VARCHAR (25),
    device VARCHAR (25),
    created_at DATETIME
);
INSERT INTO calls (user_id, status_1, ip, device,created_at)
    VALUES
    ("Петя", "нет разницы", '192.168.0.1', 'модем', '2018-05-25 21:25:54'),
    ("Маша", "нет разницы", '192.168.0.2', 'синхрофазатрон', '2018-05-25 22:22:22'),
    ("Вася", "нет разницы", '192.168.0.3', 'табурет', '2018-05-25 21:25:54'),
    ("Петя", "нет разницы", '192.168.0.1', 'модем', '2018-05-26 22:25:54'),
    ("Маша", "нет разницы", '192.168.0.2', 'синхрофазатрон', '2022-08-03 01:01:01'),
    ("Гена", "нет разницы", '192.168.0.4', 'ванна', '2022-08-04 01:01:01')
;
SELECT * FROM calls;
SELECT user_id, status_1, ip, device,created_at
FROM calls
WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE(created_at) and (ip, device) IN (
    SELECT ip, device
    FROM calls
    GROUP BY ip, device
    HAVING COUNT(*) > 1);

Результат (отброшены все 4 записи старых, а также отброшен Гена, который появился первый раз. Зато Маша уличена во вторичной регистрации и включена в вывод):
Affected rows: 0

Affected rows: 6

Query result:
+----+---------+-------------+-------------+----------------+---------------------+
| id | user_id | status_1    | ip          | device         | created_at          |
+----+---------+-------------+-------------+----------------+---------------------+
| 1  | Петя    | нет разницы | 192.168.0.1 | модем          | 2018-05-25 21:25:54 |
| 2  | Маша    | нет разницы | 192.168.0.2 | синхрофазатрон | 2018-05-25 22:22:22 |
| 3  | Вася    | нет разницы | 192.168.0.3 | табурет        | 2018-05-25 21:25:54 |
| 4  | Петя    | нет разницы | 192.168.0.1 | модем          | 2018-05-26 22:25:54 |
| 5  | Маша    | нет разницы | 192.168.0.2 | синхрофазатрон | 2022-08-03 01:01:01 |
| 6  | Гена    | нет разницы | 192.168.0.4 | ванна          | 2022-08-04 01:01:01 |
+----+---------+-------------+-------------+----------------+---------------------+
Affected rows: 6

Query result:
+---------+-------------+-------------+----------------+---------------------+
| user_id | status_1    | ip          | device         | created_at          |
+---------+-------------+-------------+----------------+---------------------+
| Маша    | нет разницы | 192.168.0.2 | синхрофазатрон | 2022-08-03 01:01:01 |
+---------+-------------+-------------+----------------+---------------------+
Affected rows: 1


text:
Q: Automate ssh port forwarding using DNS I have a number of ssh hosts (a dozen), for simplicity host1, host2, etc.
I frequently need to forward port, e.g.
ssh -L 8888:localhost:8888 host1
ssh -L 8889:localhost:8888 host2
ssh -L 8890:localhost:80   host2

This is annoying since 1) I need to remember mapping from local ports to hosts and 2) I need to do that manually
I'd like to implement some kind of system that listened to specific hosts (locally, on my machine), e.g. host1.8888.ssh.local and opened tunnel to this address automatically.

A: You can configure all this stuff inside the ssh config file, usually found at the location: $HOME/.ssh/config
for example:
Host abc
    Hostname 1.2.3.4
    Port 345
    IdentityFile /path/to/id_rsa
    LocalForward 8888 localhost:8888
    User root
Host def
    Hostname 2.3.4.5
    User root
    LocalForward 8889 localhost:8889

This way, you just need to type ssh abc and all your settings you specify inside there will get applied. Available Options found inside the man page.


text:
Q: lsf awk command quotes When I run this command in the bash terminal it works:
awk '{ sum += $1 } END { print sum }' /user/dnaiel/test.txt > /user/dnaiel/sum.txt

But when I run this:
bsub -q priority -R'rusage[mem=2000]' -oo bin${count}.out -eo bin${count}.err \
"awk '{ sum += $1 } END { print sum }' /user/dnaiel/test.txt > /user/dnaiel/sum.txt"

It does not work.  I also tried changing ' to \' but also does not work.
I get the following errors:
for the first case:
awk: { sum +=  } END { print sum }
awk:           ^ syntax error

for the case I used \'
awk: '{
awk: ^ invalid char ''' in expression

Any ideas where I am messing up with the syntax?  I am quite puzzled.
Thanks

A: notice how the $1 has disappeared in the error message?
awk: { sum +=  } END { print sum }
awk:           ^ syntax error

This is because in shell, when you quote something FIRST with dbl-quotes, as you have done with
bsub -q priority -R'rusage[mem=2000]' -oo bin${count}.out -eo bin${count}.err \
"awk '{ sum += $1 } END { print sum }' /user/dnaiel/test.txt > /user/dnaiel/sum.txt"

any ${var} references are expanded to their value. The single-quotes have lost their magic power to prevent variable expansion when they are inside a dbl-quoted string.
How to fix, escape your $s. not sure what bsub is, but this should do it:
bsub -q priority -R'rusage[mem=2000]' -oo bin${count}.out -eo bin${count}.err \
"awk '{ sum += \$1 } END { print sum }' /user/dnaiel/test.txt > /user/dnaiel/sum.txt"
# -------------^^^

IHTH


text:
Q: How can I make the number of runs of an infinite algorithm fixed regardless of machine processing power? Problem
Let's say I want to build an algorithm that needs to send a message at a specific time and that also needs to run forever. How do I make this algorithm repeat the message a fixed number of times regardless of the performance capacity of the computer used?
Example and further explanation
This is an example that replicates the problem I had when I was working yesterday:
from datetime import datetime

i=0
while True:
    if (datetime.now().minute==21) & (datetime.now().second<=10):
        print(i)
    i+=1

If we call n the last element of the output of this algorithm, we can say that for M computers where the performance capacity of each one is given by

We will have M performances given by:

In the specific case of my machine n = 5,448,521
My question is: how could I write this code so that n would be invariant with the computer's performance, but that it would always be executed from the same time?

A: If I understand you correctly, you're after something like this:
from datetime import datetime

repeats=1000

done = False
while True:
    now = datetime.now()
    if now.minute == 21:
        if not done:
            for i in range(repeats):
                print(i)
            done = True
    else:
        done = False

(Though as a general point, you don't want a "busy" loop like this, and you probably don't want to reinvent the wheel with triggering timed events. You should use some library for that.)

A: from datetime import datetime

i=0
triggered = False
while True:
    if (datetime.now().minute==21) & (datetime.now().second<=10):
        if not triggered:
            triggered = True
            print(i)
    else:
        triggered = False
    i+=1

Are you looking for something like this? You can modify triggered to be a counter instead of a bool if you need the event to happen a specific number of times instead of just once.


text:
Q: How to make php variables inside double quotes appear bold in Sublime In notepad++ when I type:
echo "This is a string with a $my_variable";

It makes $my_variable bold font so it stands out. And it only does this within double quotes.
How can I replicate this functionality in Sublime? Please note I do not want php variables to appear in bold font throughout the file, only those that are within double quotes.
Thanks

A: You'll need to edit your color scheme's .tmTheme file to enable this. To find its path, select Preferences -> Settings-User and check the value of the "color_scheme" key. If it's not present, you're using Packages/Color Scheme - Default/Monokai.tmTheme.
Next you need to open the file. In ST2 this is straightforward, just select Preferences -> Browse Packages... to open your Packages folder in your operating system's file manager (Windows Explorer, Finder, Nautilus, etc.), browse to the correct folder, find the .tmTheme file, and open it in Sublime with XML syntax. In ST3, by default packages are stored in .sublime-package zip files, so you'll need to install the PackageResourceViewer plugin from Package Control to easily access them. Once installed, open the Command Palette, type prv, then choose PackageResourceViewer: Open Resource. Scroll down to the correct directory, hit Enter, find the correct file, and hit Enter again. Change the syntax to XML if you want syntax highlighting.
Now that we have the .tmTheme file open, you'll need to add a new entry. Scroll down to the very bottom, and put a new line above the </array> tag and below the final </dict> tag. You can now insert the following block:
        <dict>
            <key>name</key>
            <string>PHP Variable in Double-Quoted String</string>
            <key>scope</key>
            <string>string.quoted.double.php variable</string>
            <key>settings</key>
            <dict>
                <key>fontStyle</key>
                <string>bold</string>
            </dict>
        </dict>

Save the file, and you should be just about ready to go. First, close Sublime, and if you're using ST2 you should go into the folder where your .tmTheme file resides and delete any .tmTheme.cache and .tmTheme.chback files with the same name as your .tmTheme file. Restart Sublime, and the changes should take effect.


text:
Q: What type does the MyCustomClass.class.getName return? public class MyCustomClass {

    public static void main() {
        MyCustomClass myClass = new MyCustomClass();

        String myClassName = myClass.class.getName(); // myClassName equals 'MyCustomClass'
    }
}

What type does the myClass.class return?

A: As mentioned here in the Apex developer guide

The class property returns the System.Type of the type it is called
on. It is exposed on all Apex built-in types including primitive data
types and collections, sObject types, and user-defined classes.

And, getName() is a method of System.Type class.


text:
Q: Highcharts - Multiple Y Axis Stacked Charts I am creating a chart with two Y axes - distance and duration.  Each Y axis will have multiple series ( run, bike, swim, etc.) stacked on top of one another.  Duration is a stacked area or areaspline and distance is a stacked column chart.
Here is the jsfiddle for the chart. http://jsfiddle.net/baberuth22/u5QCB/3/
$(function() {

var run_data = [[1324771200000,2928000],[1325376000000,2148000],[1327190400000,1001000],[1327795200000,2336000],[1329609600000,2403000],[1330214400000,2456000],[1330819200000,3615000],[1334448000000,1753000],[1338681600000,1998000],[1348358400000,1897000],[1350777600000,8130000],[1353801600000,9402000],[1354406400000,9612000],[1355011200000,4500000]];
var swim_data = [[1324771200000,1726000],[1348963200000,14520000],[1350777600000,15540000],[1352592000000,7380000],[1353801600000,4571000],[1354406400000,4500000]];
var bike_data = [[1327190400000,4289000],[1330214400000,4650000],[1330819200000,3655000],[1331424000000,2217000],[1334448000000,4349000],[1348963200000,4241000],[1350777600000,15014000],[1351382400000,4118000],[1353196800000,3362000],[1353801600000,11944000],[1354406400000,5997000]];
var strength_data = [[1324771200000,3275000],[1334448000000,600000],[1350777600000,4403000],[1351382400000,3339000],[1351987200000,4175000],[1353196800000,3754000],[1354406400000,3890000]];
var yoga_data = [[1351382400000,2656000],[1352592000000,609000]];
var other_data = [[1352592000000,309000],[1353196800000,186000]];

var run_distance_data = [[1324771200000,4],[1325376000000,3.1],[1327190400000,1.5],[1327795200000,3],[1329609600000,3.4],[1330214400000,3.5],[1330819200000,4.9],[1334448000000,2.5],[1338681600000,2.7],[1348358400000,2.6],[1350777600000,10.2],[1353801600000,7.6],[1354406400000,17.2],[1355011200000,10],[1331424000000,0],[1348963200000,0],[1351382400000,0],[1351987200000,0],[1352592000000,0],[1353196800000,0]];
var swim_distance_data = [[1324771200000,0.5],[1348963200000,1.5],[1350777600000,3.1],[1352592000000,0.2],[1353801600000,6.2],[1354406400000,3.1],[1325376000000,0],[1327190400000,0],[1327795200000,0],[1329609600000,0],[1330214400000,0],[1330819200000,0],[1331424000000,0],[1334448000000,0],[1338681600000,0],[1348358400000,0],[1351382400000,0],[1351987200000,0],[1353196800000,0],[1355011200000,0]];
var bike_distance_data = [[1327190400000,19.4],[1330214400000,20.2],[1330819200000,16.1],[1331424000000,9.9],[1334448000000,16.3],[1348963200000,16.1],[1350777600000,168],[1351382400000,15.5],[1353196800000,10.7],[1353801600000,47.2],[1354406400000,24],[1324771200000,0],[1325376000000,0],[1327795200000,0],[1329609600000,0],[1338681600000,0],[1348358400000,0],[1351987200000,0],[1352592000000,0],[1355011200000,0]];
var other_distance_data = [[1352592000000,3.1],[1353196800000,3],[1324771200000,0],[1325376000000,0],[1327190400000,0],[1327795200000,0],[1329609600000,0],[1330214400000,0],[1330819200000,0],[1331424000000,0],[1334448000000,0],[1338681600000,0],[1348358400000,0],[1348963200000,0],[1350777600000,0],[1351382400000,0],[1351987200000,0],[1353801600000,0],[1354406400000,0],[1355011200000,0]];

// one week - 604800000
var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'graph1',
        zoomType: 'x'
    },
    title: {
        text: 'Workout Duration By Week'
    },
    subtitle: {
        text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Drag your finger over the plot to zoom in'
    },
    xAxis: {
        type: 'datetime'

    },
    yAxis: [{
        type: 'datetime',
        //y-axis will be in milliseconds
        dateTimeLabelFormats: { //force all formats to be hour:minute:second
            second: '%H:%M:%S',
            minute: '%H:%M:%S',
            hour: '%H:%M',
            day: '%H'
        },
        title: {
            text: 'Duration (hours)'
        },
        min: 0

        }
                    ,
    {
        min: 0,
        title: {
            text: 'Distance ' + '(miles)'
        },
        opposite: true}
                    ],

    tooltip: {
        formatter: function() {
            var range_start_date = new Date(this.x);
            //var range_start_date = new Date(this.x * 1000);
            var range_end_date = new Date(range_start_date);
            range_end_date.setDate(range_end_date.getDate() + 6);
            var unix_end_datetime = range_end_date.getTime();
            var return_string = '' + this.series.name + ' ' + Highcharts.dateFormat('%b %e', this.x) + ' - ' + Highcharts.dateFormat('%b %e', unix_end_datetime) + '
';

            if (this.series.index <= 5){
                return_string += Highcharts.dateFormat('%H hours %M minutes', this.y) + ' ';
            }else{
                return_string += this.y + ' (miles) ';
            }

            return return_string;
        }
    },
    plotOptions: {
        column: {
            pointRange: 604800000,
            stacking: 'normal'
        },
        area: {
            stacking: 'normal'
        }
    },
    series: [
        {
        name: 'Run',
        data: run_data,
        type: 'column'},
    {
        name: 'Swim',
        data: swim_data,
        type: 'column'},
    {
        name: 'Bike',
        data: bike_data,
        type: 'column'},
    {
        name: 'Strength',
        data: strength_data,
        type: 'column'},
    {
        name: 'Yoga',
        data: yoga_data,
        type: 'column'},
    {
        name: 'Other',
        data: other_data,
        type: 'column'}
        ,
    {
        name: 'Run',
        data: run_distance_data,
        yAxis: 1,
        type: 'area'},
    {
        name: 'Swim',
        data: swim_distance_data,
        yAxis: 1,
        type: 'area'},
    {
        name: 'Bike',
        data: bike_distance_data,
        yAxis: 1,
        type: 'area'},
    {
        name: 'Other',
        data: other_distance_data,
        yAxis: 1,
        type: 'area'

        }
    ]
});

var d = new Date();
chart.xAxis[0].setExtremes(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate() - 7), Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
chart.showResetZoom();

});
It is the top chart.
The stacking doesn't seem to work properly and I do not see any examples of multiple axes stacked on the highcharts demo page. http://www.highcharts.com/demo/combo-multi-axes or http://www.highcharts.com/demo/column-stacked , but not both.
If I set both axes to 'column' type, the stacking works, but the bars are on top of each other.  Ideally I'd like a semi-transparent area chart in the background with column in front.

A: I think it actually works with two stacks the way you are doing it, but the stacking of the area series breaks because data points are not present for every date. So if you make sure when preprocessing that every data has a data point in the area series, I think it should work.


text:
Q: unable to set django model values I have below code
exinfo = ExistingCardInfo.objects.filter(CustID=custid)
trail4 = exinfo[0].trail4
logger.debug(exinfo[0].trail4) # prints 1984
exinfo[0].trail4=3000
logger.debug(exinfo[0].trail4) # again prints 1984

Initially trail4 value is 1984. After I set trail4 value to 3000, i'm still getting 1984.
Is there anything wrong with above code?

A: Indexing a queryset reruns the query. Extract the single model, modify the field, save the model, then reindex.

A: I've experience something similar to you, when trying to assign values to a queryset property when accessing them through an index.
Can you try something like:
excardinfo = exinfo[0]
excardinfo.trail4 = 3000
excardinfo.save()

A: As some of the other answers have said, indexing a queryset causes django to hit the database again.
If you don't want to save the changes to the database (in which case, you wouldn't want to use .save()), then extract that model and save it to a variable:
thismodel = exinfo[0]
print thismodel.trail4
thismodel.trail4 = 3000
print thismodel.trail4

The above will print 1984 and 3000. It will not save to database, so the row stored in the database remains unaltered.

A: I agree with @dm03514 what you get after filter is just queryset whatever changes you make in it are not reflected in the database.
To reflect changes in the database use .save() function on the object.


text:
Q: Showing a detail view from a list of movies in multiple UICollectionViews I have multiple UICollectionViews (4 to be precise) in the same ViewController. I made a containerview for every 'row' which consists of a Title and a UICollectionView. I made a Segue from every UICollectionViewCell to the details view controller and gave them an identifier. But I fail to understand how to get my Movie object from the containerview to the details page.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "MovieDetailsPlaying"){
        var destination = segue.destination as! DetailMovieController
        destination.item = containerNowPlayingView.movies[IndexPath]
    }
}

All I think I need to fix this problem is figure out how to get the IndexPath in the prepare function for the Segue in the ViewController. I hope you might be able to help me.
I already found answers like this:
Answer one

A: Considering you didn't show what type of cell your using inside cellForItemAt indexPath I had to make some things up so this could become clear to you. I also don't know what you mean by you have 4 collection views but this is one of the ways you transfer data from a collectionViewCell to the destination view controller via prepareForSegue using 1 collectionView.
Inside preparForSegue you need 3 things:
1- you need to know the type of cell your using in cellForItemAt indexPath. For this example I used a cell class named MovieCell
2- you need to get the indexPath of the selected row. CollectionView has a method on it named indexPath(for:) that accepts a collectionViewCell as an arguement: collectionView.indexPath(for: UICollectionViewCell)
3- Get the information from the array corresponding to that selected row.
For an example you have a class named MovieDataModel with a movieName property:
class MovieDataModel{
    var movieName: String?
}

The collectionView cell is named MovieCell and it has a movieTitleLabel outlet in it:
class DetailedSearchComplaintCollectionCell: UICollectionViewCell {
    @IBOutlet weak var movieTitleLabel: UILabel!
}

Inside the class with your CollectionView:
@IBOutlet weak var collectionView: UICollectionView! // in this example there is only 1 collectionView
let movies = [MovieDataModel]() // an array of MovieDataModels

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return movies.count // return the number of items inside the movies array
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "movieCell", for: indexPath) as! MovieCell // cast the cell as a MovieCell
     cell.movieTitleLabel.text = movies[indexPath.row].movieName! // this is the same info we need for the 3rd step

     return cell
}

                                                 // sender parameter <<<
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if (segue.identifier == "MovieDetailsPlaying"){

       // From the steps above
       let cell = sender as! MovieCell // 1- the same exact type of cell used in cellForItemAt indexPath. Access it using the sender parameter in the prepareFoeSegue signature and then cast it as a MovieCell
       let indexPath = collectionView.indexPath(for: cell) // 2- get the indexPath from the row that was tapped. Add the cell from step 1 as an argument to it. Notice it says collectionView because that's the name of the collectionView outlet. I'm not sure how this would work with 4 different collectionViews but you probably will have to make an indexPath for each one. Just an assumption

       var destination = segue.destination as! DetailMovieController
       destination.item = movies[indexPath!.row].movieName // 3- what MoviesDataModel item from inside the movies array and the title from it corresponds to the indexPath (the tapped row).
    }
}

I don't know the name of the collectionView cell your using but inside the class with the collectionView wherever you see the name MovieCell just change it to whatever the name of the cell is your using.


text:
Q: ImportError: Could not import PIL.Image. The use of `load_img` requires PIL. even after using pillow library My program is a feature extraction for an image processing program, we are loading the model and extracting features from each image.

*

*We load the image from file

*convert the pixels of image to numpy array

*extract features

*store features

*save to file(pkl)

This is the code snippet.
from os import listdir
from pickle import dump
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.inception_v3 import preprocess_input
from keras.models import Model
import string
from timeit import default_timer as timer
from PIL import Image
import sys

for name in listdir(directory):
    # load an image from file
    filename = directory + '/' + name
    image = load_img(filename, target_size=(230,230))
    # convert the image pixels to a numpy array
    image = img_to_array(image)
    # reshape data for the model
    image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
    # prepare the image for the VGG model
    image = preprocess_input(image)
    # get features
    feature = model.predict(image, verbose=0)
    # get image id
    image_id = name.split('.')[0]
    # store feature
    features[image_id] = feature
    #print('>%s' % name)
return features

It gives me this error
 ---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-5-566a23558a68> in <module>
     46 # extract features from all images
     47 directory = 'data/caption/1'
---> 48 features = extract_features(directory)
     49 #print('Extracted Features: %d' % len(features))
     50 # save to file

<ipython-input-5-566a23558a68> in extract_features(directory)
     27         # load an image from file
     28         filename = directory + '/' + name
---> 29         image = load_img(filename, target_size=(230,230))
     30         # convert the image pixels to a numpy array
     31         image = img_to_array(image)

c:\users\likith\appdata\local\programs\python\python38\lib\site-packages\tensorflow\python\keras\preprocessing\image.py in load_img(path, grayscale, color_mode, target_size, interpolation)
    298       ValueError: if interpolation method is not supported.
    299   """
--> 300   return image.load_img(path, grayscale=grayscale, color_mode=color_mode,
    301                         target_size=target_size, interpolation=interpolation)
    302

c:\users\likith\appdata\local\programs\python\python38\lib\site-packages\keras_preprocessing\image\utils.py in load_img(path, grayscale, color_mode, target_size, interpolation)
    109         color_mode = 'grayscale'
    110     if pil_image is None:
--> 111         raise ImportError('Could not import PIL.Image. '
    112                           'The use of `load_img` requires PIL.')
    113     with open(path, 'rb') as f:

ImportError: Could not import PIL.Image. The use of `load_img` requires PIL.

I've installed pillow and imported it into the program but it still gives me the same error.

A: Do "" pip install Image"" that will resolve your error, don't forget to uninstall PIL first


text:
Q: ORB with AGAST Detector I would like to know whether I can use ORB descriptor with AGAST detector for an android based application.
I know that BRISK uses AGAST detector for detecting the keypoints. Can I implement AGAST with ORB?
Does it work much efficient than ORB Detector/Descriptor.
Please enlighten me on this.
Thanks


text:
Q: ACF wp_query, получить конечное поле цепочки, которые в repeater->field->repeater->FIELD Нужно достучатся до поля PASSWORD
Получить страну получается, а вот написать правильный алгоритм по поиску поля PASSWORD не получается
Пытаюсь сделать вот так:
add_filter('posts_where', 'yanco_posts_where');
function yanco_posts_where( $where ) {
    $where = str_replace( "meta_key = 'repeater_machines_password_repeater_$", "meta_key LIKE 'repeater_machines_%_password_repeater_%", $where );
    return $where;
}

    if(isset($_GET['password'])) {
        $password = sanitize_text_field( $_GET['password'] );
        $meta_query[] = array(
            // 'key' => 'repeater_machines_$_password', // Format: repeater_field + _ + $ + _ + repeater_sub_field password_repeater
            'key' => 'repeater_machines_$_country_password_repeater_$_password',
            'value' => $password,
            'compare' => '='
        );
    }

https://i.stack.imgur.com/Kzd2G.png


text:
Q: Telerik Cover Flow bubbling events from user control I have a telrik coverflow, and the tiles in are of type InfoPageView, a user control. I have a button inside the InfoPageView user control from which i want to trigger an event at the parent.
I tried implementing the solution in this post:
Expose a Click event of a button inside a UserControl in Silverlight but i cant get the childs event in the parent class. Is there an alternate way to do this?
<telerikNavigation:RadCoverFlow x:Name="CoverFlow" Grid.Row="0" OffsetY="0" ItemsSource="{Binding Covers}" HorizontalAlignment="Center"
                DistanceBetweenItems="75" DistanceFromSelectedItem="25"  IsReflectionEnabled="False" ItemScale="0.5"  Margin="0,0,0,0" Width="785" Height="486">
                <telerikNavigation:RadCoverFlow.ItemTemplate>
                    <DataTemplate>
                        <local:InfoPageView Name="Custinfopage" Width="390" Height="390" />
                    </DataTemplate>
                </telerikNavigation:RadCoverFlow.ItemTemplate>
            </telerikNavigation:RadCoverFlow>

A: If you insist on having the event bubble up from your inner view, you will need to rely upon routed events. The button will mark the LeftMouseButtonDown event as handled, which means you cant just use a straight forward event handler. What you can do though, is set up a listener for handled events.
You will need to verify that the event originated from the button you want, perhaps using a Tag on that button will suffice.
public MyOuterPage()
{
    InitializeComponent();
    this.AddHandler(UIElement.MouseLeftButtonDownEvent, new System.Windows.Input.MouseButtonEventHandler(MyMouseLeftButtonDownEventHandler), true);
}

void MyMouseLeftButtonDownEventHandler(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    var button = e.OriginalSource as Button;
    if (button.Tag == "MyButton")
    {
        // do something with the event here
    }
}

A: I was unable to catch the InfoPage usercontrol on my main page through the codebehind .cs file. So i injected the event in xaml:
<local:InfoPageView Name="Custinfopage" Width="390" Height="390" OnButtonClick="Button_click_event" />

In the main .CS file:
void Button_click_event(object sender, RoutedEventArgs e)
{

        // Code
}

In the UserControl:
public event EventHandler<RoutedEventArgs> OnButtonClick;

    public void Button_Click(object sender, RoutedEventArgs e)
            {

                if (OnButtonClick!= null){
                        OnButtonClick(sender, e);
                }

            }