text:
Q: How to register OnClickListner on hyperlink I am using a text view in my aap, which is having plane text as well as a hyperlink. Now when I click on hyperlink then link open with default browser. But in actual I dont want to open default browser. Actually I want to register OnClickListener on hyperlink and want to perform other.
I searched on internet and I got this solution...
Control onclicklistener in autolink enabled textview
But this is not helpful for me.
Anyone can tell me that how I can perform this.
Thanks in advance

A: you can use a Spannable object
final Spannable span = new SpannableString(text);
span.setSpan(new ClickableSpan() {
      @Override
      public void onClick(View v) {

      }
}, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

where text is your hyperlink

A: Remove android:autoLink="web"  if this property setted into XML.
TextView textView =(TextView)findViewById(R.id.textView);
textView.setClickable(true);

when you want to open in browser use this code
textView.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='http://www.google.com'> Google </a>";
textView.setText(Html.fromHtml(text));

if you want to perform some operation register onclick listener for textview and perform.
textView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                }
            });

A: Try doing this add
in your
main.xml
<TextView
       android:id="@+id/yourTVID"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:onClick="performSomeAction" />

in your SomeActivity.java
public void performSomeAction( View v){
//Perform your action
}

A: Try this, it should solve your problem. This method will return a Spannable String which have part of it clickable.
Before calling the below method you should Create CharSequence from the String then convert it to Spannable
CharSequence charSequencce = testView.getText();
    Spannable spannable = (Spannable) charSequencce;

public SpannableStringBuilder addClickToPartsOfString(Spannable charSequence, String[] stringsToAddClick, final OnHyperLinkClickListener onClickListener) {
    SpannableStringBuilder  ssb = new SpannableStringBuilder(charSequence);

    for(final String s : stringsToAddClick) {
        int index1 = charSequence.toString().indexOf(s);
        int index2 = (s.length() + index1);
        ssb.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                onClickListener.onClick(s);
            }
        }, index1, index2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return ssb;
}

A: I've just made a library aiming to simplify this.  See Textoo.  You can achieve the same with code like:
    TextView locNotFound = Textoo
        .config((TextView) findViewById(R.id.view_location_disabled))
        .addLinksHandler(new LinksHandler() {
            @Override
            public boolean onClick(View view, String url) {
                if ("internal://settings/location".equals(url)) {
                    Intent locSettings = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(locSettings);
                    return true;
                } else {
                    return false;
                }
            }
        })
        .apply();

Internally the library converts existing links in your textview / string resources (android system parse html links in string resources into Span for you already) into custom ClickableSpan and capture clicks into calls to your handlers.
This relieve you from having to calculate and hard coding the position of clickable spans to add.  Thus make it easier to externalize your text into string resources and better for localization.


text:
Q: Proccessor is busy all the time I don't really remember when the laptop first started to experienced this problem but the problem is when I open my laptop, I don't know how or why, it is like the laptop is starting to make a dozens of hard calculations.
once I just opened it waited for minutes, without doing something, and it happened again, the laptop is getting warmer and warmer, and fans are starting to make it cooler.
the only tip I can give you guys is I was using BOINC once. but than I moved it to another computer and uninstalled boinc from my laptop. so maybe I could not uninstall it properly and it is still running somewhere in core or something...
thanks advance.
I have:
Intel Core 2 Duo CPU T5450 1.66Ghz x 2***
Intel 965GM x86 MMX SSE2***
32 bit***
Ubuntu 14.04*
here is a random screenshot from system monitor:

A: So we solved the problem with help of top command this way:
sudo killall boinc

sudo apt-get remove --purge boinc*

sudo apt-get update && sudo apt-get upgrade

sudo apt-get autoremove

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to index by 3's in a for loop R I have a matrix that is 39 columns wide and I want to get the average values across rows for the first three columns then next three ect. so I would have 13 columns total after everything was done. Triple would be the indexes I would like to use but it just makes a vector from 1:39.
Triple <- c(1:3, 4:6, 7:9, 10:12, 13:15, 16:18, 19:21, 22:24, 25:27, 28:30, 31:33, 34:36,   37:39)

AveFPKM <- matrix(nrow=54175, ncol=13)
for (i in 1:39){
  Ave <- rowMeans(AllFPKM[,i:i+2])
  AveFPKM[,i] <- Ave
  i+2
}

Thanks for the help

A: With some specifying of dimensions and apply-ing, you can pretty easily get your result. Here's a smaller example:
test <- matrix(1:36,ncol=12)

#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
#[1,]    1    4    7   10   13   16   19   22   25    28    31    34
#[2,]    2    5    8   11   14   17   20   23   26    29    32    35
#[3,]    3    6    9   12   15   18   21   24   27    30    33    36

Now get the mean of each row in each block of three columns:
apply(structure(test,dim=c(3,3,4)),c(1,3),mean)

#     [,1] [,2] [,3] [,4]
#[1,]    4   13   22   31
#[2,]    5   14   23   32
#[3,]    6   15   24   33

Or generally, assuming your number of columns is always exactly divisible by the group size:
grp.row.mean <- function(x,grpsize) {
  apply(structure(x,dim=c(nrow(x),grpsize,ncol(x)/grpsize)),c(1,3),mean)
}
grp.row.mean(test,3)

A: Here's a solution using sapply, taking advantage of the fact we know the number of columns is exactly a multiple of 3:
sapply(1:13, function(x) {
  i <- (x-1)*3 + 1    # Get the actual starting index
  rowMeans(AveFPKM[,i:(i+2)])
})


text:
Q: Objective C Alarm local notification I have developed one application for alarm. I have used local notification with cancel and snooze alert buttons. Its working fine, but when application is offline how to set snooze?
I mean, how to open my app when the local notification is executed (so the user can snooze it)?

A: That's a problem with UILocalNotification. When it's executed, you can't open your app without the user authorization. Have you ever checked some alert app to iOS? You need to lets it open all night.
When the applicationDidEnterBackground method is called, you can set a local notification into 5 seconds, so you can alert your users to let your app opened.
Another way: You can set the local notification button to "snooze" and when the user presses it, your app's opened. Doing this, the didFinishLaunchingWithOptions method returns you if the user "snooze" it.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotif)
    {
        // The user snooze the alert. Insert another local notification here.
    }

    return YES;
}


text:
Q: Show 'Date created' in windows explorer through registry or other GPO how i want it to look
I essentially want to deploy this to all users and all folders via the GPO, so all folders opens as a list and shows the date it was created as well. What ever solution to make it possible would make me happy.
The closest i am is that something has to change here Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
but i dont know what


text:
Q: How to run a program without typing the full path? System utilities such as ls don't need to have the full path typed before executing them. However, to execute Netbeans, I have to type /home/chris/netbeans-7.0.1/bin/netbeans. How can I make it so that I only have to type netbeans?

A: An easy way is to place a link in /usr/local/bin:
sudo ln -s -T /home/chris/netbeans-7.0.1/bin/netbeans /usr/local/bin/netbeans

after that you can execute netbeans with:
netbeans &

A: You can add an alias
Open Terminal Ctrl+Alt+T
nano ~/.bashrc

write this at the bottom of the file:
alias netbeans='/home/chris/netbeans-7.0.1/bin/netbeans'

Ctrl + x
Y
Enter
The netbeans word is the command you will use to start the program, you can change it to whatever you need. Inside the quotes is the command you want to run when netbeans alias is called.
In order this command to be active you have to re-open the Terminal, or type
. ~/.bashrc

A: *

*go to the program directory.

*open the terminal using ctrl+alt+T.

*Drag and drop the program file to the terminal  windows.

*Hit enter on the terminal windows.


text:
Q: How-to restrict AWS IAM User to be able execute "SSM Run Commands" on a specific EC2 server I am trying to setup and assign a policy so that a user can only trigger AWS Systems Manager Services (SSM) Run Commands on only authorized or assigned EC2 instances to them.
To do this, I am following instructions from https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sysman-configuring-access-iam-create.html and as per it, I created below custom policy with provisioning access for only 1 EC2 instance:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "ssm:ListDocuments",
                "ssm:DescribeDocument*",
                "ssm:GetDocument",
                "ssm:DescribeInstance*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        },
        {
            "Action": "ssm:SendCommand",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0",
                "arn:aws:s3:::test-ssm-logs/TESTSERV",
                "arn:aws:ssm:us-east-1:123456789012:document/AWS-RunPowerShellScript"
            ],
            "Condition": {
                "StringEquals": {
                    "ec2:ResourceTag/Name": "TESTSERV"
                }
            }
        },
        {
            "Action": [
                "ssm:CancelCommand",
                "ssm:ListCommands",
                "ssm:ListCommandInvocations"
            ],
            "Effect": "Allow",
            "Resource": "*"
        },
        {
            "Action": "ec2:DescribeInstanceStatus",
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

After I assigned above policy to a test user and when I log in using it and navigate to "Run Command", under Target Instances I see other EC2 instances as well and I am even able to execute commands to them as well. Shouldn't the user only see the 1 instance that is specified in above policy?
I do not understand what am I doing wrong here and how to fix it? Appreciate your help.
Thanks!

I have below IAM policy assigned to all my EC2 system instances:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:DescribeAssociation",
                "ssm:GetDeployablePatchSnapshotForInstance",
                "ssm:GetDocument",
                "ssm:GetParameters",
                "ssm:ListAssociations",
                "ssm:ListInstanceAssociations",
                "ssm:PutInventory",
                "ssm:UpdateAssociationStatus",
                "ssm:UpdateInstanceAssociationStatus",
                "ssm:UpdateInstanceInformation"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2messages:AcknowledgeMessage",
                "ec2messages:DeleteMessage",
                "ec2messages:FailMessage",
                "ec2messages:GetEndpoint",
                "ec2messages:GetMessages",
                "ec2messages:SendReply"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "cloudwatch:PutMetricData"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeInstanceStatus"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ds:CreateComputer",
                "ds:DescribeDirectories"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:DescribeLogGroups",
                "logs:DescribeLogStreams",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:AbortMultipartUpload",
                "s3:ListMultipartUploadParts",
                "s3:ListBucketMultipartUploads"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": "arn:aws:s3:::amazon-ssm-packages-*"
        }
    ]
}

