text:
Q: Decorating a function to create a class that splits keyword and positional arguments into two other methods I have an abstract class that @abstractmethods its __init__ and __call__. In principle, the class definition is like this:
class Base(abc.ABC):
    @abc.abstractmethod
    def __init__(self, **params):
        pass

    @abc.abstractmethod
    def __call__(self, *input):
        pass

I want to create a decorator that converts a function's keyword arguments into arguments into __init__ and positional arguments into __call__: so if
def func(a, b, *args, k=1, g=2, **kwargs):
    pass # it does something

then I would like to wrap my func in a decorator that will output like along the lines of
class Func(Base):
    def __init__(self, k=1, g=2, **kwargs):
        inspected_kwargs = ... # arguments of init in dictionary form
        for argname, val in inspected_kwargs.items():
             setattr(self, argname, val)

    def __call__(self, a, b, *args):
        inspected_args = ... # arguments of call in tuple form
        return func(*inspected_args, **self.__dict__)

I had a few attempts using inspect but I'm not sure how to inject the parameters from inspect.Signature object back to create a function. Also, I had some trouble because when local methods are added to a class that is inner to a function with simple attribute setting, the local functions are no longer in scope when the class is returned.
The question is: how to create a class inside a function whose methods are defined based on the signature of the function's input callable?
@edit
To provide more details on the idea:
def decorator(function):
    class Inner(Base):
        pass
    # non-existent functions ahead, just to convey the idea
    # the exact way to do this is exactly the matter of this question
    sig = inspect.get_signature(function)
    init = create_from_signature(signature=sig.keyword_arguments(),
body="for name, val in sig.keyword_arguments():\nsetattr(self, name, val)")
    call = create_from_signature(signature=sig.positional(),
body="return partial(func, **self.__dict__)")
    Inner.__init__ = init
    Inner.__call__ = call
    # it would be nice if Inner class name would also depend on
    # func name:
    setattr(Inner, __name__, "_".join(function.__name__, "decorated"))
    return Inner

def users_function(a, b, k=5):
    # user's code; does whatever, for me it's a black box
    return a * b / k

Expected behaviour:
decorator(users_function)(k=10)(1, 2) == users_function(1, 2, k=10)

Why do I want to do this? Because then one can call the methods of Base on the outputted object, for which knowledge of only keyword arguments would be required:
my_obj = decorator(users_function)(k=10)
my_obj.basemethod() # basemethod is implementd in Base class

A: I am trying to understand exactly what your problem is so let's start with this example:
def decorator(function):

    def wrapper(*args, **kwargs):

        print(' [decorator] Printing before function [' + function.__name__ + '] execution')

        result = function(*args, **kwargs)

        print(' [decorator] Found args: ' + str(args))
        print(' [decorator] Found kwargs: ' + str(kwargs))

        print(' [decorator] Printing after function [' + function.__name__ + '] execution')

        return result

    return wrapper

@decorator
def MyFunction(*args, **kwargs):

    print('[MyFunction] Received args:' + str(args))
    print('[MyFunction] Received kwargs:' + str(kwargs))

MyFunction(1, 2, kwarg1=3, kwarg2=2)

It will result in:
 [decorator] Printing before function [MyFunction] execution
[MyFunction] Received args:(1, 2)
[MyFunction] Received kwargs:{'kwarg1': 3, 'kwarg2': 2}
 [decorator] Found args: (1, 2)
 [decorator] Found kwargs: {'kwarg1': 3, 'kwarg2': 2}
 [decorator] Printing after function [MyFunction] execution

Where do you need to take your problem from here?


text:
Q: Select option background color doesn't change until focused on Okay,
This is driving me nuts. I'm trying to change the background color of my SELECTED options in a multi select box.
I've tried w/ CSS and Jquery to change it, and it does work, but the background color only changes when you focus on the box. Somehow the SELECTED attribute overwrites the background color with #d4d4d4 gray.
Here is an example
http://jsfiddle.net/e6XLs/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using TIA to pull FX rates from BBG? I'm trying to use the TIA module to pull EURUSD forward rates from the BBG API?  How does one go about doing this?
I tried using the BbgDataManager() to specify a specific forward rate but don't seem to be having any success.  The code I tried is below.
df = mgr['EURUSD Curncy','FWD_CURVE']
df
MultiSidAccessor(EURUSD Curncy,FWD_CURVE)
df.FWD_CURVE

Produces the following error message:
File "", line 1
    df.EURUSD Curncy
                   ^
SyntaxError: invalid syntax
df.FWD_CURVE
Traceback (most recent call last):
  File "", line 1, in
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\datamgr.py", line 85, in getattribute
    return self.get_attributes(item, **self.overrides)
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\datamgr.py", line 90, in get_attributes
    frame = self.mgr.get_attributes(self.sids, flds, **overrides)
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\datamgr.py", line 148, in get_attributes
    return self.terminal.get_reference_data(sids, flds, **overrides).as_frame()
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\v3api.py", line 745, in get_reference_data
    return self.execute(req)
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\v3api.py", line 729, in execute
    request.has_exception and request.raise_exception()
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\v3api.py", line 215, in raise_exception
    raise Exception('SecurityError: %s' % ','.join(msgs))
Exception: SecurityError: (FWD_CURVE, BAD_SEC, Unknown/Invalid Security  [nid:2972] )
Similarly, using the mgr with a query similar to the way you would pull this in Excel using BFxForward produces errors..
eurusd_sids = mgr["eurusd curncy","9/12/2019","midoutright"]\
eurusd_sids.PX_LAST

produces this error message:
Traceback (most recent call last):
  File "", line 1, in
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\datamgr.py", line 85, in getattribute
    return self.get_attributes(item, **self.overrides)
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\datamgr.py", line 90, in get_attributes
    frame = self.mgr.get_attributes(self.sids, flds, **overrides)
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\datamgr.py", line 148, in get_attributes
    return self.terminal.get_reference_data(sids, flds, **overrides).as_frame()
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\v3api.py", line 745, in get_reference_data
    return self.execute(req)
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\v3api.py", line 729, in execute
    request.has_exception and request.raise_exception()
  File "C:\Users\anthony.yeh\PycharmProjects\blpapi\venv\lib\site-packages\tia\bbg\v3api.py", line 215, in raise_exception
    raise Exception('SecurityError: %s' % ','.join(msgs))
Exception: SecurityError: (9/12/2019, BAD_SEC, Unknown/Invalid Security  [nid:2972] ),(midoutright, BAD_SEC, Unknown/Invalid Security  [nid:2972] )

A: You may try with "EURUSD BGN Curncy"


text:
Q: LocBaml include previous translations Is there a way to combine a previous translation when extracting the csv file from an application?
Or any other tool that could do this job for me?
I can't really see how could i use locbaml if i had to translate everything from scratch every time i add a new control in my application.

A: You might consider using something like WinMerge to merge the existing file with the old one.

A: You can try my open source addin http://easybaml.codeplex.com, which combines previous translations automatically. Right now it uses .resx instead of .csv, which can be changed if needed.


text:
Q: TI's bypass mode step-down converters Texas Instruments encourages the use of the TPS62730 step-down converter with bypass mode along its RF devices. Does this mean :

*

*its noise is low enough not to affect RF ? Thus being a more efficient solution than an LDO ?

*using 3.0-3.6V devices and a 3.0-4.2V battery, the converter could be bypassed when battery hits 3.6V and efficiency would become 100% ?


text:
Q: What's the right way to select and combine objects with LINQ? Here's a situation I run into frequently: I've got Parent and Child objects, and the Child object has a Parent property.  I want to run a query that gets the child objects and joins each one to the correct parent object:
Dim db = New DataContextEx()

get the children, along with the corresponding parent
Dim Children = From x In db.ChildTable
                Join y In db.ParentTable
                On x.ParentId Equals y.Id
                Execute x.Parent = y       <-- pseudocode
                Select x

