text:
Q: any rules of thumb how to smooth FFT spectrum to prevent artifacts when hand-tweaking? I've got a FFT magnitude spectrum and I want to create a filter from it that selectively passes periodic noise sources (e.g. sinewave spurs) and zero's out the frequency bins associated with the random background noise. I understand sharp transitions in the freq domain will create ringing artifacts once this filter is IFFT back to the time domain... and so I'm wondering if there are any rules of thumb how to smooth the transitions in such a filter to avoid such ringing.
For example, if the FFT has 1M frequency bins, and there are five spurs poking out of the background noise floor, I'd like to zero all bins except the peak bin associated with each of the five spurs. The question is how to handle the neighboring spur bins to prevent artifacts in the time domain. For example, should the the bin on each side of a spur bin be set to 50% amplitude? Should two bins on either side of a spur bin be used (the closest one at 50%, and the next closest at 25%, etc.)? Any thoughts greatly appreciated. Thanks!

A: I like the following method:

*

*Create the ideal magnitude spectrum (remembering to make it symmetrical about DC)

*Inverse transform to the time domain

*Rotate the block by half the blocksize

*Apply a Hann window

I find it creates reasonably smooth frequency domain results, although I've never tried it on something as sharp as you're suggesting.  You can probably make a sharper filter by using a Kaiser-Bessel window, but you have to pick the parameters appropriately.  By sharper, I'm guessing maybe you can reduce the sidelobes by 6 dB or so.
Here's some sample Matlab/Octave code.  To test the results, I used freqz(h, 1, length(h)*10);.
function [ht, htrot, htwin] = ArbBandPass(N, freqs)
%# N = desired filter length
%# freqs = array of frequencies, normalized by pi, to turn into passbands
%# returns raw, rotated, and rotated+windowed coeffs in time domain

if any(freqs >= 1) || any(freqs <= 0)
    error('0 < passband frequency < 1.0 required to fit within (DC,pi)')
end

hf = zeros(N,1); %# magnitude spectrum from DC to 2*pi is intialized to 0
%# In Matlabs FFT, idx 1 -> DC, idx 2 -> bin 1, idx N/2 -> Fs/2 - 1, idx N/2 + 1 -> Fs/2, idx N -> bin -1
idxs = round(freqs * N/2)+1; %# indeces of passband freqs between DC and pi
hf(idxs) = 1; %# set desired positive frequencies to 1
hf(N - (idxs-2)) = 1; %# make sure 2-sided spectrum is symmetric, guarantees real filter coeffs in time domain
ht = ifft(hf); %# this will have a small imaginary part due to numerical error
if any(abs(imag(ht)) > 2*eps(max(abs(real(ht)))))
    warning('Imaginary part of time domain signal surprisingly large - is the spectrum symmetric?')
end
ht = real(ht); %# discard tiny imag part from numerical error
htrot = [ht((N/2 + 1):end) ; ht(1:(N/2))]; %# circularly rotate time domain block by N/2 points
win = hann(N, 'periodic'); %# might want to use a window with a flatter mainlobe
htwin = htrot .* win;
htwin = htwin .* (N/sum(win)); %# normalize peak amplitude by compensating for width of window lineshape


text:
Q: Ionic 3 Cordova - Apple sign in sometimes throws ASAuthorizationErrorUnknown on first login attempt leading to apps getting rejected I have a Ionic 3 white label application and i am using this plugin:
https://github.com/zmagyar/cordova-plugin-applesignin
Everything seems to be working fine and there don't seem to be any issues while testing the application as i never experienced the error but when submitted to the AppStore, the reviewer sometimes blocks the application as having a bug related to Apple Sign in.
I added a logging system to the app that helped me identify the error thrown by Apple sign in plugin on occasion is: ASAuthorizationErrorUnknown.
Not all apps get rejected, even though they have the same code.
A app in particular has been repeatedly rejected. The apps don't have any differences in how the login is handled.
I tested the App on both an emulator and a physical phone with the exact same iOS version the reviewer tested on.
My questions are:
Could it be the plugin? (I previously tried other plugins that didn't work). Considering the answer is coming straight from Apple, and it works in 99.9% of the time its probably not the plugin, right?
Do you know what could cause that error?
Do you know of an alternative of implementing apple login on a Ionic 3 app that worked for you?
Fingers crossed :)
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nested Promises in JS I'm trying to wait on two promises and get both functions to be called. Below is my AWS Lambda, but I believe this is purely a Node problem.
In my log, I see @@BP12.1, and BP1-1, amd BP1-2, but I don't see BP1-3, BP1-4, and BP1-5. I can't see evidence that it called the static MessageSession.getAccessToken token. I'd like the code below to call both sendMessage and updateStatus, both of which return promises, and wait for the completion of them. I'd like sendMessage to actually call the getAccessToken and create the message.
I have a Promise to return something which joins two promises. What did I do wrong with the Promise nesting?
exports.handler = async(event, context, callback) => {
...
console.info('@@BP12.1: ');
var statusTypeName = 'AVAILABLE';
                (async() => {
                    await Promise.all([sendMessage(event), updateStatus(event, statusTypeName).promise]);
                })();
...
}

async function sendMessage(payload) {
    const promise = new Promise(function(resolve, reject) {
        console.info('@@BP1-1');
        let argumentParserResult = { ...};
        console.info('@@BP1-2');
        let accessToken = MessagingSession.getAccessToken(argumentParserResult).then((accessTokenResponse) => {
            console.info('@@BP3');
            argumentParserResult.accessToken = accessTokenResponse.access_token;
            let messagingSession = new MessagingSession(MessagingSession.getInitializedSolaceModule(), argumentParserResult);
            console.info('@@BP4');
            resolve(messagingSession);
        }).catch(error => {
            console.info('@@BP5');
            console.info("Error fetching access token: " + error);
            reject(error);
        })

    });
    return promise;
}


text:
Q: Uploading app into App Store it will takes 7 to 8 days.Is there any solution for minimum days its upload into App Store? uploading an iOS application in App Store it will takes 7 to 8 days.Is there any way it will take minimum days ?

A: If you have a good reason to convince Apple, then YES. You can ask for an expedite review. You can find the option in developer.apple.com. But, as I have said, you must convince Apple about the urgency. And more, next time you need a expedite review for a new version or for a new app, they will reject it. They never accept two expedite review request in a period of one year from a developer.

A: There is no other way. If you want to upload your app to iOS App Store you have to wait for Apple to review your App.

A: There is no set time-limit for the app approval process. it can take anywhere between 5 days and 4 weeks.There's nothing technical you can do to get your app reviewed faster.
but nevertheless here is some Tricks and Tips for App approval.


text:
Q: How to remove white space between table rows I'm actually working on something pretty easy for school but I'm failing on something simple. I'm trying to get this result, but instead I have a white space between the table rows. I'd be really glad if this is fixed. If you should have some time, could you please tell me why the
td > h3,p{ padding-left: .5rem;padding-bottom: 1rem;} only applies at the middle td?

but instead I'm getting this result:

My code goes like this:

table{
  border: 1px solid black;
}

th{
  background-color: #F7BF2A;
  padding: .5rem;
  color: white;
}

td{
  border: 1px solid black;
}

td > h3,p{
  padding-left: .5rem;
  padding-bottom: 1rem;
}

          Wanneer
          Wat
          Waar

          14u00

Zeepkistenrace

Knutsel jouw zeepkist in elkaar en breng ze mee naar de top van de kemmelberg. Inschrijven kan via e-mail naar zeepkisten@burgerfeesten.be

          Kemmelberg

          19u00

Eetwedstrijd

Wie eet het meeste burgers in 30 minuten? Versla jij het record van 16 burgers? Inschrijven kan de dag zelf aan de bonnentjesstand.

          Feesttent marktplein

          20u00

Mister/Miss KemmelBurger

          21u00

Balkan Bonanza

Wie de beentjes al eens wil losgooien kan dit perfect doen op de tonen van Balkan Bonanza. Deze groep uit Loker brengt een verrassende mix van balkan en bluegrass. Benieuwd? Afkomen!

          Podium

          22u00

Bal van de Burger

We feesten door tot in de vroege uurtjes met dicobar Bun & Pickles.

            VVK: € 3 - ADD: € 5

          Podium en feesttent

A: You should add the border-collapse: collapse tag to ensure the borders are combined:

table{
  border: 1px solid black;
  border-collapse: collapse;
}

th{
  background-color: #F7BF2A;
  padding: .5rem;
  color: white;
}

td{
  border: 1px solid black;
}

td > h3,p{
  padding-left: .5rem;
  padding-bottom: 1rem;
}

          Wanneer
          Wat
          Waar

          14u00

Zeepkistenrace

Knutsel jouw zeepkist in elkaar en breng ze mee naar de top van de kemmelberg. Inschrijven kan via e-mail naar zeepkisten@burgerfeesten.be

          Kemmelberg

          19u00

Eetwedstrijd

Wie eet het meeste burgers in 30 minuten? Versla jij het record van 16 burgers? Inschrijven kan de dag zelf aan de bonnentjesstand.

          Feesttent marktplein

          20u00

Mister/Miss KemmelBurger

          21u00

Balkan Bonanza

Wie de beentjes al eens wil losgooien kan dit perfect doen op de tonen van Balkan Bonanza. Deze groep uit Loker brengt een verrassende mix van balkan en bluegrass. Benieuwd? Afkomen!

          Podium

          22u00

Bal van de Burger

We feesten door tot in de vroege uurtjes met dicobar Bun & Pickles.

            VVK: € 3 - ADD: € 5

          Podium en feesttent

A: Add border-collapse: collapse; to table.
table {
    border: 1px solid black;
    border-collapse: collapse;
}

table {
    border: 1px solid black;
    border-collapse: collapse;
}

th{
  background-color: #F7BF2A;
  padding: .5rem;
  color: white;
}

td{
  border: 1px solid black;
}

td > h3,p{
  padding-left: .5rem;
  padding-bottom: 1rem;
}

          Wanneer
          Wat
          Waar

          14u00

Zeepkistenrace

Knutsel jouw zeepkist in elkaar en breng ze mee naar de top van de kemmelberg. Inschrijven kan via e-mail naar zeepkisten@burgerfeesten.be

          Kemmelberg

          19u00

Eetwedstrijd

