text:
Q: How to apply on click action on images in javascript/jquery? I have a fiddle which I have replicated by seeing the screenshot below:

At this moment, I am able to replicate everything in fiddle from the design.
The snippets of CSS codes which I have used in order to align images in a straight line are:
 .product-contents
 {
 display: flex;
 justify-content: space-between;
 align-items: center;
 padding: 1rem;
 }

Problem Statement:
In the fiddle, now if I click on any square images from the screenshot (Franchise Hub,Business Analytics, Tech Support, etc) apart from the Cloud Based & Mobile Image then A TV screen image(means a different image) should appear as present in the fiddle.
And if I click on Cloud Based and Mobile image then a phone image should appear (as shown in the current screenshot above)
I am not sure how to apply that logic. I am pretty sure I need to use Javascript but I am not sure how to use that.

A: Give your images unique id and hide all but one default details image. Then you attach event handler to each div that toggles image visible attribute based on id.
$('.sections').on('click', function(e) {
     val section = e.target.id;
     $('.sections').hide(); // hide all sections
     $('#' + section).show(); // display only clicked one
 });

A: Just a quick glance of what you can do. Set event listener that will listen for click on the mentioned images and then, inside of the passed callback function, change the css properties of another element using element.style.cssProperty such as display to change it from none to block.

const cbBtn = document.querySelector('div#cloud');
const container = document.querySelector('div.container');

cbBtn.addEventListener('click', event => {
  container.style.display = 'block';

  cbBtn.className = 'active';
});
div#cloud {
  width: 100px;
  height: 100px;
  border-radius: 20px;
  border: 1px solid black;
  line-height: 100px;
  text-align: center;
}
div#cloud:hover {
  background-color: green;
  color: white;
}
div.container {
  width: 100%;
  height: 200px;
  background: #ccc;
  display: none;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  line-height: 200px;
}

.active {
  background-color: green;
  color: white;
}

  Cloud Based

  CONTAINER CONTENT


text:
Q: prompt user for password on windows 7 start up and log on in java I want to prompt user for password whenever user starts windows system or when ever user logs in to windows system, is there any way to capture windows start up event in java?

A: No, I, unfortunately, do not think this is possible. Your Java application has to be called by Windows when it starts. Java doesn't really have the ability to 'start' other things like this.
Option 1:
One option you have is packaging your application in a jar or executable. Then, check out these directions. You basically want to create a shortcut in the start directory to point to the application. This is only really good if you have a dedicated application already created.
Option 2:
What I would do is try to launch a .bat file on startup. This can be achieved by doing the following:

start > all programs > right-click startup > open > right click batch file > create shortcut > drag shortcut to startup folder

And the batch file would look something like:
java -jar application.jar

I hope this helps you!

redpajama_set_name: RedPajamaStackExchange


text:
Q: RAM optimized for AMD systems? I've been told by G.Skill, that my RAM is actually optimized for Intel systems. Is this even possible?
By now, I'm also looking for new RAM, and would like to know if there are any brands or types that are AMD optimized?

A: It is possible. AMD and Intel have similar instruction sets for most operations. However, they each have their own 'optimised' instructions for doing particular things. Saying that their RAM is optimised for one chipset or another means that is supports these extended instruction sets. G.Skill makes RAM that works in both systems, though one model might work better in Intel systems while another model works better in AMD systems.
The best thing you can do is to look up what RAM is supported/recommended by your motherboard manufacturer. Check the documentation or manufacturers website for specific information.


text:
Q: How to access a node server located on a virtual machine from the host pc? I have a simple node server running in a Virtual machine , using windows server 2012 .
I want to access the server from my host pc which has Windows 10 pro OS.
I can access the server from the guest pc by using :
http://localhost:8081/customer

in the browser.
I have tried to find the IP address of the VM by using the ipconfig and arp commands but the IP address i got doesn't work (can t get a response)
I have tried specifying inbound and outgoing rules for the specific port in the Windows Server Firewall but the result was the same .
Finally i switched the firewall OFF but i still can't get a result . I m a newbie on servers and networks so I m sure i miss something
Any suggestions ?

A: The first thing you have to check is, what your Network Adapter Settings of your virtual machine are.
If they are configured as NAT at will get a little more complicated.
You can set it on Bridge mode. Bridge mode will act, as the VM is connected directly to your Network. This will only work, if you have access to a network on your host.
Because images explain more than words:
Here is the picture which explains everything very good
If you are running in NAT mode, you have to do Port forwarding. I would suggest you, to use Bridge mode because it is easier.
If you don't know, you can find out the ip via cmd ipconfig


text:
Q: How remove  and  from the_excerpt()? I have a short description by post but when I try to display description wordpress adds
 or
 or , how remove? Look at this pic:

and my code is that:

             <?php echo the_excerpt (); ?>

A: strip_tags seems to be what you're looking for:
<?php echo strip_tags(the_excerpt()); ?>

A: The answer is here. Maybe it will be useful for someone.
get_the_excerpt()

