text:
Q: Git workflow for multiple feature branch Our current stash repository has a Master and Develop branch.
Anytime if a developer is working on a story a developer creates a branch and once the coding is done a pull request is raised to merge to develop.
So far it has been good but when two developers are working on different feature branches on a  same Repository if a developer merges his changes to develop and other one is still working on, there are issues like merge conflicts and we don't want the two different feature branches to be released together.
I know this is not an issue but we want to avoid release multiple feature branches at a time.
Any thoughts on this on what are the best practices.

A: The best practice is that the 2nd developer should first rebase his feature branch from "develop" branch and then merge his changes back to "develop" branch by creating a pull request.
If you don't wish to release changes from two feature branches simultaneously, you can create tags on the "develop" branch after a merge is successful and release code using these tags.
Hope this helps!

A: I would suggest to create tags after you have merge to "develop" branch. There is no harm if you wish to release code from "master" branch using tags as well.
Honestly speaking there aren't any hard lines drawn on how you wish to release your code from Git hosted repos?
You may like to follow this sequence
rebase the feature brnach of second dev from develop branch to get changes of dev1 and avoid merge conflicts
git checkout feature_branch2

git rebase develop
merge feature-branch2 to develop branch
git checkout develop

git merge feature_branch2
tag the version you wish to release
git checkout provide_version_you_wish_to_release

git tag tag_name


text:
Q: List name for sheets being used in the formula of a specific sheet with the same workbook I am trying to write up a VBA function to get a list of name for sheets being used in the formula of a specific sheet.
Do you have any idea how to do so? Trying to use search function but seems it will mix up Old_Sheet11 and Sheet11.
Example:

*

*Sumifs(Sheet1!B:B,Sheet1!A:A,a1)

*Sumifs(Sheet2!B:B,Sheet2!A:A,a1)

*Sumifs(Sheet11!B:B,Sheet11!A:A,a1)

*Sumifs(Old_Sheet11!B:B,Old_Sheet11!A:A,a1)

*Sum(Sheet4!a5,Sheet6!a5)

List:

*

*Sheet1

*Sheet2

*Sheet11

*Old_Sheet11

*Sheet4

*Sheet6

Thanks.
Eric

A: This is not a trivial problem. But it was solved already back in 2014.
(see https://colinlegg.wordpress.com/2014/01/14/vba-determine-all-precedent-cells-a-nice-example-of-recursion/)
Find below the above code modified to spill out the requested list:
All Sheet references:
[ Sheet: Sheet1 -  0  ]
[ Sheet: Sheet1 -  1  ]
[ Sheet: Sheet2 -  2  ]
[ Sheet: Sheet2 -  3  ]
[ Sheet: Sheet11 -  4  ]
[ Sheet: Sheet11 -  5  ]
[ Sheet: Old_Sheet11 -  6  ]
[ Sheet: Old_Sheet11 -  7  ]
[ Sheet: Sheet4 -  8  ]
[ Sheet: Sheet6 -  9  ]

Your requested List:
Sheet1
Sheet2
Sheet11
Old_Sheet11
Sheet4
Sheet6

And here the modified code:
Option Explicit

'see https://colinlegg.wordpress.com/2014/01/14/vba-determine-all-precedent-cells-a-nice-example-of-recursion/
Sub Test2()

    Dim rngToCheck As Range
    Dim dicAllPrecedents As Object
    Dim dicPrecedents As Object
    Dim dicSheets As Object
    Dim i As Long
    Dim resultRange As Range
    Dim actSheetName As String
    Dim SheetNr As Integer

    Set rngToCheck = Sheet1.Range("A1:A5")
    Set dicAllPrecedents = GetAllPrecedents(rngToCheck)

    'The ORIGINAL displays the full address of the precendents
    '=========================================================
    '
    '    Debug.Print "==="
    'If dicAllPrecedents.Count = 0 Then
    '   Debug.Print rngToCheck.Address(External:=True); " has no precedent cells."
    'Else
    '    For i = LBound(dicAllPrecedents.Keys) To UBound(dicAllPrecedents.Keys)
    '        Debug.Print "[ Level:"; dicAllPrecedents.Items()(i); "]";
    '        Debug.Print "[ Address: "; dicAllPrecedents.Keys()(i); " ]"
    '    Next i
    'End If
    'Debug.Print "==="

    'List all sheets
    If dicAllPrecedents.Count = 0 Then
       Debug.Print rngToCheck.Address(External:=True); " has no precedent cells."
    Else
        For i = LBound(dicAllPrecedents.keys) To UBound(dicAllPrecedents.keys)
            'Debug.Print "[ Level:"; dicAllPrecedents.Items()(i); "]";
            Set resultRange = Range(dicAllPrecedents.keys()(i))
            Debug.Print "[ Sheet: "; resultRange.Parent.Name; " - "; i; " ]"
        Next i
    End If
    Debug.Print "==="

    'LIST EACH SHEET ONLY ONCE
    '=========================
    '
    Set dicSheets = CreateObject("Scripting.Dictionary")
    SheetNr = 0
    For i = LBound(dicAllPrecedents.keys) To UBound(dicAllPrecedents.keys)
        Set resultRange = Range(dicAllPrecedents.keys()(i))
        actSheetName = resultRange.Parent.Name
        If Not dicSheets.Exists(actSheetName) Then
            SheetNr = SheetNr + 1
            dicSheets.Add actSheetName, SheetNr
        End If
    Next i

    For i = LBound(dicSheets.keys) To UBound(dicSheets.keys)
        Debug.Print dicSheets.keys()(i)
    Next i
End Sub

'won't navigate through precedents in closed workbooks
'won't navigate through precedents in protected worksheets
'won't identify precedents on hidden sheets
Public Function GetAllPrecedents(ByRef rngToCheck As Range) As Object
    Const lngTOP_LEVEL As Long = 1
    Dim dicAllPrecedents As Object
    Dim strKey As String

    Set dicAllPrecedents = CreateObject("Scripting.Dictionary")

    Application.ScreenUpdating = False

    GetPrecedents rngToCheck, dicAllPrecedents, lngTOP_LEVEL
    Set GetAllPrecedents = dicAllPrecedents

    Application.ScreenUpdating = True
End Function

Private Sub GetPrecedents(ByRef rngToCheck As Range, ByRef dicAllPrecedents As Object, ByVal lngLevel As Long)
    Dim rngCell As Range
    Dim rngFormulas As Range

    If Not rngToCheck.Worksheet.ProtectContents Then
        If rngToCheck.Cells.CountLarge > 1 Then   'Change to .Count in XL 2003 or earlier
            On Error Resume Next
            Set rngFormulas = rngToCheck.SpecialCells(xlCellTypeFormulas)
            On Error GoTo 0
        Else
            If rngToCheck.HasFormula Then Set rngFormulas = rngToCheck
        End If

        If Not rngFormulas Is Nothing Then
            For Each rngCell In rngFormulas.Cells
                GetCellPrecedents rngCell, dicAllPrecedents, lngLevel
            Next rngCell
            rngFormulas.Worksheet.ClearArrows
        End If
    End If
End Sub

Private Sub GetCellPrecedents(ByRef rngCell As Range, ByRef dicAllPrecedents As Object, ByVal lngLevel As Long)
    Dim lngArrow As Long
    Dim lngLink As Long
    Dim blnNewArrow As Boolean
    Dim strPrecedentAddress As String
    Dim rngPrecedentRange As Range

    Do
        lngArrow = lngArrow + 1
        blnNewArrow = True
        lngLink = 0

        Do
            lngLink = lngLink + 1

            rngCell.ShowPrecedents

            On Error Resume Next
            Set rngPrecedentRange = rngCell.NavigateArrow(True, lngArrow, lngLink)

            If Err.Number <> 0 Then
                Exit Do
            End If

            On Error GoTo 0
            strPrecedentAddress = rngPrecedentRange.Address(False, False, xlA1, True)

            If strPrecedentAddress = rngCell.Address(False, False, xlA1, True) Then
                Exit Do
            Else

                blnNewArrow = False

                If Not dicAllPrecedents.Exists(strPrecedentAddress) Then
                    dicAllPrecedents.Add strPrecedentAddress, lngLevel
                    GetPrecedents rngPrecedentRange, dicAllPrecedents, lngLevel + 1
                End If
            End If
        Loop

        If blnNewArrow Then Exit Do
    Loop

End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does Selenium work for me in IntelliJ but fail when I run my jar in the command line? I set up Selenium version 4.7.1 in my project in IntelliJ using maven.  In order to get past the error reported here, I added an explicit dependency for guava version 31.1 (which is what is included in the lib folder of the downloadable package on the Selenium website for that version) and I added an exclusion on the selenium dependency for guava.
Now the application works fine when I run it in IntelliJ, but I'm getting this error when I run the jar in my terminal:
Exception in thread "main" java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
...
Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.WebDriver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)

Other similar questions I've found, like this one, all focus on the guava issue, but it seems like at this point my problem must have something to do with my build configuration in IntelliJ and the jar that is getting created.
I did find some discussions that seemed more pertinent to my issue, but they were geared towards people manually adding the jars, and the advice given was usually to switch to use maven or gradle, but I'm already using maven.  I have gone to Project Settings > Libraries and removed any external jars so that all dependencies should be getting pulled in by Maven.
Another discussion I found suggested using the maven-shaded-plugin, which I added and did mvn clean install, but still no luck.
How can I make sure the jar created by IntelliJ runs exactly the same as it runs in IntelliJ?  Any help is appreciated.

Here is my current pom.xml, which includes a suggestion from the current answer, but at this point I'm still experiencing the same issue:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>groupId</groupId>
<artifactId>stock-analysis</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>com.github.sh0nk</groupId>
        <artifactId>matplotlib4j</artifactId>
        <version>0.5.0</version>
        <exclusions>
            <exclusion>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.3.6</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-openfeign-core</artifactId>
    <version>3.0.2</version>
  </dependency>
  <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
  </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.4.2</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.4.2</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.8.0</version>
    <scope>test</scope>
  </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>RELEASE</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>31.1-jre</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.7.2</version>
        <exclusions>
            <exclusion>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.6</version>
        <configuration>

            <archive>
                <manifest>
                    <addClasspath>true</addClasspath>
                    <classpathPrefix>lib/</classpathPrefix>
                    <addDefaultImplementationEntries>false</addDefaultImplementationEntries>
                    <packageName>main.java.termaat.stocks.strategy.processing</packageName>
                    <mainClass>StockReportWriter</mainClass>
                </manifest>
            </archive>
        </configuration>
    </plugin>

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                    <outputDirectory>${project.build.directory}/lib</outputDirectory>
                    <includeScope>compile</includeScope>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>
