text:
Q: Trouble with returning value from form javascript I have a select drop down box which will return a specific value when chosen, which is working fine. However i have tried to add number of adults text form to return that value when the same button is pressed and nothing works, it is confusing me because it seems that it should be simple but nothing i try is working, Here is my HTML:
        <form>
    <select id = "journeyList">
    <option name ="Bristol " value="40">Bristol - Newcastle</option>
    <option name ="London " value="35" >Bristol - London</option>
    <option name ="Glasgow " value="70" >Glasgow - Manchester</option>
    </select>

    </form>

    Number of Adults:
    <form>
    <input type = "number" name ="adult" id="ofAdults" value="" required>
    </form>
    <button type="button" onclick="BookingFare(); return false;">Submit</button>

Javascript:
function BookingFare() {

        var journeyList = document.getElementById("journeyList");
        var price = journeyList.options[journeyList.selectedIndex].value;

        var Adults = getElementById("ofAdults").value;
        //var ofChildren = getElementById('children').value;
        //var Discount
        //var Total
        //var SeatsLeft

        if (journeyList == 40) {
         var price = journeyList.value;
        }

        if (journeyList == 35) {
         var price = journeyList.value;

        }

        if (journeyList == 70) {
         var price = journeyList.value;
        }

        document.getElementById('priceBox').innerHTML = price;
        document.getElementById('adultsBox').innerHTML = Adults;

        }

It is only the returning value of adults that i am having issues with.

A: You are missing "document." when accessing ofAdults element.
It should be

var Adults = document.getElementById("ofAdults").value

A: HTML
<select id = "journeyList">
    <option name ="Bristol " value="40">Bristol - Newcastle</option>
    <option name ="London " value="35" >Bristol - London</option>
    <option name ="Glasgow " value="70" >Glasgow - Manchester</option>
    </select>

    Number of Adults:
    <form>
    <input type = "number" name ="adult" id="ofAdults" value="" required>

    <button type="button" onclick="BookingFare(); return false;">Submit</button>

JAVASCRIPT
function BookingFare() {

        var journeyList = document.getElementById("journeyList");
        var price =journeyList.options[journeyList.selectedIndex].value;

        var Adults = document.getElementById("ofAdults").value;

        document.getElementById('priceBox').innerHTML = price;
        document.getElementById('adultsBox').innerHTML = Adults;

        }

this will display the current list value and textbox value in your div
DEMO
Note1:
your  if statement need some modification
in your case journeyList is an object so you can't directly do something like below
 if (journeyList == 40) {
         var price = journeyList.value;
        }

if you want to do something with if  then you must do like following
 if (journeyList.options[journeyList.selectedIndex].value== '40')

{
// your code goes here

}

Note2: normally we are taking the select values in onchange event. So i thing it is better to use onchange event, then no need of a button click here you can see the details at the time of selection changed.
If you want it in that way then use following code
<select id = "journeyList" onchange="BookingFare();">
    <option name ="Bristol " value="40">Bristol - Newcastle</option>
    <option name ="London " value="35" >Bristol - London</option>
    <option name ="Glasgow " value="70" >Glasgow - Manchester</option>
    </select>

    Number of Adults:
    <form>
    <input type = "number" name ="adult" id="ofAdults" value="" required>

    <button type="button">Submit</button>

js
function BookingFare() {

        var journeyList = document.getElementById("journeyList");
        var price =journeyList.options[journeyList.selectedIndex].value;

        var Adults = document.getElementById("ofAdults").value;

        document.getElementById('priceBox').innerHTML = price;
        document.getElementById('adultsBox').innerHTML = Adults;

        }

no need to click a button
here
DEMO


text:
Q: Defining a binary treatment based on a proportion I want to explore the effect of bringing in more female students into a classroom on the existing individual students' performance using a panel dataset. However, there is no particular policy change or clear cutoff. Could I define the treatment as a binary variable that equals one when the percentage of new students who are female > 80% and use that to define treatment (where post-treatment is based on the first year that passing this threshold happens) in a typical difference-in-differences (DD) model?
In this specification, I would interpret the treatment as a "shift" to more gender diversity. Does this approach complicate identification? I am mainly leaning towards DD because I also want to do an event study analysis, but the threshold aspect also makes me think about using a regression discontinuity design.
Other ways I've thought of getting at this question is using a simple two-way fixed effects regression that includes year and individual fixed effects, while using the percentage of new students who are female as the key explanatory variable.
What are the potential problems with these approaches?

A: I see a few potential problems.

*

*The cutoff seems arbitrary; it's defined by you. In fact, you're in complete control of the treatment assignment process, whereas in most difference-in-differences applications the process is outside the control of the evaluator.

*You're losing information. Binarizing the treatment in this way is saying a classroom with .79 female representation isn't a diverse environment, yet a classroom with .81 female representation is. Discretization ignores the gradations off new female representation over time.

*The irregular exposure patterns will make your event study difficult to interpret. Say you're observing students over many years. A typical student may be in a classroom with .7 representation in one year and .9 in the next. The binary treatment indicator would 'turn on' (i.e., switch from 0 to 1) once the threshold is crossed, but you've given no indication that the treatment is permanent. In a subsequent period, a student is just as likely to be nested within a group just under the demarcation line, in which case the binary treatment indicator should now 'turn off' (i.e., switch from 1 back to 0). Unless you're making the claim that once the threshold is reached that entities stay treated in all subsequent periods, then you should account for all 'on' and 'off' periods of treatment.
It will be difficult to advise you further without knowing more information. I would be interested in seeing a treatment variation plot to see when entities move into (out of) of a treated condition across time. Since you're ignoring the continuous nature of your diversification variable, your treatment effect is reduced to variation in treatment timing.
I suppose the principal question is why did you choose female representation in excess of .8 as the cutoff? Why not .5? What does theory tell you about the relationship between female enrollment and scholastic achievement? I would hope your assignment process has some theoretical grounding. And what about classrooms where male representation goes to 0 over time? The cohort is above .8 so it's "treated" according to your definition, but is it still diverse?
You've also given little information about the nested nature of your data. Do you have students nested within classrooms, nested within schools, nested within school districts? And what about the characteristics of the classrooms or the schools? Is the dataset a mixture of public and private schools? If it's universities, what about exploiting differences across disciplines? Do you consider student-teacher ratios? And what about mobility patterns? Can a student switch classrooms or school districts over time?
I didn't pose these questions to confuse you. Rather, I did it to show you how difficult it is to advise you given the finite information provided in your post. Since you're interested in how the diversification of the "group" (i.e., classroom, school, district, etc.) affects individual level academic outcomes, then perhaps a multilevel model is more appropriate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot resolve plugs-ins in Intellij after upgrading to version 2019.3 (CE) I have just upgraded my Intellij from version 2019.2.x to 2019.3 but am getting the following Maven plug-in errors in my Java project.

Cannot resolve plugin org.codehaus.mojo:exec-maven-plugin:1.6.0
Cannot resolve plugin org.apache.maven.plugins:maven-resources-plugin:3.1.0

Below are the versions listed of Maven (which I just upgraded from 3.6.0 to 3.6.3) and Java v11.
> Apache Maven 3.6.3  Maven home: /usr/local/Cellar/maven/3.6.3/libexec
> Java version: 11.0.2, vendor: Oracle Corporation, runtime:
/Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home Default
locale: en_GB, platform encoding: UTF-8 OS name: "mac os x", version:
"10.15.1", arch: "x86_64", family: "mac"

Below is an extract from the intellij log file (idea.log)

2019-11-29 13:05:06,759 [4279936]   INFO - pl.ProjectRootManagerComponent - project roots have changed
2019-11-29 13:05:06,794 [4279971]   INFO - .diagnostic.PerformanceWatcher - Pushing properties took 4ms; general responsiveness: ok; EDT responsiveness: ok
2019-11-29 13:05:06,815 [4279992]   INFO - .diagnostic.PerformanceWatcher - Indexable file iteration took 20ms; general responsiveness: ok; EDT responsiveness: ok
2019-11-29 13:05:07,480 [4280657]   INFO -      #org.jetbrains.idea.maven - org.apache.maven.plugin.PluginResolutionException: Plugin org.codehaus.mojo:exec-maven-plugin:1.6.0 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.codehaus.mojo:exec-maven-plugin:jar:1.6.0
java.lang.RuntimeException: org.apache.maven.plugin.PluginResolutionException: Plugin org.codehaus.mojo:exec-maven-plugin:1.6.0 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.codehaus.mojo:exec-maven-plugin:jar:1.6.0
 at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolve(DefaultPluginDependenciesResolver.java:120)
 at org.jetbrains.idea.maven.server.Maven3XServerEmbedder.resolvePlugin(Maven3XServerEmbedder.java:1161)
 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.base/java.lang.reflect.Method.invoke(Method.java:566)
 at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
 at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
 at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
 at java.base/java.security.AccessController.doPrivileged(Native Method)
 at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
 at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
 at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
 at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
 at java.base/java.security.AccessController.doPrivileged(Native Method)
 at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
 at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
 at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
 at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.RuntimeException: org.eclipse.aether.resolution.ArtifactDescriptorException: Failed to read artifact descriptor for org.codehaus.mojo:exec-maven-plugin:jar:1.6.0
 at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:255)
 at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:171)
 at org.eclipse.aether.internal.impl.DefaultRepositorySystem.readArtifactDescriptor(DefaultRepositorySystem.java:255)
 at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolve(DefaultPluginDependenciesResolver.java:106)
 ... 18 more
Caused by: java.lang.RuntimeException: org.eclipse.aether.resolution.ArtifactResolutionException: Failure to transfer org.codehaus.mojo:exec-maven-plugin:pom:1.6.0 from https://nexus.xxisp.yyyyyy.net/repository/public/ was cached in the local repository, resolution will not be reattempted until the update interval of nexus has elapsed or updates are forced. Original error: Could not transfer artifact org.codehaus.mojo:exec-maven-plugin:pom:1.6.0 from/to nexus (https://nexus.xxisp.yyyyyy.net/repository/public/): Connect to nexus.xxisp.yyyyyy.net:443 [nexus.xxisp.yyyyyy.net/81.135.143.77] failed: Operation timed out (Connection timed out)
 at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:424)
 at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:229)
 at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact(DefaultArtifactResolver.java:207)
 at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:240)
 ... 21 more
