text:
Q: Select duplicates in a one-to-many child table w/o using unique ID I have a table that stores a user's affiliation status. A user can be a student, faculty, staff, contractor, or any combination. That means for user 105433, he may show up as 4 lines in this table. Unfortunately a recent set of new hires have been inserted twice into the table, so users can have duplicate rows for the same affiliation.
Example rows:
Role_ID  --   Employee_ID   --    Employee Type
10000  --     203398      --      Faculty
10001   --    203398      --      Faculty
10002   --    203398     --       Student
10003   --    203542      --      Staff
10004  --     203542      --      Staff
10005    --   204844      --      Staff
10006    --   204844     --       Student
I want to remove the duplicate rows and be left with:
10000  --     203398      --      Faculty
10002   --    203398     --       Student
10003   --    203542      --      Staff
10005    --   204844      --      Staff
10006    --   204844     --       Student
I have already created a separate table and populated it with all the data that was inserted on the day of duplication if that is useful.
I used this query:
select tablename.*

from tablename

inner join (

        select MAX(role_id) as id from tablename GROUP BY employee_id

        )maxid ON tablename.role_id = maxid.id

        order by employee_id

This returns only one record per affiliation type per EMPLOYEEID, but I am unsure if I can delete using just this query. Help!

A: SELECT Role_ID, Employee_ID, Employee_Type, COUNT(*) AS cnt
FROM yourtable
GROUP BY Role_ID, Employee_ID, Employee_Type
HAVING cnt > 1

This will give you all of the duplicated records. You can select this into a temp table, then use the results to start deleting records.

A: If you're not sure that the data in the columns of your query are unique enough to identify just one record for each possible duplicate, I suggest adding ROWID to the query columns to be sure. e.g.
SELECT tablename.*, tablename.ROWID as DEL_ROWID
....

The values for ROWID uniquely identify single records. You can even use them in where clauses:
DELETE FROM tablename WHERE ROWID IN
  ( SELECT tablename.ROWID
    FROM ...... <same query>  )


text:
Q: [Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'length')" error when using datatables in vue In my laravel vuejs application I have following vue to display some data inside a datatable .
For the better user experience, I have added a Show more option to load data.
<show-more :data-size="documents.length" increment-amount="5" >

                    <action-bar :count="selectedForAction.count()">

                                <selectable-all item="selectAll" :data="documents" @select="selectAll"></selectable-all>

                                Document

                                Valid until

                                Validity

                        <button v-if="selectedForAction.count() === 1" @click="editSelectedDocument" class="flex items-center text-certstyle-titles text-sm mx-4" >

                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-2"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path></svg>

                            Edit
                        </button>
                        <button @click="removeSelectedDocument" class="flex items-center text-certstyle-titles text-sm mx-4" >

                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x-square"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="9" y1="9" x2="15" y2="15"></line><line x1="15" y1="9" x2="9" y2="15"></line></svg>

                            Remove
                        </button>
                    </action-bar>

                                <selectable
                                    v-model="selectedForAction"
                                    :item="documents[index].id"
                                    :ref="documents[index].id"
                                ></selectable>

                        {{ documents[index].name }}

{{ 'Indefinite'}}

{{ documents[index].expires_at_formatted }}

                        <status :status="documents[index].validity_status.toLowerCase()"></status>

                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-download"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>

                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>

                        <edit-documents-modal :document="documents[index]" :identifier="`editDocument${documents[index].id}`"></edit-documents-modal>

                    <button class="absolute border focus:outline-none hover:bg-certstyle-orange bg-white border-certstyle-orange hover:text-white text-certstyle-orange font-bold text-sm rounded px-4 py-1 mt-32 " v-if="showAmount < documents.length" @click="showMore">
                        show more documents
                    </button>

        </show-more>

Now the issue is, When I tried to run this, I get following console error and my data table is not getting displayed. Not even the headers...

[Vue warn]: Error in render: "TypeError: Cannot read properties of
undefined (reading 'length')"

A: Its better to use computed property to handle these situations
computed: {
 getDocumentSize() {
  return this.documents ? this.documents.length : 0;
 }
}

and in template, do the below change
<show-more :data-size="getDocumentSize" increment-amount="5" >
....

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I unlock Sniper's "The Last Wave" TF2 achievement? I'm currently attempting to achieve TF2 achievements, and I can't seem to obtain "The Last Wave":

The Last Wave
  Provide an enemy with a freezecam shot of you waving to them.

I am under the impression that you just have to taunt with your primary as Sniper after getting a kill, but after doing this many times with lots of different delays between the kill and the taunt I still haven't unlocked the achievement. I have achieved other achievements since I started trying for that one.
The only modifications I've made are a tf2mate config and frankenhud

A: There appears to be a bug by which you only obtain this achievement when you obtain the "Be Polite" achievement: once you've provided a freeze cam of each your melee taunt and your primary taunt you get both. Odd.


text:
Q: post increment inside an if statement My output is always 10 even though half of my answers are wrong.
package LabExercise;

import java.util.Scanner;
import java.util.InputMismatchException;

public class LabExer5B {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        try {

            String[] Questions = new String[10];
            String[] Choice = new String[10];
            Questions[0] = "1. What is the biggest island in the Philippines?";
            Questions[1] = "2. Jose Rizal's birthday?";
            Questions[2] = "3. Jose Rizal's death anniversary?0";
            Questions[3] = "4. What is the capital of the Philippines?";
            Questions[4] = "5. Festival held in Baguio City every february?";
            Questions[5] = "6. Andres Bonifacio's birthday?";
            Questions[6] = "7. Independence day of Philippines?";
            Questions[7] = "8. How many islands are there in the Philippines?";
            Questions[8] = "9. One of Jose Rizal's famous novel when he was imprisoned?";
            Questions[9] = "10. Writer of Lupang Hinirang?";

            Choice[0] = "A. Luzon \nB. Mindanao \nC. Visayas";
            Choice[1] = "A. June 19 \nB. December 30 \nC. November 2";
            Choice[2] = "A. April 20\nB. December 30 \nC. October 15";
            Choice[3] = "A. Manila City \nB. Taguig City \nC. Quezon City";
            Choice[4] = "A. Mascara Festival \nB. Sinulog \nC. Panagbenga Festival";
            Choice[5] = "A. March 18 \nB. October 28 \nC. November 30";
            Choice[6] = "A. June 12 \nB. October 25 \nC. July 19";
            Choice[7] = "A. 7107 \nB. 7023 \nC. 7192";
            Choice[8] = "A. Noli Me Tangere \nB. Florante at Laura \nC. Ibong Adarna";
            Choice[9] = "A. Sharon Cuneta \nB. Julian Felipe \nC. Rico Puno";

            String[] Answers = {"A", "A", "B", "A", "C", "C", "A", "A", "A", "B"};
            String[] Letter = new String[10];
            boolean CAnswers = false;
            int score = 0;

            int j = 0;
            for(int i = 0; i < 10;i++){
                 System.out.println(Questions[i]);
                System.out.println(Choice[i]);
                System.out.println("Enter your answer: ");

                Letter[j] = input.nextLine();
                if (Letter[j].equalsIgnoreCase(Answers[j])){
                    score++;
                }
            }
            System.out.println("Your score is " + score);
        } catch (InputMismatchException e) {
            System.out.println("Please input a letter");
        }
    }
}

I think it is not reading my if statement, do I need to change the if statement?

A: Why do you have i and j? You only change i, j stays 0 forever and therefore you always compare the first entry of Answers, an "A".
Solution: remove the j and replace where it was used with an i.
Optionally: remove Letter as an array entirely and just have a single String givenAnswer = input.nextLine(); in the loop.


text:
Q: WPF Button CommandParameter not passed properly to Command I have problem with passing CommandParameter to my Command
I have command:
private Command<Boolean> _setAsCompletedCommand;
public Command<Boolean> SetAsCompletedCommand
{
    get
    {
        return _setAsCompletedCommand ?? (_setAsCompletedCommand = new Command<Boolean>(isToComplete =>
        {
            if (isToComplete)
            {
                //do something
            }
            else
            {
                //do something else
            }
        }, isToComplete =>
        {
            if (isToComplete)
            {
                //check something
            }
            else
            {
                //check something else
            }

        }));
    }
}

and I'm trying to pass system:Boolean like this:
<Button
    Command="{Binding SetAsCompletedCommand}">
    <Button.CommandParameter>
        <system:Boolean>
            True
        </system:Boolean>
    </Button.CommandParameter>
</Button>

The problem is that on construction of a View my SetAsCompletedCommand.CanExecute() is executed with False parameter.
How is it possible? How can I fix it?
When I click the button CommandParameter is set properly to True
I'm using Catel framework as a MVVM framework in this project. But I don't think it produces the problem.

A: This is very tricky and is caused by the order of binding execution. As soon as the binding updates, WPF runs the CanExecute on your command. At this stage the CommandParameter isn't bound yet and Catel uses the default value of a Boolean (which is false) to use as the command parameter.
After that, commands are only being re-evaluated when a property changes. For example, there is no reason for Catel to invalidate the commands state unless a property changes.
One solution to fix this is to use CommandManager.InvalidateCommands(true) in the InitializeAsync of your view model. This will invalidate the state of all commands on the vm and re-evaluate them (and at this stage, the binding for the command parameter is correct).
You might ask yourself: "Why don't you re-evaluate automatically in the initialize method?".
Well, we did in the past, but we wanted to provide better performance out of the box. This is probably the first time you are using a command parameter that hits this restriction, but I think you created many more commands in the past. It means that you had a performance improvements on all the other commands so far, so I still think it's a good decision. There are sufficient workarounds as well to get back the old behavior where it used the CommandManager of WPF to re-evaluate commands on nearly every routed event (mouse move, keyboard, etc).

A: To start, I wouldn't ever create a property this way. You should stick to simple properties and let the command itself do all the work. I would suggest writing a custom command and have it inherit from a command base class like this one:
using System;
using System.Windows.Input;

namespace MyCommands
{
    /// <summary>
    /// Base class for all Commands.
    /// </summary>
    public abstract class CommandBase : ICommand
    {
        /// <summary>
        /// Defines the method that determines whether the command can execute in its current
        /// state.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data
        /// to be passed, this object can be set to null.</param>
        /// <returns>
        /// true if this command can be executed; otherwise, false.
        /// </returns>
        public virtual bool CanExecute(object parameter)
        {
            return true;
        }

        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data
        /// to be passed, this object can be set to null.</param>
        public virtual void Execute(object parameter) {}