Wie eet het meeste burgers in 30 minuten? Versla jij het record van 16 burgers? Inschrijven kan de dag zelf aan de bonnentjesstand.

          Feesttent marktplein

          20u00

Mister/Miss KemmelBurger

          21u00

Balkan Bonanza

Wie de beentjes al eens wil losgooien kan dit perfect doen op de tonen van Balkan Bonanza. Deze groep uit Loker brengt een verrassende mix van balkan en bluegrass. Benieuwd? Afkomen!

          Podium

          22u00

Bal van de Burger

We feesten door tot in de vroege uurtjes met dicobar Bun & Pickles.

            VVK: € 3 - ADD: € 5

          Podium en feesttent


text:
Q: Call Cypress command only when it is needed For a specific requirement, we need to execute cypress only when it is needed, it is possible that we can expose a rest api, that inside has cypress command, simple like this:
/// <reference types="Cypress" />

import express from 'express';
const router = express.Router();

router.get('/randomURL',(req,res,next) => {
    cy.visit(URL)
    cy.someCustomCommand()
    return res.status(200).send('Test');
});

It's this approach possible? Without calling cypress.run()?


text:
Q: Stuck at AsyncWebsocketConsumer implementation I am trying to develop a consumer (AsyncWebsocketConsumer type) which will be connected with a websocket and make changes to the frontend using JavaScript.
The first thing that I am failing to implement is the consumer's functions (connect, send, disconnect). Also , using Redis.
my settings.py is
ASGI_APPLICATION = "myapp.routing.application"

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            'hosts': [('localhost', 6379)],
        },
    }
}

 and my routing.py is
application = ProtocolTypeRouter({
    "channel": ChannelNameRouter({
        "example": ExampleConsumer,
    }),
})

Last, my consumers.py is
class ExampleConsumer(AsyncWebsocketConsumer):

    async def connect(self,msg):
        # Called on connection.
        # To accept the connection call:
        await self.accept()
        print('Channel connected')

When I tried the :
channel_layer = get_channel_layer()
async_to_sync(channel_layer.send)('example', {'type': 'connect'})

so that I could call the connect and see the connected-message that will let me know that the socket is connected , and then continue by sending a message , I get the :

raise NotImplementedError("You must implement application_send()")
    You must implement application_send()

I am pretty sure that I have misunderstood so many things but I am looking how to solve this problem for a long time and I couldn't find anything useful for my case , like an example or good documentation , so whatever helps will be appreciated!

A: You are using ChannelLayers wrong. They are for communicating between different instances of an application. Not for actual establishing WebSocket connections.
Try this:
settings.py
ASGI_APPLICATION = "myapp.routing.application" # make sure your project is called 'myapp' ;-)

routing.py
application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter([
             path('ws/example/', consumers.ExampleConsumer),
        ])
    ),
})

consumers.py
class ExampleConsumer(AsyncWebsocketConsumer):

    async def connect(self,msg):
        # Called on connection.
        # To accept the connection call:
        await self.accept()
        print('Channel connected')

    async def receive(self, data):
        # do something with data
        print(data)
        # send response back to connected client
        await self.send('We received your message')

You can use a Simple Websocket Client to test your ws-endpoint.

*

*Connect to http://localhost:8000/ws/example/: You should see "Channel connected" on the console, as well as a message that a client connected.

*Send a request with some data. This data should get logged in the console and you will get a response back to your client.

Hope that helps to get you started.


text:
Q: How does NumberQ work I want Log[2 x / Pi] to be expressed as Log[2/Pi] + Log[x]
so I make this replacement
Log[c__?NumberQ x] -> Log[c] + Log[x]

but it doesn't work.
Actually
MatchQ[2/Pi, c_?NumberQ]
>>> false

A: Compare documentation for NumberQ with that for NumericQ
?NumberQ

NumberQ /@ {2, 2., Pi, E}

(* {True, True, False, False} *)

?NumericQ

NumericQ /@ {2, 2., Pi, E}

(* {True, True, True, True} *)

Log[2 x/Pi] /. Log[num_?NumericQ sym_Symbol] :> Log[num] + Log[sym]

(* Log[2/π] + Log[x] *)

Note also use of PowerExpand
Log[2 x/Pi] // PowerExpand

(* Log[2] - Log[π] + Log[x] *)

A: This is another approach -the canonical answer is the one by @Bob Hanlon.
You can use CoefficientList
coeflst =
  Simplify@CoefficientList[FunctionExpand[Log[2 x/Pi]], Log[x]];
Expand[FromDigits[Reverse[coeflst], Log[x]]]


text:
Q: Cause of event id 1309 asp.net 4.0 unhandled exception in asp.net I am working on website, yesterday i faced a problem i.e server got down. i have checked the event log files then i came to know that it was due to "event id 1309 asp.net 4.0 unhandled exception" error. i just restore the back up of the website and restart the website it got worked.
Now my concern is why i got this error: is the criteria i had followed is actual way to recover from this error. i am asking this because might be we will not have latest code back up in future then what will we do? so i am asking to experts

*

*why this errors occurred, what is exact caused for this.?

*Best way to overcome this.

I have read theThis link and came to know this is due to
This problem occurs because the public headers properties of the Request.Headers property and of the Response.Headers property become non-serializable after you install the MS07-040 security update
But i have not used "Request.Headers".. please guide me.


text:
Q: Deriving the normal equation for linear regression I have been looking at different derivations of the normal equation for linear regression. The derivation that I could  follow best (https://www.youtube.com/watch?v=K_EH2abOp00) has some errors, unfortunately. So I tried to do the derivation myself without these errors. I am hung at a single step in the derivation. That step is the "something something" step. Everything seems to fit with the exception that I seem to need a $- 2 X^Ty$ but only have a $- y^TX - X^Ty$. Can you help me spot the error or tell me why the "something something" step is actually correct?
Here is my derivation:
Let $X$ be an $n \times p$ data matrix of $n$ items 'a $p$ features. Let $\hat{\beta}$ be the weight vector that minimizes the residual sum of squares (RSS) of $y - \hat{y}$, where $\hat{y} - X\hat{\beta}$. Hence, To find $\hat{\beta}$, find the minimum of RSS.
\begin{align*}
    \text{RSS} & =  (y - \hat{y})^T (y - \hat{y})\\
               & = (y - X\hat{\beta})^T (y - X\hat{\beta})\\
               & = (y^T - \hat{\beta}^TX^T) (y - X\hat{\beta})\\
               & = y^Ty - y^TX\hat{\beta} - \hat{\beta}^TX^Ty + \hat{\beta}^TX^TX\hat{\beta}
\end{align*}
\begin{align*}
    \frac{\partial ~ \text{RSS}}{\partial \hat{\beta}} & = \frac{\partial y^Ty - y^TX\hat{\beta} - \hat{\beta}^TX^Ty + \hat{\beta}^TX^TX\hat{\beta}}{\partial \hat{\beta}}\\
        & = \frac{\partial y^Ty}{\partial\hat{\beta}} - \frac{\partial \overbrace{y^TX\hat{\beta}}^{Ax}}{\partial\hat{\beta}} - \frac{\partial \overbrace{\hat{\beta}^TX^Ty}^{x^TA}}{\partial\hat{\beta}} + \frac{\partial \overbrace{\hat{\beta}^TX^TX\hat{\beta}}^{x^TAx}}{\partial \hat{\beta}} \\
        & \text{by these rules:} \frac{d~ Ax}{dx} = A, \frac{d~ x^TA}{dx} = A, \frac{d~ x^TAx}{dx} = 2Ax\\
        & = 0 - \underbrace{y^TX}_{A} - \underbrace{X^Ty}_{A} + \underbrace{2X^T X \hat{\beta}}_{2Ax}
\end{align*}
\begin{align*}
    0 & = \frac{\partial ~ \text{RSS}}{\partial \hat{\beta}}\\
        & = - y^TX - X^Ty + 2X^T X \hat{\beta}  \\
        & \text{something something}\\
        & = - 2 X^Ty + 2X^T X \hat{\beta}  \\
        \implies\\
        & X^Ty = X^T X \hat{\beta}  \\
        \implies\\
        &  ( X^T X)^{-1} X^Ty =  \hat{\beta} \\
\end{align*}
Edit:
Ok, so after adjusting for a consistent layout as mentioned in the accepted answer, the derivation is this:
\begin{align*}
    \text{RSS} & =  (y - \hat{y})^T (y - \hat{y})\\
               & = (y - X\hat{\beta})^T (y - X\hat{\beta})\\
               & = (y^T - \hat{\beta}^TX^T) (y - X\hat{\beta})\\
               & = y^Ty - y^TX\hat{\beta} - \hat{\beta}^TX^Ty + \hat{\beta}^TX^TX\hat{\beta}
\end{align*}
\begin{align*}
    \frac{\partial ~ \text{RSS}}{\partial \hat{\beta}} & = \frac{\partial y^Ty - y^TX\hat{\beta} - \hat{\beta}^TX^Ty + \hat{\beta}^TX^TX\hat{\beta}}{\partial \hat{\beta}}\\
        & = \frac{\partial y^Ty}{\partial\hat{\beta}} - \frac{\partial \overbrace{y^TX\hat{\beta}}^{Ax}}{\partial\hat{\beta}} - \frac{\partial \overbrace{\hat{\beta}^TX^Ty}^{x^TA}}{\partial\hat{\beta}} + \frac{\partial \overbrace{\hat{\beta}^TX^TX\hat{\beta}}^{x^TAx}}{\partial \hat{\beta}} \\
        & \text{by these rules:} \frac{d~ Ax}{dx} = A, \frac{d~ x^TA}{dx} = A^T, \frac{d~ x^TAx}{dx} = 2x^TA\\
        & = 0 - \underbrace{y^TX}_{A} - \underbrace{(X^Ty)^T}_{A^T} + \underbrace{2 \hat{\beta}^T X^T X }_{2x^TA}\\
        & = 2 \hat{\beta}^T X^T X - 2 y^TX
\end{align*}
\begin{align*}
    0 & = \frac{\partial ~ \text{RSS}}{\partial \hat{\beta}}\\
        & = 2 \hat{\beta}^T X^T X - 2 y^TX\\
        \implies\\
        & Xy^T = \hat{\beta}^T X^T X  \\
        \implies\\
        & \hat{\beta}^T = Xy^T  (X^T X)^{-1}  \\
        \implies\\
        & \hat{\beta} = (X^T X)^{-1} X^Ty    \\
\end{align*}

A: If you're following a Denominator layout then the issue might be with your first derivative rule, which should have been:
$$
\frac{\partial Ax}{\partial x} = A^T
$$
(see Identities)
This should turn your $y^TX$ into $X^Ty$ and you'd end up with
$$
0 = -2X^Ty + 2X^TX\hat{\beta} \implies (X^TX)^{-1} X^Ty = \hat{\beta}
$$
EDIT:
I've looked at the video and the author seems to be using the Nominator layout, in which case the second derivative rule should have been:
$$
\frac{\partial x^TA}{\partial x} = A^T
$$
which turns $X^Ty$ into $y^TX$ instead.


text:
Q: Work out missing row in MySQL I have a table that will eventually get a row missing through deletion of records.
How could I check for that missing row in that table then fill this missing row in PHP.
I guess its using looping however I just cant work out the correct loop to use
Cheers

A: One way to find a missing item in a sequence is to compare count(*) and max(id).
It should give you an idea of how many are missing, then start including ranges that your checking as in a binary search.
Alternate way is just iterate over the rows ordered by id, and trigger your insert when the sequence jumps.
$lastId = 0;
foreach ($rows as $row)
{
    if ($lastId + 1 != $row['id']) {
        fillInRows($lastId + 1, $row['id'] -1);
    }
    $lastId = $row['id'];
}

function fillInRows($min, $max)
{
   for ($i = $min; $i <= $max; $i++) {
       // exercise left for the reader
   }
}


text:
Q: ModelViewViewModel tasks I'm a noob in mvvm and I am developing my app with this arq, but I don't know how to separate tasks for UI and ViewModel
for example, I have a QR reader with zxing
/**
 * Init scanner
 */
private fun initScanner () {
    scannerView = ZXingScannerView(requireContext())
    scannerView = object : ZXingScannerView(requireContext()) {
        override fun createViewFinderView(context: Context): IViewFinder {
            val customLayout = CodiCustomQRReader(context)
            customLayout.setSquareViewFinder(true)
            customLayout.setBorderColor(ResourcesCompat.getColor(resources, R.color.codi_mango, null))
            return customLayout
        }
    }
    scanner.addView(scannerView)
}

This function is called from onviewCreated in my UI
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    requestPermissions()
    initScanner()
}

