text:
Q: Can we personalize Session Timeout for Roles in ASP.NET MVC 5 The idea is to set different values of Session Timeout for
different User Roles in ASP.NET MVC 5 and ASP.NET Identity.
Is it possible to do?

A: If you are trying to boot admins out sooner than regular users, here is my stub on this in Identity.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    // other stuff
    Provider = new CookieAuthenticationProvider
    {
        // this function is executed every http request and executed very early in the pipeline
        // and here you have access to cookie properties and other low-level stuff.
        // makes sense to have the invalidation here
        OnValidateIdentity = async context =>
        {
            // invalidate user cookie if user's security stamp have changed
            var invalidateBySecirityStamp = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager));
            await invalidateBySecirityStamp.Invoke(context);

            // check if user is in admin role
            var isAdmin = context.Identity.Claims.Any(c => c.Type == ClaimTypes.Role && c.Value == "AdminRoleName");

            // check if enough time has passed to invalidate cookie
            var currentUtc = DateTimeOffset.UtcNow;
            if (context.Options != null && context.Options.SystemClock != null)
            {
                currentUtc = context.Options.SystemClock.UtcNow;
            }

            var issuedUtc = context.Properties.IssuedUtc;
            var bootThemOut = (issuedUtc == null);
            if (issuedUtc != null)
            {
                var timeElapsed = currentUtc.Subtract(issuedUtc.Value);
                bootThemOut = timeElapsed > TimeSpan.FromMinutes(3); // invalidate admin cookies in 3 minutes
            }

            if (isAdmin && bootThemOut)
            {
                context.RejectIdentity();
                context.OwinContext.Authentication.SignOut(context.Options.AuthenticationType);
            }
        }
    }
});

A: Based on their role you could set the timeout, i.e.
HttpContext.Current.Session.Timeout = 20;

Going by your previous question you want to do this dynamically.  You could store and update the times themselves in session and set for each role on OnActionExecuting of a base controller.
    if (User.IsInRole("Admin"))
    {
        filterContext.HttpContext.Session.Timeout =
(int)filterContext.HttpContext.Session["AdminTimeoutThatYouSetSomewhereElseGlobally"];
    }


text:
Q: Java prevent tampering of certificate files (manifest) in jar files Our commercial jar which is run with batch files (java -jar ..) is distributed with our signature. It is NOT triggered with JNLP. It also contains additional 3rd party libraries. If any malicious person replaces any java class, the jar stops running because signature mismatch. But if he removes the MANIFEST files from the jar there is no check anymore. How can we prevent the program running when any class is replaced, changed? One option could be checking the manifest files in the java source as stated Verifying Jar Signature and How to verify a jar signed with jarsigner programmatically such as
jarFile jar = new JarFile(new File("path/to/your/jar-file"));

// This call will throw a java.lang.SecurityException if someone has tampered
// with the signature of _any_ element of the JAR file.
// Alas, it will proceed without a problem if the JAR file is not       signed at all
InputStream is = jar.getInputStream(jar.getEntry("META-INF/MANIFEST.MF"));
Manifest manifest = new Manifest(is);

and also checking the CodeSigners etc.
manifest.getCodeSigners();

But what happens when the person who is trying to break the jar, performs decompilation (using jad for example)? To prevent decompilation we applied  some obfuscators, but when decompiled, we can see the logic even if the method names has been changed. So the obfuscation is not enough.
What is your suggestion? Is it a good approach writing the sign checking code complicated such as with reflect api, adding garbled data, some spagetti code with goto, or can you advice a different procedure to prevent manifest tampering as well as making decompilers unsuccessful? I checked the options in the obfuscator, but what can we do in the code writing phase to improve and strengten the obfuscation step?

A: As long as I know, there is no perfect solution for this problem until now. You can read this, the problem is alike. So far, obfuscation is probably the best+easy effort. I mean, not only by using code obfuscator, but you code such that weird logic to hide your algorithm so the cracker cannot trace the logic and method calls easily.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hadamard's product of Fibonacci generating functions. $F(s) = \frac{1}{1-s-s^2}=\sum_{n\geq0}F_ns^n$.
I want to calculate $F(s) \circ F(s) = \sum_{n\geq0}F_{n}^2s^n$.
I have tried using Binet"s formula, but problem remains unsolved.

A: Square the Binet formula to get $$F_n^2=\frac{\phi^{2n}-2(-1)^n+\phi^{-2n}}{5},$$where $\phi=(1+\sqrt5)/2$. Now the series splits into three geometric series, where the common ratios are respectively $\phi^2s$, $-s$, and  $\phi^{-2}s$.


text:
Q: C++ from Class to Template EDIT: Indeed (*it)->print() works. Sorry for misleading information. When I wrote the question I thought I tried all posibilities. And the last one, even if I wouldn't have tried it, it seemed wrong to me - pointer to pointer..
Thank you for your time, was a newbie mistake, but it made me see the light!
I've started a little project a week ago. Every worked smoothly untill I had this piece of code, where this->_items is std::vector<CItem*> _items;
std::vector<CItem*>::iterator it;
for ( it = this->_items.begin(); it != this->_items.end(); ++it)
{
    //MUST use .print() for each Item.
    //so:
    //it->print() - nope
    //(*it).print() -nope - same thing.. STILL!!! What's the problem?
    //it.print() - maybe?
    //(*it)->print() - come onn!!
}

Ok.. so It didn't work. After doing some research for std::vector I realised yeah, that's a template. Let's do a template. And I kind of did. Header and implementation in one big file,  everywhere.. but the project started breaking.
After did translate Class to Template it didn't work either. So I started adding template <typename T> everywhere untill the red line goes away. It does not.
Here are the changes I've done: https://github.com/screws0ft/ubisoft/commit/1b2bd6f9d5d66fcc9315f7a03cc71a2d6f64d57e
So where's the problem? Could someone help me out?
Appreciate it!

A: However (*it)->print() should work.
But, you can do it indirectly too:
std::vector<CItem*>::iterator it;
for ( it = this->_items.begin(); it != this->_items.end(); ++it)
{
    CItem *item = *it;
    item->print();
}

If none of those don't work. You have a problem in somewhere else. Did you allocated CItem objects correctly? ...

A: The quick and dirty way:
for (auto &p : _items)
    p->print();

The correct way: change your print to something like:
std::ostream &print(std::ostream &os) {
    // print self onto os
    return os;
}

Then define an operator<< something like:
std::ostream &operator<<(std::ostream &os, item const &i) {
    return i->print(os);
}

...and finally do the printing with something like:
std::copy(begin(items), end(items), std::ostream_iterator<item>(std::cout, "\n"));

Oh, and as shown above, you really want to use items (or perhaps items_) instead of _items. Technically, _items is allowable in this context, but I'd generally advise against defining any name with a leading underscore, since the context in which you're allowed to do so is somewhat constrained.
Edit: a short demo of the quick and dirty version:
#include <iostream>
#include <vector>

class item {
    int i;
public:
    std::ostream &print(std::ostream &os) {
        return os << i;
    }

    item(int i) : i(i) {}
};

class whatever {
    std::vector<item *> items;
public:
    void print_all() {
        for (auto &i : items)
            i->print(std::cout);
    }

    whatever() {
        for (int i=0; i<10; i++)
            items.push_back(new item(i));
    }
};

int main() {
    whatever w;

    w.print_all();
    return 0;
}


text:
Q: Difference between Composer autload classmap and iclude-path In composer documentation section about autoloading I found at least two means to load classes that not corresponds to psr-0/4. First one is to specify classmap property of composer.json file and second one is fill include-path property in my composer.json.
As I can see include-path is more plain feature while classmap caused scanning for classes in specified locations. Who can explain which one should I use in different cases?

A: Avoid using include-path. It is meant for old software that expects the include_path setting to contain some directories, so that require_once "Relative/Path/To/Class.php" works from ANY location (think of the way PEAR works). Using too many paths impacts performance, because PHP needs to scan starting from the first directory, until it finds the relative path requested.
Classmaps are an always working solution if the classes do not conform to PSR-0 or PSR-4. Autoloading works by knowing the name of the class and finding out the file this class is contained in. PSR-0/4 define a way to know the file name by using and splitting the class name. Classmaps however know every class name and their file name directly. The bad thing about classmaps is that if they grow too large, they also affect performance because loading a huge classmap and then only using about 1% of the contained classes has a big overhead.
include-path and classmap are not mutually exclusive. In fact, they might be both needed: To load the first class, you'd need the classmap (otherwise you'd be forced to explicitly use require_once), and if that file will load dependencies using relative paths inside require_once (and does not know about autoloading), a proper include path has to be set.
If you ever have the chance to change it, I highly recommend to avoid setting the include path, and only use the classmap feature to autoload classes (which means you should remove any include/require functions in that code base). It would be even better if your code can be transformed to be PSR-0 compliant, but this usually is a huge rewriting task for old code with barely any benefit. You'd have to worry about performance only if you really have a HUGE framework with many files and classes - which usually is not the case with older code bases.


text:
Q: SSIS expressions on custom class/collection I am trying to modify a custom DTS Task. This task creates a single report, based on values defined on properties (e.g. ReportName, ServerName, Parameter1, Value1..) in Properties window.
I am trying to modify it in a way that would allow creation of multiple reports at once. I created a collection with a custom class. I then implemented SaveToXML and LoadFromXML methods from IDTSComponentPersist. Problem is, some of these variables need to have their values defined by expressions. I cannot see the collection or class variables in Property Expressions Editor.
Is it possible to make these properties appear there? Or, is there a way to override evaluation of expressions that would allow inserting expressions into these variables?
Thank you.


text:
Q: How to Yii2 master-slave connections I configured the MySQL master-slave replications.
How can I configure the Yii2 Active Record for insert,update and delete queries on master DB and read queries on slave DB's?

A: Yii2 handles this automatically allowing you configure multiple slaves and even multiple masters.
[
    'class' => 'yii\db\Connection',

    // configuration for the master
    'dsn' => 'dsn for master server',
    'username' => 'master',
    'password' => '',

    // common configuration for slaves
    'slaveConfig' => [
        'username' => 'slave',
        'password' => '',
        'attributes' => [
            // use a smaller connection timeout
            PDO::ATTR_TIMEOUT => 10,
        ],
    ],

    // list of slave configurations
    'slaves' => [
        ['dsn' => 'dsn for slave server 1'],
        ['dsn' => 'dsn for slave server 2'],
        ['dsn' => 'dsn for slave server 3'],
        ['dsn' => 'dsn for slave server 4'],
    ],
]

Link to section in Yii2 Guide for more info: http://www.yiiframework.com/doc-2.0/guide-db-dao.html#read-write-splitting


text:
Q: Using boost::random to select from an std::list where elements are being removed See this related question on more generic use of the Boost Random library.
My questions involves selecting a random element from an std::list, doing some operation, which could potentally include removing the element from the list, and then choosing another random element, until some condition is satisfied.
The boost code and for loop look roughly like this:
// create and insert elements into list
std::list<MyClass> myList;
//[...]