The pseudocode shows what I want to accomplish: to return the child object x but with the code after the (fake) Execute statement executed.  I can think of a lot of ways to accomplish the end goal, but they all have a lot more lines of code and/or creation of temporary objects or functions that I find inelegant.  (Note this is VB.NET syntax, but it's not a VB syntax question, since AFAIK C# would have the same problem.)
So what would be the cleanest way to do what I'm trying to do?
Edit: People have asked about what ORM I'm using, but this is really a plain vanilla LINQ question; I'm not trying to convert this into logic to be run on the server, I just want some syntactic sugar to run the code client side after the query has been run on the server.

A: You can do it like this:
Add a method to do your logic to Child class that returns this or Me in vb
class Child
{
    public Child GetWithAssignedParent(Parent y)
    {
        this.Parent = y;
        return this;
    }
}

use this method in your select query to do the logic and return the updated instances of Child class:
var children = from x In db.ChildTable
join y In db.ParentTable on x.ParentId equals y.Id
select x.GetWithAssignedParent(y);

or use Func<>
var children = from x in children
join y in parents on x.ParentId equals y.Id
select
   new Func<Child>(() =>
   {
      x.Parent = y;
      return x;
   }).Invoke();

A: These suggestions, especially @Paul's, were very helpful, but my final version is different enough that I'm going to write it up as my own answer.
I implemented the following totally general extension function:
<Extension()> _
Public Function Apply(Of T)(ByVal Enumerable As IEnumerable(Of T), ByVal action As Action(Of T)) As IEnumerable(Of T)
    For Each item In Enumerable
        action(item)
    Next

    Return Enumerable
End Function

This is the same as ForEach, except that it returns the incoming sequence, and I think the name Apply makes it clear that there are side effects.  Then I can write my query as:
Dim Children = (
            From x In db.ChildTable
            Join y In db.ParentTable
            On x.ParentId Equals y.Id
            ).
            Apply(Sub(item) item.x.Parent = item.y).
            Select(Function(item) item.x)

It would of course be better if there were a way to have custom query operators, so I wouldn't have to use the lambda syntax, but even so this seems very clean and reusable.  Thanks again for all the help.

A: You could use an anonymous type when projecting results. C# example:
var items = from x In db.ChildTable
            join y In db.ParentTable on x.ParentId equals y.Id
            select new { Child =x , Parent=y };

Then assign the parent properties.
foreach(var item in items)
{
    item.Child.Parent = item.Parent;
}

return items.Select(item => item.Child);

Also you may want to use some ORM solutions for this instead of rolling your own.

A: Here's probably the easiest solution:
var children = from x in db.ChildTable
               join y in db.ParentTable
               on x.ParentId equals y.Id
               // Assign the Parent to the Child:
               let parent = (x.Parent = y) // <-- Inline assignment (with a dummy variable "parent")
               select x;

Disclaimer:  this query has inline assignment and modifies state ... both of which are not considered "best practice".
However, it is very easy to read and understand, maintainable, and easily produces the correct results, so I'd argue it is a great solution.
Also, this will only work in C#, because VB.NET doesn't have inline-assignment.

A: If you're using LinqToObjects, use this code to assign Parents to the Children.
ILookup<int, Child> lookup = children.ToLookup(c => c.ParentId)

foreach(Parent p in parents)
{
  foreach(Child c in lookup[p.Id])
  {
    c.Parent = p;
  }
}

If you're using LinqToSql, use DataLoadOptions to load related records.

If you're using LinqToEntities, use .Include to load related records.


text:
Q: Why don't the standard C++ container adaptors provide a clear function? Does anyone know why std::queue, std::stack, and std::priority_queue don't provide a clear() member function?  I have to fake one like this:
std::queue<int> q;
// time passes...
q = std::queue<int>();  // equivalent to clear()

IIRC, clear() is provided by everything that could serve as the underlying container.  Is there a good reason to not have the container adaptors provide it?

A: I'd say it's because container adaptors are not containers.

A: Well, I think this is because clear was not considered a valid operation on a queue, a priority_queue or a stack (by the way, deque is not and adaptor but a container).

The only reason to use the container
  adaptor queue instead of the container
  deque is to make it clear that you are
  performing only queue operations, and
  no other operations. (from the sgi page on queue)

So when using a queue, all you can do is push/pop elements; clearing the queue can be seen as a violation of the FIFO concept. Consequently, if you need to clear your queue, maybe it's not really a queue and you should better use a deque.
However, this conception of things is a little narrow-minded, and I think clearing the queue as you do is fair enough.

A: Deque has clear(). See, e.g., http://www.cplusplus.com/reference/stl/deque/clear.html.
However, queue does not. But why would you choose queue over deque, anyway?

The only reason to use the container
  adaptor queue instead of the container
  deque is to make it clear that you are
  performing only queue operations, and
  no other operations.

(http://www.sgi.com/tech/stl/queue.html)
So I guess clear() is not a queue operation, then.

A: You CAN clear queues (and std::stack and priority_queue), as long as you inherit from it. The container is intentionally left protected to allow this.
#include <queue>

using namespace std;

class clearable_queue : public queue<int>
{
public:
  void clear()
    {
      // the container 'c' in queues is intentionally left protected
      c.clear();
    }
};

int main(int argc, char** argv)
{
  clearable_queue a;
  a.clear();
}

A: std::queue, std::deque, and std::priority_queue are container adaptors and only provide a small number of methods to access the underlying container.
You can clear the underlying container, so long as you can access it.  To do this, create the underlying container to pass in to the apadptor constructor.  For example:
std::deque< int > d;
std::queue< int > q( d );

... time passes ...

d.clear();

Edit: additional info
I should also have warned you to tread carefully here as calling methods on the underlying container may break assumptions made by the adaptor.  In that respect, the way you are currently clearng the queue seems preferable.

A: I think it depends on the implementation - until recently Microsoft STL didn't have clear on several containers. (it does now, eg this quick google result)
However, clear() is often simply a call to erase(begin(), end()), so implement your own equivalent and use that instead.
I think the standard refers to clear as erasing over an iterator range, so the above is what most implementations will provide. (eg Dinkumware's)


text:
Q: Eclipse RCP App: How can I prompt the user to set the workspace I want my RCP app to always prompt the user for the workspace location. I can specify a default location either with the -data arg in eclipse.ini or the osgi.instance.area.default property in configuration/config.ini. But I don't want the user to have to know about and edit either of these files to change the workspace location.
Setting the preference Prompt for workspace on startup has no effect. I launch the app in a clean workspace, with no -data arg or osgi.instance.area.default property set, and it creates a workspace folder in the current directory, and does not prompt to select a location.
I use a copy of the IDEApplication class for my application. I see that in line 188 which is one of the first lines run after start(), the platform location is already set, and this prevents the dialog from showing. I don't know why it's already set before even trying to launch the UI, and setting the preference has no effect. (I verified in configuration/.settings/org.eclipse.ui.ide.prefs that SHOW_WORKSPACE_SELECTION_DIALOG=true).
I tried re-setting the location by adding
instanceLoc = instanceLoc.createLocation(instanceLoc, null, false);

at the beginning of checkInstanceLocation(). This enables the workspace chooser dialog to come up, but setting the location this way has no effect on what the app actually uses for its instance area when it launches.
I thought that maybe some earlyStartup code in my app may be interfering, as I read that if you access the preferences too soon you can prevent the workspace chooser from opening. So I commented out the few earlyStartup declarations I had, and still I can't get the workspace chooser dialog to show.

A: The problem turned out to be that some classes loaded as dependencies of my OSGI service were accessing the class ResourcesPlugin, which causes the workspace location to be set immediately. Since this was happening before the workspace chooser dialog was launched, the location used was the value of the -data arg if specified, otherwise $(pwd)/workspace.
I tried resolving the issue by adjusting the start level of my service plug-in. With a start level of 7 or higher, the workspace chooser dialog was no longer pre-empted. However, the service did not work properly then. After numerous unsuccessful attempts to make the service work properly with a custom start level, I abandoned that approach and re-worked my code so the reference to ResourcesPlugin occurs later in the application startup process. Specifically, I moved it to the postWindowOpen method of my custom WorkbenchWindowAdvisor implementation.


text:
Q: Doctrine - QueryBuilder, select query with where parameters: entities or ids? I have a Product entity and a Shop entity.
A shop can have 0 to n products and a product can be in only one shop.
The product entity table is thus refering to the Shop entity through a shop_id table field.
When querying for the products of a given shop using doctrine query builder, we can do this:
    $products = $this->getDoctrine()->getRepository('MyBundle:Product')
                ->createQueryBuilder('p')
                ->where('p.shop = :shop')
                ->setParameter('shop', $shop)  // here we pass a shop object
                ->getQuery()->getResult();

or this:
    $products = $this->getDoctrine()->getRepository('MyBundle:Product')
                ->createQueryBuilder('p')
                ->where('p.shop = :shopId')
                ->setParameter('shopId', $shopId)  // we pass directly the shop id
                ->getQuery()->getResult();

And the both seem to work... I'm thus wondering: can we always pass directly entity ids instead of entity instances in such cases (ie: on a doctrine entity field that refers to another entity)?
I initially thought that only the first example would work...

A: According to the Doctrine documentation, you can pass the object to setParameter() if the object is managed.

extract from the documentation:

Calling setParameter() automatically infers which type you are setting as value. This works for integers, arrays of strings/integers, DateTime instances and for managed entities.

for more information, please see:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html#binding-parameters-to-your-query

A: I might be wrong, but I think that if you pass object instance instead of id number, Doctrine will automatically call $instance->getId() making your two queries the same when translated into SQL (even DQL).


text:
Q: TSQL copy one database to another I have two identical databases lets call them A & B, what I want to do is to have two copy options:
1- Copy the whole database and overwrite everything from A to B with TSQL
2- With TSQL I want to loop over each table row in A and check the last modified date filed if is greater then last modified date in B table row copy and overwrite the whole row.
Please let me now if something is not clear, any help is very appreciated and thanks in advance.

A: Using Visual Studio 2010 Premium or Ultimate you can do a schema compare and create the new database on the server you need to.  Getting the data over there is another matter entirely and is something you can perform with SSIS or linked server queries, especially considering you're simply pumping data from one side to another.
See this post for schema compare tools:
How can I find the differences between two databases?
Something we've recently complete is using the CHECKSUM and Table Switching to bring in new data, keep the old and compare both sets.
You would basically set up three tables for each doing the switch, one for production, one for   _staging and one that's an _old table that's an exact schema match.  Three tables are needed since when you perform the switch (which is instantaneous, you need to switch into an empty table).  You would pump the data into the staging table and execute a switch to change the pointer for the table definition from production to _old and from _staging to production.  AND if you have the checksum calculated on each row, you can company and see what's new or different.
It's worked out well with our use of it, but it's a fair amount of prep work to make it happen, which could be prohibitive depending on your environment.
http://msdn.microsoft.com/en-us/library/ms190273.aspx
http://technet.microsoft.com/en-us/library/ms191160.aspx
http://msdn.microsoft.com/en-us/library/ms189788.aspx
Here's a sample query that we ran on GoDaddy.com's sql web editor:
CREATE TABLE TestTable (Val1 INT NOT NULL)
CREATE TABLE TestTable2 (Val1 INT NOT NULL)

INSERT INTO TestTable (Val1) VALUES (4)

SELECT * FROM TestTable

ALTER TABLE TestTable SWITCH TO TestTable2

SELECT * FROM TestTable2


text:
Q: Specific Feature Copying I'm trying to write a script to copy multiple feature classes from two different databases into a single database, but I want to be able to specity what features I actually want. I know I need to use da.Walk to get through the first files but am stumped on how I can actually do this. Any thoughts?
here is what i have so far.
`import arcpy, os, string

workspace= ""

for dirpath, dirnames, filenames in arcpy.da.Walk(workspace, datatype="FeatureClass"):
    for filename in filenames:`

A: The following is an example of how you can use a list comprehension, fnmatch and walk to get at specific files within multiple geodatabases.  In this example I specified that I wanted all polygon feature classes with a "poly" prefix.  As an added bonus, list comprehensions are blazingly fast compared to stand alone nested for loops.
import arcpy, os, fnmatch

path = r'C:\gdrive\temp\test'

myfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in arcpy.da.Walk(path, datatype="FeatureClass", type="Polygon")
    for f in fnmatch.filter(files, 'poly*')]

# Copy the files over starting here...


text:
Q: gcc intrinsic vs inline assembly : which is better? If I want to expose a single machine specific instruction to the programmer, there are two ways I can do so :

*

*Define a new builtin / intrinsic

*Expose the same as inline assembly asm() [As its a single arithmetic type instruction, I believe there is no need for asm volatile()]

I have read that builtins allow the compiler to take care of the type checking, register allocation and "other optimizations" etc. But the compiler will need to do this even in case of asm (), right ? So what precisely is the performance benefit of using intrinsic over asm () for a single instruction ?
How does the equation change if there are multiple machine instructions involved ?
The "portability" argument in favor of intrinsic is understandable, but I am curious to understand the performance advantage, if any, of one over the other.

A: I think it depends a lot on what you're doing. Modifying GCC, and requiring a modified GCC to build your program unless/until your GCC patch makes it upstream, is a lot more of a headache than just using inline asm.
If the instruction you want to use has an abstract meaning not tied down to a particular instruction set architecture, adding the builtin/intrinsic so that the same code using it could automatically work on all targets (with fallback to a more complex implementation with multiple instructions on targets that don't have the instruction) is probably the "right" choice, but might not be practical still.
If the instruction is something very ISA-specific, obscure, not-performance-critical, etc. (I'm thinking of loading a special hardware register, cpu mode register, getting model info, etc. but I'm sure you can think of other examples) then just using inline asm is almost certainly the right solution.
Even if you do think a builtin is the "right" solution for your problem, but need to take the inline asm approach for practical reasons, you can still abstract it with a macro or static inline function in such a way that it's easy to replace all uses with an intrinsic later (or with a fallback implementation on targets without the instruction).


text:
Q: Is there a simple python 3 command that replicates matlab's interp1 command over multiple columns? Is there a simple python 3 command that replicates matlab's interp1 command over multiple columns?
data_1 contains two parameters (1 per column) that go with the time_1 time vector (data_1 is a 5 by 2 array that isn't actually used in this example so can be ignored)
data_2 contains two parameters (1 per column) that go with the time_2 time vector
import numpy as np
data_2 = np.array([ [ 0.43, -0.54], [ 0.32, -0.83], [ 0.26, -0.94], [ 0.51, -0.69], [ 0.63, -0.74] ])
time_1 = np.array([ 399.87, 399.89, 399.91, 399.93, 399.95 ])
time_2 = np.array([ 399.86, 399.88, 399.90, 399.92, 399.94 ])

I'd like to interpolate the data_2 2D array into the time_1 time vector so both data sets will have the same time vector.
Desired output (which is just the np.interp of the two data_2 columns into the time_1 time vector
and merged back into an array) is:
data_2_i = np.array([[ 0.375, -0.685], [ 0.290, -0.885], [ 0.385, -0.815], [ 0.570, -0.715], [ 0.630, -0.740]])

Actual arrays will contain approx 20 columns (parameters) and thousands of rows (longer time range).
I know you can just loop over each column with np.interp but I was hoping there was a more compact and faster python 3 (numpy, scipy, pandas, etc.) method that I haven't been able to track down yet.  I'm still pretty new to python (more familiar with matlab).
In matlab, you can just use interp1 on the entire multi-column array to get the multi-column result (although the edge cases are handled a bit differently - NaNs vs. last entry in this example - I'm not worried about the edge case differences here).

A: This looks to work (just made a quick script myself):
import numpy as np

def interp_multi(x_i, x, y):
    ncol = y.shape[1]
    y_i = np.zeros((len(x_i),ncol))
    for i in range(ncol):
        y_i[:,i] = np.interp(x_i, x, y[:,i])

    return y_i

data_2_i = interp_multi(time_1, time_2, data_2)


text:
Q: "Failed to load resource: the server responded with a status of 404 (NOT FOUND)" when trying to load a html in Flask I know very little about html programing. I am running a Minecraft server with my friends, and I found a neat program that renders out the entire map in a overview style. This application creates a bunch of files, and then to open the map, you open a file called "index.html". All I want to do, is to open this file with Flask, so that I can send out a link, and if you open said link, Flask will return that "index.html" file.
This is my Flask code:
from flask import Flask, redirect, url_for, render_template,request
app = Flask(__name__)
@app.route("/map")
def home():
    return render_template("index.html")
if __name__ == "__main__":
    app.run(host= '192.168.2.237', port=9000, debug=False)

and this is index.html:
<!DOCTYPE html>

<title>Minecraft Overviewer</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Minecraft-Overviewer 0.16.3 (4c0a69d)" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

<link rel="stylesheet" href="static/leaflet.css" />

<link rel="stylesheet" href="static/overviewer.css" type="text/css" />

        If you can see this message, there is likely a problem loading the Overviewer JavaScript components.
        Check the JavaScript console for error messages.

Ive tried moving stuff to a "static" folder, while keeping only the "index.html" file in the "templates" folder, while changing the "index.html" file slighly. I added the "static/" part to line 11 and others, and that made it load some parts of the webpage.
Before, it couldnt load any of the "script type" files that it refers to in index.html, but after doing these changes it now loads them.
BUT, now it cant find the image files, and it errors out like this:
compass_upper-left.png:1 GET http://92.35.96.72:9000/compass_upper-left.png 404 (NOT FOUND)

I think the problem is that its not looking in http://92.35.96.72:9000/static/compass_upper-left.png, but I have no idea of how to change that. Is there any way to just make it be able to look in ANY folder?
I really need help with this, and ill gladly try to elaborate or give more info if needed.

A: I FOUND IT
I honestly dont understand completely what this does, but adding this to the script, it solved the problem
https://vilimpoc.org/blog/2012/11/21/serving-static-files-from-root-and-not-static-using-flask/


text:
Q: How to load a URI with "content://" prefix using Glide Android? I'm trying to load a Contact photo with URI "content://com.android.contacts/contacts/295" by using Glide.
When I use
Glide.with(context).load(Uri.parse(contactPhoto).into(imageview)

Glide gives me a FileNotFoundException
java.io.FileNotFoundException: File does not exist; URI: content://com.android.contacts/contacts/264, calling user: android.uid.shared:10006, calling package is one of: [com.android.providers.contacts, com.android.contacts, com.android.providers.userdictionary]
        at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
        at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:689)
        at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1080)
        at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:921)
        at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:848)
        at com.bumptech.glide.load.data.FileDescriptorLocalUriFetcher.loadResource(FileDescriptorLocalUriFetcher.java:21)
        at com.bumptech.glide.load.data.FileDescriptorLocalUriFetcher.loadResource(FileDescriptorLocalUriFetcher.java:14)
        at com.bumptech.glide.load.data.LocalUriFetcher.loadData(LocalUriFetcher.java:44)
        at com.bumptech.glide.load.model.ImageVideoModelLoader$ImageVideoFetcher.loadData(ImageVideoModelLoader.java:83)
        at com.bumptech.glide.load.model.ImageVideoModelLoader$ImageVideoFetcher.loadData(ImageVideoModelLoader.java:53)
        at com.bumptech.glide.load.engine.DecodeJob.decodeSource(DecodeJob.java:170)
        at com.bumptech.glide.load.engine.DecodeJob.decodeFromSource(DecodeJob.java:128)
        at com.bumptech.glide.load.engine.EngineRunnable.decodeFromSource(EngineRunnable.java:122)
        at com.bumptech.glide.load.engine.EngineRunnable.decode(EngineRunnable.java:101)
        at com.bumptech.glide.load.engine.EngineRunnable.run(EngineRunnable.java:58)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)
        at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor$DefaultThreadFactory$1.run(FifoPriorityThreadPoolExecutor.java:52)

Obviously Glide tries to get the image from the wrong place.
I would appreciate if someone point me on how to load a photo with "content://" URIs.

A: You need to create a custom loader that uses a ContentResolver.
In Picasso for example this works because there is already a custom request handler that uses a ContentResolver.
I created one custom Glide loader for contacts for my internal use that you can take as reference.

A: Seems that Glide doesn't handle content photos Uri automatically.
So I've solved my issue using an RxJava approach.
Here is a method that emits a bitmap (Please notice the scheduler as it is important to not lag the scrolling performance)
private Observable<Bitmap> _getConvertInputStreamToBitmapObservable(ContentResolver cr,
                                                                    Uri contactUri) {
    return Observable.create(new Observable.OnSubscribe<Bitmap>() {
        @Override
        public void call(Subscriber<? super Bitmap> subscriber) {
            InputStream inputStream =
                    ContactsContract.Contacts.openContactPhotoInputStream(cr, contactUri);
            if (inputStream != null) {
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                subscriber.onNext(bitmap);
            }
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}

And here is the client code that uses the method (Please notice the unsubscribing as it is important in recycling).
       if (holder.bitmapSubscription != null) {
            holder.bitmapSubscription.unsubscribe();
        }

        holder.bitmapSubscription = _getConvertInputStreamToBitmapObservable(context.getContentResolver(),
                contactUri)
                .subscribe(holder.userImg::setImageBitmap);

A: You need to use a ContentResolver for this.
ContentResolver contextResolver = context.getContentResolver();
Uri uri = Uri.parse("content://com.android.contacts/contacts/295");
Bitmap thumbnail = null;
Cursor cursor = contentResolver.query(uri, new String[] {ContactsContract.CommonDataKinds.Photo.PHOTO}, null, null, null);

try {
    if (cursor.moveToFirst()) {
        final byte[] thumbnailBytes = cursor.getBlob(0);
        if (thumbnailBytes != null) {
            thumbnail = BitmapFactory.decodeByteArray(thumbnailBytes, 0, thumbnailBytes.length);
        }
    }
}
finally {
    cursor.close();
}

if (thumbnail != null) {
    imageView.setImageBitmap(thumbnail);
}

Try this. This should work.

A:   Uri uri =
   ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new
   Long(contactsPojo.getId()));
          final Uri displayPhotoUri = Uri.withAppendedPath(uri,
                  ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
          Glide.with(context)
                  .load(displayPhotoUri)
                  .placeholder(R.mipmap.ic_launcher)
                  .error(R.mipmap.ic_launcher)
                  .fallback(R.mipmap.ic_launcher)
                  .diskCacheStrategy(DiskCacheStrategy.ALL)
                  .into(holder.image);

A: I am use this code then working successfully
 Glide.with(context)
                    .load(uri)
                    .addListener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            Log.i(TAG, "onLoadFailed: ");
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            Log.i(TAG, "onResourceReady: ");
                            return false;
                        }
                    })
                    .into(holder.imgProfile);

A: The fastest and easiest way is to first figure out the CONTACT_ID. Then you match this CONTACT_ID against the PHOTO_URI.
//first create a cursor
val photoCursor = contentResolver.query(
                                ContactsContract.Contacts.CONTENT_URI,
                                photoProjection,
                                ContactsContract.Contacts._ID + "=?",
                                arrayOf(contactId),
                                null
                            )
//where photoProjection is like so
        val photoProjection: Array<String> = arrayOf(
            ContactsContract.Contacts.Photo.PHOTO_URI,
            ContactsContract.Contacts._ID
        )

//now grab the PHOTO_URI, this will only exist if there is a photo
                            val photo = if (photoCursor?.moveToFirst() == true) {
                       photoCursor.getString(photoCursor.getColumnIndex(ContactsContract.Contacts.PHOTO_URI))
                            } else {
                                null
                            }

//In Glide now you can load the URI directly
        Glide.with(this)
            .load(uri)
            .apply(imageTransform)
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
            .into(image)


text:
Q: 24 Game with $31,41,59,26,53$ and an additional number. We have got five numbers $31,41,59,26,53$,please add a positive integer $n$,as small as possible,which we can find a way to manipulate these numbers with addition, subtraction, multiplication, or division, so that the end result is 24.Like this:$\frac{8}{3-\frac{8}{3}}=24$.
PS:I'm so sorry to change the problem so many times,but since $53-41=12,59-26-31=2$,so we can just add $1$.
My purpose for asking this problem is to find the answer to this question:if we have $x_1,x_2,……x_k$,what's the smallest number we need add them to make 24? Such as $12,34,56,78,90,105?$

A: $$
1\times(53-41)(59-26-31)=24
$$
In general I think this will be hard, since if we restrict to addition and subtraction it is almost the subset sum problem.
As a heuristic, with just addition and subtraction we can make $2^k$ expressions between $-\sum x_i$ and $\sum x_i$, so on average we can make numbers spaced by about $2^{1-k}\sum x_i$ so as $k$ grows we should expect to get pretty close.
For the set $\{12,34,56,78,90,105\}$ we can add $24$ to the set, then check all partitions into $S_1,S_2$ for the smallest non-zero* $\sum_{S_1}-\sum_{S_2}$. In this case it is $90+78+34-105-56-12-24=5$, so 5 is a candidate.
For these numbers, however, we can do better, since
$$(90-56-34)(105+78)+12\times 2 =24$$
so 2 works (but I can't rule out 1).
(* Instead of including 24 and checking non-zero differences we can add 23 look for a zero solution, then repeat with 25 if necessary.)


text:
Q: How can I update my indexPath after deleting a Row in a TableView? I'm new to Xamarin and trying to make some basic todolist iOS app.
After struggling for a while with TableViews, I now have a TableSource, and custom cells containing a UISwitch.
My goal is, when the user activate the UISwitch, the cell is deleted for the TableView. To do that I created some custom event in my custom cell.
public partial class TodoTableViewCell : UITableViewCell
{
    public delegate void DeleteTodoEventHandler(UITableView tableView, NSIndexPath indexPath);
    public event DeleteTodoEventHandler DeleteTodo;

    partial void DeleteTodoEvent(UISwitch sender)
    {
        if (DeleteTodo != null)
            DeleteTodo(null, new NSIndexPath());
    }

    public TodoTableViewCell(IntPtr p):base(p)
    {

    }

    public TodoTableViewCell(string reuseIdentifier) : base(UITableViewCellStyle.Default, reuseIdentifier)
    {

    }

    public void UpdateCell(TodoItem Item)
    {
        TodoLabel.Text = Item.Name;
        DateLabel.Text = Formating.formatDate(Item.Date);
        HourLabel.Text = Formating.formatTime(Item.Date);
    }
}

DeleteTodoEvent is called when the user activate the UISwitch. Here is my tablesource :
public class TableSource : UITableViewSource
{

    List<TodoItem> TableItems;
    string CellIdentifier = "TodoCell";

    ...

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        TodoTableViewCell cell = tableView.DequeueReusableCell(CellIdentifier) as TodoTableViewCell;
        TodoItem item = TableItems[indexPath.Row];

        //---- if there are no cells to reuse, create a new one
        if (cell == null)
        {
            cell = new TodoTableViewCell(CellIdentifier);
        }

        cell.DeleteTodo += (table, index) => DeleteTodoHandler(tableView, indexPath);

        cell.UpdateCell(item);

        return cell;
    }

    ...

    private void DeleteTodoHandler(UITableView tableView, NSIndexPath indexPath)
    {
        TableItems.RemoveAt(indexPath.Row);
        // delete the row from the table
        tableView.DeleteRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade);
    }
}