this is ok? or I need to call these kind of functions from viewmodel?
same case with function requestPermissions().
PD: same case again with fragment management for example
/**
 * Shows result dialog fragment when QR is read
 */
override fun handleResult(res: Result?) {
    val fragmentTransaction = requireActivity().supportFragmentManager.beginTransaction()

    val prev = requireActivity().supportFragmentManager.findFragmentByTag("scanner")
    if (prev != null) {
        fragmentTransaction.remove(prev)
    }

    fragmentTransaction.addToBackStack("handler")
    val dialogFragment = CodiScannerHandler()
    dialogFragment.setStyle( STYLE_NORMAL, R.style.ScannerDialog )
    dialogFragment.show(fragmentTransaction, "handler")
}

A: you are doing everything quite right you cant write all of this logic in viewmodel because of one simple reason they all are using context and if you dont want something in your view model its context. in future if you have some kind of logic which wont use context for example requesting some info from retrofit client or room or deciding what color text should be based on some boolean you can write them in view model.
I will highly recommend you to read this documentation : https://developer.android.com/topic/libraries/architecture/viewmodel


text:
Q: How to write QueryExpression for following query? I am trying to write a plugin in dynamics crm 4.0. following is my fetch query which working fine. I tested on fetchxml Builder. but when I am trying to convert into QueryExpression it is not returing any result.
<fetch mapping='logical'>
    <entity name='new_involvedperson'>
        <attribute name='new_ageattimeofincident'/>
        <filter type='and'>
            <condition attribute='new_personid' operator='eq' alias='new_InvolvedPersonID' value='{70B1E0F8-9205-E111-9C76-005056A44AF5}'/>
            <condition attribute='new_roletype' operator='eq' value='1'/>
        </filter>
        <link-entity name='new_person' from='new_personid' to='new_personnameid'>
            <attribute name='new_firstname'/>
            <attribute name='new_lastname'/>
            <attribute name='new_dateofbirth'/>
        </link-entity>
    </entity>
</fetch>

I am trying to write following code but it is always return 0 records
ColumnSet cols = new ColumnSet();

// Set the properties of the column set.
cols.Attributes.Add("new_ageattimeofincident");

// Create the condition expression.
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "new_personid";
condition.Operator = ConditionOperator.Equal;
condition.Values = new object[1];
condition.Values[0] = incidentId;

//ConditionExpression condition1 = new ConditionExpression();
//condition1.AttributeName = "new_roletype";
//condition1.Operator = ConditionOperator.Equal;
//condition1.Values = new object[1];
//condition1.Values[0] = roleType;

// Build the filter based on the condition.
FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.Conditions.Add(condition);
//filter.Conditions.Add(condition1);

// Create a LinkEntity to link the owner's information to the account.
LinkEntity link = new LinkEntity();
link.LinkCriteria = filter;
link.LinkToEntityName = "new_person";
link.LinkToAttributeName = "new_personid";
link.LinkFromEntityName = "new_involvedperson";
link.LinkFromAttributeName = "new_personnameid";

// Create the query.
QueryExpression query = new QueryExpression();
query.EntityName = "new_involvedperson";
query.ColumnSet = cols;
query.LinkEntities.Add( link);

// Create the request object.
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieve.ReturnDynamicEntities = true;

// Execute the request.
RetrieveMultipleResponse retrieved2 = (RetrieveMultipleResponse)service.Execute(retrieve);

return retrieved2.BusinessEntityCollection.BusinessEntities;

A: Try it with new AllColumns() and see if that works.  I seem to remember a frustrating issue where if the columns specified do not contain data then no records are returned.

A: Try the following and add your retrieve request code at the end.
    QueryExpression query = new QueryExpression
    {
        EntityName = "new_involvedperson",
        //columns to be included in query
        ColumnSet = new ColumnSet(true),
        Criteria = new FilterExpression(LogicalOperator.And)
        {
            Conditions =
            {
                new ConditionExpression("new_personid", ConditionOperator.Equal, "{70B1E0F8-9205-E111-9C76-005056A44AF5}"),
                new ConditionExpression("new_roletype", ConditionOperator.Equal, 1),
            }
        },
        LinkEntities =
        {
            new LinkEntity()
            {
                LinkFromAttributeName = "new_personid",
                LinkToEntityName = "new_person",
                LinkToAttributeName = "new_personnameid",
            }
        }
    };


text:
Q: Error starting Celery Worker from Parent Folder I'm trying to deploy my Flask project on Heroku, but I'm having problems starting my Celery worker from other directory other than the src.
I've got my Flask project with the following tree:
.project
├── Procfile
├── README.md
├── requirements.txt
└── src
    ├── app.py
    ├── blueprints
    │   ├── __init__.py
    │   ├── error_pages.py
    │   └── profile.py
    ├── static
    │   └── ...
    └── templates
        └── ...

In app.py I have:
from flask import Flask
from celery import Celery
import blueprints

app = Flask(__name__)

# Load the config file
app.config.from_pyfile('config.cfg')

# Initialises celery background tasks handler
celery = Celery(main=app.name, backend=app.config['REDIS_URL'], broker=app.config['REDIS_URL'],
                include=['blueprints.profile'])
celery.conf.update(app.config)
app.celery = celery

If I am at .project/src and I use:
celery -A app.celery worker -l INFO

My worker starts with no problem.
But I cannot figure out how to start my worker from the root, for example.
This is how my Procfile is looking at the moment.
web: gunicorn --chdir ./src app:app
worker: celery -A ??????

Any thoughts?

A: i think you should that code:
celery -A src.app.celery_file worker --loglevel=debug -B

(-B : for Beat) Celery config sample:
from celery import Celery
celery = Celery(__name__)
celery = Celery('tasks', broker=) # rabbit,redis, ..
celery.conf.update({'CELERY_ACCEPT_CONTENT': ['pickle', 'json', 'msgpack', 'yaml']})
celery.conf.add_defaults(...)

celery.conf.update(CELERYBEAT_SCHEDULE={
    'db_connect_things': {
        'task': 'application.lib.tasks.db_connect_things',
        'schedule': crontab(minute=0, hour='*/12'),
    }})

class ContextTask(celery.Task):
...

A: I solved my problem by adding the following __init__.py in my src directory:
import sys
import os

# Adding the 'src' directory to the python path
sys.path.insert(0, os.path.join(os.getcwd(), 'src'))

And then calling the worker using:
celery -A src.app.celery worker -l INFO

Now, this is my Heroku Procfile
web: gunicorn --chdir ./src app:app
worker: celery -A src.app.celery worker


text:
Q: analyzing a circuit I am analyzing a converter and I have a problem in solving one of its operating modes. can you please help me? the simplified circuit is below.consider diode D is conducting, it seems that the voltage across the Lr is constant, I can not figure out why.. i thought it is two resonant circuit but it is apparently not, i just want to analyze this operation mode that the switch S1 is conducting and S2 is off; do not consider other modes
P.S. the initial conditions: v(Cs)=0, i(Lr)=2Iin, i(Ls)=I0, V(cr)=V1

A: For reference, here is your circuit:

This is a mess.  You say this is a "converter", but it's not clear what it's supposed to convert to what.  If it's meant to be a switching DC to DC converter, then it should be immediately obvious the switch is missing.
Another glaringly obvious problem is that Iin is shorted.  The voltage going into this circuit (between left end of Ls and bottom of Cs) is always 0 by definition, and the current source is completely irrelevant.
These two problems really should have been obvious.  It borders on rude to ask others to help with a circuit or schematic this messed up.
Trying to analyze this further is pointless since it doesn't make any sense as is, and the schematic is probably not depicting the real circuit anyway.


text:
Q: Android Collaborate Git with google play services maps I have a problem.
We are a students group, who are developing a Android Project. We use Eclipse and git (bitbucket) to share project in three different computers.
Our project uses google maps, and we had to get a key to use google maps.
We don't know how we can share this project by git (between ourselves). Do we need new key?
Does anyone have an example of this problem?
Does anyone know a guide?
Thanks.

A: Yeah, We face the same problem too.
Maybe "use the same keystore which generates the map-api-key for all the team members while building apk" is a workaround.


