text:
Q: Python Regex Matching Partial Parentheses ONLY I have some poorly formatted text that I need to filter. As such, there are plenty of cases in which a quote in the text begins in one line and then cuts off and finishes in a second line. In such a case, my preference is to just remove the partial quotes completely, BUT, I want to preserve regular full quotes. I know that this can be done iteratively with a counter, but I would really prefer to go about it with Regular Expressions.
Take fore example:

"This is a quote"
This is an end "partial-
quote" Here is more text.
This is an end "partial-
quote w/o more text"
This is an "embedded" quote

Here is an example with my current attempt  (\"[^\"\n]+?|^[^\"\n]+?\")(\n|$)  Note that it fails in two circumstances:

*

*Line 3 -- a partial quote proceeds the rest of a sentence (very rare occurrence, so if we can't solve its not the end of the world).

*line 6 -- an embedded quote. This is a major problem and the main reason I have taken to SO with my problem. It grabs the last quote in the embedded quote to the end of the line.

I figured that I could set up an if statement and run each line through, checking if it has less than two quotes and then proceeding to parse the partial quotes, but I thought the minds at SO would have a much cleaner solution.
NOTE The desired output is:

"This is a quote"
This is an end
 Here is more text.
This is an end
This is an "embedded" quote

(I handle the whitespaces later-on)

A: Here you go,
^((?:[^"\n]*"[^"\n]*")*[^"\n]*)"[^"\n]*\n[^"\n]*"(\n|)

Replace the matched characters with \1\n
DEMO
>>> import re
>>> s = '''"This is a quote"
This is an end "partial-
quote" Here is more text.
This is an end "partial-
quote w/o more text"
This is an "embedded" quote'''
>>> m = re.sub(r'(?m)^((?:[^"\n]*"[^"\n]*")*[^"\n]*)"[^"\n]*\n[^"\n]*"(\n|)', r'\1\n', s)
>>> print(m)
"This is a quote"
This is an end
 Here is more text.
This is an end
This is an "embedded" quote

Use this regex, if you want to deal with more than one lines present inside between double quotes.
^((?:[^"\n]*"[^"\n]*")*[^"\n]*)"(?:[^"\n]*\n)+[^"\n]*"(\n|)

DEMO

A: You can perhaps use this regex:
"[^"\n]+?\n[^"\n]+?(?:"|$)\s*

and replace with \n.
regex101 demo
"[^"\n]+?\n[^"\n]+? will match only the partial quotes (ensures there's a line break between the quotes).
ideone demo

A: ("[^"\n]*")|"[^"]*(\n)[^"]*"(?![^\n]*")|"[^"]*\n.*?(?=\n[^"]*"[^\n"]*")

You can try this.This will take case of odd number of quotes as well.See demo.
https://regex101.com/r/dL7oF8/6


text:
Q: Point and use a subdomain in GCP I have a primary domain www.example.com setup in Route 53 on AWS.
I want to point subdomain1.example.com to Google Cloud, specifically to an instance group running in Google Compute Engine.
Is this possible?

A: Yes, and this is a good design practice called nameservice delegation.  The best approach is to delegate an entire subdomain for GCP, so let's use the domain example.com and gcp.example.com as the domain and subdomain.
This way Google will manage DNS for you rather than you updating A & CNAME records in route53 manually.
Overall this will take these steps (1) creating the gcp.example.com zone in GCP (2) obtaining the NS records for gcp.example.com (3) delegating NS for gcp.example.com to Google Cloud NS and then (4) Create the resource-level records (e.g. for a VM or appengine app) in GCP Cloud DNS.
(1) Creating the Zone in GCP
This can be done in the console under Network Services -> Cloud DNS or the cloud shell. I favor the shell.
$ gcloud dns managed-zones create gcp-example --description="GCP Example Zone" \
      --dns-name="gcp.example.com"

(2) Obtain the NS Records for the new Zone
Below is an example -- copy the ones specific to your NS
gcloud dns managed-zones describe gcp-example |grep -A5 nameServers
nameServers:
- ns-cloud-d1.googledomains.com.
- ns-cloud-d2.googledomains.com.
- ns-cloud-d3.googledomains.com.
- ns-cloud-d4.googledomains.com.

(3) Add the delegate NS record in AWS
create update.json (make sure the value records are correct):
{
            "Comment": "CREATE/DELETE/UPSERT a record ",
            "Changes": [{
            "Action": "CREATE",
                        "ResourceRecordSet": {
                                    "Name": "gcp.example.com",
                                    "Type": "NS",
                                    "TTL": 300,
                                 "ResourceRecords": [ {"Value" : "ns-cloud-d1.googledomains.com."}, {"Value": "ns-cloud-d2.googledomains.com."},
                                     {"Value" : "ns-cloud-d3.googledomains.com."}, {"Value": "ns-cloud-d4.googledomains.com."}]
}}]
}

HOSTED_ZONE_ID=XXXXXX
aws route53 change-resource-record-sets --hosted-zone-id=${HOSTED_ZONE_ID} --change-batch=file://./update.json
{
    "ChangeInfo": {
        "Status": "PENDING",
        "Comment": "CREATE/DELETE/UPSERT a record ",
        "SubmittedAt": "2019-02-27T23:43:35.327Z",
        "Id": "/change/XXXXXX"
    }
}

(4) In GCP Cloud DNS, create all of your gcp resource records under gcp.example.com
At this point, you can manage all of your GCP dns within GCP Cloud DNS.  Go ahead and create vm1.gcp.example.com or appengine1.gcp.example.com

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to hide administrator account or root in Login screen? I used Ubuntu 12.04 and I want to only user account appear on the Login screen without guest and administrator account. My administrator account cannot view to everybody when their Login.
"greeter-hide-user=true" this command all account disappear. What command in user account only in Login screen?

A: To hide/invisible an administrator account in login page:
    Note: replace AdminAccount with the actual administrator account e.g. admin01
(Ctrl + Alt + T)
login in sudoer/admin account to used this command.
    sudo usermod -u 999 AdminAccount

A: Easily you can change the User ID of the user you want to hide.
The system tray only shows system users which are having USer ID =>1000
So to hide a user just give him a UID < 1000
You can change the UID using the command
sudo usermod -u UID username

Be carfull the numbers from 0 to 99 is reserved for system accounts, so don't use  them. Moreover you should be card in choosing the new UID not to be identical with some service users in your system.
The command:
awk -F':' '{ print $3}' /etc/passwd

will list all UID used in your system So you can choose the new UID without conflicting other user.
you can sort the list in increasing numeric to be easy to notice the UID numbers
awk -F':' '{ print $3}' /etc/passwd | sort -n

A: Open /etc/lightdm/users.conf in a text editor and add the administrator user name to "hidden-users", reboot and you're done.


text:
Q: GestureDetector: why this code is not working? Why is this GestureDetector not workink?
I would expect the GestureDetector to be called and detect the double tap
@Override
    public void  onTouchEvent(MotionEvent event) {

        gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onDoubleTap(MotionEvent event) {
                Log.e("onDoubleTap", event.toString());
                //handle double tap
                int x = (int) event.getX();
                int y = (int) event.getY();
                return true;
            }
        });
        gestureDetector.onTouchEvent(event);
    }

A: You are initializing your gestureDetector class every time you receive a touch event, preventing it from saving any kind of state, thus it is unable to detect a double tap. You can lazy load it instead:
@Override
    public void  onTouchEvent(MotionEvent event) {
        if(gestureDetector == null){
            gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener(){
                @Override
                public boolean onDoubleTap(MotionEvent event) {
                    Log.e("onDoubleTap", event.toString());
                    //handle double tap
                    int x = (int) event.getX();
                    int y = (int) event.getY();
                    return true;
                }
            });
        }
        gestureDetector.onTouchEvent(event);
    }

A: You are using the wrong constructor. The Full example of usage the gesture:
    private GestureDetectorCompat gesture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Just the default methods
        gesture = new GestureDetectorCompat(this, new OnGestureListener() {

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public void onShowPress(MotionEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                    float distanceY) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                    float velocityY) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onDown(MotionEvent e) {
                // TODO Auto-generated method stub
                return false;
            }
        });

        gesture.setOnDoubleTapListener(new OnDoubleTapListener() {

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                Log.i("GESTURE","DoubleTap");
                return true;
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        gesture.onTouchEvent(event);
        return true;
    }

}


text:
Q: Not getting remote address while using proxy in socket.io In my socket.io code,
socket.sockets.on('connection', function(client){
    var ip = client.handshake.address.address;
    ..
}

ip always returns 127.0.0.1 and this is because the server sits behind a proxy.
How do I get remote address properly ?
Edit: I am using http-proxy

A: In version > 1.0, the syntax is similar:
socket.handshake.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;

A: yes, this is working for me.
client.handshake.headers['x-forwarded-for'] || client.handshake.address.address;

I am properly getting the remote IP address and not 127.0.0.1

A: For people who may come from Google, using NGINX: none of these worked for me, I followed the answer in this other question and modified my proxy_pass, to create a new header that node could then use. Don't forget to call sudo systemctl restart nginx after.


text:
Q: How to create this shadow effect? I am trying to create similar to this shadow effects, and inspected CSS in chrome, still i am not getting what i want, my current code is:
.imageShadow {
    background: #fff;
    -webkit-box-shadow: 0 0 5px 0 #bbb;
    box-shadow: 0 0 5px 0 #bbb;
    height: 293px;
}

Note: My image height is 293px
Is this will work in all browsers?
Anyone have an idea?

A: If you mean the nice, curvy dropshadow then CSS at the current state does not allow it. They haven't used CSS to do this, they used image sprites.

A: Here is a chart that shows compatibility for css box-shadow:
http://caniuse.com/css-boxshadow
IE 9+, Firefox 4+, Safari 5+, and Chrome all support the style.


text:
Q: WCF async call raises exception which goes to the Unhandled Exception handler - none of my code in the callstack I am making a WCF call to ASP.NET from Windows Phone (7.0, 7.1 SDK). In some cases (I could not make this happen on the emulator or any of my devices), the unhandled exception handler fires for an exception that happens in one of these calls (clarification - this is all on the client - not on the server). I see two occurrances of this (they happen quite a bit). I have never had this issue before (not on older versions, and not on other apps that use the same WCF proxy code).
Does anyone have any idea why this is happening and how? And what I can do to work around it?
The first callstack this is happening on is:
System.ServiceModel.ProtocolException: The content type text/html of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 75 bytes of the response were: 'The page cannot be displayed because an internal server error has occurred.'. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.    at
System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)    at
System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass2.<EndGetResponse>b__1(Object sendState)    at
System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)    at
System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)    at
System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)    at
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)    at
System.Delegate.DynamicInvokeOne(Object[] args)    at
System.MulticastDelegate.DynamicInvokeImpl(Object[] args)    at
System.Windows.Threading.Dispatcher.<>c__DisplayClass4.<FastInvoke>b__3()    at
System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)    at
System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)    at
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)    at
System.Delegate.DynamicInvokeOne(Object[] args)    at
System.MulticastDelegate.DynamicInvokeImpl(Object[] args)    at
System.Windows.Threading.DispatcherOperation.Invoke()    at
System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)    at
System.Windows.Threading.Dispatcher.OnInvoke(Object context)    at
System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)    at
System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)     at
System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)    at
System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)    at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)    at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult result)    at
System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)    at
System.Threading.ThreadPool.WorkItem.doWork(Object o)    at
System.Threading.Timer.ring()     at
System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException)    at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.ProcessResponse(HttpWebResponse response, WebException responseException)    at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)    at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult result)    at
System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)