Basically, DeleteTodoHandler is called whenever the user click on the UISwitch. It correctly deletes the cell at first. However, the indexPath is never updated.
By that I mean : Imagine I have 3 cells in my TodoList.

Cell1 -> indexPath.Row = 0
  Cell2 -> indexPath.Row = 1
  Cell3 -> indexPath.Row = 2

If I delete the second one, Cell2, the indexPath from Cell3 should be = to 1 and not 2. This is not the case. Which means that if I try to delete Cell3 after that,
TableItems.RemoveAt(indexPath.Row)

will try to remove the item 3 from the list which is leading us to an exception since there are only 2 items in the list.
I'm following the examples I found in the Xamarin Doc for the deletion of rows in a TableView but in my case it's obviously not working. The indexPath.Row being read-only, what can I do guys to correctly update the indexPath after deleting an item from the TableView ?

A: You should use ViewController which include both of the UITableView and you custom UITableSource object to handle the delete event.
Then you can get the correct row you clicked by the method from UITableView like this:
Foundation.NSIndexPath indexPath = tableView.IndexPathForCell(cell);

And delete the row's data from your data list and your UI in the same time.
This is a sample code I wrote for you, take a look:
This is the ViewController:
public override void ViewDidLoad ()
        {
            //Create a custom table source
            MyTableSource mySource = new MyTableSource ();

            //Create a UITableView
            UITableView tableView = new UITableView ();
            CGRect tbFrame = this.View.Bounds;
            tbFrame.Y += 20;
            tbFrame.Height -= 20;
            tableView.Frame = tbFrame;
            tableView.Source = mySource;
            tableView.RowHeight = 50;
            this.Add (tableView);

            //Handle delete event
            mySource.DeleteCell += (cell) => {
                //Get the correct row
                Foundation.NSIndexPath indexPath = tableView.IndexPathForCell(cell);
                //Remove data from source list
                mySource.RemoveAt(indexPath.Row);
                //Remove selected row from UI
                tableView.BeginUpdates();
                tableView.DeleteRows(new Foundation.NSIndexPath[]{indexPath},UITableViewRowAnimation.Fade);
                tableView.EndUpdates();
            };
        }

