text:
Q: How do I create an ebs volume in terraform if it could not find a snapshot to restore from So I was reading the documentation on here: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ebs_volume
It says that we can either use the SnapshotId= or size= such that snapshot id will create the volume from a snapshot given the id, and size= will create a brand new one.
I have this data source to access my snapshots:
data "aws_ebs_snapshot" "p4_ebs_snapshot" {
  most_recent = true
  owners = ["self"]

  filter {
    name = "tag:Name"
    values = ["PerforceDepots"]
  }
}

I want to know if it's possible to do something like this:
if data.foundSnapshot?
    snapshotId=data.id;
else
    size=100
end

The above is obviously just pseudocode but I was wondering how I could do something like this in terraform. Is it possible?

A: Sadly, its not possible without external data source. TF does not have a notion of checking if something exists. If any data source does not exist, it errors out. The only way around that is to develop your own data source, which would provide such a functionality.


text:
Q: concatenating a uint8_t array into uint32_t array in C This might have been asked before. But I'll ask anyway. If someone could direct me to something relevant, that would also be great.
So, if I have:
uint8_t src[] = {34, 56, 31, 89, 11, 32, 67, 89};

Is this possible to get something like this through concatenation:
uint32_t dst[] = {34563189, 11326789};

If yes, how? I saw a question for casting uint8_t array into a uint32_t but I need to put the 4-bytes chunk side by side into a uint32_t array. Thanks!

A: If you really are working with decimal values:
uint32_t dst[] = {1000000 * src[0] +10000 * src[1] + 100 * src[2] + src[3],
                  1000000 * src[4] +10000 * src[5] + 100 * src[6] + src[7]};

A: In my opinion,

*

*use snprintf() to print individual uint8_ts to a char array.

*use strtol() to convert the array to integer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS CLI: How to set VPC of New Replication Instance aws dms create-replication-instance does not get VPC as an option. When I create a new instance it does not create it in the VPC I intend to create the replication instance in.
How can I achieve that?

A: You need to create a subnet group first and then use that when you build your instance.
The create-replication-subnet-group derives the VPC ID from the subnets you use for input.  The documentation is vague but VpcId is output from the command.
The docs for that command state:

Creates a replication subnet group given a list of the subnet IDs in a VPC.

Then use the replication-subnet-group-identifier as input for the create-replication-instance command.
References
https://docs.aws.amazon.com/cli/latest/reference/dms/


text:
Q: java.lang.SecurityException: No active admin owned by uid 10034 for policy #3 I create a lock screen widget app recently. It always has the exception:
( java.lang.SecurityException: No active admin owned by uid 10034 for policy #3)

I try many methods and can not eliminate the exception. I open the activity to realize the purpose of the lock screen when the condition was founded.
public class tempActivity extends Activity {
    private static final String TAG = "tempActivity";
    private DevicePolicyManager policyManager;
    private ComponentName componentName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.temp);
        Log.e(TAG, "Activity created~");
        policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        componentName = new ComponentName(this, AdminReceiver.class);
        mylock();
    }

    private void mylock() {
        boolean active = policyManager.isAdminActive(componentName);
        if (!active) { // Without permission
            Log.e(TAG, "No authority~");
            activeManage(); // To get access
            policyManager.lockNow(); // And lock screen
        } else {
            Log.e(TAG, "Has authority");
            policyManager.lockNow(); // lock screen directly
        }
        this.finish();
    }

    private void activeManage() {
        Log.e(TAG, "activeManage");
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "developers:liushuaikobe");
        startActivityForResult(intent, 1);
    }
}

A: The point is when the device admin is not active, your call to prompt it (ACTION_ADD_DEVICE_ADMIN) only ensures that the user is shown the activation intent. If he or she chooses not to activate (and which is quite likely) the lock command in the next line will fail and give the error you are encountering now.
So, basically you can only prompt the users to activate the device admin, not force them.
Delete the lockNow call in the if not active block to avoid the error.
Hope this helps.
-SB

A: Try:
if(Build.VERSION.SDK_INT > 8){
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }


text:
Q: Unable to run mavenized GWT application in eclipse with embedded Tomcat I have a proof of concept GWT 2.4 / Spring 3.1 / Maven 3 / Eclipse Indigo project that I have been working on. I am able to run the application in Dev Mode using the embedded Jetty server. I am able to create a war (mvn package with help of the gwt-maven-plugin)  and run the application on an installed Tomcat server. But when I try to Run as > Run on Server, it does not use/copy the generated/compiled JavaScript. When I go to the wtpwebapps dir, all is there but the generated/compiled JavaScript. The generated/compiled JavaScript is in the correct location in the maven target dir, it seems, but the eclipse process that copies the code the applcation to the wtpwebapps dir doesn't pick it up.
I'm not sure if I need to give more info to solve this problem, but any help is appreciated.

A: You could use a custom com.google.gwt.core.ext.ServletContainerLauncher using the embedded Tomcat API, or much more simply run your server code in Tomcat (using WTP or the tomcat7-maven-plugin) and then run DevMode in -noserver mode.
See https://developers.google.com/eclipse/docs/faq#gwt_with_maven and https://developers.google.com/web-toolkit/doc/latest/DevGuideCompilingAndDebugging#How_do_I_use_my_own_server_in_development_mode_instead_of_GWT's
I'm using the second approach in https://github.com/tbroyer/gwt-maven-archetypes
The archetype uses Jetty for now, but I'm successfully using the tomcat7-maven-plugin on a project based on the archetype (with too many tricks preventing me to set it as the default in the archetype; those tricks only being needed because of the multi-module nature of the project; but there are tricks for Jetty too).

A: I encountered a similar problem with GWT-dev 2.8.0-beta1 and jetty 9 in my eclipse maven project. Since the GWT-dev jar includes Jetty and other code directly in its jar (which is bad), it conflicts with the jetty I import in my project. The work around was to create a separate module just for running super dev mode, importing GWT-dev and my project's code but excluding the jetty jars. I then run super dev mode via the main below. This way, the super dev mode runs without seeing my jetty libs.
import com.google.gwt.dev.codeserver.CodeServer;

public class SuperDevModeMain {

  public static void main(String[] pArgs) throws Exception {
    System.out.println("Starting management-station-web-sdm!");
    String[] options = "-port 9876 com.something.ms.web.MsWeb".split(" ");
    CodeServer.main(options);
  }
}


text:
Q: Half page printing using dot matrix printer in javascript Now I am working with dot matrix printer using Asp.net client printing.
But i want a half page print. i am using css like  page-break-after:avoid .
But it doesn't stop after print the half page. (working in firefox,not working in IE and chrome)


text:
Q: Using the ZFC axioms, is {1} = 2? I am looking at the power set of two, $P(2)$ = {$\emptyset$,  {$\emptyset$},  {1}, {$\emptyset$, 1} } = {0, 1, {1} ,2}.
I consider {1} = {{0}}.  By the Empty Set Axiom and the Subset Axiom, this set includes the empty set, ie 0 $\in$ {1}. So, I can write {1} = {{0}} as {0, {0}} = {0, 1} = 2. This would mean the power set of two only has three distinct elements.
I am using ZFC Axioms.  Where am I going wrong?
Thanks for the comments.  I realise that my confusion was in how I was thinking about the Subset Axiom - not distinguishing "includes as an element" from "includes as a subset".
The question is maybe kind of ridiculous.  I am not sure if I should delete it or leave it.  I would be happy if a mod wants to delete it.

A: Let $0:=\emptyset$, $1:=\{\emptyset\}$, so that $ \{1\}:=\{\{\emptyset\}\}$.
We do have $0\in1$ as well as $0\subset1$ and $0\subset\{1\}$, but $0\notin\{1\}.$


text:
Q: Range.Find(String) Doesn't Work I have the following Spreadsheet:
[Data in Columns A-Q and almost 3000 Rows][1]
I have a dropdown on another page that has a cell for Name/Mode/Shift Listed on it and am creating a variable for each. For some reason when I change a field in a drop down, I get a '91' Object error. When I use a combination of all of the items in the dropdown that are in the 1st position, the macro works just fine. The issue is always when I change either the DC/Mode/Shift. DC is a string, Mode is a String, and Shift is an Integer.
Each Dim Search / Dim FindRow was it's own passthrough function but combined everything. Any help would be much appreciated!!!
Below is my code:
Sub DailyRouteInput_Button8_Click()
    Dim DC As String

    Worksheets("Daily Route Input").Activate

    Range("U1").Select
    DC = ActiveCell.Value

    ActiveCell.Offset(0, 1).Select
    Mode = ActiveCell.Value

    Range("C5").Select
    Shift = ActiveCell.Value

    Worksheets("Daily Route Master Data").Activate

    (Was new passthrough function)

    Dim SearchRange As Range
    Dim FindRow As Range
    Set SearchRange = Range("A2", Range("A2").End(xlUp))
    Set FindRow = SearchRange.Find(What:=DC, LookIn:=xlValues, lookat:=xlWhole)

    DC = FindRow.Row '---- Here is where the problem is ---------

    Range("A" & DC).Offset(0, 1).Select

    (Was new passthrough function)

    Dim newSearchRange As Range
    Dim newFindRow As Range
    Set newSearchRange = Range("B" & DC, Range("B" & DC).End(xlUp))
    Set newFindRow = newSearchRange.Find(Mode, LookIn:=xlValues, lookat:=xlWhole)

    Mode = newFindRow.Row '---- Here is where the problem is ---------

    Range("B" & Mode).Offset(0, 1).Select

    (Was new passthrough function)

    Dim finalNewSearchRange As Range
    Dim finalNewFindRow As Range
    Set finalNewSearchRange = Range("C" & Mode, Range("C" & Mode).End(xlUp))
    Set finalNewFindRow = finalNewSearchRange.Find(Shift, LookIn:=xlValues, lookat:=xlWhole)

    Shift = finalNewFindRow.Row '---- Here is where the problem is ---------

    Range("C" & Mode).Offset(0, 1).Select

    WeekCheck = ActiveCell.Value
    ActiveCell.Offset(0, 1).Select
    MonthCheck = ActiveCell.Value