</build>

<properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

Here is a screenshot of my project structure after the updates to my pom.  Currently the stock-analysis-1.0-SNAPSHOT.jar that is built is much to small, so I'm trying to figure out if something is configured wrong with the maven-jar-plugin.

A: Probably you aren't building dependencies correctly. U need both:
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <configuration>

                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <addDefaultImplementationEntries>false</addDefaultImplementationEntries>
                            <packageName>your package</packageName>
                            <mainClass>your class</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <includeScope>compile</includeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

It's hard to help if you don't post your pom.xml though


text:
Q: QuickBlox Android SDK OwnSurfaceView Issue Our team started building a video chat application utilizing the quickblox android SDK.  We have the requirements to resize the OpponentView to full screen while making the OwnSurfaceView smaller and overlaid on top.  Using this layout and method the quickblox iOS SDK is working as expected.
We are noticing that on most android devices we tested (agnostic of OS level; however this was occurring on 5.0 and 4.4)  the call would get connected and the OwnSurfaceView would not be displayed.  Shortly after this the video would crash.
We are seeing the following in the logs:
invalid address or address of corrupt block 0xb7b00a07 passed to dlfree

Fatal signal 11 (SIGSEGV), code 1, fault addr 0xdeadbaad in tid 10326 (Thread-1113)

PROFILE HAL: stopPreview(): E: 1417779352.559218326

config_MSG_ID_STOP_ACK: streamon_mask is not clear. Should not call PP_Release_HW

android::status_t android::QCameraHardwareInterface::setPreviewWindow(preview_stream_ops_t*):Received Setting NULL preview window

android::status_t android::QCameraHardwareInterface::setPreviewWindow(preview_stream_ops_t*): mPreviewWindow = 0x0x0, mStreamDisplay = 0x0xb82edc10

Setting NULL preview window

Destroying camera 1

virtual android::QCameraHardwareInterface::~QCameraHardwareInterface() First stop the polling threads before deleting instances

config_shutdown_pp Camera not in streaming mode. Returning.

vfe_ops_deinit: E

E/qcom_sensors_hal﹕ hal_process_report_ind: Bad item quality: 11

I/OpenGLRenderer﹕ Initialized EGL, version 1.4

D/audio_hw_primary﹕ disable_audio_route: reset and update mixer path: audio-record

D/audio_hw_primary﹕ disable_snd_device: snd_device(16: handset-mic)

D/NuPlayerDriver﹕ reset(0xb82e4480)

D/NuPlayerDriver﹕ notifyResetComplete(0xb82e4480)

D/NuPlayerDriver﹕ reset(0xb8355c10)

D/NuPlayerDriver﹕ notifyResetComplete(0xb8355c10)

Process 10109 exited due to signal (11)

qcom_sensors_hal﹕ hal_process_report_ind: Bad item quality: 11

A: The log represented by you related with error in 3-party lib. Obviously you were trying to manage Camera instance in a wrong way.
in IOS version there are different instances for each opponent representation, however in Android one is used for both users. So you can't manage view for representing opponents separatly for each of them, but you can try manage video rendering on your view. via VideoRenderer.Callbacks instances.
In the nearest future we are planing to renew android webrtc module and add QBCustomVideoView for representing each user in separete view.
Moreover many other features will be added in new QuickBlox SDK version, for example the strongly dependency of QBClient instance from Activity class will be removed, code and logic will be reviewed, multi call feature will be added  and so on.


text:
Q: Duplicate files copied in APK META-INF/LICENSE.txt I am trying to create a Java application that reads tweets from my account, stores them into a database and retrieves the tweet data. I am using the Twitter4j library, however, every time I build and run my program I am receiving this error:
Error:Gradle: Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/LICENSE.txt
File1: /Users/paulmbw/.gradle/caches/modules-2/files-2.1/org.twitter4j/twitter4j-core/4.0.4/1f3c896c7b2f20c51103078ccf0bc2ea97ac012a/twitter4j-core-4.0.4.jar
File2: /Users/paulmbw/.gradle/caches/modules-2/files-2.1/org.twitter4j/twitter4j-stream/4.0.4/e9c442a779c65cef8872e8676bf693ad88379086/twitter4j-stream-4.0.4.jar

Here is what my build.gradle look file looks like:
buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
    }
}
  apply plugin: 'com.android.application'
 apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
}

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "com.example.paulmbw.myapplication"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.google.android.gms:play-services-ads:8.4.0'
compile 'com.google.android.gms:play-services-identity:8.4.0'
compile 'com.google.android.gms:play-services-gcm:8.4.0'
compile 'org.twitter4j:twitter4j-core:4.0.4'
compile 'org.mongodb:mongo-java-driver:3.2.2'
compile 'org.twitter4j:twitter4j-stream:4.0.4'
compile 'com.google.code.gson:gson:2.6.2'
}

I have seen similar questions to this and others have suggested I am have unused dependencies, however I do believe I am using all of the entries listed above. What I'm I doing wrong?
Your help will be greatly appreciated.


text:
Q: How to pass javascript variable value from .aspx page to .ashx page I am trying to pass some JavaScript variable value from .aspx file to .ashx file when user uploads a document in the web form.
The web form is a .aspx file and the uploading functionality is in .ashx file. So I need to pass the variables from  .aspx file to .ashx file.

I was able to pass three variables but when I try to pass the fourth one then it does not work. It does not give any error but just do not pass any of the variables. When I debug the code I can see the debugger does not enters the process of upload. And the upload button also changes

This is my .aspx page code.
<%@ Page Title="" Language="VB" MasterPageFile="~/_resx/E4.master" AutoEventWireup="true" CodeFile="new.aspx.vb" Inherits="E4_Jobs_new" ValidateRequest="false" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">

 <asp:RequiredFieldValidator runat="server" ControlToValidate="txtTitle" Display="None" ErrorMessage="xx" ValidationGroup="NewJob" EnableViewState="False" />

          <input type="text" id="txtTitle" runat="server" maxlength="64" />

                    <% For Each additionalDoc As DataRow In Vacancy.Attachemnts.Rows%>
                    <li id="da<%= additionalDoc.Item("id") %>">
                        <%= additionalDoc.Item("name") %>
                        <span class="rd" data-did="<%= additionalDoc.Item("id")%>"> remove

                    <%Next%>

                <input id="file_upload" name="file_upload" type="file">

</asp:Content>

And this is the code in the .aspx file where I am passing the variables into .ashx file
$(function () {

        dimNav('vacancy');

        $('#file_upload').uploadify({
            'buttonClass': 'button2',
            'buttonText': 'Select a PDF or DOCX file to upload..',
            'width': 250,
            'fileTypeExts': '*.pdf; *.doc; *.docx',
            'formData': {
                'draftId': id,
                'type': mode,
                'employer': employer,
                'jtitle': jtitle

            },
            'uploadLimit': 6,
            'swf': '/_resx/uploadify.swf',
            'uploader': '/e4/jobs/upload-job-attachments.ashx',
            'onUploadSuccess': function (file, data, response) {
                $('#attachmentList').append('
' + file.name + ' remove
');
            }
        });
    });

The first three variables values are obtained differently than the fourth one. In the fourth one I used javascript function to get the value (as it is the input value given by the user.  Not a value stored already in database. ) .
This is my code for  in the  upload-job-attachments.ashx file where I retrieve the values
 Public Class upload_job_attachments : Implements IHttpHandler

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    context.Response.ContentType = "text/plain"
    context.Response.Expires = -1
    Try

        Dim Id As Integer = CInt(context.Request("draftid"))
        Dim type As String = CStr(context.Request("type"))
        Dim empname As String = CStr(context.Request("employer"))
        Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")

          ********** other lines of code ***********

  End Sub
End Class

what can I do to overcome the problem. I am weak in advanced javascript functionalities.  I appreciate your help

Addition
The whole script looks like
      $(function () {
        dimNav('vacancy');

        var jobTitle = $('#' + '<%= txtTitle.ClientID%>').val();

        $('#file_upload').uploadify({
            'buttonClass': 'button2',
            'buttonText': 'Select a PDF or DOCX file to upload..',
            'width': 250,
            'fileTypeExts': '*.pdf; *.doc; *.docx',
            'formData': {
                'draftId': id,
                'type': mode,
                'employer': employer,
                'jtitle': jobTitle

            },
            'uploadLimit': 6,
            'swf': '/_resx/uploadify.swf',
            'uploader': '/e4/jobs/upload-job-attachments.ashx',
            'onUploadSuccess': function (file, data, response) {
                $('#attachmentList').append('
' + file.name + ' remove
');
                alert($('#' + '<%= txtTitle.ClientID%>').val());
            }
        });

        $('body').on('click', '.rd', function () {
            var el = $(this);
            $.post('delete-job-attachment.ashx?id=' + el.attr('data-did'), '{}', function () {
                $('#da' + el.attr('data-did')).remove();
            });
        });

        $('.price-button').click(function () { $(this).next('.price-list').fadeToggle('slow'); });

        $('.m-lists table tr:nth-child(4) td:nth-child(1)').prepend('
Multiple job posting
');

        $('.jMedias').change(function () {
            suffleMedias();
        });

        var suffleMedias = function () {
            var mids = [];
            $('.jMedias:checked').each(function () {
                mids.push($(this).val());
            });
            $('.mediaLists').val(mids.toString());
        };

        $('.jType').change(function () {
            suffleJobType();
        });

        $('input:radio.p-option-radio').change(function () {
            var pOption = $(this).val();
            $('.p-option').val(pOption);
        });

        var suffleJobType = function () {
            var type = $('.jType').val();
            if (type == 0) {
                $('#contractLength, #jobHour').slideUp();
            } else if (type == 1) {
                $('#jobHour').slideDown();
                $('#contractLength').slideUp();
            } else if (type == 2) {
                $('#jobHour').slideDown();
                $('#contractLength').slideUp();
            } else if (type == 3) {
                $('#contractLength, #jobHour').slideDown();
            }

        };

        var suffleFeeType = function () {
            var fType = $('.feeType').val();

            if (fType == 0) {
                $('#salaryRateMax, #salaryRateMin, #agencyFee').slideDown();
            } else if (fType == 1) {
                if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
                 } else {
                    $('#salaryRateMax, #salaryRateMin').slideUp();
                }
                $('#agencyFee').slideDown();
            } else if (fType == 2) {
                $('#agencyFee').slideUp();
                if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
                 } else {
                    $('#salaryRateMax, #salaryRateMin').slideUp();
                }
            }
        };

        $('.feeType').change(function () {
            suffleFeeType();

        });
        $('.referrerPercentage').change(function () {
            if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
                $('#salaryRateMax, #salaryRateMin').slideDown();
            } else {
                if ($('.feeType').val() == 1) {
                    $('#salaryRateMax, #salaryRateMin').slideUp();
                }
            }
        });

        $('.calcFee').change(function () {
            CalculateAndDisplayFees();
        });

        $('.rAgency').chosen().change(function () {
            if ($(this).val() != '-1') {
                $('.psls').val('-1').trigger("liszt:updated");
                $('.retained').val('1');
            }
        });

        $('.psls').chosen().change(function () {
            if ($(this).val() != '-1') {
                $('.rAgency').val('-1').trigger("liszt:updated");
                $('.retained').val('0');
            }
        });

        var setPublishOption = function () {
            var p = $('.p-option').val();
            var $radios = $('input:radio.p-option-radio');
            $radios.filter('[value=' + p + ']').attr('checked', true);
        };

        suffleJobType();
        suffleFeeType();
        suffleMedias();
        CalculateAndDisplayFees();
        setPublishOption();
    });