text:
Q: ElasticSearch filter on array of terms is filtering out all terms In my application, users belong to a list of roles and objects have a list of roles associated with them to determine visibility.  I'm trying to create a query that ensures the user belongs to at least one of the groups that is required by the object.
Here is my index configuration:
{
    "settings": {
        "analysis": {
            "filter": {
                "nGram_filter": {
                    "type": "nGram",
                    "min_gram": 2,
                    "max_gram": 12,
                    "token_chars": []
                }
            },
            "analyzer": {
                "nGram_analyzer": {
                    "type": "custom",
                    "tokenizer": "whitespace",
                    "filter": [
                        "lowercase",
                        "asciifolding",
                        "nGram_filter"
                    ]
                },
                "whitespace_analyzer": {
                    "type": "custom",
                    "tokenizer": "whitespace",
                    "filter": [
                        "lowercase",
                        "asciifolding"
                    ]
                }
            }
        }
   },
    "mappings": {
        "team" : {
            "dynamic": "strict",
            "properties" : {
                "id": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "object": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "roles": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "name": {
                    "type": "string",
                    "index_analyzer": "nGram_analyzer",
                    "search_analyzer": "whitespace_analyzer"
                },
                "text": {
                    "type": "string",
                    "index_analyzer": "nGram_analyzer",
                    "search_analyzer": "whitespace_analyzer"
                }
            }
        }
    }
}

Here is some sample data that I have indexed:
(verified via localhost:9200/index/_search?q=name:employee_1&pretty)
{
    "id":"lsJ17K4sgQVfd",
    "roles: ["OwnerslsJ17K21px6VX","AdminslsJ17K21px6VX"],
    "object":"contact",
    "name":"employee_1",
    "text":"lsJ17K4sgQVfd employee_1 employee_1 employee_1@lsj17k1nysk75.com"
}

Here is my query that I am trying to execute to find that same contact:
{
    "_source": ["id", "object", "name"],
    "size": 30,
    "query": {
        "filtered": {
            "query": {
                "bool": {
                    "should": {
                        "multi_match": {
                            "query": "employee_1",
                            "type": "cross_fields",
                            "operator": "or",
                            "fields": ["name^2", "text"],
                            "minimum_should_match": "50%",
                            "fuzziness": "AUTO"
                        }
                    },
                    ...,
                    "minimum_should_match": 1
                }
            },
            "filter": {
                "terms": {
                    "roles": [ "AdminslsJ17K21px6VX", "lsJ17K3gHCH4P" ]
                }
            }
        }
    },
    "suggest": {
        "text": "employee_1",
        "text_suggestion": {
            "term": {
                "size": 3,
                "field": "name",
                "sort": "score",
                "suggest_mode": "missing",
                "prefix_length": 1
            }
        }
    }
}

If I remove the filter clause then I get results, but as soon as I add it back everything gets filtered out again.  What is the right way to express that I want the results to have at least one role in common?

A: The query above works as expected, the only problem was that my test case was executing before the index was fully populated.  Adding a short wait time before making my first query solved the problem.


text:
Q: A simple inequality about products Let $a_i$ and $b_i$, $i=1,\ldots,n$, be two finite sequences of numbers in $(0,1)$. We know that $a_i < b_i$ for all $i$. Is it then true that $a_1\cdots a_n < b_1\cdots b_n$?
If all the $a_i$ were the same, and all the $b_i$ were the same, this would be rather obvious since the functions $x^n$ for positive $n$ are known to be increasing on $(0,1)$. So in this special case, it works. But I'm not sure how to generalize this result.

A: If $x>y>0$ and $u>v>0$, then we always have $xu>xv$ and $xv>yv$, so that $xu>yv$.

A: $a_1\cdots a_n<a_1\cdots a_{n-1}b_n<\cdots < a_1\cdots a_{k-1}b_k\cdots b_n<\cdots <a_1b_2\cdots b_n<b_1\cdots b_n$.


text:
Q: set/getCorrelationIdString not working It was surprising to me Set/getCorrelationIdString is not workng for me. It is
amqp-client 3.6.5 and other spring-rabbit/amqp 1.6.6.Anybody else faced it ?  I am surviving with Set/getCorrelationId which works but shows as depreciated. Any solution for this.

A: That's because the DefaultMessagePropertiesConverter has default strategy as:
private volatile CorrelationIdPolicy correlationIdPolicy = CorrelationIdPolicy.BYTES;

For backward compatibility.
If you wish to use Set/getCorrelationIdString, you should inject DefaultMessagePropertiesConverter into RabbitTemplate and SimpleMessageListenerContainer with the CorrelationIdPolicy.STRING.


text:
Q: Regex to match url directory path without match file name I want a regex that will match
https://example.com/studio/ or https://example.com/studio without matching https://example.com/studio/path-to-file-blah-blah or https://example.com/studio/path-to-file-blah-blah.html
I tries https?:\/\/(?:w{3}[.])?example[.]com\/studio\S* but it's matching both groups above.
I have also tried https?:\/\/(?:w{3}[.])?example[.]com\/studio\/? and it was able to match only the first group. But the problem is matching only the second group. Please how can I do that?

A: I'm assuming you need to parse the URL from unstructured text. Assuming there's a space character, new line character, or the end of the string the following should work for you. If there's a period or other character directly after the URL this will fail, but it's easy to modify to support additional terminating characters.
https?:\/\/(?:w{3}[.])?example[.]com\/studio\/?(?:\s|$)

(?:\s|$)  Just says match a space character (which includes line endings line a new line character) OR match the end of the string.
Regex Demo
EDIT
I think you're saying group 2 is:
https://example.com/studio/path-to-file-blah-blah
https://example.com/studio/path-to-file-blah-blah.html

To match these, you'll need the following regex:
https?:\/\/(?:w{3}[.])?example[.]com\/studio\/\S+

The only change I made was the last character was \S*, but it should be \S+.
* means 0 or more
+ means 1 or more.
Hopefully this touches on what you're looking for. If I'm still off, if you label the groups it'd help me understand so I can write the correct regex.

A: Further expanding on Nathan's answer, you can change the end of the RegEx to not capture the trailing space or new line. This will match the first two cases:
https?:\/\/(?:w{3}[.])?example[.]com\/studio\/?(?=\s|$)

To match only the second case, use this:
https?:\/\/(?:w{3}[.])?example[.]com\/studio(?=[^\/])


text:
Q: Import error "undefined symbol: _ZNK9FastNoise8GetNoiseEff" when calling C++ extension in Python 3.6 I am currently trying to make some C++ extensions for a python script. In the C++ side of the story, it seems to be compiled just fine and it generates my .so shared library, but when I call it inside my python script it raises an error of undefined symbol. The current code is as follow:
#include <iostream>
#include "FastNoise.h"
#include <string>
#include <time.h>

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>

#include <boost/python/def.hpp>
#include <boost/python/module.hpp>

using namespace std;
using namespace cv;
namespace bp = boost::python;

int gen(int _size)
{
    FastNoise myNoise;
    myNoise.SetNoiseType(FastNoise::Simplex);
    myNoise.SetSeed((int)(rand() * time(NULL)));

    Size img_size(_size, _size);
    Mat noise_map(img_size, CV_32FC3);

    for (int y = 0; y < _size; y++) {
        for (int x = 0; x < _size; x++) {
            Vec3f &color = noise_map.at<Vec3f>(Point(x, y));
            color.val[0] = (myNoise.GetNoise(x, y) + 1) / 2;
            color.val[1] = (myNoise.GetNoise(x, y) + 1) / 2;
            color.val[2] = (myNoise.GetNoise(x, y) + 1) / 2;
        }
    }

    imshow("test", noise_map);
    waitKey(0);
    return 0;
}

BOOST_PYTHON_MODULE(gen) {
    bp::def("gen", gen);
}

And here is how I compiled it:
g++ main.cpp -I/opt/opencv/include/opencv -I/usr/include/python3.6m -I/usr/local/include/boost -L/opt/opencv/release/lib -L/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lpython3.6m -lboost_python36 -o NoiseModule.so -shared -fPI

When I import it within python it gives me this error:
>>> import NoiseModule
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: /home/matheus/PycharmProjects/TerrainGenerator/NoiseGenerator/NoiseModule.so: undefined symbol: _ZNK9FastNoise8GetNoiseEff
>>>

Any kind of help in regards of this problem will be really appreciated.

A: Your shared object doesn't have access to every function you use. You probably have a file like FastNoise.cpp which implements your FastNoise object. Yet you only use main.cpp to compile your dynamic library (.so) file. So make sure all .cpp files are included in the build of your python c++ extension.
Another option might be to make to implement your FastNoise object entirely inside of the header.


text:
Q: WPF: Datagrid validation not on a row level but on a collection level I have a datagrid which implements some validation rules. If these latters return that the row is not valid, the row is marked as erroneous (red icon in the row header). Basic stuff.
Now, I would like to implement a validation rule but on the whole collection. For instance, I have a column which displays each source collection item's name and I want this name to be unique throughout the whole collection. When three rows show a shared named, I'd like them all to display the red error icon in the row header.
I thought about raising an event in my model's class whenever this name property is modified, then listen to this event from the view model but it feels wrong coding that. And I don't know whether I can achieve the result (mark rows as erroneous) or not.
Is there a better way?

A: Ok, here's what I ended up doing, please let me know if this is dirty, bad practice etc.
public class MyModel : IDataErrorInfo
{
    #region Fields

    readonly ObservableCollection<MyModel> _parentCollection;

    #endregion

    #region Properties

    public string Name { get; set; }

    #endregion

    #region Validation
    string _error;
    public string Error => _error;
    public string this[string columnName]
    {
        get
        {
            List<string> foundErrors = new List<string>();
            if (string.IsNullOrWhiteSpace(columnName) ||
                (columnName == nameof(Name) &&
                 _parentCollection.Count(ed => ed.Name == Name) > 1))
            {
                foundErrors.Add("Name already used"));
            }
            _error = string.Join(Environment.NewLine, foundErrors);
            return _error;
        }
    }

    #endregion

    #region Constructor

    public EvaluationDay(ObservableCollection<MyModel> parentCollection)
        : base()
    {
        _parentCollection = parentCollection;
    }

    #endregion

    }
}