        /// <summary>
        /// Occurs when changes occur that affect whether or not the command should execute.
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}

For there, you can specify the conditions that allow your command to execute and what it should do when it is executed by simply overriding CanExecute and Execute respectively.


text:
Q: How to value comparative Likert results
I have absolutely no knowledge of statistics. My question is how to make sense of some evaluation results I received. The attached graph represents my results of a Likert question compared to my department, division, and college. My question is, how should I interpret these results? While I have more students who "strongly agree" on this question, I have fewer who merely "agree." What interpretations of my performance are authorized here? Am I performing better? Similarly? Is there some empirically valid way of making assertions about this data?
There are twelve other such graphs, and I have to write a summary of the findings. But it is hard for me to know what kind of claims I can make based on the data.

A: I believe what you should do is to compare your distribution with the distribution for college, department, etc. The null hypothesis (think of it as a baseline case you would stick to until proven otherwise) is that your results are from the same distribution, so while asking students you did not introduce some selection (for example asking only student before the first class started, so late-comers did not show up in your results). Tip for the future questions and for your report: always make clear how your data was collected.
To answer your question you should perform some visualizations and testing. For visualization I would opt for having 4 separate histograms on one graph: that would do visual comparison of distributions better. For testing you should perform a number of tests: Mann-Whitney's U, Wilcoxon signed-rank test and Sign test. Wikipedia are quite good on the limitations of these tests and assumptions behind them.


text:
Q: Network control on Windows How do I control the network interface on Windows? Actually, the idea is quiet simple.

*

*Establish connect to a certain adapter on a computer.

*Direct whole traffic of the adapter to this program.

*Give the rights to this program what must be transfer to the adapter and what should not.
I think the program has to implement any windows network adapter interface and be registered as an adapter driver. Thus, when it wants to transfer data to real adapter, the program has to call adapter driver methods. In their turn, the methods implement the same windows network interface (or that is called in other way don't really know, I hope you get the sense), don't they?
As a result, we have a kind of inheritance here.
Before use our new driver:
windows application and windows itself
________________________  windows network interface
DRIVER of Adapter1
________________________ end of OS boundaries
Adapter 1
Use our new driver:
windows application and windows itself
________________________  windows network interface
our DRIVER
________________________  windows network interface
DRIVER of Adapter1
________________________ end of OS boundaries
Adapter 1
I believe that kind of interface exists and I hope it is realized very easy.

A: You will likely need to hook Windows API calls to really do this. It is possible... Start by Googling hook API and Winternals - and see if you can find their sample code.
Before Winternals was bought by Microsoft they published their code. http://technet.microsoft.com/en-us/sysinternals/bb545021
The idea is this:

*

*You write a user-mode program which controls your hooking device
driver.

*Your hooking device driver determines if network traffic on
given API calls is ok.

*Driver allows normal API calls to succeed if they are.


text:
Q: Best method of organizing database? MORE DETAILS:
Both of you recomend using JOIN. But the main problem is how to assign multiple SUBJECTS PER EACH CLASS without using multiple duplicate values. I will have ~200 de classes, with ~30 subjects per class. That means if 2 classes share the same 20 subjects, i will have 40 rows, all with "class_id = 1" but with "subjects_Id =1, subjects_id=2, etc" Its not very ergonomic. Any other ideas? Thanks for your time!
So, I am here again asking for your time and help friends.
I have a database that its almost ok. But I am stuck at trying how to link multiple values from a table to on collumn on another.
Let me be more explicit.
I have this table:
    CLASSES
id | class_name | Matters   |
-----------------------------
1  | Class1     | 13.4.2013 |
2  | Class2     | 14.4.2013 |

And this table:
Subjects
mat_id | show title |
-----------------
   1   | English    |
   2   | French     |

Now the problem is this. Each CLASS (e.g. CLASS1) should be able to study more Subjects at once. For example, CLASS 1 should be linked with subject (mat_id) 1, 3, 5, 6.
How to do this without repeating myself, and optimize the database? I tought that I should do it like so, but its not convenient :
CREATE A NEW TABLE named
SUBJECTS_PER_CLASS
id | class_id   | mat_id    |
----------------------------
1  | 1          | 1         |
2  | 1          | 3         |

BUT then I dont know how to query it. Any ideas? Any help will be greatly appreciated!
THANKS!

A: SELECT
 *
FROM
  CLASSES
JOIN
  SUBJECTS_PER_CLASS
ON
  CLASSES.ID = SUBJECTS_PER_CLASS.class_id
JOIN
  Subjects
ON
  Subjects.id = SUBJECTS_PER_CLASS.mat_id

A: You can use join command.
Reference 1
Reference 2


text:
Q: How to get a path to a resource in a Java JAR file I am trying to get a path to a Resource but I have had no luck.
This works (both in IDE and with the JAR) but this way I can't get a path to a file, only the file contents:
ClassLoader classLoader = getClass().getClassLoader();
PrintInputStream(classLoader.getResourceAsStream("config/netclient.p"));

If I do this:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("config/netclient.p").getFile());

The result is:
java.io.FileNotFoundException: file:/path/to/jarfile/bot.jar!/config/netclient.p (No such file or directory)
Is there a way to get a path to a resource file?

A: if netclient.p is inside a JAR file, it won't have a path because that file is located inside other file. in that case, the best path you can have is really file:/path/to/jarfile/bot.jar!/config/netclient.p.

A: This is deliberate.  The contents of the "file" may not be available as a file.  Remember you are dealing with classes and resources that may be part of a JAR file or other kind of resource. The classloader does not have to provide a file handle to the resource, for example the jar file may not have been expanded into individual files in the file system.
Anything you can do by getting a java.io.File could be done by copying the stream out into a temporary file and doing the same, if a java.io.File is absolutely necessary.

A: When loading a resource make sure you notice the difference between:
getClass().getClassLoader().getResource("com/myorg/foo.jpg") //relative path

and
getClass().getResource("/com/myorg/foo.jpg")); //note the slash at the beginning

I guess, this confusion is causing most of problems when loading a resource.

Also, when you're loading an image it's easier to use getResourceAsStream():
BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/com/myorg/foo.jpg"));