A: Thank you everyone that tried to give me some tips. I was able to figure it out. XlUp was the culprit and I changed it to xlDown. It was returning an empty object for that reason because I was testing data in a column that had nothing above it. Then I listened to the rest of you and set object variables and was able to eliminate .copy and did what I originally set out to do which is increase the overall speed of the returned results from 13 seconds to just over 1 second. You can find my code below. I know I didn't call out a few variables as strings or integers but outside of that if you can provide me with any further constructive criticism I would definitely be grateful!

Sub DailyRouteInput_Button8_Click()

Dim nResult As Long
 nResult = MsgBox( _
 Prompt:="Did you save your prior DC/Mode updates to Master?", _
 Buttons:=vbYesNo)
 If nResult = vbNo Then
 Exit Sub
 End If

Dim VL As Workbook
Dim DailyRouteInput As Worksheet
Dim DailyRouteMaster As Worksheet
Dim masterRange As Range
Dim inputRange As Range
Dim DCInput As String
Dim ModeInput As String
Dim SearchRange As Range
Dim FindRow As Range
Dim finalNewSearchRange As Range
Dim finalNewFindRow As Range
Dim newSearchRange As Range
Dim newFindRow As Range

Set VL = ThisWorkbook
Set DailyRouteInput = VL.Sheets("Daily Route Input")
Set DailyRouteMaster = VL.Sheets("Daily Route Master Data")
Set masterRange = DailyRouteMaster.Range("A1:N2545")
Set inputRange = DailyRouteInput.Range("A1:BH57")

DCInput = inputRange.Cells(1, 21)
ModeInput = inputRange.Cells(1, 22)
ShiftInput = inputRange.Cells(5, 3)

DailyRouteMaster.Activate

Set SearchRange = masterRange.Range("A1", Range("A1").End(xlDown))
Set FindRow = SearchRange.Find(DCInput, LookIn:=xlValues, lookat:=xlWhole)
DC = FindRow.Row

Set newSearchRange = Range("B" & DC - 1, Range("B" & DC - 1).End(xlDown))
Set newFindRow = newSearchRange.Find(ModeInput, LookIn:=xlValues, lookat:=xlWhole)
Mode = newFindRow.Row

Set finalNewSearchRange = Range("C" & Mode - 1, Range("C" & Mode - 1).End(xlDown))
Set finalNewFindRow = finalNewSearchRange.Find(ShiftInput, LookIn:=xlValues, lookat:=xlWhole)
Shift = finalNewFindRow.Row

MonthCheck = DailyRouteMaster.Range("E" & DC)

If (MonthCheck = "January") Then

        DailyRouteMaster.Range("F" & Shift, "N" & Shift + 3).Copy
        DailyRouteInput.Activate
        inputRange.Cells(5, 26).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        DailyRouteMaster.Activate
        DailyRouteMaster.Range("F" & Shift + 4, "N" & Shift + 7).Copy
        DailyRouteInput.Activate
        inputRange.Cells(5, 39).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        DailyRouteMaster.Activate
        DailyRouteMaster.Range("F" & Shift + 8, "N" & Shift + 12).Copy
        DailyRouteInput.Activate
        inputRange.Cells(5, 52).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

        DailyRouteMaster.Range("F" & Shift + 13, "N" & Shift + 16).Copy
        DailyRouteInput.Activate
        inputRange.Cells(14, 26).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        DailyRouteMaster.Activate
        DailyRouteMaster.Range("F" & Shift + 17, "N" & Shift + 20).Copy
        DailyRouteInput.Activate
        inputRange.Cells(14, 39).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        DailyRouteMaster.Activate
        DailyRouteMaster.Range("F" & Shift + 21, "N" & Shift + 25).Copy
        DailyRouteInput.Activate
        inputRange.Cells(14, 52).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

        DailyRouteMaster.Range("F" & Shift + 26, "N" & Shift + 29).Copy
        DailyRouteInput.Activate
        inputRange.Cells(23, 26).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        DailyRouteMaster.Activate
        DailyRouteMaster.Range("F" & Shift + 30, "N" & Shift + 33).Copy
        DailyRouteInput.Activate
        inputRange.Cells(23, 39).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        DailyRouteMaster.Activate
        DailyRouteMaster.Range("F" & Shift + 34, "N" & Shift + 38).Copy
        DailyRouteInput.Activate
        inputRange.Cells(23, 52).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

        DailyRouteMaster.Range("F" & Shift + 39, "N" & Shift + 42).Copy
        DailyRouteInput.Activate
        inputRange.Cells(32, 26).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        DailyRouteMaster.Activate
        DailyRouteMaster.Range("F" & Shift + 43, "N" & Shift + 46).Copy
        DailyRouteInput.Activate
        inputRange.Cells(32, 39).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        DailyRouteMaster.Activate
        DailyRouteMaster.Range("F" & Shift + 47, "N" & Shift + 52).Copy
        DailyRouteInput.Activate
        inputRange.Cells(32, 52).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        DailyRouteInput.Activate

    Else
        MsgBox ("Something is Wrong!")
    End If

End Sub


text:
Q: i2c devices listed in root group I created an Ubuntu 18.04 headless image and flashed into eMMC on Nvidia Jetson nano module. After booting up, the i2c devices i2c-0, i2c-1, i2c-101, i2c-2, …, i2c-8 are listed in the folder of /dev/ as root user and root group instead of i2c group. No i2c group is available. I manual added i2c group by
sudo groupadd --system i2c

add user to i2c group and changed the i2c- dev group from root to i2c by
sudo chown root:i2c /dev/i2c-*

I checked. Its group has been changed to i2c
crw------- 1 root i2c 89, 0 Sep 23 07:45 /dev/i2c-0

I also applied the command below to i2c devices
sudo chmod a+rw /dev/i2c-*

After this, I tested the i2c. It works. But after reboot, the i2c-* changed back to root group again.
crw------- 1 root root 89, 0 Sep 23 07:45 /dev/i2c-0

what's wrong with it? How can I fix it before flash the image into device?


text:
Q: What does Intercept and Ref mean in Logistic Regression Model? I am looking at a results chart from a binomial logistic regression model, and I see the following results. I am not sure what "intercept" means here. I thought "coefficient" is referring to the variable in question - so it makes no sense to have no coefficient in the first line ,

Also, is "Downtown" location being used as a reference to check the results between the two locations?

A: "Ref" is shorthand for reference category.  Whenever an independent variable consists of categories, logistic regression procedures (if using this particular sort of contrast -- an indicator contrast) will choose one category by default as the reference to which each other category is compared.  Here, the odds of the outcome being "1" are estimated as being lower (0.57 as high) for North cases as for Downtown cases, all else being equal.
The intercept (also known as the regression constant) tells you nothing about the role of any independent variable, but it does serve a function in a predictive equation that can be derived from output like this.  You can use the constant and the two other coefficients to assign to each observation a predicted probability of the outcome being "1", depending on that case's values for the independent variables.


text:
Q: my live usb has error Grub Rescue my issue is NOT ubuntu 14.04 LTS installed on HDD.
my issue is live usb getting error on boot "no such device: .....
grub Rescue > "
i know people say just format and remake whole live usb again. i don't want to do that again and again it consumes too much of my time, because on LIVE USB i have lot of apps configured to my needs and they work flawlessly.
i know "boot repair app" fixes this issue on HDD but how do i boot repair my live usb?
NOTE:
my linux mint mate 17.1 (ubuntu 14.04 lts) working great on my pc.
i am only having this issue on my linux mint mate 17.1 live USB

A: You need to install/re-install grub on to the Live USB itself.
Assuming the Live USB is /dev/sdc for instance, you may get away with just
 grub-install /dev/sdc

if you are lucky. Otherwise you may need to go the more complex route as shown on
How to Repair, Restore, or Reinstall Grub 2 with a Ubuntu Live CD or USB
except that you can do all that using your functioning HDD system instead of a Live CD.


text:
Q: Non-blocking web service client using AsyncHTTPConduit CXF (JAVA) I am trying to create a non I/O blocking web service client in JAVA. I am using the AsyncHTTPConduit from CXF.
However, when there are 2 request, it seems it will create a new connection instead of reuse it. It will create new dynamic port to send web service.
Source Code:
    public Dispatch getDispatcher(String alias, String namespace, String wsdlLocation, String serviceName, String portName) throws IOException, GeneralSecurityException {
    Dispatch<Source> dispatcher = getDispatcher(wsdlLocation, namespace, serviceName, portName);

    // Create our custom SSLSocketFactory
    SSLSocketFactory socketFactory = new SSLSocketFactoryGenerator(alias, keyStoreLocation, trustStoreLocation)
            .getSSLSocketFactory();

    Client client = ((org.apache.cxf.jaxws.DispatchImpl) dispatcher).getClient();
    client.getRequestContext().put("use.async.http.conduit", true);
    client.getRequestContext().put(AsyncHTTPConduit.USE_ASYNC, AsyncHTTPConduitFactory.UseAsyncPolicy.ALWAYS);
    client.getRequestContext().put("org.apache.cxf.transport.http.async.MAX_CONNECTIONS", 501);
    HTTPConduit conduit = (HTTPConduit) client.getConduit();
    System.out.println("testtest: "+conduit.getClass().getName());
    TLSClientParameters tlsClientParameters = new TLSClientParameters();
    tlsClientParameters.setSSLSocketFactory(socketFactory);
    conduit.setTlsClientParameters(tlsClientParameters);
    conduit.getClient().setConnection(ConnectionType.KEEP_ALIVE);
    conduit.getClient().setReceiveTimeout(10000000L);

    return dispatcher;
}

Call dispatcher to send web service:
Source requestSource = (new StreamSource(new StringReader(request)));
    MyHandler handler = new MyHandler();
    Future<?> f = dispatch.invokeAsync(requestSource, handler);
    Thread.sleep(3000);

    MyHandler handler2 = new MyHandler();
    Source requestSource2 = (new StreamSource(new StringReader(request)));
    Future<?> f2 = dispatch.invokeAsync(requestSource2, handler2);