// select uniformly from list indices
boost::uniform_int<> indices( 0, myList.size()-1 );
boost::variate_generator< boost::mt19937, boost::uniform_int<> >
  selectIndex(boost::mt19937(), indices);

for( int i = 0; i <= maxOperations; ++i ) {
    int index = selectIndex();
    MyClass & mc = myList.begin() + index;

    // do operations with mc, potentially removing it from myList
    //[...]
}

My problem is as soon as the operations that are performed on an element result in the removal of an element, the variate_generator has the potential to select an invalid index in the list.  I don't think it makes sense to completely recreate the variate_generator each time, especially if I seed it with time(0).

A: I assume that MyClass & mc = myList.begin() + index; is just pseudo code, as begin returns an iterator and I don't think list iterators (non-random-access) support operator+.
As far as I can tell, with variate generator your three basic options in this case are:

*

*Recreate the generator when you remove an item.

*Do filtering on the generated index and if it's >= the current size of the list, retry until you get a valid index. Note that if you remove a lot of indexes this could get pretty inefficient as well.

*Leave the node in the list but mark it invalid so if you try to operate on that index it safely no-ops. This is just a different version of the second option.

Alternately you could devise a different index generation algorithm that's able to adapt to the container changing size.

A: You could create your own uniform_contained_int distribution class, that accept a container in its constructor, aggregates a uniform_int, and recreates the uniform_distribution each time the container changes size. Look at the description of the uniform_int which methods you need to implement to create your distribution.

A: I think you have more to worry about performance-wise. Particularly this:
std::list<MyClass> myList;
myList.begin() + index;

is not a particularly fast way of geting index-th element.
I would transform it into something like this (which should operate on a random subsequence of the list):
X_i ~ U(0, 1) for all i
left <- max_ops
N <- list size
for each element
  if X_i < left/N
    process element
    left--
  N--

provided you don't need the random permutation of the elements.


text:
Q: Renumerating partitioned sets This is a problem in my graph theory class and I'm unsure about how to solve it..

Let $X$ be the set $\{1,2,\dots,mn\}$. Suppose we partition $X$ into $m$ sets $P_1,\dots,P_m$, each of size $n$.
Suppose we choose another partition $Q_1,\dots,Q_m$, each of size $n$.
Show that the sets $P_i$ can be renumbered so that $P_i \cap Q_i$ is non-empty for every $i$.

Thanks in advance!
Edit: I'm attempting to use Hall's Marriage theorem to solve this but I'm struggling with formulating the solution in a way that would get me to my answer.

A: Hall's Marriage Theorem is the right way to go.  To put it in terms of graphs, consider a bipartite graph, where The $P_k$ form one of the bipartition sets, and the $Q_k$ form the other.  Make $P_i$ adjacent to $Q_j$ if and only if $P_i\cap Q_j\neq \emptyset.$  Then you want to show that there is a complete matching, so if you can show that Hall's condition holds, you are done.
That is, you must show that if $P_{i_1},\dots,P_{i_k}$ are given, for some $1\leq k\leq m,$ then there exist $Q_{i_1},\dots,Q_{i_k}$ that each have at least one element in common with at least one of the $P_{i_j}.$
This is quite easy when you think about it.


text:
Q: Django posting nested JSON inside n number of tables I am having trouble posting nested fields to database. All i want to do is to add lender and borrower to different tables in database. Loan JSON post format:
{
    "lender": {
        "email": "lender@hotmail.com"
    },
    "borrower": {
        "email": "borrower@gmail.com"
    },
    "amount": 4
}

This post must add lender to Lender table and borrower to Borrower table and Loan to loan table.
My view:
class LenderLoanAddAPIView(generics.CreateAPIView):
    serializer_class = lenderloan_serializers.AddLenderLoanSerializer
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        lender = self.kwargs['lender']
        return Loan.objects.filter(lender=lender).order_by('-id')

My serialiser:
class AddLenderLoanSerializer(serializers.ModelSerializer):
    lender = LenderSerializer(many=False)
    borrower = BorrowerSerializer(many=False)

    class Meta:

        model = Loan
        fields = ('lender','borrower', 'amount',)

    def create(self, validated_data):
        lender = Lender(
            email = validated_data['lender']
        )
        borrower = Borrower(
            email = validated_data['borrower']
        )
        lender.save()
        borrower.save()

        return lender

I think i must implement create method in another way. Unfortunately i don't know how. Can you please help me with this nested serializer? I really need to go on but i am stuck with this problem.


text:
Q: Refresh DataContext for child controls in WPF We have a client-server application which has the requirement of building the View dynamically. The server will send the XAML string together with the data (Dctionary< string, string>) to the client, which will then build the View from received Xaml string and bind the data to the View.
Here is the sample XAML string:
     <StackPanel>
        <TextBox>
            <TextBox.Text>
                <Binding RelativeSource="{{RelativeSource Self}}" Path="DataContext"
                         Converter="{{StaticResource fieldBindingConverter}}" ConverterParameter="ID_Id"
                         UpdateSourceTrigger="PropertyChanged">
                 </Binding>
            </TextBox.Text>
        </TextBox>

        <TextBox>
            <TextBox.Text>
                <Binding RelativeSource="{{RelativeSource Self}}" Path="DataContext"
                         Converter="{{StaticResource fieldBindingConverter}}" ConverterParameter="ID_Name"
                         UpdateSourceTrigger="PropertyChanged">
                 </Binding>
            </TextBox.Text>
        </TextBox>
     </StackPanel>

The data would look like:
new Dictionary<string, string>
    {
        {"ID_Id", "1"},
        {"ID_Name", "John"}
    };

The client will build the View by using XamlReader.Load(), and create a Window to host it as the Content. The client also assigns the received data to Window.DataContext
 window.DataContext = dictionaryData;

As the two TextBox's inherit the DataContext from Window, the Text property binds to the Dictionary.
The binding converter "fieldBindingConverter" fetches the correct value out of the dictionary by using ConverterParameter which has the key.
So the Two TextBox's will disply "1" and "John" correspondingly when the View is first built.
The problem arises when a new data arrives at client side
    new Dictionary<string, string>
    {
        {"ID_Id", "2"},
        {"ID_Name", "Peter"}
    };

By resetting the DataContext of the hosting Window will not make the binding on the TextBox refresh itself
window.DataContext = newDictionaryData;

In fact the DataContext of the TextBox still cache the old data value.
It seems that TextBox only takes a copy of its parent DataContext when it's first initialized, and then only works with that local copy afterwards.
It also appears that it not easy to have a ViewModel and implement INotifyPropertyChanged in this scenario, as the key "ID_XX" can vary among different Views and it;s hard to have a Model class defined for this dynamic nature (I could be wrong).
It does work correctly if a new hosting Window is created (and DataContext is set) every time a new data arrives, because the DataContext of all TextBox's will have the new data derived for the new hosting window.
Does anyone know how to get the TextBox "refresh" its DataContext to take the new one set on the parent Window and "refresh" the binding?

A: In WPF, we don't generally set the DataContext of a Window to one data type object like this... however it is possible. Instead, we normally create a specific class that contains all of the properties required to be displayed and as you alluded to, implements the INotifyPropertyChanged interface. In your case, we would have a property of type Staff that we could bind to in the UI:
public string Staff
{
    get { return staff; }
    set { staff = value; NotifyPropertyChanged("Staff"); }
}

Then in XAML:
<Window>
    <StackPanel>
        <TextBox Text="{Binding Staff.Id}"/>
        <TextBox Text="{Binding Staff.Name}"/>
    </StackPanel>
</Window>

In this small example, this is not strictly necessary, but in larger projects, it is likely that there would be other data to display as well. If you set the Window.DataContext to just one instance of your Staff data type, then you would find it tricky to display other data, such as a collection of Staff objects. Likewise, it is better to update the Staff property, which will inform the interface to update the UI, rather than the DataContext which will not update the UI as it  is not 'connected' to the interface.
It is the notification of property changes through the INotifyPropertyChanged interface that updates, or 'refreshes as you call it, the values in the UI controls when property changes are made. So your answer is to implement this interface and make sure that you call the INotifyPropertyChanged.PropertyChangedEventHandler when property value changes are made.
UPDATE >>>
Wow! You really aren't listening, are you? In WPF, we don't 'refresh' the DataContext, the INotifyPropertyChanged interface 'refreshes' the UI once properties have been changed. This is one possible way that you could fix this problem:
public class CustomObject
{
    public int Id { get; set; }
    public string Name { get; set; }
    ...
}

...

Dictionary<string, string> data = new Dictionary<string, string>
{
    {"ID_Id", "1"},
    {"ID_Name", "John"}
    ...
};

...

// Implement the `INotifyPropertyChanged` interface on this property
public ObservableCollection<CustomObject> CustomObjects { get; set; }

...

You could then fill your CustomObject like this:
CustomObjects = new ObservableCollection<CustomObject>();
CustomObject customObject = new CustomObject();
foreach (KeyValuePair<string, string> entry in data)
{
    if (entry.Key == "ID_Id") // Assuming this always comes first
    {
        customObject = new CustomObject();
        customObject.Id = int.Parse(entry.Value);
    }
    ...
    else if (entry.Key == "ID_Name") // Assuming this always comes lasst
    {
        customObject.Name = entry.Value;
        customObjects.Add(customObject);
    }
}

...

<ListBox ItemsSource="{Binding CustomObjects}">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type DataTypes:CustomObject}">
            <StackPanel>
                <TextBox Text="{Binding Id}"/>
                ...
                <TextBox Text="{Binding Name}"/>
            </StackPanel>
        </DataTemplate DataType="{x:Type DataTypes:CustomObject}">
    </ListBox.ItemTemplate>
</Window>

Now you could argue that you can't do this for this reason, or you don't want to do that for that reason, but at the end of the day, you have to do something like this to solve your problem.

A: You might consider creating a custom ObservableDictionary < T , U > class inherited from the ObservalbeCollection class. I've done this, and though it's been some work to get the kinks out, it's become one of my most prized custom classes. Some brief bits of code as a suggestion:
/// Dictionary changed event handler
/// <param name="sender">The dictionary</param>
/// <param name="e">The event arguments</param>
public delegate void NotifyDictionaryChangedEventHandler(object sender, NotifyDictionaryChangedEventArgs e);

public class CollectionDictionary<TKey, TValue> : ObservableCollection<TValue>
{
    #region Fields
    private ConcurrentDictionary<TKey, TValue> collectionDictionary =
        new ConcurrentDictionary<TKey, TValue>();
    #endregion

    ///
    /// Initializes a new instance of the CollectionDictionary class
    ///
    public CollectionDictionary()
    {
    }

    ///
    /// Initializes a new instance of the CollectionDictionary class
    ///
    /// <param name="collectionDictionary">A dictionary</param>
    public CollectionDictionary(Dictionary<TKey, TValue> collectionDictionary)
    {
        for (int i = 0; i < collectionDictionary.Count; i++)
        {
            this.Add(collectionDictionary.Keys.ToList()[i], collectionDictionary.Values.ToList()[i]);
        }
    }