Also, I have below IAM policy assigned to test user to so that they can  Start/Stop/Restart EC2 instances:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:Describe*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:StartInstances",
                "ec2:StopInstances",
                "ec2:RebootInstances"
            ],
            "Resource": "arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0",
            "Condition": {
                "StringEquals": {
                    "ec2:ResourceTag/Name": "TESTSERV"
                }
            }
        }
    ]
}

A: I was able to make this work by adjusting policy as below:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "ssm:ListDocuments",
                "ssm:DescribeDocument*",
                "ssm:GetDocument",
                "ssm:DescribeInstance*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        },
        {
            "Action": "ssm:SendCommand",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0",
                "arn:aws:s3:::nsight-ssm-logs/TESTSERV",
                "arn:aws:ssm:us-east-1::document/AWS-RunPowerShellScript"
            ]
        },
        {
            "Action": [
                "ssm:CancelCommand",
                "ssm:ListCommands",
                "ssm:ListCommandInvocations"
            ],
            "Effect": "Allow",
            "Resource": "*"
        },
        {
            "Action": "ec2:DescribeInstanceStatus",
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

My requirement was to only allow execution of PowerShell scripts so the line:

"arn:aws:ssm:us-east-1::document/AWS-RunPowerShellScript"

You can replace AWS-RunPowerShellScript with * to allow all commands.
Also, the EC2 Role assignment was necessary since without it I couldn't see any instances under Run Command.
Please also know that the user would see all instances under Run Command but will only be able to execute commands for the EC2 instances for which the policies are assigned to, user account. I do not think there is any option to suppress this.
Thanks for your contribution and helpful tips.


text:
Q: Why does GPG decryption with subkeys fail on one computer but not another? I have been attempting to create a system of GPG subkeys to distribute to my various computers. I have created subkey pairs for each computer with the master secret key removed as per the instructions here and here. I have the distributed the relevant .gnupg folders to my computers via scp. I am then testing these by attempting to access my pass database. The keypair folder I sent to my laptop works fine and decrypts my passwords, but the one I sent to another headless system does not, and when I attempt to show a password I get the follwoing error message:

gpg: decryption failed: No secret key

If I try using the same subkey pair .gnupg folder -  the one intended for the headless box -  on my laptop, it works fine to decrypt.
All systems run Arch Linux and the same versions of gnupg 2.1.8 and pass 1.6.5.
Can anyone suggest why the subkeys don't work to decrypt on my headless system?

A: Ok, so it turns out the use of pass was a red herring. I tried simply encrypting a document and then attempting to decrypt it. With the -v flag this showed that the problem was with the pinentry agent. So with the instructions from the answer here. I have now got it working with pinentry-curses.


text:
Q: Is creating multiple PouchDB databases on the same application considered bad design? I come from a Mysql background and I'm using Pouchdb now. I'm used to the SQL pattern of having 1 database and many tables per app.
In pouchDB it's different, because data is not stored in tables but in documents. So, in my app, I have a database for tasks, created with:
var db = new PouchDB('tasks', {revs_limit: 1, auto_compaction: true});

This is the main database for my application, but now I need to also store settings, such as "last_visit_date", "language_preference" and others.

So, I have 2 questions:

*

*Should I create only one database and then store different data
sets in sub objects or can I create multiple databases to store this data Are there any drawbacks on the second option?

*I haven't gotten into syncing with cloudant or couchdb yet, but I will have to in the future. If I have 2 databases (or more) will it make the sync process more complicated, slower or worse somehow?

A:
Is creating multiple PouchDB databases on the same application considered bad design?

In a word: No.
Long answer: Databases in CouchDB/PouchDB are essentially free. And some application designs require multiple databases.
Consider a theoretical Offline-first/mobile app which tracks an agent's sales.  It may have a database for inventory management purposes, which is synchronized with a central CouchDB server.
It will likely also have a per-agent database, with client and sales info for a given agent.
The PouchDB app will need both databases. And due to the design of CouchDB, there's no (easy, sane) way to keep those data sets in the same database, and keep agent's records separate from each other.
Databases in CouchDB/PouchDB are more like tables than databases in an RDBMS.
The only real limiting factor for creating additional databases in PouchDB (which doesn't apply to CouchDB), is that there's no easy way to list your existing databases, except with the use of plugin.  This needn't be a real limitation--it just means you need to remember which databases you've created (you probably shouldn't be programatically creating randomly-named databases... but that would probably be a bad design anyway. ;-) )


text:
Q: how to add activation rule as a contextual add-in when email body has a Link how to add activation rule as a contextual add-in when email body has a Link as fallowing

 Message

and this rule does not work as contextual add-in
>     <Rule xsi:type="ItemIs" FormType="Read" ItemType="Message" />
>         <Rule xsi:type="ItemHasRegularExpressionMatch" PropertyName="BodyAsHTML" RegExName="BodyFilter"
> RegExValue="https://www\.abcedf\.com/go"  />

A: In regular expressions slashes ("/") are delimiters, so you need to escape them:
https:\/\/www\.abcedf\.com\/go

By the way, this regular expression is trivial - it looks like all you want to do is an exact string match.

A: Unfortunately, contextual highlighting is not supported in the scenario you have mentioned.
please refer to https://dev.office.com/docs/add-ins/outlook/contextual-outlook-add-ins, the section header How to launch a contextual add-in
specifically, it states that the addin will show in the bar instead if either of these 2 conditions are true.

-When the entity is a URL or an email address
-When the add-in manifest has a rule with type="ItemHasRegularExpressionMatch" and PropertyName="BodyAsHTML" or
  PropertyName="SenderSMTPAddress"

If you would like your addin to appear in the bar instead, I would recommend confirming your regex using some regex testing tool, then when you are confidant it is correct, try modifying the manifest.

A: For scenarios like this you can use the ItemHasKnownEntity rule. "Known Entities" are pre-defined elements that Outlook recognized automatically. It saves you from having to build complex regular expressions that are both hard to write and even harder to debug.
The ItemHasKnownEntity rule for the above URL might be
<Rule xsi:type="ItemHasKnownEntity"
EntityType="Url"
RegExFilter="abcdef"
FilterName="abcdef"
IgnoreCase="true" />


text:
Q: How to minimize auth requests for Sheets add-on I'm building an addon using the "new" Sheets AddOn API. The addon creates a menu with two subitems, "For Owner" and "For Viewers". Clicking on "For Owner" opens a sidebar with some functionality that checks if the user is the sheet owner. If so, the user can post some of the sheet data to an external service. Clicking on "For Viewers" opens a sidebar that fetches and displays data from the external service.
I understand that when the owner enables the add-on, a number of auth permissions are going to be requested based on the various features used by the code. However, when a viewer accesses the add-on, far less functionality is actually available to them in that code path. Yet, they get asked for all the same auth permissions.
So the question is --- how should I structure this so that the sheet viewers get prompted for the minimal auth permissions without limiting the richness of the feature for the owner function?

A: The only way to do this is to make two add-oms one for owners and one for viewers. Apps script does not currently support selective permissions.


text:
Q: Unable to update xml file using xmlstarlet with xml tag attribute I am unable to update following xml file due to tag attribute, xmlns (namespace)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<advertiserFeatures
xmlns:doc="http://api.homeaway.com/service/v1"
xmlns="http://api.homeaway.com/domain/v0" etag="33054400302" url="/advertisers/0024/e74510aa-d4f0-4509-8c48-7c101e6f021c/features">
<parentEntity href="/advertisers/0024/e74510aa-d4f0-4509-8c48-7c101e6f021c" rel="parentEntity"/>
<advertiseVasCart>true</advertiseVasCart>
<agentAssistedCheckout>true</agentAssistedCheckout>
<dcfEnabled>false</dcfEnabled>
<enhancedDistribution>false</enhancedDistribution>
<inserted>2016-02-12T15:38:58.977Z</inserted>
<travelerFeeEnabled>true</travelerFeeEnabled>
<updated>2016-02-12T15:38:58.977Z</updated>

I can update with following command if I remove that attribute
xmlstarlet ed -u "/advertiserFeatures/advertiseVasCart" -v "false" advertiserFeatures.xml > advertiserFeatures1.xml

Any idea what am I missing?

A: You need to bind a prefix to the default namespace URI, and then use that prefix in your XPath to address elements in the corresponding namespace :
xmlstarlet ed -N x="http://api.homeaway.com/domain/v0" \
    -u "/x:advertiserFeatures/x:advertiseVasCart" \
    -v "false" advertiserFeatures.xml > advertiserFeatures1.xml

For further reading : xmlstarlet documentation on 'Namespaces and default namespace'


text:
Q: Windowless tray icon application 2 This is the continuation of Windowless tray icon application
I finally got to do what I want with this tray icon that is:
1. icon in the tray
2. click open small tray windows
3. click on tray window open main window
The only issue is that I want the small intermediate window start far away the tray. I would liket it to be near the tray icon who has launched it as shown in the following pic.

The code for the tray icon (launched from the mainwindow) is:
 var tim = new TrayIconMenuWindow.TrayIconMenuWindow();
 tim.WindowStartupLocation = WindowStartupLocation.CenterOwner;<------
 tim.ShowDialog();
 this.Visibility = Visibility.Visible;

I have tried all startuplocations but none helped.
Thanx

A: If you want the window in the bottom right of the screen, you may use something like this:
Rectangle workingArea = Screen.GetWorkingArea(this);
this.Location = new Point(workingArea.Right - Size.Width,
                                  workingArea.Bottom - Size.Height);

Edit
I just realized you are working in WPF. If that's the case,use this code:
var screenSize = System.Windows.SystemParameters.WorkArea;
this.Left = screenSize.Right - this.Width;
this.Top = screenSize.Bottom - this.Height;

A: If you expect a window to show up next to the NotifyIcon like a ContextMenuStrip associated to the NotifyIcon, you will need to obtain the exact location of the NotifyIcon in the screen and then adjust the window's location. You can find an example in:

*

*rzhw/SuperNotifyIcon
It's quite lengthy but the code to get the location of a NotifyIcon can be shorter like this:
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;

public static class NotifyIconRect
{
    #region Win32

    [DllImport("Shell32.dll", SetLastError = true)]
    private static extern int Shell_NotifyIconGetRect(
        [In] ref NOTIFYICONIDENTIFIER identifier,
        out RECT iconLocation);

    [StructLayout(LayoutKind.Sequential)]
    private struct NOTIFYICONIDENTIFIER
    {
        public uint cbSize;
        public IntPtr hWnd;
        public uint uID;
        public GUID guidItem; // System.Guid can be used.
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct GUID
    {
        public uint Data1;
        public ushort Data2;
        public ushort Data3;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
        public byte[] Data4;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;

        public static implicit operator Rect(RECT rect)
        {
            if ((rect.right - rect.left < 0) || (rect.bottom - rect.top < 0))
                return Rect.Empty;

            return new Rect(
                rect.left,
                rect.top,
                rect.right - rect.left,
                rect.bottom - rect.top);
        }
    }

    #endregion

    public static Rect GetNotifyIconRect(NotifyIcon notifyIcon)
    {
        NOTIFYICONIDENTIFIER identifier;
        if (!TryGetNotifyIconIdentifier(notifyIcon, out identifier))
            return Rect.Empty;

        RECT iconLocation;
        int result = Shell_NotifyIconGetRect(ref identifier, out iconLocation);

        switch (result)
        {
            case 0: // 0 means S_OK.
            case 1: // 1 means S_FALSE.
                return iconLocation;
            default:
                return Rect.Empty;
        }
    }

    private static bool TryGetNotifyIconIdentifier(NotifyIcon notifyIcon, out NOTIFYICONIDENTIFIER identifier)
    {
        identifier = new NOTIFYICONIDENTIFIER { cbSize = (uint)Marshal.SizeOf(typeof(NOTIFYICONIDENTIFIER))    };

        int id;
        if (!TryGetFieldValue(notifyIcon, "id", out id))
            return false;

        NativeWindow window;
        if (!TryGetFieldValue(notifyIcon, "window", out window))
            return false;

        identifier.uID = (uint)id;
        identifier.hWnd = window.Handle;
        return true;
    }

    private static bool TryGetFieldValue<T>(object instance, string fieldName, out T fieldValue)
    {
        fieldValue = default(T);

        var fieldInfo = instance.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
        if (fieldInfo == null)
            return false;

        var value = fieldInfo.GetValue(instance);
        if (!(value is T))
            return false;

        fieldValue = (T)value;
        return true;
    }
}

This code is a little tricky because it gets private field values of a NotifyIcon by reflection but I don't know any other way to accomplish this operation.


text:
Q: Issue regarding Retrieving data from FMDB Database In my IOS app I am using FMDB Database to store data. I am having problem while retrieving data. Actually in last page of my app, when i click on "sendtowatch" button, the data should be saved and at the same time it should be retrieved so that the data can be displayed in my watch app. The screenshot of my running app is below .My source code below is
screenshot of my running app screenshot
 @IBAction func sendToWatch(sender: AnyObject) {

    let ticketDB = FMDatabase(path: databasePath as String)
    if ticketDB.open()
    {

        let insertSQL = "INSERT INTO TICKET (image, ticket_category, ticket_type, date, time) VALUES ('\(display_image.image!)', '\(ticket_category.text!)', '\(ticket_type_name.text!)', '\(ticket_date.text!)', '\(ticket_time.text!)')"

        let result = ticketDB.executeUpdate(insertSQL,withArgumentsInArray: nil)

        if !result
        {

            print("Error: \(ticketDB.lastErrorMessage())")

        } else
        {

            let alt = PMAlertController(title: "Success!", description: "Your data is saved to Database!", image: UIImage(named: ""), style: .Alert)

            alt.addAction(PMAlertAction(title: "OK!", style: .Default, action: { (ACTION) -> Void in

                let ticketDB = FMDatabase(path: self.databasePath as String)
                if ticketDB.open()
                {

                    let querySQL = "SELECT * FROM TICKET"

                    let result: FMResultSet? = ticketDB.executeQuery(querySQL, withArgumentsInArray: nil)

                    if let result = result
                    {
                        self.ticketDataArray = NSMutableArray()
                        while result.next()
                        {
                            let ticketInfo = NSMutableDictionary()

                           ticketInfo.setObject(result.stringForColumn("image"), forKey: "image")
                            ticketInfo.setObject(result.stringForColumn("ticket_category"), forKey: "ticket_category")
                            ticketInfo.setObject(result.stringForColumn("ticket_type"), forKey: "ticket_type")
                            ticketInfo.setObject(result.stringForColumn("date"), forKey: "date")
                            ticketInfo.setObject(result.stringForColumn("time"), forKey: "time")
                            self.ticketDataArray.addObject(ticketInfo)

                        }

                    }else{
                       print("Error: \(ticketDB.lastErrorMessage())")

                    }

                ticketDB.close()

                }

            }))

            self.presentViewController(alt, animated: true, completion: nil)
            print(databasePath)

        }
    }

 }

 }

A: May this will help you
let select_query = "SELECT * FROM TICKET WHERE image=' size {400, 400} orientation 0 scale 1.000000' AND ticket_category='Bus' AND ticket_type='sssss' AND date='Aug 20, 2016' AND time='12:14 PM'"


text:
Q: Voltage Multiplier - Cockcroft-Walton Capacitance Value I want to design a circuit in order to Harvest radio-frequency (RF) signals and get a DC Output to a specific load (i.e micro Watt Battery of a sensor).

Notes to be considered :

*

*input will be between (uV - mV) which is low.

*frequency that i am harvesting from is the GSM frequency which is 900-915 MHz

*considering this frequency value the capacitance should be really small (pico or nano farads)

During my research i have found that the most used step-up (In terms of Voltage) configurations are mainly three types which are :
1- Transformer Topology (Which is the cheapest and less efficient for such application)
2-Diodes : Rectifiers (Which I am not interested in due to losses)
3-Voltage Doubler/ Multiplier (Which consists of diodes and capacitors such like >> Cockcroft-Walton or any other configuration)
Now the thing is that there are a lot of types of the voltage multiplier, but I could not find any certain reference that can help me through the design of the Voltage multiplier.
For example how to calculate the capacitance values lets say for multi-stage multiplier with N Stages and Vin to Vout specific ratio ?
Such as :
Vin  = 1V
Vout = 5V
N = 5-10 stages (or more depending on the output)

Cockcroft-Walton Topology with 2 stages.
Any advice will be much appreciated

A: Start at a minimum of 10uW/cm² or -20dBm/cm²  or 5 mV/mm E-field.
Needs impedance matched antenna complete circuit
Use a tuned rectangular patch antenna or rectenna with impedance matching network then  smallest Cockcroft–Walton doublers into an open loop *with π/4 to  π/2 radius..errhm I meant  λ/4 to  λ/2 radius... with suitable transmission line impedance matching striplines and at least 10 stages.
Need variable f generator
to measure s21 or DC out with f input
Another method is use Bennet doubler using  e-VEH with a motion of 5mm_DA at low frequency ( e.g. 10~30 Hz) to demodulate the steady amplitude RF field.
Sch. Diodes must be low C and ESL
Low parasitic impedance: C< 0.05 pF, Ls < 0.2 nH
Dielectric substrate must be low loss tangent
like ceramic, teflon or  special polyamide or https://plastics.ulprospector.com/datasheet/e120881/arlon-25n
must be small SMT for diode low pF for loop antenna
like 0201 SMD suitable for >>10GHz to prevent C divider loading and great efficiency.
Choose largest RF cap possible in smallest package  e.g 0201 if possible.

*

*use reputable suppliers with s parameters like Murata, TDK etc.

*must be very low loss tangent NPO type material or better ceramic

*Consider 50~100pF  with much higher SRF.

Expect 1V at maybe >> -15dBm and 3.3V at -5dBm with > 10 stages
other

*

*There is always an optimum limit to n- stage doublers based on impedance ratios and loads, leakage.

*plan on $200 budget for proto unless you get free samples for all materials. (ha!)


text:
Q: Eigenvalue of first order nonlinear differential equation How to solve for the eigenvalues of equation $$(\partial_x+1-iay)y=\lambda y$$
where y is a function of x, a is a real parameter, $\lambda$ is the eigenvalue.

A: $y' + (1-iay)y = \lambda y$
$y' = \left((\lambda-1 )+iay\right)y$
$\frac{1}{\left((\lambda-1 )+iay\right)y}\frac{\partial y}{\partial x} = 1$
$\left[\frac{1}{y}+\frac{-ia}{(\lambda-1 )+iay}\right]\frac{\partial y}{\partial x}=\lambda-1$
$\ln y - \ln\left((\lambda - 1)+iay)\right)=(\lambda-1)x + C$
$\frac{y}{(\lambda - 1)+iay}=Ce^{(\lambda-1)x}$
$y=\frac{(\lambda - 1)Ce^{(\lambda-1)x}}{1-iaCe^{(\lambda-1)x}}$


text:
Q: PHP - number of month from date I'm trying to get the number of a month from a date using this:
$newDate = date("Y-m-d", strtotime('2014-05-04'));
$Month = date('n', $newDate);
echo $Month;

It returns 1 (this is January...) How is this possible? It should return 0.
I used the date format because of that thread:
PHP: date function to get month of the date
I hope somebody can help me.
Thanks in advance
shivan

A: $Month = date('m', strtotime('2014-05-04'));
you can get the month like this

A: For datetime operation you should use DateTime class in PHP
$date = new DateTime('2014-05-04');
echo $date->format('n');


text:
Q: Завершение дочерних потоков при завершении родительского Здравствуйте. У меня такая проблема - требуется завершать дочерние потоки, если прерывается поток, который их породил. Родительский поток живет пока работают дочернее, используя join(). Дочерние потоки используют в run() - while (!Thread.currentThread.isInterrupted), то есть фактически бесконечные. Задача - прерывать дочерние потоки при прерывании родительского, при этом не объявляя дочерние потоки как демоны.
A: Когда я сталкивался с подобной задачей я решал ее так:
В дочернем потоке было булевское поле running со стандартными get и set методами, значение которого периодически проверялось. Когда родительский поток заканчивал работу, он вызывал метод setRunning(false). При очередной проверке, дочерний поток, увидев, что running == false, выходил из бесконечного цикла и заканчивал работу.
Добавил пример кода дочернего потока.
public class A extends Thread{
    private boolean running;
    public A(){
        running = true;
    }
    public synchronized void setRunning(boolean r){
        running = r;
    }
    public void run(){
        while(!Thread.currentThread.isInteruped())
            if(!running)
                break;
    }
}

A: вам нужен вариант реализации шаблона Observer (вариант Б в чистом виде)
(вариант А немножко скован тем что обьект потока создается внутри метода, поэтому добавлен Runnable в качестве параметра. можно сделать и с помощью generic, тогда ваш класс MainThread будет более универсален)
class MainThread extends Thread
{
   private final Set < Thread > children = null;

   // variant A
   public Thread createChild ( final Runnable runnable )
   {
      final Thread t = new Thread ( runnable );

      // optional
      // t.start ();

      children.add ( t );

      return t;

   }

   @Override
   public void interrupt ()
   {
      removeAll ();

      super.interrupt ();
   }

   // variant B
   protected void add ( final Thread child )
   {
      if ( ( null != child ) && !children.contains ( child ) )
      {
         children.add ( child );
         child.start ();
      }
   }

   protected void remove ( final Thread child )
   {
      if ( children.contains ( child ) )
      {
         children.remove ( child );
         child.interrupt ();
      }
   }

   protected void removeAll ()
   {
      final Iterator < Thread > iterator = children.iterator ();
      while ( iterator.hasNext () )
      {
         iterator.next ().interrupt ();
      }
   }
}

class ChildThread extends Thread
{
   public ChildThread ( final MainThread parent )
   {
      parent.add ( this );
   }

   public void interrupt()
   {
       if (isRunning)
       {
           isRunning = false;
       }
   }

   public void run()
   {
       if (!isRunning)
       {
           super.interrupt();
           return;
       }

       // полезный код... если ChildThread и runImpl сделать абстрактными
       // то получится еще и красиво :)
       runImpl();
   }
}

UP: согласно пожеланиям публики убрал грубый interrupt :D
A: Попробуйте посмотреть в сторону CyclicBarrier


text:
Q: How can I match text that precedes an `` tag then return the `` node? I have the following, where I am trying to only capture the second case, where the text matches But I want this one here. Currently, it captures both cases.
package main

import (
    "bytes"
    "fmt"
    "io"
    "strings"

    "golang.org/x/net/html"
)

func getTag(doc *html.Node, tag string) []*html.Node {
    var nodes []*html.Node
    var crawler func(*html.Node)
    crawler = func(node *html.Node) {
        if node.Type == html.ElementNode && node.Data == tag {
            nodes = append(nodes, node)
            return
        }
        for child := node.FirstChild; child != nil; child = child.NextSibling {
            crawler(child)
        }
    }
    crawler(doc)
    return nodes
}

func main() {
    doc, _ := html.Parse(strings.NewReader(testHTML))
    nodes := getTag(doc, "a")

    var buf bytes.Buffer
    w := io.Writer(&buf)
    for i, node := range nodes {
        html.Render(w, node)
        if i < (len(nodes) - 1) {
            w.Write([]byte("\n"))
        }
    }

    fmt.Println(buf.String())
}

var testHTML = `
I do not want this link here link text
But I want this one here more link text
`

This outputs:
link text
more link text
I would like to match specific text that precedes an  tag and, if it matches, return the  node. For instance, pass in But I want this one here and it returns more link text. I've been told to not parse html with regex but now I am stuck.

A: You're actually pretty close, because you are already using a proper parser (html.Parse from golang.org/x/net/html).
The trick here is that the various elements of the page are bound together conveniently, so you can use your existing crawler code with a later filtering function, if you like.  (You could instead combine the filtering directly into the crawler.)
Each n *html.ElementNode is preceded by something unless it's the initial element in a block (first of a document or first child node), and that something is in n.PrevSibling.  If its type is html.TextNode you have a sequence of the form:
some textthing

and you can examine the "some text" in the previous node:
func wanted(re *regexp.Regexp, n *html.Node) bool {
    if n.PrevSibling == nil || n.PrevSibling.Type != html.TextNode {
        return false
    }
    return re.MatchString(n.PrevSibling.Data)
}

This won't be perfect, because you could have, e.g.:
text  broken uplast link

and the code will try to match against the string up, when you probably should put the text together into text broken up and pass that to the matcher.  See more complete example here.


text:
Q: How to disable Google Tag Manager console logging After I added Google Tag Manager to the project I see lots its log entries in the console. Is there a way to disable it? Console log is full of noise:
GoogleTagManager info: Processing logged event: _vs with parameters: {
    "_o" = auto;
    "_pc" = UIViewController;
    "_pi" = "-3988739357756819671";
    "_sc" = "Bubbie.MamboBamboViewController";
    "_si" = "-3988739357756819670";
}
2017-07-27 12:01:09.744 BubbieHuff[77205:6894827] GoogleTagManager info: Processing logged event: show_view with parameters: {
    "_sc" = "Bubbie.MamboBamboViewController";
    "_si" = "-3988739357756819670";
    name = Mambo;
}

A: Swift 3 version of Scoud's solution:
static func hideGTMLogs() {
    let tagClass: AnyClass? = NSClassFromString("TAGLogger")

    let originalSelector = NSSelectorFromString("info:")
    let detourSelector = #selector(AppDelegate.detour_info(message:))

    guard let originalMethod = class_getClassMethod(tagClass, originalSelector),
        let detourMethod = class_getClassMethod(AppDelegate.self, detourSelector) else { return }

    class_addMethod(tagClass, detourSelector,
                    method_getImplementation(detourMethod), method_getTypeEncoding(detourMethod))
    method_exchangeImplementations(originalMethod, detourMethod)
}

@objc
static func detour_info(message: String) {
    return
}

A: You didn't specify the language. Warning level would seem enough in your case.
// Optional: Change the LogLevel to Verbose to enable logging at VERBOSE and higher levels.
[self.tagManager.logger setLogLevel:kTAGLoggerLogLevelVerbose];

Available levels (docs):

*

*kTAGLoggerLogLevelVerbose

*kTAGLoggerLogLevelDebug

*kTAGLoggerLogLevelInfo

*kTAGLoggerLogLevelWarning

*kTAGLoggerLogLevelError

*kTAGLoggerLogLevelNone

From the official docs:
https://developers.google.com/tag-manager/ios/v3/#logger (deprecated in favor of Firebase Analytics)

A: After a lot of digging, I managed to find a way to disable warning and error logs (not info logs unfortunately) in Google Tag Manager v7.0.0.
Code below is written in Swift 5:
static func turnOffGTMLogs() {

        let tagClass: AnyClass? = NSClassFromString("TAGJSExportedInstructions")

        guard
            var properties = class_copyMethodList(tagClass, nil)
            else { return }

        let detourSelector = #selector(FirebaseInitializer.detour_logMessage(with:message:))
        var pointed = properties.pointee
        while(!pointed.isNil()) {
            if method_getName(pointed).coreStoreDumpString.contains("logMessage") {
                guard let detourMethod = class_getClassMethod(FirebaseInitializer.self, detourSelector) else { return }
                let _ = class_replaceMethod(tagClass, method_getName(pointed), method_getImplementation(detourMethod), method_getTypeEncoding(pointed))
                break
            }
            properties = properties.advanced(by: 1)
            pointed = properties.pointee
        }
    }

@objc
static func detour_logMessage(with level: Int, message: String) {
    return
}

Extension for opaque pointer:
private extension OpaquePointer {
/*Used to check if value pointed by the opaque pointer is nil (to silence compiler warnings as self == nil would also work)
It works by figuring out whether the pointer is a nil pointer, from it's debug description .*/
func isNil() -> Bool {
    return !self.debugDescription.contains { "123456789abcdef".contains($0.lowercased()) }
}

After that you only need to call turnOffGTMLogs() once (preferably in the same place where you initialise GTM, usually in AppDelegate) to silence the log outputs.

A: Here's a cleaned up version for Swift 5 as a class you can use in your AppDelegate like this:
GoogleTagManagerHelper.hideGTMLogs()

import Foundation

internal final class GoogleTagManagerHelper {

    enum LogLevel: String, CaseIterable {
        case info = "info:"
        case warning = "warning:"
    }

    static func hideGTMLogs() {
        LogLevel.allCases.forEach { hideGTMLogs(for: $0) }
    }

    static func hideGTMLogs(for level: GoogleTagManagerHelper.LogLevel) {
        let tagClass: AnyClass? = NSClassFromString("TAGLogger")
        let originalSelector = NSSelectorFromString(level.rawValue)
        let detourSelector = #selector(detour_log(message:))
        guard
            let originalMethod = class_getClassMethod(tagClass, originalSelector),
              let detourMethod = class_getClassMethod(GoogleTagManagerHelper.self, detourSelector)
        else { return }
        class_addMethod(
            tagClass,
            detourSelector,
            method_getImplementation(detourMethod),
            method_getTypeEncoding(detourMethod)
        )
        method_exchangeImplementations(originalMethod, detourMethod)
    }

    @objc static func detour_log(message: String) { return }
}

A: I just had this problem in a project that combines Google Tag Manager and Firebase. Since no header about logging is exposed I couldn't find a way to turn it off.
This is a monkey patch I came up with that lets you control the info logs from GTM.
+ (void)patchGoogleTagManagerLogging {

    Class class = NSClassFromString(@"TAGLogger");

    SEL originalSelector = NSSelectorFromString(@"info:");
    SEL detourSelector = @selector(detour_info:);

    Method originalMethod = class_getClassMethod(class, originalSelector);
    Method detourMethod = class_getClassMethod([self class], detourSelector);

    class_addMethod(class,
                    detourSelector,
                    method_getImplementation(detourMethod),
                    method_getTypeEncoding(detourMethod));

    method_exchangeImplementations(originalMethod, detourMethod);
}

+ (void)detour_info:(NSString*)message {
    return; // Disable logging
}

A: In Swift 5, to silent info & warning logs from GTAG automatically, just insert & call those two methods in your app delegate (hideGTMLogsInfo() & hideGTMLogsWarning()):
static func hideGTMLogsInfo() {
    let tagClass: AnyClass? = NSClassFromString("TAGLogger")

    let originalSelector = NSSelectorFromString("info:")
    let detourSelector = #selector(AppDelegate.detour_info(message:))

    guard let originalMethod = class_getClassMethod(tagClass, originalSelector),
        let detourMethod = class_getClassMethod(AppDelegate.self, detourSelector) else { return }

    class_addMethod(tagClass, detourSelector,
                    method_getImplementation(detourMethod), method_getTypeEncoding(detourMethod))
    method_exchangeImplementations(originalMethod, detourMethod)
}

static func hideGTMLogsWarning() {
    let tagClass: AnyClass? = NSClassFromString("TAGLogger")

    let originalSelector = NSSelectorFromString("warning:")
    let detourSelector = #selector(AppDelegate.detour_warning(message:))

    guard let originalMethod = class_getClassMethod(tagClass, originalSelector),
        let detourMethod = class_getClassMethod(AppDelegate.self, detourSelector) else { return }

    class_addMethod(tagClass, detourSelector,
                    method_getImplementation(detourMethod), method_getTypeEncoding(detourMethod))
    method_exchangeImplementations(originalMethod, detourMethod)
}

@objc
static func detour_warning(message: String) {
    return
}
@objc
static func detour_info(message: String) {
    return
}


text:
Q: How to recover deleted file if it is still opened by some process? $ cat important_file > /dev/null &
[1] 9711
$ rm important_file
$ killall -STOP cat

[1]+  Stopped                 cat important_file > /tmp/p
$ ls -l /proc/`pidof cat`/fd/
total 0
lrwx------ 1 vi vi 64 May 13 20:32 0 -> /dev/pts/29
l-wx------ 1 vi vi 64 May 13 20:32 1 -> /tmp/p
lrwx------ 1 vi vi 64 May 13 20:32 2 -> /dev/pts/29
lr-x------ 1 vi vi 64 May 13 20:32 3 -> /home/vi/important_file (deleted)

How to recover this important_file?
I tried something like
injcode -m dup2 -ofd=3 -ofilename=/tmp/recovered_file -oflags=O_CREAT $PID_OF_CAT

but it does nothing.

A: You can just cp the file, i.e:
cp /proc/<pid>/fd/<fdno> /new/path/to/file

Of course, if the file is still being modified, you'll run into trouble with this approach.

A: ... better than copying at a given time (and gathering only that time's snapshot of the file's content) is to "tail -f" that file into a new file:

tail -c +0 -f /proc/PIDofProgram>/fd/# > /new/path/to/file

(thanks to tail's cautious programmers, that will even work with binary output.)
During its runtime, the tail -f itself keeps the file open, safely preventing it from being purged off disk when the original program ends. Thus, don't stop the tail -f immediately after your original program ends - check the tail'ed /new/path/to/file first whether it is what you want. If it isn't (or is unsatisfying for any other reason), you can copy the original file again, but this time after all writing to it has finished by "Program" and from the still-running tail -f's  /proc/PIDoftail/fd/ directory.

A: If /home is NFS, there will be a .nfsNNNNNNNNNN file in /home/vi that you can access/copy.  If home is a local filesystem, you should be able to do the same thing via the /proc/PID/fd/3 link:
cp /proc/PID/fd/3 /tmp/recovered_file

If you want to actually undelete the file, here's a blog post on the subject.

A: Use lsof to find the inode number, and debugfs to recreate a hard link to it. For example:
# lsof -p 12345 | grep /var/log/messages
syslogd 12345 root    3w   REG                8,3    3000    987654 /var/log/messages (deleted)
# mount | grep var
/dev/sda2 on /var type ext3 (rw)
# debugfs -w /dev/sda2
debugfs: cd log
debugfs: ln <987654> tmp
debugfs: mi tmp
                      Mode    [0100600]
                   User ID    [0]
                  Group ID    [0]
                      Size    [3181271]
             Creation time    [1375916400]
         Modification time    [1375916322]
               Access time    [1375939901]
             Deletion time    [9601027] 0
                Link count    [0] 1
               Block count    [6232]
                File flags    [0x0]
...snip...
debugfs:  q
# mv /var/log/tmp /var/log/messages
# ls -al /var/log/messages
-rw------- 0 root root 3301 Aug  8 10:10 /var/log/messages

Before you complain, I faked the above transcript as I don't have a deleted file to hand right now ;-)
I use mi to reset the delete time and link count to sensible values (0 and 1 respectively), but it doesn't work properly - you can see the link count remains at zero in ls. I think the kernel might be caching the inode data. You should probably fsck at the earliest opportunity after using debugfs, to be on the safe side.
In my experience, you should create the link using a temporary file name and then rename to the proper name. Linking it directly to the original file name seems to cause directory corruption. YMMV!

*

*http://glandium.org/blog/?p=87

*http://www.cyberciti.biz/tips/linux-ext3-ext4-deleted-files-recovery-howto.html

A: If your file is still being written to (so you cant use cp), and you're not using ext (so you cant use debugfs) here's an agnostic way of doing it.
Once you find the process using ps aux | grep or however, and you've double checked the removed filename via lsof -p $pid -a -d $fd you can use the following spawn a new process whose sole job is to revive it:
(tail -f -n +1 --pid $pid /proc/$pid/fd/$fd) >$file </dev/null 2>&1 &

The weird wrapping is just to safeguard against HUP, so feel free to not use it or swap it out for nohup


text:
Q: Text output of a C++ program running on a webserver and UTF-8 Supposing I have a C++ program that outputs some text in multiple languages for each user input (like the translation of an input text). This program runs on a webserver. However, if it comes to the output of non ASCII symbols (like Chinese characters or Indian scripts or Greek), what appears in the console is rubbish. Is there a way to display the output of the C++ program correctly in the response to the client's request?

A: You must arrange for your web-server's response to explicitly specify the character set in the Content-Type: header, such as:
Content-Type: text/html; charset="utf-8"

The exact mechanism for doing so depends on the web server you are using, and how your web server handles executing your C++ program.
With most web servers, when they execute an external program, the external program is expected to produce the response consisting of a list of header lines, exactly one blank line, then the content of the response. If so, you just need to make sure to include this header in your program's output, before the blank line and the content.
And then, of course, use proper UTF-8 encoding for your output.


text:
Q: C# Instance new struct with enum and array I create a struct, let's call it Example.
Here it is :
[System.Serializable]
public struct Example
{
    public enum Categories {example, test}
    [SerializeField] private Categories lineCategory ;
    public Categories _lineCategory { get {return lineCategory;} }

    [SerializeField] private Translation[] translations;
    public Translation[] _translations { get {return translations;}}
}

And here is the class Translation :
[System.Serializable]
public struct Translation
{
    public enum Languages {fr, en}
    [SerializeField] private Languages language ;
    public Languages _language { get {return language;}}

    [TextArea] [SerializeField] private string line ;
    public string _line { get {return line;}}
}

When I'm using it with unity, there are 0 problems, the System.Serializable make it easy to use.
But, for practical reason, I want to create one with code.
Here is an idea of what I want to create :
 private Example test = new Example {
        lineCategory = Example.Categories.test,
        lines = new Translation {
            {language = Languages.fr,
            line = "test ligne"},
            {language = Languages.en,
            line = "test line"},
        }
    }

Obviously it doesn't work, first because of private / public but, there are more problems and I really can't figure them.
I'm showing here only a small part of my problem, because I would like to create a really big struct for all the translations in my game so there will be more than just one lines but this way you'll understand the problem I think.
Does someone know how to create a new Example() in a good way ?

A: You could declare your properties as init only.
public string Translation[] { get => _translations ; init => _translations = value;}

You would also need to use correct types, i.e. assign an actual array: lines = new[]{ new Translation{...}}
Another option would be to provide constructors that take the parameters you need. This is in my opinion better since it forces the creator of the object to populate all required fields.
public struct Example
{
...
public Example(Categories lineCategory, Translation[] translations){
    _lineCategory = lineCategory;
    _translations = translations;
}

You might also consider using dedicated "DTO" types. I.e. one  TranslationDTO type only used for serialization, and Translation type used in all other code. This pattern can help separate any logic in your types from things needed for serialization, and example would be that many serialization libraries require public setters. But this is less of a concern if you have little to no logic in your types.


text:
Q: Adding Negative Integers in Javascript I am trying to write a function that returns the first two values in order of appearance that add to the sum. My function works fine with positive numbers, but not with negative. Can anyone tell me what I am doing wrong?
This function return an empty array:

const sumOfPairs = (arr, sum) => {
  const answer = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[i] + arr[j] === sum && i != j) {
        answer.push(arr[j], arr[i]);
      }
      break;
    }
  }
  return answer;
}

console.log(sumOfPairs([1, -2, 3, 0, -6, 1], -6));

A: Your implementation doesn't work for all positive numbers either. Try 3 as sum.
I believe you want to put the break statement inside the if statement or just replace the body of the if statement with return [arr[j], arr[i]]:

const sumOfPairs = (arr, sum) => {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[i] + arr[j] === sum && i != j) {
        // You can return here if you only want to find *one* pair
        // You also need add some additional logic if you want them
        // to be in the same order as in the original array:
        return i < j ? [arr[i], arr[j]] : [arr[j], arr[i]]
      }
    }
  }
  return []
}