log file:
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionImpl - http-outgoing-0 127.0.0.1:13629<->127.0.0.1:8080[ACTIVE][rw:w]: 542 bytes written
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.wire - http-outgoing-0 >> "POST /fghet/sd/qqwsdfdd?wsdl HTTP/1.1[\r][\n]"
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept: /[\r][\n]"
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.wire - http-outgoing-0 >> "User-Agent: Apache CXF 3.1.4.redhat-1[\r][\n]"
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Length: 323[\r][\n]"
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/soap+xml; charset=UTF-8[\r][\n]"
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.wire - http-outgoing-0 >> "Host: localhost:8080[\r][\n]"
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.wire - http-outgoing-0 >> "AAAAAAA003YYYYYYYY"
08:24:35.491 [I/O dispatcher 1] DEBUG org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionImpl - http-outgoing-0 127.0.0.1:13629<->127.0.0.1:8080[ACTIVE][r:w]: Event cleared [w]
08:24:38.468 [main] DEBUG org.apache.http.impl.nio.client.MainClientExec - [exchange: 2] start execution
08:24:38.469 [main] DEBUG org.apache.http.client.protocol.RequestAddCookies - CookieSpec selected: default
08:24:38.469 [main] DEBUG org.apache.http.client.protocol.RequestAuthCache - Auth cache not set in the context
08:24:38.469 [main] DEBUG org.apache.http.impl.nio.client.InternalHttpAsyncClient - [exchange: 2] Request connection for {}->http://localhost:8080
08:24:38.469 [main] DEBUG org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager - Connection request: [route: {}->http://localhost:8080][total kept alive: 0; route allocated: 1 of 1000; total allocated: 1 of 5000]
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager - Connection leased: [id: http-outgoing-1][route: {}->http://localhost:8080][total kept alive: 0; route allocated: 2 of 1000; total allocated: 2 of 5000]
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.client.InternalHttpAsyncClient - [exchange: 2] Connection allocated: CPoolProxy{http-outgoing-1 [ACTIVE]}
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionImpl - http-outgoing-1 127.0.0.1:13630<->127.0.0.1:8080[ACTIVE][r:]: Set attribute http.nio.exchange-handler
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionImpl - http-outgoing-1 127.0.0.1:13630<->127.0.0.1:8080[ACTIVE][rw:]: Event set [w]
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionImpl - http-outgoing-1 127.0.0.1:13630<->127.0.0.1:8080[ACTIVE][rw:]: Set timeout 0
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.client.InternalIODispatch - http-outgoing-1 [ACTIVE]: Connected
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionImpl - http-outgoing-1 127.0.0.1:13630<->127.0.0.1:8080[ACTIVE][rw:]: Set attribute http.nio.http-exchange-state
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.client.InternalHttpAsyncClient - Start connection routing
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.client.MainClientExec - Connection route established
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.client.MainClientExec - [exchange: 2] Attempt 1 to execute request
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.client.MainClientExec - Target auth state: UNCHALLENGED
08:24:38.470 [I/O dispatcher 2] DEBUG org.apache.http.impl.nio.client.MainClientExec - Proxy auth state: UNCHALLENGED


text:
Q: Change color of legend on input focus Is there any way with CSS for changing color of legend text when input gets the focus, similar to fieldset working?
Each of the fieldset changes color when their particular input gets the focus. I am trying similarly for legend.

fieldset {
    border-radius: 0.6vh;
    border: 1vh solid black;
    padding: 1.68vh;
}

fieldset:focus-within {
    border-color: blue;
}

/* legend not changing color when focused on input */
legend:focus-within {
    color: blue;
}

legend {
    padding: 0 1.2vh;
    color: black;
}

input {
    border: none;
    padding: 0.29vh;
}

input::placeholder {
    color: black;
}

input:focus {
    outline: none;
}
<fieldset>
  <legend>Name</legend>
  <input type="text" placeholder="Your name">
</fieldset>

A: You need to get the event from the input focus and select with > the legend text and change color.

fieldset {
    border-radius: 0.6vh;
    border: 1vh solid black;
    padding: 1.68vh;
}

fieldset:focus-within {
    border-color: blue;
}

/* legend not changing color when focused on input */
fieldset:focus-within > legend {
    color: blue;
}

legend {
    padding: 0 1.2vh;
    color: black;
}

input {
    border: none;
    padding: 0.29vh;
}

input::placeholder {
    color: black;
}

input:focus {
    outline: none;
}
<fieldset>
  <legend>Name</legend>
  <input type="text" placeholder="Your name">
</fieldset>


text:
Q: Source of img: "/images/..." vs "images/..." in PHP websites (VSCode and XAMPP) I have recently been drafting a website in HTML and CSS, but since the scope of the site is larger than originally planned I want to use PHP as well (for e.g. shared nav menus). After getting my server set up (VSCode, PHP w/ Xdebug, XAMPP) I simply changed my index.html to index.php and previewed the page.
The website was identical except some images were broken. I noticed the ones that worked were sourced as images/... and there ones that were broken were sourced as /images/....
Is there a difference between /images/ and images/?

Some extra information that may play into this: When setting up PHP it was a fresh install of XAMPP and using the PHP debug with Xdebug extension in VSCode. When debugging and launching the server to preview my website I kept getting the XAMPP dashboard even though my website source was set as "webRoot": "${workspaceFolder}". The only way I could bypass this was for the project to set it absolutely by removing webroot and replacing it with "url": "http://localhost:8080/WebsiteDirectory/".

A: Yes, it is.
/images/ is an absolute path starting from the root of your page
images/ is relative from subfolder you're in.
And actually it's HTML question, not PHP.


text:
Q: How to include stubs contracts from project dependency How do you define the project dependency to include the -stubs jar?
For instance I have a multi module project.
I have my contracts project that contains all the stubs.
Then in project a I do
implementation(project(":contracts"))

This doesn't put the stubs jar on the class path.
How do I specify the project dependency to bring in the stubs jar?

A: Ok so the only way for me to get this to work was the following.
In the contracts module build.gradle.kts(this is using kotlin DSL):
val stubs by configurations.creating {
  isCanBeConsumed = true
  isCanBeResolved = false
}

artifacts {
  add("stubs", tasks.verifierStubsJar.get())
}

Then on the consumer side:
testImplementation(project(":libs:contracts", "stubs"))

Using testImplementation is important here. If you only do runtime, the jars in contract module need to be prebuilt. Using testImplementation forces the dependency to be built at the time you build the project (i.e like you do when executing a test)


text:
Q: "textAlignVertical" is not a valid style property I am getting an error saying "textAlignVertical" is not a valid style property when attempting to use the 'textAlignVertical' style on a Text element. I've checked the documentation and it says I should be able to use this style property: https://facebook.github.io/react-native/docs/text.html
has anyone else had this issue?

A: Sometimes you might find that alignItems won't work well -- I saw that an icon that I was using disappeared entirely. I instead just added an alignSelf: 'center' to the styling on the text itself (rather than the parent like you need to do with alignItems) and it seemed to fix it.

A: The textAlignVertical style is an Android-only property. If you are developing on iOS, try using the flexbox alignment property alignItems: center instead.
It also appears that the textAlignVertical property was moved from TextInput properties to the Text element styles only three days ago, and is going to be released in React Native 0.19.
I am not sure how the React Native documentation is generated, but based on my reading of this commit diff, the documentation appears to be ahead of the latest released version.

A: For textAlignVertical to work properly, add lineHeight prop instead of height for ios
height: phoneWidth * 0.09, // for android
lineHeight: phoneWidth * 0.09, // for ios

A: The line height solution worked for me. I am writing this post to explicitly show how to set the line height by platform:
yourComponent: {
    width: 44, height: 44,
    ...Platform.select({
        ios: {
            lineHeight: 44
        },
        android: {}
    }),
    textAlign: 'center', textAlignVertical: 'center',
}

It's important that your and height and line height are the same and that you do it by platform.
It's important to note that I also have this component nested in a view with alignItems set to center.
I just wanted to explicitly write this code out as I had to piece it together from a few posts and this should make it easier if someone is looking for a quick copy/paste solution.


text:
Q: Can the dropships be destroyed? Overwatch's Retribution archives event has a few sections in which enemy troops drop in from gunships/dropships at certain parts of the map, most notably in the end sequence. When shooting these dropships, hitmarkers do activate, and it seems like some fire and sparks start appearing around the engines.
It begs the question; can these gunships be destroyed completely? I have not had the opportunity to play a character with the potential damage output to do so (Bastion), so I'm not too sure.

A: I've tested this with a Bastion, and even though he causes dropships to very quickly start burning, I've never been able to take one down, either before or after it releases enemies.
Hoever, in the event's final area, some dropships will release two waves of enemies. It is possible to force a dropship to retreat after the first wave of enemies by dealing enough damage to it.


text:
Q: PHP return true in a function after first word is found I have an array filled with words:
$words = array("word", "word2", "apple", "cake");

Then I want to use this array in a function that will check to see if a word exists in a string ($text) like so...
function find_word($text) {
    $words = array("word", "word2", "apple", "cake");
}

...but I want the function to stop checking if the words exist and return true after the FIRST occurrence of one of the words in the array, is in the string ($text). (So the function won't have to check every single word against the string.) If the word isn't found, then I want it to return false.
I've tried searching some methods up, and the only things that I was able to find were methods that used preg_match, but they checked every single word in the array against the string, which I think would slow the script down.
What would be the best way to accomplish this?
NOTE: I want this function to return true even if one of the words in the array, is in the word. For example: blahAPPLErandom should return true, because apple is in there.

A: for ($i = 0; $i < count($words); $i++)
    if (stripos($text, $words[$i]) !== false)
        return true;

A: What about using stristr PHP function?
function find_word($text) {
    $words = array("word", "word2", "apple", "cake");
    foreach ($words as $w) {
        if (stristr($text, $w)) return True;
    }
    return False;
}


text:
Q: Android save gif from byte array When I am using below code to save a byte array to gif, the gif file is blurred.
But if I save the byte array to a png or jpg is everything OK. Does anybody know what the problem is?
public writeToFile(byte[] array) {
    try {
        String path = "...";
        FileOutputStream stream = new FileOutputStream(path);
        stream.write(array);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

A: GIF is limited to 256 colors and do not support real transparency.

You should use PNG instead of GIF because it offers better compression and features. PNG is great for small and simple images like logos, icons, etc.
JPEG has better compression with complex images like photos.
png has a wider color pallete than gif and gif is properitary while png is not. gif can do animations, what normal-png cannot. png-transparency is only supported by browser roughly more recent than IE6, but there is a Javascript fix for that problem. Both support alpha transparency. In general I would say that you should use png for most webgraphics while using jpeg for photos, screenshots, or similiar because png compression does not work too good on thoose.


text:
Q: Visual Studio Intellisense only works partially I have a project that builds successfully.
But when i try to navigate to some of the definitions I get this error:

and also the colors are white on some classes:

the version is Vs2019 rc. i didn't have this problem with 2019 preview.


text:
Q: IllegalStateException, the specified child already has a parent - ListFragment I have looked at every error of this kind of here, but nothing fixes it. I am trying to programmatically add a fragment to my activity (with the help of other's code) and I run it and get this error:
IllegalStateException, the specified child already has a parent, you must call removeView() on the child's parent first.

I have one activity that simply hosts a fragment, using FrameLayout in its xml, then I code in that activity the FragmentManager to get it started. The details of my fragment's view are in the onCreateView() of my fragment class, ContactsFragment.java. Here, I assign a ListView as my fragment that I hope to view in my activity called AddressBook.java.
Thanks for your help, if you can spot any errors in my code. Activity, fragment, xmls, and logcat are below.
EDIT: When I take out the FragmentManager code, the error goes away, but then I get a blank white activity. Does this help anyone know more about the nature of the error? Thanks.
Code commented out:
        // Begin the transaction
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        // Replace the container with the new fragment
        ft.add(R.id.contacts_fragment, new ContactsFragment());
        // Execute the changes specified
        ft.commit();

AddressBook.java
package org.azurespot.practiceapp.addressbook;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;

import com.example.practiceapp.R;

public class AddressBook extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_book);

        // Begin the transaction
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        // Replace the container with the new fragment
        ft.replace(R.id.contacts_fragment, new ContactsFragment());
        // or ft.add(R.id.your_placeholder, new FooFragment());
        // Execute the changes specified
        ft.commit();
    }

}

activity_address_book.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.azurespot.practiceapp.addressbook.AddressBook" >

     <FrameLayout
         android:id="@+id/contacts_fragment"
         android:layout_width="0dp"
         android:layout_height="match_parent" >
     </FrameLayout>

</LinearLayout>

ContactsFragment.java
package org.azurespot.practiceapp.addressbook;

import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.example.practiceapp.R;

/*
 * Partially from http://stackoverflow.com/questions/18199359/how-to-display-contacts-in-a-listview-in-android-for-android-api-11
 */

public class ContactsFragment extends ListFragment implements
                                LoaderCallbacks<Cursor>{

    private CursorAdapter listAdapter;
    public Cursor cursor;
    private android.content.Context context;
    public View view;
    public static Uri uri;
    public static ListView listView;

    public static final String[] FROM = new String[]{
            ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.HAS_PHONE_NUMBER };

    private static final int[] TO = { R.id.contact_thumbnail,
        R.id.contact_name, R.id.contact_number };

    // columns requested from the database
    private static final String[] PROJECTION = new String[]{
        ContactsContract.Contacts._ID,
            ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
    };

    // this goes in the CursorLoader parameter list, it filters
    // out only those contacts who have a phone number
    private static final String FILTER =
            ContactsContract.Contacts.HAS_PHONE_NUMBER  + " LIKE ?";

    private static final int URL_LOADER = 0;

    @Override
    public View onCreateView(LayoutInflater inflater,
             ViewGroup container,Bundle bundle) {

        if(listView != null) {
            return listView;
        }

        // since using ListFragment, you must inflate your view this way
        View rootView = inflater.inflate(R.layout.fragment_list_view,
                container, false);
        listView = (ListView) rootView
                                .findViewById(android.R.id.list);

        // create a new SimpleCursorAdapter adapter
        context = getActivity();
        Cursor c = null; // there is no cursor yet
        int flags = 0; // no auto-re-query! (My loader re-queries.)
        // put List UI row in adapter, create empty adapter
        listAdapter = new SimpleCursorAdapter(context,
                R.layout.fragment_list_item, c, FROM, TO, flags);

        // Initializes the CursorLoader. The URL_LOADER value is
        // eventually passed to onCreateLoader().
        getLoaderManager().initLoader(URL_LOADER, null, this);

        // ListFragment then sets the adapter
        ContactsFragment listFrag = new ContactsFragment();
        listFrag.setListAdapter(listAdapter);

        return listView;

    } // end onCreateView

    // Empty public constructor, required by the system
    public ContactsFragment() {}

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    /*
     * The 3 methods below are standard for the LoaderCallbacks<Cursor> interface.
     * Here, CursorLoader does a query in the background.
     */

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // load from the "Contacts table"
        Uri contentUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

        // the query
        return new CursorLoader(getActivity(),
                contentUri,
                PROJECTION,
                FILTER,
                null,
                ContactsContract.Contacts.DISPLAY_NAME + " ASC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
         // Once cursor is loaded, give it to adapter
        listAdapter.swapCursor(data);

        // The list should now be shown.
        if (isResumed()) {
            setListShown(true);
        } else {
            setListShownNoAnimation(true);
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // Delete the reference to the existing Cursor,
        // so it can recycle it
        listAdapter.swapCursor(null);

    }

}

fragment_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ListView>

    <TextView
        android:id="@id/android:empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FF0000"
        android:text="No data"/>

</LinearLayout>

fragment_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/contact_thumbnail"
        android:layout_width="50dp"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/contact_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10" >

    </TextView>

    <TextView
        android:id="@+id/contact_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10" >

    </TextView>

</LinearLayout>

Logcat
12-27 22:37:17.145: I/PersonaManager(12130): getPersonaService() name persona_policy
12-27 22:37:17.165: D/skia(12130): GFXPNG PNG bitmap created width:48 height:48 bitmap id is 270
12-27 22:37:17.175: E/MoreInfoHPW_ViewGroup(12130): Parent view is not a TextView
12-27 22:37:17.185: D/skia(12130): GFXPNG PNG bitmap created width:72 height:72 bitmap id is 271
12-27 22:37:17.185: D/skia(12130): GFXPNG PNG bitmap created width:144 height:144 bitmap id is 272
12-27 22:37:17.205: D/skia(12130): GFXPNG PNG bitmap created width:144 height:144 bitmap id is 273
12-27 22:37:17.295: I/Adreno-EGL(12130): <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build:  ()
12-27 22:37:17.295: I/Adreno-EGL(12130): OpenGL ES Shader Compiler Version: E031.24.00.08+13
12-27 22:37:17.295: I/Adreno-EGL(12130): Build Date: 03/20/14 Thu
12-27 22:37:17.295: I/Adreno-EGL(12130): Local Branch: 0320_AU200_patches
12-27 22:37:17.295: I/Adreno-EGL(12130): Remote Branch:
12-27 22:37:17.295: I/Adreno-EGL(12130): Local Patches:
12-27 22:37:17.295: I/Adreno-EGL(12130): Reconstruct Branch:
12-27 22:37:17.325: D/OpenGLRenderer(12130): Enabling debug mode 0
12-27 22:37:18.705: I/PersonaManager(12130): getPersonaService() name persona_policy
12-27 22:37:18.715: E/MoreInfoHPW_ViewGroup(12130): Parent view is not a TextView
12-27 22:37:18.735: D/skia(12130): GFXPNG PNG bitmap created width:12 height:12 bitmap id is 274
12-27 22:37:18.735: D/AbsListView(12130): Get MotionRecognitionManager
12-27 22:37:18.745: D/AndroidRuntime(12130): Shutting down VM
12-27 22:37:18.745: W/dalvikvm(12130): threadid=1: thread exiting with uncaught exception (group=0x41737da0)
12-27 22:37:18.745: E/AndroidRuntime(12130): FATAL EXCEPTION: main
12-27 22:37:18.745: E/AndroidRuntime(12130): Process: com.example.practiceapp, PID: 12130
12-27 22:37:18.745: E/AndroidRuntime(12130): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.practiceapp/org.azurespot.practiceapp.addressbook.AddressBook}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2395)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2453)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.ActivityThread.access$900(ActivityThread.java:173)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.os.Handler.dispatchMessage(Handler.java:102)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.os.Looper.loop(Looper.java:136)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.ActivityThread.main(ActivityThread.java:5579)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at java.lang.reflect.Method.invokeNative(Native Method)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at java.lang.reflect.Method.invoke(Method.java:515)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at dalvik.system.NativeStart.main(Native Method)
12-27 22:37:18.745: E/AndroidRuntime(12130): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.view.ViewGroup.addViewInner(ViewGroup.java:3771)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.view.ViewGroup.addView(ViewGroup.java:3624)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.view.ViewGroup.addView(ViewGroup.java:3569)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.view.ViewGroup.addView(ViewGroup.java:3545)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:901)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.BackStackRecord.run(BackStackRecord.java:684)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.Activity.performStart(Activity.java:5460)
12-27 22:37:18.745: E/AndroidRuntime(12130):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
12-27