    ///
    /// Initializes a new instance of the CollectionDictionary class
    ///
    /// <param name="collectionDictionary">A concurrent dictionary</param>
    public CollectionDictionary(ConcurrentDictionary<TKey, TValue> collectionDictionary)
    {
        this.collectionDictionary = collectionDictionary;
    }

    #region Events
    /// The dictionary has changed
    public event NotifyDictionaryChangedEventHandler DictionaryChanged;
    #endregion

    #region Indexers
    ///  Gets the value associated with the specified key.
    /// <param name="key"> The key of the value to get or set. </param>
    /// <returns> Returns the Value property of the System.Collections.Generic.KeyValuePair<TKey,TValue>
    /// at the specified index. </returns>
    public TValue this[TKey key]
    {
        get
        {
            TValue tValue;

            if (this.collectionDictionary.TryGetValue(key, out tValue) && (key != null))
            {
                return this.collectionDictionary[key];
            }
            else
            {
                return tValue;
            }
        }

        ////set
        ////{
        ////    this.collectionDictionary[key] = value;

        ////    string tKey = key.ToString();
        ////    string tValue = this.collectionDictionary[key].ToString();
        ////    KeyValuePair<TKey, TValue> genericKeyPair = new KeyValuePair<TKey, TValue>(key, value);
        ////    List<KeyValuePair<TKey, TValue>> keyList = this.collectionDictionary.ToList();

        ////    for (int i = 0; i < keyList.Count; i++)
        ////    {
        ////        if (genericKeyPair.Key.ToString() == keyList[i].Key.ToString())
        ////        {
        ////            RemoveAt(i, String.Empty);
        ////            Insert(i, value.ToString(), String.Empty);
        ////        }
        ////    }
        ////}
    }

    ///
    /// Gets the value associated with the specific index
    ///
    /// <param name="index">The index</param>
    /// <returns>The value at that index</returns>
    public new TValue this[int index]
    {
        get
        {
            if (index > (this.Count - 1))
            {
                return default(TValue);
            }
            else
            {
                return this.collectionDictionary.ToList()[index].Value;
            }
        }
    }
    #endregion

    ///
    /// Dictionary has changed. Notify any listeners.
    ///
    /// <param name="e">Evevnt arguments</param>
    protected virtual void OnDictionaryChanged(NotifyDictionaryChangedEventArgs e)
    {
        if (this.DictionaryChanged != null)
        {
            this.DictionaryChanged(this, e);
        }
    }

}
That's the basic class. An example method in the class:
    ///  Adds a key/value pair to the
    /// System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>
    /// if the key does not already exist, or updates a key/value pair in the
    /// System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>
    /// if the key already exists.
    /// <param name="key"> The key to be added or whose value should be updated </param>
    /// <param name="addValueFactory">The function used to generate a value for an absent key</param>
    /// <param name="updateValueFactory">The function used to generate a new value for an
    /// existing key based on the key's existing value</param>
    /// <returns> The new value for the key. This will be either be the result of addValueFactory
    /// (if the key was absent) or the result of updateValueFactory (if the key was
    /// present). </returns>
    public TValue AddOrUpdate(TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
    {
        TValue value;
        value = this.collectionDictionary.AddOrUpdate(key, addValueFactory, updateValueFactory);

        if (this.collectionDictionary.TryGetValue(key, out value))
        {
            ArrayList valueList = new ArrayList() { value };
            ArrayList keyList = new ArrayList() { key };
            NotifyDictionaryChangedEventArgs e = new NotifyDictionaryChangedEventArgs(
                NotifyCollectionChangedAction.Add,
                valueList,
                keyList);

            this.Add(value, string.Empty);
            this.OnDictionaryChanged(e);
        }

        return value;
    }

And don't forget the enumerators:
        ///  Returns an enumerator that iterates through the
    /// ObservableExtendedCollection<TValue>.
    /// <returns> An enumerator for the
    /// underlying ObservableExtendedCollection<TKey,TValue>. </returns>
    public new IEnumerator<TValue> GetEnumerator()
    {
        return (IEnumerator<TValue>)base.GetEnumerator();
    }

    ///  Returns an enumerator that iterates through the
    /// System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>.
    /// <returns> An enumerator for the
    /// System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>. </returns>
    /// <param name="collectionFlag">Flag indicates to return the collection enumerator</param>
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator(bool collectionFlag = true)
    {
        return this.collectionDictionary.GetEnumerator();
    }

Now obviously I've left out some implementation as this is originally derived from my attempt (mostly successful) to make a readonly observable dictionary. But the basics do work. Hope this is of some use.

A: I've solved the problem by making the TextBox binding to the parent hosting Window's DataContext.
Thanks for everyone's comments.


text:
Q: Гидратация VueJs PHP Всем привет, народ помогите разобраться с Vue, для СЕО необходимо генерить код html на сервере, на клиенте минимальный функционал с vuejs: фильтровать, скрывать/показывать и тд.
<?php /** @var array $direction_list */
        foreach ($direction_list as $direction) : ?>

                <img src="<?= $direction['CountryImageUrl'] ?>" alt="">
                <a class="name" href="<?= $direction['url'] ?>"><?= $direction['CountryName'] ?>
                <a class="price" href="<?= $direction['url'] ?>">от <?= $direction['MinPrice'] ?> руб.

<a href="<?= $direction['url'] ?>">Подробнее

<?php endforeach; ?>

Как с помошью Вью спарсить html и дальше работать с ним? В голову приходит только при загрузки страницы брать данные по апи и заменять весь блок со странами а потом уже работать с ним. Доки прочитал и гугл шерстил ничего адекватного. Получается только замена поможет, помогите кто хорошо разбирается во вью)

A: Во вью кроме как серверного рендеринга нет других способов передать данные(взять данные из разметки) во Vuejs.
Если для SEO необходима разметка с данными, делайте это как обычно на сервере на php(например, в моем случае), далее описывайте компоненты для Vuejs и в разметке указывайте места вставки этих компонентов. Тогда поисковые роботы будут видеть структуру которая будет сгенирирована на сервере, а у посетителей при загрузке страницы Vuejs сравнит данные и заменит блоки на компоненты.
Если нужны подробные объяснения, напишите, постараюсь помочь


text:
Q: why is data not inserted in mysql database no error comes on the screen? I make a author_create_post.php for a News Agency Portal and Insert the data entries into mysql database. php script and form relies on same page. Form also used validation rules. After fill all form entries finally when I hit submit I got no any error but when I checked my database there is no insert entry, what is the problemb? How to solve it? Here is my complete code...
<?php
include "../tools/db.php";
include "../tools/functions.php";
include "../tools/jdf.php";
FetchPage("check_permission.php");
Permission("author");
if(isset($_POST["save"])){
    if($_POST["title"]!="" && $_POST["text"]!="" && $_POST["category"]!="" && $_POST["slider"]!="" && $_POST["important"]!=""){
        $title = ($_POST["title"]);
        $text = addslashes($_POST["text"]);
        $date = jdate('c');
        $time = time();
        $author_id = $_SESSION["user_id"];
        $cat_id=($_POST["category"]);
        $slider=($_POST["slider"]);
        $important=($_POST["important"]);

            switch($cat_id){
                case 0:
                    $cat_id = 0;
                    break;
                case 1:
                    $cat_id = 1;
                    break;
                case 2:
                    $cat_id = 2;
                    break;
                case 3:
                    $cat_id = 3;
                    break;
                default :
                    $cat_id = 4;
            }
            $s = "SELECT `title` FROM `$tbl_posts` WHERE `title`=:title";
            $res = $connect->prepare($s);
            $res->bindParam(":title",$title);
            $res->execute();
            if($res->rowCount()>=1){
                $exist ="عنوان پست تکراری می باشد!";
        }else{
            $r = $connect->query("SELECT * FROM `$tbl_posts` WHERE `important`=1");
            if($r->rowCount()>=5){
                $imp_count = "درحال حاضر بخش اخبار مهم تکمیل میباشد حداکثر ظرفیت این بخش 4 خبر است!";
            }else{
            $sql = "INSERT INTO `$tbl_posts` ( `author_id`, `title`, `category_id`, `time`, `text`, `date`, `slider`, `important` ) VALUES ( :author_id, :title, :category_id, :time, :text, :date, :slider, :important )";
            $result = $connect->prepare($sql);
            $result->execute( array(':author_id'=>$author_id, ':title'=>$title, ':category_id'=>$cat_id, ':time'=>$time, ':text'=>$text, ':date'=>$date, ':slider'=>$slider, ':important'=>$important));
            if(isset($result)){
                $success =" پست ".$title." در سایت منتشر شد ✓ ";
            }else{
                echo "";
            }
        }
    }
    }else{
        if($_POST["title"]=="") $titleerr = "عنوان مطلب را درج نمایید!";
        if($_POST["text"]=="") $texterr = "متن پست خالی میباشد!";

    }
}
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="mahdi">

    <meta name="keyword" content="FlatLab, Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina">
    <link rel="shortcut icon" href="img/favicon.html">

    <title>ارسال مطلب جدید</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-reset.css" rel="stylesheet">

    <link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
    <link href="assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen"/>
    <link rel="stylesheet" href="css/owl.carousel.css" type="text/css">

    <link href="css/style.css" rel="stylesheet">
    <link href="css/style-responsive.css" rel="stylesheet" />

        <?php FetchPage("top.php"); ?>

        <?php FetchPage("right.php"); ?>

                        <?php
                            if(isset($success) && $success!=""){
                        ?>

                            <button data-dismiss="alert" class="close close-sm" type="button">

                            </button>
                            تبریک ! <?=$success;?>

                        <?php
                        }
                        ?>

                        <?php
                            if(isset($titleerr) && $titleerr!=""){
                        ?>

                                <button data-dismiss="alert" class="close close-sm" type="button">

                                </button>
                                اخطار !  <?=$titleerr;?>

                        <?php
                        }
                        ?>

                        <?php
                            if(isset($imp_count) && $imp_count!=""){
                        ?>

                                <button data-dismiss="alert" class="close close-sm" type="button">

                                </button>
                                اخطار !  <?=$imp_count;?>

                        <?php
                        }
                        ?>

                        <?php
                            if(isset($texterr) && $texterr!=""){
                        ?>

                                <button data-dismiss="alert" class="close close-sm" type="button">

                                </button>
                                اخطار !  <?=$texterr;?>

                        <?php
                        }
                        ?>

ارسال مطلب جدید

                                <form class="form-horizontal" role="form" method="POST">

                                        عنوان مطلب

                                            <input type="text" class="form-control" style="width: 620px;" name="title" placeholder=" ">

                                        متن پست

                                                <textarea name = "text" style="width: 620px; height: 200px;"></textarea>

                                        دسته بندی

                                            <select name="category">
                                                <?php
                                                $sql = "SELECT * FROM `$tbl_category` ORDER BY `id` DESC";
                                                $result = $connect->query($sql);
                                                while($rows = $result->fetch(PDO::FETCH_ASSOC)){
                                                ?>
                                                <option value="<?=$rows["id"];?>"><?=$rows["title"];?></option>
                                                <?php
                                                }
                                                ?>
                                            </select>

                                        نمایش در اسلایدر

                                            <select name="slider">
                                                <option value="0">غیرفعال</option>
                                                <option value="1">فعال</option>
                                            </select>

                                        نمایش در اخبار مهم

                                            <select name="important">
                                                <option value="0">غیرفعال</option>
                                                <option value="1">فعال</option>
                                            </select>

                                            <input type="submit" name="save" class="btn btn-success" value="ثبت">
                                            <button type="reset" class="btn btn-default">انصراف</button>

                                </form>