And then, in my ViewModel, whenever I am adding a MyModel object to the observable collection binded to the view, I make sure to send this OC reference to the object as parameter for the constructor:
public class MyViewModel
{
    #region Properties

    public ObservableCollection<MyModel> MyModels { get; set; }

    #endregion

    ...

    int elementsToAddCount = 10;
    for (int i = 0; i < elementsToAddCount; i++)
    {
        MyModels.Add(new MyModel(MyModels));
    }

    ...

This being said, you can also simply add a parameter to the validation rule...


text:
Q: What is Attack Move for? Attack Move is a key bind that I came across in the key binding list.  From my own testing it seems to move to the target location and attack the nearest target-able object including turrets.
I heard people talking about it in IRC chats and during the casting of Tourney Games.  Most pertaining to AD-carries, in particular that Doubleliftt uses it which is the reason he is so fluid.  I was just wondering what exactly it is good for and how I could use it to improve my damage out-put as an AD Carry?
If anyone could create a little video tutorial showing instances in how you use this it would be great.  It is hard to understand when explained in words how to kite using it for instance.  To someone who has never used it before.

A: Lots of excellent answers already.  I will add my favorite reason reason to attack move:
Clearing out wards / mushrooms
If I've purchased an Oracle's Elixir, attack-move helps to ensure that I don't inadvertently pass by any enemy wards or mushrooms without destroying them.

A: Going along with what Toast said, Attack-move (a-click) is a mechanic popularized by Starcraft and Warcraft. A-move would allow units to automatically attack all enemies along the way.
Saving Milliseconds
The main advantage to A-moving is that you don't have to move your mouse. The milliseconds it takes to recognize a target and physically move the mouse above it makes a noticeable difference in professional play. Just let the keyboard hand and computer handle it.

For example,

*

*My champion is in the lower-left corner of the screen

*Enemy champion is in the middle of the screen

*My mouse is in the top-right corner of the screen

And my champion, the enemy champion and my mouse make a straight line. So now I have two choices,
Right-click on the enemy: I need to move my mouse down to the middle of the screen and click within the hit-box of the enemy, about 50 square pixels out of the whole screen. If I miss the hit-box slightly, my champion walks helplessly towards the enemy.
Attack-move: I hit "A" on the keyboard and then I left click where my cursor already was. I didn't have to drag my mouse anywhere. I didn't have to aim my cursor. I saved several milliseconds.

A-moving is especially useful when you are kiting because, by shaving off those milliseconds of mouse movement, you can use a champions attack speed to its full potential while moving.
It's useful in general when you have a good position on your enemy and don't have to retarget it every time,
It's similar to why you would use QWER to cast spells instead of clicking the icons each time.

Doublelift and many other pros may have previously played DOTA, Warcraft or Starcraft where APM optimization is the norm and developed a habit of A-moving.

A: Clarification of the term "click to attack"
There are two key bindings related to attack:

*

*Attack move - default button A - when you click A cursor changes into target pick. Clicking left mouse button then makes your character either attack the picked target or run to the picked location and attack the first target that appears in your range during the movement. If there are more targets, it picks the closest one.

*Attack move click - default Shift + Right mouse button - it is a shortcut for Attack move
Advantages of using "click to attack"

*

*When you chase into a brush you start attacking immediately when you see the target

*When you missclick right button when lasthitting then you go in the creeps and get yourself out of position, that can never happen while using Attack move

*When lasthitting, Attack move checks for a target in a slightly larger radius than right click, which makes it easier to pick the target. It also might be an advantage in larger crowds of creeps when you need to select a creep precisely.

Disadvantages

*

*When using Attack move during chasing and clicking it on the ground, then if a different eligible target appears closer, you immediately start attacking it. Therefore, you obviously lose some time and even if it is miliseconds it may change the outcome of the chase.

A: Click to attack or move to attack can be enormously valuable.
I find it most valuable in:
1) Kiting
RClick away from an enemy, then attack move away from them to automatically attack.
Continue this process to run while auto attacking them.
This same process can be done to neutral monsters and even turrets/inhibs.
2) Last hitting
Use the A key as opposed to right clicking on a minion to kill them. This ensures that even if your click misses the minion, you will still auto attack it.
3) Chasing an Enemy into a brush
Attack moving into a brush will ensure you immediately attack them upon gaining vision (As opposed to RClicking them first)
You'll find that attack moving can often shave valuable time off your attacks. It ensures you're getting maximum output of damage and removes the time wasted by human response in clicking on the target manually.  It takes a lot of practice to learn when to use it and when to right click. Particularly when the target you wish to hit is not closest to you. I'd highly recommended practicing this as an AD carry.


text:
Q: How do i Maven fetch dependency version in shell script I have one project artifact version say
apple-0.0.1

In another project mango i have dependency to apple, which i have added in pom.
In mango there is one shell script.
Which needs to refer to
apple-{apple.version}

How can i dynamically populate this value in shell script by reading the pom during package time on mango project?
Thanks in advance.


text:
Q: Laravel different Middleware I have a question regarding Middlewares.
So right now I created 3 Middlewares called Admin, Office and User.
This is the CustomerController:
class CustomerController extends Controller
{

public function getAllCustomer()
{
    return Customer::get();
}

public function addNewCustomer(Request $request)
{
    $validatedData = $request->validate([
        'Title' => 'required',
        'Name' => 'required|max:255',
        'Surname' => 'required|max:255',
        'Email' => 'required',
        'Phone' => 'required',
        'Password' => 'required',
        'dateofBirth' => 'required'
    ]);

    return \app\model\Customer::create($request->all());
}

public function update (Request $request , Customer $id)
{
    $id->update($request->all());
}

public function destroy (Customer $id)
{
    $id->delete();
}

The Customer is able to read, create, update and to delete.
But right now I want to use a Middleware, so that only the admin is able to create/read/update/delete all the data, the user and is only able to to this with his own data.
So right now I have 3 Middleware classes and I added this to the Kernel.php:
'admin' => 'App\Http\Middleware\AdminAuthentification::class',
 'office' => 'App\Http\Middleware\OfficeAuthentification::class',
 'user' => 'App\Http\Middleware\UserAuthentification::class'

My question is:
What do I Need to add in the Middleware to add the fuction I described?
Thank you very much for you help!

A: Actually this is a very ugly way of doing things but anyhow... You should checkout gates/policies or something like spatie/laravel.

namespace App\Http\Middleware;
use Closure;

class UserAuthentification {

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    if(check user type){
       //allowed
    }
    else{
        //forbidden
        //you can abort
        abort(403);

    }

    $response = $next($request);

    return $response;
}

}


text:
Q: Consuming an iterator in a while loop I have a function foo() that empties out a queue of items, N.B., not a Queue(), just a list of items. The function returns False if the list is empty. Is there a disadvantage to using a while loop to repeatedly call this function? Simply pass in the loop body seems a bit off. Ex:
while foo():
    pass

A: This form may be easier to understand:
while items:
    foo()

A: all(foo()) will consume items from an iterator until it receives a falsey value (or until the iterator is exhausted).


text:
Q: Unique Filter to Elastic Search Column not working (duplicate items inserted) I've modified my contactNumber field to have a unique filter
by updating the index settings as follows
curl -XPUT localhost:9200/test-index2/_settings -d '
{
     "index":{
        "analysis":{
           "analyzer":{
              "unique_keyword_analyzer":{
         "only_on_same_position":"true",
                 "filter":"unique"
              }
           }
        }
  },
  "mappings":{
     "business":{
        "properties":{
           "contactNumber":{
              "analyzer":"unique_keyword_analyzer",
              "type":"string"
           }
        }
     }
  }
}'

A sample Item looks like this,
doc_type:"Business"

contactNumber:"(+12)415-3499"
name:"Sam's Pizza"
address:"Somewhere on earth"

The Filter does not work, as duplicate items are inserted, I'd like NO two documents having the same contactNumber
in the above, I've also set only_on_same_position -> true so that existing duplicate values would be truncated/deleted
What am i doing wrong in the settings?

A: That's something Elasticsearch couldn't help you out of the box... you need to make this uniqueness functionality available in your app. The only idea that I can think of is to have the phone number as the _id of the document itself and whenever you insert/update something ES will use the contactNumber as _id and it will associate that document with the one that already exists or create a new one.
For example:
PUT /test-index2
{
  "mappings": {
    "business": {
      "_id": {
        "path": "contactNumber"
      },
      "properties": {
        "contactNumber": {
          "type": "string",
          "analyzer": "keyword"
        },
        "address": {
          "type": "string"
        }
      }
    }
  }
}

Then you index something:
POST /test-index2/business
{
  "contactNumber": "(+12)415-3499",
  "address": "whatever 123"
}

Getting it back:
GET /test-index2/business/_search
{
  "query": {
    "match_all": {}
  }
}

It looks like this:
   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "test-index2",
            "_type": "business",
            "_id": "(+12)415-3499",
            "_score": 1,
            "_source": {
               "contactNumber": "(+12)415-3499",
               "address": "whatever 123"
            }
         }
      ]
   }

You see there that the _id of the document is the phone number itself. If you want to change or insert another document (the address is different, there is a new field - whatever_field - but the contactNumber is the same):
POST /test-index2/business
{
  "contactNumber": "(+12)415-3499",
  "address": "whatever 123 456",
  "whatever_field": "whatever value"
}

Elasticserach "updates" the existing document and responds back with:
{
   "_index": "test-index2",
   "_type": "business",
   "_id": "(+12)415-3499",
   "_version": 2,
   "created": false
}

created is false, this means the document has been updated, not created. _version is 2 which again says that the document has been updated. And the _id is the phone number itself which indicate this is the document that has been updated.
Looking again in the index, ES stores this:
  "hits": [
     {
        "_index": "test-index2",
        "_type": "business",
        "_id": "(+12)415-3499",
        "_score": 1,
        "_source": {
           "contactNumber": "(+12)415-3499",
           "address": "whatever 123 456",
           "whatever_field": "whatever value"
        }
     }
  ]

So, the new field is there, the address has changed, the contactNumber and _id are exactly the same.


text:
Q: Jquery Validation Plugin Method required( dependency-expression ) use ok but callback not working i'm trying to make this work;
this validate is applied to a payment form, and as you can see, there are only 3 requierd inputs, if and only if
input[type=radio]:checked').val() != "CB";