22:37:18.745: E/AndroidRuntime(12130):     ... 11 more

A: In 'ContactsFragment.java' class you are not returning the inflated view. Instead the listview is returned. Try change the code as below
@Override
public View onCreateView(LayoutInflater inflater,
             ViewGroup container,Bundle bundle) {

       // since using ListFragment, you must inflate your view this way
        View rootView = inflater.inflate(R.layout.fragment_list_view,
                container, false);

        return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
       super.onActivityCreated(savedInstanceState);
         listView = (ListView)getListView();

        // create a new SimpleCursorAdapter adapter
        context = getActivity();
        Cursor c = null; // there is no cursor yet
        int flags = 0; // no auto-re-query! (My loader re-queries.)
        // put List UI row in adapter, create empty adapter
        listAdapter = new SimpleCursorAdapter(context,
                R.layout.fragment_list_item, c, FROM, TO, flags);

        // Initializes the CursorLoader. The URL_LOADER value is
        // eventually passed to onCreateLoader().
        getLoaderManager().initLoader(URL_LOADER, null, this);

        setListAdapter(listAdapter);

}

Use the same replace() method is Activity
       // Begin the transaction
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        // Replace the container with the new fragment
        ft.replace(R.id.contacts_fragment, new ContactsFragment());
        // or ft.add(R.id.your_placeholder, new FooFragment());
        // Execute the changes specified
        ft.commit();