This MyTableSource.cs:
public delegate void DeleteCellHandler(UITableViewCell cell);
        public event DeleteCellHandler DeleteCell;

        private string CellID = "MyTableCell";
        private List<string> tableItems;

        public MyTableSource ()
        {
            tableItems = new List<string> ();
            for (int i = 0; i < 10; i++) {
                tableItems.Add ("Test Cell " + i.ToString ());
            }
        }

        public void RemoveAt(int row)
        {
            tableItems.RemoveAt (row);
        }

        #region implement from UITableViewSource

        public override nint RowsInSection (UITableView tableview, nint section)
        {
            return tableItems.Count;
        }

        public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath)
        {
            MyTableCell cell = tableView.DequeueReusableCell (CellID) as MyTableCell;
            if (null == cell) {
                //Init custom cell
                cell = new MyTableCell (UITableViewCellStyle.Default, CellID);
                //Bind delete event
                cell.DeleteCell += delegate {
                    if(null != DeleteCell)
                        DeleteCell(cell);
                };
            }
            cell.Title = tableItems [indexPath.Row];
            return cell;
        }

        #endregion

This is MyTableCell.cs:
public class MyTableCell : UITableViewCell
    {
        public delegate void DeleteCellHandler();
        public event DeleteCellHandler DeleteCell;

        UILabel lbTitle = new UILabel ();
        UIButton btnDelete = new UIButton (UIButtonType.System);

        public string Title{
            get{
                return lbTitle.Text;
            }
            set{
                lbTitle.Text = value;
            }
        }

        public MyTableCell (UITableViewCellStyle style, string reuseID) : base(style,reuseID)
        {
            lbTitle.Text = "";
            lbTitle.Frame = new CoreGraphics.CGRect (0, 0, 100, 50);
            this.AddSubview (lbTitle);

            btnDelete.SetTitle ("Delete", UIControlState.Normal);
            btnDelete.Frame = new CoreGraphics.CGRect (120, 0, 50, 50);
            this.AddSubview (btnDelete);
            btnDelete.TouchUpInside += delegate {
                if(null != DeleteCell)
                    DeleteCell();
            };
        }
    }

Hope it can help you.
If you still need some advice, leave me a message here.
------------------------------New------------------------------------
I just suggest you move all logic code into the ViewController, because according to the MVC model, it should in Controller layer.
And if you want to manage your data by invoking some API or loading data from your local database, it will be more convenient.
Of cause you can put your delete event in your TableSource, just need to remove the event from controller and put it in TableSource, like:
ViewController.cs:
public override void ViewDidLoad ()
        {
            //Create a custom table source
            MyTableSource mySource = new MyTableSource ();

            //Create a UITableView
            UITableView tableView = new UITableView ();
            CGRect tbFrame = this.View.Bounds;
            tbFrame.Y += 20;
            tbFrame.Height -= 20;
            tableView.Frame = tbFrame;
            tableView.Source = mySource;
            tableView.RowHeight = 50;
            this.Add (tableView);

//          //Handle delete event
//          mySource.DeleteCell += (cell) => {
//              //Get the correct row
//              Foundation.NSIndexPath indexPath = tableView.IndexPathForCell(cell);
//              //Remove data from source list
//              mySource.RemoveAt(indexPath.Row);
//              //Remove selected row from UI
//              tableView.BeginUpdates();
//              tableView.DeleteRows(new Foundation.NSIndexPath[]{indexPath},UITableViewRowAnimation.Fade);
//              tableView.EndUpdates();
//          };
        }

In TableSource.cs, change GetCell method like this one:
public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath)
        {
            MyTableCell cell = tableView.DequeueReusableCell (CellID) as MyTableCell;
            if (null == cell) {
                //Init custom cell
                cell = new MyTableCell (UITableViewCellStyle.Default, CellID);
                //Bind delete event
                cell.DeleteCell += delegate {
//                  if(null != DeleteCell)
//                      DeleteCell(cell);
                    //Get the correct row
                    Foundation.NSIndexPath dIndexPath = tableView.IndexPathForCell(cell);
                    int deleteRowIndex = dIndexPath.Row;
                    Console.WriteLine("deleteRowIndex = "+deleteRowIndex);
                    //Remove data from source list
                    RemoveAt(deleteRowIndex);
                    //Remove selected row from UI
                    tableView.BeginUpdates();
                    tableView.DeleteRows(new Foundation.NSIndexPath[]{dIndexPath},UITableViewRowAnimation.Fade);
                    tableView.EndUpdates();
                };
            }
            cell.Title = tableItems [indexPath.Row];
            return cell;
        }

The only mistake you made is you should not add any parameter in your custom cell's delete event handle.
Because when you delete a cell from your table, the other cells will never update their own IndexPath.
For example, if you have 3 rows, and you delete the second one, it works.
But when you try to delete the third row(It's the second right now,because you just delete the second one), you will get a exception about that you don't have 3 rows or index out of bounds, because this cell's IndexPath is still 2(The correct one is 1).
So you need calculate the index in your delete event handler using UITableView's method "IndexPathForCell" like I mention above. It will always get the correct index.
------------------About your new question--------------------
The mistake you made is about delete event init, you must init it when cell is constructed, like I did:
public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath)
        {
            MyTableCell cell = tableView.DequeueReusableCell (CellID) as MyTableCell;
            if (null == cell) {
                cell = new MyTableCell (UITableViewCellStyle.Default, CellID);
                //Bind delete event
                cell.DeleteCell += delegate {
                    //Delete stuff
                };
            }
            cell.Title = tableItems [indexPath.Row];
            return cell;
        }