wich means if user is about to pay with something else than a credit card.
Following is the complete code to validate my form.
$("#paiement").validate({
        errorClass: "invalid",
        validClass: "success",
        rules: {
            referenceTypeComplementBancaire: true,
            banque: {
                required: function(nomBanque){
                    return $('#paiement input[type=radio]:checked').val() != "CB";
                }
            },
            numeroComplementBancaire: {
                required: function(numeroCompl){
                    return $('#paiement input[type=radio]:checked').val() != "CB";
                }
            },
            montantComplementBancaire: {
                required: function(montantCompl){
                    var logg = montantRentre >= panierTotal;
                    console.log(logg);
                    return montantRentre >= panierTotal;
                }
            }
        },
        messages: {
         referenceTypeComplementBancaire: "",
         banque:"",
         numeroComplementBancaire:"",
         montantComplementBancaire:""
        }
    });
}

Nothing hard, really.
But, whats hard for me to understand is why montantComplementBancaire isn't validated, even if my console logging shows me 'true' or 'false' in the right time.
What a m I doing wrong ?
----------------------------EDIT------------------------------------------
I think there's been some kind of misunderstanding, my fault. Sorry folks.
Here's how the form finally looks like:
        $("#paiement").validate({
        errorClass: "invalid",
        validClass: "success",
        rules: {
            referenceTypeComplementBancaire: true,
            banque: {
                required: function(nomBanque){
                    return $('#paiement input[type=radio]:checked').val() != "CB";
                }
            },
            numeroComplementBancaire: {
                required: function(numeroCompl){
                    return $('#paiement input[type=radio]:checked').val() != "CB";
                }
            },
            montantComplementBancaire: {
                required: function(){
                    var logg = panierTotal > montantRentre;
                    console.log(logg);
                    return panierTotal > montantRentre;
                }
            }
        },
        messages: {
         referenceTypeComplementBancaire: "",
         banque:"",
         numeroComplementBancaire:"",
         montantComplementBancaire:""
        }
    });

Where did I go wrong ? Not only do I want "montantComplementBancaire" to be validated, but I want it to be valid IF and ONLY IF its >= to panierTotal
Right now, I'm only testing wether or not to validate it, but what I'm looking for is a way to return 'valid' when montantRentre >= to panierTotal .
Am I making tjis any clearer ?

A: try return logg;
or return (montantRentre >= panierTotal);
Your code looks ok and seems to match the example here (http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-callback).  The required property doesn't need to be an object with a depends property, it can be a dependency-callback function like you have done.
You could also try
if(montantRentre >= panierTotal) {
  return true;
} else {
  return false;
}

A: I don't think your validation is setup properly. The "required" property of each form element should be a JavaScript Object with the "depends" property set to a function, presuming what you're trying to do is conditional requirements. See the "rules" entry on the validation options page: http://docs.jquery.com/Plugins/Validation/validate#toptions
I think the fixed code would be:
$("#paiement").validate({
    errorClass: "invalid",
    validClass: "success",
    rules: {
            referenceTypeComplementBancaire: 'required',
            banque: {
                    required: {
                        depends: function(nomBanque){
                            return $('#paiement input[type=radio]:checked').val() != "CB";
                        }
                    }
            },
            numeroComplementBancaire: {
                    required: {
                        depends: function(numeroCompl){
                            return $('#paiement input[type=radio]:checked').val() != "CB";
                        }
                    }
            },
            montantComplementBancaire: {
                    required: {
                        depends: function(montantCompl){
                            var logg = montantRentre >= panierTotal;
                            console.log(logg);
                            return montantRentre >= panierTotal;
                        }
                    }
            }
    },
    messages: {
     referenceTypeComplementBancaire: "",
     banque:"",
     numeroComplementBancaire:"",
     montantComplementBancaire:""
    }
    });
}

A: required: function(montantCompl){
    var logg = montantRentre >= panierTotal;
    console.log(logg);
    return montantRentre >= panierTotal;
}