fragment_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#FF0000"
    android:layout_height="match_parent" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >
    </ListView>

    <TextView
        android:id="@id/android:empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#FF0000"
        android:text="No data"/>

</LinearLayout>

activity_address_book.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.azurespot.practiceapp.addressbook.AddressBook" >

     <FrameLayout
         android:id="@+id/contacts_fragment"
         android:layout_width="match_parent"
         android:layout_height="match_parent" >
     </FrameLayout>

</LinearLayout>


text:
Q: Exclude folder from next JS build I have a bulky folder full of backend & config code located in /src/config inside my Next JS app.
I don't need to ship any of this code to the client when building. Is there a best practice for excluding this folder from building in Next JS? Thanks


text:
Q: How can I delete files based on (flac) metadata? I have several folders with both FLAC 24/96 and 16/44.1 files.
I want to delete the 24-bit/96 KHz files, but leave the others. How do I do this from the command line? Is there a way to systematically sort files by metadata and then use that list with rm?

A: For the sake of completeness, it's worth too mention that it's also very easy to open a directory and it's subdirectories in Puddletag, sort for your desired criteria, and then mark and delete the files you want. This might be safer and even faster than customizing or writing a completely new script (see: xkcd 1205 - Is It Worth the Time?).

You can use metaflac (manpage) for flac files.
$ metaflac --show-sample-rate --show-bps "somefile.flac"
44100
16

Of course this is not a complete script. You might want to take a look at the Advanced Bash-Scripting Guide.
The following would be a very basic script that deletes all files which return 44100 and 16 to the above command. The directory is given to the script as a parameter (e.g. flac-44100-removal.sh "Music/All music with 44.1kHz/")
#!/bin/bash
IFS=$'\n'

for file in $(find "${1}" -name "*.flac");
do
    if [ "$(metaflac  --show-sample-rate "$file")" = "44100" ]; then
        if [ "$(metaflac  --show-bps "$file")" = "16" ]; then
            rm -i "$file"
        fi
    fi
done

Alternatives to metaflac are: vorbiscomment for ogg, AtomicParsley for mp4/m4a, mid3v2 for mp3 or mediainfo for everything, but they all have different outputs, with mediainfo being overly customizable.


text:
Q: orphanRemoval=true bidirectional OneToOne I'm a little confused with bidirectional OneToOne relationship, and removing of orphans. These are my entities:
@Entity
@Table(name = "city")
public class City {

    @Id
    @GeneratedValue
    @Column
    public Long _UID;

    @OneToOne(mappedBy="city", orphanRemoval = true, cascade=CascadeType.ALL)
    public Mayor mayor;
}

@Entity
@Table(name = "mayor")
public class Mayor {

    @Id
    @GeneratedValue
    @Column
    public Long _UID;

    @OneToOne(optional=false)
    public City city;
}

And if I try this transaction:
City c = em.find(City.class, (long) 1);
AssertNotNull(c.getMayor());//gives true
Mayor m = new Mayor("Ed", "Lee");
c.setMayor(m);
m.setCity(c);
em.flush(); //This creates new Mayor and adds it to City, but don't delete an old one.

If I set mayor to null and flush before set new one, it works:
City c = em.find(City.class, (long) 1);
AssertNotNull(c.setMayor());//gives true
c.setMayor(null);
em.flush();
Mayor m = new Mayor("Ed", "Lee");
c.setMayor(m);
m.setCity(c);
em.flush(); //This creates new Mayor and adds it to City, but don't deletes an old one.

I use Hibernate 4 as JPA2 implementation.

A: This is a known issue in Hibernate (and actually in the JPA spec).
See this bug report for more on the problem's background, and on possible workarounds. There is another ticket on the same issue that you can vote for, as the former is already closed.

A: *

*please remove (optional=false)

*you have to do em.clear() after em.flush()


text:
Q: How to execute a program in compatibility mode from code? Environment: Windows Server 2008 R2 64 bit
I have a program that works with Windows Server 2003 SP1 compatibility mode. However, when I try to execute this program using C#, the program errors out.
I think it is because it is not running in compatibility mode when invoked from another program. I use Process.Start(pathToExe) from my code to start this program.
I tried to run the calling program in compatibility mode to check if this would make the program run correctly.
Please note that I have set the program set to compatibility from Properties | Compatibility.

A: I am not sure if I understand your problem exactly, but if you want to run the Program always in the Compatibility mode you can set the registry to make it work so.
Registry Key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers
Add a new String entry with,
Name : Your Application Path in Full.
Type: REG_SZ
Data : Required Compat Value. I think it is WIN2003 OR WIN2003SP1 in your case.
Example:
C:\Program Files\System32\Notepad.exe          REG_SZ          WIN2003
You can check for the current OS version you are running under and you can set and unset this registry value before calling the program.


text:
Q: Sort and display directory list alphabetically PHP I would like to sort my files by alphabetically, but I don't know how can i do it. I mean, I want that the directories will be the first by ABC order, and after the files ordered by ABC.
I tried several options, but I couldn't do this.
Here is my code:
<?php

    $dirlist = getFileList("./members/files/");?>

                Name
                Type
                Size
                Last Modified

            <?php
            // output file list as table rows
            foreach($dirlist as $file) {
                echo "
\n";

                    $file['nams'] = basename($file['name']);
                    $file['nams2'] = pathinfo($file['nams'], PATHINFO_EXTENSION );
                    $file['nams'] = pathinfo($file['nams'], PATHINFO_FILENAME);

                    if($file['nams2'] != 'mp4' && $file['nams2'] != '')
                    {
                        echo "",basename($file['name']),"	\n";
                    } else if($file['nams2'] != '') {
                        echo "",basename($file['name']),"	\n";
                    } else {
                        echo "",basename($file['name']),"	\n";
                    }

                    echo "{$file['type']}	\n";
                    echo "{$file['size']}	\n";
                    echo "",date('Y-m-d H:i', $file['lastmod']),"	\n";

                echo "
\n";
            }
            ?>

    <?php
    function getFileList($dir, $recurse=false, $depth=false)
    {
        $retval = array();

        // add trailing slash if missing
        if(substr($dir, -1) != "/") $dir .= "/";

        // open pointer to directory and read list of files
        $d = @dir($dir) or die("getFileList: Failed opening directory $dir for reading");
        while(false !== ($entry = $d->read())) {
            // skip hidden files
            if($entry[0] == ".") continue;
            if(is_dir("$dir$entry")) {
                $retval[] = array(
                    "name" => "$dir$entry/",
                    "type" => filetype("$dir$entry"),
                    "size" => 0,
                    "lastmod" => filemtime("$dir$entry")
                );
                if($recurse && is_readable("$dir$entry/")) {
                    if($depth === false) {
                        $retval = array_merge($retval, getFileList("$dir$entry/", true));
                    } elseif($depth > 0) {
                        $retval = array_merge($retval, getFileList("$dir$entry/", true, $depth-1));
                    }
                }
            } elseif(is_readable("$dir$entry")) {
                $retval[] = array(
                  "name" => "$dir$entry",
                  "type" => mime_content_type("$dir$entry"),
                  "size" => formatSizeUnits(filesize("$dir$entry")),
                  "lastmod" => filemtime("$dir$entry")
                );
            }
        }
        $d->close();

        return $retval;
    }

    function formatSizeUnits($bytes)
    {
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . ' kB';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . ' bytes';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . ' byte';
        }
        else
        {
            $bytes = '0 bytes';
        }

        return $bytes;
    }
?>

A: You could use scandir to return sorted file list in form of an array.
Example:
<?php
    $directory_list = scandir("./members/files/");
    print_r($directory_list);

This will output directory list similar to that:
Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
    ...
)

You can do it like this to sort them in descending order:
print_r($directory_list, SCANDIR_SORT_DESCENDING);

You can find more about scandir in PHP documentation.


text:
Q: partially initialized module 'turtle' has no attribute 'start' (most likely due to a circular import) VS code. 'start' is the problem, not file name The file name isn't the problem here, for some reason it's saying that the 'start' attribute is the problem.
import turtle

turtle.setup(400,500)                # Determine the window size
wn = turtle.Screen()                 # Get a reference to the window
wn.title("Handling keypresses!")     # Change the window title
wn.bgcolor("lightgreen")             # Set the background color
tess = turtle.Turtle()               # Create our favorite turtle

# The next four functions are our "event handlers".
def h1():
    tess.forward(30)

def h2():
    tess.left(45)

def h3():
    tess.right(45)

def h4():
    wn.bye()                        # Close down the turtle window

# These lines "wire up" keypresses to the handlers we've defined.
wn.onkey(h1, "Up")
wn.onkey(h2, "Left")
wn.onkey(h3, "Right")
wn.onkey(h4, "q")

# Now we need to tell the window to start listening for events,
# If any of the keys that we're monitoring is pressed, its
# handler will be called.
wn.listen()
wn.mainloop()


text:
Q: post array keep only 1 value PHP FORM CODE :
    echo '<form name="planeSeat" action="koltuk-sec-process.php" method="post" >';
...
    echo '<input type="checkbox" class="css-checkbox" id="'.$rightplace.'" name="artwork" value="'.$rightplace.'"  />';
...
    echo '<input type="submit" name="formSubmit" value="Üye girişi yapmadan devam et"/>';

PHP PROCESS CODE :
    $rest1 = array();
    $rest2 = array();