Caused by: java.lang.RuntimeException: org.eclipse.aether.transfer.ArtifactTransferException: Failure to transfer org.codehaus.mojo:exec-maven-plugin:pom:1.6.0 from https://nexus.xxisp.yyyyyy.net/repository/public/ was cached in the local repository, resolution will not be reattempted until the update interval of nexus has elapsed or updates are forced. Original error: Could not transfer artifact org.codehaus.mojo:exec-maven-plugin:pom:1.6.0 from/to nexus (https://nexus.xxisp.yyyyyy.net/repository/public/): Connect to nexus.xxisp.yyyyyy.net:443 [nexus.xxisp.yyyyyy.net/81.135.143.77] failed: Operation timed out (Connection timed out)
 at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.newException(DefaultUpdateCheckManager.java:225)
 at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.checkArtifact(DefaultUpdateCheckManager.java:193)
 at org.eclipse.aether.internal.impl.DefaultArtifactResolver.gatherDownloads(DefaultArtifactResolver.java:559)
 at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:483)
 at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:401)
 ... 24 more

Does anyone know how to debug this and better fix it ?
UPDATE:
I have managed to resolve the issue now. I think the problem was that although at the time that I did the upgrade I was connected to the internet I wasn't connected to my company VPN (as I was working from home that day) and this may have caused the look-up to my company's NEXUS repo to fail. Later, when I did connect to the VPN, Maven wasn't able to re-sync the plug-ins for some reason. So the issue wasn't related to the Intellij upgrade at all. I hope this technique to resolve these types of errors can help someone else.

A: This post gist/github  helped me to resolve both issues.
1/Cannot resolve plugin org.codehaus.mojo:exec-maven-plugin:1.6.0
I located the entry for this plugin in the .m2 directory,
/Users/my-user/.m2/repository/org/codehaus/mojo/exec-maven-plugin/1.6.0
I deleted this entry and did a Maven re-sync from within Intellij. This time it seemed to find it ok.
I managed to fix the second error using the same approach,
2/Cannot resolve plugin org.apache.maven.plugins:maven-resources-plugin:3.1.0
this plug-in is located under,
/Users/my-user/.m2/repository/org/apache/maven/plugins/maven-resources-plugin/3.1.0
I deleted this entry as well and then did another Maven re-sync from within Intellij and this worked too.


text:
Q: Struts 2 json result for List of arrays I have an ArrayList of arrays ArrayList<[obj1,obj2]>. Here obj1 and obj2 are different Java entities and this list is returned by a HQL query.
How to loop through this list in struts.xml file to send this as JSON result?
I tried below combination but with no luck:

*

*^itemList\[\d+\]\.^\[\0+\].id --> id is a property of entity

*^itemList\[\d+\]\.\0\.id

*^itemList\[\d+\]\.co.id --> co = entity alias in hql

*^itemList\[\d+\]\[0].id

*^itemList\[\d+\]\.\[\0+\].id

*^itemList\[\d+\]\.[0].id
edit:
I used it in struts.xml as follows;
<action name="list-view-op-cost-management_cons"  class="com.eves.aixis.s2.action.billing.ConsignmentBillingGridAction" method="listViewOperationalCostForManagement">
            <result type="json">
                <param name="ignoreHierarchy">false</param>
                <param name="includeProperties">
                    viewType,
                    searchType,
                    searchValue,
                    service,
                    page,
                    total,
                    records,
                    **^itemList\[\d+\]\.^\[\0+\].id,**
                    reqaction_,
                    actionResult,
                    ^errorList\[\d+\]

                </param>
            </result>
        </action>

Edit:
Obj1 = Consignment(Bussiness entity)
with fileds;
private Integer id;
    private String consignmentNo;
    private Customer sender;
    private Contact senderContact;
    private Pickup pickupRef;
    private Receiver receiver;
    private List<Invoice> invoiceList;
    private ConsignmentStatus consignmentStatus;
    private Boolean invoiceToReiver;
    private String deliveryInstruction;
    private String customerReference;
    private List<PackageDescription> packageDescription;// actual package info
    private List<PackageDescription> custPackage;//use in ecp (external customer portal) and use in inquiry given customer package details
    private List<PackageDescription> revProtPackages;//revenue protection packages

    private Receiver deliveryAddress;
    private List<ConsignmentTrack> connoteTrack;
    private ProductType productType;
    private List<Commodity> commodities;
    private PreBriefDeskVerify briefDeskVerify;

and obj2 = SalesOrder(Bussiness entity)
with fileds;
private Long id;
    private SalesOrderType salesItemType;

    private Consignment salesItem;

    private MasterAirwayBill mawb;
    private Pickup pickupSI;
    private Delivery deliverySI;

    private WHSalesItem whSalesItem;

    private Job job;
    private SCMBillingState billingState;

    private Tariff tariff;

    private Tariff tariffForPrinciples;

    private List<SalesOrderLineItem> salesOrderItemList;
    private String remarks;
    private SalesOrderStatus salesOrderStatus;

A: The param includeProperties contains a list of regexes, that you use to match properties of the serializable to JSON object. This regex expression should match your property name, try it
^itemList.*$

If you want only id property, then you can try
^itemList.*\.id$


text:
Q: Prefer the other machine without having to set up a socket? I use Unison to sync stuff between some Linux devices. I want to have a profile set up where, if I'm running unison from machine A to sync between A and B, I can override my prefer = newer setting and preferpartial certain files from B over files from A, even if A's are newer.
Reading the docs, it seems like the only way I can do that is by setting up a socket on B, and either making sure I can refer to B by its hostname, or keep track of its IP address. This answer to another post seems to have confirmed that that is the way.
But that seems super roundabout for something that really shouldn't have been hard to implement as a simple option that doesn't need to refer to the other machine in a 2-machine operation by hostname or IP. Isn't there a simpler way?

A: Can you write an ignore pattern to match the certain files you are talking about? If so, what you could do is to use separate Unison profiles. First run Unison with a profile that does most of your syncing with all your prefer and preferpartial options, but ignore the files you're talking about. Then run Unison with a profile that is exactly the same except without the perfer or preferpartial or ignore options. The only changes that Unison will detect during that second run will be the files you wanted to prefer the copy on root A over the copy on root B. So you can just tell Unison to prefer root A in this second profile.


text:
Q: how to solve permission classes or logics that are not working I have a permission_classes in modelviewset like this :
class MeetingViewSet(viewsets.ModelViewSet):

queryset = Meeting.objects.all()

serializer_class = MeetingSerializer
permission_classes =[IsOwner|IsCreator|IsInvited]

and this is the related model :
class Meeting(models.Model):

    TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones))

    title = models.CharField(max_length=255)
    description = models.TextField()

    # Date Time Is in UTC
    date_time = models.DateTimeField()
    time_zone = models.CharField(max_length=32, choices=TIMEZONES,
    default='UTC')

    #TODO: Convert to REMOTE_USER, Temperory integer
    host = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)

    is_private = models.BooleanField(default=True)
    is_virtual = models.BooleanField(default=True)

    url = models.CharField(blank=True,max_length=100)

    deleted = models.BooleanField(default=False)
    time_created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s' % (self.title)
        # TODO: Return host.username after bringup REMOTE_USER

    def is_invited(self, email):
        meeting = MeetingMember.objects.filter(meeting=self, email=email)
        if meeting.exists():
            return True
        return False

IsOwner is for the owner to update/delete/get/post and Iscreateor is for method post to create new object and IsInvited for method Get and invited users exististing in model :
class IsOwner(BasePermission):

    def has_object_permission(self, request, view, object):

        return  request.user.pk == object.host and request.user.is_authenticated

class IsCreator(BasePermission):

    def has_permission(self, request ,view):

        return request.method == 'POST' and request.user.is_authenticated

class IsInvited(BasePermission):

    message = 'you must have been invited to see this meeting'

    def has_object_permission(self,request, view,object):

        return request.method == 'GET' and object.is_invited(request.user.email) and request.user.is_authenticated

and user must be authenticated in all three classes but when i use simple jwt   and authenticate with a different user i can still get objects created by another user which should be forbidden bcs only the owner can access the object what am i missing?

A: After studing This Turorial, i realized that i needed to check the authentication only in has_permission so i changed the code like this and it works :
class IsOwner(BasePermission):
    def has_permission(self, request, view):
        if request.user.is_authenticated:
            return True
        return False

    def has_object_permission(self, request, view, object):
        if request.user == object.host:
            return True
        return False

class IsInvited(BasePermission):

    def has_permission(self, request, view):
        if request.user.is_authenticated:
            return True
        return False

    def has_object_permission(self,request, view,object):
        if  object.is_invited(request.user.email):
            return True
        return False


text:
Q: Create a BAT that can open a selection of executables? I want to make a batch file that gives me a selection to open various executables. For example,
What do you want to open?
1. Application1.exe
2. Application2.exe
3. Application3.exe

Inputting a number will open the desired executable that isn't in the same directory as the batch file itself. So it's basically a launcher.

A: @echo off
:input
    echo What do you want to open?
    echo 1. Application1.exe
    echo 2. Application2.exe
    echo 3. Application3.exe
    set /p "app=: "
    if "%app%"=="1" goto :start Application1.exe
    if "%app%"=="2" goto :start Application2.exe
    if "%app%"=="3" goto :start Application3.exe
    echo Invalid option!
goto :input
:start
    start "" "%~1"
exit


text:
Q: How do I completely kill a View Controller? In my app I am changing views using presentModalViewController, then release the new view controller at the end but somehow it keeps the old view controller active. So is there any way to just completely kill a view controller I am not using?
Thanks!

A: You should release all the views inside the controller as well, this could be your issue.

A: Not with presentModalViewController. By using presentModalViewController the new view will be displayed inside the original View, just the animation looks like it is above it.


text:
Q: Calculating $\lim\limits_{x\rightarrow 0^{+}} \frac{x^{\min(a,b)}}{x^a+x^b}$ It seems like $\lim\limits_{x\rightarrow 0^{+}} \dfrac{x^{\min(a,b)}}{x^a+x^b}$ is $1$ if $a\ne b$, regardless of the values of $a$ and $b$, but is this true? What does this limit equal in general?
Thanks!