A: If, for instance, the jtitle field needs to come from an input control, you can do:
'formData': {
    'jtitle': $("#somecontrol").val()
}

Which will get the value from a control.  Is that what you mean?


text:
Q: AWS Network ELB vs security groups Decided to move a couple of internal LBs from classic to network ELB. And I have noticed that NetELB does not accept traffic within the scope of those rules which have as source another security group ID(rules that have IP address sources do work).
Haven't noticed anything mentioned in the official docs about this phenomena and I am wondering if this happens due to some misconfiguration, or is a real limitation of Network ELB? Maybe AWS is working on it? It would ease the migration a lot. Opening the whole VPC CIDR or entire subnets isn't so much fun, neither refactoring the existing subnets to be more granular when opening them in security groups.

A: The Network Load Balancer (NLB) is just forwarding your connection on to an appropriate listener, so you would manage the security group on the listeners.
Take a look at the 2017 reInvent session "Tuesday Night Live" for details on Hyperplane, which is how the NLB (and other services) are actually implemented.


text:
Q: Binary Tree, how to Count All Left and Right Child php, mysql Table name classes I show you database screenshot
I am try this code but output is 0
Dear friend I have to count Left Child and Right Child of a Binary Tree My database structure is as under.
 function allcount($id)
{
    $sql = "SELECT parentsclass, childclassleft, childclassright FROM classes WHERE parentsclass = '".$id."'";
    $execsql = mysqli_query($conn,$sql);
    $array = mysqli_fetch_array($execsql);
    (array_count_values($array));
    $count = 0;
    if(!empty($array['childclassleft']))
    {
        $count += allcount($array['childclassleft']) +1;
    }
    if(!empty($array['childclassright']))
    {
        $count += allcount($array['childclassright']) +1;
    }
    return $count;
}

echo allcount();

A: I Used this code this code count left and right child node....
$memid="95000";   // your id

function getTotalLeg($memid,$leg){
      global $conn;
     $sql="select child_class from tree_class where parent_id='".$memid."' and position='".$leg."'";
      $res=mysqli_query($conn,$sql);
      $row=mysqli_fetch_array($res);
      global $total;
       $total=$total+mysqli_num_rows($res);
         if($row['child_class']!=''){
           getTotalLeg ($row['child_class'],'L');
           getTotalLeg ($row['child_class'],'R');
          }
          return $total;
        }

     $total=0;
    $left=getTotalLeg($memid,"L");
    echo $total."</br>";
     $total=0;
    $right=getTotalLeg($memid,"R");
    echo $total;


text:
Q: Select the number of days a record is present within a certain year/month In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.
So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:
November  16 days
December  5 days
Total     21 days

I've been beating my head against the wall with this one and am fresh out of ideas.

A: You want to use DateDiff
DateDiff("d",[StartDate],[EndDate])
the d above will count days.

A: This is probably the most concise answer.
declare @start datetime, @end datetime
select @start = '20101115', @end = '20101205'

select datename(month,@start+number), count(*)
from master..spt_values
where type='P'
  and number between 0 and datediff(d,@start,@end)
group by datename(month,@start+number), convert(char(6),@start+number,112)
order by convert(char(6),@start+number,112)

It will work for ranges up to 2048 days (7-8 years) but can by extended for longer if you need (on request only - that will looks more complicated).
The only reason for the convert(char portion is to make November come up before December, and also before January of the next year.

A: EDIT: Another minor fix or two...
Edited to give the full answer...
declare @user_start_date datetime
set @user_start_date = '1/1/2011'
declare @user_end_date datetime
set @user_end_date = '1/10/2011'
declare @job_start_date datetime
set @job_start_date = '1/2/2011'
declare @job_end_date datetime
set @job_end_date = '1/11/2011'

declare @nextStartDate datetime;
set @nextStartDate = str(datepart(mm, @user_start_date)) + '/1/' + str(datepart(yyyy, @user_start_date))
declare @nextEndDate datetime;
set @nextEndDate = dateadd(dd,-1,dateadd(mm,1,@nextStartDate))

create table #monthYears(startDate datetime, endDate datetime)
while (@nextStartDate < @user_end_date) begin
    insert into #monthYears values(@nextStartDate, @nextEndDate)
    set @nextStartDate = dateadd(mm,1,@nextStartDate)
    set @nextEndDate = dateadd(dd,-1,dateadd(mm,1,@nextStartDate))
end

-- Print Months
select [month], [year], case when dayCount < 0 then 0 else dayCount end from (
select month(startDate) month, year(startDate) year , datediff(dd,
    case when startDate > @job_start_date then startDate else @job_start_date end,
    case when endDate < @job_end_date then endDate else @job_end_date end) dayCount
from #monthYears) temp

select datediff(dd,
    case when @user_start_date > @job_start_date then @user_start_date else @job_start_date end,
    case when @user_end_date < @job_end_date then @user_end_date else @job_end_date end)

A: This is kinda hard in SQL but this will create a table with the month (in integer) and the number of days.
I'll leave it to you to convert the integer to the month and add the total
SET NOCOUNT on

Declare @StartDate datetime
Declare @EndDate datetime
Declare @StartDateNormalized datetime
Declare @EndDateNormalized datetime

SET @StartDate = '2010/11/15'
SET @EndDate = '2011/2/05'

declare @result table ( month int, days int)

--Normalize the Inputs

SET @StartDateNormalized = cast(Month(@startDate) as varchar) + '/1/' + cast(year(@startDate) as varchar)
SET @EndDateNormalized = cast(Month(@EndDate) as varchar) + '/1/' + cast(year(@EndDate) as varchar)

insert into @result
values
(   MONTH(@StartDateNormalized),
    DateDiff(Day, @StartDate, DateAdd(month, 1, @StartDateNormalized ) )
)

SET @StartDateNormalized = DateAdd(month, 1, @StartDateNormalized )

WHILE (@StartDateNormalized < @EndDateNormalized)
BEGIN

insert into @result
values
(   MONTH(@StartDateNormalized),
   DateDiff(Day, @StartDateNormalized, DateAdd(month, 1, @StartDateNormalized ) )
)

   SET @StartDateNormalized = DateAdd(month, 1, @StartDateNormalized )
END

insert into @result
values
(   MONTH(@EndDateNormalized),
   DateDiff(Day, @EndDateNormalized, @EndDate    ) + 1
)

select * from @result

A: DECLARE
   @StartDate datetime,
   @EndDate datetime;
SET @StartDate = '20101115';
SET @EndDate = '20101205';

WITH Mos AS (
   SELECT
      Number,
      DateAdd(Month, Number, @StartDate - Day(@StartDate) + 1) MoDate
   FROM master.dbo.spt_values
   WHERE
      Type = 'P'
      AND Number <= DateDiff(Month, @StartDate, @EndDate)
), Dys AS (
   SELECT
      MoDate,
      DateDiff(
         Day,
         CASE WHEN Number = 0 THEN @StartDate ELSE MoDate END,
         CASE WHEN Number = DateDiff(Month, @StartDate, @EndDate) THEN @EndDate ELSE DateAdd(Month, 1, MoDate) - 1 END
      ) + 1 Cnt
   FROM Mos
)
SELECT
   Year(MoDate) Yr,
   Coalesce(DateName(Month, MoDate), 'Total') Mo,
   Convert(varchar(11), Sum(Cnt)) + ' day' + CASE WHEN Sum(Cnt) = 1 THEN '' ELSE 's' END Descr
FROM Dys
GROUP BY MoDate
WITH ROLLUP
ORDER BY Grouping(MoDate), MoDate;

And here's a table version in case you wanted to do it with many at once:
CREATE TABLE AccountDates (
   AccountCode varchar(10) NOT NULL CONSTRAINT PK_AccountDates PRIMARY KEY CLUSTERED,
   StartDate datetime,
   EndDate datetime
);

INSERT AccountDates VALUES ('BLINKEN', '20101115', '20101205');
INSERT AccountDates VALUES ('KRAM', '20101027', '20110118');
INSERT AccountDates VALUES ('NUVU', '20101207', '20101207');

WITH Mos AS (
   SELECT
      AccountCode,
      D.StartDate,
      D.EndDate,
      Number,
      DateAdd(Month, Number, D.StartDate - Day(D.StartDate) + 1) MoDate
   FROM
      AccountDates D
      INNER JOIN master.dbo.spt_values V ON V.Number <= DateDiff(Month, D.StartDate, D.EndDate)
   WHERE
      V.Type = 'P'
), Dys AS (
   SELECT
      AccountCode,
      MoDate,
      DateDiff(
         Day,
         CASE WHEN Number = 0 THEN StartDate ELSE MoDate END,
         CASE WHEN Number = DateDiff(Month, StartDate, EndDate) THEN EndDate ELSE DateAdd(Month, 1, MoDate) - 1 END
      ) + 1 Cnt
   FROM Mos
)
SELECT
   AccountCode,
   Year(MoDate) Yr,
   Coalesce(DateName(Month, MoDate), 'Total') Mo,
   Convert(varchar(11), Sum(Cnt)) + ' day' + CASE WHEN Sum(Cnt) = 1 THEN '' ELSE 's' END Descr
FROM Dys
GROUP BY AccountCode, MoDate
WITH ROLLUP
HAVING Grouping(AccountCode) = 0
ORDER BY
   AccountCode,
   Grouping(MoDate),
   MoDate;

I simplified things a little from my original query.

A:
The following example determines the
  difference in days between the current
  date and the order date for products
  in the AdventureWorks database.

USE AdventureWorks;
GO
SELECT DATEDIFF(day, OrderDate, GETDATE()) AS NumberOfDays
FROM Sales.SalesOrderHeader;
GO

http://msdn.microsoft.com/en-us/library/ms189794%28v=sql.90%29.aspx


text:
Q: Why can't I cast an MP4 file served by PHP from outside of the document root? Ok, I give up... Something very strange is going on and, after days of messing with this, I have to ask for help. I have a PHP script that serves an MP4 file from outside of the document root. This script works great, except for one very important (to me at least) detail: it will not give me the option to cast the content. On the same server, when I access an MP4 file that IS inside the document root, I load the page and when I click the three dots in the bottom right corner of the Chrome video player, I have the option to Download or Cast to my Chromecast. Using my script, I only have the option to Download, and I REALLLLY need to CAST! I have tweaked this so much that the headers output from either method are all but identical. Here is my code...
<?php
$file=$_GET['file'];

//validate
if($file=="." || $file==".."){$file="";}

$mediaRoot="../../../hostMedia";
$file=$mediaRoot . DIRECTORY_SEPARATOR . $file;
$file=str_replace('\\',"/",$file);

$filesize = filesize($file);

$offset = 0;
$length = $filesize;

// find the requested range
preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);

$offset = intval($matches[1]);

$length = (($matches[2]) ? intval($matches[2]) : $filesize) - $offset;

// output the right headers for partial content
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $offset . '-' . ($offset + $length-1) . '/' . $filesize);
header('Content-Type: video/mp4');
header('Content-Length: ' . $filesize);
header('Accept-Ranges: bytes');
header('Cache-Control: max-age=0');