console.log(sumOfPairs([1, -2, 3, 0, -6, 1], -6));

The current location of the break statement in your loop causes the inner loop to terminate after its first iteration! Therefore the inner loop is equivalent to testing whether the sum of the current outer loop's item (arr[i]) and 1 (the first element in the array) is equal the provided sum.


text:
Q: How to get the contents of a saved text file (Java) Is there any way to get the contents of a text file as a string?
For example, I have the contents of the file as:

Name: John, Age: 34, Email: someone@example.com

I have seen similar questions, but they don't get me anywhere.
Edit: My code -

        String fileName = "Sample" + ".txt";
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS) + File.separator + fileName);

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));

            String currentLine;
            String content;
            StringBuilder stringBuilder = new StringBuilder();

            while ((currentLine = br.readLine()) != null) {
                stringBuilder.append(currentLine);
            }

            content = stringBuilder.toString();
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

// somewhere else in the code
final Button viewData = findViewById(R.id.viewData); // Defining the viewData button

viewData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewFileData();
            }
        });

Thanks for your Help.

A: You can try some think like this.
public class Main {

    public static void main(String[] args) throws IOException {

        File file = new File("C:\\Users\\Hasindu\\Desktop\\javaSample\\src\\sample\\sample.txt");//Text file location

        BufferedReader br = new BufferedReader(new FileReader(file));

        String currentLine;
        String content = null;
        StringBuilder stringBuilder = new StringBuilder();//Using the StringBuilder class of java for the concatenation.

        while ((currentLine = br.readLine()) != null) {

            stringBuilder.append(currentLine); //Read all the lines in the text file and concatenate them for a single stringBulder object.

        }
        content = stringBuilder.toString();//Coverting the StringBuilder object to a String
        System.out.println(content);

    }

}