why do you define an argument function(montantCompl){ that you never use? Did you mean to actually make your comparison against that? Even if you didn't, it is not really a good idea to use global variables for comparison inside anonymous functions as it leads to ambiguity, like right now when I'm trying to help you out with your issue. If these values are defined somewhere, please includ them in your question including any points where they change state.


text:
Q: django inplaceedit testing project New to django… Since a month i'm trying to follow this tutorial without success. When i syncdb i get following error:
(virt-inplaceedit)Mac:testing manuelstrasser$ python manage.py syncdb
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
    django.setup()
  File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/apps/config.py", line 123, in create
    import_module(entry)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/sorl/thumbnail/__init__.py", line 1, in <module>
    from sorl.thumbnail.fields import ImageField
  File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/sorl/thumbnail/fields.py", line 6, in <module>
    from sorl.thumbnail import default
  File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/sorl/thumbnail/default.py", line 3, in <module>
    from sorl.thumbnail.helpers import get_module_class
  File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/sorl/thumbnail/helpers.py", line 5, in <module>
    from django.utils import simplejson
ImportError: cannot import name simplejson

I installed simplejson but still same error. Anyone haveing experiences with this tutorial? I did everything exactly as per description…

A: django.utils.simplejson is deprecated in django 1.7.
Looks like you use old version of the sorl-thumbnail.  Current version of sorl-thumbnail supports django 1.7 so try to update this library.


text:
Q: $PlayOutMode:0 does not work? I have set the "$PlayOutMode" to "0", which, as I understand from the docs, should prevent a caption playout animation.
However, the caption playout is still animated...
What am I doing wrong?

A: Thanks for the question!
I have just fixed the bug.
Please download the latest version.


text:
Q: Safe to merge branch that other branch is branched from to trunk? We have a standard layout with
tags
branches
trunk

But no code is present in trunk. Trunk has never been used. Instead all work has been done in a branch and once that branch has been considered done a new branch has been created. From now on all releasable code will reside in trunk since that is how every other project we have is set up and that is how we have TeamCity fetch and build all the latest releasable projects when building an install package.
Under branches there exist a 1.0 branch and a foo branch that is branched from the 1.0 branch.
branches
 |- 1.0
     |- foo

foo is currently being developed on and 1.0 contains the latest released code. My idea was to merge 1.0 with trunk and then, when foo is done, merge that with trunk. Would that pose any issues since it's based on 1.0, which trunk will also be, and trunk might contain other changes not present in foo?
Also, at what point would it be considered safe to delete the 1.0 branch? Straight after 1.0 has been merged to trunk or after foo has also been merged?

A: *

*You have to fix your workflow and mind - they are broken

*

*If you created trunk's HEAD from some ancestor of foo, trunk can't contain (later) changes, which doesn't exist in foo (if all development happens in foo).

*You try to use 1.0/foo as trunk and trunk as tag

*You can delete svn rm obsoleted branch (1.0) only when foo will be also obsoleted - Subversion repository is path-based - you can't remove 1.0 but leave foo intact


text:
Q: jquery bootstrap selectpicker refreshing lists based upon previous list choice I have three drop down lists, one list is populated on page load and doesn't change.  The 2nd and 3rd lists may change depending on the selection.  This functionality is working fine.
I have tried to add Bootstrap selectpicker to the selectors and I can see it is working - unfortunately the lists are not refreshing based upon the selection.  I actually think "behind the scenes" they are as I can see the queries being passed but via the front end nothing happens.
Part of the HTML:
<!-- SelectPicker -->
<link href='//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/css/bootstrap-select.min.css' rel='stylesheet' type='text/css'>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>

The first two DDL's are created via php but are
<select id='ddl_first_lookup' onchange='ajaxFirstOnChange(this.value)' value='' class='selectpicker'></option>
<select id='ddl_second_lookup' onchange='ajaxSecondOnChange(this.value)' class='selectpicker'>
<select id="ddl_third_lookup" onchange='ajaxThirdLookup(this.value)' class='selectpicker'></select>

I have the following Javascript:
$(document).ready(function() {
  $(".selectpicker").selectpicker();
});

This is the point where I have discovered the problem, I am trying to implement this within the ajax on change functions without success - not even sure if it is correct.
$('.selectpicker').selectpicker('refresh');

I am pretty new to all of this so would like some help.

A: I found your question after having the same problem. Adding $('.selectpicker').selectpicker('refresh'); exactly after adding items to my list did the job.
So you probably need to find the correct place to put it. Maybe in the success part of your ajax call.

A: What I understood from my experience with this so far -
If you are adding dynamically options to the dropdown then you must need to call below function just before adding option
$(".selectpicker").selectpicker();

Once you completed adding options then call below function (if you are using ajax to add option then put this function into success part as just answered Athina)
$('.selectpicker').selectpicker('refresh');

If you are facing any weird issue like showing dropdown not data or sometime dropdown not showing properly then definitely you must have made mistake in placing about function and nothing else.

A: if refresh method doesn't help, try adding some delay.
    setTimeout(() => {
      jQuery('.selectpicker').selectpicker('refresh');
    }, 500);

A: In my Ajax successCallBack I am trying to manipulate drop down list having id as reasonCode based on dynamicId (value get from server)  as below:
$('#reasonCode option[value='+dynamicId+']').prop('selected', true);

but unfortunately this had not worked until I added another line after this as below:
$('#reasonCode').selectpicker('refresh');

A: Changing selectpicker class name when hidden:
<select name="key" class="selectpicker_oncreate">

When refreshing:
$('.selectpicker_oncreate').selectpicker('refresh');

A: I've added destroy before refresh, thats solved my issue.
// ... option:selected manipulation
$('.selectpicker').selectpicker('destroy');
$('.selectpicker').selectpicker('refresh');


text:
Q: TreeView (TreeItem) - get hierarchy index possible? I have a TreeView that looks like this:
-Parent1
- - Child1
- - Child2
- - - Subchild1
-Parent2
- - Child99

Is there a method or a simple way to get the hierarchical index of a TreeItem in the tree?
For example:
Parent1 would have a hierarchical index of 0.
Child1 would have a hierarchical index of 1.
Subchild1 would have a hierarchical index of 2.
Parent2 would have a hierarchical index of 0.
Child99 would have a hierarchical index of 1.

A: The only thing that gets on mind is using Java Reflect API, getSuperclass() method, as Java doc says: http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/class/getSuperclass.html
Please see the following Example:
public class Subclass{

    public static void main(String[] args) {
        Map map = new HashMap();
        Map map2 = new HashMap();
        printSuperclasses(map);
        printSuperclasses(map2);
}

    static void printSuperclasses(Object o) {
        Class subclass = o.getClass();
        Class superclass = subclass.getSuperclass();
        int i=0;
        while (superclass != null) {
           String className = superclass.getName();
           i++;
           System.out.println(className+" "+i);
           subclass = superclass;
           superclass = subclass.getSuperclass();
        }
     }
}

The output provided by this example is:
java.util.AbstractMap 1
java.lang.Object 2
java.util.AbstractMap 1
java.lang.Object 2
That means that in hierarchy the parent of Map object is AbstractMap(index 1), and the parent of AbstractMap is Object (index 2).


text:
Q: How to give Circle CI SSH access to my server? I have some questions and issues with my CI and CD solution.
Rails: 4.2
Capistrano: 3.4.0
The application is hosted on a private server.
Right now I have the workflow working with deploying development, staging and production via the terminal.
I also hooked up Circle CI working good on these branches.
I cannot find how to setup Circle CI to use Capistrano to deploy.
Everything is configured with the server user in the Capistrano config.
How do I give Circle CI SSH access to my deploy user? Because now I have to provide a password for the user.

A: Use SSH keys for authentication. You might as well use it for your own SSH sessions too, because it's more convenient and secure (a rare occasion!) than password authentication. Check out this tutorial on how to set it up.
Then, paste your private key to CircleCI in Project Settings -> SSH Permissions, as described here. You'd need to copy the private key from your local machine from the key pair whose public key you added to the deploy user on the server. CircleCI then will have SSH access to your server.
You can set the hostname to the domain that points to your server or your server's IP, or leave it blank so this key would be used in all hosts.

A: CircleCI Version 2 Build and Deploy with Workflows
Let's presume the following very basic PHP application. Apache config points to /web. Files and folders ending with * are ignored by Git.
__repo
  |__.circleci
  |  |__config.yml
  |__.git
  |__tests
  |  |__features
  |  |__behat.yml
  |__scripts
  |  |__deploy.sh
  |__web
  |  |__node_modules*
  |  |__index.php
  |  |__styles.scss
  |  |__gulpfile.js
  |  |__styles.css*
  |__.gitignore

*

*On the server create a new user and add it to the www-data group. Make it own the whole repo recursively. Let's presume this user is called repo-boss.
$ chown -R repo-boss:www-data repo/

*On your local machine create a new SSH key pair. Add the private key to CircleCI's back-end and have a look at resulting fingerprint we'll need later. Add the public key to /home/repo-boss/.ssh/authorized_keys.

Now let's presume the deploy.sh script holds the following very basic commands.
#!/usr/bin/env bash

# Set script to exit on errors.
set -e

# Get script's absolute location.
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Change to repo root.
cd ${DIR};
cd ..

# Git pull.
git status
git pull

# Run Gulp.
cd web/
gulp sass

And now comes CircleCI's config.yml that makes that whole thing work (after you at least once pulled the necessary stuff onto the server, of course). deploy will only run when the tests finished successfully.
version: 2
jobs:
  build:
    docker:
      - image: circleci/php:7.1-apache-node-browsers

    working_directory: ~/repo-name

    steps:
      - checkout

      - run:
          name: Whatever you need to get your app up and running.
          command: |
            command1 # Have a look at https://github.com/leymannx/drupal-circleci-behat/blob/develop/.circleci/config.yml for a more detailed example.
            command3
            command4

      - run:
          name: Run Tests.
          command: |
            behat --no-snippets -f pretty -o std

  deploy:
    machine:
      enabled: true
    working_directory: ~/repo-name
    steps:
      - checkout
      - run:
          name: Fix ssh Could not resolve hostname
          command: |
            ssh-keyscan 123.45.67.89 >> ~/.ssh/known_hosts # Add live server IP to known hosts.
            ssh-keyscan 555.45.67.89 >> ~/.ssh/known_hosts # Dev server, too.

      - add_ssh_keys: # add private SSH key from CircleCI account based on fingerprint.
          fingerprints:
            - "14:09:a1:b2:b3:c4:d5:e6:f7:g8:h9:81:"

      - run:
          name: Deploy master.
          command: if [ "${CIRCLE_BRANCH}" == "master" ]; then ssh repo-boss@123.45.67.89 'cd /var/www/repo/scripts && . deploy.sh'; else echo "Skipped"; fi
      - run:
          name: Deploy develop.
          command: if [ "${CIRCLE_BRANCH}" == "develop" ]; then ssh repo-boss@555.45.67.89 'cd /var/www/repo/scripts && . deploy.sh'; else echo "Skipped"; fi

workflows:
  version: 2
  build-and-deploy:
    jobs:
      - build:
          filters:
            branches:
              only:
                - develop
                - master
      - deploy:
          requires:
            - build
          filters:
            branches:
              only:
                - develop
                - master

Of course, you don't need to use workflows. You also can achieve this in a basic waterfall. But I liked it much better to split the two parts build and deploy up into different concerted jobs.


text:
Q: Why ScrollView auto top when scrolling down? My ScrollView:
<ScrollView
    android:id="@+id/scrollView8"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bg" >
    <LinearLayout
        android:id="@+id/ListItems"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/btnbge81"
        android:orientation="vertical" >
    </LinearLayout>
</ScrollView>

I have about 500 child controls in LinearLayout called "ListItems".
Why does the ScrollView auto top when scrolling down?

A: The EditText will scroll a ScrollView so it comes into view.  You have to implement onTouchListener.  There's an answer somewhere but in a nutshell this works for me.  You have to clear the focus from the EditText controls to keep them from scrolling into view.
public class SettingRecord extends Fragment implements OnTouchListener {
    // setup scroll views onresume()
    ScrollView sv = (ScrollView) view.findViewById(R.id.svRecord);
    sv.setOnTouchListener(this);
    sv.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
    sv.setFocusable(true);
    sv.setFocusableInTouchMode(true);
    etName = (EditText) view.findViewById(R.id.etName);

    @Override
    public boolean onTouch(View v, MotionEvent event) {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // fix focus on edit texts scrolling
        if (etName.hasFocus()) {
            etName.clearFocus();
        }
        return false;
    }
}


text:
Q: Fancy Box - how to refresh parent page when close iframe popup? I want my parent page to refresh when I close a Fancy Box popup frame. I have a login page inside the popup, so I need the parent page to refresh to show the new login state when the Fancy Box closes.

I can get it to work without the iFrame code:

But I can't get it to work with the iFrame code:

The problem is to do with this line:

'type' : 'iframe'

As soon as I add that line, the popup stops working.

Can anyone suggest a solution as to how I can get an iframe to popup in Fancy Box, and still get the parent page to refresh when the box closes?

Thanks!

A: $(".fancybox").fancybox({
    type: 'iframe',
    afterClose: function () { // USE THIS IT IS YOUR ANSWER THE KEY WORD IS "afterClose"
        parent.location.reload(true);
    }
});

Alternatively:
Go to your jquery.fancybox.js file and go line 1380 it is look like this and add parent.location.reload(true);
afterClose: function (opts) {
    if (this.overlay) {
        this.overlay.fadeOut(opts.speedOut || 0, function () {
            $(this).remove();
            parent.location.reload(true);
        });
    }
    this.overlay = null;
}

A: For me next code works ok:
$("a.ic-edit").fancybox({
            'width'     : '65%',
            'height'    : '85%',
            'autoScale'     : false,
            'titleShow' : false,
            'transitionIn'  : 'no',
            'transitionOut' : 'no',
            'scrolling'     : 'no',
            'type'          : 'iframe',
            onCleanup   : function() {
                return window.location.reload();
            }
       });

I can't say exactly, but maybe the reason in using "onCleanup" (actually I didn't try use onClosed).

A: Besides the obvious missing , which you say you have fixed IMO this is not a fancybox issue but rather a parent refresh issue.
I have found it to be a challenge to get a parent of a frame to reload as there are multiple ways to "theoretically" achieve this but "most" simply do NOT work in practice and worse yet there really doesn't appear to be any error raised by the web browsers I tested with.
Here is code that works well for me on Chrome, FF, IE:
afterClose: function(){
    parent.location.href = parent.location.href;
},

This basically says set the parent href to whatever it is currently which in effect results in a page refresh.  Try it out and it should work well.
In fact the line:
parent.location.href = parent.location.href;

can be used with frames (from the parent of course) or without frames to simply refresh a web page. HTH.

A: $(".fancybox").fancybox({
            'width'             : '75%',
            'height'            : '65%',
            'autoScale'         : false,
            'transitionIn'      : 'none',
            'transitionOut'     : 'none',
            'type'              : 'iframe',
            'hideOnOverlayClick': false,
            'onClosed'          : function() {
                                  parent.location.reload(true);
                                  }
        });

A: 'onClosed': function() {
 parent.location.reload(true);
;} // <----is it ok if you have an extra ';' here?

A: A work around to avoid having POSTDATA Warning when you close the iFrame
1) Please Create form :
<form name="RefreshForm" method="post" action="" >
<input name="Name1" value="Value1" type="hidden" />
<input name="DatafromPost1" value="ValuefromPOST1" type="hidden" />
<input name="DatafromPost2" value="ValuefromPOST2" type="hidden" />
</form>

2) add this lines at the end of your Fancy-Box:
Fancy ver 2.x.x
afterClose : function() {
setTimeout('document.RefreshForm.submit()',1000); }

Fancy ver 1.3.x
     onClosed : function() {
setTimeout('document.RefreshForm.submit()',1000); }

1000 = 1 second.

A: link refresh:
jQuery(function($){
    $('#refresh').click(function ()
        {
            parent.location.reload();
    });
});

refresh

you can give:
setTimeout(function () {
            parent.location.reload();
        }, 1000);

or condition, for example,

A: You just need to write two lines to close the fancybox and after close to reload the parent page on which you have opened your fancybox.
One thing to be notices is that if you will try it with window.opener it not going to work as fancybox is not treated as a child window of the parent when it comes to window.opener
One more thing is that window.opener is not going to work for windows phone and also with IE, as IE is already stupid.

A: Well I know this is an extremely old post but here's a newer answer that I hope helps someone out there. I am using fancybox on a page with my website inquiries to pop up in a lightbox to read / delete. When I delete an inquiry in the light box I wanted the parent to refresh to show a current list of inquiries minus the one I just deleted. The upvoted comment didn't help me (as it is probably referencing an older version of the JS file).
On line 105 of jquery.fancybox.js (v3.5.7) change:
afterClose: n.noop,