If you just use it like yours:
if (null == cell) {
    cell = new MyTableCell (UITableViewCellStyle.Default, CellID);
}
//Bind delete event
cell.DeleteCell += delegate {
    //Delete stuff
};
cell.Title = tableItems [indexPath.Row];

It will cause duplicated binding problem, because your table cell is reused, so when you try to refresh/insert/delete or even scroll your UITableView, "GetCell" method will be trigged, so when you try to invoke your cell's delete event, there are multiple delegates will be invoked, the first is working, and if you have at least 2 delegates, it will cause the problem you met.
The effect is like this screenshot:

Reproduce step:
1 Add a new item for tableview;
2 Delete the item you just added;
3 Add a new item again;
4 Delete the item you just added again;
Because there a 2 delegates, so it thrown an exception.
At last, I have uploaded the complete sample code to my GitHub, download it if you need.
UITalbViewManagement Sample code


text:
Q: Can access Windows share by IP or FQDN address but not by hostname One of the lab computers at the school I administer is not able to access a any shares under the \\ad\data$ directory. I can access it from any other computer on the network. If I use the IP \\192.168.1.248\data$ I can access the files properly. If I use the FQDN: \\ad.domain.name\data$ it also works. Any other computer at the school is also able to access this share properly.
When I try to access the share with \\ad\data$ I get the message "You do not have permission to access \\ad\data$. Contact your administrator to request access." I am logged in with the domain administrator account.
Any idea on what would cause a single domain computer to not be able to access a share that it should have access to?
The server is running Windows Server 2008 and the computer is running Windows 7 SP1.
UPDATE
Issue is now happening on multiple other computers on the network, staff computers and student computers. I am starting to think there is something seriously wrong with the Active Directory server.

A: Win7/server 2008 > control panel type in "Credential manager" and delete any saved credentials.

A: I have just had a similiar problem.
We have a domain and AD, and all users home folders are set up in the AD.
The user works on a terminal server and her home folder works fine
On the new notebook we were setting up for her, the drive was mapped, but if you tried to access it via unc or by double clicking on the mapped drive it gave an error of the location could not be found.
Browsing through a few other forums I noticed someone asked if the home folder could be access via IP or FQDN. When I tried that I could access the folder.
At first I also thought it was a DNS problem.
Reading further on someone said " try deleted the CSC cache", and then I almost swore at myself. Knowing that this notebook was used by another user that made use of offline files (Also their home folder on the same server). I found a quick way to delete the CSC cache on Win 7 (its a lot easier on XP). Rebooted the computer and the problem was solved.
Here are the links I found the info on:
http://www.petri.co.il/forums/showthread.php?t=60629
http://support.microsoft.com/kb/942974

A: I have seen an issue like this and it was caused by the DNS being set not to append the domain name automatically.
So, I would check that
Append primary and connection specific DNS suffixes is selected and that
Append parent suffixes of the primary DNS suffix is ticked.
This can be found via
Control Panel\Network and Internet\Network and Sharing Center
Local Area Connection Status
Properties
Internet Protocol Version 4 (TCP/IPv4) and/or Internet Protocol Version 6 (TCP/IPv6)
Properties
Advanced
DNS

A: I had the same problem (happened to me several times) and I resolved it by deleting all connected shares and recreating them. There have been multiple connections to same locations (using different URLs) and I suspect that it was the reason of problems.
Using command line:

*

*To see currently connected shares
net use

*To delete connection to share Y on xxx.xxx.xxx.xxx
net use \\xxx.xxx.xxx.xxx\Y /delete

*To delete connection to share Y on XXX
net use \\XXX\Y /delete

*To delete mapped network drive
net use Y: /delete

*To reconnect mapped network drive
net use Y: \\xxx.xxx.xxx.xxx\Y /PERSISTENT:YES /USER:XXX\user /SAVECRED
Another potential suspect is Samsung PC Share manager. After uninstalling it from the host the problem disappeared.

A: It could be possible that the client computer is using saved credentials. You can check using the Windows Credential Manager under Control panel.
Does this occur under a Local Admin account, eg machine_name\Administrator?
Is the machine authenticating to the domain controller properly?

A: Make sure that you aren't already connecting to \ad using different (or old) credentials.  I've seen similar issues when I had a mapped drive connected to a share on a server using my "regular" domain account and then I tried to connect to another share on the same server using my domain "admin" account.
Does a reboot resolve the problem?

A: I've had a related problem. I've had an XP Home machine accessing shares/shared folders and drives on a Windows 7 machine. I was playing around with the Workgroup / Homegroup settings on Windows 7 and changed the "Password protected sharing" option. I could see my shared folders on my XP Home machine, but could not read or write from/to them. It was driving me mad - because when I created a new user on the XP Home machine, and accessed my shares on the Win 7 machine, there were no problems - I could read and write files!
So I went back to my old (main) user account and I could still not access the shared files...
I tried all kinds of solutions - net use * /del and I tried deleting user accounts net user /delete - I tried to get rid of cached credentials - but nothing worked. Accessing the shares via an IP address DID work! Argggh!!
I tried setting the Workgroup on both machines to Workgroup (XP HOME machine was MSHOME)
Eventually what I had to do was change the COMPUTER NAME on my Windows 7 machine, rebooted, then accessed my shared folders from the XP HOME machine. It then asked me for a Logon user/password which I re-entered. However, I had paths and stuff which used my old computer name, so I then changed my Win 7 computer back to what it was originally. Alleluia! It worked - again I was asked for user/password and I could access my shares from XP HOME machine!
So, summary: there is some problem with cached credentials and no obvious way to delete them (nothing was shown in Network Password manager in the user account either). Therefore, Change your computer name temporarily and change it back and that could fix some issues.
I came across several similar issues on forums like these, but none the same as mine.

A: I had this issue after upgrading a Server 2008 R2 box to Server 2012 R2 with update.
For me going into Credentials Manager and removing Windows Credentials -> Generic Credentials resolved the issue.

A: In one of my cases, to my surprise, it just turned out to be that I needed to flush the DNS cache in addition to enabling the SMB 1.0 support feature in Windows 8.1. This was a domain-joined computer that was disconnected from its domain.
In the other case, a non-domain-joined computer, flushing the DNS cache didn't help. However, curiously, the fully-qualified name \\Name. worked when \\Name didn't (I didn't try this son the first machine).  I'm not sure what the problem here is, but I'm guessing it's related to the lack of a domain name.

A: We experienced this occurring on one specific folder only. Turns out Offline Folders caused the issue because we use redirected folders. So Windows is literally connecting to that share with the other users credentials as soon as Windows starts so it refuses the connection from the logged in user.
The solution used was to turn off offline sync.

A: Could be network ACLs. In one environment I worked in they were changed to block port 445. So:
\hostname\share

*

*Client tried to connect via SMB on TCP/IP port 445

*Blocked by network ACLs

*Client fails to connect

\hostname.fqdn\share

*

*Client tried to connect via SMB on TCP.IP port 445

*Blocked by network ACLs

*Client connects via NetBT on port 139

*Successful connect

So just so happened that connecting to FQDN tries to use NetBT, and port 139 was open, so was successful.
So solution was unblocking port 445.


text:
Q: How to update a view in react when data changes I'm trying to learn about a lot of stuff like: Typescript, Express and my new "obsessions" REACT and RXJS.
I created a Quick-List on github to study these things, but I found a question...
"How to update a view in react when data changes"
I have an object "List" on the class "IndexRoute":
import { NextFunction, Request, Response, Router } from "express";
import { List } from "../model/list";
import { Person } from "../model/person";
import * as _ from "lodash";

/**
 * Classe responsável por gerenciar as rotas de Index.
 */
export class IndexRoute {

  private router: Router;
  private list: List; <----[HERE]----

  /**
   * Constructor
   *
   * @class IndexRoute
   * @constructor
   */
  constructor(router: Router) {

    this.router = router;
    this.createList();
    this.routesForGET();
    this.routesForPOST();
    this.routesForPUT();
    this.routesForDELETE();
  }

  private createList() {
    this.list = new List();
    this.list.addPerson(new Person("111", "Joao", 1));
    this.list.addPerson(new Person("1325", "Maria", 10));
    this.list.addPerson(new Person("1564", "José", 25));
  }

  private routesForGET() {

    //Get Rota padrão (index)
    this.router.get("/", (req: Request, res: Response) => {

      var person: Person = this.list.getPersonByCPF("111");

      //set options
      let options: Object = {
        "title": "Express",
        "name": JSON.stringify(this.list.getList())
      };

      var view: string = "index";
      res.render(view, options);
    });
  }

  private routesForPOST() {

    //Adicionar uma nova person via REST
    this.router.post("/", (req: Request, res: Response) => {

      if (_.isEmpty(req.body)) {
        res.status(400).send("Não foi possivel adicionar o elemento, verifique os parametros.");
      } else {

        var cpf: string = req.params.cpf;

        var person = new Person(
          req.body.cpf,
          req.body.name,
          req.body.age
        );

        this.list.addPerson(person);
        res.send("Elemento adicionado com sucesso.");
      }
    });

    //Visualizar uma person com base no cpf
    this.router.post("/:cpf", (req: Request, res: Response) => {

      var cpf: string = req.params.cpf;
      var person: Person = this.list.getPersonByCPF(cpf);

      if (_.isEmpty(person)) {
        res.status(400).send("Não foi possivel encontrar o elemento.");
      } else {
        res.json(person);
      }

    });

    //Exibir body
    this.router.post("/get/list", (req: Request, res: Response) => {

      var l: Person[] = this.list.getList();
      if(_.isEmpty(l)){
        res.status(400).send("Lista vazia.");
      }else{
        res.json(l);
      }

    });

    //Exibir body
    this.router.post("/get/body", (req: Request, res: Response) => {
      res.send(JSON.stringify(req.body));
    });
  }

  private routesForPUT() {

    //Atualizar uma person com base no cpf
    this.router.put("/:cpf", (req: Request, res: Response) => {

      if (_.isEmpty(req.body)) {
        res.status(400).send("Não foi possivel adicionar o elemento, verifique os parametros.");
      } else {

        var cpf: string = req.params.cpf;

        var person = new Person(
          req.body.cpf,
          req.body.name,
          req.body.age
        );

        if (this.list.updatePersonByCPF(cpf, person)) {
          res.send("Elemento atualizado com sucesso.");
        } else {
          res.status(400).send("Não foi possivel atualizar o elemento,     verifique os parametros.");
        }

      }

    });
  }

  private routesForDELETE() {

    //Remover uma person com base no cpf
    this.router.delete("/:cpf", (req: Request, res: Response) => {

      var cpf: string = req.params.cpf;

      if (this.list.removePersonByCPF(cpf)) {
        res.send("Elemento removido com sucesso.");
      } else {
        res.status(400).send("Não foi possivel remover o elemento, verifique os parametros.");
      }

    });
  }
}

And I have the REACT component:
var React = require('react');
var DefaultLayout = require('./layouts/default');

class HelloMessage extends React.Component {
  render() {
    return (
      <DefaultLayout title={this.props.title}>

Hello {this.props.name}

      </DefaultLayout>
    );
  }
}

module.exports = HelloMessage;

My objective is: When the list in "IndexRoute" class changes, the view changes too.
OBS.: Without use angular.
But there is my main problem... I don't have any idea about how to do it, idk if reactive programming is the best idea, idk if i have to use react-native, exist a lot of tools to be used but idk what is the best for this scenario.
I know that angular can solve it but i like to learn another way.

A: I studied more and know how to solve it:
1 - Stopping to use express-react-views, it doesn't support mount views on the client.
2 - I have a route that return the list elements, I'll catch them with fetch() and update the view with setState().
Thx for all, and if someone saw anything wrong in my solution, please tell me to improve more. :)