text:
Q: MongoDB overwrite validation error messages I am using mongodb and mongo-driver to manage models and its data. I should translate the default validation messages to my native language.
That being said, I have being reading the mongo-driver documentation but I couldn't find anything related on replacing the model validation errors.
Thus, I have my model user.go where:
type User struct {
    ID           primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
    Email        string             `bson:"email" json:"email" binding:"required,email" validate:"is-unique"`
}

Then, whenever I send data where email is empty I get the default error message: "Key: 'User.Email' Error:Field validation for 'Email' failed on the 'required' tag".
Suggestions?


text:
Q: What am I doing wrong with arrays? I'm pretty new to the JavaScript as well as to the Node.JS and I really can't understand why I'm getting NaN using the following expression:
var aUsersBetted = {};
aUsersBetted['1337'] += 200000;
logger.debug(aUsersBetted['1337']);

After doing this it prints me NaN in console. I'm really confused now. Sorry for the dumb question by the way.

A: Let's take it line by line.
This var aUsersBetted = {}; creates an object, not an array.
This aUsersBetted['1337'] += 200000; adds 200000 to the value that is associated with the key 1337.
Since, you haven't defined the key before you use it, it's value is also undefined. So you try to add to an undefined value to a number. That's why you get this error.
One possible workaround to your problem it would be to initialize the value of 1337, like:
aUsersBetted['1337'] = 0;