The second callback this is happening on is:
System.ServiceModel.EndpointNotFoundException: There was no endpoint listening at
http://MyServer.com/Fail/FailService.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.    at
System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)    at
System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass2.<EndGetResponse>b__1(Object sendState)    at
System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)    at
System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)    at
System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)    at
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)    at
System.Delegate.DynamicInvokeOne(Object[] args)    at
System.MulticastDelegate.DynamicInvokeImpl(Object[] args)    at
System.Windows.Threading.Dispatcher.<>c__DisplayClass4.<FastInvoke>b__3()    at
System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)    at
System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)    at
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)    at
System.Delegate.DynamicInvokeOne(Object[] args)    at
System.MulticastDelegate.DynamicInvokeImpl(Object[] args)    at
System.Windows.Threading.DispatcherOperation.Invoke()    at
System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)    at
System.Windows.Threading.Dispatcher.OnInvoke(Object context)    at
System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)    at
System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)     at
System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)    at
System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)    at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)    at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult result)    at
System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)    at
System.Threading.ThreadPool.WorkItem.doWork(Object o)    at
System.Threading.Timer.ring()     at
System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)    at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)    at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult result)    at
System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)    at
System.Threading.ThreadPool.WorkItem.doWork(Object o)    at
System.Threading.Timer.ring()

A: It looks like your web server/service may be crashing due to possibly unhandled exceptions. I would checked the event logs on the web server to see if there are cases where IIS is reporting crashes.
Update for clarified question
As I understand the question now, the problem is that if the web service is down, the WCF service is raising an exception that can only be caught in the unhandled exception handler.
I have never run across this behavior, but I understand why it is happening and have a possible solution. The WCF service request is fired asynchronously, so the actual connection and processing occur in a thread, which you can see in your call stack.
If you have hooked the asynchronous method's completion event, the exception should be passed in the parameters to that event handler rather than being thrown. I believe that the exception will only be thrown if there isn't a handler because the framework doesn't know what else to do with the exception.


text:
Q: Access child element value of Div I have following code:

  Text:
       <input type="text" aria-controls="searchResult">

I want to get the input field values if anything is entered.
I only have mentioned code and i can't change it like putting id or adding any event. So then how to do it.
Even if i'm able to detect changes in div that will also helpful.
I have tried like:
$("#searchResult_filter").change(function() {
  alert("ketyup");
});

A: I have found the solution: By adding keyup eventListener
document.getElementById("searchResult_filter").addEventListener("keyup",disableConsultarOpcionesdeFinanciacion);

It call the below function on input box keyup:
function disableConsultarOpcionesdeFinanciacion()
{
 //Code to do somthing
}

A: Use .keyup()

Description: Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.

$("input[type=text]").keyup(function (e) {

        alert($(this).val());

    });

A: Try this..

 Text:
    <input type="text" aria-controls="searchResult"   onchange="GetInputVal(value)">

 function GetInputVal(val) {
 //your logic to handle the value
 }

A: jQuery selector also work like the css selector. So you can use the following code.
$("#searchResult_filter input[type=text]").keyup(function (e) {
        console.log($(this).val());
});

Or
$("input[aria-controls=searchResult]").keyup(function (e) {
            console.log($(this).val());
    });


text:
Q: "Error HRESULT E_FAIL has been returned from a call to a COM component" when executing FullTextSqlQuery? I am using a FullTextSqlQuery to grab some data from a SharePoint instance.  Initially I had a fairly simple where clause in which I filtered the results by the content type and everything worked fine.
I then tried to add some date filtering which added a condition like:
 AND mypublishstartdate <= '11/9/2011'

to the end.  Unfortunately I am now getting the error:

Error HRESULT E_FAIL has been returned from a call to a COM component.
Exception Details:
  System.ServiceModel.FaultException`1[[System.ServiceModel.ExceptionDetail,
  System.ServiceModel, Version=3.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089]]: Error HRESULT E_FAIL has been
  returned from a call to a COM component.

Does anyone know what I am doing wrong here?

A: Do you have a managed property called mypublishstartdate which has a crawlable property mapped to it?

A: In my case, recycling the application pool where search was running fixed this issue


text:
Q: Besides caching, how can I use more memory rather than cpu time on a LAMP server? My site is rough on cpu usage, but I have plenty of memory (and hdd space) I could be using. The site is sort of a game with lots of db updates and object manipulations.  Generally speaking, is there any other way to share the load after having cached as much as I think I can?
Thanks

A: There is no general advice I, am afraid.
Can't you at least roughly profile your application, to determine certain bottlenecks - if it's db updates, or object manipulations? Or even some other, obscure matter?
If your filesystem is a cheap one (not SAS), and there are many disk I/O, it may eat up your CPU easily. You have to optimize disk writes, but I am afraid again there is no common way. Try to reduce number of indexes. Cache your database in memory, when applicable.


text:
Q: Multiple Havings not working I have a database with the following schema:

ID   PositionId    LeagueId
1        4            5
3        4            5
3        8            5
4        1            6

I have this sql query in Access:
 SELECT lp.PositionId
 FROM Leagues l
 INNER JOIN Lineups lp ON (l.LeagueID = lp.LeagueId)
 GROUP BY PositionId
 HAVING sum(iif(lp.PositionId = 4,1,0)) > 1 AND sum(iif(lp.PositionId = 8,1,0)) > 0

If I only use the left side of the Having, ie:
 HAVING sum(iif(lp.PositionId = 4,1,0)) > 1

I will get 1 results (LeagueId 5).  If I use the right-side of the Having, ie:
 HAVING sum(iif(lp.PositionId = 8,1,0)) > 0

I will also get one result (LeagueId 5), but both together (like above) yields no results.

A: Your issue is because the SUM can't satisfy both HAVING predicates, so try using an OR:
  SELECT lp.PositionId
    FROM Leagues l
    JOIN Lineups lp ON (l.LeagueID = lp.LeagueId)
GROUP BY PositionId
  HAVING SUM(iif(lp.PositionId = 4,1,0)) > 1 OR SUM(iif(lp.PositionId = 8,1,0)) > 0

A: Aren't you grouping by positionid? So for each positionid you're asking the sum for that positionid to be >0 when the id is 4 AND 8 at the same time. Is this possible? Do you want an OR? Should you be using a different query?
GROUP BY LeagueID, for instance?

A: You can write a much simplified version of this query e.g.
SELECT DISTINCT 8 AS PositionId
  FROM Lineups
 WHERE PositionId = 8
UNION ALL
SELECT DISTINCT 4
  FROM Lineups
 WHERE PositionId = 4
HAVING COUNT(*) > 1;


text:
Q: Using Custom Code in Expressions (Reporting Services). Sum of calculated rows In Report Builder I need to calculate total of several rows as sum of values in the tablix. I've read that for this purpose I can use the custom code, but I don't know how to integrate it into my report. An excerpt from the Internet:

Dim public totalBalance as Integer
Public Function AddTotal(ByVal balance AS Integer ) AS Integer
                totalBalance = totalBalance + balance
                return balance

End Function

Public Function GetTotal()
                return totalBalance
End Function

To use the code, please use the AddTotal in the 'Balance' field such
  as: =AddTotal( change the Balance value based on the business role).
  This expression will return the value of the balance that has been
  changed based on the business role.
And then in the footer, use this expression: = GetTotal().  That will
  return the total value of the changed balance.

Can anybody explain step-by-step what should I do?
I have values for SKU calculated in data textbox by custom expression. SKU is the child group of Brands. I need to calculate total for Brands (I added a Total row for Brands in which I need to get total).

A: To add custom code, right click somewhere in the blank space around the report. Select "Report Properties", then "Code". Add the code from the grey box you pasted and click "Ok".  You have just created two new functions to use. Use =code.Addtotal(fields!yourfield.value or reportitems!yourfield.value) for the subtotal and =code.GetTotal(fields!yourfield.value or reportitems!yourfield.value) for the total row.


text:
Q: Auth0 Passworldess sign up flow with Worpdress registration form I m running a Wordpress site and I have set up Auth0 passwordless log in using the Lock Passwordless UI.
The passwordless authentication does not allow additional fields for the sign up and I successfully wrote a rule (not sure if is OK but it works) that redirects the user that logs in for the first time to a sign up form on Wordpress asking for more details from them.
  function (user, context, callback) {
  const namespace = 'https://mysiteurl/redirect';
  const userType = context.stats && context.stats.loginsCount === 1 ? 'new' : 'existing';
  context.idToken[`${namespace}userType`] = userType;
  if (userType === 'new') {
    context.redirect = {
    url: "https://mys-site-url/sign-up-wordpress-form"
  };
  }
  return callback(null, user, context);
}

What I would like to have is a permanent registration form on Wordpress where I collect data and the sign in process to be passwordless with email only.


text:
Q: What is the difference between AbortRequest and Forbidden According to Dynamic IP Security document in Microsoft :

AbortRequest :    Specifies that by default IIS should send a deny mode
  response of Abort back to clients. The numeric value is 0.
Forbidden : Specifies that by default IIS should send a deny mode
  response of Forbidden back to clients. The numeric value is 403.

The description seems similar. Is it just about numeric value ?

A: As that article says, aborting simply drops the connection without bothering to complete the request or give any reason for the cancellation.
Sending a Forbidden response means it will complete the request and send a HTTP status code, but it denies the user access to the originally requested resource. Some relevant response data may still be returned to the caller (even if it's just a string saying "Forbidden").


text:
Q: layout in vue.js2.5 / vuetify application In  vue.js2.5 / vuetify application  I use next layout with 2 inputs when I want 2 columns on extra small devices:
                        <v-flex xs12 sm6>
                            <v-text-field
                                    label="Created at"
                                    v-model="artist_created_at_label"
                                    readonly disabled
                                    v-show="!is_insert"
                            ></v-text-field>
                        </v-flex>

                        <v-flex xs12 sm6 class="pl-4">
                            <v-text-field
                                    label="Updated at"
                                    v-model="artist_updated_at_label"
                                    readonly disabled
                                    v-show="!is_insert && artist_updated_at_label"
                            ></v-text-field>
                        </v-flex>

I use
class="pl-4"

for right input( artist_updated_at_label ) to have distance from left input( artist_created_at_label ), but how to get rid of it
 extra small devices as I do not need it in this case?
Thanks !

A: You can access current viewport size with $vuetify.breakpoint
(docs).
It's reactive so you can make your class conditional, so that it only appears on arbitrary sizes (e.g. smAndUp excludes xs).
:class="{'pl-4': $vuetify.breakpoint.smAndUp}"


text:
Q: setCursorPosition() with threads I'm an upcoming programmer who is trying to build games in C++ (Console applications right now). But one annoying thing is bugging me and stopping me. The thing is I want to be able to multithread when letting the game character move as well as spawn enemies. But the problem is that because these two things are seperate functions and that there's only one input-spot used by the setCursorPosition the game always get messed up when these two functions get entangled. What are the solutions to this? If you guys need it I can send some source codes to try to explain my problem further. Examples and videos are very appreciated!

A: One solution is to only ever let a single thread update your screen.
You could for example have a framebuffer, which is a region of memory your threads draw into, and then another thread which in regular interval draws the entire framebuffer onto the screen. When you use two such buffers you can hide intermediate drawing steps. But actually this thread design is quite messy.
The best solution would be to use only one single thread (no multithreading, no std::thread at all). To me it appears you do not need multiple threads, but rather an event based system in which individual entities act independently and draw to the same screen. You do not need threads for this.
Multithreading is rocket science in 2019, especially in C++. Do not do it unless you are an expert.


text:
Q: What is gevent.queue.Channel? Under Gevent's what's new, a new class Channel under the gevent.queue module is mentioned:

Queue(0) is now equivalent to an unbound queue and raises DeprecationError. Use gevent.queue.Channel if you need a channel.

I checked the documentation page but there is no documentation about what Channel is or does. Looking at the source, it appears to be similar to Queue but it's not a subclass of it. What exactly is the purpose or use of Channel? Is it a specialized queue of some sort?

A: Looking at the code for the pre-1.0 version of Gevent tells you what a Channel is (though I recognize this is a bit convoluted):

Queue(0) is a channel, that is, its put method always
  blocks until the item is delivered. (This is unlike the standard
  Queue, where 0 means infinite size).

Now, as the release notes indicate, this behavior has changed in Gevent 1.0, and Queue(0) no longer works this way: Channel() does.
You'll observe that, accordingly, the implementation of Channel.put is significantly more complex than that of Queue.put.
Note that "standard Queue" refers to the standard library Queue.


text:
Q: Reusing Process object and IO redirects in C# I'm using the data ready events of the Process class to get information from the standard output and standard error of a running process.
It works great on the first run, but after calling Stop() then Start() to force a restart of the application, I no longer recieve data. I've tried CancelErrorRead() but no luck there.
I'm considering just re-instantiating the object every time I need to re-run the app, but it seems silly to need to do that.
Any advice on how to re-use a Process object to restart a stopped process?
Relevant code chunks:
Constructor:
   ProcessStartInfo objStartInfo = new ProcessStartInfo();
    objStartInfo.CreateNoWindow = true;
    objStartInfo.RedirectStandardInput = true;
    objStartInfo.RedirectStandardOutput = true;
    objStartInfo.RedirectStandardError = true;
    objStartInfo.UseShellExecute = false;

    objClient = new Process();
    objClient.StartInfo = objStartInfo;

    objClient.EnableRaisingEvents = true;
    objClient.OutputDataReceived   += new DataReceivedEventHandler(read);
    objClient.ErrorDataReceived    += new DataReceivedEventHandler(error);

Start:
    objClient.StartInfo.FileName    = strAppPath;
    objClient.StartInfo.Arguments   = strArgs;
    start();
    objClient.BeginErrorReadLine();
    objClient.BeginOutputReadLine();

Stop:
    objClient.Close();
    objClient.CancelErrorRead();
    objClient.CancelOutputRead();

A: Your Process object is not associated with a process until you call Start() (or use one of the static methods off Process).  A stopped/closed process is functionally the same as no process at all.  Given that, it's hard to believe there's any overhead to creating a new Process object, when compared to the (relatively enormous) cost of creating processes on Windows.  Just create new Process objects as needed.

A: According to msdn you should call BeginOutputReadLine and BeginErrorReadLine to enable asynchronous reads from StandardOutput or StandardError using events.
Have a look at the remarks section on
BeginOutputReadLine


text:
Q: youtube comments form in Flutter when you writing some comments on Youtube videos using mobile phone, at first,
it seems one line.
but when it is 2 lines because of length
the container height has also expanded
how to implement kind of those things?
what I currently do is pretty normal.
Container(child: TextFormField(
          //usual codes
)),

A: keyboardType: TextInputType.multiline
This Enables The keyboard to be multilined and increase its
Size


text:
Q: How to set extra link argument in Python module setup? I am using setup tools to build a Python module and I need to add extra links.
Parameter extra_link_args is not working.

A: As I said, extra_link_args is not an argument to setup. It would be like this:
extra_link_args = []

if platform.system() == 'Darwin':
    extra_link_args.append('-Wl,-rpath,' + lib_path)

setup(
    name='Mymodule',
    #extra_link_args = extra_link_args this is wrong
     ext_modules = [Extension("_mymodule", ["mycfile.c"],
                         depends=[],
                         libraries = [':mylib.a'],
                         extra_link_args = extra_link_args, #this is right
                   )],


text:
Q: Unable to access list elements in Django Webpage Following is the context dictionary that I am passing I am rendering to my webpage
    context = {'subdivision_selected': str(subdivision_selected),
               'labels': keep_month_names_only(list(rainfall_data[0].keys())),
               'data': new_dict}
    data = {'2011': [26.9, 84.8, 72.8, 111.4, 326.5, 383.2, 583.2, 441.5, 757.1, 212.3, 150.8, 238.5],
            '2012': [119.9, 45.6, 30.9, 55.8, 533.9, 458.2, 317.3, 369.6, 868.9, 209.7, 300.5, 187.3],
            '2013': [67.1, 37.6, 43.0, 46.3, 509.3, 777.0, 564.8, 336.7, 473.6, 455.8, 354.2, 92.3],
            '2014': [41.9, 8.6, 0.0, 11.1, 238.0, 416.6, 467.6, 321.6, 412.9, 402.6, 201.2, 100.4]}

After passing the context I am accessing the same from Django Webpage using chart.js as shown in following code
{% for a in data %}
var ctx = document.getElementById({{  a  }}).getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [{% for i in labels %}"{{ i }}",{% endfor %}],
        datasets: [{
            label: '{{  subdivision_selected  }}  {{  a  }}',
            data: {{  data.a  }},
        }]
    },
});
{% endfor %}

When i try to access following line, it returns empty and blank page is seen
    data: {{  data.a  }},

A: if you're looping though a dict, you want to use this syntax to access the data:
{%for key, value in data%}
  var key = {{key}}, var value = {{value}}
{%endfor%}


text:
Q: The compliance properties of the elements of the array by i On canvas I've allocated an array of stars with coordinates:
x: randomInt(1, canvas.width - 1),
y: randomInt(0, canvas.height - 1),

Every star has an initial opacity (op) value of 1. During animation, the opacity changes to 0 (and the stars disappear).
It should be that stars in the top part of the canvas (y < 75) disappear at a different speed from those at the bottom, because of the following code that sets the opacity values for each frame:
 for (let i = 0; i < SF_COUNT; i++) {
     if (stars[i].y < 75) {stars[i].op -= 0.001;}
     else {stars[i].op -= 0.01;}
 }

However, what actually happens is that stars do animate at different rates, but this difference appears random (i.e. not limited to stars at the top part of the canvas). Why? http://jsfiddle.net/Nata_Hamster/6jdnq3ry/

A: Bug:
Right now your drawFrame code sets the opacity after drawing the star, meaning that the opacity affects the next star instead of the current one:
...
// draw all SF_COUNT stars
for (let i = 0; i < SF_COUNT; i++) {
    // this draws star i with the *current* context.strokeStyle
    snowflake(stars[i].x, stars[i].y);
    // this sets the context.strokeStyle for star i + 1
    context.strokeStyle = 'rgba(255,255,255,' + stars[i].op + ')';
}
...

Fix:
Swap the two lines so that you set the color before drawing the star:
...
// draw all SF_COUNT stars
for (let i = 0; i < SF_COUNT; i++) {
    // this sets the context.strokeStyle, changing the opacity of star i
    context.strokeStyle = 'rgba(255,255,255,' + stars[i].op + ')';
    // this draws star i with the new context.strokeStyle
    snowflake(stars[i].x, stars[i].y);
}
...

Here's a fixed codepen.

A: You had the strokeStyle as the last step when it should be the first...
Here is your code with my correction:
also added a few other minor improvements to make the code more readable

var canvas = document.getElementById("drawingCanvas");
var context = canvas.getContext("2d");
var stars = [];

const SF_COUNT = 500;
context.lineWidth = 1.1;

window.onload = function() {
  changeColor1();
  drawFrame();
}

for (let i = 0; i < SF_COUNT; i++) {
  stars.push({
    x: randomInt(1, canvas.width - 1),
    y: randomInt(0, canvas.height - 1),
    op: 1
  });
}

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min));
}

function snowflake(star) {
  context.strokeStyle = 'rgba(255,255,255,' + star.op + ')';
  context.beginPath();
  context.moveTo(star.x, star.y);
  context.lineTo(star.x + context.lineWidth, star.y + context.lineWidth);
  context.stroke();
}

function drawFrame() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  for (let i = 0; i < SF_COUNT; i++)
    snowflake(stars[i]);
  setTimeout(drawFrame, 190);
}

function changeColor1() {
  for (let i = 0; i < SF_COUNT; i++)
    if (stars[i].op > 0)
      stars[i].op -= (stars[i].y < 75) ? 0.002 : 0.01;
  requestAnimationFrame(changeColor1);
}
#drawingCanvas {
  height: 170px;
  width: 400px;
  background-color: #000;
}
<canvas id="drawingCanvas"></canvas>


text:
Q: Php IDE for inside object AutoComplete I can't really understand why but although PHP is used in many sites and servers side application, still there i couldn't find any decent IDE that will have full auto-complete features like other languages has.
As specially i'm talking about auto-complete after I've signed a new object in my code.
for example:
<?php
    $mysqli = new mysqli($host,$user,$pass,$db); //here the auto complete knew how to help me with mysqli and documentation.
    $mysqli->query("query"); //here the auto complete didn't know to auto complete and suggest me all the functions available for the $mysqli object..

?>

Any idea for an IDE that really know how to do the job like Eclipse knows in Java and MS Studios knows in .Net ?

A: I would recommend PHPStorm by JetBrains. They make a GREAT product with amazing features. I have been using it for years and am addicted.

A: Netbeans is also an option, it has autocompletion and is free.


text:
Q: Google Drive Document Time Stamp I assume that the modifiedDate search field is the date of modification (obviously) or upload to the drive. Is there a way to preserve the original creation date of the file on its native system? Or is there a possibility to modify this field?
Thank you, Sean

A: You can use File.Update to set the modification date after upload.
https://developers.google.com/drive/v2/reference/files/update
Also, File.Patch works too:
https://developers.google.com/drive/v2/reference/files/patch
I know that I read another old thread sometime where it was discussed that it would be nice to be able to preserve the original creation date on insert, or at least to have that as an option, but this functionality does not exist yet.  (Can't find the post now...)
UPDATE:
I decided it would be nice to have a method to update the document time stamp, so here it is:
    public static File SetLastModified(string fileID, DateTime lastModified)
    {
        File file = DriveService.Files.Get(fileID).Fetch();
        file.ModifiedDate = lastModified.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'");
        try
        {
            FilesResource.UpdateRequest request = DriveService.Files.Update(file, fileID);
            request.SetModifiedDate = true;
            file = request.Fetch();
        }
        catch (Exception e)
        {
            throw;
        }
        return file;
    }


text:
Q: Sending push notification to all users in query I am creating an app that uses Parse cloud. I am trying to send a message from a user to all others. After writing the message in a textfield and pressing send, the delegate calls the following method and the push is handled as shown below:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//hide keyboard
[textField resignFirstResponder];

NSString *message = self.broadcastText.text;

//create a user query
PFQuery *query = [PFUser query];
PFUser *current = [PFUser currentUser];
NSString *currentUsername = current[@"username"];
[query whereKey:@"username" notEqualTo:currentUsername];

//send push in background
PFPush *push = [[PFPush alloc] init];
[push setQuery:query];
[push setMessage:message];
[push sendPushInBackground];

//clear text field
textField.text = @"";

return YES;}

What's happening is when I send the message, the sender (in this case me) is receiving the push notification as well. What I tried to do is get the current user's username and then create a user query that queries for all users whose usernames are not equal to the current user's username.
However, it didn't work, the message was also being sent to all users including the sender.
Note: I also tried using [query whereKey:@"username" notEqualTo:currentUsername]; just for debugging, and when I try to send the message, neither the sender nor any other device receives it. (when actually no one should receive it except the sender).
Any help would be greatly appreciated. Thank you.

A: Your problem is that a PFPush can't take any query, it needs a PFInstallation query.  When you store your PFInstallation for each user, you could add a field that points to the current user, something like:
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
currentInstallation[@"user"] = [PFUser currentUser];
[currentInstallation saveInBackground];

Then, do an installation query like this:
PFQuery *installationQuery = [PFInstallation query];
PFUser *current = [PFUser currentUser];
[installationQuery whereKey:@"user" notEqualTo:current];

Then, continue with your push using this query:
PFPush *push = [[PFPush alloc] init];
[push setQuery:installationQuery]; // <<< Notice query change here
[push setMessage:message];
[push sendPushInBackground];

A: In theory you send push notifications to all users that are subscribed to some channel ok.
Now you have a table with all users and all channels. Some users are subscribed other are not. First create a query for the installation, than find users that are not current user.
PFQuery *pushQuery = [PFInstallation query];
[pushQuery whereKey:"user" notEqualTo:[PFUser currentUser]];

Create a Push object and use this query.
PFPush *push = [[PFPush alloc] init];
[push setQuery:pushQuery]; // Set our Installation query
[push setMessage:@"Ciao."];
[push sendPushInBackground];

In pushQuery you can use other key, example: deviceID,installationID, deviceType etc..
I use Parse Cloud but i never use push notification so you need to try this code.


text:
Q: PHP traits - cannot use method defined in trait I used to have several library classes with the exact same methods. Figured I'd learn a bit more about two important aspects of coding; Traits and DRY.
I have the following trait:
<?php

namespace App\Berry;

trait Lib
{
    public function getIDs()
    {
        $oClass = new \ReflectionClass(get_called_class());
        $aConstants = $oClass->getConstants();
        foreach($aConstants as $sKey => $mValue)
        {
            if(!is_int($mValue))
            {
                unset($aConstants[$sKey]);
            }
        }
        return array_values($aConstants);
    }
}

The following class:
namespace App\Berry;

use Lib;

class postType
{
    const POST_TYPE_BLOG_ID     =   1;
    const POST_TYPE_BLOG_LABEL  =   __('blog', 'lib');

    const POST_TYPE_PAGE_ID     =   2;
    const POST_TYPE_PAGE_LABEL  =   __('page', 'lib');

    const POST_TYPE_NEWS_ID     =   3;
    const POST_TYPE_NEWS_LABEL  =   __('news', 'lib');
}

And am calling it like this in my PicturesController class:
$cPostTypesLibrary = new postType();
$this->set('aPostTypes', $cPostTypesLibrary->getIDs());

Now to me, this seems almost exactly like the tell me to do in the docs example #4 (About using multiple traits)
The only difference I have is I have the use outside of my class due to getting cannot use class because it is not a trait
What am I missing here?

A: You have to declare the trait inside the class
class postType
{
    use Lib;
}

A: Your class is not using the trait, you are instead using the other use of the use keyword and trying to import the Lib class from the same namespace into, well, the same namespace.
To use traits correctly, go back to the documentation, and look at where they are placed.  The use statement is placed inside of the class definition. In your case, it would look like this:
namespace App\Berry;

class postType
{
    use Lib;
    // ...
}


text:
Q: Placing the text on background image How to place the text, on the background image?

.hero {
 background-image: url("../img/photo.jpg");
}

Welcome to Parallels
Clean Responsive Parallax Theme

A:

This is a caption text

Is this what you are trying do? this pen should do the job https://codepen.io/anon/pen/qMWaXo
.caption {
  position: relative;
  padding: 0;
  margin: 0;
}

.caption img {
   display: block;
   max-width: 100%;
   height: auto;
 }

 .caption:after {
   content: "";
   position: absolute;
   display: block;
   left: 0;
   top: 0;
   width: 100%;
   height: 100%;
   background: rgba(0, 0, 0, 0) linear-gradient(to bottom, rgba(0, 0, 0, 0) 0px, rgba(0, 0, 0, 0.6) 100%) repeat 0 0;
   z-index: 1;
 }

.caption-text {
    display: block;
    position: absolute;
    box-sizing: border-box;
    color: #f1f1f1;
    width: 100%;
    left: 0;
    bottom: 0;
    padding: 1em;
    z-index: 5;
 }


text:
Q: Handling javascript errors in express Suppose I have the following async function
export async function someAsyncFunction() {
  const result = await fetchData();
  return result[0].id;
}

In the route I have
router.post(
  '/some-path',
  handleErrorAsync(async (req: Request, resp: Response, _err: Errback) => {
    const data = await someAsyncFunction();
    resp.json(data)
  })
);

And I have error handling functionalities that do
interface ResponseError extends Error {
  statusCode: number;
}

// Middleware to respond with an error when error caught
export function handleError(
  err: ResponseError,
  _req: Request,
  resp: Response,
  _next: NextFunction
) {
  if (err) {
    resp.status(err.statusCode || 500).json(err);
  }
}

export const handleErrorAsync = (func: Function) => (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  func(req, res, next).catch((error: Error) => {
    next(error);
  });
};

So this works fine if for example fetchData has an error response object, but this fails to print error objects when the error is a regular javascript error and instead it just prints {} with 500 error.
For example in this line return result[0].id; if the result is empty ([]), then this would throw TypeError, which will be caught by the handleError middleware, but then the .json(err) part will show only {}
Is there a way I can get both the servers errors (which are working correctly) and the internal server errors with that same middleware?

A: res.json do  JSON.parse which returns an empty object {}.
I can suggest destructuring the err body.
 resp.status(err.statusCode || 500).json({message:err.message, error:err});

This will give you a message for every Native Error

A: You could extend the toJSON method of Error.

let a = new Error("hi")

console.log(JSON.stringify(a))

Error.prototype.toJSON = function () {
    const alt = {};
    // get all property
    Object.getOwnPropertyNames(this).forEach((key) => {
        alt[key] = this[key];
    });

    // only get message property
    // alt["message"] = this["message"]
    return alt;
}

console.log(JSON.stringify(a))

Then just call res.json(error), and you'll get the property of Error.
Because when you call res.json(parameter), express will trigger the toJSON method of parameter.
You could read more in Is it not possible to stringify an Error using JSON.stringify?
.
But, I recommend only expose the "message" property in toJSON method.

A: I would suggest using res.send() in the error handler like
return res.status(500).send(err.message);

A: I fixed the issue using https://www.npmjs.com/package/serialize-error
import { serializeError } from 'serialize-error';

  if (err) {
    resp
      .status(err.statusCode || 500)
      .json(serializeError(err));
  }


text:
Q: Using ASP.NET MVC form-group with dropdown list? How to make an dropdown list in form-group with method="post"?
The list has to be dynamic, and the parameter send has to be something else from what is shown in label. I was trying something like this:

        Choose category:
        <select class="form-control" id="Product.Category">
@foreach (var category in Model.Categories)
{
            <option>category.CategoryName</option>
}
        </select>

But it doesn't work for me, and I have to send to controller the category Id not category name.
The goal is that:
User selects category from dropdown list, and the Id of category is being send to controller.

A: <option value="@category.Id">@category.CategoryName</option>


text:
Q: Using Spring as a dependency injection framework with play 2.4.x? I am exploring play-scala 2.4.2 and trying to get the spring DI working with it. I see there are a lot of changes in play 2.4.x and old way of overriding the GlobalSettings.getControllerInstance seems to be no more an option.
I came across this project https://github.com/jroper/play-spring, but it seems to be more of a POC proving  that Spring DI is possible but does not seems to be as easy as in earlier play versions. Will this be the spring integration mechanism for current and future play versions or a simpler mechanism or framework can be expected sometime soon from the play community?

A: Please follow the following steps:
Step1: Add the spring dependencies in build.sbt file.
libraryDependencies += "org.springframework" % "spring-context" % "4.1.6.RELEASE"
libraryDependencies += "org.springframework" % "spring-core" % "4.1.6.RELEASE"
libraryDependencies += "org.springframework" % "spring-beans" % "4.1.6.RELEASE"
libraryDependencies += "org.springframework" % "spring-aop" % "4.1.6.RELEASE"

Step2: Create a new class (ApplicationGlobalSettings.java) and that implements with GlobalSettings class.
package com.ranga.global.settings;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import play.Application;
import play.GlobalSettings;
public class ApplicationGlobalSettings extends GlobalSettings {

private static final String APPLICATION_CONTEXT_XML = "applicationContext.xml";
private ConfigurableApplicationContext applicationContext;

@Override
public void beforeStart(Application application) {
    super.beforeStart(application);
}

@Override
public void onStart(Application application) {
    super.onStart(application);
    applicationContext = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT_XML);
}

@Override
public void onStop(Application application) {
    super.onStop(application);
    if(applicationContext != null) {
        applicationContext.close();
    }
}

}
Step3: Create a new spring configuration file under conf folder (applicationContext.xml)
conf\applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

   <context:component-scan base-package="com.ranga.services, com.ranga.daos"/>

</beans>

Step4: Add the newly created GlobalSettings file location to the application configuration file (conf/application.conf).
.....some more configuration here.....
# Global Objects class
application.global=com.ranga.global.settings.ApplicationGlobalSettings

Step5: Create a new service class under com.ranga.service package (HelloWorldService.java).
package com.ranga.services;
import javax.inject.Inject;
import org.springframework.stereotype.Service;

import com.ranga.daos.HelloWorldDAO;
@Service
public class HelloWorldService {

    @Inject
    private HelloWorldDAO helloWorldDAO;

    public String sayHello() {
        return helloWorldDAO.sayHello();
    }
}

Step6: Create a new dao class under com.ranga.daos package (HelloWorldDAO.java).
package com.ranga.daos;

import org.springframework.stereotype.Repository;
@Repository
public class HelloWorldDAO {
    public String sayHello() {
        return "Hello Ranga!";
    }
}

Step7: Finally inject the HelloWorldService in Application.java file.
package com.ranga.controllers;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;

import com.ranga.services.HelloWorldService;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {

    @Inject
    private HelloWorldService helloWorldService;

    public Result index() {
        return ok(index.render(helloWorldService.sayHello()));
    }
}

Step8: Finally modify the index.scala.html file code.
@(message: String)

<h1>@message</h1>

Now done.. run the application.

A: The latest version of Play:
Create the class Global (Old Global than extended GlobaSettings):
@Singleton
public class Global {

    private static final String APPLICATION_CONTEXT = "applicationContext.xml";

    private ConfigurableApplicationContext applicationContext;

    @Inject
    public Global( ApplicationLifecycle lifecycle ) {
        applicationContext = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT_XML);
        lifecycle.addStopHook( () -> {
            applicationContext.close();
            return F.Promise.pure( null );
        });
    }

}

Create the class ConfigurableApplicationContextModule:
public class ApplicationContextModule extends AbstractModule {

    @Override
    protected void configure() {
        bind( Global.class ).asEagerSingleton();
    }

}

In application.conf add this:
play.modules.enabled += "config.ApplicationContextModule"

Create file applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

       <context:component-scan base-package="services, dao"/>

</beans>

After creating what stated above by Ranga

A: Just in case it can help someone, I also worked on a solution that is working based off of jroper's project: https://github.com/jroper/play-spring.
The key was to use spring's scanning feature to "load" the Play classes:
ctx.scan(packages:_*)
with the default play's packages:
def defaultPackages(): Seq[String] = Seq("router", "play", "controllers")
The solution works with 1 hack: you need to add the @javax.inject.Named next to the @Singleton annotations in the Play classes so that Spring can scan them and load them (i.e you need to "fork" the Play version you are using, but it's a rather small and easy change).
So here is my sample app with the SpringApplicationLoader:
https://github.com/remithieblin/play24_spring


text:
Q: SharePoint 2010 Calculated Column in large list throwing error code? I cannot find anything on this error. This calculated column saves ok, but returns -362615635 on select items in a list of about 2500 items. When i go into the item and save (no other changes made) the formula computes correctly. All other calculated columns in the list are calculating correctly. Any help would be appreciated.
=IF(
OR(
    [TypeOfItem]="a"
    ,[TypeOfItem]="b"
    ,[TypeOfItem]="c"
    ,[TypeOfItem]="d/e"
    ,[TypeOfItem]="f"
    ,[TypeOfItem]="g"
    ,[TypeOfItem]="h"
    ,[TypeOfItem]="i"
)
,"Other"
,IF(
    [TypeOfItem]="k"
    ,"One"
    ,IF(
        [TypeOfItem]="(l)"
        ,"Two"
        ,IF(
            [TypeOfItem]="m"
            ,"Three"
            ,IF([
                TypeOfItem]="n"
                ,"Four/Five"
                ,IF(
                    [TypeOfItem]="o (p)"
                    ,"Six"
                    ,IF(
                        [TypeOfItem]="q"
                        ,"Seven"
                        ,"Non")))))))


text:
Q: Trying to reset password but I don't know my Player ID - how do I get this? When I got my reset password email I follow the link to reset. But at the bottom one of the fields required is "PLAYER ID" so I can't reset/play.
What do I do? Where do I get this value from?

A: The Pokemon trainer club website needs date of birth and player id that you entered when you created the account.  The player id is set when you use the Play! Pokemon program.  If you have not done so, the field should be left blank; if you have, the ID is a 7 digit number that was given you when you set up the Play! account.
If you can still login to the PTC website, you can view your profile and select play! on the list to see your player id; if you can't, you'll need to contact support and explain the situation.  email is techhelp@pokemon.com


text:
Q: Local order parameter for confinement in gauge theories I would like some help clarifying what Zinn Justin is saying in his book "Quantum Field Theory and Critical Phenomena" p.805 on detecting confinement of gauge theories.

In particular, I understand Elitzur's theorem just states that there is no such thing as gauge symmetry breaking (since gauge is just a labeling redundancy of the theory).  However I don't understand why I cannot find a local order parameter to detect confinement in gauge theories. I understand local observables cannot be charged (since charged operators don't commute with gauge transformations)
Could someone help understand why I cannot construct some local order parameter to detect gauge field confinement? (with equations would be nice).
I think one difficulty is I don't have a clear definition of what qualifies as a local order parameter.  To prove the statement one would need to define what is a local order parameter.

A: The reason is that non-abelian gauge theories are asymptotically free.  This means that at short distance, one cannot distinguish between the confined and deconfined phase because the gauge interaction turns off.  Therefore it is hard to imagine what kind of local observable could measure the confinement phase transition.
A local order parameter just means any physical observable one can use to detect a phase transition.  It is a somewhat general definition, but phase transitions come in a large variety so it is hard to make a more precise definition.


text:
Q: How to run a K6 script locally and send data to remote InfluxDB instance (No Docker) I'm extremely new at k6 + influxdb + grafana, and I was given a task related to execute certain K6 Scripts locally but save/pass the data over a remote InfluxDB instance.
As of now I'm having issues given that I'm not sure what I'm missing regarding the needed configurations in order to do this since everytime I try to run the script pointing at the InfluxDB instance I'm just getting an error everytime I run it:
The command that I'm executing is:
k6 run --out influxdb="https://my_influxdb_url/write" //sampleScript.js
But the original URL that was handed over to me was something like this:
https://my_influxdb_url/write?db=DB_NAME&u=USERNAME&p=PASSWORD
And when I execute the first mentioned script I'm getting the following error:
ERRO[000X] Couldn't write stats           error="404 page not found\n" output=InfluxDB1
So I've tried creating K6_INFLUXDB_USERNAME and K6_INFLUXDB_PASSWORD as environment variables but I'm still getting the same error.
I'm not sure if I might be missing some .yaml file like a datasource in which I should fill those 3 values? (DB_NAME, USERNAME, PASSWORD)
Or maybe I'm just doing it all wrong and not calling the execution command properly for this scenario.
Another weird thing that I noticed is that OUTPUT is throwing InfluxDB1 instead of my actual InfluxDB url which I guess might be where my issue lies.
Any kind of tip would be greatly appreciated since the actual documentation that I've found so far is always run either on a Docker container instance of Grafana+InfluxDB or simply running it locally which is not my case :(
Thanks a lot in advance as always!!


text:
Q: Loudly is Complement or adverb/adjunct in the sentence The cat / scratched / loudly Loudly is mentioned as Complement when it is actually an adverb or adjunct in the site, http://changingminds.org/techniques/language/syntax/clause_arrangement.htm . Is it right or wrong?
I have given the following based on my understanding. Is it correct?
The cat / scratched – S / V
The cat / scratched / the door – S / V / O
The cat / scratched / loudly – S / V / A
The cat / scratched / at six o'clock – S / V / A
The cat / gave / the door / a scratch – S / V / IO / DO
The cat / scratched / the door / loudly – S / V / O / A
The cat / scratched / the door / at six o'clock – S / V / O / A
The cat / scratched / the door / soft. – S / V / O / C
The cat / can scratch / in straight lines. – S / V / C

A: Your answer is correct.
Complements can be either subject complements (in which case they follow a stative verb) or object complements (in which case they follow the direct object). A subject complement is required to complete the verb. In the example they give, it's a transitive verb and nothing is required to complete it. "The cat scratched" would be a complete sentence, so "loudly" is an adverb in "The cat scratched loudly".

A: We can not blindly classify a word, phrase or a clause as an adverb or complement. It purely depends upon the IDEA we wish to convey. If our idea is to tell WHAT did the cat do, then, "the cat scratched" is enough. In this case, "loudly" is an adverb (adjunct). Even though it is removed, still the sentence leaves the meaning we want to convey. But, our intention is to tell HOW did the cat scratch, then, the word "loudly" plays the role of a complement. If it is removed from the sentence, it can not convey what we wished.


text:
Q: How to read different linear algebra notations I always get confused by different notations in linear algebra. For example, I find that this is clear and I can follow everything that is going on by the rules of matrix multiplication
$$
A = U \Sigma V^T
$$
But sometimes I see a notation like this...
$$
A = U \Sigma V^T = u_1 \sigma_1 v^T_1 + u_1 \sigma_1v^T_1 + ... + u_r \sigma_r v^T_r
$$
and I find it really confusing to understand by looking because its not immediately obvious to me if the subscripts are columns or rows and if the result of these additions are vectors or matrices... How can I read the notation on the right of this equation?
Even worse is the summation notation which makes it even harder to see and would look something like this...
$$
A_{ij} = \sum \sum \sum \text{confusing}_{ij} \text{subscript}_{ji} \text{hell}_{ijk}
$$

A: For the SVD, you can read it as
$$ A = U \Sigma V^{T} = \sum_{i=1}^{r} \sigma_{i} u_{i} v_{i}^{T} $$
as a matrix $A$ is actually the sum of $r$ rank $1$ matrices $u_{i}v_{i}^{T}$ which have a scaling factor of $\sigma_{i}$.
The matrix $u_{i}v_{i}^{T}$ is the matrix generated as the outer product of the two vectors $u_{i} , v_{i}$


text:
Q: Understanding surface area of a revolution/length of curve I don't quite understand why the formula to find the surface area of a revolution is what it is:
$$A = 2\pi \int_a^b x\ \sqrt{1 + \left(\frac{\text{d}y}{\text{d}x}\right)^2}\ \text{d} x.$$
I would've though that A could equal: $A = 2\pi \int_a^b y\ \text{d} x$.
     .
    /|
ΔS / | Δy
  /  |
 /___|
  Δx

I've looked at proofs but I don't really understand why  $\Delta s\to 0$ and not  $\Delta x\to 0$. I would've thought that as $\Delta x\to 0$ (or  $\Delta y\to 0$) you'd end up with a slice infinitelly small, and it wouldn't have a slope to it, then I would've though that you could add up the perimeter of these 'slopeless' slices, and get the surface area.
I'd would help if I could geometrically see what is going wrong with letting  $\Delta x\to 0$ (or  $\Delta y\to 0$).
More specifically, if I just go $2\pi y$, what am I not taking into account (graphically).
I know this is like the arc length (length of a curve) formula, I have the same grievance with that.
Thank you.


text:
Q: MPMoviePlayerController sometimes plays audio, not video when fading in I've got an issue where, in a UIScrollView I have a number of views (videocontrollers in the below) which act as pages for video content (initially a thumbnail view is shown).
Sometimes (but not always) when I scroll to the next page, the audio for the video starts playing but I get no visual. This doesn't seem to happen when I'm not fading the view in.
Video init code is:
  MPMoviePlayerController* moviePlayer = [[MPMoviePlayerController alloc] init];

  self.moviePlayer = moviePlayer;

  [moviePlayer setControlStyle:MPMovieControlStyleNone];
  [moviePlayer setRepeatMode:MPMovieRepeatModeOne];
  [moviePlayer.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

  moviePlayer.backgroundView.backgroundColor = [UIColor clearColor];
  moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
  moviePlayer.contentURL = [NSURL URLWithString:[videoData.video src]];

  [self.videoController.view addSubview:self.moviePlayer.view];
  [self.videoController.view bringSubviewToFront:moviePlayer.view];
  [moviePlayer.view setAlpha:0.0f];

  // Movie Observer
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkMovieStatus:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil];

  // Add tap handler
  UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onPlayerTapped:)];
  singleFingerTap.numberOfTapsRequired = 1;
  singleFingerTap.delegate = self;
  [self.moviePlayer.view addGestureRecognizer:singleFingerTap];

  [moviePlayer prepareToPlay];

And play code (to try to avoid black flash at the start of the video) is:
- (void)checkMovieStatus:(NSNotification *)notification {
    if(self.moviePlayer.readyForDisplay && (MPMovieLoadStatePlayable | MPMovieLoadStatePlaythroughOK)) {

          [self.moviePlayer play];

          [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerLoadStateDidChangeNotification object:nil];

          [UIView animateWithDuration:0.4f animations:^{
              [self.moviePlayer.view setAlpha:1.0f];
          } completion:^(BOOL finished) {
              //[self.moviePlayer play]; // tried here as well
          }];
        }
}

Code to remove video view on scroll is:
- (void)removeMoviePlayer {
        if(self.moviePlayer) {
                [self.moviePlayer stop];

                [self.moviePlayer.view removeFromSuperview];

                self.moviePlayer = nil;
        }
}

A: I found a rather strange fix to this problem. In my case I would swipe to the video and the audio would play and there would be no picture. If I swiped away and came back, everything worked fine so just for the fun of it I tried this
MPMoviePlayerController *mp = [self.arrayOfScrollView objectAtIndex:xx];
[mp play];
[mp stop];
[mp play];

Strangely that worked. Since you posted this six months ago, if you found another workaround, I'd love to know it.


text:
Q: How I unlink deleted global package? I had linked one package with the command npm link inside the package folder and then I delete it and I can't unlink the package from npm global list.

A: If you run npm -g list --depth=0 you will see the broken path right?
Suppose the deleted package folder named demolib.
Create new folder with the same name like previous demolib
Run inside the folder npm init -y to create package.json  file.
Then, inside the folder run npm unlink and npm will removes the broken symbolic link from global npm list


text:
Q: Error: 'PRIMARY' filegroup is full We have increased disk space on the SQL Server, and there is definitely enough space on the server, yet below error is raised:

com.softmar.fileserver.WebFileException: com.microsoft.sqlserver.jdbc.SQLServerException: Could not allocate space for object 'dbo.WebFileImage'.'pkWebFileImage' in database 'sslFileServer' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.

The properties of the database shows that there is only 1.1 MB available, yet other databases on the same SQL server shows much more space available on the properties.  So why is only this database not accommodating the disk size increase?  Looking at the file settings it is set to unrestricted growth.
This is rather critical so will appreciate your swift response.

A: add a file to your database and set it's filegroup to primary.


text:
Q: Adding qdisc under the mq top-level qdisc This LWN article suggests that one may add/replace the network scheduler for a queue "under" the mq "dummy scheduler."  These two point to that end:
The mq scheduler does two things:

- present device TX queues as classes, allowing to attach
  different qdiscs to them, which are grafted to the TX queues

- present accumulated statistics of all device queue root qdiscs

I would appreciate being schooled on how to do this.  I've tried many combinations.  For example, from this listing of the default (CentOS 7.6):
# tc qdisc show dev eth2
qdisc mq 0: root
qdisc pfifo_fast 0: parent :8 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent :7 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent :6 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent :5 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent :4 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent :3 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent :2 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent :1 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1

I've tried many variations trying to experiment with grafting different schedulers under mq.  Here are some attempts:
# tc qdisc add dev eth2 parent 0:1 fq_codel target 1ms interval 10ms quantum 9014
RTNETLINK answers: No such file or directory
# tc qdisc add dev eth2 parent 0:1 handle 1: fq_codel target 1ms interval 10ms quantum 9014
RTNETLINK answers: No such file or directory

Would anyone know the magic to put different schedulers under mq than only pfifo_fast?  One point that is highly frustrating is that the manual page, and many internet articles, reference root and parents regarding the schedulers and queues.  However, none do an adequate job in describing, from the output I have above from the tc qdisc show dev eth2 command, what is the root and which are the parents.  I'm guessing, but my guesses seem to be far off.

A: The kernel's default reserved handle 0: can't be referenced correctly (as major value 0: ). You have first to (re)install the qdisc root mq, using a valid handle (ie: not 0:):
# tc qdisc add dev eth2 root handle 1: mq

Which now should give you this:
# tc qdisc show dev eth2
qdisc mq 1: root
qdisc pfifo_fast 0: parent 1:8 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent 1:7 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent 1:6 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent 1:5 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent 1:4 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent 1:3 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent 1:2 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
qdisc pfifo_fast 0: parent 1:1 bands 3 priomap  1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1

You can now run your commands as intended using parent 1:1 instead of 0:1 etc.


text:
Q: Lebesgue-Radon-Nikodym: How to write $\bigcup_n (A_n \cap B_n)$? I am learning measure theory and often it helps to know some (basic) set theory. For e.g. one can write union of measurable sets as a disjoint union and then use countable additivity of the measure.
I am reading the proof of special case of Lebesgue-Radon-Nikodym theorem from Folland:
We have two $\sigma$-finite measures $\mu$ and $\nu$ on $X$ and the space $X$ is written as $X=\cup_n E_n=\cup_n F_n$ of increasing union with both $\mu(E_n)$ and $\nu(F_n)$ finite for all $n$. From here, we want to write $X=\cup_n X_n$ where $X_n$ are disjoint with both $\mu(X_n)$ and $\nu(X_n)$ finite for all $n$
I think $X_n= (E_n\cap F_n)\cap {G_n}^c$, where $G_n=(\cup_{k=1}^{n-1} (E_k \cap F_k))$. Clearly $X_n $ are disjoint. But how do I show that $\cup_n X_n=X$?
In general, what is $\cup_n (A_n \cap B_n)$?


text:
Q: File INPUT returning mangled file body in windows browsers but not mac I am reading the files within a file INPUT. When I run my code, in the file.body, I get the correct content which is just a text/csv in any browser on Mac OS X. But, on any browser in Windows 7, the file.body comes through base64 encoded. And, if I create a .txt file with the same content copied from the .csv, the file body is not base64 encoded.
How can I get the browsers on windows to return a non-base64-encoded file.body?


text:
Q: footnotesize in tables How to write footnote in tables please? I would like to give [1] in cell, which is link to text below the table. Thank you
\documentclass{article}
\usepackage{array}
\usepackage{makecell, multirow, booktabs}
\usepackage{caption}
\begin{document}

\begin{table}[h]
\centering
\caption{title}
\footnotesize\setlength{\extrarowheight}{2pt}
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|}
    \hline
    \multicolumn{3}{|c|}{[1]} & \multicolumn{2}{c|}{C} & R & \multicolumn{3}{c|}{P} \\
    \hline
    \multicolumn{3}{|c|}{} & \multirow{2}{*}{~}& &  & \multicolumn{3}{c|}{}\\
    \cline{1-3} \cline{7-9}
    & & & & & & & & \\
    \hline
    col1 & col2 & col3 & col4 & col5 & col6 & col7 & col8  &col9 \\
    \hline
\end{tabular}
\label{table}

\end{table}
 \multicolumn{9}{\footnotesize Čísla }
\end{document}

A: *

*it is not very clear how you like to have your footnote

*with \threepartttable you can obtain the following:

\documentclass{article}
\usepackage{booktabs, makecell, multirow, threeparttable}
\usepackage{caption}

\begin{document}
    \begin{table}[ht]
\centering
\caption{title}
\label{tab:mythreeparttable}
\footnotesize                       % used font size
\setlength{\extrarowheight}{2pt}
\begin{threeparttable}
\begin{tabular}{| *{11}{c|} }
    \hline
\multicolumn{3}{|c|}{A\tnote{a}} & \multicolumn{2}{c|}{C} & R & \multicolumn{3}{c|}{P} \\
    \hline
\multicolumn{3}{|c|}{} & \multirow{2}{*}{~}& &  & \multicolumn{3}{c|}{}\\
    \cline{1-3} \cline{7-9}
    & & & & & & & & \\
    \hline
    col1 & col2 & col3 & col4 & col5 & col6 & col7 & col8  &col9 \\
    \hline
\end{tabular}
   \begin{tablenotes}[para,flushleft]
    \item[a] text of the footnotes
    \end{tablenotes}
\end{threeparttable}
    \end{table}
\end{document}

if you like to have footnote marks in brackets, than add in preamble
\renewcommand\tnote[1]{\textsuperscript{[#1]}}

and you will obtain:

edit: in case that you like to have normal font size in table and only footnotes with \footnotesize fonts, than move command \footnotesize from the beginning of table to `table notes (see @Mico comment):
\documentclass{article}
\usepackage{booktabs, makecell, multirow, threeparttable}
\renewcommand\tnote[1]{\textsuperscript{[#1]}}
\usepackage{caption}

\begin{document}
    \begin{table}[ht]
\centering
\caption{title}
\label{tab:mythreeparttable}
\setlength{\extrarowheight}{2pt}
\begin{threeparttable}
\begin{tabular}{| *{11}{c|} }
    \hline
\multicolumn{3}{|c|}{A\tnote{a}} & \multicolumn{2}{c|}{C} & R & \multicolumn{3}{c|}{P} \\
    \hline
\multicolumn{3}{|c|}{} & \multirow{2}{*}{~}& &  & \multicolumn{3}{c|}{}\\
    \cline{1-3} \cline{7-9}
    & & & & & & & & \\
    \hline
    col1 & col2 & col3 & col4 & col5 & col6 & col7 & col8  &col9 \\
    \hline
\end{tabular}
   \begin{tablenotes}[para,flushleft]\footnotesize
    \item[a] text of the footnotes
    \end{tablenotes}
\end{threeparttable}
    \end{table}
\end{document}


text:
Q: Executar música no programa em C Preciso executar uma musica durante a execução de um programa em C. No Windows podemos fazer assim - caso o arquivo esteja no mesmo diretorio do programa:
#include<stdio.h>
#include<stdlib.h>
int main (){

  system("start music.mp3");
  return 0;
}

o arquivo será executado. vocês sabem qual o equivalente em unix? pesquisei mas não consegui passar os parâmetros corretamente para as funções da biblioteca , que possivelmente faz isso: https://www.cs.cf.ac.uk/Dave/C/node22.html

A: A resposta abaixo considera a utilização de um programa via linha de comando, como feito na pergunta (para o Windows). Uma outra abordagem seria utilizar uma biblioteca em C para tocar o MP3. Certamente existe alguma.
O primeiro passo é instalar um tocador de MP3 que possa ser acionado pela linha de comando. Existem vários, um deles é o mpg123.
Caso você esteja numa distribuição baseada no Debian, você pode instalar o mpg123, assim:
sudo apt-get install mpg123

Feito isso, você chama ele via linha de comando:
mpg123 nomeDaMusica.mp3 &

O & no da linha serve para que sua linha de comando não fique travada aguardando o retorno do comando.
No seu código C, você faz assim:
#include<stdio.h>
#include<stdlib.h>
int main (){

  system("mpg123 Rachmaninoff\\ -\\ Prelude\\ in\\ C-sharp\\ minor.mp3 &");
  return 0;
}

Note que o nome do arquivo MP3 é: Rachmaninoff - Prelude in C-sharp minor.mp3
Entretanto, para o bash lidar com espaços é necessário usar o caracter de quebra \.


text:
Q: Adding a key, value to a dict, but I didn't tell it to? I'm working on some game code in python 3.7. I'm using a lot of dictionaries to store various data, and at one point I needed a new dictionary to store certain values from one dictionary as keys in other dictionaries. When I ran the code, I ended up with a value in my new dictionary that I can't figure out why it got in there.
Example:
data = {'value1': 4, 'value2': 'hello'}
target = {'value1': 3}

def fillTarget(info, times):
    for key, value in info.items():
        if key == 'value2':
            target[key] = value
            target[value] = times
        else:
            for _ in range(times):
                target[key] = target[key] + info[key]

fillTarget(data, 4)

When I print(target), I end up with:
{'value1': 19, 'value2': 'hello', 'hello': 4}

Why am I getting 'value2' as a key, value in (target)? Isn't line 6-8 telling it to add the value as a key, but then the else: should not transfer the key to (target)?

A: You are adding two items to dictionary
target[key] = value //{'value2': 'hello'}
// and
target[value] = times //{'hello': 4 }
//where key = 'value2', value = 'hello' and times = 4

Click Here to get more details on how to add items to dictionary in python.


text:
Q: Dynamic log level changes with Logback in a docker app Logback has a feature to scan changes in logback.xml (per this) - this is a great feature which allows long running applications to be shipped with INFO as default level to be changed to DEBUG when something has to be briefly investigated.
But in my recent app (hosted on my company's K8s cluster as a Docker container), am unable to use the above feature because:

*

*dont yet have the provision to host external volumes wherein I can put my logback.xml (to be changed by developers during debugging)

*dont yet have the provision to change environment variables in a running container without a restart

*dont have a JNDI server to map log variables

Given this, is there a way I can build a provision for developers to change the logging level of my application at runtime without an app/container restart?

A: I'm not sure if you're also forbidden to mount configmap into a container, as you haven't mentioned it.
But on the off chance that you're not, you can create a configmap:
apiVersion: v1
kind: ConfigMap
metadata:
  name: logback-conf
data:
  logback.xml: |
    <configuration>
      <root level="debug">
        <appender-ref ref="STDOUT" />
      </root>
    </configuration>

And add it to the container, as follows:
  containers:
    - name: app
      volumeMounts:
      - name: config
        # The conf will be mounted at /app/logback.xml
        mountPath: /app
...
  volumes:
    - name: config
      configMap:
        name: logback-conf

If you aren't allowed to even inject a configmap (which to my knowledge doesn't cause downtime), there's really not much you can do

A: I have a similar problem: I need to change the application log level at runtime without restart the spring boot application. In my situation, I'm not working in a docker context, but I think the solution to our problem is the same.
After research I found 3 possible solutions:

*

*change log file at runtime

*enable JMX and work with JConsole to change log levels

*use Spring Boot Admin.

The 3 solution is the best, if your app is a Spring Boot app. You can read the following tutorial Changing the logging level at runtime.

You can found an example how to enable the Admin interface on Github.


text:
Q: Mysql run a script in many database I have an application with many identical databases. I need to create an sql update script to alter all these databases.
There is a databases index table with all databases stored in the Mysql istance:
create table db (dbname varchar(64), active tinyint);
insert into db values ('db1',1),('db2',1),('db3',1);

I need to run an alter script for each database in that list. So i need something like a foreach of previus select and run a "use db" before the alter command.
Something like this but in sql:
foreach(db in "select dbname from db"){
   use db;
   alter table1 ....;
}

A: You can create another database to hold other database records. Database name, username, passwords, IPs etc. And then you can query from that database and use a foreach loop.


text:
Q: XtraGrid binding inherited object I have one base class and 2 inherited classes. According configuration of application must bind Customer1 or Customer2 to XtraGrid:
public abstract class MyBase
{
    public int ItemID { get; set; }
}

public class Customer1 : MyBase
{
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
}

public class Customer2 : MyBase
{
    public string Name { get; set; }
}

Now, binding code:
    Customer1 c1 = new Customer1();
    c1.ItemID = 1;
    c1.Name = "N1";
    c1.BirthDate = DateTime.Now;

    BindingList<MyBase> tmpList = new BindingList<MyBase>();
    tmpList.Add(c1);

    gridControl1.DataSource = tmpList;

But grid display only ItemID field which is derived from MyBase class.
Could you pls help?
Thanks.

A: The simple answer is - you cannot do that. This is not a specific to the XtraGrid, but to all controls that use list data binding. When you use List<T>, BindingList<T> etc. the typeof(T) is extracted and used as item type to retrieve bindable properties. Note that none of these classes (and IList<T> in general) supports variance, so you cannot use the base class as a generic parameter. Just use the concrete class when instantiating List/BindingList which you plan to use as a data source (in your case - BindingList<Customer1> or BindingList<Customer2>).

A: You are only seeing the ItemID field in your grid because you have added the base class MyBase as the type to your BindingList.
You should change the type of the BindingList to either Customer1 or Customer2 in your code.
Customer1 c1 = new Customer1();
c1.ItemID = 1;
c1.Name = "N1";
c1.BirthDate = DateTime.Now;

BindingList<Customer1> tmpList = new BindingList<Customer1>();
tmpList.Add(c1);

gridControl1.DataSource = tmpList;

Using the base class MyBase is restricting the view on the Customer class to just what is available in the base class. So the grid can only see the ItemID field.
You will not be able to bind a collection of both Customer1 and Customer2 types to the grid. You need to rethink your solution. You could possibly create a class which contains all the fields from Customer1 and Customer2 (lets call this Customer) and also add an additional field, possibly an enum, that sets the Customer Type (ie. Customer1 or Customer2). Then you can create a binding like this:
public enum CustomerType
{
    Customer1,
    Customer2
}

public class Customer
{
    public int ItemID { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
    public CustomerType Type {get; set; }
}

Customer c = new Customer();
c.ItemID = 1;
c.Name = "N1";
c.BirthDate = DateTime.Now;
c.Type = CustomerType.Customer1;

BindingList<Customer> tmpList = new BindingList<Customer>();
tmpList.Add(c);

gridControl1.DataSource = tmpList;

You grid will then be able to display all the fields you are interested in.

A: Thanks for your time.
I just tried UnBound column type and resolved issue.


text:
Q: exclude a folder and match all .html pattern files in a root folder using regex i need to write a regex which match all .html files from all the folder except images folder.
Below is format of html files
/magazines/sample.html
/test/index.html
/test/format_ss1.html
/test/folder/newstyle_1.html
/images/two.html

i need to get only first 2 html files i.e., we are exluding files which ends with '_[0-9]' and '_ss[0-9]' and .hmtl files in images folder.
i have successfully done by excluding 3 and 4 but i can't able to excule .html files in images folder.
$regex = '/[a-zA-Z0-9\-][^_ss\d][^_\d]+\.html/'; //this will do for 3 and 4 files

but i need to exlude images folder..
i have tried like
$regex = '/[^images\/][a-zA-Z0-9\-][^_ss\d][^_\d]+\.html/'; // not working

can some one help me out this..

A: Have a try with:
~^(?!/images/)[a-zA-Z0-9/-]+(?!_ss\d|\d)\.html$~

in action:
$arr = array(
'/magazines/sample.html',
'/test/index.html',
'/test/format_ss1.html',
'/test/folder/newstyle_1.html',
'/images/two.html'
);
foreach($arr as $str) {
    if (preg_match('~^(?!/images/)[a-zA-Z0-9/-]+(?!_ss\d|\d)\.html$~', $str))
        echo $str,"\n";
}

output:
/magazines/sample.html
/test/index.html


text:
Q: Setting page title and keywords from PHP code does WP offer any functions which can be used to set the page title and/or keywords from the PHP/Controller level?
I'm basically looking for something like the wp_enqueue_style() function, which results in changes to the HTML page header but for the title and keywords fields. I have some PHP code which dynamically retrieves/builds the page title and would like to avoid having to alter my theme/templates to display this.
Greetings/Thanks
Robert

A: You can use the wp_title filter to modify the HTML document title, and you can use the wp_head action to hook in a custom HTML meta link. e.g.:
<?php
function wpse46249_filter_wp_title( $title ) {
    // $title contains the default document title
    // output by WordPress. Modify it here however
    // you want.
    $some_custom_title_content = 'CUSTOM TITLE CONTENT HERE';
    // Now append it to the default
    $custom_title = $title . $some_custom_title_content;
    // Then return the result
    return $custom_title;
}
add_filter( 'wp_title', 'wpse46249_filter_wp_title' );

function wpse46249_add_meta_link() {
    echo '<meta name="keywords" content="INSERT KEYWORDS HERE" />';
}
add_action( 'wp_head', 'wpse46249_add_meta_link' );
?>

These callbacks can be added to a Plugin, to keep them safe from Theme switching.
For further reference, I would recommend taking a look at how the popular SEO Plugins implement these extensions.


text:
Q: why do we use big-$O$ in solving recurrence relations Solving recurrence by substitution, first guess $f(n)$ then prove $T(n)=O(f(n))$.
For example, $T(n)=2T(n/2)+n$. My guess $f(n)=n\lg n$, and then I prove it by induction that $T(n)=O(n\lg n)$.
What is confusing is why do we use big-$O$ to solve the recurrence? I mean, I can prove that $T(n)=O(N^2)$, but that doesn't solve the recurrence, we should've used big-theta instead since it's a tight bound. What am I missing?

A: Let $f = O(x)$. It is obvious that $f = O(x^{c})$ and $f=O(c^{x})$ for $c>1$ and in general case $f=O(y)$ for $\forall y>x$, but in the theory of computing we consider always the lowest possible bound.
In your example, $f=O(n\log{n})$. $f=O(x)$ for $x>n\log{n}$, too. But we consider the lowest bound that is $n\log{n}$.
For $\Theta$, we say $f=\Theta(x)$, we must show two things: $f=O(x)$ and $f=\Omega(x)$.

A: I think that this in some sense depends on the context in which you're working. So if, for example, you were in an introductory computational complexity course, one motiviation for using $O$ notation instead of $\Theta$ notation is that your professor may want you to be able to step through the process more slowly and recognize that the ability to use $\Theta$ necessarily depends on $O$ and $\Omega$, on both the upper and the lower bounds.
Another possible reason is that you wish to find the lowest possible upper bound, not just any upper bound; as Hasan Heydari pointed out, it matters most how slow the algorithm can possibly. This is because the big question in computational complexity is to see whether or not a whole big class of problems called $NP$ have algorithms with polynomial upper bounds. In this regard, we don't necessarily care $\Omega$ what the lower bound for the running time is, and thus don't necessarily care about the more exact running time $\Theta$.


text:
Q: how to get the x labels to be in the same order?
how to get the x labels to be in the same order?
i want the x labels to be in the same order.
in the top and bottom pictures, the order of 'Ya' and 'Tidak' is different

A: Use order as parameter of sns.countplot:
x_order = sorted(data['Polydipsia'].unique())

sns.countplot(data['Polydipsia'], hue=data['Kelas'], order=x_order)


text:
Q: Trying to removed unused imports with a pre-commit hook but imports that are being used are getting removed I just installed eslint-plugin-unused-imports. When I commit, it does all its linting work and removed a bunch of imports even though many of those imports are being used in the file.
May or may not be worth noting, this project has a bunch of legacy Backbone and newer React components, with some Backbone views rendering React components. Also, this is a JS not TS project.
eslint-plugin-unused-imports issues states:
https://github.com/sweepline/eslint-plugin-unused-imports/issues/new?assignees=&labels=&template=bug_report.md&title=

If the issue is with something being marked wrongly as a unused import
and therefore being removed. It is an issue with the imported package
(@typescript-eslint/eslint-plugin for TS or eslint for JS) and its
no-unused-vars rule. I cannot do anything about this except updating
if a fix is made upstream.
If new rules are added no-unused-vars upstream which should be
autofixed, mark your issue rule addition.

But I'm not sure how to address this.
Below is my linting setup:
"devDependencies": {
    ...
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^10.0.1",
    "eslint-config-prettier": "^6.15.0",
    "eslint-import-resolver-webpack": "^0.13.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^2.2.3",
    "eslint-plugin-node": "^9.1.0",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-promise": "^4.3.1",
    "eslint-plugin-react": "^6.10.3",
    "eslint-plugin-standard": "^4.1.0",
    "eslint-plugin-unused-imports": "^1.1.0",
    ...
    "prettier": "^2.2.1",
    "prettier-eslint": "^9.0.0",
    "prettier-eslint-cli": "^5.0.0",
    "prettier-stylelint": "^0.4.2",
    ...
    "stylelint": "^9.8.0",
    "stylelint-config-prettier": "^4.0.0",
    "stylelint-config-standard": "^18.0.0",
    "stylelint-prettier": "^1.1.2",
    ...
  },
  "peerDependencies": {
    "eslint": ">=6.0.1",
    "eslint-plugin-import": ">=2.18.0",
    "eslint-plugin-node": ">=9.1.0",
    "eslint-plugin-promise": ">=4.2.1",
    "eslint-plugin-standard": ">=4.0.0"
  },
  "lint-staged": {
    "src/**/*.{js,json,jsx,scss}": [
      "node ./scripts/lint-prettier.js"
    ],
    "*.{js,jsx,json,md}": [
      "prettier --list-different"
    ]
  },
  ...
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged && npm test"
    }
  }
}


text:
Q: python request get url with predefined cookies and session id from chrome browser I fetch some header and values as below
accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9

    user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36

    cookies:_gcl_au=<some number>; _ga=<some number>; _gid=<some string>;
            csrftoken=<some string>; sessionid=<some string>

I want to fetch (HTTP GET)same url using python request library and use same cookies and session id. My csrftoken and sessionid is already defined that I want to use for requests.get . Is it possible and if yes then how to do it?
Thanks