A:
When the list in "IndexRoute" class changes, the view changes too.

The props used by the component (passed in from its parent) need to change based on route change.
More

I don't have any idea about how to do it, idk if reactive programming is the best idea

Walk before running. Start with hello world https://reactjs.org/docs/hello-world.html


text:
Q: WordPress Loop Takes Custom Meta from other Posts I used Devin Says' Team Post Type as a base for a custom post type with custom meta: https://github.com/devinsays/team-post-type. My plugin is virtually unchanged, aside from language updates and added fields.
When I output my posts, Custom Meta values that are empty for subsequent posts in the loop take the value of previous posts. So - if the Custom Meta of 'telephone' for Post One is set to '555-555-5555' and the Custom Meta of 'telephone' for Post Two is not set, in my loop, it displays '555-555-555'.
So - the HTML output (for example) would look like:

Person 1

555.555.5555

Person 2

555.555.5555

... even when there is no phone number in the database for Person 2.
I found this similar question which has the same symptom, but did not see a 'solution' that would help me - the recommendations that are stated are things I am doing already, and I do not see a critical difference in the way that I am calling data to the page: Values from custom meta boxes being repeated in posts
Does anyone have a suggestion regarding this problem?
I'm trying to output my posts using the following:
add_shortcode('staff-list', 'jpro_staff_list');
function jpro_staff_list($atts) {

extract(shortcode_atts(array(
), $atts));

$args = array (
    'post_type' => array( 'staff' ),
    'posts_per_page' => '-1',
    'orderby' => 'menu_order',
    'order'   => 'ASC'
);
$query = new WP_Query( $args );

$staff_list = '
';

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();

        $post   = get_post($id);
        $postID = $post->ID;

        $image  = get_the_post_thumbnail( $postID, 'medium', array( 'class' => 'aligncenter' ));
        $name   = get_the_title($postID);
        $bio    = apply_filters('the_content', $post->post_content);
        $title  = get_post_meta($postID, 'staff_title', true);
        $video  = get_post_meta($postID, 'staff_video', true);
        $email  = get_post_meta($postID, 'staff_email', true);
        $phone  = get_post_meta($postID, 'staff_phone', true);
        $fax    = get_post_meta($postID, 'staff_fax', true);

        if(!empty($image)){
        $output_image = '
'.$image.'
';
        }

        if(!empty($name)){
        $output_name ='
'.$name.'
';
        }

        if(!empty($bio)){
        $output_bio ='
'.$bio.'
';
        }

        if(!empty($video)){
        $output_video ='

';
            }

        if(!empty($title)){
        $output_title ='
'.$title.'
';
        }

        if(!empty($email)){
        $output_email ='

 '.$email.'

            ';
            }

        if(!empty($phone)){
        $output_phone ='

 '.$phone.'

            ';
            }

        if(!empty($fax)){
        $output_fax ='
 '.$fax.'
';
        }

            $staff_list .='
';
            $staff_list .= $output_name;
            $staff_list .= $output_video;
            $staff_list .= '
';
            $staff_list .= $output_image;
            $staff_list .= $output_name;
            $staff_list .= $output_title;
            $staff_list .= $output_email;
            $staff_list .= $output_phone;
            $staff_list .= $output_fax;
            $staff_list .= '
';
            $staff_list .= $output_bio;
            $staff_list .= '
';
    }
} else {
    $staff_list .='
Ooops! No Staff Found.
';
}

$staff_list .='
';
wp_reset_postdata();
return $staff_list;

}

A: Technically your script works correctly. Because you never clear the $output_xyz variables at any time your script assumes the value from the last loop.
Either change your if ( !empty (...) ) ... to have an else block like this:
if ( !empty ( $phone ) ) {
    $output_phone = '...';
} else {
    $output_phone = '';
}

Or clear the variables at the beginning of each loop:
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();

        $output_image = '';
        $output_phone = '';
        ...
    }
}


text:
Q: Reload a Letsencrypt certificate on Docker I'm running Nginx within a Docker container and I need to reload its configuration periodically to pick up the updated Letsecnrypt SSL certificate.
In the docker-compose file I have the followings
command: "/bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g \"daemon off;\"'"

Which, as far as I know, should reload the configuration and restart Nginx every 6 hours. however, it doesn't work. The SSL certificate is renewed but it's not picked up by Nginx.
Any ideas of how I can correctly reload the Letsencrypt SSL certificate every few hours?
Update 08/08/19
From my understanding, the issue is related to the fact that the certificate files I mount into the container are actually symlinks and symlinks don't play nicely with Docker.

A: These solutions involving a while loop inside the command of docker-composer.yml have a fundamental flaw regarding signal handling.  The shell script is now the main process which receives the signal for shutting down, but it won't be properly forwarded to nginx.  This causes the container to not shut down immediately on docker-compose down, and then it runs into the default 10 seconds timeout before it is killed.  See Why do my services take 10 seconds to recreate or stop?
Here's a solution that leaves nginx as the main process:
version: '3.6'
services:
    nginx:
        image: nginx
        volumes:
            - ./99-autoreload.sh:/docker-entrypoint.d/99-autoreload.sh
    # add certbot container here

And then create a file 99-autoreload.sh:
#!/bin/sh
while :; do
    # Optional: Instead of sleep, detect config changes and only reload if necessary.
    sleep 6h
    nginx -t && nginx -s reload
done &

Don't forget to chmod 755 99-autoreload.sh, otherwise it won't be executed.
A more advanced setup would be to actually detect change and only reload if necessary.  This can be done with inotifywait for example.

A: This should work if you have the ability to use the host's crontab for scheduling:
0 */6 * * * docker exec <nginx_container_id> nginx -s reload
via Source
And then don't specify the custom command with the wait and reload that you tried in your question. Just orchestrate the reload from the host's cron.
If you can't use the host's cron in your environment, however, you'll need another solution...


text:
Q: How to get the previous focus and compare strings How can I get the previous focus/be able to compare strings?

A: You need to listen for the FocusEvent.FOCUS_OUT event; you can learn more in the documentation.
But seriously, you should learn basic repetition constructs like a loop first.  No one should ever have two arrays that look like that ;-)

A: The FocusEvent.FOCUS_IN event contains also a reference to the interactive object losing the focus (relatedObject property).
In your code you could change:
textbox[i].addEventListener(KeyboardEvent.KEY_UP, k);
textbox[i].tabIndex= i;

to:
textbox[i].addEventListener(KeyboardEvent.KEY_UP, k);
textbox[i].addEventListener(FocusEvent.FOCUS_IN, handleFocusIn);
textbox[i].tabIndex= i;

function handleFocusIn(anEvent: FocusEvent): void
{
  if (anEvent.relatedObject is TextField)
  {
     var previousBox: TextField = anEvent.relatedObject as TextField;
     var currentBox: TextField = anEvent.target as TextField;
     // etc.
  }
}

Like the previous answer said, try to figure out how looping works. Also you can reference the TextField using []:
// to reference names_mc.box19_txt using an index
var index: int = 19;
var textbox: TextField = names_mc['box' + index + '_txt'];


text:
Q: load parquet file and keep same number hdfs partitions I have a parquet file /df saved in hdfs with 120 partitions.  The size of each partition on hdfs is around 43.5 M.
Total size
hdfs dfs -du -s -h /df
5.1 G  15.3 G  /df

hdfs dfs -du -h /df
43.6 M  130.7 M  /df/pid=0
43.5 M  130.5 M  /df/pid=1
...
43.6 M  130.9 M  /df/pid=119

I want to load that file into Spark and keep the same number of partitions.
However, Spark will automatically load the file into 60 partitions.
df = spark.read.parquet('df')
df.rdd.getNumPartitions()

60

HDFS settings:
'parquet.block.size' is not set.
sc._jsc.hadoopConfiguration().get('parquet.block.size')

returns nothing.
'dfs.blocksize' is set to 128.
float(sc._jsc.hadoopConfiguration().get("dfs.blocksize"))/2**20

returns
128

Changing either of those values to something lower does not result in the parquet file loading into the same number of partitions that are in hdfs.
For example:
sc._jsc.hadoopConfiguration().setInt("parquet.block.size", 64*2**20)
sc._jsc.hadoopConfiguration().setInt("dfs.blocksize", 64*2**20)

I realize 43.5 M is well below 128 M.  However, for this application, I am going to immediately complete many transformations that will result in each of the 120 partitions getting much closer to 128 M.
I am trying to save myself having to repartition in the application imeadiately after loading.
Is there a way to force Spark to load the parquet file with the same number of partitions that are stored on the hdfs?

A: First, I'd start from checking on how Spark splits the data into partitions.
By default it depends on the nature and size of your data & cluster.
This article should provide you with the answer why your data frame was loaded to 60 partitions:
https://umbertogriffo.gitbooks.io/apache-spark-best-practices-and-tuning/content/sparksqlshufflepartitions_draft.html
In general - its Catalyst who takes care of all the optimization (including number of partitions), so unless there is really a good reason for custom settings, I'd let it do its job. If any of the transformations you use are wide, Spark will shuffle the data anyway.

A: I can use the spark.sql.files.maxPartitionBytes property to keep the partition sizes where I want when importing.
The Other Configuration Options documentation for the spark.sql.files.maxPartitionBytes property states:

The maximum number of bytes to pack into a single partition when reading files. This configuration is effective only when using file-based sources such as Parquet, JSON and ORC.

Example (where spark is a working SparkSession):
spark.conf.set("spark.sql.files.maxPartitionBytes", 67108864) ## 64Mbi