$rest1[] = htmlspecialchars($_POST["artwork"]);
$rest2[] = htmlspecialchars($_POST["artwork2"]);

   if($rest1 != null){

    print_r ($rest1);

    }

    if($rest2 != null){

    print_r ($rest2);

    }

When I send artwork, if I selected 2 checkboxes, $rest1 only keeps the last value. How can I send my all values?

A: You probably wanted to code
$rest1[] = htmlspecialchars($_POST["artwork"]);
$rest1[] = htmlspecialchars($_POST["artwork2"]);

instead of
$rest1[] = htmlspecialchars($_POST["artwork"]);
$rest2[] = htmlspecialchars($_POST["artwork2"]);

A: For one result, break should do the trick:
$foobar = array('uno', 'dos', 'tres');
foreach ($foobar as $fb) {
    echo '<p>'.$fb.'</p>';
    break;
}

A: the reason is simple : in case of multiple checkbox checked with the same name, you have to specified an array for the checkbox name, this way you will be able to traverse the posted values
echo '<input type="checkbox" class="css-checkbox" id="'.$rightplace.'" name="artwork[]" value="'.$rightplace.'"  />';

echo '<input type="checkbox" class="css-checkbox" id="'.$rightplace.'" name="artwork[]" value="'.$rightplace.'"  />'; // second checkbox

print_r ( $_POST['artwork'] ) // will display the artwork array

all of your checkbox with similar content should have the same name !!!!!


text:
Q: PushSharp 4.0.10.0: HTTP/2-based Apple Push Notification service (APNs) We use PushSharp 4.0.10 to send iOS Push Notifications:
https://github.com/Redth/PushSharp
Recently we recieved this email from Apple Developer:
"If you still send push notifications with the legacy binary protocol, it's time to update to the HTTP/2-based Apple Push Notification service (APNs) provider API. You'll be able to take advantage of great features, such as authentication with a JSON Web Token, improved error messaging, and per-notification feedback.
To give you additional time to prepare, the deadline to upgrade to the APNs provider API has been extended to March 31, 2021. We recommend upgrading as soon as possible, as APNs will no longer support the legacy binary protocol after this date."
My question is: Will PushSharp 4.0.10 still work after March 31, 2021?

A: There is a discussion about this but the thread was closed. But there are still some suggestions on this thread that you might want to try.
The Apple Push Notification service (APNs) will no longer support the legacy binary protocol as of November 2020
https://github.com/Redth/PushSharp/issues/923
**
EDIT - 25th March 2021
The deadline is close and @Ashita Shah asked some code snippet so I hope the following can save your time.
Add the following class dotAPNSService to your project. You can customise this structure according to your needs. Also I didn't focus the best of best coding C# standards when implementing my own push notification service. You can implement LINQ, Tasks async etc. I tested this dotAPNS library and it works perfectly fine. For Android you can still use PushSharp.
Before you implement the dotAPNSService helper class, get the following from your Apple developer account. The ApnsJwtOptions values should be:
BundleId - your app's bundle ID. Should not include specific topics (i.e. com.myapp but not com.myapp.voip).
CertFilePath - path to the .p8 certificate you have downloaded from the Developer Center.
KeyId - The 10-character Key ID you obtained from your developer account
TeamId - The 10-character Team ID you use for developing your company's apps. Obtain this value from your developer account.
public class dotAPNSService : IDisposable
{
    public event EventHandler OnTokenExpiredHandler;
    private ApnsJwtOptions options = null;

    public dotAPNSService()
    {
        options = new ApnsJwtOptions()
        {
            BundleId = "com.xx.xxxx",
            CertFilePath = "../../certificate.p8",
            KeyId = "The_Key_Id",
            TeamId = "The_Team_Id"
        };
    }

    public void SendNotifications(String[] deviceTokens, String title, String body)
    {
        if (deviceTokens == null || deviceTokens.Length <= 0)
        {
            return;
        }

        if (String.IsNullOrEmpty(title))
        {
            return;
        }

        if (String.IsNullOrEmpty(body))
        {
            return;
        }

        // once you've gathered all the information needed and created an options instance, it's time to call
        var apns = ApnsClient.CreateUsingJwt(new HttpClient(), options);

        // start the process
        foreach (String deviceToken in deviceTokens)
        {
            var push = new ApplePush(ApplePushType.Alert)
                .AddAlert(title, body)
                .AddToken(deviceToken);

            Send(apns, push, deviceToken);
        }
    }

    public void SendSilentNotifications(String[] deviceTokens)
    {
        try
        {
            if (deviceTokens == null || deviceTokens.Length <= 0)
            {
                return;
            }

            // once you've gathered all the information needed and created an options instance, it's time to call
            var apns = ApnsClient.CreateUsingJwt(new HttpClient(), options);

            // start the process
            foreach (String deviceToken in deviceTokens)
            {
                var push = new ApplePush(ApplePushType.Background)
                    .AddContentAvailable()
                    .AddToken(deviceToken);

                Send(apns, push, deviceToken);
            }
        }
        finally
        {

        }
    }

    private void Send(ApnsClient apns, ApplePush push, String deviceToken)
    {
        try
        {
            var response = apns.SendAsync(push);
            if (response.Result.Reason == ApnsResponseReason.Success)
            {
                // the notification has been sent!
            }
            else
            {
                Boolean removeToken = false;
                switch (response.Result.Reason)
                {
                    case ApnsResponseReason.BadDeviceToken:
                        removeToken = true;
                        break;
                    case ApnsResponseReason.TooManyRequests:
                        break;
                }

                // remove the token from database?
                if (removeToken)
                    OnTokenExpired(new ExpiredTokenEventArgs(deviceToken));
            }
        }
        catch (TaskCanceledException)
        {
            // ERROR - HTTP request timed out, you can use the deviceToken to log the error
        }
        catch (HttpRequestException ex)
        {
            // ERROR - HTTP request failed, you can use the deviceToken to log the error
        }
    }

    protected virtual void OnTokenExpired(ExpiredTokenEventArgs args)
    {
        try
        {
            EventHandler handler = OnTokenExpiredHandler;
            if (handler != null)
            {
                ISynchronizeInvoke target = handler.Target as ISynchronizeInvoke;
                if (target != null && target.InvokeRequired)
                    target.Invoke(handler, new object[] { this, args });
                else
                    handler(this, args);
            }
        }
        catch (Exception ex)
        {

        }
    }
}

These are the namespaces of the dotAPNSService helper class:
using System;
using System.ComponentModel;
using System.Net.Http;
using System.Threading.Tasks;
using dotAPNS;

In order to use the dotAPNSService helper on your project just pull the tokens from the database and then pass them to it. For instance, to send silent notifications:
public void SendScheduledSilentNotifications()
{
    try
    {
        IList<User> users = _accountService.GetUsers(true);
        if (users != null && users.Count > 0)
        {
            List<String> deviceTokens = new List<String>();
            foreach (User user in users)
            {
                if (!String.IsNullOrEmpty(user.DeviceToken))
                    deviceTokens.Add(user.DeviceToken);
            }

            if (deviceTokens.Count > 0)
            {
                using (dotAPNSService service = new dotAPNSService())
                {
                    service.OnTokenExpiredHandler += new EventHandler(OnTokenExpired);
                    service.SendSilentNotifications(deviceTokens.ToArray());
                }
            }
        }
    }
    finally
    {

    }
}

To remove the expired tokens from the database you can use the following:
private void OnTokenExpired(object sender, EventArgs e)
{
    if (e == null)
        return;

    if (e.GetType() == typeof(ExpiredTokenEventArgs))
    {
        var args = (ExpiredTokenEventArgs)e;
        User user = _accountService.GetUserByDeviceToken(args.Token);
        if (user != null)
        {
            user.DeviceToken = String.Empty;
            Boolean success = !(_accountService.SaveUser(user) == null);
            if (success)
                // INFO - expired device token has been removed from database
            else
                // INFO - something went wrong
        }
    }
}

You can download the source code from here:
https://github.com/alexalok/dotAPNS
The API is now sending thousands of silent notifications at one time and there are no delays, crashes etc. Hope this code snippet helps and saves your time!


text:
Q: Creating a bootable Mac OS USB from Ubuntu 20.04. Unetbootin won't install I am trying to create a bootable usb drive for Mac OS El Capitan from a machine that has Ubuntu 20.04.
I have tried to install Unetbootin.
sudo add-apt-repository ppa:gezakovacs/ppa
sudo apt-get update
sudo apt-get install unetbootin
I received this installation message in the terminal:
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies.
 unetbootin : Depends: libqt4-network (>= 4:4.5.3) but it is not installable
              Depends: libqtcore4 (>= 4:4.7.0~beta1) but it is not installable
              Depends: libqtgui4 (>= 4:4.5.3) but it is not installable
              Recommends: extlinux but it is not going to be installed
              Recommends: unetbootin-translations but it is not going to be installed
              Recommends: gksu but it is not installable or
                          kdesudo but it is not installable
E: Unable to correct problems, you have held broken packages.
I am an Ubuntu novice, but I have used it on and off for the last 12 years. Are there any ways to fix this please?


text:
Q: Why does jquery tmpl not parse my {{ if }}? I have a jquery template containing an if but it won't evaluate the if - it just outputs the value as-is. I have found several examples and documentation showing that this should work.
What am i doing wrong?
http://jsfiddle.net/G4J5u/

A: You have extra space in the template tags:
Yours:
{{ if disabled}}disabled{{ /if }}

Correct:
{{if disabled}}disabled{{/if}}

Tested it on JSFiddle.