A: Wlog $a\le b$. Then your fraction is equal to $$\frac{1}{1+x^{(b-a)}}$$ If $b=a$ this is equal to $1/2$. If not, it tends to $1$ when $x$ tends to $0$.

A: I should say that it is trivial. For $x\rightarrow 0$ you should keep the smaller power of $x$. That is it. But if $a\neq b$ then, for sure, $b>a$ and you should keep just terms containing $a$ and again you have 1.

A: Without loss of generality assume that $a\le b$. Then $$\lim_{x\to 0^+}\frac{x^a+x^b}{x^a}=1+\lim_{x\to 0^+}x^{b-a}=\begin{cases}
2,&b=a\\
1,&b>a\;,
\end{cases}$$
so $$\lim_{x\to 0^+}\frac{x^a}{x^a+x^b}=\begin{cases}
\frac12,&b=a\\\\
1,&b>a\;.
\end{cases}$$

A: HINT $\ $ It is easy to compute the limit of a quotient of two polynomials having equal order $\rm\:n\:$ because cancelling their common factor $\rm\:x^{\:n}\:$ leaves a determinate limit, namely
$$\rm\lim_{x\ \to\ 0}\ \frac{f_{\:n}\: x^{\:n} + f_{\:n+1}\ x^{\:n+1}+\ \cdots}{g_{\:n}\: x^n+g_{\:n+1}\: x^{\:n+1}\:+\ \cdots}\ =\ \lim_{x\ \to\ 0}\ \frac{f_{\:n} + f_{\:n+1}\: x\ +\ \cdots}{g_{\:n} +g_{\:n+1}\: x \:+\ \cdots}\ =\ \frac{f_n}{g_n}$$


text:
Q: Prolog - count occurrence of number I want to write predicate which can count all encountered number:
count(1, [1,0,0,1,0], X).
X = 2.

I tried to write it like:
count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.

Why doesn't work it?

A:
Why doesn't work it?

Prolog is a programming language that often can answer such question directly. Look how I tried out your definition starting with your failing query:
?- count(1, [1,0,0,1,0], X).
   false.
?- count(1, Xs, X).
   Xs = [], X = 0
;  Xs = [1], X = 1
;  Xs = [1,1], X = 2
;  Xs = [1,1,1], X = 3
;  ... .
?- Xs = [_,_,_], count(1, Xs, X).
   Xs = [1,1,1], X = 3.

So first I realized that the query does not work at all, then I generalized the query. I replaced the big list by a variable Xs and said: Prolog, fill in the blanks for me! And Prolog did this and reveals us precisely the cases when it will succeed.
In fact, it only succeeds with lists of 1s only.  That is odd.  Your definition is too restricted - it correctly counts the 1s in lists where there are only ones, but all other lists are rejected. @coder showed you how to extend your definition.
Here is another one using library(reif) for
SICStus|SWI. Alternatively, see tfilter/3.
count(X, Xs, N) :-
   tfilter(=(X), Xs, Ys),
   length(Ys, N).

A definition more in the style of the other definitions:
count(_, [], 0).
count(E, [X|Xs], N0) :-
   if_(E = X, C = 1, C = 0),
   count(E, Xs, N1),
   N0 is N1+C.

And now for some more general uses:

How does a four element list look like that has 3 times a 1 in it?

?- length(L, 4), count(1, L, 3).
   L = [1,1,1,_A], dif(1,_A)
;  L = [1,1,_A,1], dif(1,_A)
;  L = [1,_A,1,1], dif(1,_A)
;  L = [_A,1,1,1], dif(1,_A)
;  false.

So the remaining element must be something different from 1.
That's the fine generality Prolog offers us.

A: The problem is that as stated by @lurker if condition (or better unification) fails then the predicate will fail. You could make another clause for this purpose, using dif/2 which is pure and defined in the iso:
count(_, [], 0).
count(Num, [H|T], X) :- dif(Num,H), count(Num, T, X).
count(Num, [H|T], X) :- Num = H, count(Num, T, X1), X is X1 + 1.

The above is not the most efficient solution since it leaves many choice points but it is a quick and correct solution.

A: You simply let the predicate fail at the unification Num = X. Basically, it's like you don't accept terms which are different from the only one you are counting.
I propose to you this simple solution which uses tail recursion and scans the list in linear time. Despite the length, it's very efficient and elegant, it exploits declarative programming techniques and the backtracking of the Prolog engine.
count(C, L, R) :-
    count(C, L, 0, R).

count(_, [], Acc, Acc).
count(C, [C|Xr], Acc, R) :-
    IncAcc is Acc + 1,
    count(C, Xr, IncAcc, R).
count(C, [X|Xr], Acc, R) :-
    dif(X, C),
    count(C, Xr, Acc, R).

count/3 is the launcher predicate. It takes the term to count, the list and gives to you the result value.
The first count/4 is the basic case of the recursion.
The second count/4 is executed when the head of the list is unified with the term you are looking for.
The third count/4 is reached upon backtracking: If the term doesn't match, the unification fails, you won't need to increment the accumulator.
Acc allows you to scan the entire list propagating the partial result of the recursive processing. At the end you simply have to return it.

A: I solved it myself:
count(_, [], 0).
count(Num, [H|T], X) :- Num \= H, count(Num, T, X).
count(Num, [H|T], X) :- Num = H, count(Num, T, X1), X is X1 + 1.

A: I have decided to add my solution to the list here.
Other solutions here use either explicit unification/failure to unify, or libraries/other functions, but mine uses cuts and implicit unification instead. Note my solution is similar to Ilario's solution but simplifies this using cuts.
count(_, [], 0) :- !.

count(Value, [Value|Tail],Occurrences) :- !,
    count(Value,Tail,TailOcc),
    Occurrences is TailOcc+1.

count(Value, [_|Tail], Occurrences) :- count(Value,Tail,Occurrences).

How does this work? And how did you code it?
It is often useful to equate solving a problem like this to solving a proof by induction, with a base case, and then a inductive step which shows how to reduce the problem down.
Line 1 - base case
Line 1 (count(_, [], 0) :- !.) handles the "base case".
As we are working on a list, and have to look at each element, the simplest case is zero elements ([]). Therefore, we want a list with zero elements to have no instances of the Value we are looking for.
Note I have replaced Value in the final code with _ - this is because we do not care what value we are looking for if there are no values in the list anyway! Therefore, to avoid a singleton variable we negate it here.
I also added a ! (a cut) after this - as there is only one correct value for the number of occurrences we do not want Prolog to backtrack and fail - therefore we tell Prolog we found the correct value by adding this cut.
Lines 2/3 - inductive step
Lines 2 and 3 handle the "inductive step". This should handle if we have one or more elements in the list we are given. In Prolog we can only directly look at the head of the list, therefore let us look at one element at a time. Therefore, we have two cases - either the value at the head of the list is the Value we are looking for, or it is not.
Line 2
Line 2 (count(Value, [Value|Tail],Occurrences) :- !, count(Value,Tail,TailOcc), Occurrences is TailOcc+1.) handles if the head of our list and the value we are looking for match. Therefore, we simply use the same variable name so Prolog will unify them.
A cut is used as the first step in our solution (which makes each case mutually exclusive, and makes our solution last-call-optimised, by telling Prolog not to try any other rules).
Then, we find out how many instances of our term there are in the rest of the list (call it TailOcc). We don't know how many terms there are in the list we have at the moment, but we know it is one more than there are in the rest of the list (as we have a match).
Once we know how many instances there are in the rest of the list (call this Tail), we can take this value and add 1 to it, then return this as the last value in our count function (call this Occurences).
Line 3
Line 3 (count(Value, [_|Tail], Occurrences) :- count(Value,Tail,Occurrences).) handles if the head of our list and the value we are looking for do not match.
As we used a cut in line 2, this line will only be tried if line 2 fails (i.e. there is no match).
We simply take the number of instances in the rest of the list (the tail) and return this same value without editing it.


text:
Q: Split files into a TFileStream I'm doing two functions to join and divide files in a TFileStream, the code:
Join
procedure TFormHome.btnJoinClick(Sender: TObject);
var
  InStream, OutStream: TFileStream;
  OutFileName, InFileName1, InFileName2: string;
begin
  OutFileName := 'salida.out';
  InFileName1 := 'image.jpg';
  InFileName2 := 'test.exe';
  OutStream := TFileStream.Create(OutFileName, fmCreate);
  try
    InStream := TFileStream.Create(InFileName1, fmOpenRead);
    ShowMessage(IntToStr(InStream.Size));
    try
      OutStream.CopyFrom(InStream, InStream.Size);
    finally
      InStream.Free;
    end;
    InStream := TFileStream.Create(InFileName2, fmOpenRead);
    ShowMessage(IntToStr(InStream.Size));
    try
      OutStream.CopyFrom(InStream, InStream.Size);
    finally
      InStream.Free;
    end;
  finally
    OutStream.Free;
  end;
end;

Divide
procedure TFormHome.btnUnJoinClick(Sender: TObject);
var
  Source, Target: TStream;
  Buffer: array of Byte;
  i: Integer;
  SourceName, TargetNames: string;
  SizeTargets: Integer;
begin
  SourceName := 'salida.out';
  TargetNames := 'test.exe';
  SizeTargets := 2232832;
  Source := TFileStream.Create(SourceName, fmOpenRead);
  Target := TFileStream.Create(TargetNames, fmCreate);
  try
    SetLength(Buffer, SizeTargets);
    Source.ReadBuffer(Pointer(Buffer)^, Length(Buffer));
    Target.WriteBuffer(Buffer[0], Length(Buffer));
  finally
    Target.Free;
  end;
end;

The problem is that when I divide the files, files that are executable break and run when I want to show errors like:
  Windows can not find the file "route ..." Make sure the name is spelled correctly and try again

or
  The version of this file is not compatible with the version of Windows you are running ... (and then talking about 32 or 64 bits)

Also check and the size of the executable in the second function is good.
The problem is that in the second code as a result have all the files are corrupted
How do I solve this problem?