A: change this:
$sql = "INSERT INTO `$tbl_posts` ( `author_id`, `title`, `category_id`, `time`, `text`, `date`, `slider`, `important` ) VALUES ( :author_id, :title, :category_id, :time, :text, :date, :slider, :important )";

to
$sql = "INSERT INTO `tbl_posts` ( `author_id`, `title`, `category_id`, `time`, `text`, `date`, `slider`, `important` ) VALUES ( :author_id, :title, :category_id, :time, :text, :date, :slider, :important )";

You had a $ sign before your table name
Also when verifying the success or failure of the execute function, do this
    if ($result === true) {
        $success =" پست ".$title." در سایت منتشر شد ✓ ";
    } else {
        echo "";
    }

isset does not verify that the query was successfully executed. And remember execute() returns true or false So you need to check based on the boolean values(true or false)


text:
Q: is LibVlc crossplatform? I am pretty new to working with media codecs, I was trying to play media files using Java and doing some research out there I found vlcj binding to match my need . I wish to bundle the libvlc native library along with the plugin modules in my application. My question is that is libvlc cross platform ? or is it more specific to the OS / architecture . I do know that each of the modules are compiled against specific architecture but how about the core libvlc itself ?

A: No, it's not cross platform - it's a native library, OS-specific. If you wish to distribute your resulting application as one multi-platform binary you'll have to include VLC for each and every platform you wish to support, it will get large very quickly. I'd advise against this approach.
Personally, I took the approach of building separate platform-specific installers (all still automated and taken care of via ant) and then just bundling the required native libraries. This also has the advantage that on some systems with good dependency support, the library doesn't need to be bundled at all (on Debian / Ubuntu for example, I simply add VLC as a dependency into the package's control file.


text:
Q: Recursion and binding I'm trying to understand how to work with recursion and I'm having a little trouble.
So from what I understand, if you attempt to use a local variable, the value will reset because the recursion starts at the top of the function every time (like a= [] will reset to an empty list every time).
Is there a way to complete a recursion while maintaining values ( for example, if I added values to a list) and keeping it to the local level ( within the function)?

A: There are two different approaches that I use to handle this. Each example will produce the list [1, 2, 3, 4].
The first approach uses an default argument that is empty at first, but is later used to pass an accumulator to the deeper calls.
def build_range(n, accumulator=None):
    accumulator = accumulator or []
    if n == 0:
        return accumulator

    accumulator.insert(0, n)
    return build_range(n-1, accumulator)

print build_range(4) # [1, 2, 3, 4]

The second approach uses list concatenation to build up the list by summing smaller lists. Note that this approach isn't great with lists because you keep having to build new ones, but can be cleaner for immutable data types.
def build_range(n):
    if n == 0:
        return []
    return build_range(n-1) + [n]

print build_range(4) # [1, 2, 3, 4]

Then, a third, non-recursive approach would be to unroll to recursion into a loop.
def build_range(n):
    accumulator = []
    while n:
        accumulator.insert(0, n)
        n -= 1
    return accumulator

print build_range(4) # [1, 2, 3, 4]

Obviously, this is kind of a tortured, inefficient example of building a range backwards (inserts are less ideal than appends), but hopefully it gets the ideas across.

A: It's a hard question to answer because it's not really clear what you understand and what you don't. @JaredGoguen has made a nice attempt at showing you a variety of techniques. I wanted to add a couple to it
This implementation uses an auxiliary recursive function. It works similarly to Jared's second implementation, but because of its tail call, it could be put on a trampoline to make it stack safe. This is how I implement recursive procedures at least 90% of the time.
def build_range (n):
  def aux (m, acc):
    if m == n:
      return acc
    else:
      return aux(m + 1, acc + [m])
  return aux(0, [])

print(build_range(4))
# [0, 1, 2, 3]

Another variation on this technique is to use a lambda as an accumulator. This is particularly useful for building an iterable in a forward direction without having to keep the pending result on the stack. Again, because of the tail call, a trivial modification could be made to utilize a trampoline and make it stack safe
def map (f, xs):
  def aux(xs, k):
    if not xs:
      return k([])
    else:
      return aux(xs[1:], lambda ys: k([f(xs[0])] + ys))
  return aux(xs, lambda x: x)

print(map(lambda x: x * x, [1,2,3,4]))
# [1, 4, 9, 16]


text:
Q: Lemmatizer supporting german language (for commercial and research purpose) I am searching for a lemmatization software which:

*

*supports the german language

*has a license that allows it to be used for commercial and research purpose. LGPL license would be good.

*should preferably be implemented in Java. Implementations in other programming languages would also be OK.

Does anybody know about such a lemmatizer?
Regards,
UPDATE: Hi Daniel, At first, thank you for the great work you are providing with the LanguageTool.
We would like to index german Texts into elasticsearch (ES) and pre-analyze the texts using either
 an ES-built-in german stemmer (please see https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-stemmer-tokenfilter.html)
or
the following plugin https://github.com/jprante/elasticsearch-analysis-baseform. The latter uses your morphology file under http://www.danielnaber.de/morphologie/morphy-mapping-20110717.latin1.gz and that is why I thought you maybe have some evaluation data in order to know what is the trade-off when using the lemmatization based on your morphology file instead of an ES-built-in stemmer. Do you maybe have some figures in terms of precision/ coverage of your german morphology? Or comparative data with the german stemmers used in Elasticsearch?
Best regards