text:
Q: Image failing to display in R shiny I feel like there is really silly mistake, but I can't solve this myself and it is driving me crazy. To simply put, Rshiny is not display the image.
I put the source image in www directory in same path as the Rscript file, yet something is wrong.
The code I used are below:
ui <- fluidPage(
  fluidRow(
    titlePanel(title=div(img(height = 100,
                             width = 100,
                             src = "dummy-logo.png"), "dummy")),
    sidebarLayout(...

This is the pathway for my image.

Here is the directory.:

Yet Rshiny could not find the image:

I looked around other posts but I am still not sure where I went wrong. I am pretty sure this is some really dumb mistake that I will be ashamed of but as of now, it is driving me nuts.  Thank you.

A: Have you checked this answer? Embedding Image in Shiny App
Maybe rewrite the  titlePanel to:
titlePanel(title=div(id="dummy", img(height = 100,
                         width = 100,
                         src = "dummy-logo.png"))),

And check if the image is really named - dummy-logo.png.
Otherwise i would suggest you create a New Project in RStudio -> New Directory -> Shiny Web Application. Put your ui and server functions in there.
Create the www-folder, put your image in there and it should work like that.


text:
Q: Правильная работа else в forech При указании условия esle в цикле выводится не 1 значение переменной, а зацикленное значение.
Массив вида:
[
{
    "user": "Петров Иван",
    "Department": "1",
    "Total": 9688,
    "Addon_1": "1",
    "Addon_2": "2",
    "Addon_3": "3",
    "topuser": "4"
},
{       "user": "Иванов Петр",
    "Department": "1",
    "Total": 9688,
    "Addon_1": "1",
    "Addon_2": "2",
    "Addon_3": "3",
    "topuser": "4"
}

]
$arr = json_decode($response, true);
$a = "Петров Иван";
<?php
foreach ($arr as $row) {
    if($row['user'] == $a)
        echo $row['user'];
    else {
        echo $a;
    }
}
?>

Как правильно вывести если "user" в массиве = $a вывести "user" из массива, если такое значение не найдено вывести переменную $a.

A: Приблизительный алгоритм может быть таким:
$userFound = false;    // флаг, сообщающий что пользователь найден
foreach ($arr as $row) {
    if($row['user'] == $a)
        $userFound = true;
        echo $row['user'];
        break;         // прерываем цикл, так как дальнейшие элементы нас не интересуют
    }
}
// так как пользователь НЕ найден - выводим что-то еще.
if (!$userFound) {
    echo $a;
}


text:
Q: How to properly handle onError inside RxJava (Android)? I'm getting a list of installed apps on the device. It's a costly operation, so I'm using Rx for that:
    Observable<List> observable = Observable.create(subscriber -> {
        List result = getUserApps();

        subscriber.onNext(result);
        subscriber.onError(new Throwable());
        subscriber.onCompleted();
    });

    observable
            .map(s -> {
                ArrayList<String> list = new ArrayList<>();
                ArrayList<Application> applist = new ArrayList<>();
                for (Application p : (ArrayList<Application>) s) {
                    list.add(p.getAppName());
                    applist.add(p);
                }
                return applist;
            })
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError(throwable -> L.e(TAG, "Throwable " + throwable.getMessage()))
            .subscribe(s -> createListView(s, view));

However, my problem is with handling errors.
Normally, user launches this screen, waits for apps to load, selects what is best and goes to next page. However, when user quickly changes the UI - app crashes with NullPointer.
Okay, so I implemented this onError. However it still doesn't work, and with above usecase it throws me this:
    04-15 18:12:42.530  22388-22388/pl.digitalvirgo.safemob E/AndroidRuntime﹕ FATAL EXCEPTION: main
        java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add `onError` handling.
                at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:52)
                at android.os.Handler.handleCallback(Handler.java:730)
                at android.os.Handler.dispatchMessage(Handler.java:92)
                at android.os.Looper.loop(Looper.java:176)
                at android.app.ActivityThread.main(ActivityThread.java:5419)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:525)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
                at dalvik.system.NativeStart.main(Native Method)
         Caused by: rx.exceptions.OnErrorNotImplementedException
                at rx.Observable$31.onError(Observable.java:7134)
                at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:154)
                at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:111)
                at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70)
                at rx.internal.operators.NotificationLite.accept(NotificationLite.java:147)
                at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.pollQueue(OperatorObserveOn.java:177)
                at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.access$000(OperatorObserveOn.java:65)
                at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$2.call(OperatorObserveOn.java:153)
                at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:47)
                at android.os.Handler.handleCallback(Handler.java:730)
                at android.os.Handler.dispatchMessage(Handler.java:92)
                at android.os.Looper.loop(Looper.java:176)
                at android.app.ActivityThread.main(ActivityThread.java:5419)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:525)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
                at dalvik.system.NativeStart.main(Native Method)
         Caused by: java.lang.Throwable
                at pl.digitalvirgo.safemob.fragments.wizard.ApplicationsFragment.lambda$getAppList$25(ApplicationsFragment.java:267)
                at pl.digitalvirgo.safemob.fragments.wizard.ApplicationsFragment.access$lambda$2(ApplicationsFragment.java)
                at pl.digitalvirgo.safemob.fragments.wizard.ApplicationsFragment$$Lambda$3.call(Unknown Source)
                at rx.Observable$1.call(Observable.java:145)
                at rx.Observable$1.call(Observable.java:137)
                at rx.Observable.unsafeSubscribe(Observable.java:7304)
                at rx.internal.operators.OperatorSubscribeOn$1$1.call(OperatorSubscribeOn.java:62)
                at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:47)
                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390)
                at java.util.concurrent.FutureTask.run(FutureTask.java:234)
                at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:153)
                at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:267)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
                at java.lang.Thread.run(Thread.java:841)

How should I properly handle this problem?

A: Here is the newbie response (because I am new in javarx and finally fix this issue) :
Here is your implementation :
    Observable.create(new Observable.OnSubscribe<RegionItem>() {
                @Override
                public void call(Subscriber<? super RegionItem> subscriber) {
                    subscriber.onError(new Exception("TADA !"));
                }
            })
            .doOnNext(actionNext)
            .doOnError(actionError)
            .doOnCompleted(actionCompleted)
            .subscribe();

In this previous implementation, when I subscribe I trigger the error flow ... and I get an application crash.
The problem is that you HAVE TO manage the error from the subscribe() call. The "doOnError(...)" is just a kind of helper that clone the error and give you a new place to do some action after an error. But it doesn't Handle the error.
So you have to change your code with that :
    Observable.create(new Observable.OnSubscribe<RegionItem>() {
                @Override
                public void call(Subscriber<? super RegionItem> subscriber) {
                    subscriber.onError(new Exception("TADA !"));
                }
            })
            .subscribe(actionNext, actionError, actionCompleted);

Not sure about the real explanation, but this is how I fix it. Hope it will help.

A: .doOnError() is an operator, and is not as such a part of the Subscriber.
Therefore, having a .doOnError() does not count as an implemented onError().
About the question in one of the comments, of course it is possible to use lambdas.
In this case simply replace
.doOnError(throwable -> L.e(TAG, "Throwable " + throwable.getMessage()))
.subscribe(s -> createListView(s, view))

with
.subscribe(s -> createListView(s, view),
    throwable -> L.e(TAG, "Throwable " + throwable.getMessage()))

A: My take is: you are probably using Action1 in
.subscribe(s -> createListView(s, view));

You will need to replace it with Subscriber or Observer which has abstract method onError. This method will be called from subscriber.onError(new Throwable());
EDIT: This is how I would do it. Upon closer look I think the main problem in your code is the early part where you call subscriber.onError even when there's no error. You probably don't need map either because you are technically passing data as-is without manipulation. But I left it in case it is needed later.
     Observable.create(new Observable.OnSubscribe<Application>() {
        @Override
        public void call(Subscriber<? super Application> subscriber) {
            List result = getUserApps();
            if (result != null){
                for (Application app : result){
                     subscriber.onNext(app);
                }
                subscriber.onComplete();
            }else{
                subscriber.onError(new IOException("no permission / no internet / etc"));
               //or if this is a try catch event you can pass the exception
            }
        }
     })
    .subscribeOn(Schedulers.io())//the thread *observer* runs in
    .observeOn(AndroidSchedulers.mainThread())//the thread *subscriber* runs in
    .map(new Func1<Application, String>() {

        // Mapping methods are where data are manipulated.
        // You can simply skip this and
        //do the same thing in Subscriber implementation
        @Override
        public String call(Application application) {
            return application.getName();
        }
    }).subscribe(new Subscriber<String>() {
        @Override
        public void onCompleted() {
           Toast.makeText(context, "completed", Toast.LENGTH_SHORT).show();
           //because subscriber runs in main UI thread it's ok to do UI stuff
           //raise Toast, play sound, etc
        }

        @Override
        public void onError(Throwable e) {
           Log.e("getAppsError", e.getMessage());
           //raise Toast, play sound, etc
        }

        @Override
        public void onNext(String s) {
            listAdapter.add(s);
        }
    });