Then your expression, aUsersBetted['1337'] += 200000;, would add 200000 to 0 and set this to the back to the place in memory, where aUsersBetted['1337'] points to.

A: First, initiate your object value to 0. You are trying to add 200000 to an undefined value.
var aUsersBetted = {};
aUsersBetted['1337'] = 0;
aUsersBetted['1337'] += 200000;
window.console.log(aUsersBetted['1337']);

test it here: https://jsfiddle.net/hjqvwfwt/

A: You didn't initialized the variable aUsersBetted['1337'].
JavaScript tries to do this: undefined+200000
What you want: 0+200000
Use:
aUsersBetted['1337'] = 0;
aUsersBetted['1337'] += 200000;


text:
Q: Loading Unity solution with Rider corrupts the project Whenever I load an existing Unity project in Rider, Unity doesn't make me run/build it, returning blank errors in the console.
I have tried reinstalling Unity and deleting Rider's configuration files.
I also believe the bug may be caused by the "Rider Editor" Unity package not working correctly.
Also, after reloading the Unity project, all of the Unity Scripts associated with the Gameobjects are unable to be loaded.
I found this in the Editor.log:
-----CompilerOutput:-stdout--exitcode: 134--compilationhadfailure: True--outfile: Temp/UnityEngine.SpatialTracking.dll
Microsoft (R) Visual C# Compiler version 2.9.1.65535 (9d34608e)
Copyright (C) Microsoft Corporation. All rights reserved.