A: LanguageTool can do that (disclaimer: I'm the maintainer of LanguageTool), it's available under LGPL and implemented in Java. You could use GermanTagger.tag(), the result can have more than one reading (as language is often ambiguous), and each reading's AnalyzedToken finally has a lemma.


text:
Q: Reg Ex matching time range I have a log file that saves logs by time stamp. What I have to do is to read certain values between time range. For example from the beginning of file and 5:3:55. I am not good with regex was wondering how can I write expression to read it. So far I have come with following expression which is not right. Any samples how to write it properly? Thanks
([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)

The post that has the solution for range doesnt work for my needs as it is taking a range of time and dealing with files. While I need to go from start of file time stamp than certain increment than do certain word matches. Thanks

A: Do not use regular expressions for maths! You might use them to parse all dates (e.g. with the regex you included in your question), but then do the comparisons against your given timestamps with the parsed value. It's like comparing numbers lexically.
If you really needed a regex that matches every date between 5:3:34 and 5:3:55, it would need to match all possible digits separately:
/5:3:(3[4-9]|4[0-9]|5[0-5])/

A: You need a bit more than a regex (at least to make a sane solution).  Here is a sample program that demonstrates a simple solution in Perl:
use warnings;
use strict;

my $time_min = '08:19:48';
my $time_max = '12:30:48';

while (1)
{
   print "enter time: ";

   chomp($_ = <STDIN>);

   if (time_numeric($_) <= time_numeric($time_max) and
       time_numeric($_) >= time_numeric($time_min))
   {
        print "$_ is between $time_min and $time_max\n";
   }
   else
   {
        print "$_ ain't between $time_min and $time_max\n";
   }
}

sub time_numeric
{
   if ($_[0] =~ /^(\d{1,2}):(\d{1,2}):(\d{1,2})$/)
   {
        return ($3 + $2 * 100 + $1 * 10000);
   }
   else
   {
        die "Invalid time!";
   }
}

It doesn't bother to validate the time, simply assuming that the input is real times.  It also only works with 24 hour time stamps.
It does work with input whether or not it has leading zeros in the fields.
If you are working in Perl, also consider using a module such as Time::Piece, as demonstrated in this answer.


text:
Q: How to detect a noexcept method using SFINAE I'm asking about a variation of a (popular) question - detecting the existence of a method of a class.
I've read many answers here in SO, and most of the (post C++17) solutions look like this:
#include <type_traits>

template<class ...Ts>
struct voider{
    using type = void;
};

template<class T, class = void>
struct has_foo : std::false_type{};

template<class T>
struct has_foo<T, typename voider<decltype(std::declval<T>().foo())>::type> : std::true_type{};

Basically, we're letting the compiler decide using a "trick" :
if the expression std::declval<T>().foo() is well-formed,
then decltype(std::declval<T>().foo()) doesn't produce a compiler-error,
then the compiler "prefers" has_foo<T, typename voider<decltype(...)>>::type since it doesn't need to replace the second template type  with a default type.
great, but how can we combine noexcept with it?
I've tried many ways but it seems most techniques (including decltype(declval<type>.my_func()))
only care about the name, return type and the argument types and not about the noexcept.

A: You can do it with the help of noexpect operator (since C++11).

The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions.

e.g.
template<class T>
struct has_foo<T,
               typename voider<decltype(std::declval<T>().foo()),
                               std::enable_if_t<noexcept(std::declval<T>().foo())>
                              >::type
              > : std::true_type{};

LIVE


text:
Q: My activity_main.xml still uses the default theme even after I specified another theme My activity_main.xml still uses the default theme even after I specified another theme. Please find my code below:
styles
<resources>

    <!-- Launch screen -->
    <style name="LaunchScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->

    </style>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->

    </style>

</resources>

manifest
 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

  ...

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    ...
    android:theme="@style/LaunchScreenTheme"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:src="@drawable/logo_orange"

    />

</LinearLayout>

Even though I've set the LaunchScreenTheme above, it still uses the default AppTheme
Any idea why?

A: In activity_main.xml, try style:"@style/LaunchScreenTheme" instead android:theme="@style/LaunchScreenTheme"

A: if you want to set a theme specifically for an activity then you have set it like this in your manifest -
<activity
        android:name=".StartActivity"
        android:theme="@style/LaunchScreenTheme" />

if you want to set a theme for the whole application then you have to set it like this is your manifest -
 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/LaunchScreenTheme">

...


text:
Q: RSS Reader(WebClient/XmlTextReader) somehow uses wrong encodig - including failing Unittest I have a rssReader working fine on some rss feeds but I got one where I have some problems with special danish charaters - encoding I expect.
I see this encoding in the raw Http response form this url:
http://www.sydvestjyllandsefterskole.dk/rss
Content-Type: text/xml; Charset=UTF-8
<?xml version="1.0" encoding="iso-8859-1" ?>

Have tried those 2 encodings and others but nothing seems to work.
I have made a unittest to show the problem and what I have tried: (NUnit)
public IEnumerable<TestCaseData> RssItemEncodingTestCases
{
    get
    {
        yield return new TestCaseData("http://www.sydvestjyllandsefterskole.dk/rss", "Stort fremmøde til dejlig familiedag.", new ASCIIEncoding());
        yield return new TestCaseData("http://www.sydvestjyllandsefterskole.dk/rss", "Stort fremmøde til dejlig familiedag.", new UTF8Encoding());
        yield return new TestCaseData("http://www.sydvestjyllandsefterskole.dk/rss", "Stort fremmøde til dejlig familiedag.", new UnicodeEncoding());
        yield return new TestCaseData("http://www.sydvestjyllandsefterskole.dk/rss", "Stort fremmøde til dejlig familiedag.", Encoding.GetEncoding("ISO-8859-1"));
    }
}

[TestCaseSource("RssItemEncodingTestCases")]
public void TestEncoding(string url, string expectedToStartWith, Encoding encoding)
{
    var description = Read(url, encoding);

    Assert.That(description, Is.StringStarting(expectedToStartWith));
}

public string Read(string url, Encoding encoding = null)
{
    var client = new WebClient();
    if (encoding != null)
        client.Encoding = encoding;
    try
    {
        using (XmlReader reader = new XmlTextReader(client.OpenRead(url)))
        {
            while (reader.Read())
            {
                if (reader.IsStartElement() & reader.Name == "item")
                {
                    while (reader.Read())
                    {
                        switch (reader.Name)
                        {
                            case "description":
                                return reader.ReadElementContentAsString();
                        }
                        if (reader.Name == "item" & reader.NodeType == XmlNodeType.EndElement)
                            break;
                    }
                }
            }
        }
    }
    catch
    {

    }
    return null;
}

Expected: String starting with "Stort fremmøde til dejlig familiedag."
  But was: "Stort fremmøde til dejlig familiedag.

Any idea how to get this decoded properly?

A: It got fixed by making them change the encoding of the RSS feed to utf-8:
<?xml version="1.0" encoding="utf-8" ?>


text:
Q: How can I know the greatest value of the function knowing its derivative? I answered this as g(5), and my justification was that at the first part of the drawing(until x = 4) $g^{'}$ is negative, so the function was decreasing. after $x=4$, $g^{'}$ is positive, so the function is increasing. but my answer was wrong, could anyone trace where is my wrong thought?
I have to answer the question in no more than 2.5 minutes.

A: You are confusing the slope in the plot of $g'$ with the sign of $g'$.
Since $g'$ is positive on $[0,2]$, $g$ is increasing there. Then $g'$ is negative on $[2,5]$ so it is decreasing there. So $g(2)$ is the maximum.


text:
Q: Why do i get these hyperlinks on my website? Security Flaw? In the image below is where I recently found these malicious hyperlinks.
I tried to log into my web-host and I couldn't find any hyperlinks attached to the elements in my files.

My Questions:

*

*How do I avoid these?

*How can I remove them?

*Despite these hyperlinks, Is my website vulnerable to any XSS attacks? If yes, please specify the holes i should fill.

I am using Ajax to send an instant response if the email already exists or not; Would this influence the attacker to easily send XMLHTTPRequests to the server?
I just want to make my website 100% safe as in a matter of none would ever get into the database ( confidentiality, integrity, and availability ) considering I have SSL certificate over HTTPS. Even if it's only login system website without many complicated input stuff.
I heard using SQL stored procedures help, also HTML encoding.
Please visit the website and take a look over the code
www.tarsh.tk
Any Help/Hints/Tips/Links would be appreciated.

A: The site at www.tarsh.tk does not have any hyperlinks for me see http://picpaste.com/Screen_Shot_2016-03-20_at_11.29.02_PM-F7OsKLUZ.png.
Maybe it isn't the site and it is your browser. Have you tried a different browser?
I used Chrome 49 and Safari 9, both are rendering the site without hyperlinks.


text:
Q: Collectd - Perl/Python plugin - registration functions not working I would like to ask about Collectd's plugins Perl and Python and their registration functions.
I tried to code plugin in Perl (and also in Python), set up read and write functions and after that register them into Collectd (plugin_register functions). In all cases it wasnt working. Everytime, the logs show:

Found a configuration for the "my_plugin" plugin, but the plugin
  isn't loaded or didn't register a configuration callback.
  severity=warning

I load my plugin in perl.conf.
Below I attach example of plugin which is directly from Collectd.perl documentation. This plugin, as well as my plugin, has the same result.
package Collectd::Plugins::FooBar;
  use strict;
  use warnings;
  use Collectd qw( :all );

  sub foobar_read
    {
    my $vl = { plugin => 'foobar', type => 'gauge' };
    $vl->{'values'} = [ rand(42) ];
    plugin_dispatch_values ($vl);
    return 1;
    }
  sub foobar_write
    {
    my ($type, $ds, $vl) = @_;
    for (my $i = 0; $i < scalar (@$ds); ++$i) {
      print "$vl->{'plugin'} ($vl->{'type'}): $vl->{'values'}->[$i]\n";
    }
    return 1;
    }

  sub foobar_match
    {
    my ($ds, $vl, $meta, $user_data) = @_;
    if (matches($ds, $vl)) {
      return FC_MATCH_MATCHES;
    } else {
      return FC_MATCH_NO_MATCH;
    }
    }

  plugin_register (TYPE_READ, "foobar", "foobar_read");
  plugin_register (TYPE_WRITE, "foobar", "foobar_write");
  fc_register (FC_MATCH, "foobar", "foobar_match");

A: Post your configuration if you can.
The documentation says that the LoadPlugin configuration goes in the collectd.conf file (not that that seems to matter in your case from your log file).
Put your foobar.pm module at /path/to/perl/plugins/Collectd/Plugins/FoorBar.pm matching it with the path that you specified ... (match the case of names of plugin and plugin pm file).
LoadPlugin perl
# ...
<Plugin perl>
  IncludeDir "/path/to/perl/plugins"
  BaseName "Collectd::Plugins"
  EnableDebugger ""
  LoadPlugin "FooBar"

  <Plugin FooBar>
    Foo "Bar"
  </Plugin>
</Plugin>


text:
Q: Vector times reverse of vector I'm programming, and I need to do a dot product of one vector and the reverse of another vector. For example, if my two vectors are
$$<x_1,x_2,x_3>,<y_1,y_2,y_3>$$
I want to calculate $x_1y_3 + x_2y_2 + x_3y_1$. How do I express this using linear algebra operations? It's always faster to tell the computer to do those than to implement them yourself. I'm really shaky on this stuff!

A: Call your first vector $x$ and the other vector $y$. Let $$A=\left(\begin{array}{ccc}
0 & 0 & 1\\
0 & 1 & 0\\
1 & 0 & 0\\ \end{array}\right).$$
Then the value you want is $x^T\cdot A\cdot y.$

A: You mentioned in the comments that you are using Python with NumPy. Then there is a way to exploit that:
>>> import numpy as np
>>> x = np.array([1,2,3])
>>> y = np.array([4,5,6])
>>> y[::-1]
array([6, 5, 4])
>>> np.dot(x,y[::-1])
28

Of course, this is more suited for StackOverflow.


text:
Q: Existence of $f \in L^2(\Bbb R^n)$ with $f=g_1$ on $E$ and $\mathscr{F}(f)=g_2$ on $F$ The question has been posted here but had no response.

Question:
Suppose $E,F$ subsets of $\Bbb R^n$ have finite measure. Show that for any $g_1,g_2 \in L^2(\Bbb R^n)$ there exists $f \in L^2(\Bbb R^n)$ with
$f=g_1$ on $E$ and $\mathscr{F}(f)=g_2$ on $F$,where $\mathscr{F}(f)$ is the Fourier transform of $f$.
My attempt:
This is a problem from Schlag's book Classical and multilinear harmonic analysis, chapter 10 problem 10.3. I try to prove it by contradiction and Amrein-Berthier thm but failed.
Any solution or hint is highly appreciated.
A-B thm: Let E,F be sets of finite measure in $\Bbb R^n$.Then $ \left\|f\right\|_{L^2(\Bbb R^n)} \leq C( \left\|f\right\|_{L^2(E^c)}+ \left\|\mathscr{F}(f)\right\|_{L^2(F^c)} )$ for some $C=C(E,F,n)$

A: Let $V \subset L^2(\mathbb{R})$ be the space of functions supported on $E$, and $W$ the space of functions whose Fourier transform is supported on $F$.  (This notation differs from Jason's hint, sorry.)  Note both subspaces are closed.  Use the A-B theorem to show that $V \cap W = 0$, which is easy, and that $V+W$ is closed, which is a little harder.  One approach to the latter is this: any function in $V+W$ can be written uniquely as $f+g$ where $f \in V$, $g \in W$.  Then $V+W$ is closed iff the operators $f+g \mapsto f$ and $f+g \mapsto g$ are bounded, for then the map $f+g \mapsto (f,g)$ is an isomorphism of $V+W$ with $V \oplus W$.
To show the latter, we can use the A-B theorem to write, for $f \in V$, $g \in W$,
$$\require{cancel}\begin{align*}
\|f\|_{L^2(\mathbb{R})} &\le C(\cancel{\|f\|_{L^2(E^c)}} + \|\mathcal{F}(f)\|_{L^2(F^c)}) \\
&= C \|\mathcal{F}(f+g)\|_{L^2(F^c)} && \text{since $\mathcal{F}g = 0$ on $F^c$} \\
&\le C \|\mathcal{F}(f+g)\|_{L^2(\mathbb{R})} \\
&= C\|f+g\|_{L^2(\mathbb{R})} && \text{Plancherel}.
\end{align*}$$
So the map $f+g \mapsto f$ is bounded, and a similar argument works for $f+g \mapsto g$.
Now that $V+W$ is closed, consider the orthogonal projections $P_V h = 1_E \cdot h$ and $P_W h = \mathcal{F}^{-1} (1_F \cdot \mathcal{F}h)$.  By the below lemma, taking $f = g_1 \in V$ and $g=\mathcal{F}^{-1} g_2$, we can find $h$ such that $P_V h = f$, which is to say $h=g_1$ on $E$, and $P_W h = g$, which is to say $\mathcal{F}h = g_2$ on $F$.

Lemma.  Suppose $V,W$ are two closed subspaces of a Hilbert space $H$ with $V \cap W = 0$ and $V+W$ closed.  Then for every $f \in V$, $g \in W$, there exists a unique $h \in V+W$ with $P_V h = f$ and $P_W h = g$.

I don't have a reference for this, so here's a proof based on ideas from [1].
The idea is that if we want to have $(P_V + P_W)h = f+g$, where $h=v+w$ with $v \in V$, $w \in W$, then we must have
$$\begin{align*} v + P_V w &= f \\ w + P_W v &= g. \end{align*}$$
Applying $P_V$ to the second equation and subtracting, we need to have $v - P_V P_W v = f - P_V g$.  We show that we can find such $v$, and that it works.
Let $P_W|_V$ be the restriction of $P_W$ to $V$.  Then I claim $\|P_W|_V\| < 1$.  To see this, first recall that $v+w \mapsto v$ is bounded, so there is a constant $K$ so that $\|v\| \le K \|v+w\|$ for all $v \in V$, $w \in W$.  Now let $v \in V$ be arbitrary. Since $P_W v$ and $v - P_W v$ are orthogonal, the Pythagorean theorem gives
$$\|v\|^2 = \|P_W v\|^2 + \|v-P_W v\|^2 \ge \|P_W v\|^2 + \frac{1}{K^2} \|v\|^2$$
and thus $\|P_W v\|^2 \le (1-\frac{1}{K^2}) \|v\|^2$.
As such, the operator $I - P_V P_W$, considered as an operator on $V$, is invertible.  Let $v = (I-P_V P_W)^{-1}(f - P_V g)$, so that $v - P_V P_W v = f - P_V g$.  Then set $w = g - P_W v$, and $h = v+w$.  We now have
$$\begin{align*}
P_V h &= v + P_V g - P_V P_W v = f - P_V g + P_V g = f \\
P_W h &= P_W v + g - P_W v = g
\end{align*}$$
as desired.

[1] Deutsch, Frank, The angle between subspaces of a Hilbert space, Singh, S. P. (ed.) et al., Approximation theory, wavelets and applications. Proceedings of the NATO Advanced Study Institute on recent developments in approximation theory, wavelets and applications, Maratea, Italy, May 16-26, 1994. Dordrecht: Kluwer Academic Publishers. NATO ASI Ser., Ser. C, Math. Phys. Sci. 454, 107-130 (1995). ZBL0848.46010, https://doi.org/10.1007/978-94-015-8577-4_7

A: For a solution of your problem, see Remark 4.11 in the paper Patrick L. Combettes, Noli N. Reyes, Functions with prescribed best linear approximations, Journal of Approximation Theory, 162 (2010) 1095--1116.


text:
Q: How to refresh a Page using react-route Link I am trying to refresh a page using react-route Link. But the way I have implemented it goes to the URL one step back.(as an example if the URL was ../client/home/register and when I press the reload is goes to ../client/home)
below is my code
const AppErrorPage = () => (

Error

 Something went wrong, please reload the page

         <Link to="" refresh="true">
            Reload
          </Link>

);

A: I ended up keeping Link and adding the reload to the Link's onClick event with a timeout like this:
function refreshPage() {
    setTimeout(()=>{
        window.location.reload(false);
    }, 500);
    console.log('page to reload')
}

<Link to={{pathname:"/"}} onClick={refreshPage}>Home</Link>

without the timeout, the refresh function would run first

A: You can use this
 {window.location.href="/something"}}>Something

A: You can simply run this after successful query.
window.location.reload();

A: Try like this.
You must give a function as value to onClick()
You button:
<button type="button" onClick={ refreshPage }> Reload </button>

refreshPage function:
function refreshPage(){
    window.location.reload();
}

A: To refresh page you don't need react-router, simple js:
window.location.reload();

To re-render view in React component, you can just fire update with props/state.

A: Here's one way of doing it using React Bootstrap and a component that you can then drop into any page...
import Button from 'react-bootstrap/Button';

export const RefreshCurrentPage = () => {

  function refreshPage(){
    window.location.reload();
  }

  return (

      <Button onClick={ refreshPage } variant="secondary" size="sm" className="btn ml-4">Refresh Page</Button>

  );

}


text:
Q: Slide image with swipe handler in Windows Phone 8.1 I have created some images in Adobe PhotoShop to introduce the user to an application in WP 8.1 in C#. I want to display and intro Page, only if the user's settings is empty (it is a very simply but good boolean condition for my case).
So when the user open for the first time the application, the first image will be opened, if the user swipe to the left, the second one will appear, in case swipe to the right, nothing should happen, because the image -1 doesn't exist:
public int getPage (int newPage)
{
    if (0 <= newPage <= N_IMAGES) {
        return newPage;
    }
    if (newPage < 0) {
        return 0;
    } else {
        return N_IMAGES;
    }
}

My images are named: intro1.png, intro2.png, intro3.png and intro4.png.
So to summary it: Open application, first intro, swipe left, second intro....

*

*How Can I make this intro in WP 8.1 ?
So the intro is like a slide show, where the images changed on swipe left/right.

*For the last images, is possible to add over it, some button, not displayed, but clickable ?
Thank you in advance for your help.
UPDATE x2 (WORKS)
Hi,
I finally let it works; the problem was due to the fact that the images, must be added in a particular way, and not just copy and past.
<Grid Name="introgrid">
    <FlipView x:Name="flipView1" SelectionChanged="FlipView_SelectionChanged">

        <FlipViewItem Name="first" Width="395">
            <FlipViewItem.Background>
                <ImageBrush ImageSource="Assets/intro1.png"/>
            </FlipViewItem.Background>

        </FlipViewItem>
        <FlipViewItem Name="second" Width="395">
            <FlipViewItem.Background>
                <ImageBrush ImageSource="Assets/intro2.png"/>
            </FlipViewItem.Background>
        </FlipViewItem>

        <FlipViewItem Name="third">
            <FlipViewItem.Background>
                <ImageBrush ImageSource="Assets/intro3.png"/>
            </FlipViewItem.Background>
        </FlipViewItem>
        <FlipViewItem Name="final" Width="395">
            <FlipViewItem.Background>
                <ImageBrush ImageSource="Assets/3.jpg"/>
            </FlipViewItem.Background>
            <StackPanel HorizontalAlignment="Center" VerticalAlignment="Top">
                <Image Source="Assets/Face.png" Width="180" />
                <TextBlock Text="Se hai già le credenziali:" FontSize="25" Margin="0,15,0,0" HorizontalAlignment="Center"/>
                <Button x:Name="login" Content="Accedi" HorizontalAlignment="Center" Margin="0,15,0,0" FontSize="22" Background="#FF0DACE9" Click="login_action" />
                <TextBlock Text="Se non ti sei ancora registrato:" FontSize="25" Margin="0,15,0,0" HorizontalAlignment="Center"/>
                <Button x:Name="register" Content="Registrati" HorizontalAlignment="Center" Margin="0,15,0,0" FontSize="22" Background="#FF0DACE9" Click="register_action" />
                <TextBlock Text="Hai qualche domanda ?" FontSize="25" Margin="0,15,0,0" HorizontalAlignment="Center"/>
                <Button x:Name="info" Content="Sito web" HorizontalAlignment="Center" Margin="0,15,0,0" FontSize="22" Background="#FF0DACE9" Foreground="White" Click="info_action" />
            </StackPanel>

        </FlipViewItem>
    </FlipView>
</Grid>

A: The FlipView control is probably what you need.
You can have a setting in the app local storage that will tell you when this view has been displayed and on next load not show it if the setting exists.
More info on FlipView
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh781233.aspx


text:
Q: ASP.NET Running Application within subdirectory I'm wondering how it is possible to run an MVC application in a subdirectory. The problem is that when running in a subdirectory, every Action seems to be navigated to the Root path rather then the subdirectory.
In order to test if it would work, I've edited the "Project URL" and "Override application root URL" in the project properties window.
I've considered adding a key to the web.config with the configurable routing value and creating a singleton class that would read this key, although i would have to manually editing all pages to make it work, but clearly that wouldn't be the best way out there as it would take a lot of time and when willing to change the directory name, you'd have to change it over all the pages in the application.
Another thing I tried is editing the RouteConfig.cs file and replacing / adding it along with the default router.
routes.MapRoute(
            name: "Rooted",
            url: "{root}/{controller}/{action}/{id}",
            defaults:
                new { root = "Admin", controller = "Login", action = "Index", id = UrlParameter.Optional }
        );

Sadly this however didn't seem to work either as it would still redirect to Index/Home instead of Admin/Index/Home.
I'm wondering if someone has a better idea how to get this to work with as little change as possible. I can't be the first one to ask this, and when Googling about possible duplicates none came up with a suitable solution.

A: I don't know if is what you are looking for but I have a MVC project running under subdirectory of a main project. For every root I have to write in RouteConfig 2 rules.
Consider that my subDirectory is sport.
 Example for images
           routes.MapRoute(
                name: "Images",
                url: "files/images/{width}x{height}/{myID}.png",
                defaults: new { controller = "ControllerName", action = "ActionName" },
              constraints: new RouteValueDictionary { { "width", "[0-9]+" }, { "height", "[0-9]+" }, { "myID", "[0-9a-z_]+" }}
            );
            routes.MapRoute(
                name: "Images2",
                url: "sport/files/images/{width}x{height}/{myID}.png",
                defaults: new { controller = "ControllerName", action = "ActionName" },
              constraints: new RouteValueDictionary { { "width", "[0-9]+" }, { "height", "[0-9]+" }, { "myID", "[0-9a-z_]+" }}
            );

In your case if (for example) your subdirectory is test try in this way
1st rule for local
routes.MapRoute(
            name: "Rooted",
            url: "{controller}/{action}/{id}",
            defaults:
                new { controller = "Login", action = "Index", id = UrlParameter.Optional }
        );

2ns rule for pubblished
routes.MapRoute(
                name: "Rooted",
                url: "test/{controller}/{action}/{id}",
                defaults:
                    new { controller = "Login", action = "Index", id = UrlParameter.Optional }
            );

before doing this you should add a new Application (as subDirectory) to your site from IIS.
Follow these steps

*

*Open IIS Manager

*Right click on Default Web Site and select "Add Application"

*Set the Virtual Path "YourSubDireCtoryName" and and the proper
Physical Path (Put all project files in a folder where you want; just write the correct path)

A: Turned out my problem was caused by something entirely different.
It went to the rootfolder because the form submit contained a hard path aka "/login/login" instead of "~/login/login".
Even though it was not the answer, I suggest people to look at faby's post too as it does contain some nice information which shouldn't get lost.


text:
Q: iOS OpenGL ES Analyzer lists "Non-Existent Framebuffer Attachment" and "Missing Framebuffer Attachment", yet the FBO works I'm using an OpenGL framebuffer object (FBO) to implement stencil shadows on iOS. The code works—that is, visually the stencil buffer is doing the job, and performance seems fine.
When I run the application through the OpenGL ES Analyzer instrument, however, it complains of a "Non-Existent Framebuffer Attachment" and "Missing Framebuffer Attachment." I can't make sense of these messages, since the FBO does have attachments for color, depth, and stencil. A call to glCheckFramebufferStatus() returns GL_FRAMEBUFFER_COMPLETE, indicating no problems.
Is this a bug in Instrument's OpenGL Analyzer?
See also this thread, which gives no answers, but raises the same issue.

A: I finally got an answer from Apple on their Forums:
APPLE OFFICIAL REPLY

Thanks for reporting this bug. This is a known issue that is fixed in
  the Xcode 4.4 & 4.5 Developer Previews.   Cheers, Seth.


text:
Q: LDAP Authentication always requires the domain as part of username I'm trying to authenticate a user using LDAP for Windows Server for AD authentication.  Below is my code:
 string domList = "LDAP://172.21.0.1:389/CN=Configuration,DC=myDom,DC=local;
 System.DirectoryServices.DirectoryEntry deRoot = new System.DirectoryServices.DirectoryEntry(domList, userNameURL, password, authType);
                                    deRoot.RefreshCache();

This works fine in most cases, I have one particular site where I get an invalid username/password error.
If I change the username to be of the format myDom\username then it works.  However I only want the user to enter their username. I don't see why the domain is needed as it's part of the LDAP connection string.  Any ideas why this is happening?

A: This turned out to be a red herring.  I need to set the authentication type to be secure


text:
Q: casting a type parameter to a basic type without boxing Is there any way to make a code like this work:
public class Func2<A, B>
{
    private Func<A, B> f;

    public Func2(Func<A, B> f)
    {
        this.f = f;
    }

    public object invoke(object obj, long l)
    {
        if (typeof(B) == typeof(long))
        {
            if (obj != null)
                l = (long)obj;
            return f((B)l); //error! cannot convert type 'long' to 'B'
        } else {
            return f((B)obj);
        }
    }
}

The problem here is that I cannot directly cast B to long without casting B to object first. I am trying to avoid at all costs having to box, as it would slow down a lot fast operations on functions. So is there any way to achieve this?
I know I could actually define a specialized Func2 to specifically handle the case of when B is a long. But as the arity of the function grows, the combination of longs and objects grow  exponentially - and in the real use case I want also to support doubles !. Is there any way to support this without boxing? Maybe with unsafe code?
Thank you!
Cauê

A: You can overload the method, and instead of casting the long value to A, you can cast the delegate to Func<long, B>:
public class Func2<A, B> {

  private Func<A, B> f;

  public Func2(Func<A, B> f) {
    this.f = f;
  }

  public B invoke(long a) {
    if (typeof(A) == typeof(long)) {
      return (f as Func<long, B>)(a);
    } else {
      throw new NotSupportedException();
    }
  }

  public B invoke(object a) {
    return f((A)a);
  }

}

Example:
Func2<long, string> f = new Func2<long, string>(l => l.ToString());

Console.WriteLine(f.invoke(42)); // calls the invoke(long) method
Console.WriteLine(f.invoke("x")); // calls the invoke(object) method

A: Just found out the answer ! : )
public object invoke(object obj, long l)
{
    if (typeof(B) == typeof(long))
    {
        if (obj != null)
            l = (long)obj;
        Func<A, long> x = (Func<A, long>)(object)f;
        return x(l);
    } else {
        return f((B)obj);
    }
}

This way we don't have to autobox the long to object, but we actually cast the Func type to receive the long we specified!
As for why I am trying to do this, read the above comment, and I'd still be trying to find a best way to do this.
By now, we have the following Haxe code:
var f:Int->Int->Float = function(x:Int, y:Int) return x + y + 0.5;
var f2:Dynamic->Dynamic->Dynamic = f; // ok
var f3:Dynamic->Int->Dynamic = f; //also ok
f2(10, 30); // ok - this will box the 10 and 30

What I'm trying to do is create a Fun3 type that has an invoke call that will take both the boxed and unboxed arguments. If the underlying function really accepts unboxed types, it will try first to use them.


text:
Q: Removing Column Header using JSLink I know this is probably an easy thing, but I'm not finding it anywhere (my GoogleFu isn't up to par, I guess). I'm trying to remove column headers in a list when reformatting using JSLink. We are currently using SP2013.
Basically, I have a list with two columns. One column stores a URL, while the other column stores the description (or what is displayed as the hyperlink). When all is said and done, I only want the hyperlink to be displayed. At this point, I'm able to display what I want using the following code, but I don't know how to turn off the headings:
(function () {

var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.Templates.Fields = {

'URL': { 'View': quickLinks },
'Title': { 'View': quickLinks2 }

};

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);

}) ();