// open file for reading
$file = fopen($file, 'r');

// seek to the requested offset, this is 0 if it's not a partial content request
fseek($file, $offset);

// populate $data with all except the last byte of the file
$numBytes=($filesize-1);
$dataLen=0;
while($dataLen<$numBytes){
    $lenGrab=($numBytes-$dataLen);
    if($lenGrab>(1024*2700)){$lenGrab=(1024*2700);}
    $data=fread($file, $lenGrab);
    print($data);
    $dataLen+=strlen($data);
}

// close file
fclose($file);
?>

A thousand "thank-you"s to whoever solves this one!
UPDATE
Ok, taking @Brian Heward's advice, I have spent countless hours making sure that the headers are ABSOLUTELY IDENTICAL!!! I was so sure it would work, but alas, it still fails to give me the option to cast. Here is my updated PHP...
<?php
session_start();

$accessCode=$_SESSION['accessCode'];
$file=$_GET['file'];

//handle injection
if($file=="." || $file==".."){$file="";}

if($accessCode=="blahblahblah8"){

    $mediaRoot="../../../hostMedia";
    $file=$mediaRoot . DIRECTORY_SEPARATOR . $file;
    $file=str_replace('\\',"/",$file);

    $filesize = filesize($file);

    $offset = 0;
    $length = $filesize;
    $lastMod=filemtime($file);

    if ( isset($_SERVER['HTTP_RANGE']) ) {
        // if the HTTP_RANGE header is set we're dealing with partial content
        $partialContent = true;
        // find the requested range
        preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
        $offset = intval($matches[1]);
        $length = (($matches[2]) ? intval($matches[2]) : $filesize) - $offset;
    } else {
        $partialContent = false;
    }

    if ( $partialContent ) {
        // output the right headers for partial content
        header('HTTP/1.1 206 Partial Content');
        header('Content-Range: bytes ' . $offset . '-' . ($offset + $length-1) . '/' . $filesize);
    }else{
        header('HTTP/1.1 200 OK');
    }

    // output the regular HTTP headers
    header('Content-Type: video/mp4');
    header('Content-Length: ' . $length);
    header('Accept-Ranges: bytes');
    header('ETag: "3410d79f-576de84c004aa"');
    header('Last-Modified: '.gmdate('D, d M Y H:i:s \G\M\T', $lastMod));

    // don't forget to send the data too
    $file = fopen($file, 'r');

    // seek to the requested offset, this is 0 if it's not a partial content request
    fseek($file, $offset);

    //populate $data with all except the last byte of the file
    $numBytes=($length);
    $dataLen=0;
    while($dataLen<$numBytes){
        $lenGrab=($numBytes-$dataLen);
        if($lenGrab>(1024*2700)){$lenGrab=(1024*2700);}
        $data=fread($file, $lenGrab);
        print($data);
        $dataLen+=strlen($data);
    }

    fclose($file);
}else{
    echo "You are not authorized to view this media.";
}

?>

If someone can get this thing to work, you are seriously a superhero!
FINAL UPDATE (for now...)
Well, after many, many hours of frustration, I had to abandon the approach and try something different. Luckily, there are usually more than one way to accomplish something, and I have found another way. I am hosting the .mp4 files inside the doc root in a folder protected using HTTP Basic Auth. Very similar to what I was trying to achieve and it is working for me. Thanks for your advice and direction!

A: Your headers are "all but identical" and there is the problem. Make them identical :P
Use the developer tools on your browser, (F12) and check the network headers each request is making.  The most likely causes are the following lines I used on a similar project and you seem to be missing:
header('Content-Description: File Transfer');
header('Content-Disposition: inline; filename=' . basename($file));

alternately it might want
header('Content-Disposition: attachment; filename=' . basename($file));

A: This script might be what you're looking for, it handles video serving via PHP really well, Source
 <?php
// disable zlib so that progress bar of player shows up correctly
if(ini_get('zlib.output_compression')) {
    ini_set('zlib.output_compression', 'Off');
}

$folder = '.';
$filename = 'video.mp4';
$path = $folder.'/'.$filename;

// from: http://l...content-available-to-author-only...n.net/post/stream-videos-php/
if (file_exists($path)) {
    // Clears the cache and prevent unwanted output
    ob_clean();

    $mime = "video/mp4"; // The MIME type of the file, this should be replaced with your own.
    $size = filesize($path); // The size of the file

    // Send the content type header
    header('Content-type: ' . $mime);

    // Check if it's a HTTP range request
    if(isset($_SERVER['HTTP_RANGE'])){
        // Parse the range header to get the byte offset
        $ranges = array_map(
            'intval', // Parse the parts into integer
            explode(
                '-', // The range separator
                substr($_SERVER['HTTP_RANGE'], 6) // Skip the `bytes=` part of the header
            )
        );

        // If the last range param is empty, it means the EOF (End of File)
        if(!$ranges[1]){
            $ranges[1] = $size - 1;
        }

        // Send the appropriate headers
        header('HTTP/1.1 206 Partial Content');
        header('Accept-Ranges: bytes');
        header('Content-Length: ' . ($ranges[1] - $ranges[0])); // The size of the range

        // Send the ranges we offered
        header(
            sprintf(
                'Content-Range: bytes %d-%d/%d', // The header format
                $ranges[0], // The start range
                $ranges[1], // The end range
                $size // Total size of the file
            )
        );

        // It's time to output the file
        $f = fopen($path, 'rb'); // Open the file in binary mode
        $chunkSize = 8192; // The size of each chunk to output

        // Seek to the requested start range
        fseek($f, $ranges[0]);

        // Start outputting the data
        while(true){
            // Check if we have outputted all the data requested
            if(ftell($f) >= $ranges[1]){
                break;
            }

            // Output the data
            echo fread($f, $chunkSize);

            // Flush the buffer immediately
            @ob_flush();
            flush();
        }
    }
    else {
        // It's not a range request, output the file anyway
        header('Content-Length: ' . $size);

        // Read the file
        @readfile($path);

        // and flush the buffer
        @ob_flush();
        flush();
    }

}
die();

?>


text:
Q: Solving an exponential equation with different bases Solve the equation $2^x + 5^x = 3^x + 4^x$. I can figure out two special solutions $x=0$ and $x=1$, and I try to prove that they are the only two solutions. However, I find it hard to do so because I can't prove the monotony given there are also exponential in the derivative. Any hints to that?

A: $$2^x+5^x=3^x+4^x \iff5^x-4^x=3^x-2^x$$
Lagrange's theorem applies (intermediate value theorem) functions:
$$f:[4, 5]\to \mathbb R,\ g:[2, 3]\to \mathbb R,\ f(u)= u^x,\ g(v)=v^x$$
Exist $c\in [4, 5]$ and exist $ d\in [2, 3] $ so
$5^x-4^x = xc^{x-1}$ and $3^x-2^x=xd^{x-1}$.
The equation is written as equivalent: $$xc^{x-1}= xd^{x-1}.$$
It follows that equation solutions are $0$ and $1.$