to
afterClose: function() {parent.location.reload(true);},

It's been irritating me for a few days but it now works no worries.

A: When using the examples with 'location.reload' you get a browser pop that lets you know it needs to reload the page. I fired a button click to refresh the page and no warning popup.
$(".addDoc").colorbox({
    iframe: true,
    width: "550px",
    height: "230px",
    'onClosed': function() {
        $("#btnContSave").click();
    }
});

A: Refresh or reload on closing the form using fancybox in Shopify

I was using this on Shopify but this will work on other also

  jQuery(".add-device").fancybox({
    maxWidth  : 970,
    maxHeight : 700,
    fitToView : false,
    width     : '90%',
    height    : '90%',
    autoSize  : false,
    closeClick  : false,
    openEffect  : 'none',
    closeEffect : 'none',
    beforeClose: function() {
      device_has_subs = false;
      $("#mac_address").prop("readonly", false);
    },
    afterClose    : function() {
      window.location.reload(true);
        }
  });

here only afterClose is playing the task
we can also write parent instead of window

afterClose    : function() {
  parent.location.reload(true);
    }

If just reset the form in shopify then, In shopify sometime $("form")[0].reset() not works so using iteration we can empty the form value
  jQuery(".add-device").fancybox({
    maxWidth  : 970,
    maxHeight : 700,
    fitToView : false,
    width     : '90%',
    height    : '90%',
    autoSize  : false,
    closeClick  : false,
    openEffect  : 'none',
    closeEffect : 'none',
    beforeClose: function() {
      device_has_subs = false;
      $("#mac_address").prop("readonly", false);

      var array_element = document.getElementById("form_id");
      if (array_element){

        for (i=0; i < array_element.length; i++){
            element = array_element[i].type.toLowerCase();
            switch(element){
              case "text":
                  array_element[i].value = "";
                  break;
              case "hidden":
                  array_element[i].value = "";
                  break;
              case "email":
                  array_element[i].value = "";
                  break;
              case "checkbox":
                  if(array_element[i].checked){
                    array_element[i].checked = false;
                  }
                  break;
              case "select-one":
                  array_element[i].selectedIndex = -1;
                  break;
              case "select-multi":
                  array_element[i].selectedIndex = -1;
                  break;
              default:
                  break;
          }

        }

      }

    },
  });

form_id is the form id

A: 'onClosed' : function() { parent.location.reload(true); }


text:
Q: Obtaining closures at runtime I would like to know if there is any method to check whether two functions have the same arguments at runtime in python 3.
Basically, I have this function (func) that takes another function and an argument. I want to check the values assigned to args in the lambda function
func(another_func, args):
   return lambda(x : another_func(x, args))

It is not feasible to run the code before and check the results because I am implementing a lazy framework. My main goal is to be able to understand what are the arguments of the function because there is one variable argument that I do not care but there is one static that is created before running the function.
##EDIT
I actually solved this problem using the inspect module (getclosure) for those who are interested!

A: I actually solved this problem using the inspect module (getclosure) for those who are interested!
Extension (Martijn Pieters):
I think you are referring to getclosurevars(). You can also just access function.closure, and access the value of each cell via its cell_contents attribute.


text:
Q: finding a positive linear combination of a list of vectors. I'm interested in finding linear combinations of rows of the following matrix such that every entry is either zero or positive. I'm not exactly sure what the best way to approach this problem is.
[   1    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  138 -102    0  122  244  -41    0    0   99 -205   41  122  -99    0 -244  183  -67    7]
[   0    1    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  157 -116   -1  140  280  -47    0    0  113 -233   47  140 -113    0 -280  210  -76    8]
[   0    0    1    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  176 -132    0  156  312  -52    0    0  126 -261   52  156 -126   -1 -312  236  -85    9]
[   0    0    0    1   -1    0    0    0    0    0    0    1    0    0    0    0    0    0    0    0   51  -35    0   41   85  -12    1    1   34  -70   12   43  -34    0  -85   58  -18    2]
[   0    0    0    0    0    2    0    0    0    0    0    1    0    0    0    0    0    0    0    0   88  -63    0   75  153  -24   -1    1   61 -126   24   76  -61    0 -153  110  -37    4]
[   0    0    0    0    0    0    1    0    0    0    0    0    0    0    0    0    0    0    0    0  151 -114    0  137  270  -46    0    0  110 -228   46  135 -110    0 -270  206  -77    8]
[   0    0    0    0    0    0    0    1    0    0    0    1    0    0    0    0    0    0    0    0  161 -119    0  142  285  -46    1    0  115 -238   46  143 -115    0 -285  211  -76    8]
[   0    0    0    0    0    0    0    0    1    0    0    0    0    0    0    0    0    0    0    0  101  -73   -1   89  178  -30    0    0   72 -148   30   89  -72    0 -178  133  -47    5]
[   0    0    0    0    0    0    0    0    0    1    0    0    0    0    0    0    0    0    0    0  164 -120    0  143  286  -46    0    0  116 -240   46  143 -116    0 -286  212  -76    8]
[   0    0    0    0    0    0    0    0    0    0    0    2    0    0    0    0    0    0    0    0    3   -2    0    2    5    0    1    0    2   -4    0    3   -2    0   -5    2    1    0]
[   0    0    0    0    0    0    0    0    0    0    0    0    1    0    0    0    0    0    0    0  100  -74    0   88  176  -29    0    0   71 -147   29   88  -71   -1 -176  132  -47    5]
[   0    0    0    0    0    0    0    0    0    0    0    0    0    1    0    0    0    0    0    0  162 -119    0  142  284  -46    0    0  114 -238   46  142 -115    0 -284  211  -76    8]
[   0    0    0    0    0    0    0    0    0    0    0    0    0    0    1    0    0    0    0    0   78  -58    0   69  138  -23    0    0   56 -116   23   69  -56    0 -138  104  -38    4]
[   0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    1    0    0    0    0  160 -118    0  141  282  -46    0    0  114 -236   46  141 -114    0 -282  210  -76    8]
[   0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    1    0    0    0  142 -104    0  125  250  -41    0    0  101 -209   41  125 -101    0 -250  186  -67    7]
[   0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    1    0    0  123  -90    0  107  216  -35    0    0   87 -180   35  108  -87    0 -216  160  -57    6]
[   0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    1    0   39  -29    0   35   70  -12    0    0   28  -58   12   35  -28    0  -70   53  -19    2]
[   0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    1  101  -74    0   89  178  -29    0    0   72 -149   29   89  -72    0 -178  132  -48    5]
[   0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  201 -148    0  177  354  -58    0    0  143 -296   58  177 -143    0 -354  264  -95   10]
as an example, this vector of coefficients gives a solution, (i.e. the left matrix product is a vector with non-negative entries)
[ 0  0  0  0  0  0  0  0  1  0  0  0  0  1  0  0  2  0 -2]
any ideas would be greatly appreciated!

A: Given a set of $n$-component vectors $v_j$, $j=1\ldots,m$, the condition that the linear combination $\sum_j c_j v_j$ has all nonnegative entries is the set of linear inequalities $\sum_j c_j v_{jk} \ge 0$, $k = 1\ldots n$.  You can use linear programming methods to try to satisfy these inequalities.
Of course there is the trivial solution: all $c_j = 0$, but you probably don't want that.  You might add some constraint to avoid this solution (e.g. $\sum_j c_j \ge 1$).


text:
Q: Creating method for division I'm trying to write a method that takes two integers a and b and divides them. However I want the result to be a double. I've tried two ways:
(1)
public int divide(int a, int b) {
    if (b == 0) {
       System.out.println("Error, division by zero is undefined!");
    return 0;
    }
    else {
       a = Double.parseDouble(a);
       b = Double.parseDouble(b);
       return a / b;
    }
}

(2) (cast)
public int divide(int a, int b) {
    if (b == 0) {
       System.out.println("Error, division by zero is undefined!");
    return 0;
    }
    else {
       return (double) a / b;
    }
}

The first code generates the error message:
error: incompatible types: int cannot be converted to String
        a = Double.parseDouble(a);
                               ^

While the second generates the error message:
error: incompatible types: int cannot be converted to Double
        return (Double) a / b;
                        ^

Can anyone explain why these codes don't work and show me how to write a functioning code?

A: public double divide(int a, int b)
 {
   if (b == 0)
   {
       System.out.println("Error, division by zero is undefined!");
       return 0;
    }
    else
    {

         return ((double)a) / b;
     }
   }

Your only problem was returning an int and cast to a Double object.

A: You method returns an int, but return (Double) a / b; returns a double.
You should change it so that you either have
public double divide(int a, int b) {

as the first line (if you want to return a double) OR
return (int) a / b;

if you want to return an int.

A: *

*If you want your result to be double, then you need to change the return type of your function double.

*Use Double.parseDouble(String.valueOf(a)) to get double value.

*If you don't change the return type of you function then there will be loss of
precision in case if you get the response as decimal value. So do change the
return type of your function

A: The first problem is that Double.parseDouble() takes a String to return a double:
 public double divide(int a, int b) {
        if (b == 0) {
           System.out.println("Error, division by zero is undefined!");
        return 0;
        }
        else {
           double c = Double.parseDouble(a + ".0");
           double d = Double.parseDouble(b + ".0");
           return c / d;
        }
    }

In the second methode you need to cast correctly:
public double divide(int a, int b) {
    if (b == 0) {
       System.out.println("Error, division by zero is undefined!");
    return 0;
    }
    else {
       return ((double)a) / ((double)b);
    }
}

A: Double.parseDouble() requires a string as input, so Double.parseDouble("4") works, but Double.parseDouble(4) is incorrect.
Try changing all parameters to doubles and the return type to a double to avoid doing type casting inside the code.  Also, if the user wanted to divide two decimal values he/she would not need to call another function to do so.
public double divide(double numerator, double denominator)
{
    if(denominator == 0)
    {
        System.out.println("Error cannot divide by 0");
        return 0.0;
    }
    else
    {
        return numerator / denominator;
    }
}

If you want the parameters to be integers, then you need to return a typecast.
public double divide(int numerator, int denominator)
{
    if(denominator == 0)
    {
        System.out.println("Error cannot divide by 0");
        return 0;
    }
    return (double)numberator / denominator;
}