When you really have to load a (non-image) file from a JAR archive, you might try this:
File file = null;
String resource = "/com/myorg/foo.xml";
URL res = getClass().getResource(resource);
if (res.getProtocol().equals("jar")) {
    try {
        InputStream input = getClass().getResourceAsStream(resource);
        file = File.createTempFile("tempfile", ".tmp");
        OutputStream out = new FileOutputStream(file);
        int read;
        byte[] bytes = new byte[1024];

        while ((read = input.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.close();
        file.deleteOnExit();
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
} else {
    //this will probably work in your IDE, but not from a JAR
    file = new File(res.getFile());
}

if (file != null && !file.exists()) {
    throw new RuntimeException("Error: File " + file + " not found!");
}

A: You need to understand the path within the jar file.
Simply refer to it relative.   So if you have a file (myfile.txt), located in foo.jar under the \src\main\resources directory (maven style).  You would refer to it like:
src/main/resources/myfile.txt

If you dump your jar using jar -tvf myjar.jar  you will see the output and the relative path within the jar file, and use the FORWARD SLASHES.

A: In my case, I have used a URL object instead Path.
File
File file = new File("my_path");
URL url = file.toURI().toURL();

Resource in classpath using classloader
URL url = MyClass.class.getClassLoader().getResource("resource_name")

When I need to read the content, I can use the following code:
InputStream stream = url.openStream();

And you can access the content using an InputStream.

A: The one line answer is -
String path = this.getClass().getClassLoader().getResource(<resourceFileName>).toExternalForm()

Basically getResource method gives the URL. From this URL you can extract the path by calling toExternalForm().

A: follow code!
/src/main/resources/file
streamToFile(getClass().getClassLoader().getResourceAsStream("file"))

public static File streamToFile(InputStream in) {
    if (in == null) {
        return null;
    }

    try {
        File f = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        f.deleteOnExit();

        FileOutputStream out = new FileOutputStream(f);
        byte[] buffer = new byte[1024];

        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }

        return f;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    }
}

A: A File is an abstraction for a file in a filesystem, and the filesystems don't know anything about what are the contents of a JAR.
Try with an URI, I think there's a jar:// protocol that might be useful for your purpouses.

A: I spent a while messing around with this problem, because no solution I found actually worked, strangely enough! The working directory is frequently not the directory of the JAR, especially if a JAR (or any program, for that matter) is run from the Start Menu under Windows. So here is what I did, and it works for .class files run from outside a JAR just as well as it works for a JAR. (I only tested it under Windows 7.)
try {
    //Attempt to get the path of the actual JAR file, because the working directory is frequently not where the file is.
    //Example: file:/D:/all/Java/TitanWaterworks/TitanWaterworks-en.jar!/TitanWaterworks.class
    //Another example: /D:/all/Java/TitanWaterworks/TitanWaterworks.class
    PROGRAM_DIRECTORY = getClass().getClassLoader().getResource("TitanWaterworks.class").getPath(); // Gets the path of the class or jar.

    //Find the last ! and cut it off at that location. If this isn't being run from a jar, there is no !, so it'll cause an exception, which is fine.
    try {
        PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(0, PROGRAM_DIRECTORY.lastIndexOf('!'));
    } catch (Exception e) { }

    //Find the last / and cut it off at that location.
    PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(0, PROGRAM_DIRECTORY.lastIndexOf('/') + 1);
    //If it starts with /, cut it off.
    if (PROGRAM_DIRECTORY.startsWith("/")) PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(1, PROGRAM_DIRECTORY.length());
    //If it starts with file:/, cut that off, too.
    if (PROGRAM_DIRECTORY.startsWith("file:/")) PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(6, PROGRAM_DIRECTORY.length());
} catch (Exception e) {
    PROGRAM_DIRECTORY = ""; //Current working directory instead.
}

A: This is same code from user Tombart with stream flush and close to avoid incomplete temporary file content copy from jar resource and to have unique temp file names.
File file = null;
String resource = "/view/Trial_main.html" ;
URL res = getClass().getResource(resource);
if (res.toString().startsWith("jar:")) {
    try {
        InputStream input = getClass().getResourceAsStream(resource);
        file = File.createTempFile(new Date().getTime()+"", ".html");
        OutputStream out = new FileOutputStream(file);
        int read;
        byte[] bytes = new byte[1024];

        while ((read = input.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
        input.close();
        file.deleteOnExit();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
} else {
    //this will probably work in your IDE, but not from a JAR
    file = new File(res.getFile());
}

A: The following path worked for me: classpath:/path/to/resource/in/jar

A: private static final String FILE_LOCATION = "com/input/file/somefile.txt";

//Method Body

InputStream invalidCharacterInputStream = URLClassLoader.getSystemResourceAsStream(FILE_LOCATION);

Getting this from getSystemResourceAsStream is the best option.  By getting the inputstream rather than the file or the URL, works in a JAR file and as stand alone.

A: It may be a little late but you may use my library KResourceLoader to get a resource from your jar:
File resource = getResource("file.txt")

A: When in a jar file, the resource is located absolutely in the package hierarchy (not file system hierarchy). So if you have class com.example.Sweet loading a resource named ./default.conf then the resource's name is specified as /com/example/default.conf.
But if it's in a jar then it's not a File ...

A: Inside your ressources folder (java/main/resources) of your jar add your file (we assume that you have added an xml file named imports.xml), after that you inject ResourceLoader if you use spring like bellow
@Autowired
private ResourceLoader resourceLoader;

inside tour function write the bellow code in order to load file:
    Resource resource = resourceLoader.getResource("classpath:imports.xml");
    try{
        File file;
        file = resource.getFile();//will load the file
...
    }catch(IOException e){e.printStackTrace();}

A: Maybe this method can be used for quick solution.
public class TestUtility
{
    public static File getInternalResource(String relativePath)
    {
        File resourceFile = null;
        URL location = TestUtility.class.getProtectionDomain().getCodeSource().getLocation();
        String codeLocation = location.toString();
        try{
            if (codeLocation.endsWith(".jar"){
                //Call from jar
                Path path = Paths.get(location.toURI()).resolve("../classes/" + relativePath).normalize();
                resourceFile = path.toFile();
            }else{
                //Call from IDE
                resourceFile = new File(TestUtility.class.getClassLoader().getResource(relativePath).getPath());
            }
        }catch(URISyntaxException ex){
            ex.printStackTrace();
        }
        return resourceFile;
    }
}

A: This Class function can get absolute file path by relative file path in .jar file.

public class Utility {

    public static void main(String[] args) throws Exception {
        Utility utility = new Utility();
        String absolutePath = utility.getAbsolutePath("./absolute/path/to/file");
    }

    public String getAbsolutePath(String relativeFilePath) throws IOException {
        URL url = this.getClass().getResource(relativeFilePath);
        return url.getPath();
    }
}

If target file is same directory with Utility.java, your input will be ./file.txt.
When you input only / on  getAbsolutePath(), it returns /Users/user/PROJECT_NAME/target/classes/. This means you can select the file like this /com/example/file.txt.


text:
Q: Any clever way to unescape data from JSON string? I am sending some jsonrpc requests to a web2py server, with a celery backend. Sometimes, I get errors which I want to analyze. The errors come escaped in the jsonrpc reply, so they are not easy to understand. I get something like this:
{"version": "1.1", "id": "ID4", "error": {"message": "TypeError: 'NoneType' object does not support item assignment", "code": 100, "data": ["  File \"/home/myuser1/tmp/web2py/gluon/tools.py\", line 4068, in serve_jsonrpc\n    s = methods[method](*params)\n", "  File \"/home/myuser1/tmp/web2py/applications/mycompany_portal/controllers/activity.py\", line 66, in get_cdr_page\n    invalidate_cache = pars['invalidate_cache'], use_long_polling = pars['use_long_polling'])\n", "  File \"/home/myuser1/projects/new-mycompany-portal/python_modules/pmq_client.py\", line 85, in get_page\n    res = result.get(timeout=10)\n", "  File \"/home/myuser1/.virtualenvs/python2.7.2-mycompany1/lib/python2.7/site-packages/celery/result.py\", line 119, in get\n    interval=interval)\n", "  File \"/home/myuser1/.virtualenvs/python2.7.2-mycompany1/lib/python2.7/site-packages/celery/backends/amqp.py\", line 138, in wait_for\n    raise self.exception_to_python(meta['result'])\n"], "name": "JSONRPCError"}}

What I want is to get the error.data part of the jsonrpc reply, unescape it and display it as a stacktrace. I can do it manually (change \" -> " and process the \n), but I would like to avoid reinventing the wheel here.

A: Is this raw unparsed JSON? Parse it as JSON:
import json
print ''.join(json.loads(yourstring)['error']['data'])

A: Re-edit:
Use:
unquote
http://docs.python.org/2/library/urllib.html#urllib.unquote
or
unquote_plus
http://docs.python.org/2/library/urllib.html#urllib.unquote_plus
for unescape-ing HTTP-like data (ie. percentage-escaping)
See this question and answers for more info:
Unescape Python Strings From HTTP
And, for unescape-ing regular escaped symbols (ie. backslashes), use .decode() (counterpart of .encode()). See these answers:
https://stackoverflow.com/a/10944959/1284631
https://stackoverflow.com/a/9340191/1284631


text:
Q: how to populate an aspx bulletedList control with records from a database to show the bulletts Hi I have a ASPX Bulletted list control
                <asp:BulletedList id="blProductsBulletedList"
                BulletStyle="Disc"
                DataTextField="CheckListsFriendlyName"
                runat="server">
            </asp:BulletedList>

and i have a single column datatable bound to it in the page load:
            string strSQLQuery = "SELECT [CheckListsFriendlyName] FROM [SingleEnded2].[dbo].[WOCFriendlyNames]";
        // Run the query and bind the resulting DataSet
        // to the GridView control.
        DataTable dt = getCheckListExampleList(strSQLQuery);
        if (dt.Rows.Count > 0)
        {
            blProductsBulletedList.DataSource = dt;
            blProductsBulletedList.DataBind();
        }

        }

further down in the cs file is the 'getCheckListExampleList()':
        DataTable getCheckListExampleList(string strSQLQuery)
    {
        SqlConnection seConnection = new SqlConnection(Databases.getDbConnectionString("csSingleEnded2"));
        DataTable dt = new DataTable();
        SqlCommand seCmd = new SqlCommand(strSQLQuery, seConnection);
        try
        {
            SqlDataAdapter sda = new SqlDataAdapter();
            seCmd.Connection = seConnection;
            sda.SelectCommand = seCmd;
            sda.Fill(dt);
        }
        catch (Exception ex){
            // The connection failed. Display an error message.
            throw new Exception("Unable to connect to the database", ex);
        }
        return dt;
      }

This works, however the list does not appear bulleted and just appears as if its just a view of the records. Can anyone point me in the right direction to show each result as a bulleted list item and also after X amount of results add titles to split the results up into sections?


text:
Q: User friendly ubuntu distribution for Old PowerBook G4 15" I have Mac PB G4 15" 1.5 with 512mb RAM, and need to use it office style, maybe some graphic processing but nothing fancy, I need, a user friendly distribution that could bring out the best of this nice machine.

A: Xubuntu would be best for this. Some other people have gone through it here
http://ubuntuforums.org/showthread.php?t=1147883
I'd say download the live CD or USB and give it a try see how quick it is.


text:
Q: Read Network Requests and Response Headers - Chrome Extension V3 I can't seem to figure out how to read, but not modify, the outgoing network requests and response headers for a chrome extension in manifest v3. From my experimentation, declarativeNetRequest and the rule definitions are primarily geared around modifying the request / response header, but all I want to do is to read the request URL and the response headers. Any help would be appreciated.

A: declarativeNetRequests is not the right chrome API for collecting request/response headers. You need to add a permission for webRequest. Here is how you get them in background.js with web
chrome.webRequest.onCompleted.addListener(async function(details) {
    // get response headers here here
}, {urls: ['<all_urls>']}, ['responseHeaders'])

chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
    // get request headers here
}, {urls: ['<all_urls>']}, ['requestHeaders'])


text:
Q: Angular: after moving from Karma to Jest, Error "Unrecognized CLI Parameters" I updated my project from Angular 6.4 to Angular 7.1 and now running the script: ng test app-name --coverage gives me the error:
● Unrecognized CLI Parameters:

  Following options were not recognized:
  ["main", "polyfills", "tsConfig"]

  CLI Options Documentation:
  https://jestjs.io/docs/en/cli.html

The configuration for the test command in angular.json looks like this:
"test": {
  "builder": "@angular-builders/jest:run",
  "options": {
    "main": "apps/app-name/src/test.ts",
    "polyfills": "apps/app-name/src/polyfills.ts",
    "tsConfig": "apps/app-name/tsconfig.spec.json",
    "configPath": "./jest.config.json",
    "styles": [
      "apps/app-name/src/styles.scss"
    ],
    "scripts": [],
    "assets": [
      "apps/app-name/src/favicon.ico",
      "apps/app-name/src/assets"
    ]
  }
},

How am I supposed to update the config to be compatible with Angular 7?

A: The error was that I forgot to remove/replace the old karma-builder configuration when I moved to Jest.
Apparently Angular 7 checks things like that better than Angular 6 (hooray!), so I mistook it for an Angular or Jest bug.


text:
Q: Specify custom resolution in XCom I have the Steam version of XCom Enemy Within, and wish to configure it to use a higher resolution than the highest it gives me (1440 x 900).
I have modified my /Users/<user>/Library/Application Support/Steam/SteamApps/common/XCom-Enemy-Unknown/XCOMData/XComGame/Config/DefaultEngine.ini file to ensure it contains the following:
[SystemSettings]
ResX=1920
ResY=1080

But this has had no effect. A similar modification worked for me when I was playing this game on Windows 8.1.
Is it possible to play this game with custom resolutions on OS X, or has this facility been disabled for some reason?
Update:
I've also updated ~/Library/Application Support/Feral Interactive/XCOM Enemy Unknown/XEW/MacInit/XComEngine.ini with the same content, to no avail.

A: You can set the launch options to
-ResX=1920 -ResY=1080

Any options from http://udn.epicgames.com/Three/CommandLineArguments.html#Rendering  should work.


text:
Q: Reading FormData object into Java HTTP Triggered Azure Functions I recently created an HTTP Triggered Java Azure function to handle some of my backend tasks. This Azure-Functions main purpose was to accept/read in image files wrapped in a javascript FormData Object
and upload the files to my azure blob storage.
I've been searching online but wasn't able to find a working example of how to read in a File from a FormData Object in java? I've seen some examples of this being done with azure functions in C# and
node.js.
Here is the link --> Azure functions - How to read form data
So there has to be means of doing this in Java, does anyone have or can anyone provide a working example ?
public class Function {
     @FunctionName("HttpTrigger-Java")
     public HttpResponseMessage run(@HttpTrigger(name = "req", methods =
  {HttpMethod.POST}) HttpRequestMessage<Optional<String>> request,
         final ExecutionContext context) {

        String postRequest = request.getBody();

         //HELP: I need to get the FormData object from the postRequest some how...
        FormData formDataObj = postRequest.getFormData();

        //HELP: Then I need to get my image file from the FormData Object...
        File sourceFile = formDataObj.getImageFile();

        try {
            // Parse the connection string
            storageAccount = CloudStorageAccount.parse(storageConnectionString);

            // get blob client
            blobClient = storageAccount.createCloudBlobClient();

            // get container name
            container = blobClient.getContainerReference(containerName);

            //Getting a blob reference
            blob = container.getBlockBlobReference(sourceFile.getName());

            //Creating blob and uploading file to it
            blob.uploadFromFile(sourceFile.getAbsolutePath());

        } catch (StorageException ex) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("There was an error with Storage Account.").build();
        }

        return request.createResponseBuilder(HttpStatus.OK).body("Images Uploaded Successfully!, ").build();

}

}

A: I believe you can parse the body using Apache Commons FileUpload and to do so from a string, this answer shows a way to do it.


text:
Q: How to had foreign key (lol).
For who I know I been working (for training) on a pokemon database.
I have a problem with my database creation.
I have 18 different types :

"Acier"
"Combat"
"Dragon"
"Eau"
"Electrik"
"Fee"
"Feu"
"Glace"
"Insecte"
"Normal"
"Plante"
"Poison"
"Psy"
"Roche"
"Sol"
"Spectre"
"Tenebre"
"Vol"

A pokemon can have one OR two types :
Example :

*

*Pickachu type Electrik.

*Bulbizarre type Plante and Poison.

I try to use foreign key for create my database but I don't know how to do it please help.
I have a Pokemon model class:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Pokemon.Models
{
    [Table("Pokemons")]
    public class Pokemon
    {
        [Key]
        public int PokemonId { get; set; }

        [StringLength(30)]
        public string PokemonName { get; set; }

        [StringLength(30)]
        public string PokemonUsName { get; set; }

        [StringLength(30)]
        public string PokemonDeName { get; set; }

        [StringLength(30)]
        public string PokemonJpName { get; set; }

        public string PokemonDescription { get; set; }

        public int PokemonRate { get; set; }

        public string PokemonImage { get; set; }

        public int PokemonTypeId { get; set; }

        [ForeignKey("PokemonType")]
        public virtual PokemonType PokemonType { get; set; }
    }
}

And a PokemonType model class:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Pokemon.Models
{
    [Table("PokemonTypes")]
    public class PokemonType
    {
        [Key]
        public int TypeId { get; set; }

        [StringLength(8)]
        public string Type { get; set; }

        public virtual ICollection<Pokemon> Pokemons { get; set; }
    }
}

I hope I asked my question clearly.
I want to make a pokemon "Bulbizarre" whit Type1Id = 7   //7for plante
And type2Id = 24 //24 for poison.
But some of them have only one type : type1Id 13 //13 for Electrik
and Type2Id = null. //because no second type.
Table PokemonTypes screen from databse

A: I made it !
I made databse first and scaffold it!
Database diagram
this make me 3 model class with everythings correct inside

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace DataModels.Models
{
    public partial class Pokemons
    {
        public Pokemons()
        {
            PokemonsPokemonTypes = new HashSet<PokemonsPokemonTypes>();
        }

        public int Id { get; set; }
        public int Num { get; set; }

        [Required]
        [StringLength(30)]
        public string Name { get; set; }

        [StringLength(30)]
        public string UsName { get; set; }

        [StringLength(30)]
        public string JpName { get; set; }

        public int? Rate { get; set; }
        public string Description { get; set; }
        public string Image { get; set; }

        [StringLength(50)]
        public string Kind { get; set; }

        public double? Height { get; set; }
        public double? Weight { get; set; }

        [InverseProperty("Pokemon")]
        public virtual ICollection<PokemonsPokemonTypes> PokemonsPokemonTypes { get; set; }
    }
}

using System.ComponentModel.DataAnnotations.Schema;

namespace DataModels.Models
{
    public partial class PokemonsPokemonTypes
    {
        public int PokemonId { get; set; }
        public int TypeId { get; set; }

        [ForeignKey("PokemonId")]
        [InverseProperty("PokemonsPokemonTypes")]
        public virtual Pokemons Pokemon { get; set; }

        [ForeignKey("TypeId")]
        [InverseProperty("PokemonsPokemonTypes")]
        public virtual PokemonTypes Type { get; set; }
    }
}

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace DataModels.Models
{
    public partial class PokemonTypes
    {
        public PokemonTypes()
        {
            PokemonsPokemonTypes = new HashSet<PokemonsPokemonTypes>();
        }

        public int Id { get; set; }

        [StringLength(8)]
        public string Type { get; set; }

        [InverseProperty("Type")]
        public virtual ICollection<PokemonsPokemonTypes> PokemonsPokemonTypes { get; set; }
    }
}

This works pretty well!
One Product (Pokemon) can have Multipke Categories (Type).

A: There is one bug in your code listing, The [ForeignKey] attribute can be put on the foreign key property or the navigation property, but if on the Navigation property it needs to be set to point to the FK field name. (PokemonTypeId)
Two options to support more than one pokemon type:
If a Pokemon can have 1 or 2, but at max 2 types, then you can add two PokemonType references to the Pokemon. For example:
    public int PrimaryPokemonTypeId { get; set; }
    [ForeignKey("PrimaryPokemonTypeId")]
    public virtual PokemonType PrimaryPokemonType { get; set; }
    public int? SecondaryPokemonTypeId { get; set; }
    [ForeignKey("SecondaryPokemonTypeId")]
    public virtual PokemonType SecondaryPokemonType { get; set; }

If you can possibly refer to more than 2 types then you can adopt a many-to-many relationship rather than a 1 to many relationship. You can restrict the # of related types in code to two if you wish, but the data schema will support any number of types on a Pokemon.
A Pokemon would hold a collection of types. This means introducing a linking table. I.e. A PokemonTypePokemon.
If this is EF Core then you need to define the linking table:
public class Pokemon
{
    // ... Pokemon fields...

    public virtual ICollection<PokemonTypePokemon> PokemonTypes { get; set; } = new List<PokemonTypePokemon>();
}

public class PokemonType
{
    // Classifications...

    public virtual ICollection<PokemonTypePokemon> Pokemon { get; set; } = new List<PokemonTypePokemon>();
}

public class PokemonTypePokemon
{
    public virtual Pokemon { get; set; }
    public virtual PokemonType { get; set; }
}

This will require a little wiring up in the DbContext to associate the linking table. In the DbContext's OnModelCreating handler...
// EF Core

modelBuilder.Entity<Pokemon>()
   .HasMany(x => x.PokemonTypes)
   .WithOne(x => x.Pokemon)
   .HasForeignKey("PokemonId");

modelBuilder.Entity<PokemonType>()
   .HasMany(x => x.Pokemon)
   .WithOne(x => x.PokemonType)
   .HasForeignKey("PokemonTypeId");

You will likely need to configure the PK for the PokemonTypePokemon table as well to use a composite key on PokemonId & PokemonTypeId.
With EF6 you can map a HasMany().WithMany(), without needing the map the joining table in many cases. This should give you some idea where to start with the mapping change and joining table. Do a bit of Google-fu on EF Many-to-Many to refine.


text:
Q: java.awt.HeadlessException - Applet not displayed I am using Tomcat 5.5.23, JDK 1.5 on HP Unix. We have an application which when invoked form tomcat starts an applet. It was working fine till JDK 1.4. But now we have moved to JDK 1.5 and the applet does not start. The exception thrown is -
java.awt.HeadlessException:
No X11 DISPLAY variable was set, but this program performed an operation which requires it.
I then added JAVA_OPTS="-Djava.awt.headless=true" to catalina.sh file. But still I get the same Headless exception, but this time without the X11 Display message.
Any help would be appreciated.

A: Odd.. you're trying to run an applet (I assume you are talking about a subclass of java.awt.Applet) inside tomcat? Generally this won't work because there's no display on which to display the applet.
Assuming you don't want the applet to display anywhere and you just want to execute some portion of it programmatically, you may be able to get by using a virtual X server such as Xvfb or Xvnc. Once you have Xvfb or Xvnc running on your host running tomcat, you might try to set the DISPLAY inside the tomcat startup scripts to use the display of the virtual X server.

A: -Djava.awt.headless=false

add above in your Tomcat startup script. it will work 100%

A: You are maybe using something in your Java code that can not work on a headless system, such as graphics components (Swing objects, images, etc.). Some of these components, instead of being directly handled by Java, are handled by underlying platform (Windows kernel itself or X-Window server on Unix). This way the overall performance of application is boosted.
So the question now is, ok if it was working on Java 1.4, why doesn't it work on 1.5? My bet, given the peformance boost since Java 1.2 that Swing has received over time, is that Sun has moved the management of some graphic objets to OS level to increase performance. So if you can not stick to 1.4, then you should revise your code.
This good article will help you understand how to modify your application to make it headless-friendly.

A: Applets are going to have a hard-time running server-side.  They are designed to run inside of a container, such as a web browser.  The exception is getting thrown most likely because the applet is trying to draw it's GUI -- and the server is providing no support for this.  I'm surprised that it worked in JDK 1.4 -- I don't know what changed between the two revisions which would have affected this.

A: You may also have to install the x11 libraries, or at least explicitly export the path to them.
/usr/X11R6/lib

A: *

*Open $CATALINA_HOME/bin/startup.sh file with your preferred text browser

*Paste this line export CATALINA_OPTS="$CATALINA_OPTS -Djava.awt.headless=false" at the beginning of the file

*Save and close the file

*Restart Tomcat

A: In spring boot with database access, when you specify asterisks: **** as username and password, it will try to prompt the user for a username and password (you read that right), and it will throw this HeadlessException if it's not a gui application.


text:
Q: Cannot add or update a child row: a foreign key constraint fails tables empleado and contrato I get this error when perform an insert query:
 Cannot add or update a child row: a foreign key constraint fails (`unimonito`.`empleado`, CONSTRAINT `empleado_ibfk_1` FOREIGN KEY (`cargo`) REFERENCES `cargo` (`idCargo`) ON DELETE CASCADE ON UPDATE CASCADE)

My tables are:
 CREATE TABLE `contrato` (
  `idContrato` int(3) NOT NULL,
  `tipoContrato` int(3) NOT NULL,
  `descripcion` varchar(50) NOT NULL,
  `fechaInicio` date NOT NULL,
  `fechaFin` date NOT NULL,
  `cedulaEmpleado` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `empleado` (
  `idEmpleado` int(3) NOT NULL,
  `nombreEmpleado` varchar(50) NOT NULL,
  `cedula` int(10) NOT NULL,
  `telefono` int(10) NOT NULL,
  `cargo` int(3) NOT NULL,
  `taller` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `franquicia` (
  `idFranquicia` int(3) NOT NULL,
  `nombreFranquicia` varchar(50) NOT NULL,
  `ciudad` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `taller` (
  `idTaller` int(3) NOT NULL,
  `nombreTaller` varchar(50) NOT NULL,
  `Franquicia` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `contrato`
  ADD PRIMARY KEY (`idContrato`),
  ADD KEY `contrato_ibfk_1` (`cedulaEmpleado`),
  ADD KEY `contrato_ibfk_2` (`tipoContrato`);

ALTER TABLE `empleado`
  ADD PRIMARY KEY (`cedula`),
  ADD UNIQUE KEY `idEmpleado` (`idEmpleado`),
  ADD KEY `empleado_ibfk_1` (`cargo`),
  ADD KEY `taller` (`taller`);
ALTER TABLE `franquicia`
  ADD PRIMARY KEY (`idFranquicia`),
  ADD KEY `ciudad` (`ciudad`);
ALTER TABLE `taller`
  ADD PRIMARY KEY (`idTaller`),
  ADD KEY `Franquicia` (`Franquicia`);
ALTER TABLE `contrato`
  ADD CONSTRAINT `contrato_ibfk_1` FOREIGN KEY (`cedulaEmpleado`) REFERENCES `empleado` (`cedula`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `contrato_ibfk_2` FOREIGN KEY (`tipoContrato`) REFERENCES `tipocontrato` (`idContrato`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `empleado`
  ADD CONSTRAINT `empleado_ibfk_1` FOREIGN KEY (`cargo`) REFERENCES `cargo` (`idCargo`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `empleado_ibfk_2` FOREIGN KEY (`taller`) REFERENCES `taller` (`idTaller`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `franquicia`
  ADD CONSTRAINT `franquicia_ibfk_1` FOREIGN KEY (`ciudad`) REFERENCES `ciudad` (`idCiudad`);
ALTER TABLE `taller`
  ADD CONSTRAINT `taller_ibfk_1` FOREIGN KEY (`Franquicia`) REFERENCES `franquicia` (`idFranquicia`);

When I insert a row in the phpmyadmin panel, the query executes successfully, but if I do the same on my project, the above error appears.
What is the issue?


text:
Q: Titanium, display the value in XML from javascript? I need to get the textarea value from java script file. below is my code,
On click of button in index.xml, the control should go to getPrivacy_policy() and display the privacy page.
Privacy.xml
<Alloy>
    <Window id="privacyWin" title="Plan India" platform="android,ios">
        <View id="header">
              <Label id="title">Privacy Policy</Label>
        </View>

         <TextArea id="privacyID" suppressReturn="false"></TextArea>

    </Window>
</Alloy>

index.js
   function getPrivacy_policy()
    {
        var privacy_string = "some long text...";
        return privacy_string;
        var privacyPolicy = Alloy.createController('privacy').getView();
        privacyPolicy.open();
    }

How can display the privacy_string value in textarea which is located in privacy.xml?
Note that both (XML and Js) are different files.

A: In Alloy you can access the view elements by their ID, so you can do:
$.privacyID.value

which will return the text inside the TextArea


text:
Q: Upload Images to Facebook without using the Facebook android-sdk I am developing an app in which I want to share an image on Facebook. I have searched a lot and all the results i could find were using the Facebook android-sdk. But i am not using Facebook android-sdk, so can anyone please help me with the Post request that i am to use along with the parameters to the graph api for uploading photo on my feed??
The image does not have a link, I am uploading it through my mobile.
In this documentation in the publishing section, I am not able to understand the method /ALBUM_ID/photos and its arguments. Please help.
-Thanks in advance

A: The URL which you have provided is about Graph Api.
and If you want to use Graph Api, You must have an Access Token, and to get Access Token you are going to use Facebook-Android-SDK.
Remember all the methods in Graph-api needs a valid access token agains your app.

A:                 HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(
                        "https://graph.facebook.com/me/photos?access_token="
                                + AccessTokens.fbaccesstoken);
                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                entity.addPart("source", new ByteArrayBody(data, "myImage.jpg"));
                entity.addPart("message", new StringBody(caption.getText()
                        .toString()));
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,
                        localContext);


text:
Q: How can I login to the same website, different accounts, different proxies, at the same time? Hei guys, I want to make a testing program to login to the same website, with different accounts and different proxies, so that all the accounts will be online at the same time from different proxies. No need for other stuff, just to login.
I tried to use Watin, even though, I can set IE to nomerge, I still can't use different proxies for every session.

A: It is not possible from watin, you can do it directly from the WebRequest but not by using watin.


text:
Q: When we talk about 'a closure' do we refer to a single variable, or do we refer to all 'closed' variables? Let's take the following (JavaScript) code that returns a function that closes over variables x and y to illustrate:
function test() {
  var x = Math.random();
  var y = Math.random();
  var f = function() {
    console.log(x, y);
  };

  return f;
}
test()();

The code is nonsensical, I just want to close over x and y.
Variables x and y don't exist outside of the function test but they remain available in the function f.
Barring any compiler optimizations (like inlining), do we say there is a single closure (created by f), or do we say there are two closures (for/over x and y)?

A: A closure is a first class function that captures the lexical bindings of variables defined in it's environment.  When it captures the bindings it is said to have "closed over" the variables.
Note: this means closures only exist at runtime (once it has "closed over" variables).
So in the example above a single closure is created when the code is executed.  This closure is "closed over" the variables x and y.

A: "A closure" is a function that closes over one or more variables, not the variable(s) that are closed over.  So it's a single closure.


text:
Q: Simple dot product of list and nested list conditioned on indices in separate list Here is a simple dot product (or sum product) using a nested list and normal list.
x1 = [[1, 1, 1], [9, 9, 9]]
x2 = [2, 2, 2]
M = [0]

result = []
for x in x1:
    result.append(sum(a * b for a, b in zip(x, x2)))

result
[6, 54]

However, under a condition involving the indices m specified in M, I want to potentially have some of the elements in result be None.
I want to make this comparison: for each x[m] < x2[m] then the value appended should be None instead of the sum product.
So the desired result using the example above should be:
result = [None, 54]

...because 1 < 2 is true so None
...and 9 < 2 is false so append the sum product as you otherwise would: 54
A requirement is that the length of M can vary and may be empty.

A: Just add the final conditioning at the end?
for m in M:
    if x[m] < x2[m]:
        result[m] = None

A: Using list comprehension,
Valid only for -

*

*if x2 has a single list.

*and M[0] has a single element.

Ex.
x1 = [[1, 1, 1], [9, 9, 9]]
x2 = [2, 2, 2]
M = [0]
result = []
for x in x1:
    # return true if x[m] less than x2[m]
    is_less = [(True if x[m] < x2[m] else False) for m in M][0]
    #check is_less is true then append None into result list
    if is_less:
        result.append(None)
    else:
        result.append(sum(a * b for a, b in zip(x, x2)))

print(result)

O/P:
[None, 54]


text:
Q: Keep unique values with only 1 instance I have the following dataset:
    Col_A   Amounts
0   A      100
1   B      200
2   C      500
3   D      100
4   E      500
5   F      300

The output I am trying to achieve is to basically remove all values based on the "Amounts" column which have a duplicate value and to keep only the rows where there is one unique instance of a value.
Desired Output:
    Col_A   Amounts
1   B      200
5   F      300

I have tried to use the following with no luck:
df_1.drop_duplicates(subset=['Amounts'])

This removes the duplicates, however, it still keeps the values which have occurred more than once.
Using the pandas .unique function also provides a similiar undesired output.

A: You are close, need keep=False for remove all duplicates per Amounts column:
print (df.drop_duplicates(subset=['Amounts'], keep=False))
  Col_A  Amounts
1     B      200
5     F      300

A: Less straight forward than the previous answer, but if you want to be able keep the rows that appear n times, you could use value_counts() as a mask, and keep only the rows that appear exactly / at least / less than n times:
import pandas as pd

data = { 'Col_1': ['A','B','C','D','E','F'],
        'Amounts': [100, 200, 500, 100, 500,300]
        }
df = pd.DataFrame(data)

n=1

mask = df.Amounts.value_counts()
df[df.Amounts.isin(mask.index[mask.lt(n+1)])]

outputs:
  Col_1  Amounts
1     B      200
5     F      300


text:
Q: Creating and re-using map template in ArcMap? I am using ArcMap 10.1 and working on a project which requires 5 different analyses on the same data. I created five map documents (.mxd) and completed my analyses. Now, the problem is that I want to export my results in map format but I want them to be uniform in display i.e. having a same map template. Is there a way to save one of the maps as a template and then use it for creating other 4 maps?
I tried saving one document in 'Map Templates' folder in ArcGis folder but a message box appears which says that I don't have permission to save in that location and I must contact administrator for that, even though I am the only user and administrator of the computer. I don't want to manually add all map elements for 5 different maps, thats too tedious!

A: The help page on Using Map Templates explains it quite well.
Here are three different ways you can go about rectifying this.

*

*From the help, it appears that you need to make a change in the registry to save in <install drive>:\Program Files\ArcGIS\Desktop10.1\MapTemplates. By changing it via ArcMapAdvancedSettings.exe, all users can access the templates. (Not really useful in your instance.)

*You can save the mxd to a different location and create a folder in MapTemplates. Then just copy the mxd into that new folder and it will appear as a template.

*The easiest way is to save it in %APPDATA%\ESRI\Desktop10.1\ArcMap\Templates. Only one user can access these templates, but in your case, you'll be the only person.

If you also want to apply a template you have created to an existing map, first have that map open and then click the Change Layout button on the Layout toolbar to open the Select Template dialog box.


text:
Q: Convert SQL Query to IList using of Dapper I use VS2012 and SQL Server 2012
I add Dapper to my VS2012 like this

I have one class like this :
    public class DomainClass
    {
        public SexEnum sex { get; set; }
        public int Id { get; set; }
        public string Name { get; set; }
    }

    enum SexEnum
    {
        Men = 0, Women = 1
    }

I have a table ATest and i have a query like this :
Select * From ATest

How i can execute this query and convert my result in to IList of DomainClass with Dapper ?

A: public static IList<DomainClass> GetAllDomains()
{
    using (var con = new SqlConnection(Properties.Settings.Default.YourConnection))
    {
        const String sql = "Select sex, Id, Name  From ATest ORDER BY Name ASC;";
        con.Open();
        IList<DomainClass> domains = con.Query<DomainClass>(sql).ToList();
        return domains;
    }
}

A: I write this static class and this extension method :
/// <summary>
/// Put this Class in your project
/// and use ConvertSqlQueryToIList extension method on SqlConnection object.
/// </summary>
public static class Convert
{

    public static IList<T> ConvertSqlQueryToIList<T>(
                                           this SqlConnection sqlConn,
                                           T domainClass,
                                           string sqlQueryCommand
                                                            )
    {
        ConnectionState connectionState = ConnectionState.Closed;
        try
        {

            if (sqlConn.State != ConnectionState.Open)
            {
                sqlConn.Open();
                connectionState = sqlConn.State;
            }

            IList<T> result = sqlConn.Query<T>(sqlQueryCommand).ToList();

            return result;
        }
        catch (Exception exception)
        {

            throw exception;
        }
        finally
        {
            if (connectionState == ConnectionState.Closed)
                sqlConn.Close();
        }
    }

}

And i fond that Dapper convert int field in to Enum property,
like Sex property in my quetsion.


text:
Q: How to get top search results and return a random gif using tenor api in discord.py i was trying to make a gif command using tenor api using this function,but in this it just returns one gif everytime so how can i make it like it get the top results and appends it in a list and just get a random gif using random module
def get_gif(searchTerm):
    response = requests.get("https://g.tenor.com/v1/search?q={}&key={}&limit=1".format(searchTerm, TenorToken))
    data = response.json()

    # see urls for all GIFs
    for result in data['results']:
        for media in result['media']:
            return data['results'][0]['media'][0]['gif']['url']

A: Change limit=1in your api call to a number up to 50 as per: https://tenor.com/gifapi/documentation#endpoints-search
data["results"]will then be a list of GIF_OBJECT, and you can select a random one of those using random.choice:
import random
...

...
gif = random.choice(data["results"])

You could then return the gif using something like
return gif['media'][0]['gif']['url']


text:
Q: When is it necessary or convenient to use Spring or EJB3 or all of them together? I'm a little confused by the mixed use of JSF2+Spring+EJB3 or any combination of those. I know one of the Spring principal characteristics is dependency injection, but with JSF managed beans I can use @ManagedBean and @ManagedProperty anotations and I get dependency injection functionality. With EJB3 I'm even more confused about when to use it along with JSF or if there is even a reason to use it.
So, in what kind of situation would it be a good idea to use Spring+JSF2 or EJB3+JSF2?
Until now I have created just some small web applications using only JSF2 and never needed to use Spring or EJB3. However, I'm seeing in a lot of places that people are working with all this stuff together.

A: First of all, Spring and EJB(+JTA) are competing technologies and usually not to be used together in the same application. Choose the one or the other. Spring or EJB(+JTA). I won't tell you which to choose, I will only tell you a bit of history and the facts so that you can easier make the decision.

Main problem they're trying to solve is providing a business service layer API with automatic transaction management. Imagine that you need to fire multiple SQL queries to perform a single business task (e.g. placing an order), and one of them failed, then you would of course like that everything is rolled back, so that the DB is kept in the same state as it was before, as if completely nothing happened. If you didn't make use of transactions, then the DB would be left in an invalid state because the first bunch of the queries actually succeeded.
If you're familiar with basic JDBC, then you should know that this can be achieved by turning off autocommit on the connection, then firing those queries in sequence, then performing commit() in the very same try in whose catch (SQLException) a rollback() is performed. This is however quite tedious to implement everytime.
With Spring and EJB(+JTA), a single (stateless) business service method call counts by default transparently as a single full transaction. This way you don't need to worry about transaction management at all. You do not need to manually create EntityManagerFactory, nor explicitly call em.getTransaction().begin() and such as you would do when you're tight-coupling business service logic into a JSF backing bean class and/or are using RESOURCE_LOCAL instead of JTA in JPA. You could for example have just the following EJB class utilizing JPA:
@Stateless
public class OrderService {

    @PersistenceContext
    private EntityManager em;

    @EJB
    private ProductService productService;

    public void placeOrder(Order newOrder) {
        for (Product orderedproduct : newOrder.getProducts()) {
            productService.updateQuantity(orderedproduct);
        }

        em.persist(newOrder);
    }

}

If you have a @EJB private OrderService orderService; in your JSF backing bean and invoke the orderService.placeOrder(newOrder); in the action method, then a single full transaction will be performed. If for example one of the updateQuantity() calls or the persist() call failed with an exception, then it will rollback any so far executed updateQuantity() calls, and leave the DB in a clean and crisp state. Of course, you could catch that exception in your JSF backing bean and display a faces message or so.
Noted should be that "Spring" is a quite large framework which not only competes EJB, but also CDI and JPA. Previously, during the dark J2EE ages, when EJB 2.x was extremely terrible to implement (the above EJB 3.x OrderService example would in EJB 2.x require at least 5 times more code and some XML code). Spring offered a much better alternative which required less Java code (but still many XML code). J2EE/EJB2 learned the lessons from Spring and came with Java EE 5 which offers new EJB3 API which is even more slick than Spring and required no XML at all.
Spring also offers IoC/DI (inversion of control; dependency injection) out the box. This was during the J2EE era configured by XML which can go quite overboard. Nowadays Spring also uses annotations, but still some XML is required. Since Java EE 6, after having learned the lessons from Spring, CDI is offered out the box to provide the same DI functionality, but then without any need for XML. With Spring DI @Component/@Autowired and CDI @Named/@Inject you can achieve the same as JSF does with @ManagedBean/@ManagedProperty, but Spring DI and CDI offers many more advantages around it: you can for example write interceptors to pre-process or post-process managed bean creation/destroy or a managed bean method call, you can create custom scopes, producers and consumers, you can inject an instance of narrower scope in an instance of broader scope, etc.
Spring also offers MVC which essentially competes JSF. It makes no sense to mix JSF with Spring MVC. Further Spring also offers Data which is essentially an extra abstraction layer over JPA, further minimizing DAO boilerplate (but which essentially doesn't represent the business service layer as whole).
See also:

*

*What exactly is Java EE?

*JSF Controller, Service and DAO

*@Stateless beans versus @Stateful beans

A: There's no real easy answer here as Spring is many things.
On a really high level, Spring competes with Java EE, meaning you would use either one of them as a full stack framework.
On a finer grained level, the Spring IoC container and Spring Beans compete with the combination of CDI & EJB in Java EE.
As for the web layer, Spring MVC competes with JSF. Some Spring xyzTemplate competes with the JPA interfaces (both can use eg Hibernate as the implementation of those).
It's possible to mix and match; eg use CDI & EJB beans with Spring MVC, OR use Spring Beans with JSF.
You will normally not use 2 directly competing techs together. Spring beans + CDI + EJB in the same app, or Spring MVC + JSF is silly.


text:
Q: Listing more than 100 records in Route 53 using Ansible I'm currently using the route53_facts module on a project. I have 250 record sets in one hosted zone. I'm having difficulty with listing all record sets in that zone. The Route 53 API works by returning pages of maximum 100 records at a time. In order to retrieve the next page, you must pass the NextRecordName response value to the route53_facts module's start_record_name: field (pretty straightforward).
The issue I'm having specifically is getting Ansible to do this. Presumably one would do this using a loop, e.g. in pseudocode:
start
get 100 records
do until response does not contain NextRecordName:
    get 100 records (start_record_name=NextRecordName)
end

In Ansible, I have written the below task to do this:
- block:
  - name: List record sets in a given hosted zone
    route53_facts:
      query: record_sets
      hosted_zone_id: "/hostedzone/ZZZ1111112222"
      max_items: 100
      start_record_name: "{{ record_sets.NextRecordName | default(omit) }}"
    register: record_sets
    until: record_sets.NextRecordName is not defined
  when: "'{{ hosted_zone['Name'] }}' == 'test.example.com.'"

...however, this does not work as expected. Instead of continuously paging through responses until no more records are left, it repeatedly returns the first 100 records ("the first page").
As I can see from the Ansible debug output, start_record_name: is repeatedly null:
"attempts": 2,
"changed": false,
"invocation": {
    "module_args": {
        "aws_access_key": null,
        "aws_secret_key": null,
        "change_id": null,
        "delegation_set_id": null,
        "dns_name": null,
        "ec2_url": null,
        "health_check_id": null,
        "health_check_method": "list",
        "hosted_zone_id": "/hostedzone/ZZZ1111112222",
        "hosted_zone_method": "list",
        "max_items": "100",
        "next_marker": null,
        "profile": null,
        "query": "record_sets",
        "region": null,
        "resource_id": null,
        "security_token": null,
        "start_record_name": null,
        "type": null,
        "validate_certs": true
    }
},

...my guess is that the | default(omit) filter is always being executed. In other words, record_sets.NextRecordName is never initialized at this point in the task.
I'm hoping somebody can assist me in getting Ansible to return all records from a zone in Route 53. I think I've gotten tangled up in Ansible's looping behavior. Thanks!

A: Caveat this with "as best I can tell:"
To answer your question, it actually seems that until: and register: do not interact in the same way that when: and register: do. The best explanation I have is that until: behaves like a database transaction: it rolls back the register: assignment if the conditional is false, meaning that when the body of the until: task is tried again, it uses the same parameters as the first time. The only thing which keeps an until: block from being an infinite loop is the retries: value.
So, in your specific case, I think this will do the job:
- name: initial record_set
  route53_facts:
  # bootstrap so the upcoming "when:" will evaluate correctly
  register: record_facts
- set_fact:
    # capture the initial answer
    records0: '{{ record_facts.ResourceRecordSets }}'
- name: rest of them
  route53_facts:
    start_record_name: '{{ record_facts.NextRecordName }}'
  register: record_facts
  when: record_facts.NextRecordName | default("")
  with_sequence: count=10
- set_fact:
    all_records: >-
      {{ record0 + (record_facts.results |
           selectattr("ResourceRecordSets", "defined") |
           map(attribute="ResourceRecordSets") | list) }}

The with_sequence: is a hack because loop: (for which with_* is syntatic sugar) needs a list of items over which to iterate, but given that the responses that come back without NextRecordName will cause the when: to fail, skipping them, makes the (in your case) 3 through 10 items resolve almost immediately.
Then you just need to pull out the actual response data from the now list of route53_facts: replies, and glue them to the initial one to get the complete list.

Having said all of that, I am now convinced that route53_facts: (and any other AWS module that pushes the burden of that iteration into the playbook) behavior is a bug. The module caller already has a max_items: available to them, but it's an implementation detail that that any value can't be larger than some random pagination cut-off.


text:
Q: Can I output datetime string to Redshift and make the column as timestamp? I need to create a table in Redshift using the data source in S3. There are a couple of columns have datetime like string value. I want the Redshift treats it like timestamp. If I just assign timestamp to those columns during the table creation, would it work or does it need additional steps?
The reason I have those columns as string is those columns were created by Python code and run into json serialization problem at first :How to overcome "datetime.datetime not JSON serializable"?
My input data is:
{
"created_date": "2019-06-21 23:32:28",
"resolved_date": ""
"last_updated_date": "2019-06-23 04:08:35"
}

In Redshift, I want to make the columns in timestamp fomat
"created_date": timestamp,
"resolved_date": timestamp,
"last_updated_date": timestamp

Will Redshift recognize my data and parse it as timestamp?
Any pointers are appreciated.

A: When using Redshift spectrum you can map string json fields to TIMESTAMP columns directly, but your example would not work, because of the empty string for a timestamp - that's not parsable - you'd have to make sure that your python code generates proper JSON nulls.
That would be your external table:
CREATE EXTERNAL TABLE my_external_schema.my_external_table(
    "created_date": timestamp,
    "resolved_date": timestamp,
    "last_updated_date": timestamp
  )
  ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
  STORED AS TEXTFILE
  LOCATION 's3://my_external_location/'

if you really need that data loaded in redshift, you could then do:
CREATE TABLE my_schema.my_table AS SELECT * FROM my_external_schema.my_external_table;

Another option is to use Redshift COPY command to load the data. It should also be able to treat json string as TIMESTAMP, and there I believe you may be able to specify to treat "" as NULLs.


text:
Q: Matching part of regex I must to match the stars(*), that satisfied such conditions:
\*\S.*\S\* -> (for example *y text1 text2 u*)

The problem is, that i want to match only this stars, if the condition is true, how can it be done(desirable in java:))(i have write so:
Pattern params = Pattern.compile("\\*\\S.*\\S\\*");

but this matches stars and text between stars...)

A: You can use non-capturing groups, like this:
`Pattern pattern = Pattern.compile("(\\*)(?:\\S.*\\S)(\\*)");`

Basically, the match pattern contains 3 groups: (\\*), (?:\\S.*\\S), (\\*).
The second group is like (?:re), it is non-capturing group, means let regex don't count this group in the result.
Here is the sample code:
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTest {

/**
 * @param args
 */
public static void main(String[] args) {

        Pattern pattern = Pattern.compile("(\\*)(?:\\S.*\\S)(\\*)");

        String string ="for example *y text1 text2 u*";
        Matcher matcher = pattern.matcher(string);

        boolean found = false;
        if (matcher.find()) {
            System.out.println("group count:"+matcher.groupCount());
            System.out.println("---------------");
            for(int i=1; i<=matcher.groupCount(); i++)
            {
                System.out.println("group "+i);
                System.out.println("start index:"+matcher.start(i));
                System.out.println("end index:"+matcher.end(i));
                System.out.println("text:"+string.substring(matcher.start(i), matcher.end(i)));
                System.out.println("---------------");
            }

            found = true;
        }
        if(!found){
            System.out.println("not found.");
        }

}

}

Please note in java the group count in Matcher class is 1 based. The group count in the above code is 2.
If you don't use non-capturing group like this:
Pattern pattern = Pattern.compile("(\\*)(\\S.*\\S)(\\*)");

The result will return 3 groups.
For details, please refer this link:
    http://java.sun.com/docs/books/tutorial/essential/regex/groups.html

A: You must use a non-greedy pattern, like:
Pattern.compile("\\*\\S.*?\\S\\*");

Note that additional ? character

A: It's not clear why you'd want to do such a thing. If you want to "only match"--do you mean "capture"--the stars, then simply test the given pattern against your target string, and, if it matches, then you know there are two stars around some text, and it doesn't matter whether the regex captured them. It's two stars!
What are you actually trying to do?

A: I agree with other responders: it is unclear exactly what you are trying to do but if you want anything between two *'s in the text, then:
Pattern params = Patterns.compile ( "\\*[^\\*]+\\*" );

That will find every non-zero length string between two *'s.
With more information we can provide better answers.


text:
Q: Creating a android unity3d plugin Marshmallow 6.0 dangerous permissions Hi I am currently trying to build the so called android plugin:NoodlePermissionGranter inside Unity3D so I can request dangerous permissions on runtime.
I've found the plugin on another question on stackoverflow.
Answer used from topic: [
Implementing Android 6.0 permissions in unity3d ]
I made some changes to make it easier to build but it is not working as expected.
The Plugin should request a dangerous permission if it is not yet granted.
When trying to request the permission it instantly callsback to PERMISSION_DENIED.
In advance sorry for my bad english.
EDIT:No error.

NoodlePermissionGranter.Java

package com.noodlecake.unityplugins;

      ///////////////////////////////////////////////////////////
     ///////////////// NoodlePermissionGranter /////////////////
    /// Implements runtime granting of Android permissions. ///
   /// This is necessary for Android M (6.0) and above. //////
  ///////////////////////////////////////////////////////////
 //////////////////// Noodlecake Studios ///////////////////
///////////////////////////////////////////////////////////

import android.Manifest;
import android.os.Build;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.util.Log;
import android.content.pm.PackageManager;
import com.unity3d.player.UnityPlayer;

public class NoodlePermissionGranter
{
    // Only implements WRITE_EXTERNAL_STORAGE so far.
    // Implement the rest by matching the enum in NoodlePermissionGranter.cs
    // to the getPermissionStringFromEnumInt below.

    private final static String UNITY_CALLBACK_GAMEOBJECT_NAME = "NoodlePermissionGranter";
    private final static String UNITY_CALLBACK_METHOD_NAME = "permissionRequestCallbackInternal";
    private final static String PERMISSION_GRANTED = "PERMISSION_GRANTED"; // this will be an arg to the above method
    private final static String PERMISSION_DENIED = "PERMISSION_DENIED";

    public static String getPermissionStringFromEnumInt(int permissionEnum) throws Exception
    {
        switch (permissionEnum)
        {
            case 0:
                return Manifest.permission.WRITE_EXTERNAL_STORAGE;
            case 1:
                return Manifest.permission.READ_PHONE_STATE;
            case 2:
                return Manifest.permission.READ_EXTERNAL_STORAGE;
            // "and the rest is still unwritten" - Natasha Bedingfield
        }
        Log.e("NoodlePermissionGranter", "Error. Unknown permissionEnum " + permissionEnum);
        throw new Exception(String.format("Error. Unknown permissionEnum %d",permissionEnum));
    }

    public static void grantPermission(Activity currentActivity, int permissionEnum)
    {
        // permission enum must match ordering in NoodlePermissionGranter.cs
        final Activity act = currentActivity;
        Log.i("NoodlePermissionGranter","grantPermission " + permissionEnum) ;
        if (Build.VERSION.SDK_INT < 23) {
            Log.i("NoodlePermissionGranter","Build.VERSION.SDK_INT < 23 (" + Build.VERSION.SDK_INT+")");
            return;
        }

        try
        {
            final int PERMISSIONS_REQUEST_CODE = permissionEnum;
            final String permissionFromEnumInt = getPermissionStringFromEnumInt(permissionEnum);
            if (currentActivity.checkCallingOrSelfPermission(permissionFromEnumInt) == PackageManager.PERMISSION_GRANTED) {
                Log.i("NoodlePermissionGranter", "already granted");
                UnityPlayer.UnitySendMessage(UNITY_CALLBACK_GAMEOBJECT_NAME, UNITY_CALLBACK_METHOD_NAME, PERMISSION_GRANTED);
                return;
            }

            final FragmentManager fragmentManager = currentActivity.getFragmentManager();
            final Fragment request = new Fragment() {

                @Override public void onStart()
                {
                    super.onStart();
                    Log.i("NoodlePermissionGranter","fragment start");
                    String[] permissionsToRequest = new String [] {permissionFromEnumInt};
                    Log.i("NoodlePermissionGranter","fragment start " + permissionsToRequest[0]);
                    requestPermissions(permissionsToRequest, PERMISSIONS_REQUEST_CODE);
                }

                @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
                {
                    Log.i("NoodlePermissionGranter", "onRequestPermissionsResult");
                    if (requestCode != PERMISSIONS_REQUEST_CODE)
                        return;

                    if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // permission was granted, yay! Do the
                        // contacts-related task you need to do.
                        Log.i("NoodlePermissionGranter", PERMISSION_GRANTED);
                        UnityPlayer.UnitySendMessage(UNITY_CALLBACK_GAMEOBJECT_NAME, UNITY_CALLBACK_METHOD_NAME, PERMISSION_GRANTED);
                    } else {

                        // permission denied, boo! Disable the
                        // functionality that depends on this permission.
                        Log.i("NoodlePermissionGranter",PERMISSION_DENIED);
                        UnityPlayer.UnitySendMessage(UNITY_CALLBACK_GAMEOBJECT_NAME, UNITY_CALLBACK_METHOD_NAME, PERMISSION_DENIED);
                    }

                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.remove(this);
                    fragmentTransaction.commit();

                    // shouldBeOkayToStartTheApplicationNow();
                }
            };

            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(0, request);
            fragmentTransaction.commit();
        }
        catch(Exception error)
        {
            Log.w("[NoodlePermissionGranter]", String.format("Unable to request permission: %s", error.getMessage()));
            UnityPlayer.UnitySendMessage(UNITY_CALLBACK_GAMEOBJECT_NAME, UNITY_CALLBACK_METHOD_NAME, PERMISSION_DENIED);
        }
    }

}

NoodlePermissionGranter.sh

export JAVA_HOME=/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
ClASSPATH="classes.jar"

javac NoodlePermissionGranter.java -bootclasspath android.jar -classpath $ClASSPATH -d .
javap -s com.noodlecake.unityplugins.NoodlePermissionGranter
jar cvfM NoodlePermissionGranter.jar com/
rm -rf com
read -p "Press any key to continue... " -n1 -s

EDIT

Logcat

04-01 16:13:44.656  5504  5518 I NoodlePermissionGranter: grantPermission 1
04-01 16:13:44.657  5504  5504 I NoodlePermissionGranter: fragment start
04-01 16:13:44.657  5504  5504 I NoodlePermissionGranter: fragment start android.permission.READ_PHONE_STATE
04-01 16:13:44.658  5504  5518 I NoodlePermissionGranter: grantPermission 0
04-01 16:13:44.659  5504  5518 I NoodlePermissionGranter: grantPermission 2
04-01 16:13:44.667  5504  5504 I NoodlePermissionGranter: fragment start
04-01 16:13:44.667  5504  5504 I NoodlePermissionGranter: fragment start android.permission.WRITE_EXTERNAL_STORAGE
04-01 16:13:44.675  5504  5504 I NoodlePermissionGranter: fragment start
04-01 16:13:44.675  5504  5504 I NoodlePermissionGranter: fragment start android.permission.READ_EXTERNAL_STORAGE
04-01 16:13:44.906  5504  5504 I NoodlePermissionGranter: onRequestPermissionsResult
04-01 16:13:44.907  5504  5504 I NoodlePermissionGranter: PERMISSION_DENIED
04-01 16:13:44.907  5504  5504 I NoodlePermissionGranter: onRequestPermissionsResult
04-01 16:13:44.907  5504  5504 I NoodlePermissionGranter: PERMISSION_DENIED
04-01 16:13:44.907  5504  5504 I NoodlePermissionGranter: onRequestPermissionsResult
04-01 16:13:44.907  5504  5504 I NoodlePermissionGranter: PERMISSION_DENIED

A: Be sure to check if your android manifest has the dangerous permissions!
That was my problem.


text:
Q: if statement occuring while condition is false (System.Net) I'm new here so if this post is formatted terribly, I apologise.
So the issue I'm having...
I am making a Tcp Based messaging app similar to Discord, Teamspeak etc. As you can see below, I have a function that returns a byte[] which is pulled from the network stream. I also have an if/else statement to ensure that the function does not try to pull data from a stream that is not connected so I have a bool (connected) that determines the state of the connection. This bool is properly updated to match the connection status. I thought this may have been the problem at first but I have discovered through debugging that it is not.

private byte[] RecieveData(TcpClient server)
        {
            byte[] data = new byte[1024];
            if (connected)
            {
6th line ->     server.GetStream().Read(data, 0, data.Length);
                return data;
            }
            else
            {
                return null;
            }
        }

Picture of debugging (cant add images for some reason)

My question is, why does 6th line of code (server.GetStream().Read(data, 0, data.Length);) run when the if-condition is false.
If you need anything from me (pics, code etc.) just ask!
Any help will be greatly appreciated. Thanks!
Minimal Reproducible Example
Client:
In order of execution
private void ServerDisconnect(TcpClient server, byte[] data) //Called from a button
    {
        connected = false;
        Server = null;
        Disconnect(server);
    }

public void Disconnect(TcpClient server)// Checks for a connection, if there is, send DISCON request to server, if not dont
    {
        if (server.Connected) SendMessage(server, DISCON, currentUser);
        connected = false;
        server.Close();
    }

private void SendMessage(TcpClient server, byte code, User user)// Uses AddMessageCode method to specify what type of request the message is.
    {
        NetworkStream stream = server.GetStream();
        byte[] data = AddMessageCode(code, ObjectToByteArray(user));//Uses a simple Binary converter to serialize a class.
        stream.Write(data, 0, data.Length);//Sends request to server
    }

private byte[] AddMessageCode(byte code, byte[] data)// Adds the byte code to the start of the data array.
    {
        byte[] newData = new byte[data.Length + 1];
        newData[0] = code;
        Array.Copy(data, 0, newData, 1, data.Length);
        return newData;
    }

In theory, the below method should not cause an error. But it does.
private byte[] RecieveData(TcpClient server)
    {
        byte[] data = new byte[1024];
        if (server.Connected)
        {
            server.GetStream().Read(data, 0, data.Length);
            return data;
        }
        else
        {
            return null;
        }
    }

If this still wasnt clear enough. I apologise.
Link to source code

A: In this particular instance, the if statement had already executed with the condition being true. The part I did not understand was that the stream.Read() method waits until data has been received to continue.
If that didnt make sense, here is an analogy by @mjwills,
The if statement is a house and the door is the condition. If you came into the house while the door was open (condition was true) no matter if the door is open or not (condition is true or false) you are in the house (the code inside the if statement is executing). And in this instance, the code inside does not complete quickly, it waits for data from the stream.
Thanks stackoverflow community for helping me understand this in within 10 mins of the question posting!


text:
Q: Unable to Add component through innerHtml I'm unable to add my already created components through innerHtml having id="myId".
Components are c:Contact360_Contact_Info_L1 and c:Contact360_Contact_Info_L2.
Are we not allowed this lightning or is there any other way to display it?
Component:
<aura:component >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

</aura:component>

Controller:
({
    doInit: function(component, event, helper) {
        var temp = ''+
            '
'+
                '
'+
                    '<c:Contact360_Contact_Info_L1 aura:id="Comp1" otherCompId="Comp2" thisCompId="Comp1"/>' +
                    '<c:Contact360_Contact_Info_L2 aura:id="Comp2" otherCompId="Comp1" thisCompId="Comp2"/>'+
                    '

';
        var element = document.getElementById("myId");
        element.innerHTML = temp;
    }
})

This innerHtml is working when I'm simply writing something instead of calling the components there.

A: In general Lightning Component markup is not parsed by the browser as HTML. It's parsed by the Lightning Framework, and then delivered to the browser in a JavaScript object-shaped format. But innerHTML is a property meant to be processed by the browser (actually Lightning Locker Service intercepts it, but still only raw HTML is handled). So what you have typed just literally injects the markup for the browser to see and it has no idea what to do with it.
In general you should not be constructing anything in Lightning via raw innerHTML. Any problem you are trying to solve that way can probably be solved in a more component-friendly manner.


text:
Q: Autohotkey to cycle through active program windows I have this autohotkey file. When I press F2, it toggles through any windows explorer tabs I have open and keeps it in focus / sends it to the top. If no file explorer windows are open, it opens one up

Code
F2::
IfWinNotExist, ahk_class CabinetWClass
    Run, explorer.exe
GroupAdd, kjexplorers, ahk_class CabinetWClass ;You have to make a new group for each application, don't use the same one for all of them!
if WinActive("ahk_exe explorer.exe")
    GroupActivate, kjexplorers, r
else
    WinActivate ahk_class CabinetWClass ;you have to use WinActivatebottom if you didn't create a window group.
Return

The problem I have is I can't make it work for other applications. Many times I have multiple chrome windows open, or multiple excel files open, and I can't cycle through them like I can here with a different hotkey. I tried replacing the .exe file names, groupnames, doesn't work with anything but windows explorer here

A: F5::
IfWinNotExist, ahk_class Chrome_WidgetWin_1
    Run, chrome.exe
GroupAdd, kjexplorers5, ahk_class Chrome_WidgetWin_1 ;You have to make a new group for each application, don't use the same one for all of them!
if WinActive("ahk_exe chrome.exe")
    GroupActivate, kjexplorers5, r
else
    WinActivate ahk_class Chrome_WidgetWin_1 ;you have to use WinActivatebottom if you didn't create a window group.
Return

This is the basic variant autohotkey I'm using to cycle through chrome windows and put them up top.
full answer here: Windows shortcut key to maximize all chrome windows or any specific application


text:
Q: Share item in actionbar using contextual actionbar For the first time i use the contextual actionbar. When i click in the item of my ListView i want have the possibility to share that item in some way (whatsapp/mail/gmail/drive etc etc..). I'm trying in with this method but no works:
the menu layout:
<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">

        <item
            android:id="@+id/shareButton"
            android:actionProviderClass="android.widget.ShareActionProvider"
            android:title="@string/share"
            android:showAsAction="always"/>
</menu>

The contextual actionbar class:
public class CABMode implements ActionMode.Callback {
private ShareActionProvider mshare;
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        mode.getMenuInflater().inflate(R.menu.cab, menu);
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        // don't need to do anything
        return false;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        mshare = (ShareActionProvider) item.getActionProvider();
        mshare.setShareIntent(Share());
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        Mode = null;
    }

 public Intent Share() {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, "Share");
    return intent;
 }

}

Well, the contextual actionbar it opens well when i do an long click, but the share button in the actionbar doesn't work. When i say "not works" i mean that seems not clickable. Nothing works when i click over the item. Nothing appears. What i want it's open the multiple share ways. Thanks

A:
When i say "not works" i mean that seems not clickable

ActivityChooserView, the action view ShareActionProvider returns, disables the "share" button when there are no items to display, which in your case if because you're setting up ShareActionProvider incorrectly. All of the "on click" events are handled internally, you won't receive any callbacks to ActionMode.Callback.onActionItemClicked.
Rather than settings it up in ActionMode.Callback.onActionItemClicked, move that code into ActionMode.Callback.onCreateActionMode and call Menu.findItem to initialize it.
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        mode.getMenuInflater().inflate(R.menu.cab, menu);

        final MenuItem item = menu.findItem(R.id.your_share_action_provider_id);
        mshare = (ShareActionProvider) item.getActionProvider();
        mshare.setShareIntent(Share());
        return true;
    }