text:
Q: Java Picovoice Porcupine Initalization failed Linux Raspberry OS im trying to create an home assistant with a laptop x86_64 running Raspberry Os. Of I try to run my code i get this Error
ai.picovoice.porcupine.PorcupineIOException: Initialization failed.
at ai.picovoice.porcupine.Porcupine.init(Native Method)
at ai.picovoice.porcupine.Porcupine.<init>(Porcupine.java:61)
at ai.picovoice.porcupine.Porcupine$Builder.build(Porcupine.java:262)
at de.VoiceRecognition.ball.WakeWordDetection.main(WakeWordDetection.java:79)

this is my code:
                final String accessKey = "[Acceskey]"; // AccessKey obtained from Picovoice Console (https://picovoice.ai/console/)

            mainFrame.startFrame();

            ByteArrayOutputStream outputStream = null;

            String Keypath =   "voiceTickets/de_linux_v2_1_0.ppn";
            String ModelPath = "voiceTickets/porcupine_params_de.pv";

            // get audio capture device

            try {
                micDataLine = mic.getTargetDataLine();
                micDataLine.open(format);
            } catch (LineUnavailableException e) {
                System.err.println("Failed to get a valid capture device. Use --show_audio_devices to " +
                        "show available capture devices and their indices");
                System.exit(1);
                return;
            }

                Porcupine handle = new Porcupine.Builder()
                                    .setAccessKey(accessKey)
                                    .setKeywordPath(Keypath)
                                    .setModelPath(ModelPath)
                                    .build();

Thank you!


text:
Q: Counting Number of objects in labeled image I have an image which i try to count the number of object -mainly filled circles- so to kill the overlapping between the circle i end up with a labeled image which works pretty well so far, no i apply
bwconncomp(theLabeledImage,4); in way to get the number of filled circles , but what i get looks like this
  Connectivity: 4
  ImageSize: [505 394 3]
  NumObjects: 87
  PixelIdxList: {1x87 cell}

which happened to be wrong the given output is 87, while i have 48 in the image.
Image:

So any suggestion :) ?.

A: A couple of things were tripping you up here.
First, I think you were running bwconncomp on the labeled image, not the binary image.  This will double-count a lot of the regions because you'll end up counting the region and its border.  See below in my code where I do this (labelImageBWCC = bwconncomp(rgb,4);) and end up with a count of 89 regions.
Second thing is that the watershed transform will sometimes not cleanly break at a junction and instead will end up generating a bunch of little regions right on the border.  This is the 'plateau problem' with watershed transforms, but thankfully we can avoid the ramifications of this issue by simply filtering out those little regions with an area threshold.
With those things corrected you can get the right number of coins.  Code here:
img = imread('coins.tif');

% Threshold and binarize image and fill holes
binImg = ~im2bw(img, graythresh(img));
binImg = imfill(binImg, 'holes');

% Distance transform and watershed segmentation
D = bwdist(~binImg);
D = -D;
D(~binImg) = -Inf;
L = watershed(D);
% Generate label image
rgb = label2rgb(L,'jet',[.5 .5 .5]);
% Show results of watershed
figure, imshow(rgb,'InitialMagnification','fit')
title('Watershed transform of coins.tif')

% Count number of label regions.  Note - this is incorrect!  This will
% count borders and background, which we don't want
labelImageBWCC = bwconncomp(rgb,4);

% Generate new binary image that only looks at individual regions generated
% by watershed segmentation so we are counting watershed regions, not label
% colors
binWatershed = L > 1; % 1 is background region; any region with index > 1 is coin
minCoinSize = 50; % minimum size in pixels
regs = regionprops(binWatershed, 'Area', 'Centroid', 'PixelIdxList');
% Remove all regions with size below threshold
regs(vertcat(regs.Area) < minCoinSize) = [];

% Display image with coin count labeled
figure, imshow(img)
hold on
for k = 1:numel(regs)

    text(regs(k).Centroid(1), regs(k).Centroid(2), num2str(k), ...
        'Color', 'r', 'HorizontalAlignment', 'center')

end
hold off

redpajama_set_name: RedPajamaStackExchange


text:
Q: create dropdown example in laravel from existnig dropdown list I want to try for dependent dropdown in laravel 5.
In which main dropdown having several lists like(Electronics,Automobiles) and from one of them click or change event.
I want to create another whole dropdown .
if I clicked on Electronics than one another dropdown will be Automatic generated for electronics.
enter image description here
If I clicked on electronics from first dropdown list at that time another dropdown will be automatically generated for the electornics.
and than if i clicked Automobiles from first dropdown list than it should replace the last automatically created dropdown which is for electronics.

A: <!doctype html>

  <meta charset="utf-8">
  <title>Dependent Drop-down Demo</title>

Dependent Drop-down Demo

        {!! Form::open(['url'=>'Demo']  ) !!}

        <select name="category" id="category" class=" form-control">
            <option value=" "selected disabled>Select Category</option>
            @foreach($categories as $category)
                <option value='{{ $category->id }}' > {{$category->name}} </option>
            @endforeach
        </select>
        <select hidden name="subcategory" id="subcategory" class=" form-control">
        </select>
        <select hidden name="semicategory" id="semicategory" class=" form-control">
        </select>

        {!! Form::close() !!}


text:
Q: reduce system of equations which is under-determined in mathematica I obtained the folloiwng equation (as an example):
{2 w11 + 3 w21 == 2 w12, w11 == 4 w12 + 3 w22, w11 + 2 w21 + w22 == 0,
  2 w12 + w21 + 2 w22 == 0}

And I want to determine w11, w12, w21, w22. However, simply do the following:
Solve[{3 w11 + 2 w21 == 5 w11 + 3 w12, w11 + w21 == 5 w21 + 3 w22,
  3 w12 + 2 w22 == -2 w11 - w12, w12 + w22 == -2 w21 - w22}, {w11,
  w12, w21, w22}]

Because the system of equations is under-determined. I have one thought, i.e. using matrix algebra. But I need to automatically group those coefficients in front of w11, w12, w21, w22 into a matrix (list of lists) then go from there. But I am not sure how to manipulate these equations easily to generate such a matrix. Please help, or if you have better ideas, please share too.
Many thanks.

A: There is a built-in function CoefficientArrays for converting systems of linear (or polynomial) equations into a matrix form.
The matrix you want is the second part of the result:
In[7]:= vars = {w11, w12, w21, w22};

In[8]:= CoefficientArrays[{2 w11 + 3 w21 == 2 w12,
   w11 == 4 w12 + 3 w22, w11 + 2 w21 + w22 == 0,
   2 w12 + w21 + 2 w22 == 0}, vars] // Normal

Out[8]= {{0, 0, 0,
  0}, {{2, -2, 3, 0}, {1, -4, 0, -3}, {1, 0, 2, 1}, {0, 2, 1, 2}}}

The inhomogeneous part is the first part of the result, a vector:
In[9]:= CoefficientArrays[{3 w11 + 2 w12 == 5 w11 + 3 w21 + a,
   w11 + w12 == 5 w12 + 3 w22 - c,
   3 w21 + 2 w22 + b == a - 2 w11 - w21,
   w21 + w22 == f - 2 w12 - w22}, vars] // Normal

Out[9]= {{-a,
  c, -a + b, -f}, {{-2, 2, -3, 0}, {1, -4, 0, -3}, {2, 0, 4, 2}, {0,
   2, 1, 2}}}

A: Here are your equations and variables:
vars = {w11, w12, w21, w22};
eqs = {2 w11 + 3 w21 == 2 w12, w11 == 4 w12 + 3 w22,
   w11 + 2 w21 + w22 == 0, 2 w12 + w21 + 2 w22 == 0};