A: You are joining multiple input files together without indicating in the output where one file ends and the next begins. Your divide code has no idea which bytes belong to the JPG and which bytes belong to the EXE.
Case in point, the divide code you have shown is extracting the JPG bytes and saving them to an .exe file.  So of course that .exe file is not going to run correctly.
In order to extract the EXE, you have to extract/skip the JPG first, and that means you have to know how many bytes are in the JPG.  So you need to store the input file sizes in the joined output, not just their data, eg:
procedure TFormHome.btnJoinClick(Sender: TObject);
var
  OutStream: TFileStream;

  procedure AddFile(const FileName: sstring);
  var
    InStream: TStream;
    Size: Int64;
  begin
    InStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
    try
      Size := InStream.Size;
      OutStream.WriteBuffer(Size, SizeOf(Size));
      OutStream.CopyFrom(InStream, Size);
    finally
      InStream.Free;
    end;
  end;

begin
  OutStream := TFileStream.Create('salida.out', fmCreate);
  try
    AddFile('image.jpg');
    AddFile('test.exe');
  finally
    OutStream.Free;
  end;
end;

procedure TFormHome.btnUnJoinClick(Sender: TObject);
var
  Source: TStream;

  procedure SkipFile;
  var
    Size: Int64;
  begin
    Source.ReadBuffer(Size, SizeOf(Size));
    Source.Seek(Size, soCurrent);
  end;

  procedure ExtractFile(const FileName: string);
  var
    Target: TStream;
    Size: Int64;
  begin
    Source.ReadBuffer(Size, SizeOf(Size));

    Target := TFileStream.Create(FileName, fmCreate);
    try
      Target.CopyFrom(Source, Size);
    finally
      Target.Free;
    end;
  end;

begin
  Source := TFileStream.Create('salida.out', fmOpenRead or fmShareDenyWrite);
  try
    SkipFile;
    ExtractFile('test.exe');
  finally
    Source.Free;
  end;
end;

I would suggest that you consider storing the filenames as well:
procedure TFormHome.btnJoinClick(Sender: TObject);
var
  OutStream: TFileStream;

  procedure AddFile(const FileName: string);
  var
    InStream: TStream;
    Name: UTF8String;
    Len: Integer;
    FileSize, TotalSize: Int64;
  begin
    InStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
    try
      Name := UTF8String(ExtractFileName(FileName));
      Len := Length(Name);

      FileSize := InStream.Size;

      TotalSize := SizeOf(Len) + Len + SizeOf(FileSize) + FileSize;
      OutStream.WriteBuffer(TotalSize, SizeOf(TotalSize));

      OutStream.WriteBuffer(Len, SizeOf(Len));
      OutStream.WriteBuffer(PAnsiChar(Name)^, Len);
      OutStream.WriteBuffer(FileSize, SizeOf(FileSize));
      OutStream.CopyFrom(InStream, FileSize);
    finally
      InStream.Free;
    end;
  end;

begin
  OutStream := TFileStream.Create('salida.out', fmCreate);
  try
    AddFile('image.jpg');
    AddFile('test.exe');
  finally
    OutStream.Free;
  end;
end;

procedure TFormHome.btnUnJoinClick(Sender: TObject);
var
  Source: TStream;

  procedure SkipFile;
  var
    TotalSize: Int64;
  begin
    Source.ReadBuffer(TotalSize, SizeOf(TotalSize));
    Source.Seek(TotalSize, soCurrent);
  end;

  procedure ExtractFile;
  var
    Target: TStream;
    TotalSize, FileSize: Int64;
    Name: UTF8String;
    Len: Integer;
    Pos: Int64;
  begin
    Source.ReadBuffer(TotalSize, SizeOf(TotalSize));
    Pos := Source.Position;

    Source.ReadBuffer(Len, SizeOf(Len));
    SetLength(Name, Len);
    Source.ReadBuffer(PAnsiChar(Name)^, Len);

    Source.ReadBuffer(FileSize, SizeOf(FileSize));

    Target := TFileStream.Create(String(Name), fmCreate);
    try
      Target.CopyFrom(Source, FileSize);
    finally
      Target.Free;
    end;

    if (Source.Position - Pos) <> TotalSize then
      raise Exception.Create('Extract failed. Bad position');
  end;

begin
  Source := TFileStream.Create('salida.out', fmOpenRead or fmShareDenyWrite);
  try
    SkipFile;
    ExtractFile;
  finally
    Source.Free;
  end;
end;


text:
Q: CSS Capitalize First Letter In All Caps Word Is it possible to capitalize the first letter only of a word that is all caps using CSS?
So change "TESTING" to "Testing"?
TESTING

The css property text-transform: capitalize doesn't work (capitalizes the first letter but ignores the rest).

A: CSS:

HTML:

TESTING.

A: Yes it is possible with just CSS, here's how:

.capitalize {
  text-transform: lowercase;
  display: inline-block;
}

.capitalize:first-letter {
  text-transform: uppercase
}
TESTING

You'll notice I added display:inline-block, this is because:
"A first line has meaning only in a block-container box, therefore the ::first-letter pseudo-element has an effect only on elements with a display value of block, inline-block, table-cell, list-item or table-caption." source

A: You can use jquery as follows:
MYTEXT

Reference:
Uppercase first letter of variable

A: You can try identify it with Js.

A: .capitalize::first-letter {
     text-transform: capitalize;
}

https://jsfiddle.net/5wbe2ugq/
There's no way to see in CSS if the first letter is capitalized, however you can make sure of it via:
.capitalize::first-letter {
     text-transform: capitalize;
}

.capitalize {
     text-transform: lowercase;
}

A:
TESTING

Make sure to add display:inline-block because the element span does not work with :first-letter unlike with p,div,tables, etc. If you are using an element which has block by default, then you don't need to put a display:inline-block just like the code below.

TESTING

Cheers,


text:
Q: Output of a << with -ve no?
Possible Duplicate:
Left shifting with a negative shift count

Consider my code follows
int main()
{
    int k=1;
    k=k<<-1;
    printf("%d",k);
}

o/p

-2147483648

Why the output is like this.I know negative no's are stored in 2's complement but here is there any use of this concept of -2s complement.Kindly give me some idea.

A: k << -1;  // Before the OP edit
and
k = k<<-1;
These statements are undefined behavior in C.
Using a negative value in the right operand of the bitwise left or right shift operator is undefined behavior in C (see C99, 6.5.7).

A: The reason for the -2147483648 result - if you're testing this on an x86 processor - is that the shift count gets clamped to 31 (see "Intel Architecture Software Developer's Manual Volume 2: Instruction Set Reference"). So you're getting 1<<31, which equals 0x80000000, which when printed as a signed 32-bit integer becomes -2147483648.

A: The result of a shift operation is undefined if the second operand is negative.
http://msdn.microsoft.com/en-us/library/f96c63ed%28v=vs.80%29.aspx
Why am I getting strange results bit-shifting by a negative value?


text:
Q: Segmentation fault on linux when calling POCO c++ ServerSocket() On Fedora 29 with POCO C++ installed using
dnf install poco-devel

This code:
#include <Poco/Net/ServerSocket.h>

int main() {
    Poco::Net::ServerSocket svs(9980);
    return 0;
}

Compiled using this Makefile:
CC = g++
CPPFLAGS += -I/usr/include
CPPFLAGS += -I/usr/include/Poco
CFLAGS += -c
CFLAGS += -g
LDFLAGS += -g
LDLIBS += -lPocoFoundation
LDLIBS += -lPocoUtil
LDLIBS += -lPocoNet
SOURCES = test.cpp
OBJECTS = $(SOURCES:.cpp=.o)
EXECUTABLE = test

all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) $(OBJECTS) $(LDLIBS) -o $@

.cpp.o:
    $(CC) $(CPPFLAGS) $(CFLAGS) $< -o $@

install:
    @echo "Build complete!"

Gives the following in gdb
 Thread #1 [test] 8015 [core: 3] (Suspended : Signal :
 SIGSEGV:Segmentation fault)    typeinfo name for
 Poco::Net::Impl::IPv6SocketAddressImpl() at 0x4020c0
    Poco::Net::SocketAddress::toString[abi:cxx11]() const at
 0x7ffff7ce2239     Poco::Net::SocketImpl::bind() at 0x7ffff7ce74c8
    Poco::Net::ServerSocket::ServerSocket() at 0x7ffff7ce0e78       main() at
 test.cpp:6 0x4011c5

And in valgrind:
 ==8034== Process terminating with default action of signal 11 (SIGSEGV): dumping core
 ==8034==  Bad permissions for mapped region at address 0x4020C0
 ==8034==    at 0x4020C0: ??? (in /path/to/test85-poco/test)
 ==8034==    by 0x4BCB238: Poco::Net::SocketAddress::toString[abi:cxx11]() const (in
 /usr/lib64/libPocoNet.so.60)
 ==8034==    by 0x4BD04C7: Poco::Net::SocketImpl::bind(Poco::Net::SocketAddress const&, bool,
 bool) (in /usr/lib64/libPocoNet.so.60)
 ==8034==    by 0x4BC9E77: Poco::Net::ServerSocket::ServerSocket(unsigned short, int) (in
 /usr/lib64/libPocoNet.so.60)
 ==8034==

Passing -v to g++ yields:
g++ -I/usr/include -I/usr/include/Poco -c -g -v test.cpp -o test.o
Using built-in specs.
COLLECT_GCC=g++
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-redhat-linux
Configured with: ../configure --enable-bootstrap --enable-languages=c,c++,fortran,objc,obj-c++,ada,go,lto --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-shared --enable-threads=posix --enable-checking=release --enable-multilib --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-gcc-major-version-only --with-linker-hash-style=gnu --enable-plugin --enable-initfini-array --with-isl --enable-libmpx --enable-offload-targets=nvptx-none --without-cuda-driver --enable-gnu-indirect-function --enable-cet --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 8.2.1 20181105 (Red Hat 8.2.1-5) (GCC)
COLLECT_GCC_OPTIONS='-I' '/usr/include' '-I' '/usr/include/Poco' '-c' '-g' '-v' '-o' 'test.o' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
 /usr/libexec/gcc/x86_64-redhat-linux/8/cc1plus -quiet -v -I /usr/include -I /usr/include/Poco -D_GNU_SOURCE test.cpp -quiet -dumpbase test.cpp -mtune=generic -march=x86-64 -auxbase-strip test.o -g -version -o /tmp/ccDd0TCY.s