text:
Q: SSIS Can't Store Decimal Output Into Variable (Execute SQL Task) For the life of me I can't figure out how to store a decimal from a Stored Procedure into an SSIS Variable.
I have an Execute SQL Task that returns a result set. I mapped the column to the variable. I keep getting "Input string was not in a correct format". If I'm returning a decimal from my stored procedure and have the variable type as decimal. I would think this would work, but it doesn't.
Other things I've tried...
- Cast the column as a float and use variable double.
- Cast the column as a varchar and use variable string (succeeded but didn't store value)
- I've done variations on using Output instead of resultset but basically same issues.
Any ideas on how I can get this to work?
Thanks in advance!
As requested here are some screenshots:
This shows the assignment to the variable.

This is showing the variable as a decimal type.

This is showing the error received.

I didn't include the stored procedure but it defines vPreviousValue as a decimal(18,4) and returns it in the result set.

A: In case it may be helpful to someone else in the future...
After trying many variations I was able to figure out how to make this work.
I had the stored procedure output into a 'double' parameter.
I also found this link useful: http://milambda.blogspot.com/2014/02/sql-server-integration-services-data.html


text:
Q: How to Add header to child list in ExpandListVie How to Add header to child list in ExpandListView like this
AvailableTasks       =============     Parent
TaskNo   TaskName    Status
-----------------------------
  1        read      progress      |
-----------------------------      |
  2        listen    pending       |   Childs
-----------------------------      |
  3       walking   started        |
-----------------------------      |

any help is needed urgently, is appreciated

A: in your getChildrenCount you increase to 1 for header of your group like:
@Override
public int getChildrenCount(int groupPosition) {
    return "your children group count" + 1;
}

and in getChildView you check the first child of group and return your header of group like
@Override
public View getChildView(int groupPosition, final int childPosition,
        boolean isLastChild, View convertView, ViewGroup parent) {
    if(childPosition == 0){
         return "your header of group view";
    }
    // your original code here, note that, the childPosition is increased to 1
}

Hope this help.


text:
Q: Undefined symbols for architecture x86_64 - Visual toolkit Compilation (VTK - QT) I'm working in the development of an application in QT, based on the combination of several already existing tools such as: ITK, VTK, DCMTK and SoQT (among others...).
I'm trying to compile this whole mess and after several attempts, I can't help but obtaining this error:

Undefined symbols for architecture x86_64:
  "vtkPolyDataReader::New()", referenced from:
      ModelBuildingControl::extractProfileModels(unsigned int)in ModelBuildingControl.cpp.o
      ModelBuildingControl::loadModel()      in ModelBuildingControl.cpp.o
      vtkPolydata2Points::vtkPolydata2Points()in vtkPolydata2Points.cpp.o
      vtkPolydata2Points::vtkPolydata2Points()in vtkPolydata2Points.cpp.o
  "vtkPolyDataReader::GetOutput()", referenced from:
      ModelBuildingControl::extractProfileModels(unsigned int)in ModelBuildingControl.cpp.o
      vtkPolydata2Points::readSurfaceFromFile(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in vtkPolydata2Points.cpp.o
  "vtkPolyDataReader::SetOutput(vtkPolyData*)", referenced from:
      ModelBuildingControl::loadModel()      in ModelBuildingControl.cpp.o
  "vtkStructuredPointsReader::New()", referenced from:
      ModelBuildingControl::transformVolume()       in ModelBuildingControl.cpp.o
      ModelBuildingControl::transformAtlasInNaturalCOS(QString, QString) in ModelBuildingControl.cpp.o
      ModelBuildingControl::landmarkDist()       in ModelBuildingControl.cpp.o
  "vtkStructuredPointsReader::GetOutput()", referenced from:
      ModelBuildingControl::transformVolume()       in ModelBuildingControl.cpp.o
      ModelBuildingControl::transformAtlasInNaturalCOS(QString, QString) in ModelBuildingControl.cpp.o
  "vtkStructuredPointsWriter::New()", referenced from:
      ModelBuildingControl::transformVolume()       in ModelBuildingControl.cpp.o
      ModelBuildingControl::transformAtlasInNaturalCOS(QString, QString) in ModelBuildingControl.cpp.o
      ModelBuildingControl::buildAtlas()       in ModelBuildingControl.cpp.o
      ModelBuildingControl::exportPatientVolumes()       in ModelBuildingControl.cpp.o
  "vtkWriter::SetInput(vtkDataObject*)", referenced from:
      ModelBuildingControl::transformVolume()       in ModelBuildingControl.cpp.o
      ModelBuildingControl::transformAtlasInNaturalCOS(QString, QString) in ModelBuildingControl.cpp.o
      ModelBuildingControl::warpLensAtlasIntoPatients(std::basic_ofstream<char, std::char_traits<char> >&, vtkPolyData*, QString)in ModelBuildingControl.cpp.o
      ModelBuildingControl::warpScleraAtlasIntoPatients(std::basic_ofstream<char, std::char_traits<char> >&, vtkPolyData*, QString)in ModelBuildingControl.cpp.o
      ModelBuildingControl::landmarkDist()       in ModelBuildingControl.cpp.o
      ModelBuildingControl::buildAtlas()       in ModelBuildingControl.cpp.o
      ModelBuildingControl::exportPatientVolumes()       in ModelBuildingControl.cpp.o
      ...
  "vtkPolyDataWriter::New()", referenced from:
      ModelBuildingControl::warpLensAtlasIntoPatients(std::basic_ofstream<char, std::char_traits<char> >&, vtkPolyData*, QString)in ModelBuildingControl.cpp.o
      ModelBuildingControl::warpScleraAtlasIntoPatients(std::basic_ofstream<char, std::char_traits<char> >&, vtkPolyData*, QString)in ModelBuildingControl.cpp.o
      ModelBuildingControl::landmarkDist()       in ModelBuildingControl.cpp.o
      Points2vtkPolydata::Points2vtkPolydata()in Points2vtkPolydata.cpp.o
      Points2vtkPolydata::Points2vtkPolydata()in Points2vtkPolydata.cpp.o
  "vtkStructuredPointsReader::SetOutput(vtkStructuredPoints*)", referenced from:
      ModelBuildingControl::landmarkDist()       in ModelBuildingControl.cpp.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

Regarding the versions of the software I'm using, they are:
ITK: 4.3.1
VTK: 5.10.1
SoQT: 1.5.1
DCMTK: 3.6.1 (snapshot at 2012-11-02)
So far, I think the error has something to do with the dynamic and static linking of the libraries VTK libraries, as all the files the program is looking for are already there!
Any light you may shed into solving my problem will be more than welcome!!
Thanks in advance!

A: It looks like you are not linking to a few vtk libs like vtkIO. In CMake you can avoid having to specify each vtk lib by adding ${VTK_LIBRARIES} to your TARGET_LINK_LIBRARIES() for the application you are compiling.


text:
Q: Using QGIS, how can I create attributes within a polygon layer based from a selection in that layer? I'd like to add a column, or attribute rather, to selected rows within a polygon layer. I would simply like to make a binary system, where those that are selected receive a "1,' let's say, and all others are represented by a "0." How can I do this?

A: Nevermind- using edit > field calculator > and entering a value for only selected features should do the trick! I can replace NULL values using field calculator from there.


text:
Q: Will open files limit in Centos affect HTTP connections? Does the limit apply to a single session or all sessions? When I do a ulimit -n I got 256, I assume it means I can open 256 files at the sametime.
Does it means I can open 256 files with one single session? or all sessions?
For example, I logined to my server with username "abc" (via putty/ssh), and open 200 files, with the session still running, I logined to the same server again with the same username "abc" (via putty/ssh), I can open only another 56 files? or I can open another 256 files?
Lastly, does this limit also restrict number of http connections? e.g. with the above example, I have opened 200 files, and then I use "wget" or "curl" to make http connections.
Thanks

A: ulimit is a bash builtin, so it applies only to the shell, and particularly any processes created by the current shell. Hence if you change it for any reason you will have to do so in a persistent way.
You might want to checkout the /etc/security/limits.conf file for setting session limits on a per-user basis. (which appears to be the CentOS preferred method)
you can see open files using the lsof -P | grep $somepid command

A: Linux system limits number of open file descriptors per-process.
256 seems enough for most websites, if you use Apache with preforking MPM.
To increase limit you need to add a line to /etc/security/limits.conf to allow processes of some user or group to increase default value. After that PAM will set this to maximum the moment you log in. But that is not enough for Apache, since it doesn't "login".
You will also need to increase this values before starting Apache. In CentOS you can edit your /etc/init.d/apache2 script and put ulimit -n XXXXXX into beggining of  start() function.
You can check limit for running process in file /proc/<PID>/limits, list of open file descriptors is in /proc/<PID>/fd/


text:
Q: Перегрузка оператора "+" в шаблоне Здравствуйте. Столкнулся с проблемой: не могу правильно перегрузить оператор сложения в шаблоне класса. Может кто показать мне мою ошибку? Тип данных массива в шаблоне может быть char,int, float, double. Должно поддерживаться сложение разных типов данных (т.е. если первый объект с параметром int, а второй - с параметром double, то метод должен возвращать объект с параметром double).
#pragma once
template <typename T>
class Vector
{
    T *data;
    size_t size;
public:
    Vector();
    Vector(size_t size);
    ~Vector();
    size_t getSize();
    void SetAll();
    void ClearAll();
    void SetVectorSize(size_t);
    T operator [](int);
    template< typename U >
    Vector & operator+(Vector <U> &B);
};

cpp файл:
#include "stdafx.h"
#include "Vector.h"
#include <typeinfo.h>
#include <iostream>
...
...
template<typename T>
template<typename U>
inline Vector & Vector<T>::operator+(Vector<U>& B)
{
    if (sizeof(this->data[0]) > sizeof(B.data[0]))
    {
        Vector <T> obj;
    }
    else
    {
        Vector <U> obj;
    }
    obj.data[0] = 1;
    return obj;
}

A: Если я верно понял, что вы хотите, то решение примерно такое -
template<typename U>
Vector<common_type_t<T,U>> operator+(const Vector<U>&) const
{
    Vector<std::common_type_t<T,U>> x;
    // складываете, как вам надо .......
    return x;
}

Код
Vector<int> a;
Vector<double> b;
auto c = a+b;
cout << typeid(c).name() << endl;

даст Vector<double>.
И еще - вы должны объявить этот оператор как возвращающий вектор нового типа, а не ссылку - иначе вы по сути вынуждены возвращать ссылку на свой объект, а его тип предопределен.
Update В принципе, можно как-то так - но, как мне кажется, это будет совсем не так красиво:
template<typename U>
auto operator+(const Vector<U>&A) const
{
    Vector<decltype(T(0)+U(0))> x;
    return x;
}

Т.е. даем компилятору самому решить, какой тип имеет сумма, и этот тип используем для типа возвращаемого значения.

A: Например, вот так (C++11):
#include <type_traits>

template<class T, class Enable = void>
class Vector;

template <typename T>
class Vector<T, typename std::enable_if<std::is_integral<T>::value || std::is_floating_point<T>::value>::type>
{
    T *data;
    size_t size;

public:
    Vector(){};
    Vector(size_t _size) : size(_size){}
    ~Vector(){}
    size_t getSize();
    void SetAll();
    void ClearAll();
    void SetVectorSize(size_t);
    T operator [](int);
    Vector<T> operator+ (Vector<T>& B)
    {
        return Vector<T>(size + B.size);
    }
};

int main()
{
    Vector<int> a;
    Vector<int> b;
    a + b;

    return 0;
}