To control the number of partitions during transformations, I can set spark.sql.shuffle.partitions, for which the documentation states:

Configures the number of partitions to use when shuffling data for joins or aggregations.

Example (where spark is a working SparkSession):
spark.conf.set("spark.sql.shuffle.partitions", 500)

Additionally, I can set spark.default.parallelism, for which the Execution Behavior documentation states:

Default number of partitions in RDDs returned by transformations like join, reduceByKey, and parallelize when not set by user.

Example (where spark is a working SparkSession):
spark.conf.set("spark.default.parallelism", 500)


text:
Q: Is the von Neumann algebra of type I under the given hypothesis?
Suppose $\mathscr{R}$ is a von Neumann algebra acting on $\mathcal{H}$ and $\{E_a\}$ is a family of abelian projections in $\mathscr{R}$ such that $I= \sum E_a$.

Assume this is given. Now this means that "non-zero abelian" projection exists in the algebra $\mathscr{R}$. So it cannot be of type $II$ or of type $III$ (since by definition in those algebras there is no abelian projections). Then I have two question in mind:

*

*Can I now say that $\mathscr{R}$ is of Type I (definition: there exists an abelian projection with central carrier $I$)?

*If Q1 is true. then how to construct an abelian projection, $E$ with $C_E=I$, from the initial $\{E_a\}$?

A: There is no explicit way of doing this. The problem is that you don't know the relations between the distinct $E_a$.
Applying the Type Decomposition Theorem, there exists a central projection $P$ such that $RP$ is type I, and $R(I-P)$ has no abelian subprojections. Since $E_a(I-P)$ is abelian for all $a$, we get that $E_a(I-P)=0$ for all $a$; thus $I-P=\sum_a E_a(I-P)=0$, and $P=I$.
Explicitly constructing an abelian projection $E$ with $C_E$ is not doable with the data you have. Consider for instance $R=M_2(\mathbb C^2)$, and
$$
E_1=\begin{bmatrix} (1,1)&(0,0)\\ (0,0)&(0,0)\end{bmatrix},
\quad
E_2=\begin{bmatrix} (0,0)&(0,0)\\ (0,0)&(1,0)\end{bmatrix},
\quad
E_3=\begin{bmatrix} (0,0)&(0,0)\\ (0,0)&(0,1)\end{bmatrix}.
$$
Examples of abelian projections $E$ with $C_E=I$ are $E_1$, and $E_2+E_3$.
If instead we have
$$
E_1=\begin{bmatrix} (1,0)&(0,0)\\ (0,0)&(0,0)\end{bmatrix},
\quad
E_2=\begin{bmatrix} (0,1)&(0,0)\\ (0,0)&(0,0)\end{bmatrix},
\quad
E_3=\begin{bmatrix} (0,0)&(0,0)\\ (0,0)&(1,0)\end{bmatrix},
\quad
E_4=\begin{bmatrix} (0,0)&(0,0)\\ (0,0)&(0,1)\end{bmatrix}.
$$
Now the examples become $E_1+E_2$ and $E_3+E_4$. An orthogonal family of abelian projections is not enough information to explicitly find who the abelian projection with central carrier 1 will be.


text:
Q: Windows Phone Emulator 8.0: No hardware virtualization detected when I do have it I just installed Vistual Studio 2013 and I get an error stating

This computer does not support hardware virtualization, which means Windows Phone Emulator 8.0 can't run on this PC.

The problem is, that I do have hardware virtualization, and I'm not running this in a VM. I have Windows 8.1 Pro installed as the primary OS on my desktop, using an Intel Core2 Duo e6600. Microsoft's own "coreinfo" util found at here says my CPU "Supports Intel hardware-assisted virtualization". I was even able to run Hyper-V on Windows 8.0 about a year ago, but since removed it.
Any idea why it's not being detected, and preventing the emulator from running?


text:
Q: how do i modify the get number function so that in the next attempt i will get new number "use strict"

function getNumber(){
   return (Math.floor(Math.random()*100+1));
}

var compNumber = getNumber();
var chances = 0;
let playAgain = false;

do {
    playAgain = false;
    var userNumber = prompt("Enter your number.");
        userNumber = Number(userNumber);

    if(userNumber>compNumber){
        console.log("your number is greater.");
    }
    else if(userNumber<compNumber){
        console.log("your number is lesser.");
    }
    else{
        console.log(`congratulations you guessed it right and your score is ${100-chances}`);
            playAgain = confirm("do you want to play again ?");
        if(playAgain){
            getNumber();
            chances = 0;
        }
    }
    chances++
}while(userNumber!== compNumber && chances<=100 || playAgain);

now this program giving me same random number after i confirm to play again but i wanted another random number how could i achieve this

A:

"use strict"

function getNumber(){
   return (Math.floor(Math.random()*100+1));
}

var compNumber = getNumber();
var chances = 0;
let playAgain = false;

do {
    playAgain = false;
    var userNumber = prompt("Enter your number.");
        userNumber = Number(userNumber);

    if(userNumber>compNumber){
        console.log("your number is greater.");
    }
    else if(userNumber<compNumber){
        console.log("your number is lesser.");
    }
    else{
        console.log(`congratulations you guessed it right and your score is ${100-chances}`);
            playAgain = confirm("do you want to play again ?");
        if(playAgain){
            compNumber = getNumber();
            chances = 0;
        }
    }
    chances++
}while(userNumber!== compNumber && chances<=100);


text:
Q: How to prove this formula to evaluate limits? A text says
For any positive integer n,
Lim x approaching a $(x^n - a^n)/(x - a) = na^{n-1}$
Then it proved it using the quotient obtained by the division of two polynomials and obtained a polynomial and pluhged in x= a as polynomials are continuous to yield the result. Then it also said that the given theorem is also true if
"N is any rational number and a is positive" why how can we prove this because then we no longer are dealing with polynomials ?

A: By a change of variable:
Let $n=p/q$, then with $x=y^q$ and $a=b^q$,
$$\frac{x^{p/q} - a^{p/q}}{x - a}=\frac{y^p-b^p}{y^q-b^q}=\frac{\dfrac{y^p-b^p}{y-b}}{\dfrac{y^q-b^q}{y-b}},$$
which tends to
$$\frac{pb^{p-1}}{qb^{q-1}}=\frac{pa^{(p-1)/q}}{qa^{(q-1)/q}}=\frac pqa^{p/q-1}=na^{n-1}.$$


text:
Q: Return to a previous session id We have a legacy (php) aplication, accepting file uploads and they are stored at a path depending on the session id. Now we had to provide a very simple API for this webapp, where through an iOS api (iPad) a file upload is performed. We return an url which the customer will open in an embedded webkit window.
Because the sessions from the upload and view actions are different, we thought to grab the session parameter and return it in our response from the file upload. Then the client gets redirected to that url, we set the session id to the previous id and continue to the page the customer can continue the work.
Apparently, nothing I tried works. We use Zend Framework 1, but that shouldn't really matter. I tried:

*

*Setting a Set-Cookie header (this results in a cookie containing two PHPSESSID values)

*Use a setcookie("PHPSESSID", $session, 3600) to set the PHPSESSID

*Use the Zend http Reponse with a setHeader('Set-Cookie', 'PHPSESSID=....', true)
The last two options just don't do anything, like I didn't set the session at all. How can I solve this? We actually can't touch the legacy code base that much to modify its working and change the way the path resolving works for file uploads.
So, the flow is:
Request to api.myapp.tld -> Response with a string in body -> Open webkit window with this response string as location -> Request is performed -> Response with a Redirect header and a method to set the cookie to something different -> Webkit performs redirect -> Customer gets to a page with same session ID as the first request to api.myapp.tld.
If there is an alternative to set the session id, it would be great.

A: That's not trivial to debug, but you have some options. I'm not fluent with Zend Framework 1.x, so this is not framework specific (frameworks sometimes add stuff on top), but PHP specific.
In PHP a session is identified by two things:

*

*Name (example: a common default name is PHPSESSID)

*ID (that is the random "number")

The Name allows to use multiple sessions at once, while the ID identifies the session in specific.
It sounds a bit you need to use two session IDs in parallel. I suggest you make the script that needs to deal with the legacy session to have another sessions name than your current script.
You can then pass in the legacy/old session id by using the other session name while your current session can remain as is.
I hope this information is helpful. If you have got problems to implement that, please ask.

A: I ended up by something simpler. The session was related to the path like this /path/to/location/ . $sessionId. When the second session was started, I simply renamed the directory from the old session to the new one. Simple and fast to get this working.


text:
Q: Value of complex integral Let $\alpha,\beta,\gamma\in\mathbb{C}$. I'd like to calculate the integral
$$\int_{-\infty}^{0}t^\alpha e^{\beta t}(1-e^{-2t})^\gamma dt.$$ For some special cases like when $\gamma=0$ or if $\gamma\in\mathbb{R}$, I can find the value of the integral explicitly. However, I can't find how to compute this integral for the general case.
How can I find it?


text:
Q: Como corrigir Cross site scripting ou XSS Estou estudando sobre algumas vulnerabilidades que encontrei em um site que fiz e me deparei com a possibilidade do invasor enviar código malicioso, pelo que li e por isso minha pergunta aqui, só preciso corrigir o meu script com um código parecido com esse:
Aplicação com vulnerabilidade:
$busca= $_GET["busca"];

Aplicação sem vulnerabilidade:
$busca= htmlspecialchars ($_GET["busca"]);

Somente com essa alteração é possível eliminar a possibilidade de ataque via Cross site scripting ou XSS?

A: Boa tarde,
A utilização do htmlspecialchars não irá resolver ataques de XSS sofisticados. Aconselho utilizar esse classe Anti-XSS que está mais específica:
<?php

class AntiXSS {
    public static $err = "XSS Detected!";

    /*
     * @function   : setEncoding
     * @return     : String
     * @parameters : str: Content you want to change the character encoding
     *               newEncoding: Character encoding you want set
     * @description: Convert the character encoding of the string
     *               to newEncoding from currentEncoding. currentEncoding
     *               detecting by function so you only need give str and
     *               newEncoding to the setEncoding function.
     */
    public static function setEncoding($str, $newEncoding) {
        $encodingList = mb_list_encodings();
        $currentEncoding = mb_detect_encoding($str, $encodingList);
        $changeEncoding = mb_convert_encoding($str, $newEncoding, $currentEncoding);

        return $changeEncoding;
    }

    /*
     * @function   : blacklistFilter
     * @return     : String
     * @parameters : str: Content you want to filter with blacklist
     * @description: Filter the content by blacklist method. Library use
     *               RSnake's XSS attack vectors. To add new attack vectors
     *               I'm continue to research.
     */
    public static function blacklistFilter($str) {
        if (preg_match("/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t(.*)>(.*)/i", $str) > 0) {
            return $str;
        } else {
            return self::$err;
        }
    }