GNU C++14 (GCC) version 8.2.1 20181105 (Red Hat 8.2.1-5) (x86_64-redhat-linux)
    compiled by GNU C version 8.2.1 20181105 (Red Hat 8.2.1-5), GMP version 6.1.2, MPFR version 3.1.6-p2, MPC version 1.1.0, isl version isl-0.16.1-GMP

GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
ignoring nonexistent directory "/usr/lib/gcc/x86_64-redhat-linux/8/include-fixed"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-redhat-linux/8/../../../../x86_64-redhat-linux/include"
ignoring duplicate directory "/usr/include"
  as it is a non-system directory that duplicates a system directory
#include "..." search starts here:
#include <...> search starts here:
 /usr/include/Poco
 /usr/lib/gcc/x86_64-redhat-linux/8/../../../../include/c++/8
 /usr/lib/gcc/x86_64-redhat-linux/8/../../../../include/c++/8/x86_64-redhat-linux
 /usr/lib/gcc/x86_64-redhat-linux/8/../../../../include/c++/8/backward
 /usr/lib/gcc/x86_64-redhat-linux/8/include
 /usr/local/include
 /usr/include
End of search list.
GNU C++14 (GCC) version 8.2.1 20181105 (Red Hat 8.2.1-5) (x86_64-redhat-linux)
    compiled by GNU C version 8.2.1 20181105 (Red Hat 8.2.1-5), GMP version 6.1.2, MPFR version 3.1.6-p2, MPC version 1.1.0, isl version isl-0.16.1-GMP

GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
Compiler executable checksum: a86aaae86aad006cc531272eca0396eb
COLLECT_GCC_OPTIONS='-I' '/usr/include' '-I' '/usr/include/Poco' '-c' '-g' '-v' '-o' 'test.o' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
 as -v -I /usr/include -I /usr/include/Poco --64 -o test.o /tmp/ccDd0TCY.s
GNU assembler version 2.31.1 (x86_64-redhat-linux) using BFD version version 2.31.1-13.fc29
COMPILER_PATH=/usr/libexec/gcc/x86_64-redhat-linux/8/:/usr/libexec/gcc/x86_64-redhat-linux/8/:/usr/libexec/gcc/x86_64-redhat-linux/:/usr/lib/gcc/x86_64-redhat-linux/8/:/usr/lib/gcc/x86_64-redhat-linux/
LIBRARY_PATH=/usr/lib/gcc/x86_64-redhat-linux/8/:/usr/lib/gcc/x86_64-redhat-linux/8/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/usr/lib/gcc/x86_64-redhat-linux/8/../../../:/lib/:/usr/lib/
COLLECT_GCC_OPTIONS='-I' '/usr/include' '-I' '/usr/include/Poco' '-c' '-g' '-v' '-o' 'test.o' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
g++ -g test.o -lPocoFoundation  -lPocoUtil -lPocoNet -o test

A more elaborate approach yields a similar result:
#include <Poco/Net/ServerSocket.h>
#include <iostream>

int main() {
    std::string Address("192.168.0.11:9980");
    Poco::Net::SocketAddress addr(Address);

    if (addr.family() == static_cast<Poco::Net::IPAddress::Family>(Poco::Net::Impl::IPAddressImpl::IPv6)) {
        std::cout << "Addr: ipv6 " << std::endl;
    }
    else if (addr.family() == static_cast<Poco::Net::IPAddress::Family>(Poco::Net::Impl::IPAddressImpl::IPv4)) {
        std::cout << "Addr: ipv4 " << std::endl;
    }
    else {
        std::cout << "Addr: something else (err)." << std::endl;
    }
    Poco::Net::ServerSocket svs(addr);
    return 0;
}

With this on the console:
 Addr: ipv4

gdb stack trace:
 Thread #1 [test] 7865 [core: 0] (Suspended : Signal :
 SIGSEGV:Segmentation fault)        typeinfo name for
 Poco::Net::Impl::IPv6SocketAddressImpl() at 0x403100
    Poco::Net::SocketAddress::toString[abi:cxx11]() const at
 0x7ffff7ce2239     Poco::Net::SocketImpl::bind() at 0x7ffff7ce74c8
    Poco::Net::ServerSocket::ServerSocket() at 0x7ffff7ce0db7       main() at
 test.cpp:39 0x40236a

and valgrind report:
 ==7616== Process terminating with default action of signal 11 (SIGSEGV): dumping core
 ==7616==  Bad permissions for mapped region at address 0x403100
 ==7616==    at 0x403100: ??? (in /path/to/test85-poco/test)
 ==7616==    by 0x4BCB238: Poco::Net::SocketAddress::toString[abi:cxx11]() const (in
 /usr/lib64/libPocoNet.so.60)
 ==7616==    by 0x4BD04C7: Poco::Net::SocketImpl::bind(Poco::Net::SocketAddress const&, bool,
 bool) (in /usr/lib64/libPocoNet.so.60)
 ==7616==    by 0x4BC9DB6: Poco::Net::ServerSocket::ServerSocket(Poco::Net::SocketAddress const&,
 int) (in /usr/lib64/libPocoNet.so.60)
 ==7616==    by 0x402375: main (test.cpp:38)

Question:
How to create a ServerSocket on linux using POCO that executes without a segmentation fault?

A: Building POCO directly from source resolved the issue.  Used the following to build:
sudo dnf remove poco-devel
git clone https://github.com/pocoproject/poco
cd poco/build
cmake ..
make -j4
sudo make install

The POCO files are written to
/usr/local/include and
/usr/local/lib
so modified the makefile as follows:
CC = g++
CPPFLAGS += -I/usr/local/include
CPPFLAGS += -I/usr/local/include/Poco

CFLAGS += -c
CFLAGS += -g
LDFLAGS += -g
CFLAGS += -std=c++14
LDLIBS += -L/usr/local/lib
LDLIBS += -lPocoFoundation
LDLIBS += -lPocoUtil
LDLIBS += -lPocoNet
LDLIBS += -Wl,-rpath=/usr/local/lib
SOURCES = test.cpp
OBJECTS = $(SOURCES:.cpp=.o)
EXECUTABLE = test

all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) $(OBJECTS) $(LDLIBS) -o $@

.cpp.o:
    $(CC) $(CPPFLAGS) $(CFLAGS) $< -o $@

install:
    @echo "Build complete!"

ServerSocket on linux using POCO now executes without a segmentation fault.


text:
Q: Port forwarding from one router to router, then to a machine on the second router I have a combo modem/router provided by my ISP. I plugged a second router into this device because the wireless speeds were subpar. Now I am trying to set up a home media server that is accessible from outside the network using a dynamic DNS service. I have the dynamic DNS working correctly, but now I am trying to tunnel the data from the internet-facing router at 192.168.0.1 to the second router at 192.168.1.1
I am probably going down the wrong road here, but I set the second router to have an IP of 192.168.0.150, so as to put it on the same subnet as the other router. I then forwarded the ports I need to that location, where I then have that router forwarding those same ports to the correct machine. None of this works, and I can no longer connect to the internet from machines on that second router. Where am I going wrong here?

A: The first router is being used as a router, and the second router is being used as a Wireless Access Point (AP) - it doesn't need to be a router, as it resides on the same network as the first router.
Connect the AP router to the first router via LAN ports.  Turn off DHCP on the AP router.
Now all the LAN ports both routers, and the wifi network on the AP router are all on the same subnet because they are bridged.  They can all use DHCP from the first router.  Because in this configuration, you are connecting them as a layer two network, which means that broadcast traffic, such as DHCP requests, can be seen by every device.
Effectively, you can ignore the port forwarding on the second router, and port forward on the first router directly to devices connected to the second routers wireless network.


text:
Q: What is the NavigationLink symbol? What is the symbol in the navigation link that looks like this: ">"
I'm trying to get it to use in my project but can't seem to find it.

A: You should be able to use it in SwiftUI like…
Image(systemName: "chevron.right")

If you download the app SF Symbols you can browse all the images that you can access using systemName like this.
https://developer.apple.com/sf-symbols/


text:
Q: File Upload is not working with API Gateway Pattern I have implemented Spring security using- The API Gateway Pattern: Angular JSand Spring Security (referred Angular JS and Spring Security successfully for my application).
In my application (divided into- Gateway + UI + Resource), I have created a .pdf file upload module in 'UI' application which is failing at Gateway application while it tries to redirect request to Resource application (even this file upload functionality was working fine before implementing this API Gateways pattern and Security).
The file upload javascript code from 'UI' application as below:
if(idProofFile.files.length == 0)
        {
            $scope.alerts = [
                             { type: 'danger', msg: 'No File(s) selected, please Browse and Select ID Proof File(s) first.' },
                             ];
            return;
        }
        else{

            // Upload user's files::
            //create form data to send via POST
            var formData = new FormData();

            for(var i=0; i< idProofFile.files.length; i++){
                if(idProofFile.files[i].size > 31457280) // check for each file size should not be more than 30 MB = 30*1024*1024 bytes
                {
                    $scope.alerts = [
                                     { type: 'danger', msg: 'The size of file: '+ idProofFile.files[i].name +' is more than 30 MB. Max limit of a file size is 30 MB.'}
                                     ];
                    return;
                }
                else{
                    var extension = idProofFile.files[i].name.substr(idProofFile.files[i].name.lastIndexOf('.') + 1).toLowerCase();
                    //alert(extension);

                    if (idProofFile.files[i].name.length > 0)
                    {
                        if (allowedExtensions.indexOf(extension) === -1)
                        {
                            $scope.alerts = [
                                             { type: 'danger', msg: 'Only PDF files are allowed. Selected file:- '+ idProofFile.files[i].name +' is a .'+extension+' file.'}
                                             ];
                            return;
                        }
                    }
                }

                formData.append("idProof",idProofFile.files[i]);
            }

            var request = new XMLHttpRequest();

            request.open('POST', 'resource/upload_id_proof/' +$rootScope.loggedInUserPrimaryKeyId+'/'+$rootScope.loggedInUserId, false);
            request.send(formData);

The Spring security code fromm 'Gateway' application is as below:
        @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
                .antMatchers("/update_new_user/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests()
                //.antMatchers("/index.html", "/", "/login", "/message", "/home")
                //.antMatchers("/index.html", "/", "/login", "/message", "/home", "/css", "/font-awesome/**", "/fonts", "/img/**", "/js/**", "/less", "/mail").permitAll()
                .antMatchers("/index.html", "/", "/css/**", "/font-awesome/**", "/fonts", "/img/**", "/js/**", "/less", "/mail").permitAll()
                //.antMatchers("/ui/", "/ui/public/js/**", "/ui/js/**").permitAll()
                .antMatchers("/ui/public/**").hasAnyAuthority("Admin", "SuperAdmin", "Owner", "Tenant")
                .antMatchers("/ui/private/projectadmin/**").hasAuthority("Admin")
                .antMatchers("/ui/private/superadmin/**").hasAuthority("SuperAdmin")
                .antMatchers("/ui/private/owner/**").hasAuthority("Owner")
                .antMatchers("/ui/private/tenant/**").hasAuthority("Tenant")
                .anyRequest().authenticated()
                .and()
                .csrf()
                .csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);

    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                    HttpServletResponse response, FilterChain filterChain)
                            throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                        .getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null
                            && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }
}