-----CompilerOutput:-stderr----------
/home/rotolonico/Unity/Hub/Editor/2019.3.0a5/Editor/Data/Tools/RoslynScripts/unity_csc.sh: line 89: 10933 Aborted                 (core dumped) "/home/rotolonico/Unity/Hub/Editor/2019.3.0a5/Editor/Data/Tools/RoslynScripts/../../Tools/Roslyn/csc" /shared /noconfig @Temp/UnityTempFile-35071e8ef485631d5b4eb3ee7f34ec61
-----EndCompilerOutput---------------
- Finished compile Library/ScriptAssemblies/UnityEngine.SpatialTracking.dll

Microsoft (R) Visual C# Compiler version 2.9.1.65535 (9d34608e)
Copyright (C) Microsoft Corporation. All rights reserved.

[ScriptCompilation] Recompiling all scripts because: Reload of assemblies failed
- Starting compile Library/ScriptAssemblies/UnityEngine.TestRunner.dll
- Starting compile Library/ScriptAssemblies/Unity.ugui.dll
- Starting compile Library/ScriptAssemblies/com.unity.multiplayer-hlapi.Runtime.dll
- Starting compile Library/ScriptAssemblies/Unity.Timeline.dll

I am using:
Unity 2019.3.0a5,
Rider 2019.1,
My OS is Fedora 30 Thirty (x86-64)
The problem also occurs in Unity 2019.2 and 2019.1

A: I am not sure if this is a coincidence or not but it seems like the bug stopped occurring when I upgraded from 4GB of RAM to 16GB. This seems like is completely unrelated, but the bug itself started occurring when I was forced to downgrade to 4GB of RAM due to one bank failing.


text:
Q: Is it possible to selecting dataset by time range when range is different for every pixel in pythons xarray module I try to select only this part of the data within a specific time range that is different for every pixel.
For indexing, I have two np.datetime64[ns] xr.DataArrays with shape(lat:152, lon:131) named time_range_min, time_range_max
One is holding the start dates and the other one the end dates.
I try this for selecting the data
dataset = data.sel(time=slice(time_range_min, time_range_max))

but it yields

cannot use non-scalar arrays in a slice for xarray indexing:
<xarray.DataArray 'NDVI' (lat: 152, lon: 131)>

If I cannot use non-scalar arrays it means that it is in general not possible to do this, or can I transform my arrays?

A: If "time" is a list of dates in string that is ordered from past to present (e.g. ["10-20-2021", "10-21-2021", ...]:
import numpy as np
listOfMinMaxTimeRanges = [time_range_min, time_range_max]
specifiedRangeOfTimeIndexedList = []
for indexingListOfMinMaxTimeRanges in range(np.shape(listOfMinMaxTimeRanges)[1])):
  specifiedRangeOfTimeIndexed = [specifiedRangeOfTime for specifiedRangeOfTime in np.arange(0, len(time), 1) if time.index(listOfMinMaxTimeRanges[0][indexingListOfMinMaxTimeRanges]) <= specifiedRangeOfTime <= time.index(listOfMinMaxTimeRanges[1][indexingListOfMinMaxTimeRanges])]
  for indexes in range(len(specifiedRangeOfTimeIndexed)):
    specifiedRangeOfTimeIndexedList.append(specifiedRangeOfTimeIndexed[indexes])

Depending on how your dataset is structured:
dataset = data.sel(time = specifiedRangeOfTimeIndexedList)

or
dataset = data.sel(time = time[specifiedRangeOfTimeIndexedList])

or
dataset = dataset[time[specifiedRangeOfTimeIndexedList]]

or
dataset = dataset[:, time[specifiedRangeOfTimeIndexedList]]

or
dataset = dataset[time[specifiedRangeOfTimeIndexedList], :, :]