    /*
     * @function   : whitelistFilter
     * @return     : String
     * @parameters : str: Content you want to filter with blacklist
     *               whiteFilterPattern: Some patterns for filter the
     *               data types.
     * @description: Filter the content by whitelist method. To add
     *               new data types, I'm continue to research.
     */
    public static function whitelistFilter($str, $whiteFilterPattern) {

        switch ($whiteFilterPattern) {
            case "string":
                $pattern = "([a-zA-Z]+)";
            break;
            case "number":
                $pattern = "([0-9]+)";
            break;
            case "everything":
                $pattern = "(.*)";
            break;
            default:
                $pattern = "([0-9a-zA-Z]+)";
            break;
        }

        if(preg_match("/^$pattern $/i", $str) > 0) {
            return $str;
        } else {
            return self::$err;
        }
    }

    /*
     * @function   : setFilter
     * @return     : String
     * @parameters : str: Content you want to filter with blacklist
     *               filterMethod: Library have 3 method.
     *                  -Black Method
     *                  -White Method
     *                  -Gray Method
     *               filterPattern: Some patterns for filter the
     *               data types. (You can only use with whitelist filter)
     *               noHTMLTag: Use PHP's strip_tags function to
     *               remove HTML tags from content.
     * @description: Filter the content by method.
     */
    public static function setFilter($str, $filterMethod, $filterPattern = NULL, $noHTMLTag = NULL) {

        if (urldecode($str) > 0) {
            $str = urldecode($str);
        }

        if ($noHTMLTag == 1) {
            $str = strip_tags($str);
        }

        $str = strtolower($str);
        $str = addslashes($str);
    $str = htmlspecialchars(trim($str));

        switch($filterMethod) {
            case "black":
                $str = self::blacklistFilter($str);
            break;
            case "white":
                $str = self::whitelistFilter($str, $filterPattern);
            break;
            default:
            break;
        }

        return $str;
    }
}
?>

Espero ter ajudado.

A: Basta remover certos caracteres, como por exemplo <, >, &, ', ", /
Crie algum tipo de filtro, da pra utilizar o regex para fazer esse filtro.
$xss = /[&<>"'*]/;
De uma olhada no w3school de como utilizar o regex
https://www.w3schools.com/php/php_regex.asp
no exemplo abaixo tem uma solução utilizando javascript, eu utilizei esse código no React (frontend), o filtro era realizado assim que o usuário digitava alguma coisa, só não esquece que colocar o filtro no backend também

export const htmlPurify = (value = '') => {
  const regex = /[!@#$%^&<>"'¨¨*]/;
  return value.replace(regex, '');
};

A: Você tem uma opção não tão sofisticada quanto a do P1xM4, mas uma alternativa também é a filter_var:
$busca= htmlspecialchars ($_GET["busca"]);
$strBusca = filter_var($busca,FILTER_SANITIZE_NUMBER_STRING);

A: Basta bloquear caracteres especiais de serem interpretados no browser.
Alguns deles são < > ' ", etc.


text:
Q: In ES6 with react, can I destructure an object just once for use in multiple methods? import React, { Component } from 'react'
import { connect } from 'react-redux';

export default function(strategies = []) {
    class Authentication extends Component {
        constructor() {
            super()
            this.state = {
                allGreen: true
            }
        }
        componentWillMount() {
            const { history } = this.props
            strategies.map(strategy => {
                if (!this.props.auth[strategy]) {
                    this.setState({ allGreen: false })
                    history.replace('/')
                }
            })
        }
        componentWillUpdate(nextProps, nextState) {
            const { history } = this.props
            strategies.map(strategy => {
                if (!nextProps.auth[strategy]) {
                    this.setState({ allGreen: false })
                    history.replace('/')
                }
            })
        }
        render() {
            if (!this.state.allGreen) return (

)

            return this.props.children
        }
    }

    function mapStateToProps(state) {
        return {
            auth: state.auth
        }
    }

    return connect(mapStateToProps)(Authentication)
}

I'm using 'destructor object' usually in ES6
For example, const { history } = this.props like.
However, I want to know whether there is an efficient way to have just one object destruction, and use it in all of component's method.(componentWillMount, componentWillUpdate ...)
Above picture, I used object destruction twice in componentWillMount method and componentWillUpdate method. ( const { history } = this.props )
I want to destruct object just once! Is there any solution ?

A: There's not performance issues on using destructurization multiple times (you are not expanding the whole object if this is your fear).
An ES 6 code like::
const aaa = {
  a: 5,
  b: 'ffff'
}

const { bbb } = aaa;

... is translated to...
var aaa = {
  a: 5,
  b: 'ffff'
};

var bbb = aaa.bbb;

Try it to https://babeljs.io
So use it, or simply use this.props.history


text:
Q: Only append document if image is valid using jquery I have an array of image urls that I need to add to a document (shown below). Some of the urls do not contain images. How do I check this?
picUrls = ["https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/048.jpg","https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18166-shivling-whatsapp-image-and-dp.jpg","http://www.fakeurl.io/fakeimage1.jpeg","https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18416-navratri-image-for-whatsapp-and-facebook.jpg"]

I am using jquery and have tried the .load & .error
for(let i = 0; i < picUrls.length; i++) {
    const picUrl = picUrls[i];

    //create image to preload:
    var imgPreload = new Image();
    $(imgPreload).attr({
      src: picUrl
    });

    //check if the image is already loaded (cached):
    if (imgPreload.complete || imgPreload.readyState === 4) {

      //image loaded:
      //your code here to insert image into page
      $('#content-container').append(imgPreload);

    } else {
      //go fetch the image:
      $(imgPreload).load(function (response, status, xhr) {
        if (status == 'error') {

          //image could not be loaded:
          console.log('error');
        } else {

          //image loaded:
          //your code here to insert image into page
          $('#content-container').append(imgPreload);

        }
      });

A: You can create a helper function that returns a promise whether an image is a valid image or not
      const picUrls = [
        'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/048.jpg',
        'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18166-shivling-whatsapp-image-and-dp.jpg',
        'http://www.fakeurl.io/fakeimage1.jpeg',
        'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18416-navratri-image-for-whatsapp-and-facebook.jpg',
      ];

      const getOnlyValidImage = src =>
        new Promise((resolve, reject) => {
          const img = new Image();
          img.src = src;
          img.onload = () => resolve(img);
          img.onerror = () => resolve(null);
        });

      const preloadImages = async () => {
        for (let i = 0; i < picUrls.length; i++) {
          const picUrl = picUrls[i];
          const image = await getOnlyValidImage(picUrl)
          if (image) {
            $('#content-container').append(image);
          }
        }
      };

      preloadImages();


text:
Q: How to create shorter if-statements, or make them look better? I have this code, where the conditions are very similar and the methods being called are the same. I was wondering if there's a way to make this look better, or at least make it smaller and thus easier to read.
public void open(int i, int j){
    if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
    throw new IndexOutOfBoundsException
        ("Index out of bounds.");
    }
    grid[i][j] = true;

    if (i - 1 >= 0 && grid[i - 1][j]) {
        unionFind.union(location(i - 1, j), location(i, j));
        unionFind2.union(location(i - 1, j), location(i, j));
    }

    if (i + 1 < n && grid[i + 1][j]) {
        unionFind.union(location(i + 1, j), location(i, j));
        unionFind2.union(location(i + 1, j), location(i, j));
    }

    if (j - 1 >= 0 && grid[i][j - 1]) {
        unionFind.union(location(i, j - 1), location(i, j));
        unionFind2.union(location(i, j - 1), location(i, j));
    }

    if (j + 1 < n && grid[i][j + 1]) {
        unionFind.union(location(i, j + 1), location(i, j));
        unionFind2.union(location(i, j + 1), location(i, j));
    }
    numberOpen++;
}

A: Well, you could easily write a method which conditionally calls the union method, then call that unconditionally from open:
public void open(int i, int j) {
    if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
        throw new IndexOutOfBoundsException("Index out of bounds.");
    }
    grid[i][j] = true;
    // I'm assuming the result of this doesn't change between calls?
    // (We don't know the type, either.)
    Location thisLocation = location(i, j);
    maybeUnion(i - 1, j, thisLocation);
    maybeUnion(i + 1, j, thisLocation);
    maybeUnion(i, j + 1, thisLocation);
    maybeUnion(i, j - 1, thisLocation);
    numberOpen++;
}

private void maybeUnion(int x, int y, Location unionWith) {
    if (x < 0 || y < 0 || x >= n || y >= n || !grid[x][y]) {
        return;
    }
    unionFind.union(location(x, y), unionWith);
    unionFind2.union(location(x, y), unionWith);
}

A: private int[] dr = new int[] {-1, 1, 0, 0};
private int[] dc = new int[] { 0, 0, -1, 1};

public void open(int i, int j) {
    if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
        throw new IndexOutOfBoundsException("Index out of bounds.");
    }
    grid[i][j] = true;

    Location thisLocation = new location(i, j);

    for (int k = 0; k < 4; i++) {
        int newI = dr[k] + i;
        int newJ = dc[k] + j;
        performUnion(new Location(newI, newJ), thisLocation);
    }

    numberOpen++;
}

private void performUnion(Location loc, Location unionWith) {
    if (loc.x < 0 || loc.y < 0 || loc.x >= n || loc.y >= n && !grid[loc.x][loc.y]) {
        return;
    }
    unionFind.union(loc, unionWith);
    unionFind2.union(loc, unionWith);
}

A: Try this.
static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

boolean inRange(int i, int j) {
    return i >= 0 && i < n && j >= 0 && j < n;
}

public void open(int i, int j) {
    if (!inRange(i, j))
        throw new IndexOutOfBoundsException("Index out of bounds.");
    grid[i][j] = true;
    for (int[] dir : DIRECTIONS) {
        int ii = i + dir[0], jj = j + dir[1];
        if (inRange(ii, jj) && grid[ii][jj]) {
            unionFind.union(location(ii, jj), location(i, j));
            unionFind2.union(location(ii, jj), location(i, j));
        }
    }
    numberOpen++;
}


text:
Q: Can't run Jquery function more than once I'm using JQuery and AJAX to load replace content in the website (for an HTML based game) instead of switching pages, which would stop music and animations that are playing. However, once the user clicks on a div with the class "d," the script for the div with class "f" no longer works. The same is true if the user clicks .f first; then .d no longer loads in the content anymore. How can I let these both (and many more in the future) work without canceling each other out? Do I need to use a loop? Or an if/else statement?
$(document).ready(function(){
    //d
    $(".d").click(function(){
        $("#content").load("d.htm");
    });

    //f
    $(".f").click(function(){
        $("#content").load("f.htm");
    });
});