function quickLinks(ctx) {

    var urllink = ctx.CurrentItem.URL;
    var urldesc = ctx.CurrentItem.Title;
    var appeldLink = "" + urldesc + "";

    return appendLink;

}

function quickLinks2(ctx) {

    var urldesc2 = "";

    return urldesc2;

}

I'm sure what I'm asking to do is uber easy ... I'm just not finding it. What can I add to the above code to remove the column headers? (NOTE: The above code is working just fine to display what I need. I'm just looking to be rid of the column headers.)

A: There's a Header Template you can use to override the header:
overrideCtx.Templates.Header = function(ctx) {return "--"};

This plugin may help you: https://chrome.google.com/webstore/detail/cisar/nifbdojdggkboiifaklkamfpjcmgafpo?hl=en


text:
Q: webapp does not appear on firebase dashboard alongside android app I'm working on an android app and using Firebase. I'd like to have a webapp alongside this android app in the same project. When I click on the option to add a webapp I just get the script-tag for the HTML page. Serving the page locally works but nothing appears on the console indicating that there is also a webapp in this project. Is this normal?

A: This is indeed the expected behavior. Web apps are managed differently than Android and iOS apps and never show in your list of apps.


text:
Q: Auto focus text field in UIWebview I am loading a webview form in my iOS app and I want to autofocus a textfield on the form. I tried
NSString *focus = [NSString stringWithFormat:@"document.getElementsByName('j_captcha')[0].focus()"];
[self.webView stringByEvaluatingJavaScriptFromString: focus];