A: <?php
$myExcerpt = get_the_excerpt();
$tags = array("
", "
");
$myExcerpt = str_replace($tags, "", $myExcerpt);
?>

<?php   echo $myExcerpt; ?>

A: This way I implemented it myself and it worked.
<?php echo strip_tags(get_the_excerpt());?>


text:
Q: Bootstrap grid and span I'm having trouble getting span and the grid working properly on my bootstrap homepage.  I want "contact" and "Store Hours" to sit side by side at span 6 each, but they're going under each other at the width of the hero unit above it that holds info. How can I get the span to take hold?
home.html

Welcome

            //fill with store info

 Contact

 314.555.3000

 100 St. Louis Ave

 Store Hours

 Monday - Thursday // 10:30 AM to 8:00 PM

 Friday - Saturday // 10:30 AM to 9:00 PM

 Sunday // Closed

stylesheet.css
.hero-unit {
    text-align: center;
    background-color: #99CCFF;
    margin: 90px;
    padding: 20px;
    font-size: 11px;
    line-height: 1.4em;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    box-shadow: 1px 1px 10px #444;
    border-color: #3399FF;
}

A: Mmmhhh, if I'm not mistaken bootstrap classes are: "col-md-6" or "col-lg-6" , etc
Also, you need to wrap the colummns in a "row"
You should try something like:

Also, you are closing 1 div too many, the
 at the end

A: Try this for Bootstrap 3:

Welcome

                //fill with store info

 Contact

 314.555.3000

 100 St. Louis Ave

 Store Hours

 Monday - Thursday // 10:30 AM to 8:00 PM

 Friday - Saturday // 10:30 AM to 9:00 PM

 Sunday // Closed

else Bootstrap 2 :

Welcome

                //fill with store info

 Contact

 314.555.3000

 100 St. Louis Ave

 Store Hours

 Monday - Thursday // 10:30 AM to 8:00 PM

 Friday - Saturday // 10:30 AM to 9:00 PM

 Sunday // Closed


text:
Q: I am unable to connect to Mongodb using mongosqld on windows I am trying to create an on prem BI connector for my Atlas MongoDB Database.
I have been able to install the connector but when i run
mongosqld --mongo-uri "mongodb://<URI-REPLICA-NODE-1:PORT>,<URI-REPLICA-NODE-2:PORT>,<URI-REPLICA-NODE-3:PORT>/?replicaSet=<URI-REPLICA-SET>&retryWrites=true&w=majority" --auth -u <USERNAME> -p <PASSWORD> --addr 127.0.0.1:3309 --mongo-ssl

But i am getting this error
unable to load MongoDB information: failed to create admin session for loading server cluster information: unable to execute command: server selection error: context deadline exceeded...
i have not yet found a viable solution for this. please help or point me in the right direction.
i am following this tutorial

A: I have been able to solve it. Apparently I had not whitelisted the IP address of the system where I was running mongosqld on.
As soon as I whitelisted it on my database it worked.


text:
Q: No module named oauth2 - importing from google.oauth2 I am trying to utilize service accounts on a Google Cloud Platform project; however, I am getting an import error after installing the packages as directed on this website:
The code that breaks the app is:
    from google.oauth2 import service_account
When that line is commented out or removed the app doesn't crash; however much of what I need to do involves using service accounts to perform actions that require domain-wide access. I can't find any alternate method of maintaining authorization and performing actions for users in the domain (aside from service accounts), and I also can't find any solutions for this issue on Stack Overflow or elsewhere - any help is appreciated.


text:
Q: Trick to Remember Book 1 of Euclid? Is there a trick or pattern to help remember the (48!) propositions in book 1 of Euclid's Elements?
Book 2 has a fairly nice picture summing it all up
http://www.gogeometry.com/geometry/euclid_elements_23_definiti.gif
and you can use basic algebra also
http://aleph0.clarku.edu/~djoyce/elements/bookII/bookII.html
and the definitions fit into a nice pattern too
http://www.gogeometry.com/geometry/euclid_elements_23_definiti.gif
but even remembering the 48 propositions in book 1 is a lot, maybe they clump together in patterns?


text:
Q: Connect and use search service programmatically I'm building a web service that will search SharePoint site collection for certain items via search service, and then pass results to a list and as the result, display them in my web service method.
The problem is, I have no idea how to connect to a search service through the code and use it there, also can't seem to find any information about how to do it.

A: This is what works for me in CSOM (C#) in a SharePoint online environment. The code sample below only returns the first result, even if the search result returns more than one item (naturally you can use LINQ as you please). You did not specify your working environment, but I would think that there is an equivalent method for on-premise C# code.
        var keywordQuery =
        new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(ctx);

        keywordQuery.QueryText = keyword;
        keywordQuery.RowLimit = 500;

        var searchExecutor =
        new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(ctx);

        var results = searchExecutor.ExecuteQuery(keywordQuery);

        ctx.ExecuteQuery();

        var bytitle = results.Value.FirstOrDefault().ResultRows.Where(c => c["Title"].ToString() == keyword);


text:
Q: How to create private key from SSL certificate? I want to create private for ssl certificate which is in CER format. I have CER format certificate and PKCS #7 certificate with that.
are private key available on-server only or do we get them  with certificate separately?
 i am working with Apache on windows

A: Based on your description you have only the certificate. This certificate contains the public key. You cannot create a private key from it because of how Public Key Cryptography works.
If you could create the private key from any certificate you could essentially authenticate yourself as an arbitrary server on the internet and man in the middle attacks would be easy. Thus, it is good that you cannot get a private key from a certificate.


text:
Q: Loop counter resetting to -1 This is a course project for a simple search counter for the word "Wrox" in a string.
My code:
var myString = "Welcome to Wrox books. ";
myString = myString + "The Wrox website is www.wrox.com. ";
mystring = myString + "Visit the Wrox website today. Thanks for buying Wrox. ";

var i = 0;
var wroxCount = 0;

while (i <= myString.length) {
    i = myString.indexOf("Wrox",i);
    wroxCount++;
    i++;
}

It works fine until i decides to reset to -1 for some reason. It works until it suddenly doesn't. I don't know what I'm doing wrong.

A: String.indexOf returns -1 when the substring you are searching for was not found in the string.
So this is what you should check against in your while condition, instead of i <= myString.length because if i is positive, the substring was found inside the string, so the index is lower than the length.
i = myString.indexOf('Wrox');
while (i > 0) {
    wroxCount++;
    i = myString.indexOf('Wrox', i + 1);
}


text:
Q: Mean curvature calculated using second order derivation of the second fundamental form Is there a formula for calculating the mean curvature tensor using Ricci tensor, Gauss curvature tensor and the second order derivative of the second fundamental form? More precisely, I found some formula in the paper of S. Funabashi, Totally complex submanifolds of a quaternionic Kaehlerian manifold, Kodai Math. J. 2 (1979), 314-336. on page 327, just below the formula (4.1).
Thank you!

A: It should not be difficult to obtain such a formula from the Gauss equation by taking covariant derivatives and appropriate contractions. In fact, the twice contracted Gauss equation relates the scalar curvatures, the Ricci tensor, the square of the mean curvature and the square of the length of the second fundamental form. See eg. p. 47 in "The large scale structure of the space-time" by S.W. Hawking and G.F.R. Ellis.


text:
Q: Alternative for Intent.makeRestartActivityTask(mainActivity) pre android 3.0 I have in my application a service the notify the user using a notification , i read about the
Responding to Notification but this method work for android API 11 and above is there a way to make the same thing on pre Android API 11.


text:
Q: Different contents of the root block of react.js I am developing a dynamic page,
the main template is rendered on PHP,
there is a root block for react in which there is a certain logic;
The question is how to have two different react-applications in one file,
 depending on some parameter coming from the outside,
for example, one page will be "brands" and for the other "reviews",
you also need to give parameters from the outside, for example id
a thought comes to mind in the root file index.js and parse url and resolve this case
by if-else statements. but something tells me that this is a bad programming tone
I'm doing backend, so I don't know the right solution for the react. any ideas?
import React from "react";
import ReactDOM from "react-dom";
import Brands from "./components/Brands.js";

ReactDOM.render(<Brands />, document.getElementById("root"));

A: If I understand correctly you want to have main page based on PHP, which is generated by some framework (like lavarel) on server-side. PHP page will contain <div id="react-root"/> or similar block where React app will appear. You need to tell React app what to render depending on some parameter value which is known by PHP backend.
If so, there are following options:

*

*HTML5 'data' Attribute
Embed some tag to PHP page with arbitrary data- attribute. HTML5 supports arbitrary parameters as long as they prefixed with data- attribute.
For example
 <script id="appselector" data-app="runApp1" src="http://yoursite.io/app.js" >

And in root file pf React app do
 var script_tag = document.getElementById('appselector')
 var choosenApp = script_tag.getAttribute("data-app");
 // choosenApp will contain required id

Sure, in place of <script/> tag can be any other tag that you want to embed. You may look at this post to find additional details.

*Use the QueryString but again with your <script/> block.
For example
<script id="appselector" src="http://yoursite.io/app.js?app=runApp1">

And in the root of your React app do
var script_tag = document.getElementById('appselector');
var query = script_tag.src.replace(/^[^\?]+\??/,'');
// Parse the querystring into arguments and parameters
var vars = query.split("&");
var args = {};
for (var i=0; i<vars.length; i++) {
    var pair = vars[i].split("=");
    // decodeURI doesn't expand "+" to a space.
    args[pair[0]] = decodeURI(pair[1]).replace(/\+/g, ' ');
}
var choosenApp = args['app'];

(Options 1 and 2 are taken from here)

*As suggested by @Prakash Sharma, you may use React-router. The main difference from options 1 and 2 is that react-router allows end user to choose what app to run. It mostly used to make React app multi paged. For example, first page will be on address http://reactapp.com/app1 and another will be on address http://reactapp.com/app2 and so on. Besides that addresses are changed all them should point to single PHP page on your backend. React-router inside React app will intercept URL and show correct page or app. No real PHP page change takes place.
This case is suitable if you want end user to select one app by him/herself. Also react app may change addresses in code.


text:
Q: what is difference between tap interface and normal interface? I'm studying about virtual networking.
I saw the youtube video that makes tap interfaces and adds them to Open Virtual Switch.
From here, I don't know what tap interfaces are.
What's different between normal interface like eth0 and tap interface?
Is tap interface just virtual L2 interface to add it to OVS?
If it is right, what's the purpose of tap interface w/o attaching it to OVS?

A: OpenVSwitch is a virtual switch. It works by attaching to several Ethernet devices in raw packet/Ethernet mode. It switches Ethernet frames between those Ethernet devices by reading/writing raw Ethernet frames to/from those network interfaces.
This is nice if you want to switch between real Ethernet devices. If you want to connect a VM to your Open V Switch instance you need to attach Open V Switch to a virtual Ethernet devices representing your connection to this VM: writing packet to this virtual network interface should send the Ethernet frame to the VM and packet sent by the VM should be sent to this virtual network interface.
TAP network interfaces are designed for this. They represent virtual Ethernet devices. A TAP network interface is managed by some user process:

*

*when an Ethernet frame is sent to the network interface, the user process receives this Ethernet frame;

*the user process can send Ethernet frames to this network interface.
This is often used for:

*

*VPNs (such as OpenVPN): When an Ethernet frame is sent to the TAP network interface, the VPN process receives it and forwards it in a tunnel. Conversely when the user process receives an Ethernet frame from the tunnel it forwards them to the TAP interface;

*vitual machines: When an Ethernet frame is sent to the TAP interface, the hypervisor/emulator receives it and forwards it to the VM. Conversely when the VM sends a packet to its interface, the hypervisor/emulator forwards it to the TAP interface.
For Openvswitch, you typically create a TAP interface which represents your connection to a VM and can then connect this network interface to OpenVSwitch.


text:
Q: Oracle 10g DB - How to give multiple users access to same db My application has a db with many tables. Now there is a new application and i have to give them access to only one table. How can it be done...is it possible to create a new user which will point to the same db and have access to only particular table?

A: CREATE ROLE app_usr_role;

CREATE USER app_user IDENTIFIED BY password;

GRANT app_usr_role TO app_user;

GRANT SELECT,INSERT,UPDATE ON table TO app_usr_role;

A: Yes, this is possible. You need to use GRANT or REVOKE commands for this. First, you'd have to revoke unneeded privileges from your new user. See here scripts to list and revoke this privileges. Then grant access only to your table, like
GRANT SELECT, INSERT, UPDATE, DELETE on YOUR_TABLE to NEW_USER

See more info here http://www.techonthenet.com/oracle/grant_revoke.php


text:
Q: MongoDB log file growth Currently my log file sits at 32 meg.  Did I miss an option that would split the log file as it grows?

A: If you think that 32 megs is too large for a log file, you may also want to look inside to what it contains.
If the logs seem mostly harmless ("open connection", "close connection"), then you may want to start mongod with the --quiet switch. This will reduce some of the more verbose logging.

A: You can use logrotate to do this job for you.
Put this in /etc/logrotate.d/mongod (assuming you use Linux and have logrotate installed):
/var/log/mongo/*.log {
    daily
    rotate 30
    compress
    dateext
    missingok
    notifempty
    sharedscripts
    copytruncate
    postrotate
        /bin/kill -SIGUSR1 `cat /var/lib/mongo/mongod.lock 2> /dev/null` 2> /dev/null || true
    endscript
}

A: Rotate the logs yourself
http://www.mongodb.org/display/DOCS/Logging
or use 'logrotate' with an appropriate configuration.

A: Using logrotate is a good option. while, it will generate 2 log files that fmchan commented, and you will have to follow Brett's suggestion to "add a line to your postrotate script to delete all mongod style rotated logs".
Also copytruncate is not the best option. There is always a window between copy and truncate. Some mongod logs may get lost. Could check logrotate man page or refer to this copytruncate discussion.
Just provide one more option. You could write a script that sends the rotate signal to mongod and remove the old log files. mongologrotate.sh is a simple reference script that I have written. You could write a simple cron job or script to call it periodically like every 30 minutes.


text:
Q: Excel workbook gets opened repeatedly after closing I have used the method Application.ontime() for scheduling some macros.After closing the workbook, it gets opened again and again. to overcome this problem, I set another event on workbook- BeforeClosed. Now it is showing runtime error 1004:Method 'OnTime' of 'Object'_Application failed.I am not getting why this happening even after reffering the help context from web. Below code is given.
Private Sub Workbook_Open()

starttime = Now + TimeValue("00:02:00")

Application.OnTime EarliestTime:=starttime, Procedure:="startapp", schedule:=True

rtime = TimeValue("14:30:00")

Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder",  Schedule:=True

Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder_out",Schedule:=True

Application.OnTime EarliestTime:=rtime, Procedure:="SendReminderFromProxy",Schedule:=True

End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)

MsgBox "Dear" & " " & Environ("USERNAME") & ", " & "Please do not forget to save before closing."

starttime = Now + TimeValue("00:02:00")

Application.OnTime EarliestTime:=starttime, Procedure:="startapp", Schedule:=False

rtime = TimeValue("14:30:00")

Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder", Schedule:=False

Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder_out", Schedule:=False

Application.OnTime EarliestTime:=rtime, Procedure:="SendReminderFromProxy", Schedule:=False

End Sub

A: When cancelling an OnTime, you need to use the exact same argument values you used when creating it (except for the third argument).
That means you can't pass a different time when you cancel it.
Dim starttime '<<< store the time values for later use...
Dim rtime

Private Sub Workbook_Open()

    starttime = Now + TimeValue("00:02:00")

    Application.OnTime EarliestTime:=starttime, Procedure:="startapp", schedule:=True

    rtime = TimeValue("14:30:00")

    Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder",  Schedule:=True

    Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder_out",Schedule:=True

    Application.OnTime EarliestTime:=rtime, Procedure:="SendReminderFromProxy",Schedule:=True

End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    MsgBox "Dear" & " " & Environ("USERNAME") & ", " & "Please do not forget to save before closing."

    'use the global variable here
    On Error Resume Next '<< prevent error if no schedule is set
                         '   or if already triggered
    Application.OnTime EarliestTime:=starttime, Procedure:="startapp", Schedule:=False
    Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder", Schedule:=False
    Application.OnTime EarliestTime:=rtime, Procedure:="sendreminder_out", Schedule:=False
    Application.OnTime EarliestTime:=rtime, Procedure:="SendReminderFromProxy", Schedule:=False
    On Error Goto 0

End Sub


text:
Q: Avoid seeing "restrict editing" sidebar - MS WORD I created a template and then restricted the editing to specific areas.
I added a simple macro to avoid seeing the yellow highlighting
ActiveWindow.View.ShadeEditableRanges = False

Now I want to avoid that when a user tries to modify a restricted area, the "Restricted Editing" sidebar appears.
I recorded a macro to see what instructions VBA reads, but there is no command to open the sidebar...
Do you think there is a way to avoid the sidebar appearing? If I was in excel, I would think about something like:
 Private Sub RestricEditing_Change(ByVal Target As Range)
' Determine whether the change is in the restricted editing area
   Set checkRange = Application.Intersect(Target, restricted area)

' If the change wasn't in this range then we're done
   If checkRange Is Nothing Then Exit Sub
   Else "do not show the restricted editing sidebar"

Thanks in advance to all of you!

A: When I use the following, the taskpane appears to be "disabled" for the user. It can still be shown via the "Restrict Editing" button in the Developer tab of the Ribbon:
Application.Taskpanes(wdTaskPaneDocumentProtection).Visible = False

To "disable" this pane when the document is opened I've had to resort to some trickery - and the pane in question will be visible for a moment. This assumes that the very start of the document should not be editable. SendKeys will trigger the pane; the disable is called on a timer.
Sub AutoOpen()
    Application.ScreenUpdating = False
    ActiveWindow.View.ShadeEditableRanges = False
    SendKeys "T"
    DoEvents
    Application.OnTime Now + TimeValue("00:00:01"), "DisableProtectionPane"
End Sub

Sub DisableProtectionPane()
    Application.TaskPanes(wdTaskPaneDocumentProtection).Visible = False
End Sub

I note that

*

*when the user dismisses the taskpane by clicking the "x" at the top right, the behavior is the same as using the above code.

*both this setting and that of the highlighting are reset to default when the document is closed and opened again.

*that using Application.Taskpanes(wdTaskPaneDocumentProtection).Visible = true does not necessarily reset the behavior during a Word session.


text:
Q: Direct root domain to a context and subdomain to another context I have situation where i want to direct my root domain i.e. www.abc.com to a context in tomcat and *.abc.com to another context in tomcat.
currently www.abc.com abc.com and *.abc.com all point to my ROOTcontext in tomcat but I want
www.abc.com and abc.com to point to ROOT and
*.abc.com to some other context in tomcat.

A: This is an old one, but since I reach here from Google's first page, it deserves an answer.
I guess the best shot is to add "VirtualHost"s to your httpd and "Host"s to your tomcat's server.xml for each subdomain. Take this as a "HelloMultiWorld" example:
<VirtualHost *:80>
  ServerName abc.com
  ServerAlias www.abc.com sd1.abc.com
  ...
  ProxyPreserveHost true
  ProxyPass / ajp://localhost:8009/
  ProxyPassReverse / ajp://localhost:8009/
  ...
</VirtualHost>

And, in Tomcat's server.xml:
<Engine defaultHost="localhost" ...>
  ...
  <Host name="localhost" appBase="webapps" ...>...</Host>
  <Host name="sd1.abc.com" appBase="webapps-sd1"...>...</Host>
</Engine>

Obviously, you need a "webapps" and a "webapps-sd1" folder with their own ROOT.war.
With this configuration, HTTPd will proxy all abc.com, www.abc.com and sd1.abc.com requests to Tomcat (using AJP - you can also use HTTP/8080). Tomcat will receive a request with a "Host: xxx.abc.com" HTTP header (because of "ProxyPreserveHost"). With multiple "Host"s in server.xml, it will route the request according to the "Host" header. All unidentified hosts will route to 'defaultHost'.


text:
Q: SQL Server FileStream - How to acquire files path I'm working on this application where I need to upload large data files to my SQL Server DB, and I've been using FileStream to do it more efficiently.
I understand the files are stored directly into my system's folders (C:\CryptoDB).
The thing is, I need to manipulate these files (decrypt them) but I haven't been able to recover their filepath.
Doing so, I would be able to manipulate them directly, not having to re-download them via SQL, which is a real waste.
What I've been able to do so far:
My table:
CREATE TABLE [arquivo] (
[idUsuario]   INT NOT NULL,
[fileState]   INT NOT NULL,
[fileContent] varbinary(max) FILESTREAM,
[fileName]    VARCHAR (150)   NULL,
[fileSize]    VARCHAR (50)    NULL,

id UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE,

CONSTRAINT [FK_arquivo_usuario] FOREIGN KEY ([idUsuario]) REFERENCES usuario(id)
);

Insert:
Insert into arquivo(id, idUsuario, fileState, fileContent, fileName, fileSize) Values(
newId(),
1,
5,
(SELECT * FROM OPENROWSET(BULK 'c:\medio.jpeg', SINGLE_BLOB) AS varbinary(max)) ,
'medio.jpeg',
'123'
)

And when I try to recover the filepath:
DECLARE @filePath varchar(max)

SELECT @filePath = fileContent.PathName()
FROM arquivo

PRINT @filepath

The result I get:
\\TEHORT-PC\MSSQLSERVER\v02-A60EC2F8-2B24-11DF-9CC3-AF2E56D89593\CryptoDB\dbo\arquivo\fileContent\31E3697E-0576-4B0F-B0AA-6E046F4116A1\VolumeHint-HarddiskVolume2

Where the file actually is:
C:\CryptoDB\DATA\902a7d8d-c8c1-43b0-8c94-b12319293f42\7febdbd1-02c6-4b00-aa3c-a72bee80ef9c\

A: *

*SQL query for get physical location of all FILESTREAM data (source)
SELECT      t.name AS 'table',
            c.name AS 'column',
            fg.name AS 'filegroup_name',
            dbf.type_desc AS 'type_description',
            dbf.physical_name AS 'physical_location'
FROM        sys.filegroups fg
INNER JOIN  sys.database_files dbf
ON          fg.data_space_id = dbf.data_space_id
INNER JOIN  sys.tables t
ON          fg.data_space_id = t.filestream_data_space_id
INNER JOIN  sys.columns c
ON          t.object_id = c.object_id
AND         c.is_filestream = 1
All FILESTREAM BLOB-fields query result sample

*SQL query for get subfolders for FILESTREAM data on server:
(These tables only used within dedicated Administrator connection (DAC)).
SELECT o.name AS [Table], cp.name AS [Column], r.rsguid AS [Rowset GUID], rs.colguid AS [Column GUID] FROM SYS.SYSROWSETS r CROSS APPLY sys.sysrscols rs
JOIN sys.partitions p ON rs.rsid = p.partition_id
JOIN sys.objects o ON o.object_id = p.object_id
JOIN sys.syscolpars cp ON cp.colid = rs.rscolid
WHERE rs.colguid IS NOT NULL AND o.object_id = cp.id AND r.rsguid IS NOT NULL AND r.rowsetid = rs.rsid AND o.name = 'DOCUMENT' and cp.name = 'DIGITAL_FILE';
2.1. Query result:

Table: DOCUMENT
Column: DIGITAL_FILE
Rowset GUID: 0x6AA5E6045794D34D8B1FAC0F49A49B0A
Column GUID: 0xD756E638FB2CC843AE98F489B57F6D7D

Calculating Sub-Path from this guids:

0x6AA5E6045794D34D8B1FAC0F49A49B0A equals this path:
  04e6a56a-9457-4dd3-8b1f-ac0f49a49b0a
[reversed 6AA5E604]-[reversed 5794]-[reversed D34D]-[reversed 8B1F]-[original AC0F49A49B0A]
0xD756E638FB2CC843AE98F489B57F6D7D equals this path:
  38e656d7-2cfb-43c8-ae98-f489b57f6d7d (rules in previus guid parsing)

2.2 Result calculated full path for FILESTREAM storage:

i:\SQL Base posc_astrachan FileStreams\GTMK\GTM_FILE_STREAM\04e6a56a-9457-4dd3-8b1f-ac0f49a49b0a\38e656d7-2cfb-43c8-ae98-f489b57f6d7d

*Get original filename for BLOB-value in NTFS-folder.

3.1. Stored procedure for query advanced SQL Server Page info
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[procDBCC_PAGE]
    @db_name varchar (500),
    @filenum INT,
    @pagenum INT
AS
BEGIN
SET NOCOUNT ON
DBCC TRACEON (3604);
DBCC PAGE (@db_name, @filenum, @pagenum, 3) WITH TABLERESULTS;
SET NOCOUNT OFF
END

3.2. Stored procedure for query original filename for FILESTREAM'ed BLOB-field of table
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[procFindLogSequenceNumber]
-- @TableName varchar (500),
 @instanceS varchar (19), -- key value for filed INSTANCE_S
 @tableName varchar(500), -- DOCUMENT
 @keyFieldName varchar(500), -- INSTANCE_S
 @LogSequenceNumber varchar (500) OUTPUT
AS
SET NOCOUNT ON

DECLARE @db_name varchar (500)
DECLARE @filenum INT
DECLARE @pagenum INT
DECLARE @slotnum INT
DECLARE @rid varchar (100)
DECLARE @ridDotted varchar (100)

DECLARE @parent_object varchar (500)

DECLARE @sql nvarchar(2000)
DECLARE @sqlTable Table(physloc varchar(100))

DECLARE @DBCC_PAGE_Output Table ([ParentObject] varchar (MAX), [Object] varchar (MAX), [Field] varchar (MAX), [VALUE] varchar (MAX))

SET @db_name = db_name()

SET @sql = 'SELECT top 1 sys.fn_PhysLocFormatter (%%physloc%%) AS [PhysicalRID] FROM '+@tableName+' WHERE '
             +@keyFieldName+' = '''+@instanceS+''''

INSERT @sqlTable (physloc)
EXECUTE sp_executesql @sql

SET @rid = (select top 1 physloc from @sqlTable)
if @rid is NULL
BEGIN
  RETURN -1;
END

-- parse (@rid): (1:1172779:6)  1-@filenum, 2- @pagenum, 3- @slotnum
SET @ridDotted = Replace(@rid, ':', '.');
SET @ridDotted = Replace(@ridDotted, '(', '');
SET @ridDotted = Replace(@ridDotted, ')', '');

SET @filenum = (SELECT Parsename(@ridDotted, 3))
SET @pagenum = (SELECT Parsename(@ridDotted, 2))
SET @slotnum = (SELECT Parsename(@ridDotted, 1))

INSERT @DBCC_PAGE_Output ([ParentObject], [Object], [Field], [VALUE])
EXECUTE procDBCC_PAGE @db_name, @filenum , @pagenum

SET @parent_object = (SELECT TOP 1 [ParentObject] FROM @DBCC_PAGE_Output WHERE [Field] = 'INSTANCE_S'
 AND [VALUE] = @instanceS)

--CreateLSN field Only
SET @LogSequenceNumber = (SELECT [VALUE] FROM  @DBCC_PAGE_Output WHERE
 [ParentObject] = @parent_object AND
 [Field] = 'CreateLSN'
)

if @LogSequenceNumber is NULL
BEGIN
  RETURN -1;
END

-- result 0006c050:00000120:0090 (442448:288:144)
-- clear (...)
SET @LogSequenceNumber = Replace(@LogSequenceNumber, ' ', '.');
SET @LogSequenceNumber = (SELECT Parsename(@LogSequenceNumber, 2))

--replace ":" to "-"
SET @LogSequenceNumber = Replace(@LogSequenceNumber, ':', '-');

SET NOCOUNT OFF

3.3. Sample query for stored procedure for get filename on NTFS folder for BLOB:
declare @filestreamFileName varchar(500);
exec procFindLogSequenceNumber 'ZW_NU9hGZ0CKoSXYAoc', 'DOCUMENT', 'INSTANCE_S', @filestreamFileName OUTPUT
select @filestreamFileName

3.4. Result (original file name in NTFS folder):

0003137a-00001244-00d0

3.5. Result full path:

i:\SQL Base posc_astrachan FileStreams\GTMK\GTM_FILE_STREAM\04e6a56a-9457-4dd3-8b1f-ac0f49a49b0a\38e656d7-2cfb-43c8-ae98-f489b57f6d7d\0003137a-00001244-00d0

A: The path you get is correct, you are supposed to get the network share path not the local path and use SqlFileStream to open a stream.
https://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqlfilestream%28v=vs.110%29.aspx
You could also get a file handle using OpenSqlFilestream method, i.e. to use it in Windows API.
https://msdn.microsoft.com/en-us/library/bb933972.aspx

A: Alexander's answer is great, saved me a LOT of trouble correlating page/slot numbers to actual LSNs. In my case using SQL Server 2008 R2 I had to make some adjustments to his SP to get it working, those were:
The SPs first parameter:

@instanceS varchar (100), -- key value for filed INSTANCE_S

In my case this is a uniqueidentifier so I needed a bigger varchar, original value was 19.
When querying DBCC PAGE Output:

SET @parent_object = (SELECT TOP 1 [ParentObject] FROM
  @DBCC_PAGE_Output WHERE [Field] = @keyFieldName  AND [VALUE] =
  @instanceS)

It originaly stated "[Field] = 'INSTANCE_S'" which apparently hardcoded a value that worked for OP but not for me. It needed to match the name of the FILESTREAM table's key field.
Also to clarify the SPs input params a bit:

@instanceS = The actual column value which identifies the row. Will
  this always match the column set as the table's "RowGuid"?
  @tableName = Pretty clear. The FILESTREAM table's name.
  @keyFieldName = The name of the table's key column. Should be the
  source column from where @instanceS was taken.


text:
Q: ngrx component unit test : how to set store value and make the subscribe call I am writing a unit test for my component. I want to test/cover the part wherein I am calling a function calculateJohnDoe inside my subscribe. Please refer below :
ngOnInit(): void {
    this.authStore$ = this.store.select('auth');
    this.authStore$.subscribe(authData => {
      if (authData && authData.myprop) {
          this.calculateJohnDoe();
        }
    });
}

What I am trying to do in my spec is as follows :
describe(..., () => {
  let mockStore: MockStore<AuthState>;

    // Testbed configuration
      providers: [ Store ]
      }).compileComponents();

      mockStore = TestBed.get(Store);
    ...

    it('should call the function', () => {
        mockStore.setState({
           myprop: true
        });
        const spy = jest.spyOn(LoginComponent.prototype, 'calculateJohnDoe');
        expect(spy).toHaveBeenCalled();
    });

    ...

});

But the problem is I never get the myprop true updated store event/callack in my component ts file called.

A: You can create a mock service that represents your store, this class will simulate an observable subject with the attribute _anObservable :
class MockService {
    _anObservable = new Subject();
    select(prop: string) {
        return this._anObservable.asObservable();
    }
}

describe(..., () => {

    // Testbed configuration
    providers: [
        { provide: YourStore, useClass: MockService }
    ]

    ...

    it('should call the function', inject([YourStore], (store) => {
        const spy = jest.spyOn(LoginComponent.prototype, 'calculateJohnDoe');
        store._anObservable.next({
            myprop: true
        });
        expect(spy).toHaveBeenCalled();
    }));

    ...

});


text:
Q: Can't instantiate class, while populating selectonemenu in JSF2 I'm trying to populate selectOneMenu from DB and I get run time error Can't instantiate class. I get
java.lang.NullPointerException at pointControllerConverter.getPoints(pointControllerConverter.java:89)

Any advice?
This is my code:
xhtml file:
    <p:selectOneMenu id="point" value="#{pointController.selectedPoint}"
                     var="items_var">

         <f:selectItems value="#{pointController.points}" var="points_var"
                        itemLabel="#{points_var.name}" itemValue="#{points_var.name}"/>

    </p:selectOneMenu>

Managed bean:
    @ManagedBean(name = "pointController")
    @SessionScoped

    public class PointController implements Serializable {

    @EJB
        private ethoam.entity.PointFacade ejbFacade;
        private List<point> points;
        private point selectedPoint;
        private point[] selectedPoints;
        private List<Point> selectedPointsList;
        private SelectItem[] PointNamesOptions;

        public PointController() {
                  this.initList();
        }

        @PostConstruct
        private void initList() {

        points = new ArrayList<point>(PointControllerConverter.getPoints().values());

    }

        // getters setters
     }

Converter class:
    public static class PointControllerConverter implements Converter {

    @PersistenceContext(unitName = "PointPU")
    private static EntityManager ejbfacade;

    public static Map<String, point> points = new HashMap<String, point>();

    public static Map<String,point> getPoints() {

    points = (Map<String, point>) ejbfacade.createNamedQuery("SELECT d FROM point d WHERE d.name = :name");
    return points;
    }

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if (value == null || value.length() == 0) {
            return null;
        }
        PointController controller = (PointController) facesContext.getApplication().getELResolver().
                getValue(facesContext.getELContext(), null, "pointController");
        return controller.ejbFacade.find(getKey(value));
    }

    java.lang.Integer getKey(String value) {
        java.lang.Integer key;
        key = Integer.valueOf(value);
        return key;
    }

    String getStringKey(java.lang.Integer value) {
        StringBuilder sb = new StringBuilder();
        sb.append(value);
        return sb.toString();
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof point) {
            point o = (point) object;
            return getStringKey(o.getIdPoint());
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Point.class.getName());
        }
    }

}

A: Well first I don't know why you are using a Converter as a List supplier !
You might need to move getPoints() logic into a ManagedBean.
On the other hand the NullPointerException is caused due the failed injection of of the entity manager (which I don't know why it's a static).
In a Converter or Validator you can't inject using @PersistenceContext or @EJB
See Why: How to inject @EJB, @PersistenceContext, @Inject, @Autowired, etc in @FacesConverter?
You may do this:
Context envCtx = InitialContext().lookup("java:comp/env");
EntityManager em =  (EntityManager) envCtx.lookup("persistence/PointPU");


text:
Q: Which math environment use to make a table layout? I'd like to typeset math in table layout, which is stretched to page width e.g.:
\begin{flalign*}
   a)\, \lim_{n\to\infty} \frac{1000n}{n^2+1} &&
   b)\, \lim_{n\to\infty} \left( \sqrt{n+1}-\sqrt{n}\right) &&
   c)\, \lim_{n\to\infty} \frac{\sqrt[3]{n}\sin n!}{n+1}&&\\
   d)\, \lim_{n\to\infty} \frac{(-2)^n+ 3^n}{(-2)^{n+1}+3^{n+1}}&&
\end{flalign*}

This produces output where each column is aligned to right, I'd prefer left align:

Moreover some padding between lines would be nice.
I've tried using an array environment:
\[
  \begin{array}{p{0.33\textwidth}p{0.33\textwidth}p{0.33\textwidth}}
   a)\, \displaystyle\lim_{n\to\infty} \frac{1000n}{n^2+1} &
   b)\, \displaystyle\lim_{n\to\infty} \left(\sqrt{n+1} - \sqrt{n}\right)&
   c)\, \displaystyle\lim_{n\to\infty} \frac{\sqrt[3]{n}\sin n!}{n+1}\\
   d)\, \displaystyle\lim_{n\to\infty} \frac{(-2)^n+ 3^n}{(-2)^{n+1}+3^{n+1}}
 \end{array}
\]

It seem to solve the problem with align, but math commands inside array produces too many errors and space between rows is even smaller.
Any idea how to solve this?

A: \documentclass[a4paper]{article}
\usepackage{tabularx,array}
\newcolumntype{Y}{>{$\displaystyle\exer}X<{$}}
\newenvironment{exercises}[2][1.5]
  {\par\flushleft\setcounter{exercise}{0}
   \renewcommand{\arraystretch}{#1}\tabularx\linewidth{@{}#2@{}}}
  {\endtabularx\endflushleft}
\newcounter{exercise}
\renewcommand{\theexercise}{\alph{exercise}}
\newcommand{\exer}{\stepcounter{exercise}\makebox[1.2em][r]{\theexercise)\ }}

\begin{document}
\begin{exercises}[2.5]{YYY}
\lim_{n\to\infty} \frac{1000n}{n^2+1} &
\lim_{n\to\infty} \left(\sqrt{n+1} - \sqrt{n}\right)&
\lim_{n\to\infty} \frac{\sqrt[3]{n}\sin n!}{n+1}\\
\lim_{n\to\infty} \frac{(-2)^n+ 3^n}{(-2)^{n+1}+3^{n+1}}
\end{exercises}
\end{document}

You see that you only need to specify how many columns you need and, possibly, the amount of interline stretching. The numbering is automatic.
Alternative definition
Here the intercolumn space is stretched, rather than the column width
\newcolumntype{Y}{>{$\displaystyle\exer}l<{$}}
\newenvironment{exercises}[2][1.5]
  {\par\flushleft\setcounter{exercise}{0}
   \renewcommand{\arraystretch}{#1}
   \begin{tabular*}\linewidth{@{\extracolsep{\fill}}#2@{}}}
  {\end{tabular*}\endflushleft}
\newcounter{exercise}
\renewcommand{\theexercise}{\alph{exercise}}
\newcommand{\exer}{\stepcounter{exercise}\makebox[1.2em][r]{\theexercise)\ }}

A: Here is a plain-format version too, just for fun:
\def\ealign#1{\def\amp{&}% props to Bruno
  \def\intoalpha##1{\ifcase##1 a\or b\or c\or d\or e\or f\or g\or h\or i\or
    j\or k\or l\or m\or n\or o\or p\or q\or r\or s\or t\ot u\or v\or w\or x\or
    y\or z\else##1\fi} % convert given int < 26 to letter
  \count1=0 % used by plain output for info, let's use it for column count
  \vbox{\openup1\jot % increase (base)lineskip(limit) by 3pt (default)
    \halign to\hsize{% make the horizontal alignment take up full width
      &{\rm\intoalpha{\count1})}\enspace\global\advance\count1 by1% column count
      \mathsurround0pt$\displaystyle##$\tabskip0pt&% every other column resets
      \amp##\tabskip1em plus.5\hsize\crcr#1\crcr}}}% \tabskip to zero, so there
                                                   % is no surplus skip at end

So you see,
$$\ealign{
  \lim_{n\to\infty} {1000n\over n^2+1} &
  \lim_{n\to\infty} \left(\sqrt{n+1}-\sqrt n\,\right) &
  \lim_{n\to\infty} {{\root3\of n}\sin n!\over n+1} \cr
  \lim_{n\to\infty} {(-2)^n+3^n\over(-2)^{n+1}+3^{n+1}}
}$$
and that's that. However, if you'd like to have it indented, you could
$$\tabskip\parindent\ealign{
  \lim_{n\to\infty} {1000n\over n^2+1} &
  \lim_{n\to\infty} \left(\sqrt{n+1}-\sqrt n\,\right) &
  \lim_{n\to\infty} {{\root3\of n}\sin n!\over n+1} \cr
  \lim_{n\to\infty} {(-2)^n+3^n\over(-2)^{n+1}+3^{n+1}}
}$$
is the same thing, only a second time.
\bye

Looks like:

A: You could use the normal align* environment, combined with the spreadlines environment from the mathtools package. The parameter for spreadlines (here 20pt) sets the linespacing for align and gather environments within it. Should you want this change to be global, you could instead add \setlength{\jot}{20pt} to your preamble.
\documentclass[12pt]{article}
\usepackage{mathtools}
\begin{document}
\begin{spreadlines}{20pt}
\begin{align*}
   &a)\, \lim_{n\to\infty} \frac{1000n}{n^2+1} &
   &b)\, \lim_{n\to\infty} \left( \sqrt{n+1}-\sqrt{n}\right) &
   &c)\, \lim_{n\to\infty} \frac{\sqrt[3]{n}\sin n!}{n+1}\\
   &d)\, \lim_{n\to\infty} \frac{(-2)^n+ 3^n}{(-2)^{n+1}+3^{n+1}}
\end{align*}
\end{spreadlines}
\end{document}


text:
Q: Angular issue about autocomplete of material design I have created an autocomplete controls with http api getting data.
But <mat-option *ngFor="let region of regions" [value]="region.name"> is throw an error like this:
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
I have checked the data returns Region[] in method 1 , line 52.
And I google for solution method 2, it works but not able to work with loading indicator
I hope someone can give a hand to me. Thanks.
My code: https://stackblitz.com/edit/angular-89p1pm

I have 3 questions to ask:

*

*error popup

*method 1: not show list of countries

*how to deal with Observable with loading indicator
Method 1
form.get('region').valueChanges.pipe(
  debounceTime(300),
  tap(r => this.isLoading = true),
  switchMap(inputCountry =>
    this.regionService.getRegions().pipe(
      map( regions => {
        return regions.filter(region => region.name.indexOf(inputCountry) >= 0)
      })
    )
  )
).subscribe(data => {
  console.log('onRegionChanged: data', data);
  this.isLoading = false;
  this.regions = data;
})

Method 2
form.get('region').valueChanges.pipe(
      debounceTime(300),
      tap(r => this.isLoading$.next(true)),
    ).subscribe(inputCountry => {
      this.regions$ = this.regionService.getRegions().pipe(
        tap(r => this.isLoading$.next(false)),
        map(regions => regions.filter(region => region.name.indexOf(inputCountry) >= 0))
      )
    });

A: Stackbltiz
Your issue is that you're iterating over an empty array. Just add it to your condition.
<ng-container *ngIf="!isLoading && regions?.length">


text:
Q: NetConnection addHeader not working? I am using an open source flash player to play video files. Now the twist is that the server that hosts the files checks the Referer in the header before serving the files, so I need a way to forge these headers.
I'm on my own server, where I try setting the video file to my PHP script:
$headers =  getallheaders();
$string = '';
foreach($headers as $key=>$val){
  $string .= $key . ': ' . $val . "\n";
}

And I mail myself the string and then serve the video file. For some reason, I just cannot forge or even add any extra headers to the request:
    nc = new NetConnection();
    nc.addHeader('Referer', true, 'http://google.com');
    nc.addHeader('Test', true, 'http://google.com');

I am using the opensource and light-weight flash player:
http://gokercebeci.com/dev/download/f4player


text:
Q: How to check if a submake is up to date Let's consider this files structure:
/project
+ Makefile
+ projectA
| + Makefile
| + foo.c
| + bar.c
| + ...
|
+ projectB
  + Makefile
  + oak.c
  + ...

How can I quickly check if a submake is up to date?
In my main make I have:
all:
   make -C projectA

And in the submakefile
all: a.txt b.txt

%.txt:%.xtx
   cp $< $@

The problem with this solution is that I will always call the submake whatever it has nothing to do. I want to avoid it.
The ugly solution I've found is to create a make rule in my submakefile to echo all the files that are depending on the main target. Then I can call the submake with a shell command:
 listfiles=$(shell make -C projectA listfiles)
 all: $(listfiles)
    make -C projectA

EDIT
A better approach would be to have a shell script in each sub-projects that returns the list of all the project's dependencies. For instance:
projectc/listdep.sh:
 #!/usr/bin/bash
 find . -iname *.[ch]

Then I can use this script in the parent make:
 projectc/a.out: $(shell projectc/listdep.sh)
    make -C $(dir $@)

In this way, the parent make won't call the recipe if projectc/a.out exists and is more recent that its dependencies.

A: I hope your projectA and projectB are "self-contained".  That means, their builds do not read any sources or build intermediate files from outside that project.  They may use tools, such as gcc or, as you have it in the example above cp, but not sources outside of their directory, and not any files that are built by somebody else.  In other words, if you deleted the whole rest of the tree and only build projectA and projectB by themselves with their Makefiles, they will build just fine.
In such a case, it is OK to use recursive Make.
If you use recursive Make, you have to do what you are doing,
make -C projectA

There is no better way.  That is the best way to "quickly check" if the "submake" is up to date.


text:
Q: как задать не статичный свет У меня obj loader c orbitcontrol, мне нужно не статичное освещение, чтобы фигура освещалась по мере прокрутки ее, а другие стороны затемнялись немного.
Я пробовал вот так:
var ambient = new THREE.AmbientLight( 0x006400);
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 5, 5, 5);
scene.add( directionalLight );

A: добавить камеру в сцену scene.add(camera);, "прикрутить" свет к камере, а не к сцене camera.add(directionalLight)'
jsfiddle пример


text:
Q: Facebook window not showing correctly & cancel button is invisible in iphone I am integrating facebook login functionality in my iphone application. When I click on "Login with Facebook" button then facebook window opens which is shown below

As you see , "Facebook" is partially visible. Also I can not see any "Cancel" button on the screen. I can not figure out what is wrong with this. By the way I am using official facebook ios sdk from GitHub. My ios sdk is 4.3 & xcode 4. I want "Cancel" buuton on this scrren so that user can navigate back to application & also facebook Title on the view should be displayed correctly. Please guide me. Thanks.


text:
Q: Client-Server connection response timeout issues User creates a folder in client and in the client-side code I hit an API to the server to make this persistent for that user. But in some cases, my server is so busy that the request timesout. The server has executed my request but timedout before sending a response back to client. The timeout set is 10 seconds in client. At this point the client thinks that server has not executed its request (of creating a folder) and ends up sending it again. Now I have 2 folders on the server but the user has created only 1 folder in the client. How to prevent this?
One of the ways to solve this is to use a unique ID with each new request. So the ID acts as a distinguisher between old and new requests from client. But this leads to storing these IDs on my server and do a lookup for each API call which I want to avoid.
Other way is to increase the timeout duration. But I dont want to change this from 10 seconds.
Something tells me that there are better solutions.
I have posted this question in stackoverflow but I think its better suited here.
UPDATE: I will make my problem even more explicit. The client is a webbrowser and the server is running nginx+django+mysql (standard stack). The user creates a folder in webbrowser. As a result I need to hit a server API. The API call responds back, thereby client knows API call was success. This is normal scenario. Sometimes though, server successfully completes the API request but the client-side (webbrowser) connection timesout before server can respond back. The client has no clue at this point. The user thinks the request was a fail & clicks again. This time it was a success but when the UI refreshes he sees 2 folders. I want to remedy this situation.

A: Sounds like you are working in a distributed network environment, have transactions that one node expects another node to carry out reliably and you are specifically dealing/experiencing with timeouts.  This is a relatively generic problem that many people had to solve at one time or another.  Take a look at the three-phase commit protocol and see if that would be suitable for your application.  Or possibly two-phase commit is good enough for what you are doing.


text:
Q: Bounding a Sum of Adjoint L-Function Values Fix integers $k\geq2$ and $N>1$, and let $S(k,N)$ denote the normalized new Hecke eigenforms in  $S_k(\Gamma_1(N))$.  [If it makes my question easier to answer, feel free to replace this with $\Gamma_0(N)$].
For $f \in S(k,N)$, one can define an associated adjoint L-function $L(s,\mathrm{ad}\ f)$. Of particular interest is the special value at $s=1$, which is related to congruences between modular forms. There is a period $\Omega_f$ such that $\frac{L(1,\mathrm{ad}\ f)}{\Omega_f}$ is algebraic.

I am interested in the finite sum
$\displaystyle\sum_{f \in S(k,N)}\frac{L(1,\mathrm{ad}\ f)}{\Omega_f} $.
What, if anything, can be said about this sum? Can we bound it?

There appears to be a vast amount of literature on related topics (e.g. the paper http://www.sci.ccny.cuny.edu/~bfeigon/Average_L-values.pdf seems relevant), but I am unqualified to determine what is known for the sum I wrote above.

A: Here is a naive way I think you can get some bounds.  Warning: I have not thought through this too carefully, and the bounds from such an approach might not be as good as you want in any case.
The adjoint $L$-value is essentially the Petersson norm $(f,f)$.  If $f$ is a new form, then it is $\frac{2^{k}}{N} (f,f)$ with normalization as in that Feigon-Whitehouse paper.  So you want to bound $(f,f)$.  Well, the Petersson norm is equivalent to the sup norm (of $y^{k/2}|f|$) on $S(k,N)$.  Asymptotic bounds for the sup norm have been studied analytically, for instance by Blomer-Holowinsky (which also contains a summary of the relation between the sup norm and Petersson norm) in the case of square free level and recently by Saha in greater generality.  This gives you bounds for individual newforms, and a slightly cruder bound for a general cusp form.  Then you can use the dimension formula to at least get a rough bound on this sum.  One can maybe do better by trying to filter forms in $S(k,N)$ according to their "true level."


text:
Q: How to solve problems such as: find $A(x)$, the accumulation function of $f(x)=x^2$ such that $A(x)= \frac{x^3}3$? Suppose that $A(x)= \int_a^x t^2 \mathrm dt $ and that $A(x)=  \frac{x^3}2$. Find $a$.
I think that the only solution is $a = 0$.
Assuming this is correct, is there a general method to find number a?

*

*In general, we are interested in determining the primitive of a function f for which constant C is null. This particular primitive seems more " basic" as others, since the others can be obtained from it adding some constant C.

*For example, all primitives of $f(x)=x^2$ will be written in terms of the "basic" primitive $F(x) = \frac{x^3}3$

*Not all area functions ("accumulation functions") of a function, say, once again $f(x)=x^2$, will be identical to its "basic" primitive. For example, the area function defined as $x \mapsto \int_5^x t^2 \mathrm dt$ is not identical to the "basic" primitive of $f$, that is, to $F(x)= \frac{x^3}3$. (See image below.)

*Apparently, only the function $x \mapsto \int_0^x t^2\mathrm dt$ is identical to the basic primitive $F(x)$ as defined above.

*Hence my question: is there a method to determine which particular area function of a function $f$ (with which domain, and in particular which number $a$ as limit of integration) is identical to the "basic/standard" primitive of $f$?

The image below shows that  the area function A(x) with a=0 is identical to the " basic" primitive of f(x)=x². this is not the case with a=5.

A: We require $A(x) = x^3/3$ and we compute
$$  A(x) = \int_a^x t^2 \,\mathrm{d}t = \left. \frac{t^3}{3} \right|_{t=a}^x = \frac{x^3}{3} - \frac{a^3}{3}  \text{.}  $$
Equality of these two expressions for $A(x)$ requires $-a^3/3 = 0$, which forces $a = 0$.
The general technique, demonstrated above, is to compute the definite integral, then solve the resulting equality for the value or values of $a$ that satisfy it.
Warning: The set of accumulation functions is not the full set of antiderivatives and it can be confusing to think otherwise at this time.
An example of this deficiency of accumulation functions is: find $b$ such that $B(x)$, the accumulation function of $2x$ is $B(x) = x^2 + 10$.  We proceed by the generic technique:
$$  \int_b^x 2t \,\mathrm{d}t = \left. \frac{2t^2}{2} \right|_{b}^x = x^2 - b^2  \text{.}  $$
This gives the equation $10 = -b^2$, which has no solution (because the left-hand side is positive and the right-hand side is negative for all choices of $b$).  However, $\frac{\mathrm{d}}{\mathrm{d}x} \left( \frac{x^2}{2}+10 \right) = 2x$, so this $B$ is an example of an antiderivative of $2x$ which is not an accumulation of $2x$.
Also, beware this notion of "basic": Any identity that happens to contain a constant offset makes "basic"ness unclear.  Which is more "basic": $\sec^2 \theta$ or $\tan^2 \theta + 1$.  The two expressions are equal for all $\theta$ and the "${}+1$" is not optional.


text:
Q: AWS EKS configure HTTPS listener I want to secure my web service running on Kubernetes (EKS). It is running on port 80 .I want to run this on port 443.
When I apply the YAML file (for service and ingress), on AWS console I still have it listening on port 80 (and not on 443):

This is my YAML file:
How can I let it works? Thanks for you time!
   #SERVICE LOGGER
   apiVersion: v1
   kind: Service
   metadata:
     name: load-balancer-api-logger
     namespace: servicename-core-ns
     annotations:
       service.beta.kubernetes.io/aws-load-balancer-ssl-cert: arn:aws:acm:eu-central-1:786543355018:certificate/acdff29d4-7a32-42f1-8f11-1d4f495a5c77
       service.beta.kubernetes.io/aws-load-balancer-ssl-ports: "443"
       service.beta.kubernetes.io/aws-load-balancer-backend-protocol: http
       service.beta.kubernetes.io/force-ssl-redirect: "true"
   spec:
     selector:
       app: api-logger
     type: NodePort
     ports:
     - protocol: TCP
       port: 443
       targetPort: 5000
     selector:
       app.kubernetes.io/name: api-logger
   ---

   apiVersion: networking.k8s.io/v1
   kind: Ingress
   metadata:
     name: ingress-articor
     namespace: servicename-core-ns
     annotations:
       kubernetes.io/ingress.class: alb
       alb.ingress.kubernetes.io/scheme: internet-facing
       alb.ingress.kubernetes.io/target-type: instance
       alb.ingress.kubernetes.io/healthcheck-path: "/healthcheckep"
       alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}, {"HTTPS": 443}]'
       alb.ingress.kubernetes.io/ssl-redirect: '443'
   spec:
     rules:
       - host: logger.domainname.com
         http:
           paths:
             - path: "/"
               pathType: Prefix
               backend:
                 service:
                   name: load-balancer-api-logger
                   port:
                     number: 80

Please consider that if I try to manually set the ALB to work with HTTPS it works fine. What I'm trying to achive here is to configure it via YAML file.

A: You should configure all settings in Ingress object. The following spec also don't repeat the default value set by the controller:
apiVersion: v1
kind: Service
metadata:
 name: load-balancer-api-logger
 namespace: servicename-core-ns
spec:
 selector:
   app: api-logger
 type: NodePort
 ports:
 - protocol: TCP
   port: 443
   targetPort: 5000
 selector:
   app.kubernetes.io/name: api-logger
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
 name: ingress-articor
 namespace: servicename-core-ns
 annotations:
   kubernetes.io/ingress.class: alb
   alb.ingress.kubernetes.io/scheme: internet-facing
   alb.ingress.kubernetes.io/healthcheck-path: "/healthcheckep"
   alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:eu-central-1:786543355018:certificate/acdff29d4-7a32-42f1-8f11-1d4f495a5c77
spec:
 rules:
 - host: logger.domainname.com
   http:
     paths:
     - path: "/"
       pathType: Prefix
       backend:
         service:
           name: load-balancer-api-logger
           port:
             number: 443


text:
Q: How to build a model when we have three separate train, validation, and test sets? I have a data set which should be divided into train, test, and validation sets.
Code:
set.seed(98274)                              # Creating example data
y <- sample(c(0,1), replace=TRUE, size=500)
x1 <- rnorm(500) + 0.2 * y
x2 <- rnorm(500) + 0.2 * x1 + 0.1 * y
x3 <- rnorm(500) - 0.1 * x1 + 0.3 * x2 - 0.3 * y
x4 <- rnorm(500) + 0.19 * y
x5 <- rnorm(500) + 0.2 * x3 + 0.11 * x2 - 0.174 * x4
x6 <- rnorm(500) - 0.12 * x1 + 0.28 * x2 - 0.33 * y
mydata <- data.frame(y, x1, x2, x3, x4, x5, x6)

## divide the data
set.seed(200)
n=nrow(mydata)
id.train=sample(1:n,300,replace=FALSE)
id.valid=sample(setdiff(1:n,id.train),100,replace=FALSE)
id.test=setdiff(setdiff(1:n,id.train),id.valid)

mydata.train=mydata[id.train,]
mydata.valid=mydata[id.valid,]
mydata.test=mydata[id.test,]

I want to do variable selection so that the AUC will be maximized. If I just had train and test sets, I would do something like this:
# Transformation of the variable of interest into a factor, with names for the levels
library(caret)
levels <- unique(mydata$y)
mydata.train$new_y=factor(mydata.train$y, labels=make.names(levels))

data_ctrl = trainControl(method = "cv", number = 5,summaryFunction=twoClassSummary,
                         classProbs = TRUE)

# build model and select variables
model = train(new_y ~x1 + x2 + x3 + x4 + x5 + x6
              , data=mydata.train, method="glmStepAIC",metric = "ROC"
              , trControl=data_ctrl,trace=FALSE)
model$finalModel

# test model on test set
prob.predict = predict.glm (model$finalModel, mydata.test, type="response")

cutoff=0.5
test.pred = rep(0, nrow(mydata.test))
test.pred[prob.predict >= cutoff] = 1
# Confusion matrix
M=table(test.pred, mydata.test$y,dnn=c("Prediction","Observation"))
M

a=M[1,1]
b=M[1,2]
c=M[2,1]
d=M[2,2]

# Sensitivity
d/(b+d)

# Specificity
a/(a+c)
# AUC
library(ROCR)
pred=prediction(prob.predict,mydata.test$y )
perf=performance(pred,measure="tpr",x.measure="fpr")

auc.perf = performance(pred, measure = "auc")
auc.perf@y.values

I could use the train set to do cross-validation. However, since I have a separate validation set I don't know how to use it to validate my model. How we should do variable selection and build a model when we have three separate data sets (i.e.  train, validation, and test)?


text:
Q: Same declaration two different types I would like to be able to do this:
X<int> type_0;
X<int> type_1;

and I would like for type_0 and type_1 to be two different types. How can I do it?

A: template < typename T, int I > class X;

X<int, __LINE__ > x0;
X<int, __LINE__ > x1;

x0 and x1 will be different types as will any other declarations like this if they are not on the same line in the file.

A: You could use ordinal tags:
template <typename T, int Tag> class X { ... };

typedef X<int, 0> type_0;
typedef X<int, 1> type_1;

Alternatively, you could use inheritance:
class type_0 : X<int> { ... };
class type_1 : X<int> { ... };

But this suffers from some difficulties, such as the need to forward constructor parameters and hazards with mixing assignment semantics and inheritance.

A: You'll need to parameterize on another thing (e.g. an integer?). For example, define X as template <typename T, int N> struct X {...}; and use X<int,0> type_0; X<int,1> type_1. If template parameters match, they are the same type.

A: Make a class that inherits from the X template class, like this:
template <int I>
class type_i : public X<int>
   {
   };

typedef type_i<0> type_0;
typedef type_i<1> type_1;


text:
Q: Connecting firebase to ionic3 app I am trying to connect Firebase to an Ionic 3 app. I have installed the Firebase library and imported all the requirements needed, but I have this error:
Runtime Error Uexpected value 'AngularFiredatabase' imported by the module "AppModule' please add @NgModule annotation


text:
Q: Library for pattern matching shapeless coproduct with partial functions I have a relatively ergonomic pattern I use to pattern match shapeless Coproducts. It looks basically like this
val stringOrInt: String :+: Int :+: CNil  = Coproduct("Hello world")

implicit class Coproduct2Syntax[A, B](val value: A :+: B :+: CNil) extends AnyVal {
  type cop = A :+: B :+: CNil

  def comatch[Z](
    caseA: PartialFunction[A, Z],
    caseB: PartialFunction[B, Z]
  ): Z = {
    val a = Function.unlift[cop, Z](_.select[A].flatMap(caseA.lift))
    val b = Function.unlift[cop, Z](_.select[B].flatMap(caseB.lift))
    a.orElse(b).apply(value)
  }
}

stringOrInt.comatch({
  case s => s.length
},{
  case i => i
})
// Int = 11

This works well enough but I haven't gone through the trouble of defining CoproductNSyntax for 0-22.
I'm aware we can do something similar with Poly1, but that requires defining a separate object
My question is: are there any existing libraries that provide this type of pattern for matching for Coproducts?


text:
Q: How do I draw a new image without making a new UIImageView I have a character in an iPod Touch game I am making that moves around the screen.  That I have under control... However I want him able to shoot fireballs, and I don't want to have to make a new UIImageView for every fire ball he shoots.  I have the image and everything... I think i need to use quartz core or openGL ES, but I can't make sense of the apple documentation.

A: Another option would be to implement drawRect in your view, and draw the fireballs there.


text:
Q: How do I split by commas, then sections surrounded by double quotes? I have a file "data.txt" with lines such as
4, "124 Sesame, Street Lane", Chicago, IL
5, 2342 Main Street, Denver, CO
6, 124 Some Street, Los Angelos, CA

I have a python script that reads this file line by line and splits it up into a tuple of data in the form (id, street address, city, state). The script splits each line up by commas:
line = file.readline()
line_tuple = line.split(',')

This method clearly breaks down because I have some lines that have chunks of text surrounded by double quotes that I want to consider as a whole entity in the tuple as opposed to two distinct pieces of data.
How do I tell python to treat blocks of double quotes a single entity when splitting by commas?
I have tried splitting by quotes first and then commas and vice versa, but these methods don't seem to get at what I am trying to do.

A: That is called a "comma separated values" or short "csv". Python has a library for reading it.
Check out: http://docs.python.org/2/library/csv.html or http://docs.python.org/3/library/csv.html if you are using Python 3.

A: Use a real CSV parser. Python 2, Python 3
# default delimiter is , and default quotechar is "
>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
...     spamreader = csv.reader(csvfile)
...     for row in spamreader:
...         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam


text:
Q: E: Package 'steamcmd' has no installation candidate Each time I try to install SteamCMD via apt it responds with:
Package steamcmd is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'steamcmd' has no installation candidate

I have a Raspberry Pi running Ubuntu 20.04.

A: A quick scan (rmadison steamcmd)
guiverc@d960-ubu2:/home/wallpapers$   rmadison steamcmd
 steamcmd | 0~20130205-1 | xenial/multiverse  | source, i386
 steamcmd | 0~20130205-1 | bionic/multiverse  | source, i386
 steamcmd | 0~20180105-3 | focal/multiverse   | source, i386
 steamcmd | 0~20180105-4 | groovy/multiverse  | source, i386
 steamcmd | 0~20180105-4 | hirsute/multiverse | source, i386

(or via web browser; https://packages.ubuntu.com/search?suite=all&section=all&arch=any&keywords=steamcmd&searchon=names)
shows the command is only available for i386 architecture; ie. not a raspberry pi using armv7 or arm64.  Your pi has the wrong CPU for steamcmd


text:
Q: How to add Qt libraries to visual studio I have a source with VC++ 2017
I receive the error "Error    C1083   Cannot open include file: 'QtCore/QMap': No such file or directory    " when i try compile the project.
I download Qt libraries and add to Include project but the problem exist.
Which directory of Qt of i had to add to project to resolve error?
this is header of my code that generate error
#include <QtCore/QMap>
#include <QtCore/QString>
#include <QtCore/QList>

A: You need to update your project. Go to the project properties by right-clicking on it in Solution Explorer and then select Properties. Then:

*

*In C/C++->General->Additional Include Directories you must set the Qt installation include path;

*In Linker->General->Additional Library Directories you must add the path of .libs files of your qt installation;

*In Linker->Input->Additional Dependencies you must put the name of .lib files that you need in order to build the project.

If it's a Qt project, you should also have the Qt plugin installed, in order to work properly with moc and other Qt features.
In alternative (that I suggest) you can create a CMake project and open in in Visual Studio.


text:
Q: Code First Optional One-To-One Relationship Writing a model for situation where I have two tables which are customers and users. Each user record might have an optional related customer record and vice versa, but none of them is a must. I figured out that FK Associations are not what I need, but Independent Associations are. But I just can find a way to make it work, I keep getting the 'Unable to determine the principal end...The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.' exception.
My models are very simple:
public class User
{
    [Key]
    public int          Id              { get; set; }
    [StringLength(20)]
    public string       CustomerId      { get; set; }
    public string       Password        { get; set; }
    public bool         Locked          { get; set; }

    //[ForeignKey("CustomerId")]
    public virtual Customer Customer    { get; set; }
}

public class Customer
{
    [Key]
    [Column("Id", TypeName = "nvarchar")]
    [StringLength(20)]
    public string       Id              { get; set; }   //  nvarchar    20
    [Required]
    public string       GivenName       { get; set; }   //  nvarchar    100
    [Required]
    public string       Surname         { get; set; }   //  nvarchar    100

    //[InverseProperty("Customer")]
    public virtual User User            { get; set; }
}

I've tried to add the ForeignKeyAttribute and InversePropertyAttribute, which are currently commented out, but they didn't help either. I would prefer to use data annotations and not fluent API, if it's possible in my case.

A: In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal. When configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent also be the foreign key.This problem is most easily solved by using a ForeignKey annotation on the dependent class to identify that it contains the foreign key. In your case, Customer could be  the dependent and its key, Customer.UserId, should also be the foreign key. But both Keys must be declared using the same type:
public class User
{
   [Key]
   public int  Id  { get; set; }

   public virtual Customer Customer { get; set; }
}

public class Customer
{
   [Key, ForeignKey("User")]
   public int  UserId { get; set; }

   public virtual User User{ get; set; }
}

I don't know how to resolve your problem using Data Annotations, but if you want to use Fluent Api, I think the configuration of the relationship would be like this:
 modelBuilder.Entity<User>().HasOptional(u => u.Customer).WithOptionalPrincipal(c => c.User);

Update
I understand your escenario, but if you have the same columns that you show in your model, I think  you  should have a one-to-many relationship mapped in DB instead one-to-one. Try to map your relationship this way:
public class User
{
    [Key]
    public int Id { get; set; }

    public string Password { get; set; }
    public bool Locked { get; set; }

    public string CustomerId { get; set; }

    [ForeignKey("CustomerId")]
    public virtual Customer Customer { get; set; }
}

public class Customer
{
    [Key]
    [Column("Id", TypeName = "nvarchar")]
    [StringLength(20)]
    public string Id { get; set; }   //  nvarchar    20
    [Required]
    public string GivenName { get; set; }   //  nvarchar    100
    [Required]
    public string Surname { get; set; }   //  nvarchar    100

    public virtual  ICollection<User> Users { get; set; }
}

Remember map your properties with the same column'names that you have in DB.


text:
Q: EF : order by 2 fields when they are not null I have an entity with fields:
public partial class Load
{
    public DateTime CreatedOn { get; set; }
    public DateTime? UpdatedOn { get; set; }
}

I have to order records (DESC) by following way:
If UpdatedOn has value then "look at" this value, else look at CreatedOn value. How to do it?

A: The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand
look here
 items.OrderBy(x => x.UpdatedOn ?? x.CreatedOn);

OR
 items.OrderByDescending(x => x.UpdatedOn ?? x.CreatedOn);


text:
Q: Can I use Azure Notification Hub for a custom push notifications service? Azure notifications hub supports pushing notifications to various notification services (android, ios, windows phone etc).  Is it possible to define a custom notification service to push notifications to?

A: Azure Notification Hubs - Frequently Asked Questions (FAQs):

*Which device platforms do you support?

  We support sending notifications to Apple iOS, Android, Windows
  Universal and Windows Phone, Kindle, Android China (via Baidu),
  Xamarin (iOS & Android), Chrome Apps platforms.

*Do you support SMS/Email/web notifications?

  Notification Hubs is primarily designed to send notifications to
  mobile apps using the above listed platforms. We do not provide
  capability to send email or SMS however third party platforms which
  provide these capabilities can be integrated along with Notification
  Hubs to send native push notifications by using Azure Mobile Services.
  E.g. this tutorial talks about how to send SMS notifications using
  Azure Mobile services - Send SMS with Mobile Services.We also do not
  provide an in-browser push notification out of the box. Customers may
  choose to implement this using SignalR. We also provide a tutorial for
  sending push notification to Chrome apps which will work on Google
  Chrome browser. See this - Chrome Apps tutorial.


text:
Q: Update meta_value in wp_postmeta using API I am trying to update a specific meta_key field using an API. meta_key name is _yoast_seo_redirect. it contains a redirect URL which we give in post options within wordpress.

What I am trying to achieve is, whenever someone hit the url like :
http://yoursite.com/wp-json/post_info/post?id=59&meta_value=www.google.com
it should update the post_id : 59 with meta_value : www.google.com
Write now, I am getting json error while trying to achieve this :
[
{
code: "json_no_route",
message: "No route was found matching the URL and request method"
}
]

Here is my function using which I am trying to achieve :
function get_post_details ($params)
{
    $id = $_GET['id'];
    $meta_value = $_GET['meta_value'];

    if(update_post_meta( $id, '_yoast_wpseo_redirect', $meta_value ))
    {
        $post['status'] = 'Successfully Updated';
        $post['flag'] = '1';
    }
    else
    {
        $post['status'] = 'Error';
        $post['flag'] = '0';
    }

    if( empty( $post ) ){
        return null;
    }

    return $post;
}

 // Register the rest route here.

add_action( 'rest_api_init', function () {
    register_rest_route( 'post_info', 'post',array(

            'methods'  => 'GET',
            'callback' => 'get_post_details'

        ));

});

Any help would be appreciated. Thank You !

A: I can't really recreate the error. Are you sure the script is properly loaded?
function get_post_details ($params)
{
    return rest_ensure_response( 'Hello World, this is the WordPress REST API' );
}

// Register the rest route here.
add_action( 'rest_api_init', function () {
    register_rest_route( 'post_info', 'post',array(
            'methods'  => 'GET',
            'callback' => 'get_post_details'
        ));
});

This gave me the expected response - so the route was correctly registered at
http://www.example.com/wp-json/post_info/post

As for the arguments, as suggested in the REST API docs, you should use $params instead of $_GET. Changing this and adding $post = array(); (so the variable is properly declared), made your code work on my local machine. You should probably check first, if these values are even set, also
function get_post_details ($params)
{
    $id = $params['id'];
    $meta_value = $params['meta_value'];

    $post = array();

    if(update_post_meta( $id, '_yoast_wpseo_redirect', $meta_value ))
    {
        $post['status'] = 'Successfully Updated';
        $post['flag'] = '1';
    }
    else
    {
        $post['status'] = 'Error';
        $post['flag'] = '0';
    }

    if( empty( $post ) ){
        return null;
    }

    return $post;
}

// Register the rest route here.
add_action( 'rest_api_init', function () {
    register_rest_route( 'post_info', 'post',array(
            'methods'  => 'GET',
            'callback' => 'get_post_details'
        ));
});

and the route
http://www.example.com/wp-json/post_info/post?id=21&meta_value=https://www.google.com

If you don't have pretty permalinks enabled, the route may look different!


text:
Q: Error when making requests using headers I am trying to make a request to a url with some headers and it doesn't seem to be working. I get an error (TypeError: expected string or bytes-like object)
import time
from rauth.service import OAuth1Service
import oauth
import rauth
import hmac
import requests
import oauth2 as oauth1

url = 'https://secure.trademe.co.nz/Oauth/RequestToken?scope=MyTradeMeRead,MyTradeMeWrite '

headers = {'oauth_callback': "http%3A%2F%2Fwww.website-tm-access.co.nz%2Ftrademe-callback",
          'oauth_consumer_key' : "C74CD73FDBE37D29BDD21BAB54BC70E422" ,
          'oauth_version': 1.0,
          'oauth_timestamp': int(time.time()),
          'oauth_nonce' : oauth1.generate_nonce(),
          'oauth_signature_method' : "HMAC-SHA1",
          'oauth_signature' : "5s3%2Bel078a5AXGi43FBDyfg5yWY%3D"
          }

r = requests.get(url, headers=headers)

following this:

To make the Authorization header, you simply append all the values starting with "OAuth". Each value must be URL encoded.

1. Authorization: OAuth oauth_callback="http%3A%2F%2Fwww.website-tm-access.co.nz%2Ftrademe-callback",
> oauth_consumer_key="C74CD73FDBE37D29BDD21BAB54BC70E422",
> oauth_version="1.0", oauth_timestamp="1285532322",
> oauth_nonce="7O3kEe", oauth_signature_method="HMAC-SHA1",
> oauth_signature="5s3%2Bel078a5AXGi43FBDyfg5yWY%3D"

We can finally make
  a request to the server. By making a request to
  https://secure.trademe.co.nz/Oauth/RequestToken?scope=MyTradeMeRead,MyTradeMeWrite
  with the Authorization header, we should get back an oauth_token and
  oauth_token_secret.
oauth_token=86EE20AFF655C34CB34873449A5F98020B&oauth_token_secret=905448B594595D5A030DC68BE40AE03C2B&oauth_callback_confirmed=true

A: The error says that you pass something else than a string as header value. And indeed,
 'oauth_version': 1.0,
 'oauth_timestamp': int(time.time()),

pass numeric values rather than string values. Make this strings and let's see whether it works.


text:
Q: Update Chart range to end Row I have created the below macro its working fine .. I wants to pick value to end Row dynamically instead $A$3:$A$328  .. something like Range("A3" & Rows.Count).End(xlUp).Row
Can anyone help me please
  Private Sub CommandButton1_Click()

    Dim arrCharts, cht
    Dim wb As Worksheet
    Dim wbTarget As Workbook
    Dim sh As Worksheet

    Set wbTarget = Workbooks.Open(Filename:="C:\Users\mahather\Desktop\Report\Summary Report.xlsx")
    Set wb = wbTarget.Worksheets("Graph")
    Set sh = wbTarget.Worksheets("Summary")

    arrCharts = Array("Chart 2", "Chart 5")

    For Each cht In arrCharts
        With wb.ChartObjects(cht).Chart
            .SeriesCollection(1).XValues = "='Summary'!$A$3:$A$328"
        End With
    Next cht

    End Sub

A: You could use the below code,
Dim LastRow As Long
 LastRow = ThisWorkbook.Sheets("Summary").UsedRange.Rows(ThisWorkbook.Sheets("Summary").UsedRange.Rows.Count).Row

and then edit the below line under for each
  .SeriesCollection(1).XValues = "='Summary'!$A$3:$A$" & LastRow

Let me know if this helps.


text:
Q: mysql insert if doesn't exist update I have more then 1 million records in tables.
   user_id name_id
    1       1
    1       2
    2       1

I have this structure and I need:
insert into (user_id,name_id) (1,2)

*

*if record exist = update name_id

*if record doen't exist insert
user_id and name_id

Who can write example for it? It should work fast.

A: insert into users (user_id, name_id)
values (1, 2)
on duplicate key update
  name_id = values(name_id);

You're gonna need a unique index for on duplicate key to work.


text:
Q: How to write mockito test case for logging? public void someMethod(Object obj) {
  ObjectMapper o = new ObjectMapper ();
  logger.info(o.writeValueAsString(obj));
}

I don't understand how to write test case for this.
I am using Apache log4j logger
And writing test case in mockito with spring boot
How to mock log when I have code like
class Someclass {

  Logger logger= LoggerFactory.getLogger(Someclass);
  //Some code and methods
}

Test class
class SomeclassTest{
  ...
  ...

  Logger logger;

  @Before {
  public void setup () {

  Mockito.when
    (LoggerFactory.getLoggers(Matchers.any(Class.class)))
   .thenReturn(logger);
  }
  ...
  ...
}


text:
Q: Sass can't compile mixin variables I recently purchased a template from templatemonster.com which contains the SASS source. I attempted to compile it using sass --update style.scss but it stopped and output this :
Error: Invalid CSS after "...x: #{$postfix}-": expected expression (e.g. 1px, bold), was ";"
    on line 7 of custom/mixins/_indent-utilities.scss

The offending code is a mixin. As I understand it, SASS is constantly changing how it handles variables. This error returned with current build 3.4.22. At first, I thought maybe something had been deprecated, so I tried a few other arbitrary versions of SASS, but to no avail. Unfortunately, the template came with no gemfile, so I have no idea what its dependencies are. Here is the offending code :
@mixin indent-responsive($prefix, $postfix, $rules, $medias, $offsets) {
  @if ($postfix != '' and $postfix != null) {
    $postfix: #{$postfix}-;
  }

  @if ($prefix != '' and $prefix != null) {
    $prefix: #{$prefix}-;
  }

  @each $resolution, $alias in $medias {
    @if ($resolution == 0) {
      @each $offset in $offsets {
        .#{$prefix}#{$postfix}#{strip-unit($offset)} {
          @each $rule in $rules {
            #{$rule}: $offset;
          }
        }
      }
    } @else {
      @media (min-width: $resolution) {
        @each $offset in $offsets {
          .#{$prefix}#{$alias}-#{$postfix}#{strip-unit($offset)} {
            @each $rule in $rules {
              #{$rule}: $offset;
            }
          }
        }
      }
    }
  }
}

If anyone could offer any insight, I'd super appreciate it!
Thanks! :)

A: Looks like it's not handling the string/interpolation right. Try changing this:
  @if ($postfix != '' and $postfix != null) {
    $postfix: #{$postfix}-;
  }

  @if ($prefix != '' and $prefix != null) {
    $prefix: #{$prefix}-;
  }

to this:
  @if ($postfix != '' and $postfix != null) {
    $postfix: $postfix + '-';
  }

  @if ($prefix != '' and $prefix != null) {
    $prefix: $prefix + '-';
  }


text:
Q: Changing from frameset/frame to iframe I am refreshing an older generation server-based web application which makes extensive use of   framesets and frames. I understand why frames are bad and iframes a better, HTML5 compliant solution.
What I'm struggling to achieve is the iframe equivalent of something easy to do with frames: a left 'menu' frame of fixed width, and a right 'content' frame which fills the remainder of width available, both with height 100%.
With frameset it is simply: <frameset cols="300,*">...</frameset>
With iframes the "*" isn't allowed to specify the remainder, dimensions must be specified as either px or %. Percent sounds like it should be ideal but it is not: if I make the browser 4000 px wide I want all the additional space to go into the content, not the menu.
Have searched widely and can't figure it out. I'm sure there's a simple css-based, non-js, HTML5-compliant way to do this, but I'm ignorant as to how. Thanks in advance.


text:
Q: $lookup on an array of objects matching by id So I have two collections, stock and store.
I'm trying to query the store by id.
my stock looks like this
{
  _id: ObjectId('5ee93b1e9f96dd1257885748')
  productId: 100,
  inStore: [
    {
      _id: ObjectId('5ee7ad659f96dd1257885742'),
      store: ObjectId('5ee906e59f96dd1257885745'),
      quantity: 10
    },
    {
      _id: ObjectId('5ee9085f9f96dd1257885746'),
      store: ObjectId('5ee904549f96dd1257885744'),
      quantity: 50
    }
  ]
}

With store being a referenced object to a store
store: { type: Types.ObjectId, ref: 'Store' },

{
  _id: ObjectId('5ee904549f96dd1257885744')
  name: 'Manchester Store'
}

What's the correct way to query by all stock documents, that contain inStore.store._id?
I'm currently trying this (following How do I query referenced objects in MongoDB?):
const inventories = await InventoryModel()
    .aggregate([
      { $unwind: "$inStore" },
      { $lookup: {
        from: "Store",
        localField: "inStore.store",
        foreignField: "_id",
        as: "inStore.store"
      }},
      {$match: {
        "inStore.store._id": '5ee906e59f96dd1257885745'
      }}
    ])

But I'm not getting any results? but I do notice that store is an empty array, when i remove the match condition.  How do I properly use lookup in this scenario?
Thanks in advance

A: *

*If you have the store id, you don't need to use the aggregation pipeline at all. Use  a simple find with condition

'inStore._id' => ObjectId('...')

*Your query condition uses a string, but your ids are ObjectIds. These are different values because their types are different and therefore you won't get any matches.


text:
Q: Failed building wheel for lap while loading google-coral example-object-tracker I'm a noob so please use laymen terms while supplying feedback.  I have a coral mini dev board and after shelling in, updating, etc outlined here I start with the examples at the coral site.  I follow instructions 1-3 here and then go to gstreamer and follow the instructions in that readme file.  Each time building of lap fails.  I have tried to pip install it on its own and end up with the same error.  This is a brand new board and I have only followed the instructions to update and implement the example.  Here is the error that I'm getting regardless of whether I bash install_requirements.sh or pip3 install lap:
mendel@green-orange:~/google-coral/example-object-tracker/gstreamer$ pip3 install lap
Collecting lap
  Using cached https://files.pythonhosted.org/packages/bf/64/d9fb6a75b15e783952b2fec6970f033462e67db32dc43dfbb404c14e91c2/lap-0.4.0.tar.gz
Building wheels for collected packages: lap
  Running setup.py bdist_wheel for lap ... error
  Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-dmwngj35/lap/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-yjkmj6gr --python-tag cp37:
  Partial import of lap during the build process.
  Generating cython files
  running bdist_wheel
  running build
  running config_cc
  unifing config_cc, config, build_clib, build_ext, build commands --compiler options
  running config_fc
  unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
  running build_src
  build_src
  building extension "lap._lapjv" sources
  building data_files sources
  build_src: building npy-pkg config files
  running build_py
  creating build
  creating build/lib.linux-aarch64-3.7
  creating build/lib.linux-aarch64-3.7/lap
  copying lap/__init__.py -> build/lib.linux-aarch64-3.7/lap
  copying lap/lapmod.py -> build/lib.linux-aarch64-3.7/lap
  running build_ext
  customize UnixCCompiler
  customize UnixCCompiler using build_ext
  customize UnixCCompiler
  customize UnixCCompiler using build_ext
  building 'lap._lapjv' extension
  compiling C++ sources
  C compiler: aarch64-linux-gnu-g++ -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC

  creating build/temp.linux-aarch64-3.7/lap
  compile options: '-I/usr/lib/python3/dist-packages/numpy/core/include -Ilap -I/usr/lib/python3/dist-packages/numpy/core/include -I/usr/include/python3.7m -c'
  aarch64-linux-gnu-g++: lap/_lapjv.cppaarch64-linux-gnu-g++: lap/lapjv.cppaarch64-linux-gnu-g++: lap/lapmod.cpp

  lap/_lapjv.cpp:4:10: fatal error: Python.h: No such file or directory
   #include "Python.h"
            ^~~~~~~~~~
  compilation terminated.
  error: Command "aarch64-linux-gnu-g++ -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/lib/python3/dist-packages/numpy/core/include -Ilap -I/usr/lib/python3/dist-packages/numpy/core/include -I/usr/include/python3.7m -c lap/_lapjv.cpp -o build/temp.linux-aarch64-3.7/lap/_lapjv.o -MMD -MF build/temp.linux-aarch64-3.7/lap/_lapjv.o.d" failed with exit status 1

  ----------------------------------------
  Failed building wheel for lap
  Running setup.py clean for lap
Failed to build lap
Installing collected packages: lap
  Running setup.py install for lap ... error
    Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-dmwngj35/lap/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-ftdhrrmv/install-record.txt --single-version-externally-managed --compile --user --prefix=:
    Partial import of lap during the build process.
    Generating cython files
    running install
    running build
    running config_cc
    unifing config_cc, config, build_clib, build_ext, build commands --compiler options
    running config_fc
    unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
    running build_src
    build_src
    building extension "lap._lapjv" sources
    building data_files sources
    build_src: building npy-pkg config files
    running build_py
    creating build
    creating build/lib.linux-aarch64-3.7
    creating build/lib.linux-aarch64-3.7/lap
    copying lap/__init__.py -> build/lib.linux-aarch64-3.7/lap
    copying lap/lapmod.py -> build/lib.linux-aarch64-3.7/lap
    running build_ext
    customize UnixCCompiler
    customize UnixCCompiler using build_ext
    customize UnixCCompiler
    customize UnixCCompiler using build_ext
    building 'lap._lapjv' extension
    compiling C++ sources
    C compiler: aarch64-linux-gnu-g++ -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC

    creating build/temp.linux-aarch64-3.7/lap
    compile options: '-I/usr/lib/python3/dist-packages/numpy/core/include -Ilap -I/usr/lib/python3/dist-packages/numpy/core/include -I/usr/include/python3.7m -c'
    aarch64-linux-gnu-g++: lap/_lapjv.cppaarch64-linux-gnu-g++: lap/lapjv.cppaarch64-linux-gnu-g++: lap/lapmod.cpp

    lap/_lapjv.cpp:4:10: fatal error: Python.h: No such file or directory
     #include "Python.h"
              ^~~~~~~~~~
    compilation terminated.
    error: Command "aarch64-linux-gnu-g++ -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/lib/python3/dist-packages/numpy/core/include -Ilap -I/usr/lib/python3/dist-packages/numpy/core/include -I/usr/include/python3.7m -c lap/_lapjv.cpp -o build/temp.linux-aarch64-3.7/lap/_lapjv.o -MMD -MF build/temp.linux-aarch64-3.7/lap/_lapjv.o.d" failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-dmwngj35/lap/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-ftdhrrmv/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in /tmp/pip-install-dmwngj35/lap/

Thank you in advance

A: Can you run sudo apt-get install python3-dev and then retry the demo?


text:
Q: Upload script to SharePoint Online Web Part I have a web part that will render an existing report on Report Server. The way I found to do this, is to render the report in a App Part using <iframe/> and then reference the App Part in a web part using <Content Type="html" Src="~appWebUrl/Pages/Default.aspx" />. However I will need to access the web part properties from the javascript. I'm trying to see if this is possible by using this function with a breakpoint on the 3rd line just to check if we were able to pull the properties:
function getWebPartProperties() {
    var object = $('#gordoWebPart');
    var properties = object.get_properties();
    var properties2 = object.get_properties();
}

And I'm referencing this script in my App Part using  <script type="text/javascript" src="../Scripts/App.js"></script>. The problem is that even though I can see the App.js loaded in my App Part (using IE developer tools), I can't see the script loaded on my web part.
Am I registering the script in the wrong way? How should I approach this?

A: You need to use querystrings to get the webpart properties, as used in this example:
<Content Src="~remoteAppUrl/AppPartContent.html?strProp=_strProp_&intProp=_intProp_&boolProp=_boolProp_&enumProp=_enumProp_"
        Type="html"/>

Then you can get that from your javascript:
http://www.joezimjs.com/javascript/3-ways-to-parse-a-query-string-in-a-url/
Have a look at this article, I have extracted the code from there:
http://msdn.microsoft.com/en-us/library/office/fp179921(v=office.15).aspx


text:
Q: Where is the keybinding located in dconf for v for Ubuntu 19.10? Pressing the key combination, <Super>v, will open the notification tray at the top of the screen.
I intend to override this key combination but can't seem to find where it's located in gsettings or in dconf.
For example, I'd love to remove the keybinding like this: dconf write /org/gnome/desktop/wm/keybindings/notificationTray "['']"

A: It is in the system keyboard shortcuts..

The gsettings thing is
org.gnome.shell.keybindings toggle-message-tray ['<Super>v', '<Super>m']

to remove the binding Super+V you can run
gsettings set org.gnome.shell.keybindings toggle-message-tray "['<Super>m']"

for dconf way..
dconf write /org/gnome/shell/keybindings/toggle-message-tray "['<Super>m']"

for resetting to default
dconf reset /org/gnome/shell/keybindings/toggle-message-tray