The controller code from 'Resource' application:
    @RequestMapping(value="/upload_id_proof/{userPrimaryKeyId}/{userId}", method = RequestMethod.POST)
public @ResponseBody String uploadIdProof(
        //@RequestParam(value = "infoClient") String infoClientString,
        @RequestParam(value = "idProof") MultipartFile[] idProofFiles,
        @PathVariable Long userPrimaryKeyId,
        @PathVariable String userId) {

The request is failing at 'Gateway' application and not forwarded to 'Resource' application. The exception at 'Gateway' is as below:
**Invalid CSRF token found for localhost:8080/resource/upload_id_proof/40/11**

Detailed logs:
2016-04-29 10:00:05.797 DEBUG 6020 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/configprops.*']
2016-04-29 10:00:05.797 DEBUG 6020 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/configprops.*'
2016-04-29 10:00:05.797 DEBUG 6020 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/configprops/']
2016-04-29 10:00:05.797 DEBUG 6020 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/configprops/'
2016-04-29 10:00:05.797 DEBUG 6020 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2016-04-29 10:00:05.797 DEBUG 6020 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-04-29 10:00:05.797 DEBUG 6020 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-04-29 10:00:05.800 DEBUG 6020 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@493c907: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@493c907: Principal: org.springframework.security.core.userdetails.User@620: Username: 11; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: Owner; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: b6cd10df-a20e-49ae-9212-d32e7520db8f; Granted Authorities: Owner'
2016-04-29 10:00:05.800 DEBUG 6020 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-04-29 10:00:05.800 DEBUG 6020 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@3439c41
2016-04-29 10:00:05.800 DEBUG 6020 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter'
2016-04-29 10:00:05.800 DEBUG 6020 --- [nio-8080-exec-1] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8080/resource/upload_id_proof/40/11
2016-04-29 10:00:05.802 DEBUG 6020 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

I have tried ignoring csrf by below code in Gateway app:
http.httpBasic().and()
.csrf().ignoringAntMatchers("/resource/upload_id_proof/**");

There is not any issue log this time but the request is not forwarded to controller in 'Resource' app and now the logs are something as below:
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/resource/upload_id_proof/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.web.util.matcher.OrRequestMatcher  : matched
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.NegatedRequestMatcher  : matches = false
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.util.matcher.AndRequestMatcher   : Did not match
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 5 of 13 in additional filter chain; firing Filter: ''
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 6 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/logout'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 7 of 13 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.a.AnonymousAuthenticationFilter  : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fb6efb77: Principal: org.springframework.security.core.userdetails.User@620: Username: 11; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: Owner; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 8902a97c-cd54-4c78-92e4-383270fd97c7; Granted Authorities: Owner'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/index.html'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/css/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/font-awesome/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/fonts'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/img/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/js/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/less'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/mail'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/ui/public/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/ui/private/projectadmin/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/ui/private/superadmin/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/ui/private/owner/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/resource/upload_id_proof/40/11'; against '/ui/private/tenant/**'
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /resource/upload_id_proof/40/11; Attributes: [authenticated]
2016-04-29 10:56:32.165 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fb6efb77: Principal: org.springframework.security.core.userdetails.User@620: Username: 11; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: Owner; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 8902a97c-cd54-4c78-92e4-383270fd97c7; Granted Authorities: Owner
2016-04-29 10:56:32.166 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@442f6da3, returned: 1
2016-04-29 10:56:32.166 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
2016-04-29 10:56:32.166 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
2016-04-29 10:56:32.166 DEBUG 5912 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : /resource/upload_id_proof/40/11 reached end of additional filter chain; proceeding with original chain
2016-04-29 10:56:32.283 DEBUG 5912 --- [nio-8080-exec-4] tRepository$SaveToSessionResponseWrapper : Skip invoking on
2016-04-29 10:56:32.283 DEBUG 5912 --- [nio-8080-exec-4] tRepository$SaveToSessionResponseWrapper : Skip invoking on
2016-04-29 10:56:32.285 DEBUG 5912 --- [nio-8080-exec-4] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2016-04-29 10:56:32.285 DEBUG 5912 --- [nio-8080-exec-4] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

Except this file upload functionality, all other modules are working fine in API Gateway pattern and I did not find much help on internet for this issue, please help me to proceed the request to the 'Resource' application.


text:
Q: Декодирование Байтовой строки в формате ID3v2 с присутствием разных кодировок в строке Есть Байтовая строка
`b"ID3\x03\x00\x00\x00\x00\x1fvTIT2\x00\x00\x00'\x00\x00\x01\xff\xfe\x15\x04:\x040\x04B\x045\x04@\x048\x04=\x041\x04N\x04@\x043\x045\x04@\x04 \x00'\x001\x003\x00TPE1\x00\x00\x00\x0f\x00\x00\x01\xff\xfe\x1a\x04C\x04@\x040\x04@\x040\x04TRCK\x00\x00\x00\r\x00\x00\x01\xff\xfe1\x006\x00/\x001\x006\x00TCON\x00\x00\x00\x17\x00\x00\x01\xff\xfeI\x00n\x00d\x00i\x00e\x00 \x00R\x00o\x00c\x00k\x00TPE2\x00\x00\x00\x0f\x00\x00\x01\xff\xfe\x1a\x04C\x04@\x040\x04@\x040\x04TYER\x00\x00\x00\x0b\x00\x00\x01\xff\xfe2\x000\x001\x004\x00TALB\x00\x00\x00\x11\x00\x00\x01\xff\xfe\x10\x04@\x04E\x048\x04<\x045\x044\x04\

В ней присутствую символы Кодировки Utf-16 И ISO-8859-1, причем сказано, что если символы кодируются в utf-16 то будет вначале стоять \xff\xfe\, каким образом можно декодировать строку так, что бы получился правильный результат?


text:
Q: Gitflow Workflow with Maven - when to build what? Gitflow introduces several branches like develop, release, hotfix, and also encourages feature branches.
In a Maven project, you usually build SNAPSHOT and release versions, and often number them with semantic, three-digit versions.
It would be sensible to automate the build process as much as possible, but the question is: When should we build a SNAPSHOT version, when should be build a release version, when should we build none of that at all?
I image the following could be sensible:

*

*Whenever a feature branch is merged back into develop, a SNAPSHOT build is triggered and deployed to the Maven repository.

*When a release branch is created, as release build is started.

But there are much more situations:

*

*When I fix bugs on the release (or hotfix) branch, do I always want a new release build?

*During developing a feature, should I build on the feature branch? If so, what should this version be called (1.2.3-FEATURE1-SNAPSHOT?)?

A: Let's start with releases. Whether a version is going to be released or not is decided in the future when an already-built binary is deployed to TST envs and checked. When committing or building you can't predict whether the version will be a "release".
Once you abandon these ideas things will become much simpler. And since you can't use branch-based versions for releases, what's the point of making things different for feature branches? You might as well forget about mixing the concepts of branching and versioning together.
With Continuous Delivery (you can borrow its ideas even if you don't use it to the fullest) any build may potentially go to PRD, thus:

*

*Build a binary with any type of versioning that you like. With Maven the easiest is to stick with SNAPSHOT* and never use "release" ones. It's unique, it's standard, it has some advantages with Nexus (retention policies).

*When you're ready to go to PRD and the release version is chosen - tag it somehow. It can be a CI Job that keeps track of all PRD deployments; or you may have a page with all the release versions; or you may transfer the binary to another Maven repo (still can be a SNAPSHOT type). The latter is convenient if you go with retention policies for the snapshots.

Also we usually want to mention from which commit the binary was built. You can put this into the binary (some kind of version.properties) during the build time. You may even create an endpoint in your app that servers this version for convenience.
PS: if you simply want to follow GitFlow advice - there is an example of how you could version. But you'll have all the problems (and more) that you already mentioned in the question.
* Maven automatically resolves SNAPSHOT versions into timestamp-ones. But you can't actually use this functionality because the timestamp is going to be different for different artifcacts during the build. If you want to keep version the same across all the binaries in the build you need to generate and assign a timestamp version manually using versions:set. It's not complicated, but is worth mentioning.


text:
Q: Limit LEFT JOIN to a maximum of one results I am trying to calculate the amount of orders we have received between two times, and how many of those have been packed by the warehouse staff.
We have an 'orders' table with the orders and when an order is finished and unfortunately when it's been dealt with in a manner such as a cancelled order that shouldn't be added to the calculation it will recieve a "Finished" status which is too much of a legacy code that I can't change.
In order to track if the order has been packed I instead want to join another table called 'orders_sent', but unfortunately if an order has more than one package, there will be more than one row in that table for that orders_id.
So what I want to do is check if an order has been placed, and if it has "finished" and also exists in the sent table I will count it as sent, if it's "finished" but not in the sent table, it should be ignored completely, and finally I want to count all rows total, ignoring any duplicates because of more than one entry in the sent table.
Here is what I come up with so far.
"SELECT " &_
"   COUNT(CASE orders_status WHEN 'Finished' THEN 1 ELSE NULL END) AS Sent, " &_
"   COUNT(*) AS Total " &_
"FROM " &_
"   orders " &_
"   LEFT JOIN orders_sent ON orders_id = orders_sent_orderid " &_
"WHERE " &_
"   orders_date > '" & datetime & "' " &_
"   AND orders_date < '" & dateAdd("d",1,datetime) & "' " &_
"   AND NOT (" &_
"       orders_status = 'FINISHED' " &_
"       AND orders_sent_id IS NULL) "

I tried grouping on orders_sent_id, but that didn't work because all orders that doesn't exists in the sent table gets grouped together. Trying to group by orders_id gave me wonky results which I can't quite explain (6 sent and 6 total). Not grouping gives me 33 sent and 54 total.
Running the SQL, skipping the count and just showing the orders_ID's I get 47 orders total in that time period using the SQL below. Not grouping show a few duplicated IDs because of orders_sent containing multiple rows for a few orders.
"SELECT " &_
"   orders_id AS oid " &_
"FROM " &_
"   orders " &_
"   LEFT JOIN orders_sent ON orders_id = orders_sent_orderid " &_
"WHERE " &_
"   orders_date > '" & datetime & "' " &_
"   AND orders_date < '" & dateAdd("d",1,datetime) & "' " &_
"   AND NOT (" &_
"       orders_status = 'Skickad och avslutad' " &_
"       AND orders_sent_id IS NULL) " &_
"GROUP BY " &_
"   orders_id"

So how can I get rid of the duplicates from the JOIN so they don't mess up the total?

A: Based on @P.Salmon's comment, this is the corrected SQL which seem to have fixed my problem:
"SELECT " &_
"   COUNT(CASE WHEN orders_status = 'Finished' AND os.orders_sent_ts < '" & dateAdd("h",27,datetime) & "' THEN 1 ELSE NULL END) AS Sent, " &_
"   COUNT(*) AS Total " &_
"FROM " &_
"   orders " &_
"   LEFT JOIN (" &_
"       SELECT DISTINCT " &_
"           orders_sent_orderid, " &_
"           orders_sent_ts " &_
"       FROM " &_
"           orders_sent "&_
"       WHERE " &_
"           1) AS os ON orders_id = os.orders_sent_orderid " &_
"WHERE " &_
"   orders_date > '" & datetime & "' " &_
"   AND orders_date < '" & dateAdd("d",1,datetime) & "' " &_
"   AND NOT (" &_
"       orders_status = 'Finished' " &_
"       AND os.orders_sent_orderid IS NULL) "

I added in a timestamp from the orders_sent table in my CASE for sent to make sure I can go back to any date and see how it worked that day. The +27hours is because the trucks leave at 15:00, but the cutoff time for orders that are supposed to be sent the same day is at 12:00.


text:
Q: Removing points and small lines in opencv Is there any function or algorithm to remove points and small/short lines from the image. I have made a metric map for robot. I have used algorithm to make a skeleton from the image. What I need is, to remove small/short lines and point to get smooth lines- see the picture. I am new in opencv, so maybe it is simple problem.
Any suggestion? Thanks.
To make skeleton I use this code
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "highgui.h"
#include <stdlib.h>
#include <stdio.h>

using namespace cv;

int main( int argc, char** argv )
{

cv::Mat img = cv::imread("test4.png", 0);

cv::Mat skel(img.size(), CV_8UC1, cv::Scalar(0));

cv::Mat temp(img.size(), CV_8UC1);

cv::Mat sub_mat = Mat::ones(img.size(), img.type())*255;

cv::Mat eroded;

cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,

cv::Size(3, 3));

cv::subtract(sub_mat, img, img);

bool done;
do
{
  cv::erode(img, eroded, element);
  cv::dilate(eroded, temp, element); // temp = open(img)
  cv::subtract(img, temp, temp);
  cv::bitwise_or(skel, temp, skel);
  eroded.copyTo(img);

  done = (cv::countNonZero(img) == 0);
} while (!done);

cv::subtract(sub_mat, skel, skel);

cv:imwrite("skelet.png",skel);

cv::imshow("Skeleton", skel);

cv::waitKey(0);

return 0;
}

A: To remove points and noise in general, the simplest way is to implement a Median filter (a filter based on the median of the pixel's neighbourhood).
Here is en example on how to program it in c:
    Mat median(Mat in)
{
    int sizeW = 3;//Neighborhood size
    int offset = sizeW/2; //external border of the image
    if(in.channels()==3) cvtColor(in,in,CV_BGR2GRAY,1);
    in.convertTo(in, CV_8UC1);

    //Init
    int x,y,i,j,k;
    uchar temp;
    uchar median[9] = {0};// the size of this matrix = sizeW²
    int nRows = in.rows;
    int nCols = in.cols;
    Mat out = Mat::zeros(nRows-2*offset, nCols-2*offset, CV_8UC1 );

    //Processing
    for(x=offset; x<nRows-offset; x++)
        for(y=offset; y<nCols-offset; y++)
    {
        //Median
        for(i=(-sizeW/2); i<=sizeW/2; i++)
            for(j=(-sizeW/2); j<=sizeW/2; j++)
                median[(i+sizeW/2)*sizeW + (j+sizeW/2)] = in.at<uchar>(x+i,y+j);

        //Sort the median array
        for(int z=0; z<sizeW*sizeW; z++)
            for(k=1; k<sizeW*sizeW; k++){
                if(median[k-1]>median[k]){
                    temp = median[k-1];
                    median[k-1] = median[k];
                    median[k] = temp;
                }
            }
        out.at<uchar>(x-offset,y-offset) = median[(sizeW*sizeW/2)+1];
    }// for all pixels

    return out;
}

You should try with the neighbourhood size = 3.


text:
Q: Strange compilation errors Could someone tell me what my compile-time errors mean and help me with them?
Heres one of the errors:

C:\doc1\collect2.exe  [Error] ld returned 1 exit status

Here is the text file:
 T(F)       R1        R2       R3        R4
 95.0     95.20     66.10     43.10     29.00
 96.0     96.10     67.60     43.50     31.20
 97.0     97.40     67.00     43.70     30.50
 98.0     97.20     69.10     44.10     30.70
 99.0     98.90     68.00     44.70     32.80
100.0    99.50     71.10     45.10     31.50
101.0   101.00     71.20     45.30     31.60
102.0   101.60     71.00     45.70     30.50
103.0   101.80     73.10     46.30     32.50
104.0   103.70     73.50     46.60     32.70
105.0   105.60     72.80     47.10     33.60

Here is my source
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
#include <stdlib.h>

using namespace std;

void read ();
void slope(double,double,double,double,double,int,double);
void write(double,double,double,double,double,double);
double temp, R1, R2, R3, R4,rsq;

int main ()
{
    read();
    return 0;
}

void read()
{

    ifstream indata("c:\\doc1\\temperaturedata.txt");
    int indx=0;
    if(indata == NULL)
    {
        cout<< "There is no file go get it from the CD"<< endl;
        return;
    }
    const int columns = 5;
    const int rows = 11;

    double Ihatearray[rows][columns];
    string temparature;
    getline(indata, temparature);
    for(int i = 0; i < rows; ++i)
    {
        for (int j = 0; j < columns; ++j)
            {
                cout << "\t" << flush;
                indata >> Ihatearray[i][j];
                cout.setf(ios::fixed);
                cout << setprecision(2) << Ihatearray[i][j] <<flush;
            }
            cout << endl;
            double temp[20], R1[20],R2[20],R3[20],R4[20];
    }
    //indata.close();
    slope(temp, R1, R2, R3, R4,indx,rsq);
}
void slope(double x[5], double y[], double& m, double& b, int n,double& r)
{
    int i;
double xsum = 0., ysum = 0., xave, yave, x2sum = 0., y2sum = 0.,xysum =0.;

for(int i = 0; i < n; i++)
{
    xsum  += x[i];
    ysum  += y[i];
    x2sum += x[i] * x[i];
    y2sum += y[i] * y[i];
    xysum += x[i] * y[i];
}

xave=xsum/n;
yave=ysum/n;

m=(xysum-yave*xsum)/(x2sum-xave*xsum);
b=yave-m*xave;
r=(xysum-n*xave*yave)/(sqrt(x2sum-n*xave*xave)*sqrt(y2sum-n*yave*yave));

write (temp, R1, R2, R3, R4,rsq);

}
void write (double temp [], double R1[], double R2[], double R3[],double R4[],double
            rsq)
{
    //Where I will print out a table of the results.
}

A: void slope(double,double,double,double,double,int,double);
void write(double,double,double,double,double,double);

and
void slope(double x[5], double y[], double& m, double& b, int n,double& r)

void write (double temp [], double R1[], double R2[], double R3[],double R4[],double rsq)

Spot the difference? These declarations and definitions must match.
More errors, your code looks like this
double temp, R1, R2, R3, R4,rsq;

void read()
{
    ...
    for(int i = 0; i < rows; ++i)
    {
        ...
        double temp[20], R1[20],R2[20],R3[20],R4[20];
    }
    //indata.close();
    slope(temp, R1, R2, R3, R4,indx,rsq);
}

Now look at what you've written, you've declared temp, R1, R2 etc twice. Now which declaration do you think applies when you call slope? Here's the rule, declarations inside { and } are only visible inside the { and }.
I get the feeling you should be a little more organised in your coding. These are only details, but the details must be got right.


text:
Q: Running scripts after openvpn I've wrote a script to start openvpn (called vpn_up) but then I want it to also run my firewall script (called firewall_up) after starting the vpn.  Here is the script that works:
#!/bin/bash
#script called vpn_up

exp_login=mylogin
exp_pass=mypass

config_file=$1

expect -c "

spawn openvpn --config $config_file --script-security 2 --up /etc/openvpn/update-systemd-resolved --down /etc/openvpn/update-systemd-resolved --dhcp-option 'DOMAIN-ROUTE .' --down-pre

expect \"Auth Username:\"
send \"$exp_login\r\";
expect \"for no echo)\"
send \"$exp_pass\r\";
interact
"

After opening the vpn, I want it to run my script firewall_up
#!/bin/bash
#script called firewall_up
# get your IP address

curl -s ifconfig.me > /tmp/ip_address

#Clear any iptables rules you might have at the moment
iptables -F
#Start building the firewall by allowing tun and your localhost
iptables -A INPUT -i tun+ -j ACCEPT
iptables -A OUTPUT -o tun+ -j ACCEPT

#Add the IP address of the VPN to the firewall
IP_LIST=$(tr '\n' ' ' < /tmp/ip_address)
for IP in $IP_LIST; do
iptables -A INPUT -s $IP -j ACCEPT
iptables -A OUTPUT -d $IP -j ACCEPT
done

iptables -A INPUT -p udp --sport 1195 -j ACCEPT
iptables -A INPUT -p udp --dport 1195 -j ACCEPT
iptables -A OUTPUT -p udp --sport 1195 -j ACCEPT
iptables -A OUTPUT -p udp --dport 1195 -j ACCEPT

#iptables -A INPUT -p udp --sport 53 -j ACCEPT
#iptables -A INPUT -p udp --dport 53 -j ACCEPT
#iptables -A OUTPUT -p udp --sport 53 -j ACCEPT
#iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A INPUT -p udp -j DROP
iptables -A OUTPUT -p udp -j DROP

# Stop anything not from VPN or localhost
iptables -A INPUT -j DROP
iptables -A OUTPUT -j DROP

#Clean up your tempoary files
rm /tmp/ip_address

Currently, I have to run
sudo vpn_up some_config_file

in one terminal window and then run
sudo firewall_up

in another window and then it all works just fine.
I'd like to have just one script to do everything.  I tried adding
--up /usr/sbin/firewall_up

to the spawn openvpn command to my first script i.e.
#!/bin/bash
# script called vpn_up

exp_login=mylogin
exp_pass=mypass

config_file=$1

expect -c "

spawn openvpn --config $config_file --script-security 2 --up /etc/openvpn/update-systemd-resolved --up /usr/sbin/firewall_up --down /etc/openvpn/update-systemd-resolved --dhcp-option 'DOMAIN-ROUTE .' --down-pre

expect \"Auth Username:\"
send \"$exp_login\r\";
expect \"for no echo)\"
send \"$exp_pass\r\";
interact
"

But it ends up running firewall_up before the vpn is actually up.  I.e it uses my Initial IP address, not the IP address after the vpn is up and running.  Is there any way to just add more code after the expect is finished and openvpn is done?
Any suggestions?
Thanks
As asked, here is the key (I think) output from openvpn:
Fri May 14 11:39:31 2021 /sbin/ip link set dev tun0 up mtu 1500
Fri May 14 11:39:31 2021 /sbin/ip addr add dev tun0 local 10.167.0.50 peer 10.167.0.49
Fri May 14 11:39:31 2021 /usr/sbin/firewall_up tun0 1500 1557 10.167.0.50 10.167.0.49 init
Fri May 14 11:39:33 2021 /sbin/ip route add 185.195.19.203/32 via 192.168.0.1
Fri May 14 11:39:33 2021 /sbin/ip route add 0.0.0.0/1 via 10.167.0.49
Fri May 14 11:39:33 2021 /sbin/ip route add 128.0.0.0/1 via 10.167.0.49
Fri May 14 11:39:33 2021 /sbin/ip route add 10.167.0.1/32 via 10.167.0.49
Fri May 14 11:39:33 2021 Initialization Sequence Completed

The problem appears to be that it runs firewall_up before completing the initialization.


text:
Q: How to use Laravel DB to fetch data from dynamically created tables? I have been creating an application in Laravel 5.3 and because of the nature of the application, I needed to create a table specific to each user that registers. To do so I have used the homeController (user is redirected to it after a successful registration) and this code is used in  it :
$user_id = Auth::user()->id;
$user_name = Auth::user()->name;
$table_name = $user_name . '_' . $user_id;

if (Schema::hasTable($table_name))
{
    $specs = DB::table($table_name)->select('select * from ' . $table_name);
    return view('home')->with('rvalue', $specs);
}else{
    Schema::connection('mysql')->create($table_name, function ($table){
        $value = 0;
        $table->string('address')->default($value);
        $table->string('phone')->default($value);
        $table->string('name')->default($value);
    });
}

As of the code in home.blade.php I've added :
foreach ($rvalue as $value)
{
    var_dump($value);
}

My problem is that although the table and the columns in it are created and present in the database, I still don't know how to retrieve the default value that is assigned to the columns at the time of their creation and send and display them in the view.
I would be very thankful of you if you could tell me how to make it work.

A: Your query to database must be like this:
DB::table($table_name)->select('*')->get();

Select method used to specified selected fields, not for query it self.
Read official documentation for more useful methods: https://laravel.com/docs/5.3/queries


text:
Q: MS SQL Express 2012 slow in VirtualBox image I am accessing MS SQL Server Express running in a VirtualBox image for a Java / Hibernate (with EhCache setup) application.
The VM is connected via NIC mode.
When the server starts up it loads (most of the DB's) data in EhCache.
Right now it takes ~5 minutes to start up. If I switch to a dedicated machine that hosts MS SQL Server (not Express) the startup takes ~1 min.
Any suggestions what could be wrong here?

A: Ok found the problem.
VirtualBox in NIC mode somehow reduces the network speed between host and guest to 10mps.
More can be found in this forum thread on the Virtualbox site.
For a ticket in this regard (that seems to be marke as fixed but isn't, at least not in version 4.3.10 r93012) see here


text:
Q: NodeJS + Express: How to use sessions variables in other methods. (Session-variable: undefined) I'm using NodeJS 0.10.18 and Express 3.4.0 for a webserver to work with an PhoneGap application.
I want to use Session Variables/Sessions to store the users Username to use it in other methods.
When i login in the login method, the username is stored in req.session.name (it is set because i can print it to the console). But later on when i want to use it in the reserve method the req.session.name variable is suddenly undefined.
Can you tell me what i'm doing wrong?
Here's my code:
//NodeJS Modules
var http = require('http');
var express = require("express");

//Variables
var app = express();
var listenport = '8123';
var Username = "";
var Password = "";

//Application configuration
app.configure(function(){
    app.use(express.cookieParser('S3CRE7'));
    app.use(express.cookieSession());
    app.use(app.router);
});

//Create header for every HTTP response
app.all("*", function(req, res, next) {
    res.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*'});
    next();
});

//Login
app.post("/MobileApplication/login", function(req, res) {
    //Response 0 = correct

    var loginUsername = req.param('Username');

    //VALIDATE

    //STORE IN SESSION
    req.session.name = loginUsername;
    console.log(req.session.name);

    res.end("0");
});

//Reservation
app.post("/MobileApplication/reserve", function(req, res) {
    var name = req.session.name;
    console.log(name);
    res.end("0");
});

//If the url isn't valid respond with 404
app.all("*", function(request, response) {
    response.end("404!");
});

//Listen on listenport
http.createServer(app).listen(listenport);

Phonegap ajax login request:
jQuery.ajax({
            url: "http://" + serverip + ":" + serverpoort + "/MobileApplication/login?Username=" + Username + "&Password=" + Password + "",
            type: "POST",
            beforeSend: function(data) {
                console.log("login - sending");
            },
            success: function(data) {
                console.log("login - succes!");

                if (data === "0") {
                    $('input[type="checkbox"]').filter('#checkbox-1').each(function() {
                        if ($(this).is(':checked')) {
                            // perform operation for checked
                            window.localStorage.setItem("Username", Username);
                            window.localStorage.setItem("Password", Password);
                            $.mobile.navigate("#customers", {transition: "slide"});
                        }
                        else {
                            // perform operation for unchecked
                            window.localStorage.setItem("Username", "");
                            window.localStorage.setItem("Password", "");
                            $.mobile.navigate("#customers", {transition: "slide"});
                        }
                    });
                }
                if (data === "1") {
                    navigator.notification.alert(
                            'The username you have entered does not exist.', // message
                            doNothing,
                            'Error', // title
                            'Ok'                  // buttonName
                            );
                }
                if (data === "2") {
                    navigator.notification.alert(
                            'You have entered a wrong password.', // message
                            doNothing,
                            'Error', // title
                            'Ok'                  // buttonName
                            );
                }

            },
            error: function(a, b, c) {
                alert("login - error: " + a.toString() + " " + b.toString() + " " + c.toString());
                navigator.notification.alert(
                        "login - error: " + a.toString() + " " + b.toString() + " " + c.toString(), // message
                        doNothing,
                        'Error', // title
                        'Ok'                  // buttonName
                        );
            }
        });


text:
Q: for statement does not loop - android I'm breaking the for loop after the first iteration. I am aware it is not good practice to do so but I am not sure how to fix this.
I get the message "for statement does not loop". I am using android studio IDE.
List<PriceWithCurrency> commercialPrices = purchaseLineItem.getProduct().getCommercialPrices();
CrewSalesRecord crewSalesRecord =
        new CrewSalesRecord(
                purchase.getEmployeeIdentifier(),
                purchaseLineItem.getQuantity());
                crewSalesRecords.add(crewSalesRecord);

for (PriceWithCurrency currency : commercialPrices) {
    ProductData purchaseData = new ProductData(
            purchaseLineItem.getProduct().getProductId(),
            purchaseLineItem.getProduct().getShortDescription(),
            purchaseLineItem.getQuantity(),
            crewSalesRecords, currency.getPrice());
            uncombinedProductDataList.add(purchaseData);
    break;
}

A: I'm fairly certain that's a compiler warning, not an error. However, if you're going to break your loop after the first iteration anyway, why won't you just fetch the first item in the list instead of looping?
Example:
for (PriceWithCurrency currency : commercialPrices) {
     ProductData purchaseData = new ProductData(purchaseLineItem.getProduct().getProductId(),
               purchaseLineItem.getProduct().getShortDescription(), purchaseLineItem.getQuantity(),
crewSalesRecords, currency.getPrice());
     uncombinedProductDataList.add(purchaseData);
     break;
}

Becomes
PriceWithCurrency firstCurrency = commercialPrices.get(0);
ProductData purchaseData = new ProductData(purchaseLineItem.getProduct().getProductId(),
    purchaseLineItem.getProduct().getShortDescription(), purchaseLineItem.getQuantity(),
    crewSalesRecords, firstCurrency.getPrice());
uncombinedProductDataList.add(purchaseData);