But that doesnt seem to work. "j_captcha" is the name of the textfield. How can I achieve this?

A: This did the trick for me
NSString *evalStr = [NSString stringWithFormat:@"setTimeout( function(){document.getElementsByName('j_captcha')[0].focus();},1000);"];
[webView stringByEvaluatingJavaScriptFromString:evalStr];

This post helped - https://stackoverflow.com/a/14268931/653978


text:
Q: Use of importing scss in react component I am trying to understand a project and there I found an interesting way of applying styles to the component.  I would like to know what are the advantages that one can get by using this type of styling.
**productRow.scss**

    #price{
        background-color:yellow;
    }

productRow.js
import PropTypes from 'prop-types';
import React from 'react';
import {price} from '../styles/productRow.scss';//Here extracted price from the styles file

const ProductRow = ({data}) =>{
    return(

{data.name}-{data.price}

);};

ProductRow.propTypes = {
    data: PropTypes.object,
    ToggleDetails: PropTypes.bool
};

export default ProductRow;


text:
Q: PHP MySQL How To and Performance I'm struggling a bit on the best way to do this with as little performance hit as possible.
Here's the setup...
Search results page with search refining filters that make an AJAX call to a PHP handler which returns a new (refined) set of results.
I have 4 tables that contain all of the data I need to connect to in the PHP handler code.
Table 1 - Main table of records with main details
Table 2 - Ratings for each product from professional rating company #1
Table 3 - Ratings for each product from professional rating company #2
Table 4 - Ratings for each product from professional rating company #3
The refiners on the search results page are jquery sliders with ranges from the lowest allowed rating to the highest for each.
When a slider handle is moved, a new AJAX call is made with the new value(s) and the database query will run to create a fresh set of refined results.
Getting the data I need from Table 1 is the easy part. What I'm struggling with is how to efficiently include a join on the other 3 tables and only picking up rows that match the refining values/ranges.  Table 2, 3, and 4 all have multiple columns for year (2004-2012) and when I made an initial attempt to put it all into one query, it bogged down.
Table 2, 3, and 4 hold the various ratings for each record in Table 1.
The columns in Table 2, 3, and 4 are...
id - productID - y2004 - y2005 - y2006 - y2007 - ... you get the idea.
Each year column has a numeric value for each record (default is 0).
What I need to do is efficiently select records that match the refiner ranges selected by the user across all 4 tables at once.
An example refiner search would be...get all records from Table 1 where price is between $25 and $50 AND where Table 2 records have a rating (from any year/column) between 1 - 4 AND where Table 3 records have a rating (from any year/column) between 80 - 100 AND where Table 4 records have a rating (from any year/column) between 80 - 100.
Any advice on how to set this up with as much performance as possible?

A: My suggestion would be to use a different table structure. You should merge Table 2, 3 and 4 into a single ratings table with the following structure:
id | productID | companyID | year | rating

Then you could rewrite your query as:
SELECT *
FROM products p
JOIN ratings r ON p.id = r.productID
WHERE p.price BETWEEN 25 AND 50
    AND (
        ( r.companyID = 1 AND r.rating BETWEEN 1 AND 4 )
        OR ( r.companyID = 2 AND r.rating BETWEEN 80 AND 100 )
        OR ( r.companyID = 3 AND r.rating BETWEEN 80 AND 100 )
    )

This way the performance would surely increase. Also, your tables will be more scalable, both with the years and the number of companies.
One more thing: if you have a lot of fields in your products table, it might be more useful to execute 2 queries instead of joining. The reason for this is that you are fetching redundant data - every joined row will have the columns for product, even though you only need it once. This is a side-effect of joins, and there is probably a performance threshold where it will be more useful to query twice than to join. It is up to you to decide if/when that is the case.


text:
Q: Asymptotic for a binomial sum Is it possible to derive an asymptotic expression as $n \to \infty$ for the following sum:
$$S_n(a,x) = \sum_{k=1}^n \binom{n}{k} \frac{k!^2 x^k}{k \cdot (a)_k} $$
$(a)_k$ is the rising factorial (Pochhammer symbol).
Euler-Maclaurin seems way too complicated here, and I'm not sure what else to try.

A: Einar Rødland showed that
$$
S_n (a,x) \approx n!B(a,n)x^n {}_1F_1\! \left( { - n - a + 1, - n + 1;\tfrac{1}{x}} \right).
$$
Here $B$ is the beta function and ${}_1 F_1$ is one of Kummer's hypergeometric functions. Employing Kummer's transformation ${}_1F_1 (- n - a+1;- n+1;\tfrac{1}{x}) = e^{1/x} {}_1F_1 (a;1 - n; - \tfrac{1}{x})$ and truncating the series for ${}_1F_1$ after $n$ terms, we obtain the approximation
$$
S_n (a,x) \approx \frac{{n!}}{{\Gamma (n + a)}}x^n e^{1/x} \sum\limits_{k = 0}^{n - 1} {\frac{{\Gamma (k + a)}}{{k!x^k }}\Gamma (n - k)} .
$$
Note that, in general, the terms in the sum are decreasing in magnitude as $k$ is increasing. Numerically this formula seems to perform very well even when $|a/x|$ is comparable with or larger than $n$. Indeed, the ratio of the last and the first term is
$$
\frac{{\Gamma (n + a - 1)}}{{\Gamma ^2 (n)\Gamma(a)x^{n - 1} }},
$$
which is small if $x$ is not close to $0$ even if $a=\mathcal{O}(n)$. For large $n$, one may truncate the series after any finite number of terms to obtain simpler approximations. In particular, to leading order,
$$
S_n (a,x) \approx n!B(a,n)x^n e^{1/x} .
$$

A: I followed the same suggestion as @Maxim of summing over $r=n-k$. The main reason is that for large $n$, ie $n\gg a, 1/|x|$, the largest terms are with $k$ close to $n$: having them for small $r$ is more convenient.
This gave me a somewhat different looking expression:
$$
S_n(a,x)
= \frac{n!(n-1)!(a-1)!x^n}{(n+a-1)!}\cdot
  \sum_{r=0}^{n-1}\frac{(n+a-1)^{\underline{r}}}{(n-1)^{\underline{r}}r!x^r}