or
dataset = dataset[specifiedRangeOfTimeIndexedList]

...

A: I found a way to group every cell with stacking in xarray:
time_range_min and time_range_max marks now a single date
stack = dataset.value.stack(gridcell=['lat', 'lon'])
for unique_value, grouped_array in stack.groupby('gridcell'):
    grouped_array.sel(time=slice(time_range_min,time_range_max))


text:
Q: trouble connecting android app to localhost So I have connected my laptop to my androids wifi and used the gateway IP address however I am stuck trying to pull from the  database. The database works as I have tested it separately.
Logcat suggests  there's an error in login. (Ill Mark where the errors come up so you don't have to)
07-31 01:49:41.323: W/System.err(20516):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-31 01:49:41.343: E/JSON Parser(20516): Error parsing data org.json.JSONException: End of input at character 0 of
07-31 01:49:41.353: D/request!(20516): starting
07-31 01:49:41.353: W/dalvikvm(20516): threadid=11: thread exiting with uncaught exception (group=0x4194ada0)
07-31 01:49:41.353: E/AndroidRuntime(20516): FATAL EXCEPTION: AsyncTask #1
07-31 01:49:41.353: E/AndroidRuntime(20516): Process: com.example.mysqltest, PID: 20516
07-31 01:49:41.353: E/AndroidRuntime(20516): java.lang.RuntimeException: An error occured while executing doInBackground()
07-31 01:49:41.353: E/AndroidRuntime(20516):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at java.lang.Thread.run(Thread.java:841)
07-31 01:49:41.353: E/AndroidRuntime(20516): Caused by: java.lang.NullPointerException //this will be marked
07-31 01:49:41.353: E/AndroidRuntime(20516):    at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:125)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:1)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-31 01:49:41.353: E/AndroidRuntime(20516):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-31 01:49:41.353: E/AndroidRuntime(20516):    ... 4 more
07-31 01:49:42.054: W/IInputConnectionWrapper(20516): showStatusIcon on inactive InputConnection
07-31 01:49:42.474: E/WindowManager(20516): android.view.WindowLeaked: Activity com.example.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42da7448 V.E..... R......D 0,0-1026,288} that was originally added here
07-31 01:49:42.474: E/WindowManager(20516):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:457)
07-31 01:49:42.474: E/WindowManager(20516):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
07-31 01:49:42.474: E/WindowManager(20516):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
07-31 01:49:42.474: E/WindowManager(20516):     at android.app.Dialog.show(Dialog.java:288)
07-31 01:49:42.474: E/WindowManager(20516):     at com.example.mysqltest.Login$AttemptLogin.onPreExecute(Login.java:103)
07-31 01:49:42.474: E/WindowManager(20516):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
07-31 01:49:42.474: E/WindowManager(20516):     at android.os.AsyncTask.execute(AsyncTask.java:535)

package com.example.mysqltest;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {

    private EditText user, pass;
    private Button mSubmit, mRegister;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    // php login script location:

    // localhost :
    // testing on your device
    // put your local ip instead, on windows, run CMD > ipconfig
    // or in mac's terminal type ifconfig and look for the ip under en0 or en1
    // private static final String LOGIN_URL =
    // "http://xxx.xxx.x.x:1234/webservice/login.php";

    // testing on Emulator:
    private static final String LOGIN_URL = "http://192.168.43.1/drinkdealz/login.php";

    // testing from a real server:
    // private static final String LOGIN_URL =
    // "http://www.mybringback.com/webservice/login.php";

    // JSON element ids from repsonse of php script:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        // setup input fields
        user = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);

        // setup buttons
        mSubmit = (Button) findViewById(R.id.login);
        mRegister = (Button) findViewById(R.id.register);

        // register listeners
        mSubmit.setOnClickListener(this);
        mRegister.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.login:
            new AttemptLogin().execute();
            break;
        case R.id.register:
            Intent i = new Intent(this, Register.class);
            startActivity(i);
            break;

        default:
            break;
        }
    }

    class AttemptLogin extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                        params);

                // check your log for json response
                Log.d("Login attempt", json.toString());  ////THIS IS WHERE ERROR COMES UP////

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                    // save user data
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(Login.this);
                    Editor edit = sp.edit();
                    edit.putString("username", username);
                    edit.commit();

                    Intent i = new Intent(Login.this, ReadComments.class);
                    finish();
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                } else {
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null) {
                Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }

}

Finally, sorry for excessive posting today, deadline approaching!
EDIT: I ran it again and got the error: 07-31 02:29:58.732: E/AndroidRuntime(26604): Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=192.168.43.1/drinkdealz/register.php


text:
Q: Verify electronic signature in .NET I have a set of questions:

*

*What does a .p7s file contain? I read that it usually is an encrypted message sent to an e-mail, but in my case I have a file and a .p7s file on my hdd. The file is much larger than the .p7s, so I am wondering what is in it (and of course how to later use it).

2.this question occurs mostly because I have no naswer for 1. - If I have my public key in the form of a byte array, how can I verify the signature in C#? I found this on the internet, but again, it uses some text gotten from an e-mail and I honestly don't know what is happening:
public static bool Verify(byte[] signature, string text)
        {
            X509Certificate2 certificate = new X509Certificate2(@"D:\My-CV.docx.p7s");

            if (signature == null)
                throw new ArgumentNullException("signature");
            if (certificate == null)
                throw new ArgumentNullException("certificate");

            //hash the text
            // Methode 3 for Hashing
            System.Security.Cryptography.SHA1 hash3 = System.Security.Cryptography.SHA1.Create();
            System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding();
            byte[] combined = encoder.GetBytes(text);
            byte[] hash3byte = hash3.ComputeHash(combined);

            //Adding the text from the email, to a contentInfo
            ContentInfo content = new ContentInfo(hash3byte);

            // decode the signature
            SignedCms verifyCms = new SignedCms(content, true);
            verifyCms.Decode(signature);

            // verify it
            try
            {
                verifyCms.CheckSignature(new X509Certificate2Collection(certificate), false);
                return true;
            }
            catch (CryptographicException)
            {
                return false;
            }
        }

Can someone help me with this?

A: The .p7s file is containing the signature of your document. The content is not encrypted, but it's look like.
The document file is much larger, because it contains the date, the .p7s the signature.
To check the signature, you need the public part of the certificate with which the document was signed.
You can check this two posts to check the signature :

*

*Check signature for x509 certificate

*In C#, sign an xml with a x.509 certificate and check the signature
The last thing is to load the signature data, from the p7s file.
I make some search, and come back to you.


text:
Q: Помощь в изменении кода функции покупки В swift 2.1 такая функция покупки работала. Помогите переделать на swift 3.1
var listOfProducts = [SKProduct]()
var productoPurchase = SKProduct()

func buyProduct() {
print("buy " + productoPurchase.productIdentifier)
let pay = SKPayment(product: productoPurchase)
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().addPayment(pay)
}

Xcode ругается на строки
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().addPayment(pay)

И предлогает исправить на
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().add(pay)

Немного поискав нашел вариант исправления второй строки на
SKPaymentQueue.default().remove(pay)

https://codedump.io/share/GYuvWc0s4HMi/1/skpaymentqueuedefaultqueueaddpaymentpayment-crash-when-moving-between-vc-swift-2330

A: SKPaymentQueue.default().add(self)
.
.
.
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)

Вообще то надо вот это хорошенечко проштудировать, если хотите все сделать правильно, обратите внимание, что там есть куски кода с пометками 'как не надо делать (Does not follow best practices..)' и 'как надо делать (Follows best practices..)'.
Ваш код не похож на последний тип.


text:
Q: Problems writing to the registry while installing OpenOffice.org During the process I end-up with:

Error 1406 : could not write value BASISINSTALLOCATION to key \Software\Open Office.org\Layers\Basis\32.

That's not a typo, it's straight from the dialog box. Event viewer should also read the exact same message.
Apparently something is blocking the modification of a key in registry.
I tried disabling Spyware Blaster, XP-Antispy, Antivirus and Firewall. (With an Admin profile account.)
I will also try with right-clicking installer to raise privileges.
I'm working with Windows Vista Home Premium, UAC is already deactivated.
Any ideas? Help appreciated.

A: Even though you are logged into an account that is a member of the Administrators group, if you have UAC turned on you may still need to run the installer with elevated privileges. Instead of double-clicking the installer, try right-click then run-as-administrator from the menu.


text:
Q: Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required I am using following code to send email.when i am tring to send mail i am getting the error message
MailMessage mail = new MailMessage(from.txt, to.txt, subject, body);
SmtpClient clint = new SmtpClient();
//for determile email smtp...
string x = from.txt;
int startIndex = x.IndexOf('@');
int endIndex = x.LastIndexOf('.');
int length = endIndex - startIndex;
string xx = x.Substring(startIndex + 1, length - 1);

if (xx == "gmail" || xx == "Gmail")
{
    clint.Host = "smtp.gmail.com";
    clint.Port = 587;
    clint.EnableSsl = true;
}
if (xx == "Hotmail" || xx == "hotmail" || xx == "live" || xx == "Live")
{
    clint.Host = "smtp.live.com";
    clint.Port = 587;
    clint.EnableSsl = true;
}
if (xx == "yahoo" || xx == "Yahoo")
{
    clint.Host = "smtp.mail.yahoo.com";
    clint.Port = 465;
    clint.EnableSsl = true;
}
clint.Credentials = new System.Net.NetworkCredential(username, password);
clint.DeliveryMethod = SmtpDeliveryMethod.Network;
clint.UseDefaultCredentials = false;
clint.Send(mail);
MetroMessageBox.Show(this, "Email Successfully Send", "Success",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);

and also how can attach any file to this email