Here is the matrix:
In[48]:= matrix =  Transpose[ eqs /. Equal :> Subtract /.
    Map[Thread[vars -> #] &, IdentityMatrix[Length[vars]]]]

Out[48]= {{2, -2, 3, 0}, {1, -4, 0, -3}, {1, 0, 2, 1}, {0, 2, 1, 2}}

EDIT:
The same works for your second group of equations:
In[49]:= eqs = {3 w11 + 2 w21 == 5 w11 + 3 w12,  w11 + w21 == 5 w21 + 3 w22,
  3 w12 + 2 w22 == -2 w11 - w12,  w12 + w22 == -2 w21 - w22};

In[50]:= matrix = Transpose[ eqs /. Equal :> Subtract /.
    Map[Thread[vars -> #] &, IdentityMatrix[Length[vars]]]]

Out[50]= {{-2, -3, 2, 0}, {1, 0, -4, -3}, {2, 4, 0, 2}, {0, 1, 2, 2}}

EDIT:
Expanding on the solution, upon request. First, how it works: the idea is to first bring all variables to the left, which is achieved by replacing the equals operator with subtraction:
In[69]:= eqs = {3 w11 + 2 w21 == 5 w11 + 3 w12,  w11 + w21 == 5 w21 + 3 w22,
     3 w12 + 2 w22 == -2 w11 - w12,  w12 + w22 == -2 w21 - w22};

In[70]:= eqs /. Equal :> Subtract
Out[70]= {-2 w11 - 3 w12 + 2 w21, w11 - 4 w21 - 3 w22, 2 w11 + 4 w12 + 2 w22, w12 + 2 w21 + 2 w22}
The rules are constructed so that for any group of rules, only one variable is set to 1, and the rest to 0:
 In[71]:= Map[Thread[vars -> #] &, IdentityMatrix[Length[vars]]]

 Out[71]= {{w11 -> 1, w12 -> 0, w21 -> 0, w22 -> 0}, {w11 -> 0, w12 -> 1, w21 -> 0, w22 -> 0},
        {w11 -> 0, w12 -> 0, w21 -> 1, w22 -> 0}, {w11 -> 0, w12 -> 0, w21 -> 0, w22 -> 1}}

This allows to compute the coefficients:
In[72]:= eqs /. Equal :> Subtract /. Map[Thread[vars -> #] &, IdentityMatrix[Length[vars]]]

Out[72]= {{-2, 1, 2, 0}, {-3, 0, 4, 1}, {2, -4, 0, 2}, {0, -3, 2, 2}}

Upon inspecting how the rules work, it is easy to see that we need to apply Transpose to the result.
Now, your second request requires more work:
In[53]:= eqs = {3 w11 + 2 w12 == 5 w11 + 3 w21 + a, w11 + w12 == 5 w12 + 3 w22 - c,
   3 w21 + 2 w22 + b == a - 2 w11 - w21, w21 + w22 == f - 2 w12 - w22};

In[55]:= modifiedEqs = With[{alts = Alternatives @@ vars},
   eqs //. {lhs_ == HoldPattern[Plus[left___, x_, right___]] /; !FreeQ[x, alts] :>
                    lhs - x == left + right,
            HoldPattern[Plus[left___, x_, right___] == rhs_] /; FreeQ[x, alts] :>
           (left + right == rhs - x)}]

Out[55]= {-2 w11 + 2 w12 - 3 w21 == a, w11 - 4 w12 - 3 w22 == -c,
     2 w11 + 4 w21 + 2 w22 == a - b,   2 w12 + w21 + 2 w22 == f}

In[68]:= matrix = {Transpose[# /. (lhs_ == rhs_) :> lhs /.
    Map[Thread[vars -> #] &, IdentityMatrix[Length[vars]]]], #[[All,2]]} &[modifiedEqs]

Out[68]= {{{-2, 2, -3, 0}, {1, -4, 0, -3}, {2, 0, 4, 2}, {0, 2, 1,  2}}, {a, -c, a - b, f}}

The main difference is that we need an extra step to separate the constants and bring them to the r.h.s. You may find it more useful to figure out the details of how this works yourself.
Edit:
Yes, I forgot to mention: to understand the solution, you should know what happens when you apply rules in nested lists - in this case, each list of rules inside a larger lists results in a transformed copy of an expression, for example:
In[73]:= {a, b, c} /. {{a -> 1}, {b -> 1}, {c -> 1}}

Out[73]= {{1, b, c}, {a, 1, c}, {a, b, 1}}

HTH


text:
Q: Fasteest algorithm to compute avg distance between two Sets of points Please see picture :

Given the set of points marked in Red, I take two consecutive points (here 0 and 1 - these numbers are  just for illustration , thus not the index in the array holding these points.).
I take their midpoint. From the midpoint I draw a normal on each segments in the Green set (segment = line between two consecutive points).
The blue line is such a normal. The intersection point falls between points 10 and 11. I record the length of it.
The black normal line however, is a normal on the line given by points 12 and 13. But, the intersection does not fall between 12 and 13 . So I reject it.
I want to get the median value of the lengths all such accepted lines, measured from the midpoints of the segments in the red set.
My Brute force algorithm is running at O(MN) time.
My questions :

*

*Is there a standard algorithm for what I am seeking? That is to say, I do not know if the parameter I am measuring has a common name.

*What is the fastest method of measuring it.

I would love to do some parallel processing, but I am using D, and I am getting :
 "core.thread.threadbase.ThreadError@src/core/thread/threadbase.d(1219): Error creating thread"

Thank you.


text:
Q: Present editable input to a user with ruby I'm on Ubuntu 14.04 with Ruby 1.9.3. I'm trying to present an editable input to the user.
The only solution I happened to find was using the read command from the bash-shell:
read -e -i "Default Value" -p "Prompt> " ; echo $REPLY
Executed from the command line it works well, the edited input is in the REPLY variable.
But if I define
def edits
  `read -e -i "Default Value" -p "Prompt> ; echo $REPLY" `
end

and run it in ruby I get an error:
sh: 1: read: Illegal option -e

My questions are now:

*

*What went wrong in my solution?

*Is there a better solution in ruby?

A: The -e flag for read is a bash extension. You're using the sh shell (or something emulating sh), which has the read command but doesn't have that flag.
The Readline module provides terminal input, with editing, from within Ruby:
require "readline"
while buf = Readline.readline("> ", true)
  p buf
end

It also has history and completion features.


text:
Q: Restricting the use of back button without JavaScript I'm currently involved in an ASP.NET project where I need to restrict the users ability to go back in the page structure using the back button. It is essentially a wizard style navigation and I don't want to give the user the ability to go back from the last step and re-submit the data. JavaScript is not an option unfortunately, so I "solved" it by setting the HttpCacheability in every pages Load event to NoCache. This gives the user the "Page expired" page when he or she clicks the back button. It isn't very elegant at all, and I'm wondering what other options I have to achive the desired results.

A: Keep the navigation state on the server side, and if the user hits a page that doesn't correspond with a next/prev click, redirect them to where they were supposed to be.

A: Only expose one URL for your entire wizard. The step displayed will depend on session state, which can store what steps they have already completed.
That way there is no "invalid" URL for the user to load.
You should probably consider creating a UserControl for each step. You then place all the steps on a single .aspx page and show and hide them as appropriate.

A: The short answer is "you can't."  Because it's browser-side functionality, any method to do this will be via something exposed by the browser, which means it's trivially defeatable.  The long answer is you don't want to.  This creates usability issues (any changes to normal browser behavior is undesired).  I would suggest using a session cookie to determine where in the process they should be and issue a 302 redirect to the appropriate page if they try to access the wrong page of the process (prior to processing any GET/POST data as well as discarding any data they may have been submitting).  Trying to defeat the users by altering how the browser's base functionality works will always lead to headaches.

A: It's not possible. Even if you get it working in internet explorer in Firefox it will not work.
The only way to handle this is you need to handle saving the state of a users step in either their session, database etc and then when they submit verify that they are submitting on the correct step.


text:
Q: Undo changes of '2to3' library I had some python code in my SSH Project Folder which I had to convert from Python 2.7 to Python 3.*. Hence I installed the library 2to3.
However, before running the command 2to3 . -w, I navigated to the ROOT directory which contained all the Python and Conda relevant library files by mistake and ran my code from there.
So I think that has changed all the python files from the root directory and not just my project-specific files. Hence I am getting multiple errors now while running the code.
By any chance, is there any way to undo these changes? I tried conda update --all to upgrade my packages but nothing is happening. Is re-installing everything the only way to fix this?


text:
Q: No response from Selenium Server when starting from jar file I am setting up a headless Ubuntu server as a node.  This node runs Chrome via Chromedriver, and I am able to run tests when I launch the jar via bash.  This is the command I am using:
java -jar /opt/selenium-server-standalone-2.39.0.jar -role node -hub
http://qwautomation02:4444/grid/register -port 5555
-Dwebdriver.chrome.driver=/opt/chromedriver.exe -nodeConfig /mnt/smb/Configuration/nodeConfig.json

I have written a Java application to run this command and insert the ports that are being used into a database.  This application uses the same bash command to start the Selenium server as above.  I am launching this jar from the /opt directory, the same directory that the Selenium server jar is in.  Here is the applicable method:
    public static Process startupNode(int portNumber, String browser) throws IOException{
    //If Linux, else Windows.
    String port = String.valueOf(portNumber);
    if (Portability.isUnix()) {
        return Runtime.getRuntime().exec(String.format("java -jar /opt/selenium-server-standalone-2.39.0.jar -role node -hub http://qwautomation02:4444/grid/register -port %s -Dwebdriver.chrome.driver=/opt/chromedriver -nodeConfig /mnt/smb/Configuration/nodeConfig.json"
                , port));
    }
    else
        return Runtime.getRuntime().exec(String.format("java -jar C:\\Selenium\\vendor\\selenium-server-standalone-2.39.0.jar -role node -hub http://qwautomation02:4444/grid/register -port %s -Dwebdriver.chrome.driver=C:\\Chromedriver\\chromedriver.exe -nodeConfig \\\\qwautomation02\\WebDriver\\Configuration\\nodeConfig.json"
                , port));
}

I can start a test and part of runs, but this exception is always thrown during execution and cannot be caught.

It appears that the session is losing communication with the hub in mid execution.  But, considering the test will run to completion when I manually run the bash command, I am at a loss for why this is occurring.

A: This sounds like an Ubuntu permissions error. Your personal Ubuntu user has execute access, but the user / process that is running the java file may not.


text:
Q: iOS - AWS Cognito - Check if user already exists I want to allow a user to enter their email address/password in a field. Upon continuing, I want to run a check to see if that user already exists. If they do, log them in and continue with app, if they do not, move to account creation flow where they will be instructed to add name, phone number, etc.
I cannot for the life of me find documentation on how to log a user in using AWS Cognito. I should be able to pass email/pass in a call and get a response back that says User Exists/User does not exist or whatever! Am I missing something here?
Any help would be greatly appreciated. I've scoured the documentation..this is my last resort.

A: In the current SDK, calling getUser on your AWSCognitoIdentityUserPool just constructs the in-memory user object. To make the call over the network, you need to call the getSession method on the constructed user. Here's a Swift 3 method I wrote to check whether an email is available:
/// Check whether an email address is available.
///
/// - Parameters:
///   - email: Check whether this email is available.
///   - completion: Called on completion with parameter true if email is available, and false otherwise.
func checkEmail(_ email: String, completion: @escaping (Bool) -> Void) {
        let proposedUser = CognitoIdentityUserPoolManager.shared.pool.getUser(email)
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        proposedUser.getSession(email, password: "deadbeef", validationData: nil).continueWith(executor: AWSExecutor.mainThread(), block: { (awsTask) in
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            if let error = awsTask.error as? NSError {
                // Error implies login failed. Check reason for failure
                let exceptionString = error.userInfo["__type"] as! String
                if let exception = AWSConstants.ExceptionString(rawValue: exceptionString) {
                    switch exception {
                    case .notAuthorizedException, .resourceConflictException:
                        // Account with this email does exist.
                        completion(false)
                    default:
                        // Some other exception (e.g., UserNotFoundException). Allow user to proceed.
                        completion(true)
                    }
                } else {
                    // Some error we did not recognize. Optimistically allow user to proceed.
                    completion(true)
                }
            } else {
                // No error implies login worked (edge case where proposed email
                // is linked with an account which has password 'deadbeef').
                completion(false)
            }
            return nil
        })
    }

For reference, my ExceptionString enum looks like this:
public enum ExceptionString: String {
    /// Thrown during sign-up when email is already taken.
    case aliasExistsException = "AliasExistsException"
    /// Thrown when a user is not authorized to access the requested resource.
    case notAuthorizedException = "NotAuthorizedException"
    /// Thrown when the requested resource (for example, a dataset or record) does not exist.
    case resourceNotFoundException = "ResourceNotFoundException"
    /// Thrown when a user tries to use a login which is already linked to another account.
    case resourceConflictException = "ResourceConflictException"
    /// Thrown for missing or bad input parameter(s).
    case invalidParameterException = "InvalidParameterException"
    /// Thrown during sign-up when username is taken.
    case usernameExistsException = "UsernameExistsException"
    /// Thrown when user has not confirmed his email address.
    case userNotConfirmedException = "UserNotConfirmedException"
    /// Thrown when specified user does not exist.
    case userNotFoundException = "UserNotFoundException"
}

A: Some clarification is in order. Cognito has several parts.  The part that does "Authentication" (which is what you are talking about) is called "Cognito User Pools".  Not to be confused with Cognito Federated Identity Pools.
With User Pools you can create usernames and password combinations with attributes, and these can be used to authenticate and deliver a persistent, cross device, Cognito Federated identity identityId to a user (across multiple devices).
Once logged in, the Federated Identity Pool is hooked to roles which can get your "Authorized" to use AWS services (like Dynamo DB etc).
It can be tricky to get all these parts working together and AWS has an online site called "Mobile Hub" that will build code for you and download an xcode project.  This process configures the Federated Identity Pool and the User Pool correctly, and connects them all up to a set of example code.
Connecting the credentials provider to the user pool to the identity pool is a bit counterintuitive, but the AWSIdentityManager in the aws-mobilehub-helper-ios on github manages all that for you.  So I would recommend starting with mobile hub on the console.
Cognito is a somewhat confusing system, here is a link to a brief powerpoint that hits the highlights of how it works (for people that can't understand the AWS docs (like me)).
With that said, "how to check if a user already exists?"
The most reasonable approach is to create the user (via signup), and get a reject if the name is in use, and suggest that your user try a different username.  With respect to the email being in use, you will get that reject upon confirmation (signup sends confirmation id's by email and/or via text).  This can be overridden to reclaim the email address, or you can do a test beforehand to see if the email is in use by attempting to log in and looking at the failure code.
you can fetch the user as the other answer suggests, however if you have established in user pools an alias for login (like email) you will find this problematic, because this just tells you if someone has the user name, not if someone is already using the email address, and you will get a reject later at confirmation time.

A: ListUsers is now a nice way to check for existing usernames.
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html
You can also look for existing emails, phone numbers, and other default attributes.
Here is a simple .NET example:
    Dim userRequest = New ListUsersRequest With {
            .UserPoolId = "poolId",
            .Filter = "username = bob@email.com"
        }
    Dim response = amazonCognitoIdentityProviderClient.ListUsers(userRequest)
    Debug.WriteLine(response.Users.Count)


text:
Q: Extracting Yahoo Weather using jQuery and YQL I'm trying to extract the weather from Yahoo using YQL. However for some reasons nothing returns, however I have tried manually to call the URL with the Select statement is it does returns the results I wanted. Can someone help to debug that went wrong with my codes?
$(function(){

    var loc1 = 'Singapore, Singapore'; // Singapore
    var u = 'c';
    var query1 = "SELECT * FROM weather.forecast WHERE woeid in (select woeid from geo.places(1) where text='" + loc1 + "' AND u='" + u + "'";
    var cacheBuster = Math.floor((new Date().getTime()) / 3600 / 1000);

    var url1 = 'https://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query1) + '&format=json&_nocache=' + cacheBuster;

    window['wxCallback1'] = function(data) {
        var info = data.query.results.channel;
        $('#wxIcon1').append('
' + info.item.condition.text + '
');
        $('#wxTemp1').html(info.item.forecast[0].low + '°' + (u.toUpperCase()) + '' + ' - ' + info.item.forecast[0].high + '°' + (u.toUpperCase()) + '');
        $('#wxHum1').html(info.atmosphere.humidity + '%');

    };
    $.ajax({
        url: url1,
        dataType: 'jsonp',
        cache: true,
        jsonpCallback: 'wxCallback1'
    });

});

A: Managed to find the problem. Here's the full working codes including the HTML section which was left out earlier. Do note that the condition code denotes the graphic file to be displayed. See https://www.igorkromin.net/index.php/2015/09/11/yahoo-weather-condition-code-to-weather-icons-font-mapping/
<!doctype html>

<META http-equiv="Page-Enter" CONTENT="RevealTrans(Duration=3,Transition=23)">
<title>selWeather</title>

          SINGAPORE

          TEMPERATURE

          HUMIDITY


text:
Q: Is it possible create a not measurable set absence of axiom of choice? While reading Analysis II- Terence Tao, he writes that almost all set we encounter are measurable (naturally), and if one wants to create non-measurable set, one need to consult the axiom of choice. Immediately, I think that can we create non-measurable set without the axiom of choice?
The question might seem stupid, I ask just out of curiosity.


text:
Q: writing the output of m.start() - m.end() into a list I have a string that I want to remove gaps from. I have found the beginning and the end position of the gaps, but I don't want to print to the screen.
Instead, I want to save it as a list.
Here's the code I have:
S1= "AAAA--TTT--GCCTT--GGG"
import re
    t=[]
    p = re.compile("-+")
    for m in p.finditer(s1):
        t.append(m.end()-m.start()) ## This produces an error. I want to save the output as a list

A: Is this what you want?
 S1= "AAAA--TTT--GCCTT--GGG"
 S2 = S1.replace('--', ' ')
 l = list(S2.split(' '))

Gets you this output ['AAAA', 'TTT', 'GCCTT', 'GGG']

A: this is output of print(m.end()-m.start())
2
2
2

so I want the output saved as a list t= [2,2,2] instead of printing to the screen


text:
Q: _casterror (null check operator used on a null value) when trying to get directory Always getting Null at "await getExternalStorageDirectory();", no matter temporary or not.
How can i solve this ?
Future<String> get _localPath async {
    final directory = await getExternalStorageDirectory();

    return directory.path;
}

A: Did you remember to get permission?
Add this to your android_manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Then you need to prompt the user to grant the permission before you can use it. For that, you'll probably want to check out permission_handler.
After that, remember that it is still a nullable getter, and you'll want to handle that scenario peacefully. If you have null-safety enabled, your Future should be returning String? instead of String.


text:
Q: MySQL: Display Password as ******* I'm creating a table where a password needs to be stored, but when displayed I don't want the password to be shown, I want asterisks to be displayed.
For example, if the password is abc123, when selected I want it to display *******.
Is this done when creating the column for the table, or is it done when inserting the password value into the password column?
I've read into encrypting, which I plan on doing, but it displays the encrypted value when selected which is don't want.
Any help will be great thanks!


text:
Q: Parsing HTML to return CSS rules from ids and classes attributes with PHP I hate to have to write down a lot of CSS rules and then enter my styles in it, so I'd like to develop a tiny php script that would parse the HTML I'd pass to it and then return empty CSS rules.
I decided to use PHP's DomDocument.
The question is: How could I loop through the whole structure? (I saw that for example DomDocument only has getElementByTag or getElementById and no getFirstElement for example)
I only want to get the ids and the classes in a given block of HTML code, I'd pass things like:

        hello world

I only want to know how could I loop through every node?
Thanks!

A: You can pass an asterisk (*) to getElementsByTagName to get all tags and then loop through them...
<?php

 $nodes = $xml->getElementsByTagName("*");
 $css = "";

 for ($i = 0; $i < $nodes->length; $i ++)
 {
    $node = $nodes->item($i);
    if ($node->hasAttribute("class")) {
      $css = $css . "." . $node->getAttribute("class") . " { }\n";
    } elseif ($node->hasAttribute("id")) {
      $css = $css . "#" . $node->getAttribute("id") . " { }\n";
    }
 }

 echo $css;

?>

A: The SimpleXML extension for PHP may help you. It work perfectly to navigate through HTML tree.
http://www.php.net/manual/en/simplexml.examples-basic.php


text:
Q: How to update table after dismissing previous view controller? So I have a table view populated with data, when clicking on a cell I go to another view controller where I delete the selected cell object. After deleted, the view controller goes back to the table view controller but the table view does not update. How can I fix that?
@IBAction func deleteUser(_ sender: Any) {
    let alertController = UIAlertController(title: "Delete user", message:
           "Are you sure you want to delete this user?", preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "Cancel", style: .default))

    alertController.addAction(UIAlertAction(title: "Delete", style: .destructive,  handler: { action in
        // self.performSegue(withIdentifier: "LogoutID", sender: nil)
        print("User ID\(self.userID)")
        self.backEnd.deleteJSONUser(query: self.userID,completion: {(err) in
            if let err = err {
                print("Failed to delete",err)
                return
            }
            print("Successfully deleted user")

        })
        // self.dismiss(animated: true)
        //goes back to previous table with all users
        self.instanceOfVCA.usersTableView.reloadData()
        //self.instanceOfVCA.users.remove(at: Int(self.userID)!)
        self.navigationController?.popViewController(animated: true)

     }))

    self.present(alertController, animated: true, completion: nil)
}

I already tried WillApear:
override func viewWillAppear(_ animated: Bool){

    usersTableView.reloadData()
}

A: Your issue is that you are deleting the data from your backend but you are not also deleting it from whatever array or database that backs your table view.  You need to notify the VC with the tableView to delete the item AND reload (or just call the deleteRow method).  You can do this with a protocol and delegate, a notification, a database subscription or a completion handler.


text:
Q: Declare a resource outside the using statement I have a question about C# using statement. According to the docs, it is a best practice to both declare and initialize the resource (for instance, a SqlConnection object) inside the using statement. My question is: if I'll only declare the object outside the using scope (and initialize it as part of the using statement), is it completely equal to declaring it as part of the using statement? My use case is that I need to use an SqlConnection object outside the using scope. (I would like to call SqlConnection.ClearPool on it, in case I get some specific exception.

A: Both scenarios are equivalent. But when you declare a variable outside the scope of the using statement, the variable will get disposed after the completion of the using statement's scope but still remain in scope. Accidental use of the variable after the using statement's scope may lead to exception to be thrown. This is considered to be bad practice and is avoided. I have never had reason to declare the variable before the using statement.


text:
Q: Outlook Web Addins-office 365 OWA getCallbackTokenAsync return "failed" but works fine with Outlook Client after recent UI update in OWA Regarding the addin which we have developed was working perfectly fine before the new UI update for Office 365 OWA,
I have used the getCallbackTokenAsync() to get the token for authentication in code for accessing some 'ExtendedProperty' from the mail mail object. Till now every thing was working smooth , but after the ui update getCallbackTokenAsync() returns 'failed' only in OWA but by using same User in outlook Client the addin works perfectly fine as expected.
Cannot imagin whats wrong here, Server returns token in Client but not in OWA?
Always new updates has more complications to debug.
Is it really the update ? or something with security on browsers?
Cannot even guess because its working at one place and not other platform.
Update 1:
Detailed error object in browser console;

So here if access restricted in OWA then the question is how it comes that access is granted via Outlook Client.
Update 2: Manifest and code for callback
Manifest------
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
           xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
           xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="MailApp">

  <!-- Begin Basic Settings: Add-in metadata, used for all versions of Office unless override provided. -->

  <!-- IMPORTANT! Id must be unique for your add-in, if you reuse this manifest ensure that you change this id to a new GUID. -->
  <Id>0ee7b924-eb57-414f-aeb3-0230b6a768ce</Id>

  <!--Version. Updates from the store only get triggered if there is a version change. -->
  <Version>1.0.0.0</Version>
  <ProviderName>Local</ProviderName>
  <DefaultLocale>de-de</DefaultLocale>

  <!-- The display name of your add-in. Used on the store and various places of the Office UI such as the add-ins dialog. -->
  <DisplayName DefaultValue="Retriever (V5) V1" >
  <Override Locale="en-US" Value="Version 5 (Stable)"/>
  </DisplayName>
  <Description DefaultValue=
   "Descriptiom">
   <Override Locale="en-US" Value=
   "Description (Angular V5 (BETA)."/>
</Description>

  <!-- Icon for your add-in. Used on installation screens and the add-ins dialog. -->
  <IconUrl DefaultValue="https://addin_url/assets/retriever-icon-32.png" />
  <HighResolutionIconUrl DefaultValue="https://addin_url/assets/retriever-hi-res-icon.png"/>

  <!--If you plan to submit this add-in to the Office Store, uncomment the SupportUrl element below-->
  <SupportUrl DefaultValue="https://addin_url" />

  <!-- Domains that will be allowed when navigating. For example, if you use ShowTaskpane and then have an href link, navigation will only be allowed if the domain is on this list. -->
  <AppDomains>
    <AppDomain>https://addin_url</AppDomain>
    <AppDomain>https://addin_url</AppDomain>
    <AppDomain>AppDomain3</AppDomain>
  </AppDomains>
  <!--End Basic Settings. -->

  <Hosts>
    <Host Name="Mailbox" />
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="Mailbox" MinVersion="1.1" />
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemRead">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://addin_url/#archived_mail_retrieve"/>
        <RequestedHeight>250</RequestedHeight>
      </DesktopSettings>
    </Form>
  </FormSettings>

  <Permissions>ReadWriteItem</Permissions>
  <Rule xsi:type="RuleCollection" Mode="Or">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Read" />
  </Rule>
  <DisableEntityHighlighting>false</DisableEntityHighlighting>

  <VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides" xsi:type="VersionOverridesV1_0">
    <Requirements>
      <bt:Sets DefaultMinVersion="1.5">
        <bt:Set Name="Mailbox" />
      </bt:Sets>
    </Requirements>

     <VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1" xsi:type="VersionOverridesV1_1">
         <Requirements>
            <bt:Sets DefaultMinVersion="1.5">
               <bt:Set Name="Mailbox" />
            </bt:Sets>
         </Requirements>
         <Hosts>
            <Host xsi:type="MailHost">
              <DesktopFormFactor>
                 <!-- Location of the Functions that UI-less buttons can trigger (ExecuteFunction Actions). -->
                 <FunctionFile resid="fnFile" />
                 <ExtensionPoint xsi:type="MessageReadCommandSurface">
            <!-- Use the default tab of the ExtensionPoint or create your own with <CustomTab id="myTab"> -->
            <OfficeTab id="TabDefault">
              <!-- Up to 6 Groups added per Tab -->
              <Group id="msgReadGroup">
                <Label resid="groupLabel" />
                <!-- Launch the add-in : task pane button -->
                <Control xsi:type="Button" id="msgReadOpenPaneButton">
                  <Label resid="paneReadButtonLabel" />
                  <Supertip>
                    <Title resid="paneReadSuperTipTitle" />
                    <Description resid="paneReadSuperTipDescription" />
                  </Supertip>
                  <Icon>
                    <bt:Image size="16" resid="icon16" />
                    <bt:Image size="32" resid="icon32" />
                    <bt:Image size="80" resid="icon80" />
                  </Icon>
                  <Action xsi:type="ShowTaskpane">
                    <SourceLocation resid="messageReadTaskPaneUrl" />
                  </Action>
                </Control>
                <!-- Go to http://aka.ms/ButtonCommands to learn how to add more Controls: ExecuteFunction and Menu -->
              </Group>
            </OfficeTab>
          </ExtensionPoint>

                 <!-- Go to http://aka.ms/ExtensionPointsCommands to learn how to add more Extension Points: MessageRead, AppointmentOrganizer, AppointmentAttendee -->
              </DesktopFormFactor>

               <MobileFormFactor>
                  <FunctionFile resid="fnFile" />
                  <ExtensionPoint xsi:type="MobileMessageReadCommandSurface">
                     <Group id="mobileGroupID">
                        <Label resid="residAppName" />
                        <Control xsi:type="MobileButton" id="TaskPaneBtn">
                           <Label resid="residTaskPaneButtonName" />
                           <Icon xsi:type="bt:MobileIconList">
                              <bt:Image size="25" scale="1" resid="icon16" />
                              <bt:Image size="25" scale="2" resid="icon16" />
                              <bt:Image size="25" scale="3" resid="icon16" />
                              <bt:Image size="32" scale="1" resid="icon16" />
                              <bt:Image size="32" scale="2" resid="icon16" />
                              <bt:Image size="32" scale="3" resid="icon16" />
                              <bt:Image size="48" scale="1" resid="icon16" />
                              <bt:Image size="48" scale="2" resid="icon16" />
                              <bt:Image size="48" scale="3" resid="icon16" />
                           </Icon>
                           <Action xsi:type="ShowTaskpane">
                              <SourceLocation resid="messageReadTaskPaneUrl" />
                           </Action>
                        </Control>
                     </Group>
                  </ExtensionPoint>
               </MobileFormFactor>
            </Host>
         </Hosts>
         <Resources>
            <bt:Images>
               <bt:Image id="icon16" DefaultValue="https://addin_url/assets/retriever-icon-16.png"/>
               <bt:Image id="icon32" DefaultValue="https://addin_url/assets/retriever-icon-32.png"/>
               <bt:Image id="icon80" DefaultValue="https://addin_url/assets/retriever-icon-80.png"/>
            </bt:Images>
            <bt:Urls>
               <bt:Url id="fnFile" DefaultValue="https://addin_url/#archived_mail_retrieve" />
               <bt:Url id="messageReadTaskPaneUrl" DefaultValue="https://addin_url/#archived_mail_retrieve" />
            </bt:Urls>
           <bt:ShortStrings>
              <bt:String id="groupLabel" DefaultValue="Addin-Group" />
              <bt:String id="customTabLabel" DefaultValue="Archiver-Tab" />
              <bt:String id="paneReadButtonLabel" DefaultValue="Retriever" />
              <bt:String id="paneReadSuperTipTitle" DefaultValue="Archived-Retriever" />
               <bt:String id="residTaskPaneButtonName" DefaultValue="Retriever" />
               <bt:String id="residAppName" DefaultValue="Archived-Retriever" />
               <bt:String id="residTaskpaneUrl" DefaultValue="Archived-Retriever" />
           </bt:ShortStrings>
           <bt:LongStrings>
               <bt:String id="paneReadSuperTipDescription" DefaultValue="Decription for Addins" />

           </bt:LongStrings>
         </Resources>
      </VersionOverrides>
      </VersionOverrides>
</OfficeApp>

Code getCallbackTokenAsync()
setConfig(data : any){
  this.config = data[0];
  config_array = data[0]
  console.log(data[0]);
  localStorage.setItem('app_config',JSON.stringify(data[0]));
  Office.context.mailbox.getCallbackTokenAsync({isRest: true, "asyncContext" : this.__archiveComponent}, function(result){
    if (result.status === "succeeded") {
      let accessToken = result.value;
    //  result.asyncContext.getSingleValueExtendedProperty(accessToken);  Commented because this function is no more called
      result.asyncContext.getMultiValueExtendedProperty(accessToken,data[0]);
    } else {
      console.log(result);
    }
});
}

The function gets the token and pass it to the fuction but the conditions fails and goes to the else condition and the result get printed in the browser console can see the image in Update 1.
Update 3
setConfig(data : any){
  this.config = data[0];
  config_array = data[0]
  console.log(data[0]);
  localStorage.setItem('app_config',JSON.stringify(data[0]));
  Office.context.mailbox.getCallbackTokenAsync({isRest: true, "asyncContext" : this.__archiveComponent}, function(result){
    if (result.status === "succeeded") {
      let accessToken = result.value;
        //Calling a function to get the token out of current fuction.
      result.asyncContext.getMultiValueExtendedProperty(accessToken,data[0]);
    } else {
      console.log(result);
    }
});
}

In the code above
Office.context.mailbox.getCallbackTokenAsync({isRest: true, "asyncContext" : this.__archiveComponent}, function(result)

Line says that "asyncContext" is issigned to the class object(I have created object of the class) that is this.__archiveComponent in order to access the functions in the class with the token by using
result.asyncContext.getMultiValueExtendedProperty(accessToken,data[0]);
So Now if I replace the Class Object for "asyncContext" with any string and print the token then Yes it works and prints the tocken with success, But not with Object
Note : This above code was working fine before the Office.js library update , After the update we got this issue with ""asyncContext".
If changed anything here then which is the correct the correct way to access the token out of the getCallbackTokenAsync() function. to pass on for authenticate Users??


text:
Q: Trying to put lua scripts into folders. Love2D Ok, so i've made a game using love2D and I tried converting it into a .app, because i'm running Mac OSX. But I got the error saying that main.lua needs to be that the top level of the .zip. So I tried putting all of my lua scripts into a folder leaving only the main.lua and the conf.lua in the top level of the .zip. But now love2D cannot find the other files in the folder. I tried putting the name of the directory when using "require." for instance:
    require "dir/player.lua"

but that wouldn't work...

A: Use
require "dir.player"

The dot . denotes a parent level, the .lua is not needed.


text:
Q: Yup date min doesn't work with Formik DatePicker I'm using yup validationSchema for Formik, however, when I'm trying to validate date, it doesn't work, validation for all other fields work correctly. What I'm doing wrong?
 const formSchema = yup.object({
     startsAt: yup.date().label('startsAt').required("Required").min(new Date(Date.now() -86400000), "Date cannot be in the past"),
     endsAt: yup.date().label('endsAt').required("Required").min(yup.ref('startsAt'),"End date can't be less than start date")
  })

Here is my DatePickers:
import { DatePicker } from 'formik-material-ui-pickers'
import { Formik, Field, Form} from 'formik'

  <Formik
    validationSchema={formSchema}
   >
    <Form>
    <Field
          component={DatePicker}
          format="MM/DD/YYYY"
          inputVariant="outlined"
          name="startsAt"
          label="Start Date"
          className={classes.dtPicker}
        />
        <Field
          component={DatePicker}
          format="MM/DD/YYYY"
          inputVariant="outlined"
          name="endsAt"
          label="End Date"
          className={classes.dtPicker}
        />
      </Form>
    </Formik>

A: Instead of:
startsAt: yup.date().label('startsAt').required("Required").min(new
Date(Date.now() -86400000), "Date cannot be in the past"),

try:
import {parse, isDate} from 'date-fns';
const parseDateString = (value, originalValue) =>
  isDate(originalValue) ? originalValue : parse(originalValue);

startsAt: yup.date().label('startsAt').required("Required")
.transform(parseDateString)
.min(
      new Date().setHours(0, 0, 0, 0),
      'Date cannot be in the past'
    ),


text:
Q: Probabilities playing bridge Being very bad with probabilities, I would greatly appreciate help for the following problem.
The first bid of my partner indicates that, among his $13$ cards, he handles $6$ hearts and a maximum of $3$ spades.
In my hand, I handle $0$ hearts and $6$ spades.
So, my question is : what are the probabilities corresponding to $0$, $1$, $2$ or $3$ spades in my partner's hand ?
Should I need to precise that this is not homework ?
Thnaks for your help.

A: There are 19 diamonds/clubs and 7 spades available, from which he is dealt 7 cards.
So number of ways of getting $k$ spades is ${7\choose k}{19\choose7-k}$. That gives 50388,189924,244188,135660. Hence the probabilities are 0 spades 8.125%, 1 spade 30.625%, 2 spades 39.375%, 3 spades 21.875%.

A: First of all, the probability will depend on the numbers of jacks, queens, kings and aces in your hand, since you know how many points your partner has.
But let's forget that extra piece of information, then your hand consists of $6$ high cards, denote that by $H$, and $7$ low cards, $L$. Then we want to find out $P(H_p = i)$ for $i =6,7,8,9$, given that you have $H_m =6$.
So we first find the number of ways to obtain $H_p =i$.
We have $6$ hearts out of a possible $13$ hearts.
We have $i-6$ spades out of a possible $7$ spades.
We have $13-i$ low cards out of a possible $19$ low cards.
So the number of combination wihich gives $H_p=i$ is
$$\binom{13}{6}\binom{7}{i-6} \binom{19}{13-i} .$$
As we know that $H_p$ lies between $6$ and $9$, we have
$$ P(H_p = i) = \frac{ \binom{13}{6} \binom{7}{i-6} \binom{19}{13-i}}{ \sum_{i=6}^9 \binom{13}{6} \binom{7}{i-6} \binom{19}{13-i}}.$$
This gives the probability on $n$ spades as $\frac{13}{160}$ for $0$, $\frac{49}{160}$ for $1$, $\frac{63}{160}$ for $2$ and $\frac{35}{160}$ for 3.
So let your partner know that you have quite a lot of spades, as in most cases you will have a fit in spades.


text:
Q: rails csv, array shows no data I am using csv to export data. I am dynamically populating the fields and in order to do so i have added loop in to csv:
csv_data = CSV.generate do |csv|
  csv << [
  @userHeaders.each do |user|
    "#{user.name}"
  end
  ]
end

but this returns some thing like this: [#<User >, #<User >, #<User >, #<User >]
but when i tried to inspect the value after assigning it to a variable, it displays all the names that have been passed.
name = "#{user.name}"
puts name.inspect  # (this diaplays all the names)

is there any format to display the data while looping inside csv?
please guide with answer
thanks

A: Try just using the map (aka collect) method of your array:
csv_data = CSV.generate do |csv|
  csv << @userHeaders.map { |user| user.name }
end


text:
Q: Open source popup/panel for actionscript 3? Does anybody have a solution for a popup (for a help panel)?  thanks.  this is in pure as3.

A: To use ActionScript 3 to open an HTML popup do something like this:
var url:String = "javascript:openNewWindow('test.html','thewin', 'height=200,width=250,toolbar=no,scrollbars=no')";
var request:URLRequest = new URLRequest(url);
try {
  navigateToURL(request, '_blank'); // second argument is target
} catch (e:Error) {
  trace("Error occurred!");
}

I am not sure what you mean by pure ActionScript. Do you want the pop-up to be in the SWF? If so then you can create a sprite and show or hide it based on an event.

A: You may use the PopUpManager of AS3Commons UI Layers. See also the Tutorial: Creating an alert box with the AS3Commons PopUpManager.


text:
Q: cannot test static asset For a scala project I'm using the test documentation to test this very simple controller that simply return a static asset
class HomeController @Inject() extends Controller {
  def index() =
    controllers.Assets.versioned(path="/public/data", "afile.json")
}

I started to made the following test for testing the json file :
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.http.Status
import play.api.test.FakeRequest
import play.api.test.Helpers._

class HomeControllerSpecTest extends PlaySpec with GuiceOneAppPerSuite {
  "HomeController" should {
    "render the index page" in {
      val home = route(app, FakeRequest("GET","/index/")).get
      status(home) mustBe Status.OK
    }
  }
}

When starting the serveur and checking with the browser the asset is well send/received BUT the test failed because of 404 status.
How assets can be tested ?


text:
Q: Angular mat-autocomplete with dynamic inputs I'm new in angular material design and I have a problem with mat-autocomplete for dynamic inputs. By default user see one input but when some value is selected than another input can be added and this is the tricky part - how to make that all those inputs will be using only one mat-autocomplete? Is it possible?
Below is code where I'm using mat-autocomplete. The addItem() function is adding another input which would be bind to the same mat-autocomplete. Should it be moved above ? And what about unique id? How can I solve this issue with multiple inputs connected to the same mat-autocomplete?

    <mat-form-field class="example-full-width">
        <input required type="text" placeholder="Item ID"
            matInput
            [formControlName]="i"
            [id]="i"
            [matAutocomplete]="auto">

        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let option of filteredOptions | async"
                [value]="option.code"
                (click)="selectOption(option, i)">
                {{option.code}}
            </mat-option>
        </mat-autocomplete>

    </mat-form-field>

A: You have to use multiple auto complete elements and all the inputs need to bind with array of valueChanges event capturing functions. The reason is if you're trying to bind valueChanges with formArray ("items") then the function will execute number of time that how many inputs in the array. Use the following code to achieve target.
for(var i = 0;i<numberOfInputElements;i++){
    const items = this.form.get('items') as FormArray;
    this.filteredOptions[index] = items.at(index).get('item').valueChanges
        .pipe(
          startWith(''),
          map((value: string) => (value) ? this._filter(value, this.options) : this.options.slice())
        );
}


text:
Q: One site takes a long time to make a connection, other sites on server fine On a CentOS server with multiple websites, one particular site takes a long time to respond to requests from some geographical areas, but not from other geographical areas. Other sites on the same server are not affected. For instance, if I try to reach the website without a proxy, then the site takes a long time to connect upwards of 10 seconds (confirmed with wget -p). As soon as the connection is made, the pages and images download very quickly. If I configure my browser to use a proxy through Amazon, then the site loads very quickly (no connection latency). I see nothing in the error logs that might give a clue.
Note that each site on this server has a different IP address. However, I don't see anything different about the configuration for this site's IP address, sites-enabled file, or anything else that might give a clue as to the origin of the issue.

A: The sites have same class (for ex. from the same /24 ) IP addresses? If the IP's are from different blocks i could imagine a routing problem with one block.
Second guess: the site tries to get the reverse DNS of the connecting IP, and that times out. Or maybe depending on the connecting geographical area does some API call's to different servers (and one server is down/slow)


text:
Q: Need help in placing dynamically button in iphone application using objective c language?
I need your help to create a button dynamically in iphone

Thanks

A: Cut and paste this into a View-based project's ProjectViewController.m file:
- (void) pressed:(id)sender
{
    NSLog( @"pressed!" );
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.contentMode = UIViewContentModeScaleToFill;
    UIImage *img = [UIImage imageNamed:@"myimage.png"];
    [btn setBackgroundImage:img forState:UIControlStateNormal];
    [btn setTitle:@"Button Title" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pressed:) forControlEvents:UIControlEventTouchUpInside];
    btn.frame = CGRectMake( 20, 20, 200, 100 );
    [self.view addSubview:btn];

}

The main thing to remember is that setBackgroundImage:forState: will stretch the image to fill the button's frame, while setImage:forState: will not.


text:
Q: PHP MySQL inserting 3 different form values to 4 different tables I need help with Php forms. I am trying to insert at least 2 & a Max of 3 team players data to MySQL for registration purposes.
By using a loop to get the 3 form values and iterate until data is stored in the tables
First Table is Players table:
columns names are as follows.
playerid, playerfirstname, playerlastname, playerdob, playernationalranking, playerphonenumber, playeremailaddress, playerpassportnumber,playerplayinghistory, playeraddress, playercountry
Second Table is Participants table:
columns names are as follows.
playerid, participtionid, championshipid, countryid, created_at, status (is deleted or not) , room_booking_status
Third Table is Photo links
Time, FileLocation, IP, idUsers, playerid
on top of that, another i need to insert to a 4th table and its teamplayers table:
column names are as follows.
Teamid, participtionid, countryid, idplayer1, idplayer2, idplayer3, TimeStamp
PHP code starts as follows:
if (!isset($_SESSION)) {
  session_start();
}
$editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    }
$colname_numRows = "-1";
    if (isset($_SESSION['MM_UserGroup'])) {
      $colname_numRows = $_SESSION['MM_UserGroup'];
    }
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {

        for($i=1;$i<4;$i++) {

        // combining date of birth
        $playerDob = $_POST['year'.$i]."-".$_POST['month'.$i]."-".$_POST['day'.$i];
        $playerDob = mysql_real_escape_string($playerDob);
          // first query
          $insertPlayerInfo = sprintf("INSERT INTO players (playerid, playerfirstname, playerlastname, playerdob, playernationalranking, playerphonenumber, playeremailaddress, playerpassportnumber, playerplayinghistory, playeraddress, playercountry) VALUES ('', %s, %s, '$playerDob', %s, %s, %s, %s, %s, %s, %s)",
        GetSQLValueString(str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($_POST['playerFirstName'.$i])))), "text"),
        GetSQLValueString(str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($_POST['playerLastName'.$i])))), "text"),
        GetSQLValueString($_POST['playerNationalRanking'.$i], "int"),
        GetSQLValueString($_POST['playerPhoneNumber'.$i], "text"),
        GetSQLValueString($_POST['playerEmailAddress'.$i], "text"),
        GetSQLValueString($_POST['playerPassportNumber'.$i], "text"),
        GetSQLValueString($_POST['playerPlayingHistory'.$i], "text"),
        GetSQLValueString($_POST['playerAddress'.$i], "text"),
        GetSQLValueString($_POST['playerCountryID'.$i], "int"));

        mysql_select_db($db, $EntrySystem);

        if($myPlayerInfoResult = mysql_query($insertPlayerInfo, $EntrySystem))
        {

            $_SESSION['playerid'.$i] = mysql_insert_id($EntrySystem) or die(mysql_error());

        // second query
            $insertSQL = sprintf("INSERT INTO participants (playerid, participationid, championshipid, countryid, created_at, status, room_booking_status) VALUES ('".$_SESSION['playerid'.$i]."','', %s, %s, %s, '1', '0')",
                           GetSQLValueString($_POST['championshipid'], "int"),
                           GetSQLValueString($_POST['countryid'], "int"),
                           GetSQLValueString($_POST['created_at'], "date"));

            mysql_select_db($db, $EntrySystem);

            if($myInsertSQL = mysql_query($insertSQL, $EntrySystem))
            { // if successfully submitted, proceed to next page
            $participationid = mysql_insert_id($EntrySystem)or die(mysql_error());
            $_SESSION['participationid'.$i] = $participationid;
            }

    if(!is_dir("upload/".$_SESSION['MM_Username'])) {

    mkdir("upload/".$_SESSION['MM_Username']);

                }

                        function savedata(){
                            global $_FILES, $_POST, $putItAt;
                            $sql = "INSERT INTO `db`.`photos`
                                (
                                `Time`,
                                `FileLocation`,
                                `IP`,
                                `countryid`,
                                `participationid`)
                        VALUES (NOW(),'".mysql_real_escape_string($putItAt)."', '". $_SERVER['REMOTE_ADDR']."', '". $_SESSION['MM_UserGroup']."'
                        ,'" .$_SESSION['participationid'.$i]."');";
                        mysql_query($sql) or die(mysql_error());
                        }

                        $putItAt = "upload/".$_SESSION['MM_Username']."/" .sha1(rand())."-" .basename($_FILES['uploadedfile'.$i]['name']);

                        $putItAt = str_replace("php", "txt" , $putItAt);

                        if(move_uploaded_file($_FILES['uploadedfile'.$i]['tmp_name'],$putItAt)) {

                            savedata();

                        } else {

                            if(copy($_FILES['uploadedfile'.$i]['tmp_name'],$putItAt)) {

                                savedata();

                            } else {

                                echo 'Image upload has not been successful. go back and try again.';
                            }

                        }

                        // Ids
            mysql_select_db($db, $EntrySystem);
            $insertTeamInfo = sprintf("INSERT INTO teamPlayers (Teamid, participationid, countryid, idplayer1, idplayer2, idplayer3, TimeStamp)
                                        VALUES('','".$_SESSION['participationid']."', %s,'".$_SESSION['playerID1']."', '".$_SESSION['playerID2']."', '".$_SESSION['playerID3']."','')",
                                        GetSQLValueString($_POST['countryid'], "int"));

            mysql_query($insertTeamInfo) or die(mysql_error());

            $insertGoTo = "myentries.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      }
      header(sprintf("Location: %s", $insertGoTo));

                    }

                }

        }

HTML Form goes here...
    <form enctype="multipart/form-data" method="post" name="form1" action="<?php echo $editFormAction; ?>">

Select Championship

          <select name="championshipid">
            <option>Select championship..</option>
            <?php
    do {
    ?>
            <option value="<?php echo $row_availableChampionships['championshipid']?>" ><?php echo $row_availableChampionships['championshipname']?></option>
            <?php
    } while ($row_availableChampionships = mysql_fetch_assoc($availableChampionships));
    ?>
          </select>

    // First table for selecting Championship

      Player 1

First Name

    <input type="text" name="playerFirstName1" value="" />
    <input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
    Choose a photo to upload: <input name="uploadedfile1" type="file" />
    <input name="countryid" type="hidden" value="<?php echo $_SESSION['MM_UserGroup']; ?>" />
    <input name="participationid" type="hidden" value="<?php echo $_SESSION['idparticipants']; ?>" />

Last Name
<input type="text" name="playerLastName1" value="" />
Date of Birth
          <select name="day1">
            <option>Day</option>
            <?php
    for ($day = 1; $day <= 31; $day++) {
    echo "<option value=\"$day\">$day</option>\n";
    }

    ?>
          </select>
          Please select an item.
            <select name="month1">
              <option>Month</option>
              <option value="01" >01-January</option>
              <option value="02" >02-February</option>
              <option value="03" >03-March</option>
              <option value="04" >04-April</option>
              <option value="05" >05-May</option>
              <option value="06" >06-June</option>
              <option value="07" >07-July</option>
              <option value="08" >08-August</option>
              <option value="09" >09-September</option>
              <option value="10" >10-October</option>
              <option value="11" >11-November</option>
              <option value="12" >12-December</option>
            </select>
              <select name="year1">
                <option>Year</option>
                <?php
     for ($year = 1950; $year <= 2005; $year++) {
    echo "<option value=\"$year\">$year</option>\n";
    }
      ?>
              </select>
              National Ranking
          <input type="text" name="playerNationalRanking1" value="" >
          Phone Number
          <input type="text" name="playerPhoneNumber1" value="" >

          Email Address
          <input type="text" name="playerEmailAddress1" value="">

        Passport Number
      <input type="text" name="playerPassportNumber1" value="">
       Playing History
        <textarea name="playerPlayingHistory1" value=""></textarea>

        Address

        <textarea name="playerAddress1" value=""></textarea>

    <input type="hidden" name="playerID1" value="">
      <input type="hidden" name="playerdob1" value="">
      <input type="hidden" name="playercountry1" value="<?php echo $_SESSION['MM_UserGroup']; ?>">
      <input type="hidden" name="idUsers1" value="<?php echo $_SESSION['MM_UserGroup']; ?>">
      <input type="hidden" name="created_at1" value="<?php
                                                                $now = new DateTime();
                                                                echo $now->format('Y-m-d H:i:s');?>">

      Player 2

First Name

    <input type="text" name="playerFirstName2" value="">
    <input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
    Choose a photo to upload: <input name="uploadedfile2" type="file" />
    <input name="countryid" type="hidden" value="<?php echo $_SESSION['MM_UserGroup']; ?>">
    <input name="participationid" type="hidden" value="<?php echo $_SESSION['idparticipants']; ?>">

Last Name
<input type="text" name="playerLastName2" value="">
Date of Birth
          <select name="day2">
            <option>Day</option>
            <?php
    for ($day = 1; $day <= 31; $day++) {
    echo "<option value=\"$day\">$day</option>\n";
    }

    ?>
          </select>
          Please select an item.
            <select name="month2">
              <option>Month</option>
              <option value="01" >01-January</option>
              <option value="02" >02-February</option>
              <option value="03" >03-March</option>
              <option value="04" >04-April</option>
              <option value="05" >05-May</option>
              <option value="06" >06-June</option>
              <option value="07" >07-July</option>
              <option value="08" >08-August</option>
              <option value="09" >09-September</option>
              <option value="10" >10-October</option>
              <option value="11" >11-November</option>
              <option value="12" >12-December</option>
            </select>
              <select name="year2">
                <option>Year</option>
                <?php
     for ($year = 1950; $year <= 2005; $year++) {
    echo "<option value=\"$year\">$year</option>\n";
    }
      ?>
              </select>
              National Ranking
          <input type="text" name="playerNationalRanking2" value="" >
          Phone Number
          <input type="text" name="playerPhoneNumber2" value="" >

          Email Address
          <input type="text" name="playerEmailAddress2" value="">

        Passport Number
      <input type="text" name="playerPassportNumber2" value="">
       Playing History
        <textarea name="playerPlayingHistory2" value=""></textarea>

        Address

        <textarea name="playerAddress2" value=""></textarea>

    <input type="hidden" name="playerID2" value="">
      <input type="hidden" name="playerdob2" value="">
      <input type="hidden" name="playercountry2" value="<?php echo $_SESSION['MM_UserGroup']; ?>">
      <input type="hidden" name="idUsers2" value="<?php echo $_SESSION['MM_UserGroup']; ?>">
      <input type="hidden" name="created_at2" value="<?php
                                                                $now = new DateTime();
                                                                echo $now->format('Y-m-d H:i:s');?>">

      Player 3

First Name

    <input type="text" name="playerFirstName3" value="">
    <input type="hidden" name="MAX_FILE_SIZE" value="5000000" >
    Choose a photo to upload: <input name="uploadedfile3" type="file" >
    <input name="countryid" type="hidden" value="<?php echo $_SESSION['MM_UserGroup']; ?>">
    <input name="participationid" type="hidden" value="<?php echo $_SESSION['idparticipants']; ?>">

Last Name
<input type="text" name="playerLastName3" value="">
Date of Birth
          <select name="day3">
            <option>Day</option>
            <?php
    for ($day = 1; $day <= 31; $day++) {
    echo "<option value=\"$day\">$day</option>\n";
    }

    ?>
          </select>
          Please select an item.
            <select name="month3">
              <option>Month</option>
              <option value="01" >01-January</option>
              <option value="02" >02-February</option>
              <option value="03" >03-March</option>
              <option value="04" >04-April</option>
              <option value="05" >05-May</option>
              <option value="06" >06-June</option>
              <option value="07" >07-July</option>
              <option value="08" >08-August</option>
              <option value="09" >09-September</option>
              <option value="10" >10-October</option>
              <option value="11" >11-November</option>
              <option value="12" >12-December</option>
            </select>
              <select name="year3">
                <option>Year</option>
                <?php
     for ($year = 1950; $year <= 2005; $year++) {
    echo "<option value=\"$year\">$year</option>\n";
    }
      ?>
              </select>
              National Ranking
          <input type="text" name="playerNationalRanking3" value="" >
          Phone Number
          <input type="text" name="playerPhoneNumber3" value="" >

          Email Address
          <input type="text" name="playerEmailAddress3" value="">

        Passport Number
      <input type="text" name="playerPassportNumber3" value="">
       Playing History
        <textarea name="playerPlayingHistory3" value=""></textarea>

        Address

        <textarea name="playerAddress3" value=""></textarea>

    <input type="hidden" name="playerID3" value="">
      <input type="hidden" name="playerdob3" value="">
      <input type="hidden" name="playercountry3" value="<?php echo $_SESSION['MM_UserGroup']; ?>">
      <input type="hidden" name="idUsers3" value="<?php echo $_SESSION['MM_UserGroup']; ?>">
      <input type="hidden" name="created_at3" value="<?php
                                                                $now = new DateTime();
                                                                echo $now->format('Y-m-d H:i:s');?>">

                <input type="hidden" name="MM_insert" value="form1">
            </form>

    <?php // }//end the if statement for the number of participants ?>

I don't know where I went wrong, some how it is not storing all the data, it stores 2 players and 2 participation and stores only one id in the teamsplayers table and 2 images in files table.
How do I get this script to work the way it should. All Suggestions are welcome.


text:
Q: Can't get ng2-translate to play ball in Nativescript/Angular application I'm attempting to build a Nativescript/Angular application with internationalisation. I researched my options and found that ng2-translate should do the trick, together with nativescript-ng2-translate, which should handle the loading of translation files.
However, this does not seem to work. I created an example project that has the same basic structure than my own project. It's a bog standard nativescript/angular project build from the tab template.
The translate pipe never does anything. Calling translate service directly also does not give any results. What am I doing wrong?
Code is here: https://github.com/JuergenSimon/translation-test

A: I did a lot of head banging with nativescript-ng2-translate plugin as well as with ngx-translate, however couldn't get either of them to work. Using ng2-translate with NativeScript http module seems to be the only way that works right now, at least it did for me. I referred this to make it work. Hope it helps you!

A: Actually I got it to work after all. What I was missing was to set a default language in app.component.ts. So ultimately, it looks like this:
app.module.ts:
import { NgModule, NgModuleFactoryLoader, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NSModuleFactoryLoader } from "nativescript-angular/router";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { TranslateModule, TranslateLoader, TranslateService } from "ng2-translate";
import { TNSTranslateLoader } from "nativescript-ng2-translate";

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        AppRoutingModule,
        TranslateModule.forRoot({
            provide: TranslateLoader,
            useFactory: () => new TNSTranslateLoader("/assets/i18n")
        })
    ],
    exports: [
        TranslateModule
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        {provide: NgModuleFactoryLoader, useClass: NSModuleFactoryLoader},
        TranslateService
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule {
}

Then imported the TranslateModule again in tabs.module.ts:
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";

import { BrowseComponent } from "./browse/browse.component";
import { HomeComponent } from "./home/home.component";
import { SearchComponent } from "./search/search.component";
import { TabsRoutingModule } from "./tabs-routing.module";
import { TabsComponent } from "./tabs.component";
import { TranslateModule, TranslateLoader } from "ng2-translate";
import { TNSTranslateLoader } from "nativescript-ng2-translate";

@NgModule({
    imports: [
        NativeScriptModule,
        TabsRoutingModule,
        TranslateModule
    ],
    declarations: [
        TabsComponent,
        HomeComponent,
        BrowseComponent,
        SearchComponent
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class TabsModule {
}

And set the default language in tabs.component.ts:
import { Component, OnInit } from "@angular/core";
import { isAndroid } from "platform";
import { SelectedIndexChangedEventData, TabView, TabViewItem } from "tns-core-modules/ui/tab-view";
import { TranslateService } from "ng2-translate";

@Component({
    selector: "TabsComponent",
    moduleId: module.id,
    templateUrl: "./tabs.component.html",
    styleUrls: ["./tabs.component.css"]
})
export class TabsComponent implements OnInit {
    private _title: string;

    constructor(private translate: TranslateService) {
        translate.setDefaultLang('en');
    }
    ...

The last step could possibly have been done in apps.component.ts as well. After that, the pipe and translate service worked fine.


text:
Q: How to use Stackdriver Structured Logging in App Engine Flex Java environment Google App Engine flexible environment automatically pipes stdout and stderr to Stackdriver (Google Cloud Logging). But this only supports plain text log message without any metadata (not even logging levels).
I found Logback appender for google cloud logging.
https://cloud.google.com/logging/docs/setup/java
But this does not seem to support structured logging yet.
And also, it makes GRPC calls for every log entry under the hood. So, I wonder how scalable it is (especially compare to current app engine structure which has separate Fluentd agent handles logs).
Is there any out of box or simple solution to send structured log from App Engine to Stackdriver?

A: You could use the Logback appender + Implement LoggingEnhacer
public class LogEnhancer implements LoggingEnhancer {

  @Override
  public void enhanceLogEntry(LogEntry.Builder logEntry) {
    // add Labels
    logEntry.addLabel("project", "conversational-services");

    // Transform textPayload to JSONPayload
    ObjectMapper mapper = new ObjectMapper();
    Builder structBuilder = Struct.newBuilder();
    String textPayload = logEntry.build().getPayload().getData().toString();
    try {
      // Validate JSON Payload
      mapper.readTree(textPayload);
      JsonFormat.parser().merge(textPayload, structBuilder);
      logEntry.setPayload(JsonPayload.of(structBuilder.build()));
    } catch (InvalidProtocolBufferException e) {
      // Error reporting an error! FML
      System.err.println(e.getMessage());
    } catch (IOException e) {
      // Do nothing (there is not a JSON Payload)
    }

  }

}

This class add labels and transform a JSON String in a JSONPayload
You need to specify the LoggingEnhacer on the logback.xml file
<!DOCTYPE configuration>
<configuration>
  <appender name="CLOUD" class="com.google.cloud.logging.logback.LoggingAppender">

    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
      <level>INFO</level>
    </filter>
    <log>application.log</log>
    <resourceType>gae_app</resourceType>
    <!--  References to the LoggingEnhacer class -->
     <enhancer>[path_for_your_logging_enhancer_class]</enhancer>
    <flushLevel>WARN</flushLevel>
  </appender>

  <root level="info">
    <appender-ref ref="CLOUD" />
  </root>
</configuration>

A: It's quite possible to do structured logging in StackDriver logging. In fact, each individual log entry uses the LogEntry structure. As you can see it includes severity and metadata.
According to the App Engine documentation, the following logs are provided out of the box:

Request logs record requests sent to all App Engine apps. The request log is provided by default and you cannot opt out of receiving it.
App logs record activity by software within the App Engine app. The
  log is provided by default and you cannot opt out of receiving it.
Runtime logs are provided from the flexible environment using a
  preinstalled Logging agent.


text:
Q: java script function disable using coding permanently
Blockquote

i want to disable java script checked box
'prevent this page from creating additional dialog'
permanently using coding.
please suggest me the right function

Blockquote

A: Sorry friend but You can not do this.
The javascript popup is a browser feature there to prevent sites from showing multiple alerts to prevent you from leaving.


text:
Q: Sitecore - Deleting Items from the workbox Is it possible to delete entries out of the workbox? I have some old items that still are in a draft state. When i press view item / view page I get the content tree without that specific item / a not found error. The workbox however is still showing those old and deleted files.

A: Firstly, thanks for the replies to my question.
I have tried all of the things suggested and found nothing to be working.
What I've done:

*

*Rebuild link database

*Cleared browser cache

*Checked the items still in the workflow for excistense (They didn't even excist in the content tree anymore...)

*Clean up database <- this one helped me out


text:
Q: Apex Trigger - Move Attachments from Task to Account I have a user which attached JPGs to the wrong object (Task vs Account). I wrote this trigger thinking I could quickly fix it but I am getting this error:
Error: Compile Error: Illegal assignment from LIST to SOBJECT:Account at line 9 column 13
Help! :D
trigger Update_Attachment_Parent on Attachment (after insert, after update) {
//Create a List to store the Ids of Attachments to be deleted
List<Id> forDeletionIds = new List<Id>();
for (Attachment a : trigger.new){
    //Check to see if the Attachment has a Task as the Parent Record
    String parentIdString = String.valueof(a.parentId);
    if (parentIdString.substring(0,3) == '00T'){
        //Select the AccountId from the Task
        Account parent = [SELECT AccountId FROM Task WHERE WhatId = :a.parentId];
        //Check to see if the Account exists
        if (parent.AccountID != null){
            //Select the Attachment body (it isn't in memory for an update)
            Attachment body = [SELECT Body FROM Attachment WHERE Id = :a.Id];
            //Create a new Attachment, preserving as much as is possible
            Attachment newA = New Attachment(
                Name = a.Name,
                Body = body.Body,
                ContentType = 'image/jpeg',
                Description = 'Account Photo',
                OwnerId = a.OwnerId,
                ParentId = parent.AccountId
            );
            //Insert the new Attachment
            insert newA;
            //Add the now duplicate Attachment ID to a list
            forDeletionIds.add(a.Id);
        }
    }
}
//List and then delete all duplicate Attachments
List<Attachment> forDeletion = [SELECT Id FROM Attachment WHERE Id IN :forDeletionIds];
delete forDeletion;
}

A: Account parent = [SELECT AccountId FROM Task WHERE WhatId = : a.parentId];

i think it is
task  parent =[SELECT AccountId FROM Task WHERE WhatId = : a.parentId];

There is a illegal assignment from task to account

A: now, after lots of different testings etc... i finally made the following trigger, which works totally great. feel free to share.
let me quickly summarize the background of this, I am activating email to salesforce, so if customers sending emails in, they will automatically attached to either relevant Lead or Account. Unfortunately, the attachment is usually saved to the Task but this doesn´t help our complaint and customer service center, as they want the attachments saved to the parent object, such as Lead or Account, so with the following trigger, it´s doing totally, what I expected, as well as deleting the attachment from task to avoid double attachments.

trigger MoveAtt on Attachment (after insert) {
      List forDeletionIds = new List();

for (Attachment a : trigger.new){
String parentIdString = String.valueof(a.parentId);
if (parentIdString.substring(0,3) == '00T'){
    System.debug(a.parentId);
    if(Task.WhatId != null){
        task parent1 = [SELECT Id,WhatId  FROM Task WHERE Id = :a.parentId];
    if (parent1.WhatId  != null){
        Attachment body = [SELECT Body FROM Attachment WHERE Id = :a.Id];
        Attachment newA = New Attachment(
            Name = a.Name,
            Body = body.Body,
            Description = 'Email Attachment from ' + date.today(),
            OwnerId = a.OwnerId,
            ParentId = parent1.WhatId
        );
    }
    task parent = [SELECT Id,WhoId  FROM Task WHERE Id = :a.parentId];
    if (parent.WhoId  != null){
        Attachment body = [SELECT Body FROM Attachment WHERE Id = :a.Id];
        Attachment newA = New Attachment(
            Name = a.Name,
            Body = body.Body,
            Description = 'Email Attachment from ' + date.today(),
            OwnerId = a.OwnerId,
            ParentId = parent.WhoId
        );
        insert newA;
        forDeletionIds.add(a.Id);
    }}}List<Attachment> forDeletion = [SELECT Id FROM Attachment WHERE Id IN :forDeletionIds];  delete forDeletion;
}}

A: Try using
 Account parent = [SELECT AccountId FROM Task WHERE WhatId = :a.parentId LIMIT 1];

UPDATE
You are trying to assign a Task record into an account, which is not possible. Instead you can save the id into ID variable
 ID parent = [SELECT AccountId FROM Task WHERE WhatId = :a.parentId LIMIT 1].Id;

and use this id instead


text:
Q: Using python I need to remove commas from my excel file and then convert it to csv I have the python code to convert an excel file to csv, however portions of the data in the excel file have commas which affects the conversion.
What would be the best way, staying within python, to remove the commas then convert?

A: If you can convert from excel to csv using a different delimiter, e.g. ; instead of comma, you can remove the commas from the converted file, then convert the csv delimiter (;) back to comma.


text:
Q: Resizable window + Vertical splitter? I have a resizable window using jQuery-UI, but I want to have a vertical splitter between two divs in the window as shown by this example here: http://methvin.com/splitter/vbasic.html
The problem is that the libraries will conflict with each other and give weird results while resizing the window, right? Does anyone know of any libraries for flexible, dynamic window sizes?


text:
Q: Oracle/SQL - Join one table multiple times to the same table I'm trying to wrap my brain around a query and hoping you can help.  I have two tables: a customer_table and a product_table that look like this
name    sku_num1    sku_num2    sku_num3    sku_num4
----------------------------------------------------
Bob     A           B           C           D
Frank   E           A
Tom     G
Shelly  G           E
Justin  E           G           A

sku_num     widget_name
-------------------
A           widget_a
B           widget_b
C           widget_c
D           widget_d

So what I want to do is return a list of all the customers who have at least 1 product whose SKU appears in the product table.  So with the above information I would receive back the records for
Bob
Frank
Justin
Any ideas how to do this?

A: There is no need to join one table twice:
SELECT *
FROM customers
WHERE sku_num1 IN (SELECT sku_num
                   FROM product_table)
   OR sku_num2 IN (SELECT sku_num
                   FROM product_table)
   ....

The reason why you need multiple conditions that do a full table scan on the product_table is your wrong database design. The products a customer bought should not go into multiple columns in the customer table. Instead you should have a third table that is a N:M relation between customer and products.

A: Does something like this not work?
select name
from customer c, products p
where ( c.sku_num1 = p.sku)
or    ( c.sku_num2 = p.sku)
or    ( c.sku_num3 = p.sku)
or    ( c.sku_num4 = p.sku)

A: Christopher,
Does this mean that you are just looking for any customers where sku_num1 or sku_num2 or sku_num3 or sku_num4 is not null?
If that's the case, you could do it two different ways.
select * from customers
    where sku_num1 is not null
    or sku_num2 is not null
    or sku_num3 is not null
    or sku_num4 is not null

If you are trying to see if they have ordered something from a specific product list, you could modify this to:
select * from customers
    where sku_num1 in (select sku_num from skus)
    or sku_num2 in (select sku_num from skus)
    or sku_num3 in (select sku_num from skus)
    or sku_num4 in (select sku_num from skus)

Incidentally, this is why people normally don't structure tables like this.  There should be another join table, for lack of anything better to call it, customer_skus which would tie together customers and skus and just have a customerID and a sku_num.
This would make the query easier to write, read, and maintain.  The query would look something like:
select distinct name from customers, customer_skus, skus
    where customers.id = customer_skus.id
    and customer_skus.sku_num = skus.sku_num

A: You can join a table with itself by using an alias:
select * from mytable a, mytable b where condition