= \frac{(n-1)!x^n}{\binom{n+a-1}{a-1}}\cdot
  \sum_{r=0}^{n-1}\frac{\binom{n+a-1}{r}}{\binom{n-1}{r}r!x^r}
$$
where $m^{\underline{r}}=m!/(m-r)!$ is the falling factorial. The sum actually corresponds to a generalised hypergeometric series
$$
S_n(a,x)
\sim \frac{(n-1)!x^n}{\binom{n+a-1}{a-1}}\cdot
  {}_1F_1\left(
  \genfrac..{0pt}{}{-(n+a-1)}{-(n-1)}
  ;\frac{1}{x}\right)
$$
although this does not exist when $n,a$ are positive integers as the denominator becomes zero for $r\ge n$ so the GHS is not naturally truncated to $r<n$.
I'm not sure what type of arguments are of interest. For large $n$, we may approximate $(n+a-1)^{\underline{r}}/(n-1)^{\underline{r}} \approx [(n+a-1)/(n-1)]^r$, which yields
$$
S_n(a,x)
\approx \frac{(n-1)!x^n}{\binom{n+a-1}{a-1}}
 \cdot \exp\left(\frac{n+a-1}{(n-1)x}\right).
$$
A few test computations where $n\gg a,1/|x|$ looked promising. Maxim's approximation seems to require $n\gg a/|x|$, which this approximation is somewhat less dependent on. Of course, both fail close to $x=0$.
Another improvement in terms of efficient approximation is to use a power series expansion of the logarithm of GHS, since these often converge much faster: eg a low order approximation of $\ln F(-(n+a-1);-(n-1);u)$ may outperform the above approximation which is just to the first order.

To assess the terms of the original sum more easily, we may
rewrite it
$$
S_n(a,x)
= \sum_{k=1}^n
  \frac{n^\underline{k}(k-1)!x^k}{a^\overline{k}}
= \frac{nx}{a}\cdot\sum_{j=0}^{n-1}
  \frac{(n-1)^\underline{j\,}j!x^j}{(a+1)^\overline{j\,}}.
$$
using $p^\overline{q}$ and $p^\underline{q}$ to represent rising and falling factorials: I prefer these over the Pochhammer symbols which may be used to represent either.
In general, the terms (absolute value in case $x$ is negative) may be divided into three regions:

*

*for low $k$, they will be falling;

*for mid-range $k$, they will be rising;

*for high $k$, they will again be falling.

As $x$ approaches 0, the rising mid-range will shrink until, for $x$ close to 0, the terms will be falling throughout. The first term will then be the dominant one, while adding a few more terms may improve the approximation.
As $|x|$ increases, the mid-range rising region expands, while first the low-end falling region and later the high-end falling region shrink. The high-end terms will be dominant and similar to the terms of the exponential series as used in the above approximations.
Difficulties are caused by two issues. First, the terms may have two local maxima: one at $j=0$ ($k=1$) and another between the mid- and high-range regions. Either of these may be the dominant one.
The second issue is that, when the higher term is dominant, the expomential appoximation works better when the dominant term is close to the upper end: ie for $k$ close to $n$, or low $r=n-k$ after. In this case, my original idea for analysing the sum might work better:
to identify which $k$ gave the dominant term, and then build the approximation around that.
Note that the ratio between consecutive terms is $(n-k)kx/(a+k)$, so it is fairly easy to check where the terms are rising or falling. Also, solving in $k$ for ratio close to $1$ will help identify the maximum and then approximate nearby terms relative to this.

A: Not an answer.
$$S_n(a,x) = \sum_{k=1}^n \binom{n}{k} \frac{(k!)^2 }{k \, (a)_k}x^k$$
$$\frac{\partial S_n(a,x)}{\partial x} = \sum_{k=1}^n \binom{n}{k} \frac{(k!)^2 }{ \, (a)_k}x^{k-1}$$
$$\frac{\partial S_n(1,x)}{\partial x}=\frac{e^{\frac{1}{x}}\, x^n\, \Gamma \left(n+1,\frac{1}{x}\right)-1}{x} \quad \implies \quad  S_n(1,x)=\color{red}{\large ???}$$

A: Not an answer (so I still hope for someone to post a better one and get the bounty), but I need somewhere to put my notes on this.
Using @Maxim 's suggestion in the comments, we change the summation index.
Denote $k=n-l$, then
$$S_n(a,x) = n! x^n \sum_{l=0}^{n-1} \frac{(n-l-1)!}{l! ~ (a)_{n-l} ~ x^l}$$
$$(a)_{n-l}=\frac{\Gamma(a+n-l)}{\Gamma(a)}$$
$$S_n(a,x) = \Gamma(a) n! x^n \sum_{l=0}^{n-1} \frac{\Gamma(n-l)}{l! ~ \Gamma(n-l+a) ~ x^l}$$
$$S_n(a,x) = n! x^n \sum_{l=0}^{n-1} \frac{B(n-l,a)}{l! x^l}$$
$$B(n-l,a)=\int_0^1 t^{n-l-1}(1-t)^{a-1}dt$$
However, Beta function is not very useful here. Instead, we could use Stirling approximation for Gamma function, which up to 2 orders, reads:
$$\Gamma(n+1)\asymp {\sqrt {2\pi n}}\left({\frac {n}{e}}\right)^{n}\left(1+{\frac {1}{12n}}+{\frac {1}{288n^{2}}}+O(1/n^3) \right)$$
Thus we have for the 0 order approximation, assuming $l$ fixed:
$$\frac{\Gamma(n-l)}{\Gamma(n-l+a)} \asymp e^a  \left(\frac{n-l-1}{n-l-1+a}\right)^{n-l-1/2} \frac{1}{(n-l-1+a)^a} $$
So, we have asymptotic series:
$$S_n(a,x) \asymp \Gamma(a) n^{-a} n! x^n \sum_{l=0}^{m} \frac{1}{l!x^l}$$
Where $m$ is some number, $m\ll n$.
However, I checked numerically for some values, and it's a very poor approximation.
We may need to use more orders of Stirling approximation. I'll return to this problem as soon as I'm able.


text:
Q: caught TypeError: Cannot read properties of undefined I can't figure out where I went wrong I keep getting the same error, I already defined i with let but it keeps saying I haven't defined i I am lost, I am very new to coding.
import { films } from '../data/films.js'
console.log(films[0].url)
function getLastNumber(url) {
const secondToLastLetterOfUrl = url[url.length - 2]
return secondToLastLetterOfUrl
let filmList = document.querySelector('#filmlist')
for (let i = 0; i < films.length; i++) { }
let figure = document.createElement('figure')
let figImage = document.createElement('img')
let figCaption = document.createElement('figcaption')
let filmNum = getLastNumber(films[i].url)
figImage.src = `https://starwars-visualguide.com/assets/img/films/${filmNum}.jpg`
figCaption.textContent = films[i].title
figure.appendChild(figImage)
figure.appendChild(figCaption)
filmList.appendChild(figure)

A: There are two problems with your code:

*

*getLastNumber is missing the closing curly brace. It probably would go after the return.

*The for loop is empty. The scope of i is limited to the for loop, so when you try to access i four lines later, it is undefined. You probably want to move the closing curly bracket of the for loop after filmList.append(figure) line.


text:
Q: math.asin() function returns incorrect value The math.sin() function returns the correct value, but the math.asin() value is incorrect.
Code:
sineValue = math.sin(math.radians(125))
print(sineValue)

Expected output: 0.8191520442889917
Actual output: 0.8191520442889917
Code:
asineValue = math.asin(math.radians(0.75))
print(asineValue)

Expected output: 48.59037789
Actual output: 0.01309034324060011
As you can see the asin value is way off, even though it is run with the radian of 0.75.
My expected output results were found with a handheld calculator. Not sure why the results would be different though.

A: The argument to asin is not an angle. You can't put it in radians.
The return value of asin is an angle in radians that you can convert to degrees if you want.
angle = math.degrees(math.asin(0.75))

Result:
48.590377890729144

A: Looks like you're computing the arcsin of 125 degrees.  If so, you have to account for the range of arcsine (-90 degrees to +90 degrees):
https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Principal_values


text:
Q: How to edit grid box height Is it possible to make the total lengh of boxes 3-15 shorter than the length of box 2? I want them to be tabs that don't span along the body text (box 2) but instead are about 1/5 as long as box 2.

.wrapper {
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-auto-rows:minmax(100px, auto);
  grid-gap: 1em;
}
.wrapper > div {
background: #eee;
  padding: 1em;
}
.wrapper > div:nth-child(odd) {
  background: #ddd;
}
.box1 {
  grid-row:1/3;
}
.box2 {
  grid-column: 2/4;
  grid-row:1/16;
}
.jsdoc {
  text-align: center;
}

JS documentation

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Box 3

Box 4

Box 5

Box 6

Box 7

Box 8

Box 9

Box 10

Box 11

Box 12

Box 13

Box 14

Box 15

A: Instead of creating all the boxes side by side, you should create 3 boxes first. .box1 for heading, .box2 for body and another box for tab items and put all the box inside the new box. Then you can style to grow the new box as you want. May be grid-row:3/6;.
Check my approach:

 .wrapper {
        display: grid;
        grid-template-columns: 1fr 3fr;
        grid-auto-rows:minmax(100px, auto);
        grid-gap: 1em;
    }
    .wrapper > div, .wrapper > div.tabs > div{
        background: #eee;
        padding: 1em;
    }
    .wrapper > div:nth-child(odd) {
        background: #ddd;
    }
    .box1 {
        grid-row:1/3;
        /* Vertically Center The Heading */
        display: flex;
        align-items: center;
    }
    .box2 {
        grid-row:1/16;
    }
    .wrapper > div.tabs {
        grid-row:3/6;
        display: grid;
        grid-template-columns: 1fr;
        grid-gap: 1em;
        padding: 0;
        background-color: #fff;
    }
    .jsdoc {
        text-align: center;
    }

JS documentation

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Box 3

Box 4

Box 5

Box 6

Box 7

Box 8

Box 9

Box 10

Box 11

Box 12

Box 13

Box 14

Box 15

Hope this approach will help you to create that you are trying to create.


text:
Q: Setting up handling unicode in Mediawiki Math extension I am having trouble with some unicode characters inside <math></math> tags in Mediawiki.
For example, the following:
<math>′</math>

Results in: Failed to parse (syntax error): {\displaystyle ′} error.
I am using clean installation from this docker image (version: 1.35.2).
I also downloaded, extracted and enabled most recent Math extension (by adding wfLoadExtension( 'Math' ); to LocalSettings.php)
How can I make Mediawiki\Math handle unicode properly?


text:
Q: Scipy hierarchial clustering - clusterize new vector I am clusterizing a bunch of feature vectors using scipy linkage with ward method.
I want a predictive model that works in two steps:

*

*Training data is clusterized

*A new vector comes, the distance between the vector and each cluster is computed, the new vector is assigned the "nearest" cluster's label

How can I compute the distances between a new vector and precomputed clusters?

A: Use the euclidean metric? I think the precomputed clusters have a center. So you can calculate the distanc between every center and the new vector.