A: Since $f(a)=a^x$ is concave for $x\in[0,1]$ and convex for $x\not\in(0,1)$, the definitions of concavity and convexity say
$$
\begin{align}
\color{#C00}{3^x}+\color{#090}{4^x}
&=\color{#C00}{\left(\frac23\cdot2+\frac13\cdot5\right)^x}+\color{#090}{\left(\frac13\cdot2+\frac23\cdot5\right)^x}\tag1\\[3pt]
&{\ge\atop\le}\color{#C00}{\left(\frac23\cdot2^x+\frac13\cdot5^x\right)}+\color{#090}{\left(\frac13\cdot2^x+\frac23\cdot5^x\right)}{{\quad\text{if }x\in[0,1]}\atop{\quad\text{if }x\not\in(0,1)}}\tag2\\[6pt]
&=2^x+5^x\tag3
\end{align}
$$
Explanation:
$(1)$: write $3$ and $4$ as convex combinations of $2$ and $5$
$(2)$: definition of $\text{concavity}\atop\text{convexity}$
$(3)$: combine like terms
Furthermore, equality holds only if $f$ is linear on $\{2,3,4,5\}$, and that happens iff $x\in\{0,1\}$.


text:
Q: WebNative Portal Xinet - Grab image I am trying to grab an image on my WebNative Xinet portal. When i use the method i am using right now: I get an image back, but i also get all the HTML with it to display the image. This is what i am using to grab the image right now:
GETIMAGE.php?type=small&path=/Images/myimage.png

This is kind of working. The issue with this is that it returns a complete HTML document with the image tags in it displaying the image.
How is it possible to get the raw image back with no HTML included? My main objective is to grab the image and encode it to base64 to be displayed in an e-mail.

A: That request should absolutely be giving you an HTTP response with an image payload.
I'm assuming you're using cURL to speak with Portal.  Did you authenticate with server before making the GETIMAGE.php request?  If so, are you including the session ID cookie in your GETIMAGE.php request?
EDIT: I saw your other post and it looks exactly like the auto-generated code Chrome shows in its DOM inspector.  Are you sure you're getting HTML from that URL?  I'm staring at the source and I can't find anywhere where it emits HTML.


text:
Q: Wrong SQL table structure I need a new table for a better clicked links tracking system, I tried with this:
CREATE TABLE tracker (
    id int(10) NOT NULL auto_increment,
    link varchar(255) NOT NULL,
    clicks int(10) NOT NULL

    PRIMARY KEY (id)
);

But I got this error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(id))' at line 6

Any ideas about what the problem is? How do I have to put the structure to make it correct?

A: You are missing a , after the clicks int(10) NOT NULL column !
CREATE TABLE tracker (
    id int(10) NOT NULL auto_increment,
    link varchar(255) NOT NULL,
    clicks int(10) NOT NULL,
    PRIMARY KEY (id)
);

A: The comma operator is missing after the clicks int(10) NOT NULL column.

A: try this,
CREATE TABLE tracker(
id INT NOT NULL AUTO_INCREMENT ,
link VARCHAR( 255 ) NOT NULL ,
clicks INT NOT NULL ,
PRIMARY KEY ( id )
)

A: You are missing comma near clicks int(10) NOT NULL.No need to mention int length
CREATE TABLE tracker (
id int NOT NULL auto_increment,
link varchar(255) NOT NULL,
clicks int NOT NULL,
PRIMARY KEY (id)
);

http://sqlfiddle.com/#!2/487352


text:
Q: regex validating url I have the following urls as subjects
localhost/hx
localhost/h.php
localhost/h/x
localhost/h/x/y
localhsot/h?hello
localhost/h

Currently my pattern is something like /localhost/h[/]*/i, but this does not work.
I do not want to match line 1 or 2, but the others are valid.

*

*Problem 1: I am not able to make / or ? optional, if I remove * from the pattern it does not match localhost/h.

*Problem 2: I am not able to escape ? for line 5, I tried \\ and \ but neither worked.

A: I'd use:
/localhost\/h(?:\/|\?|$)/

A: You have two conditions:

*

*The uri should end up after the h

*The uri should be h followed by / or ? and some chars after

so you need an alternative match.
a correct regex would be localhost\/h(?:$|[?\/].+) Demo Here
What is does is matching localhost/h litteraly and then opening a non capturing group (?: with two alternative

*

*end of line with $
or |

*

*/ or ? followed by at least one char .+

A: I used a regex making use of Negative Lookbehinds.
Regex: .*+(?<!\.php)(?<!hx)
See this DEMO too see how it works.


text:
Q: Sort Multiple Files Recursively I am attempting to sort multiple types of files recursively throughout multiple sub-directories.
Currently I have this, which only sorts through the current directory and only for one specific type of file :
for x in *.jpg; do
   d=$(date -r "$x" +%Y-%m-%d)
   mkdir -p "$d"
   mv -- "$x" "$d/"
done

I would like the sorting to be able to search through sub-directories, and sort multiple types of files instead of just "*.jpg" files.

A: Assuming you are using bash 4, it's as simple as
shopt -s globstar
for x in **/*; do
    [[ -d $x ]] && continue  # Skip directories
    d=$(date -r "$x" +%Y-%m-%d)
    mkdir -p "$d"
    mv -- "$x" "$d/"
done


text:
Q: If the running time is short ( 2 ms), would it be worth to use multiple threads? I wrote a Java program. For a small input, after warm-up (the first 50 runs), its running time turns to be around 2 milliseconds.
In this case, could we get any benefit if I use multiple threads version? If not, what are the overhead hidden the benefits of parallel execution?

A: Most likely the overhead of starting the threads would far outweigh any speedup. On windows you'll even have trouble measuring the execution time reliably for such fast programs.
But of course, you must ask yourself if you truly need any speedup for a program that runs in 2 ms.

A: Id depends on if 2ms is too slow. It also depends if you want to run the tasks concurrently.
Why not use an Executor to run your tasks then you can add threads as you need them.

A: Well, 2ms is at least a candidate for splitting up over multiple threads.  Continually creating/running/terminating/joining threads is a non-starter - hopeless design.  If signaling work to a set of dedicated threads or issuing work to a pool, it all depends on the work done and the data organization.
If there is any blocking, or CPU-intensive, work that an be effectively performed in parallel in those 2ms, then you could give it a go.  The key issue with CPU-intensive work is how much data and how it is organized.  If the data to be worked on can easily be chopped up into nice, [L1-cache-size or smaller] chunks, you're onto a winner.  If not, be prepared for a dissapointment.
You could, of course, try it and see..


text:
Q: resizing row's height in QTreeWidget/QTreeView I have some problems with sizing row's height in QTreeWidget. I use QStyledItemDelegate with QPlainTextEdit. During editing text in QPlainTextEdit i check for changes with a help of:
rect = self.blockBoundingRect(self.firstVisibleBlock())

and if text's height changes i resize editor size and need row in QTreeWidget also resizing. But i don't know how to inform TreeWidget or a Delegate about changes. I tried to initialize editor with index, that i could use in a future, but Delegate creates new editor every time and i failed to use signals. Also I used following function to catch resize event, but it' doesn't:
bool QAbstractItemDelegate::editorEvent ( QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index )

How can i bound editor's size changes with TreeWidget?
And one more thing, by default all items (cells) in TreeWidget have -1 or some big value as default width. I need whole text in cell to be visible, so how can i limit cells width only by visible range and make it expand in height? I want for it the same behavior as in instance a table in MSWord.
Thank you in advance,
Serge

A: I believe you would have to notify model about the data change without closing editor, this should force treeview to recalculate its row height according to the new content of the field it's showing. What you could do is override eventFilter method in your delegate and try to emit commitData signal on key press; smth like this:
bool YourStyledItemDelegate::eventFilter(QObject* object, QEvent* event)
{
    bool result = QStyledItemDelegate::eventFilter(object, event);
    QWidget* editor = qobject_cast<QWidget*>(object);
    if (editor)
    {
        if (event->type() == QEvent::KeyPress)
        {
            emit commitData(editor); //<- this should force row to recalculate its size
        }
    }
    return result;
}

hope this would give you an idea on how to proceed, regars


text:
Q: laying out button group in a ClojureScript om-bootstrap navbar I'm trying to include a button group in the navbar of a ClojureScript application in which I'm using om-bootstrap, but the layout isn't coming out right --- it's like the button group is interrupting the navbar's layout flow.  What I'm getting looks like this:

I'd like it to look more like this, with everything on one line:

Here's my code:
(fn [data owner]
  (reify
    om/IRender
    (render [_]
      (n/navbar
       {:brand (d/a {:href "#"} "Brand")}
       (n/nav
        {:collapsible? true}
        (b/dropdown {:key 1, :title "Menu 1"}
                    (b/menu-item {:key 11} "Hamburger")
                    (b/menu-item {:key 12} "Fries")
                    )
        (b/button-group {}
                        (b/button {} "Foo")
                        (b/button {} "Bar"))
        (b/dropdown {:key 2, :title "Menu 2"}
                    (b/menu-item {:key 21} "Tofu")
                    (b/menu-item {:key 22} "Salad")
                    )
        )))))

Can someone explain how to get everything on one line?

A: I would use a row.
This is a sample layout from a page of mine.  I have one row, two columns.  The first column has three vertical items.  The second column contains a table.
If you set the "width" (:xs 12) and have a single column, it should take up the width of the page.  There are different settings for what I am calling width.  It decides, based on device, when things wrap.
        [om-bootstrap.grid :as g]

                (d/div #js {:style (utils/display (:display e-map))}
                       (p/panel {:header (str "Daily Schedule for " current-date)
                                 :bs-style "primary"
                                 :footer (utils/footer-text)}
                                (g/row {}
                                       (g/col {:class "daily-widgets"
                                               :xs 2}
                                              (om/build db/daily-buttons-widget {:display true})
                                              (om/build ds/date_scanner {:component-id :selected-daily-date :display true})
                                              (om/build summary_work/summary-work-widget {:monitor :selected-daily-date})
                                              )
                                       (g/col {:xs 10}
                                              (table {:striped? true :bordered? true :condensed? true :hover? true}
                                                     (d/thead
                                                      (d/tr
                                                       (d/th {:width "5%"} "Technician")
                                                       (d/th {:width "10%"} "Customer")
                                                       (d/th {:width "10%"} "Vehicle")
                                                       (d/th {:width "10%"} "Status")
                                                       (d/th {:width "10%"} "Checked In")
                                                       (d/th {:width "5%"} "Hours")
                                                       (d/th {:width "50%"} "Notes")
                                                       ))
                                                     (format-tbody daily-view current-date owner))
                                              )
                                       )


text:
Q: Problem in selecting hypothesis

This question form edexcel S2 past paper with answer copied from the marking scheme. Here why we put alternative hypothesis as $p>0.5$ without using $p<0.5$ because in question it mention as "no better than". Please help.


text:
Q: When to use an AppCompatView vs a normal Android view What is the difference between using them, and when should they be used?
An example of the documentation for an AppCompatView is:

A tint aware EditText. This will automatically be used when you use
  EditText in your layouts. You should only need to manually use this
  class when writing custom views

Why should the AppCompatView only be used for custom views?
There is a similar question, but I am looking for a good explanation for why the AppCompatView should only be used for custom views.

A: In your layouts, you should be using the "normal" views, since the support library injects the compatibility code automatically.
The classes provided by the support library are only needed when writing a new custom view. In this case you have to extend the AppCompat views in order to get the new properties (such as tint).

A: Some material design features like the material theme and custom activity transitions are only available on Android 5.0 (API level 21) and above. However, you can design your apps to make use of these features when running on devices that support material design and still be compatible with devices running previous releases of Android.
Que-> Why the AppCompatView should only be used for custom views.
Answer -> In simple terms AppCompatView  is used for maintaining compatibility. If your app uses the Material theme as with Theme.Material but does not provide an alternative theme, your app will not run on versions of Android earlier than 5.0.
If the layouts that you design according to the material design guidelines do not use any of the new XML attributes introduced in Android 5.0 (API level 21), they will work on previous versions of Android. Otherwise, you can provide alternative layouts. You can also provide alternative layouts to customize how your app looks on earlier versions of Android.
Making backwards compatible material design Android applications is much easier with AppCompat, especially when you understand how its styles and themes are working together to dynamically tint the user interface.
With AppCompat, you should spend less time fiddling with assets and backwards compatibility, and more time focusing on actually building your application.
Currently, new projects created through Android Studio incorporate this library by default.
Note: This library depends on the v4 Support Library.
Below are few links for references

*

*Android Material Themes Made Easy With AppCompat

*Migrating to the AppCompat Library

*Getting Material Design for Pre-Lollipop Devices with AppCompat v21


text:
Q: How many 1s in the base 10 list of numbers from 1 to trillion? Also how many doublets of 1s? For example the number 311 has 1 doublets of 1s, and 2111 has two doublets of 1s. Also, if you instead concatenated the consecutive numbers from 1 to a trillion, how many doublets of 1s in that case?(I mean for example, if you concatenate the consecutive numbers 1,151 and 1,152 you have an extra doublet from the last 1 in 1,151 and the first 1 in 1,152. )

A: In listing all the numbers from $0$ to $10^{12}-1$ every tenth number will have a $1$ in the first place.  That is $10^{11}$ times.  That's $10^11$.  For all of the other places, each digit will appear in the $k$th place exactly $1/10$ of the time.  SO that will be a $1$ appears in the $k$th place $10^{11}$.  Add those up it is $12*10^{11}$ ones.  Going from $1$ to $10^{12}$ removes the number $0$ and adds the number $1,000,000,000,000$.  So that is $1$ more $1$.
So there are $12*10^{11}+1$ ones.


text:
Q: Как нарисовать данную UIView с помощью UIBezierPath? Цель:
Нарисовать данный круг, цветовая часть можно быть полностью заполненной, а может наполовину и т.д
Текст внутри не нужен.

Что сделано мною:
Весь день сидел и сделал через поиск угла, поворота данного угла, передвинул все 5 найденых дуг в нужном виде.
Но понял, скорее всего можно сделать, чтобы был один круг с 5 частями, к сожалению, так и не понял как это сделать.

A: Вот пример реализации подобных секторов, размеры секторов рассчитываются на основе ширины вью
class ArcsView: UIView {

    struct Arc {
        var color: UIColor
        var angle: CGFloat
    }

    override func draw(_ rect: CGRect) {

        let arcsCount = 5
        let arcsWidth: CGFloat = 40.0
        let spaceWidth: CGFloat = 10.0

        let innerArcRadius = rect.width / 2.0 - arcsWidth
        let outerArcRadius = rect.width / 2.0

        // определяем расстояния (углы) между секторами по формуле треугольника, зная длины всех сторон

        let innerSpaceAngle = acos((pow(innerArcRadius, 2) + pow(innerArcRadius, 2) - pow(spaceWidth, 2)) / (2 * innerArcRadius * innerArcRadius))
        let outerSpaceAngle = acos((pow(outerArcRadius, 2) + pow(outerArcRadius, 2) - pow(spaceWidth, 2)) / (2 * outerArcRadius * outerArcRadius))
        let arcsAngle = CGFloat.pi * 2 / CGFloat(arcsCount)

        // заполняем массив для примера

        let arcs = [
            Arc(color: .red, angle: arcsAngle),
            Arc(color: .orange, angle: arcsAngle),
            Arc(color: .yellow, angle: arcsAngle),
            Arc(color: .green, angle: arcsAngle),
            Arc(color: .blue, angle: arcsAngle)
        ]

        // поворачиваем сектора для симметрии

        var angle: CGFloat = -arcsAngle / 4

        arcs.forEach {

            // добавляем дуги, которые сами соединяются линией и затем замыкаем контур

            let path = UIBezierPath()
            path.lineWidth = 2

            path.addArc(withCenter: CGPoint(x: rect.midX, y: rect.midY),
                        radius: innerArcRadius,
                        startAngle: angle + innerSpaceAngle / 2,
                        endAngle: angle + $0.angle - innerSpaceAngle / 2,
                        clockwise: true)

            path.addArc(withCenter: CGPoint(x: rect.midX, y: rect.midY),
                        radius: outerArcRadius,
                        startAngle: angle + $0.angle - outerSpaceAngle / 2,
                        endAngle: angle + outerSpaceAngle / 2,
                        clockwise: false)

            path.close()

            $0.color.setFill()
            path.fill()

            angle += $0.angle
        }

    }

}


text:
Q: Conditionally set anonymize_ip in Gatsby I am trying to implement tracking acceptance on a Gatsby site using gatsby-plugin-google-gtag and a custom cookie prompt component.
Currnetly the tracking code is setup and working and the cookie prompt component is conditionally rendering depending if the user has previously made their choice regarding tracking. Where things are failing is trying to conditionally set anonymize_ip based on the users choice. I have tried to set true/false based on a ternary statement in gatsby-config.js, but this seems to error login issues in terminal relating to GraphQL (not linked).
anonymize_ip: document.cookie.match(/^(.*;)?\s*ga-disabled\s*=\s*[^;]+(.*)?$/) ? true : false, // If cookie exists, set value to true
Does anyone know the best way to achieve this?
Thanks
Cookie Prompt
import React from "react";
import { setCookie } from "../../assets/js/utils/cookies";

const CookiesPrompt = () =>  {

    const gaOptout = () => {
        setCookie('ga-disabled', true, 30);
    }

    const gaAccept = () => {
        setCookie('ga-hide-prompt', true, 30);
    }

    return (

This website uses cookies

                <button onClick={() => gaOptout()} className="cookies-prompt__link button--non">I wish to opt-out</button>

            <button onClick={() => gaAccept()} className="cookies-prompt__button button button--primary">Accept</button>

    );
};

export default CookiesPrompt;

Gatsby-config.js
plugins: [
    "gatsby-plugin-sass", "gatsby-plugin-react-helmet", "gatsby-transformer-json", "gatsby-plugin-image", "gatsby-plugin-sharp", "gatsby-transformer-sharp",
    {
        resolve: `gatsby-plugin-google-gtag`,
        options: {
        // You can add multiple tracking ids and a pageview event will be fired for all of them.
        trackingIds: [
            'G-xxxxxxx', // Google Analytics / GA
        ],
        // This object gets passed directly to the gtag config command
        // This config will be shared across all trackingIds
        gtagConfig: {
            // optimize_id: 'OPT_CONTAINER_ID',
            anonymize_ip: document.cookie.match(/^(.*;)?\s*ga-disabled\s*=\s*[^;]+(.*)?$/) ? true : false, // If cookie exists, set value to true
            cookie_expires: 0,
        },
        // This object is used for configuration specific to this plugin
        pluginConfig: {
            // Puts tracking script in the head instead of the body
            head: false,
            // Setting this parameter is also optional
            respectDNT: true,
            // Avoids sending pageview hits from custom paths
            exclude: ['/preview/**', '/do-not-track/me/too/'],
        },
        },
    },
    {
        resolve: 'gatsby-source-filesystem',
        options: {
            name: 'data',  // Identifier. Will then be queried as `dataJson`
            path: './src/assets/data',   // Source folder containing the JSON files
        },
    },
    {
        resolve: 'gatsby-source-filesystem',
        options: {
            name: 'projectImages',  // Identifier. Will then be queried as `projectImagesJson' ?
            path: './public/static/projects',   // Source folder containing the JSON files
        },
    },
 ]

A: gatsby-config.js configurations are set on build-time, not on runtime, so there's no way that you can listen document in that environment/file on-demand.
However, you can use the anonymize IP based on user choice (onClick) by triggering the gaOptout() function:

Deactivate Google Tracking

Where gaOptout:
function gaOptout() {
  ;(document.cookie =
    disableStr + "=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/"),
    (window[disableStr] = !0)
}

var gaProperty = "UA-XXXXXXXX-X",
  disableStr = "ga-disable-" + gaProperty
document.cookie.indexOf(disableStr + "=true") > -1 && (window[disableStr] = !0)


text:
Q: the meaning of 'with profit' here
Lawson had the pedagogic instinct; whenever he found anything out he
  was eager to impart it; and because he taught with delight he talked
  with profit. Philip, without thinking anything about it, had got into
  the habit of sitting by his side.
Of Human Bondage by W. Somerset Maugham

Does the 'profit' here mean 'advantage'? If so, whose advantage does this sentence mean? talker or listener?

A: Maugham is echoing a very famous line from the Art of Poetry by the Roman poet Horace, which every educated reader of Maugham's generation would recognize. Here's Ben Jonson's translation (1640):

Poets would either profit or delight,
  Or mixing sweet and fit, teach life the right.

In applying the tag to a teacher, Maugham cleverly twists its sense: because Larson delights in teaching, his teaching is profitable to those whom he teaches.


text:
Q: graphicsmagick is doubling the size of "some" PNG files Using GraphicsMagick to read in a PNG file and write it out under a different name is causing the file size to increase by more than double. This only happens to some PNG files and I can't figure out what is causing it.
Example problem PNG: http://www.google.co.in/logos/2011/verne-hp-3.png
I have tried everything from disabling the opacity channel to using different compression types to changing the interlacing type but nothing is helping me understand what is causing this problem.
If anyone has any suggestions on what might be causing this, your help would be very welcome.
Thank you.

A: The file is an indexed-color PNG with alpha stored in a tRNS chunk. When I rewrite this file to disk GM uses RGBA PNG, which causes the image size to increase.


text:
Q: Folder structure of your work Users,
I am using LaTeX for homework at university. By now, I had always other programs generating some files, that I used in my LaTeX-document. For example MATLAB generated some graphs, Inkscape generated some pictures and so on.
I always used a folder structure like this:
/experiment01/matlab/
/experiment02/matlab/
/experiment02/inkscape/
...

/beamer-presentation01/
/beamer-presentation02/
...

/fulltext01/
/fulltext02/
...

With this, I am on the one hand able to use figures again in different versions of presentations and the thesis text. On the other hand, my latex references break, if I rename folders. Also the old presentations do not have a fixed state, because the sketches done by Inkscape might change (if not versioned).
What do you recommend? Do you keep your proper work separated from the LaTeX-files? Do you refer to the same figure again in different documents or do you copy it?

A: This is highly dependent on your work flow. For example, I do all of my plotting in pgfplots so data is central to me rather than plot images. A typical paper that I'm writing will have

*

*A master folder with the .tex file. Inside the master folder are:

*

*A folder for images, figures and externalized (it using TikZ/pgfplots) figures.

*A folder for data. Keep this away from your programs!

*A folder for scripts and programs. Don't write directly to the data folder!
However, each paper is a very simple document. For something much larger like my thesis I had an elaborate directory structure, with each chapter in its own folder. The master .tex file sat in a special folder called build rather than at the top of the structure. Each chapter was otherwise treated like a paper in the simple structure above, and there were a couple of other special folders to contain the preamble and macros etc.
For (very) simple documents it may not be worth having any structure at all, opting for a pool of files in a single folder.
Putting aside my paranoia about having data to be published in the same directory as scripts and programs that can overwrite it, modern operating systems offer simple ways to view the contents of a directory by type in the UI. In a *nix terminal this is trivial too with something like
ls *.dat

to view just data files. One could therefore make a case for no special directory structure at all for all but the largest documents.
A final note; for large documents, consider using version control. I suggest Git, but that's a matter of taste. It's saved my skin more times than I care to mention.


text:
Q: IndexError: index 720 is out of bounds for axis 0 with size 720 With the following code, I am trying to make cross-validation, splitting into k = 5 folds, and then picking one of those for validation, and the remaining for training.
# size of the different sets:
# features (800,2)
# labels (800,)

lambdaValues = [0.001, 0.01, 0.1, 1, 10, 100]
nFolds = 5
foldSize = int(len(features)/nFolds)

for i in range(len(lambdaValues)):
    for ii in range(0, len(features), foldSize):
        pick_training = np.array(features)
        pick_validation = np.zeros((foldSize, 2))
        training_labels = labels
        validation_labels = np.zeros((foldSize, 2))
        k = ii
        # perform k-fold split (here a five-fold split)
        for n in range(foldSize):
            pick_validation[n] = pick_training[k]
            validation_labels[n] = training_labels[k]
            pick_training = np.delete(pick_training, k, axis=0)
            training_labels = np.delete(training_labels, k, axis=0)
            k+=1
        # do something (cross-validate)
        # do something (cross-validate)
        # do something (cross-validate)

        print(pick_training.shape) # expected size (160, 2)
        print(pick_validation.shape) # expected size (640, 2)

However, right now when I run it (still missing some actual computations) I get the following error:

I cant quiet understand why this happens, as the values of n, k are correct, and the size of pick_validation is (160,2) and pick_training is (640,2).
Can anyone hint to me why it would say that index 720 is out of bounds? (given the sizes of the arrays above where neither is of size 720).


text:
Q: Data-driven SSRS security Say we have a Project Status Report in SQL Server Reporting Services (SSRS 2012) that takes the Project ID as the parameter, how can we secure the report so that only team members of that project can see the result?
We have the team members for every project in a separate table.
Thanks.

A: You can pass the userID as a parameter to your SQL query using query parameters and assigning user id by using command User!UserID. Then inside your SQL query you can check the privileges by using your team member table and return data accordingly


text:
Q: Why charged particle interaction cross section increases as the particle's energy decreases? I'm tying to gain a little more understanding of the dose deposition profile of high energy (~100MV) protons in matter (depth dose curve - medical physics).
I understand that the Bragg peak occurs because the proton deposits most of its energy just before stopping.
I'm wondering why particle interaction cross section is related to the protons kinetic energy. An answer in lay terms would be appreciated.

A: So apparently this behavior as described by Bethe-Bloch is due to electron pickup. Which I'm guessing quite literally means the propagation of electrons along the path of the particle by coulomb interaction.
As the particle slows, interaction with electrons is more common because of this build up of electrons


text:
Q: rollup "unresolved dependencies" and "missing global variable name" errors, but no specific dependencies referenced I'm trying to integrate React into an existing app that used Rollup, and trying to upgrade to the latest Babel and Rollup versions in the process. When I yarn build, the error/warning output about unresolved dependencies and missing global variable names doesn't provide any more information about which dependencies are part of the problem:
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
[object Object] (imported by commonjs-proxy:[object Object])
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
[object Object] (guessing '_object_Object_')
created public/app.js in 12.1s
✨  Done in 13.52s.

So, in the generated app.js, it's starting and ending with
(function (_object_Object_) {
    'use strict';

    var _object_Object___default = 'default' in _object_Object_ ? _object_Object_['default'] : _object_Object_;
    // etc etc etc
}(_object_Object_));

This is my rollup.config.js:
/**
 * Imports
 */
import resolve from '@rollup/plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify-es';
import json from 'rollup-plugin-json'
import eslint from 'rollup-plugin-eslint';
import filesize from 'rollup-plugin-filesize';
import progress from 'rollup-plugin-progress'
import visualizer from 'rollup-plugin-visualizer';

/**
 * Constants
 */
const production = !process.env.ROLLUP_WATCH;

/**
 * Configuration
 */
export default {
  input: 'client/src/main.jsx',
  output: {
    file: 'public/app.js',
    format: 'iife'
  },
  plugins: [
    progress(),
    eslint(),
    resolve({
      mainFields: ['main', 'module', 'browser'],
      extensions: ['.js', '.jsx', '.json'],
    }), // resolve dependencies from node_modules
    json(),
    commonjs({
      include: ['node_modules/**'],
      exclude: ['node_modules/process-es6/**'],
      namedExports: {
        'node_modules/react/index.js': [
          'Children',
          'Component',
          'PropTypes',
          'createElement',
        ],
        'node_modules/react-dom/index.js': ['render'],
      },
    }), // convert CommonJS modules to ES modules
    babel({
      exclude: ['node_modules/**'],
      presets: ['@babel/preset-env', '@babel/preset-react']
    }), // convert with Babel
    production && uglify(), // minify if not development
    !production && visualizer(),
    filesize(),
  ],
};

And these are my devDependencies from the package.json:
    "@babel/cli": "^7.7.5",
    "@babel/core": "^7.7.5",
    "@babel/plugin-external-helpers": "^7.7.4",
    "@babel/preset-env": "^7.7.6",
    "@babel/preset-react": "^7.7.4",
    "@rollup/plugin-node-resolve": "^6.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2015-rollup": "^3.0.0",
    "codacy-coverage": "^3.4.0",
    "eslint": "^6.0.1",
    "eslint-config-airbnb-base": "^13.1.0",
    "eslint-plugin-import": "^2.18.0",
    "eslint-plugin-react": "^7.17.0",
    "event-emitter": "^0.3.5",
    "mocha": "^6.1.4",
    "mocha-junit-reporter": "1.22.0",
    "mocha-multi-reporters": "^1.1.6",
    "nyc": "^14.1.1",
    "rollup": "^1.27.12",
    "rollup-plugin-babel": "^4.3.3",
    "rollup-plugin-commonjs": "^8.2.6",
    "rollup-plugin-eslint": "^4.0.0",
    "rollup-plugin-filesize": "5.0.1",
    "rollup-plugin-json": "^4.0.0",
    "rollup-plugin-progress": "^1.1.1",
    "rollup-plugin-uglify-es": "^0.0.1",
    "rollup-plugin-visualizer": "^3.3.0"

I've currently got my entry point (client/src/main.jsx) and app component stripped down to the bare minimum:
import React from 'react'; // eslint-disable-line no-unused-vars
import ReactDOM from 'react-dom';
import App from './App.jsx';

const reactContainer = document.querySelector('#reactRoot');
ReactDOM.render(<App />, reactContainer);

import React from 'react';

class App extends React.Component {
  render() { // eslint-disable-line class-methods-use-this
    return
Here goes.
;
  }
}

export default App;

What am I missing here? I've followed that link in the output (https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency) and followed directions pretty meticulously, and also inspected various other Rollup+React repos, but none that I've found use the latest versions of Babel or Rollup.


text:
Q: Problem in printing Jpanel Data I am working on a swings application I have a Jpanel, I am facing serious problem with printing this JPanel data with "card printer". This is working fine when i using paper color printer but when i am using card printer its printing nothing. I have tested the printer using some Images and it is printing fine when i print any Image directly but using my application having problem the card printer not receiving any data while the paper printer is printing fine. Any one faced this before or anyone please help me out. This is my code:
 private void printCard(){

    PrinterJob printjob = PrinterJob.getPrinterJob();
    printjob.setJobName(" CUSTOMER CARD ");

    printjob.setPrintable (new Printable() {
         public int print(Graphics pg, PageFormat pf, int pageNum){

             pf.setOrientation(PageFormat.LANDSCAPE);

             if (pageNum > 0){
                return Printable.NO_SUCH_PAGE;
             }

             Graphics2D g2 = (Graphics2D) pg;
             g2.translate(pf.getImageableX(), pf.getImageableY());
             g2.translate( 0f, 0f );
             jLayeredPane2.paint(g2);

             return Printable.PAGE_EXISTS;
         }
    });

    if (printjob.printDialog() == false)
       return;

    try {
       printjob.print();
    }
    catch (PrinterException ex) {
       System.out.println("NO PAGE FOUND."+ex);
    }
 }

A: I've run across issues with some printers not liking how Java printing works, and it seems greatly to do with how the printers support vector-based printing. Try raster printing instead. Render your JLayeredPane into a BufferedImage at 300dpi and printing the BufferedImage.


text:
Q: What are the __NR_-prefixed symbols in glibc? I'm trying to compile Box86 on Alpine Linux, a Linux distribution which uses the musl libc implementation rather than glibc. At 46% completion, the compilation halts with the following errors:
/home/newbyte/box86/src/emu/x86syscall.c:124:11: error: '__NR_gettimeofday' undeclared here (not in a function); did you mean 'gettimeofday'?
  124 |     { 78, __NR_gettimeofday, 2 },
      |           ^~~~~~~~~~~~~~~~~
      |           gettimeofday
/home/newbyte/box86/src/emu/x86syscall.c:210:12: error: '__NR_clock_gettime' undeclared here (not in a function); did you mean 'clock_gettime'?
  210 |     { 265, __NR_clock_gettime, 2 },
      |            ^~~~~~~~~~~~~~~~~~
      |            clock_gettime
/home/newbyte/box86/src/emu/x86syscall.c:211:12: error: '__NR_clock_getres' undeclared here (not in a function); did you mean 'clock_getres'?
  211 |     { 266, __NR_clock_getres, 2 },
      |            ^~~~~~~~~~~~~~~~~
      |            clock_getres

Naturally, my first instinct was to look these names up and figure out what they are for so that I can find a suitable replacement, but I had little luck doing so, which leads me to my question: What are these __NR_-prefixed symbols, and what do they do?

A: You seem to be compiling using musl 1.2.0 or later, which has a 64-bit time_t even on 32-bit targets. This means that the 32-bit system calls (gettimeofday, clock_gettime, clock_getres) are not compatible with musl's definition of struct timeval and struct timespec. To protect from accidentally calling those system calls with the wrong types, the corresponding system call constants are not available in this environment.

A: Identifiers starting with __NR_ are non-portable, Linux-kernel-specific names for the constants defining system call numbers.  The portable names that user space programs should use, start with SYS_ instead.
GNU libc allows the non-portable names to pass through from the kernel's headers into <sys/syscall.h>; it sounds like musl libc doesn't.  Try search-and-replace changing __NR_ to SYS_ throughout this file.


text:
Q: Access a JSON string value I have this example where I am trying to access json value, but it does not even produces any alert. What is the problem?
My JSON
{
 "response": [
{
  "id": "0",
  "elementName": "osname",
  "isEqual": true,
  "isPrasentinXml1": true,
  "isPrasentinXml2": true,
  "attribute": [
    {
      "name": "osname",
      "firstValue": "Linux\u000a",
      "secondValue": "SunOs\u000a"
    }
  ]
},
{
  "id": "1",
  "elementName": "hostname",
  "isEqual": false,
  "isPrasentinXml1": true,
  "isPrasentinXml2": true,
  "attribute": [
    {
      "name": "hostname",
      "firstValue": "estilo\u000a",
      "secondValue": "buckeye.informatica.com\u000a"
    }
  ]
}
]
}

I want to fetch Linux\u000a and SunOs\u000a, so i wrote
alert(compareData.response[0].attribute[0].firstValue+", "+compareData.response[0].attribute[0].secondValue);

Note: compareData Is where my data is in actual code

A: Your error was that you have quotes around your JSON and it was treated as a string. Also you forgot to replace compareData variable name with jsonobj in the second alert. Try the fiddle below, it seems it is what you want.
jsFiddle: http://jsfiddle.net/Dna9H/6/
EDIT:
If your JSON is really represented by the string take a look at Michael Sagalovich solution.

A: Try this
http://jsfiddle.net/Dna9H/8/

A: As far as I see it in the fiddle, your object is the string. You need to parse it into an object first. compareData = JSON.parse(compareData) could help (JSON.parse is supported by the majority of browsers, I think). jQuery also has parser: $.parseJSON(compareData).

A: Your syntax. This works:
var jsonobj = {
    "response": [
        {
        "id": "0",
        "elementName": "osname",
        "isEqual": true,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "attribute": [{
            "name": "osname",
            "firstValue": "Linux\u000a",
            "secondValue": "Linux\u000a"}]
        },
        {
        "id": "1",
        "elementName": "hostname",
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "attribute": [{
            "name": "hostname",
            "firstValue": "estilo\u000a",
            "secondValue": "buckeye.informatica.com\u000a"}]
        }
    ]
 };

alert(jsonobj.response[0].elementName);
alert(jsonobj.response[0].attribute[0].firstValue + ", " + jsonobj.response[0].attribute[0].secondValue);

Please can I ask if you can install and learn how to use Firebug or Chrome's dev console. These tools can make your life a whole lot easier.


text:
Q: php include results in page being written in pre I'm learning php, been trying to make a cms, but when I use an include for the header this results in the page appearing as if it were written in pre tags. There's no errors when I debug or anything. And I'm completely stumped. When I put the header back in without the include it renders just fine.
<?php include("..\includes\layouts\header.php"); ?>

That's the include I'm using.
I've tried using the full path name, tried it in different browsers and using :
include($_SERVER["DOCUMENT_ROOT"]

A: Check that you are closing your php tags, ending your strings with semi colons etc.. My guess is that your html is being sucked into the php code which freaks out and just dumps it.
Maybe try one of the validators such as http://phpcodechecker.com (I have not used this one so I cannot comment on it's effectiveness)
Edit: I am rereading your post and I think I understand what you are trying to say - your header contains the path to your css and when you put it in a separate php file the css doesn't work?  So the first thing to do is determine if the issue with the php path or the css path inside the header.php file. Look at your source code to see if the header code is being included - if it is then play around with the css path - though including the header in a php file will not cause that css path to change.
I am guessing that your header is not included at all from your mention of paths. include() works from the loading file's location. The path it wants is a server path and not a url. The one that you have above: ../includes... means that you have an include folder at the same level as the loading file such as (assume index.php is the main file):
/includes/layouts/header.php
/somedirectory/index.php

The ../ means - drop down one directory then go up from there.
If your path is more like:
/includes/layouts/header.php
/index.php

Then the include would be:
include('./includes/layouts/header.php');

Let me know if that works - if it doesn't try to explain your directory structure.


text:
Q: How do you fix an incomplete SSL chain I have a Go Daddy SSL cert installed, and works fine everywhere except Android.
https://www.ssllabs.com/ssltest/analyze.html  says the chain is incomplete, and I read on stack overflow that an SSL chain in the wrong order will fail on Android.
But how do I put it in order?  On my Server? SSL cert itself needs to be rekeyed?  Move things on FTP?

A: Following up on zakjan's answer,  I had a problem when I tried to use jquery to do an AJAX request on my newly secure server, in an android webview.  It worked in the browser, but not in my app.
I used this site: https://certificatechain.io/
I pasted in the text of my signed .crt file I got back from Comodo (positiveSSL), and it gave me back a concatination of everything I needed.  I saved it as my domain + "chain.crt" (see below)
Then, in my apache configs, I entered something like this for that particular virtual host:
SSLEngine On
SSLCertificateFile /etc/ssl/localcerts/example_com.crt
SSLCertificateKeyFile /etc/ssl/localcerts/example.com.key
SSLCACertificateFile /etc/ssl/localcerts/example.com.chain.crt

After that, my Android app's webview did not have a problem using ajax to POST to my server.  I tried it on 2 real-world devices, one running 2.3.4, one running 4.something.  And on the emulator running 2.3.  All worked.
I hope this helps.

A: The chain was in crt file, that the original SSL was working off.
For GoDaddy there is a 2nd cert - gd_bundle.crt
Copy this info and add it to the crt installed on the server.
So the original crt on the server had 1 certificate, and after it will have 3 on the same file.  This is the chain.
I still got contains anchor in chain issues on ssllabs.com but this is not an issue, just an option to leave in or out - according to - https://security.stackexchange.com/questions/24561/ssltest-chain-issues-contains-anchor/24566#24566

A: You can solve the incomplete certificate chain issue manually by concatenating all certificates from the certificate to the trusted root certificate (exclusive, in this order), to prevent such issues. Note, the trusted root certificate should not be there, as it is already included in the system's root certificate store.
You should be able to fetch intermediate certificates from the issuer and concat them together by yourself. Btw, I have written a script to automate the procedure, it takes a certificate to produce output of correctly chained certificates. https://github.com/zakjan/cert-chain-resolver


text:
Q: Scrolling to a element in bootstrap modal in web driver is not working I am trying to close a bootstrap modal through Web driver script.The modal has Close button at the bottom.I am trying to scroll to the element and then click on the element but it is not working.when used moveToELement(toElement) method the script is throwing

MoveTargetOutOfBoundsException: Offset within element cannot be
  scrolled into view:" exception

. So I have tried to javascript scroll method and another way.They didn't throw any exception but it also didn't work. Below is the code
        WebDriver d=new FirefoxDriver();
        d.get("http://getbootstrap.com/javascript/");
        d.findElement(By.linkText("Modal")).click();
        d.findElement(By.cssSelector("button[data-target='#myModal']")).click();
        WebElement e=d.findElement(By.className("btn-default"));
//using moveToElement
        Actions a=new Actions(d);
        a.moveToElement(e).click().build().perform();
//using js scroll
        JavascriptExecutor js=(JavascriptExecutor)d;
        Point p=e.getLocation();
        int y=p.getY();
        int x=p.getX();
        js.executeScript("scroll("+x+","+y+")");
        e,click();
//another way
        Coordinates coordinate = ((Locatable)e).getCoordinates();
        coordinate.onPage();
        coordinate.inViewPort();
        e.click();

Any suggestions regarding how to solve this.Thanks in advance

A: The following are the reasons why your code is not working:

*

*You haven't added the code for timeout (Implicit/Explicit), and that may sometimes result in an exception related to element not found.

*Lastly, the class-name by which you are trying to locate the 'Close' button, i.e., in fact returning 13 different elements (when checked using Firepath).

Below code sorts out all the above-mentioned problems and works too:
    WebDriver d=new FirefoxDriver();
    d.manage().window().maximize();//Maximizing window
    d.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);//Giving implicit timeout of 20 seconds

    //Navigating to the site
    d.get("http://getbootstrap.com/javascript/");

    //Clicking on the "Modal" Link text
    d.findElement(By.linkText("Modal")).click();

    //Clicking on the "Launch Demo modal" button
    d.findElement(By.cssSelector("button[data-target='#myModal']")).click();

    //Clicking on the Close button of opened Modal window
    d.findElement(By.xpath("//div[@id='myModal']//button[.='Close']")).click();

A: The reason its not working is cause your element Close is under a modal dialog. So your className wont work cause there are multiple elements using that class both in modal dialog and html. Try using xpath as:
.//*[@id='myModal']//button[text()='Close']

If you want to perform scroll also, you can achieve it by following code:
((JavascriptExecutor) d).executeScript("window.scrollBy(" + x + ","
            + y + ")", "");

Where x and y are co-ordinates of the element found through given xpath. Using the given xpath u need to only find that element and perform element.click().


text:
Q: How to send custom http 400 error message with mvc controller? Quite strange and not sure why.
I have an old mvc site and wants to add some custom error message. For example, when http status code is 400, I want to output
{
    "error": {
        "code": "",
        "message": "xxx is wrong with ..."
    }
}

So I used the solution here,
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, @"{
                ""error"": {
                    ""code"": "",
                    ""message"": ""xxx is wrong with ...""
                }
            }");

but there are two problems:

*

*It can't handle json message as above example shows a 502 bad gateway error.

*For a basic string, it works but my text is in description, and the body is still "bad request".

I tried lots of other ways (e.g. send out HttpResponseMessage), but none worked. With HttpResponseMessage,
return new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                ReasonPhrase = HttpStatusCode.BadRequest.ToString(),
                Content = new StringContent("hello")
            };

I actually got status 200 and body is:
StatusCode: 400, ReasonPhrase: 'BadRequest', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: text/plain; charset=utf-8
}

So I want to output a BadRequest status message with some Json body, how can I do that?

A: After two days, I finally worked it out.
The solution from previous stackoverflow question actually works on my local machine, but doesn't output anything when I deployed to a server.
On my local machine, VS will run code in IIS express, and on the server it is IIS. So in the web.config, I actually need these lines:
<system.webserver>
    <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough"></httpErrors>
</system.webserver>


text:
Q: How to select the  by CSS? First I was using <h:dataTable> and I was OK with this but after then I needed some more functionality, So I started using Primefaces and used its
. Everything is going fine but the CSS that I applied on tables stopped woking. Then I found that
 is first creating a
 and then inside the
, it is creating a
.

....

But <h:dataTable> creates just HTML
. Now I want to know how can I get table's id or is there any solution that I can access that table. I also want to know that Why <h:dataTable> and
 differs from each other.

A: If you want to style tables in a generic manner, just change the CSS selectors accordingly.  The
 of
 is selectable by the ui-datatable class.
.ui-datatable td {
    background: pink;
}

If you want to style only a specific table in a specific manner, rather give it a classname so that you can select by the classname instead of by ID.
E.g.

is overrideable by .ui-datatable.foo {}. E.g.
.ui-datatable.foo td {
    background: hotpink;
}