A: For the error you got, I read online that you should use the UseDefaultCredentials before the Credentials line and that EnableSsl of your clint object should be set to true.
Reference here

and also how can attach any file to this email

You can by adding an attachment to the mail object :
mail.Attachments.Add(new Attachment(filename));

I forgot to mention that the double authentication in Gmail might be a problem. If so, refer to the second solution in the link I previously linked.


text: Q: Can I block unidentified calls? When I get a phone call from an unidentified caller. I never answer it. It's always a charity or sales call. Can I make it just not ring through if the caller is unidentified?


text:
Q: iOS 13 UIWindowScene how to lock orientation? I want to use SceneDelegate, UIWindowScene, UIWindowSceneDelegate and other UIScene related things.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }

    window = UIWindow.init(frame: windowScene.coordinateSpace.bounds)
    window?.windowScene = windowScene

    let vc = UIStoryboard(name: "FCBottomTabBar", bundle: nil).instantiateInitialViewController()!
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
}

How can i dynamically lock the orientation for this window? For example for portrait only? Dynamically means that in runtime when user interacts with something the orientation locks back to all.
For example for screen A i need to lock to only portrait orientation. For screen B to only landscape.

A: From 'Device orientation' initially make it portrait.
In AppDelegate make a variable 'orientation' and set its value to UIInterfaceOrientationMask.portrait
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    ...
    var orientation = UIInterfaceOrientationMask.portrait
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return orientation
    }
}

Now in your desired ViewController write this to change orientation
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    (UIApplication.shared.delegate as! AppDelegate).orientation = .landscapeLeft
    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")

}

Hope it will help you.

A: This other answer seems overly complex and uses a private API. In a view controller, to set the supported orientations, simply override supportedInterfaceOrientations.
For example, to lock it to Portrait orientation:
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    .portrait
}


text:
Q: Is there any way I can convert any MS Document to PDF using LibreOffice SDK in java? I want to write the code which will take input as ms document and convert it into PDF. I want to use LibraOffice SDK for conversion, but not able to find the related things. Is it possible to do? If yes, can you give me some pointers?

A: LibreOffice has native PDF "save as" capability, and of course you can exploit this feature from SDK.
I use it in my ASP.NET VC#, with I post here. I guess java will not be very different.
Once you have worked on your xDocument (both Calc or Write) you save them as PDF in this way:
            XStorable xStorable = (XStorable)xDocument;
            PropertyValue[] storeProps = new PropertyValue[3];
            storeProps[0] = new PropertyValue();
            storeProps[0].Name = "FilterName";
            storeProps[0].Value = new uno.Any("writer_pdf_Export");
            storeProps[1] = new PropertyValue();
            storeProps[1].Name = "Overwrite";
            storeProps[1].Value = new uno.Any(true);
            storeProps[2] = new PropertyValue();
            storeProps[2].Name = "SelectPdfVersion";
            storeProps[2].Value = new uno.Any(1);

            xStorable.storeToURL("file:///" + outFile, storeProps);
            xDocument.dispose();

A: Don't know much about LibreOffice SDK, but this is certainly doable with iText (http://developers.itextpdf.com/apis). It's an easy to use API.
I have also had good results from Apache FOP. That said, beware there, as it is much slower and can be a memory hog as it loads the entire document into memory.


text:
Q: String is not convertible to Range error on swift anyone  func setupAvatarColor(name: String, incoming: Bool) {
        let diameter = incoming ? UInt(collectionView.collectionViewLayout.incomingAvatarViewSize.width) : UInt(collectionView.collectionViewLayout.outgoingAvatarViewSize.width)

        let rgbValue = name.hash
        let r = CGFloat(Float((rgbValue & 0xFF0000) >> 16)/255.0)
        let g = CGFloat(Float((rgbValue & 0xFF00) >> 8)/255.0)
        let b = CGFloat(Float(rgbValue & 0xFF)/255.0)
        let color = UIColor(red: r, green: g, blue: b, alpha: 0.5)

        **let nameLength = count(name);**
        let initials : String? = name.substringToIndex(advance(sender.startIndex, min(3, nameLength)))
        let userImage = JSQMessagesAvatarFactory.avatarWithUserInitials(initials, backgroundColor: color, textColor: UIColor.blackColor(), font: UIFont.systemFontOfSize(CGFloat(13)), diameter: diameter)

        avatars[name] = userImage
    }

I receiving the error '`String is not convertible to Range<I>'in the highlighted code (10th line)`. AnyOne?

A: In Swift 2 Apple removed alot of global functions.
In your case to get the length of a String do:
str.characters.count

A: You can't use count anymore in Swift 2.0 for getting the string length.
So instead of:
let nameLength = count(name);

Use:
let nameLength = name.endIndex;

or
let nameLength = name.characters.count;

A: Swift 2.0 lets you call advance on endIndex and startIndex which is what you need here I guess. Ps, avataWithUserInitials takes NSString as first argument and substringToIndex returns String so I don't see any reason to define it as String optional.
let initials = name.substringToIndex((name.characters.count < 3) ? name.endIndex:name.startIndex.advancedBy(3))


text:
Q: Google Maps: how to find the point having the same driving distance from a set of points Given three points (or more) on a map, I would like to find the point that is closest to all of them and is at the same driving distance from all of them.
I would like to do this in Google Maps, using the provided driving directions service.
Any idea?
Thanks a lot
UPDATE
in this question is mentioned a way to find the center of a bunch of locations, which could be a first step
var locations = [
            ['Bondi Beach', -33.890542, 151.274856, 4],
            ['Coogee Beach', -33.923036, 151.259052, 5],
            ['Cronulla Beach', -34.028249, 151.157507, 3],
            ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
            ['Maroubra Beach', -33.950198, 151.259302, 1]
        ];

//[OTHER CODE]

var bound = new google.maps.LatLngBounds();

for (i = 0; i < locations.length; i++) {
  bound.extend( new google.maps.LatLng(locations[i][1], locations[i][2]) );

  // OTHER CODE
}

var geoCenter = bound.getCenter();//THIS IS THE GEOGRAPHICAL CENTER

After this, one could just retrieve the driving directions from each point to the center, and hope they're about the same distance. If, for any reason, the distances are too different, some kind of methodology should developed in order to find the desired point.

A: I dont think there is any service that will achieve that.
You could attempt to calculate the geographic centre point and then calculate the driving distance to that point from each point using the direction services.
If one or more of the driving distances is significantly longer the other you could than adjust the 'centre point' along the route and trying again.
Also consider three point along a straight road - there is nowhere that is both closest and equidistant to all of them


text:
Q: Git rebase without changing the commiter of each commit I changed the author name of some past commits (commits I made) using rebase starting at the root.
I used git rebase -i -p --root, and then marked the commits I wanted to change with "edit".
Then I used git commit --amend --author="Username <email>" --no-edit
and then git rebase --continue for each commit.
It worked perfectly for the ones I marked edit, however, I am not the only one working in the repository.  All the commits that I did not mark edit (ones that were not mine) now say that someone else authored but I committed. I reset the repository to before the rebase, but would like to know if there's a way to rebase without making it seeming like I committed everything? There must be a way to leave some commits alone during a rebase, but I can't find anything online.


text:
Q: Eigenvectors of the derivative operator are the exponential function The eigenvectors of the derivative operator are the exponential function. The derivative operator is not Hermitian, so we get complex eigenvalues.
$\frac{d}{dx} f(x) = \lambda f(x) \Rightarrow f(x)=Ce^{\lambda x}$
what is the solution of the eigenvalue problem: $e^{zcos(x)}$
$\frac{d}{dx} e^{zcosx} = -ze^{zcosx}sin(x)$
$-\frac{1}{sinx}\frac{d}{dx} e^{zcosx} = ze^{zcosx}$
seeking for the eigenvectors. I don't see the solution.
I am very lost. Thank you.


text:
Q: Does synchronize keyword prevent a thread from using its own variable while locked? Lets take an example:
public class DBServer {
static boolean listening = false;
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
static List<ClientThread> users = null;

public static void main(String[] args) {
    users= new LinkedList();
    int portNumber = 0;//some valid port number
    System.out.println("Now using port number=" + portNumber);
    try {
        serverSocket = new ServerSocket(portNumber);
    } catch (IOException e) {
        System.out.println(e);
    }

    while (listening) {
        try {
            System.out.println("Number of users connected: " + users.size());
            clientSocket = serverSocket.accept();
            System.out.println("Someone just joined.");
            ClientThread ct= new ClientThread(clientSocket);
            users.add(ct);
            ct.start();
        }catch (IOException e) {
            System.out.println(e);
        }
    }
}
}//End of class

public class ClientThread extends Thread {
    int c = 0;
    //some other variables
    ClientThread(Socket s){
        this.clientSocket= s;
    }
    void doSomething(){
        ClientThread ct = DBServer.users.get(0);
        synchronized(ct){
            ct.c++;//or some other operation on c
        }
    }
    void method2(){
        c++;//or some other operation on c
    }

    //some other methods

    public void run(){
    //some never ending logic that decides which method is being called
    }
}//End of class

Let's assume that there are 3 users(User 0, User 1, User 2) connected to the server at a given time.
User 1 obtains the intrinsic lock for the object of User 0. It is certain that User 2 can't obtain the lock for User 0 while User 1 still posses it. Can User   0 himself change the value of c using method2() while the lock is held by User 1? If so, is there a way to make variable c synchronized between the thread owning it and other threads?

A: So for your following question
//If so, is there a way to make variable c synchronized?
Go for AtomicInteger which will prevent the race condition,
AtomicInteger c;

A: you can make C a static variable of class DBServer that way all threads will have access to it.
now, that will require you to change method2() to be synchronized.
and if you do that, to answer your question under these new terms, user 0 will not be able to change variable C while its under the control of user 1.