text:
Q: Date formatting on x-axis in matplotlib I have following data:
    ID      Date  Chemical  Group
0    6  06-12-21        21      1
1   12  07-03-22        26      2
2   11  08-03-22        28      1
3   13  08-03-22        29      2
4   15  08-03-22        28      1
5   14  09-03-22        26      2
6    7  16-12-21        23      2
7    8  16-12-21        24      2
8    9  16-12-21        23      2
9   10  16-12-21        25      1
10   1  20-11-21        21      1
11   2  26-11-21        19      2
12   3  26-11-21        31      2
13   5  26-11-21        32      1
14   4  27-11-21        31      2

I set the format for date column, sort on it and print it:
maindf['Date'] =  pd.to_datetime(maindf['Date'], format='%d-%m-%y')
maindf.sort_values('Date', inplace=True)
print(maindf)

Dates are properly recognised:
    ID       Date  Chemical  Group
10   1 2021-11-20        21      1
11   2 2021-11-26        19      2
12   3 2021-11-26        31      2
13   5 2021-11-26        32      1
14   4 2021-11-27        31      2
0    6 2021-12-06        21      1
6    7 2021-12-16        23      2
7    8 2021-12-16        24      2
8    9 2021-12-16        23      2
9   10 2021-12-16        25      1
1   12 2022-03-07        26      2
2   11 2022-03-08        28      1
3   13 2022-03-08        29      2
4   15 2022-03-08        28      1
5   14 2022-03-09        26      2

I draw boxplots:
import seaborn as sns
sns.boxplot(data=maindf, x='Date', y='Chemical', hue='Group')
plt.xticks(rotation=20)
plt.show()

I get following graph:

I see that although the dates are correct here, the times (hours, minutes, seconds) are also shown on x-axis with all these set as 0. I want to remove these so I set format for date on x-axis and then again display the graph:
sns.boxplot(data=maindf, x='Date', y='Chemical', hue='Group')
from matplotlib.dates import DateFormatter
dtFmt = DateFormatter('%d-%m-%y') # define the formatting
plt.gca().xaxis.set_major_formatter(dtFmt)
plt.xticks(rotation=20)
plt.show()

Now I get following graph:

I find that the dates on x-axis are all wrong. They start from 1-1-1970! Where is the problem and how can it be corrected. Thanks for your help.

A: Due to the way seaborn handles the trailing zeros, think this is not getting set properly.
One way to fix it is to use strftime() AFTER you have sorted the data to change the datetime back to string like this...
maindf['Date'] =  pd.to_datetime(maindf['Date'])
maindf.sort_values('Date', inplace=True)
maindf['Date'] = maindf['Date'].dt.strftime('%d-%m-%Y') ## Change to format you need
sns.boxplot(data=maindf, x='Date', y='Chemical', hue='Group')
plt.xticks(rotation=40)
plt.show()

The other option is to use get & set xticklabels() by removing the everything from T onwards, so that you see the right format.
maindf['Date'] =  pd.to_datetime(maindf['Date'])
maindf.sort_values('Date', inplace=True)
sns.boxplot(data=maindf, x='Date', y='Chemical', hue='Group')
plt.gca().set_xticklabels([date_text.get_text().split("T")[0] for date_text in plt.gca().get_xticklabels()])
plt.xticks(rotation=40)
plt.show()

Both would give you the below date format...


text:
Q: Self-intersecting path of stacked regular tetrahedra (This question occurred to me after reading
@IanAgol's reminisces
of Conway's spiral tetrahedron billiard path.)
Let $T_i$ be a regular tetrahedron,
and $P$ a collection of regular tetrahedra
glued together face-to-face.
Say that $P$ constitutes a
"path of stacked regular tetrahedra"
iff two conditions hold:

*

*The dual graph (node for each $T_i$, arc if $T_i$ shares
a face with $T_j$) is a path.

*No edge of the construction is incident to more than three tetrahedra.

The first condition intuitively insists on a snake-like object.
The second condition excludes too many tetrahedra circling about
one edge. (Without this, $5$ dihedral angles of $70.5^\circ$
fit into $360^\circ$, but $6$ do not.)
My question is:

Q.
  What is the fewest number of tetrahedra in a path $P$ of stacked regular tetrahedra that self-intersects?

$P = \cup_i T_i$ self intersects if a pair of
distinct tetrahedra share a point strictly interior to both.
So such a self-intersecting snake might be called
a tetrahedral ouroboros.
This example1
establishes an upperbound of $31$ tetrahedra
(adding one more would self-intersect),
but clearly this is not the minimum number of tetrahedra.
(This example was aiming toward closure, not self-intersection.)

Fig.6(detail): $QH_7$: $4L+2=30$.

1
Elgersma, Michael, and Stan Wagon. "The quadrahelix: A nearly perfect loop of tetrahedra."
arXiv:1610.00280
(2016).

A: Michael Elgersma, a coauthor on the paper I cited, provided an answer to my question:
an $11$-tetrahedra snake suffices to self-intersect. Here is his illustration of
the first $10$ tetrahedra:

He also sent me a convincing proof of optimality:

Theorem: The shortest tetrahedal snake that has self intersections, has length $11$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: toggle value of disabled attribute when JavaScript enabled I have an input tag on my website that uses javascript for autocomplete ...I want  <input> tags' disabled attribute as true when my users don't have javascript enabled on their systems.
but when Javascript is enabled I want the value of disabled=false.
how do I go about doing that?
what I've done so far:
<input name="xyz" class="xyzautocomplete" type="text" id="name" value="enter name" disabled="true">

will using
document.getElementById("name").disabled = false;

inside same <input> tag as script="" work for both cases??
IE,
 <input name="xyz" script="document.getElementById("name").disabled = false;" class="xyzautocomplete" type="text" id="0" value="enter name" disabled="True">

IF NOT, how would I do it??

A: If the javascript is disabled then none of the javascript syntaxes will work.
You have to do it with Tag
Please try with below solution -
<script>
     <!--
        document.write('<input name="xyz" class="xyzautocomplete" type="text" id="0" value="enter name" >')
     -->
  </script>

  <noscript>
    <input name="xyz" class="xyzautocomplete" type="text" id="0" value="enter name" disabled >
  </noscript>

A: The other answers are correct with regards to the inline JavaScript. There is no script attribute, and onload isn't defined for inputs, so your script will need to be in a <script> element following the input.
However, what none of the existing answers mention is that disabled is a boolean attribute, that is, its presence or absence determines whether the input is disabled or not. Its value does not matter.
So setting the attribute to a value in JavaScript does not work. The attribute would still be there, just with a different value!
What you need to do is remove the attribute altogether.

document.getElementById("name").removeAttribute('disabled');
<input name="xyz" class="xyzautocomplete" type="text" id="name" value="enter name" disabled="true">

A: It is never good way to put JS inline. Put it after the html element. Also you are targeting id of xyz with does not exists. Your id is 0.

document.getElementById("0").disabled = false;
<input name="xyz"  class="xyzautocomplete"  disabled  type="text" id="0" value="enter name">

As you can see input is disabled, but JS makes it enabled. People who don't have JS wont be able to use input.


text:
Q: iOS: can I use one timer to trigger multiple things at certain times? I need a button to do different things depending on how far along the person is in watching a video.
So for instance at 0-20 seconds it does thing A
then at 20-25 it does thing B
and 25-32 thing C
Can I make a timer that counts up and fires different messages off at specific intervals to enable/disable my buttons or change what they do?
Or should I have it fire and simultaneously start another timer and change what my button does and form a chain of events?
Thanks!

A: do an if statement so if timer >0 and <20 seconds make button event a, if timer is >20 and <25 make button event b and so on.
This way when a user clicks on the button depending on what time the timer is on then it would have changed appropriately anyway.
What you can do however which i think would be even convenient is to allow the user to press the button at anytime anyway but before any code is executed check the current position of the timer, and if the timer is > 0 but < 20 then execute EVENT a, and if timer > 20 but < 25 then execture event B this way you dont have to change the buttons but simply redirect the code that gets executed just by checking the current position of the timer. And this way there is only one timer involved.
Hope that made sense.
Its much more simpler like this rather than having the timer simultaneously fire another time, creating more timers means more objects needed to be created meaning more things to manage.
However if you want to fire multiple events and you prefer to do it that way then you do this:
http://howtomakeiphoneapps.com/2010/03/how-to-make-an-egg-timer-for-your-iphone/
Sorry i wrote this in psuedo style but im sure you have enough to understand what i am saying.
PK

A: NSTimer has a method setFireDate:(NSDate *)date, so instead of creating a chain of timers, you can have one timer and reschedule the next fire time as needed. Just make sure that your timer interval is large enough so that the timer won't fire before you get a chance to reschedule it.

A: Default action is A
Set up a timer for B and one for C. When B-timer fired set current action to B. When C-Timer fires set current action to C.

A: For Stage Time I set up one repeating timer as the countdown timer.  On each fire, I would check the time remaining and update various UI bits appropriately.
For your app, I would go with the repeating timer approach only if I had plans for other time-based features in future releases or if I wanted to dynamically change the times for event A, B and C.  Otherwise, I'd probably set up three timers at the beginning, one each for events A, B and C.  That way the logic managing the time partitioning is all in one place, likely the AppDelegate, and the button change logic can all live in the View Controller.

A: What I am doing right now is starting the timer with interval of 1 and repeat: YES
When it fires it calls a method which simply increments seconds(int)
Within this method, which is called every 1 second, I will use a switch statement to check the value of seconds and if it is a certain value it will pause my player and invalidate the timer.
This should pause the video and stop my seconds from being incremented.
I will then have a button for the user to resume the video which will play the vid and begin the same timer again and resume incrementing seconds.
My only worry is that the second count may not be accurate to the video because of processing delays at runtime dealing with the video and the switch statement being checked. I'll report back how it works.


text:
Q: Django forms: making a disabled field persist between validations At some point I need to display a "disabled" (greyed out by disabled="disabled" attribute) input of type "select". As specified in the standard (xhtml and html4), inputs of type "select" can not have the "readonly" attribute. Note that this is for presentation purposes only, the actual value must end up in the POST. So here is what I do (quoting a part of the form declaration in django):
from django import forms

_choices = ['to be', 'not to be']
class SomeForm(forms.Form):
    field = forms.ChoiceField(choices=[(item, item) for item in _choices],
                   widget=forms.HiddenInput()) # the real field

    mock_field = forms.ChoiceField(required=False, # doesn't get submitted
                        choices=[(item, item) for item in _choices],
                        label="The question",
                        widget=forms.Select(attrs={'disabled':'disabled'}))

Then it is initialized like this:
initial_val = 'to be'
form = SomeForm(ititial={'field':initial_val,
                         'mock_field':initial_val})

And all is well. Well, until the form gets validated and one of the other fields fails the validation. When this happens, the form is reloaded and the values are preserved, but not the one of the "mock_field" - it never got submitted (it is disabled). So it is not preserved. While this doesn't affect the data integrity, it is still not so good presentation-wise.
Is there any way to preserve that field, with as little hackery as possible? The form is a part of a django.contrib.formtools.FormWizard and the initial values (and some fields) are generated dynamically. Basically, there is a lot of stuff going on already, it'd be great if it was possible not to overcomplicate things.

A: Browsers don't POST disabled fields.
You can try to copy fields initial value to mock_field in your Form's __init__
def __init__(self, *args, **kwargs):
    super(SomeForm, self).__init__(*args, **kwargs)
    mock_initial = self.fields['field'].initial
    self.fields['mock_field'].initial = mock_initial

Code is not tested. Normally you would be concerned about form.data as well, but in this case it won't be different than initial

A: Well, this will be the first time I answer my question, but I've found a solution and (while it cerainly is a hack) it works.
Instead of getting the initial value from the form instance, - self.fields['whatever'].initial seems to be None inside the constructor, I am getting the value from keyword argument "initial". And then I set it as the only choice for the "mock" field. Like this:
from django import forms

_choices = ['to be', 'not to be']
class SomeForm(forms.Form):
    field = forms.ChoiceField(choices=[(item, item) for item in _choices],
                   widget=forms.HiddenInput()) # the real field

    mock_field = forms.ChoiceField(required=False, # doesn't get submitted
                        choices=[(item, item) for item in _choices],
                        label="The question",
                        widget=forms.Select(attrs={'disabled':'disabled'}))

    def __init__(self, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)
        mock_initial = kwargs['initial']['field']
        self.fields['mock_field'].choices = [(mock_initial, mock_initial),]

This probably needs some error handling. Obviously, this will not work if the initial value is not provided for the actual field.


text:
Q: Submit form requires more than one click in IE Please find below file code where multiple file upload functionality is given. On click of upload link it opens input file browser window where we select file and then click on submit.
In chrome, submit button submits the form on first click but In IE, it does not submit the form on first click.
In IE, If we select one file using upload link then submit button submits the form in second click.
If we select two file then it submits the form in 3rd click and accordingly.
Please let me know how to stop this event chain to submit in one click.
Please find below test.html file as,
https://www.dropbox.com/s/o7dwxhjnegxo0fo/Test.html?dl=0


text:
Q: Cause of undeclared entity warning using nusoap and asmx? I'm writing a php client for an ASP.Net web service. When I run, I get:
wsdl error: XML error parsing WSDL from https://ctechgames:443/Service1.asmx on line 99: Undeclared entity warning

after making the call. I'm pretty new at this, and I really don't know what I'm doing.
Request and response are both empty. I don't know what's going on, or why. Here's my client code:
$client = new nusoap_client("https://ctechgames:443/Service1.asmx",
                        array('soap_version' => SOAP_1_2));
$schoolName = $client->call('GetSchoolName', array() );

Any advice?

A: Solved the problem. Changed the code to the following:
$client = new nusoap_client("https://ctechgames:443/Service1.asmx?wsdl",
                        array('soap_version' => SOAP_1_2));
$schoolName = $client->call('GetSchoolName', array('parameters' => array()) );

The ?wsdl gets the wsdl from the website, instead of the html for access from a web browser. The 'parameters' => array() is just something .Net web methods want, based on the way it parses the parameters.
Hope this helps someone out there!


text:
Q: Get Post object by page I tried to get certain amount of Post objects per page (like 10) and I tried that using extension methods
  int _start = _page * _listItemsPerPage;
  int _end = (_page + 1) * _listItemsPerPage;

  if (Posts.Count > _end)
       return  (Posts.Skip(_start).Take(_end - _start)) as List<Post>;
  else
       return  (Posts.Skip(_start).Take(Posts.Count - _start)) as List<Post>;

But I've done something wrong because It allways returns null .
Aditional info:

*

*Posts is List< Post > Type, collection of dummie data

*_page - page number

*_listItemsPerPage - how many items are needed to be displayed

*_start - starting index

*_end  - ending index

*I've done prior exception check

A: The calls to Skip and Take return an IEnumerable<Post>, not a List<Post>, so converting to a List<Post> with as List<Post> fails and returns null.
Either add call to AsList(), or just return the IEnumerable<Post>.


text:
Q: Blocking specific USB drives on MacOS I need to block specific USB drives on MacOS. I found two methods.

*

*Use Disk Arbitration framework and register approval callback.(user mode)

*Use MAC policy API in kernel extension and register mpo_mount_check_mount callback.(kernel mode)

In user mode, I can get a kDADiskDescriptionDeviceVendorKey which is the vender id of USB drive. I'm wondering how I can get the same information in mpo_mount_check_mount callback or some other API I don't know. The MAC policy API is undocumented and browsing the XNU source code is extremely challenging for a new MacOS developer.
This is a screenshot from IORegistryExplorer. Could I get this information from a kernel extension using MACF or other APIs? Thanks!

I can use DiskArbitration and IOKit frameworks to get vender id in user mode, but I cannot use the same code in kernel extension.
This is my code.
int GetVenderId(DADiskRef dsk, int *vid)
{
    io_service_t ioService;
    CFTypeRef vendorid;

    ioService = DADiskCopyIOMedia(dsk);

    if (0 != ioService)
    {
        vendorid = IORegistryEntrySearchCFProperty(ioService, kIOServicePlane, CFSTR("idVendor"), NULL, kIORegistryIterateParents | kIORegistryIterateRecursively);
        if(0 != vendorid)
        {
            if (CFNumberGetValue(vendorid, kCFNumberIntType, vid))
            {
                return 0;
            }

            CFRelease(vendorid);
        }

        IOObjectRelease(ioService);
    }

    return 1;
}


text:
Q: How do I generate a .jar file from javadoc generated html? I am working on an Android Studio project and I need to export the Javadoc documentation for an AAR package that we are going to distribute.
Apparently Android Studio does not yet support this automatically, so I would like to generate a separate .jar package containing the documentation that can be then imported by Android Studio (or IntelliJ).
I have tried simply making a jar file of the generated documentation folder but importing the resulting jar file as Android Studio module does not enable me to see the documentation of the classes from my AAR package.
Using Eclipse and/or Maven is not an option. I would like to obtain the .jar archive manually only using javadoc and jar tools if possible.


text:
Q: TailwindCSS Margins of Parent and Child overlapping? I am using TailwindCSS and have a nested HTML structure like so:

What I don't understand is why the inner div is placed in such a way that its border aligns with the border of the outer div and the margins which I applied overlap. However, I noticed that when I add a border around the outer div, the margins suddenly behave how i would expect: the outer div contains the elements including margins.
Here is a jsfiddle to illustrate my point: https://jsfiddle.net/1vptz5fc/
How can I get the divs to behave like they do with borders, just without adding a border?

A: Is would say you should use the padding py that will fix it , look:

.test {
  border: 1px solid red;
}

    with py

    Other Content

<button type="button" onclick="document.getElementById('parent').style.border = 'none';">
Click Me
</button>

    with border

    Other Content

<button type="button" onclick="document.getElementById('parent').style.border = 'none';">
Click Me
</button>

A: It seems like it's the default behaviour if there's no element between parent and child.
Margin collapsing occurs in three basic cases:

*

*Adjacent siblings

*No content separating parent and descendants

*Empty blocks

There's a stackoverflow thread that might help you:
How to disable margin-collapsing?
More information on margin collapse:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
You can probably add display: inline-block; to get the expected results regarding the margin but you will have to adjust with other styles.


text:
Q: A word to describe something of two origin/source I'm looking for a word to describe something of two origin/source . Like a river of two origin points.

A: If your viewpoint is looking back towards the sources, it is bifurcated, meaning it splits.
If you just want the union of two sets of discrete things, then commingled

to join or mix together

"Commingle." Merriam-Webster.com. Merriam-Webster, n.d. Web. 2 Apr. 2016.
If you want the state of being composed of two things, it is conjoint.

Combining all or both people or things involved

Oxford dictionaries:http://www.oxforddictionaries.com/us/definition/american_english/conjoint
If the two sources mix, like paint, then blended would work. Blended is also used for abstractions like theories or ideas.

to mix (things) thoroughly and usually with good results
   to exist together as a combination

"Blend." Merriam-Webster.com. Merriam-Webster, n.d. Web. 2 Apr. 2016.


text:
Q: syntax for setting html in jquery with frames I have the following jquery sentence in my program:
$("#(parent.frames[2].id)").html (Content);

In frame 2 there is a string variable called id which holds the id of the element I want to change. What I want to do is to replace all the html of this id with the string Content.
The console is actually outputing a syntax error Error: Syntax error, unrecognized expression: #(parent.frames[2].id). What should be the correct syntax?

A: Your selector is invalid. I assume you mean the .parent object of window.
Try this instead
$("#"+parent.frames[2].id).html(Content);

A: I finally implemented it with javascript:
parent.frames[2].document.getElementById(parent.frames[2].id).innerHTML = Content;


text:
Q: cw and . does not work as expected in vim on character deletion If I have the following non-sense text:
Hi woman! What is your name? I know what you mean...
Yeap.
Yeap. Again :)
Hi woman! What i s your name? I know what you mean...
Yeap.
Yeap. Again :)
Hi woman! What is your name? I know what you mean...
Yeap.
Yeap. Again :)
Hi woman! What is your name? I know what you mean...
Yeap.
Yeap. Again :)

and I want to replace all occurences of woman with man I do:
Go my cursor to the first occurence of woman which is on the first line. I press * and all occurrences are highlighted.
Then I type cw and delete w and o and press ESC.
Then I press n and move to the next occurrence.
Then I type . and expect that wo will be removed.
But only w is deleted. Why?

A: Instead of deleting the characters in insert mode, delete them in normal mode. Navigate to woman and type 2x to delete the first two characters.
Or, you can use substitution: :%s/woman/man/g.


text:
Q: Как достать элементы из JSON в виде массива? "0": {},
"Guys": {
    "0": null,
    "1": {
        "id": "1",
        "name": "Mort",
        "lat": "443",
        "lng": "23",
        "status": "1"
    },
    "2": {
        "id": "2",
        "name": "Sam",
        "lat": "45",
        "lng": "324",
        "status": "0"
    },
    "3": {
        "id": "3",
        "name": "Peter",
        "lat": "546",
        "lng": "24",
        "status": "1"
    },
    "4": {
        "id": "4",
        "name": "Adam",
        "lat": "643",
        "lng": "22",
        "status": "1"
    },
    "5": {
        "id": "5",
        "name": "Bonzo",
        "lat": "2423",
        "lng": "2344",
        "status": "0"
    },
    "6": {
        "id": "6",
        "name": "hjghj",
        "lat": "657",
        "lng": "66",
        "status": "1"
    },
    "7": {
        "id": "7",
        "name": "h",
        "lat": "44",
        "lng": "44",
        "status": "0"
    },
    "8": {
        "id": "8",
        "name": "h",
        "lat": "6576",
        "lng": "6",
        "status": "1"
    },

Как вытащить все элементы из Guys(в моем случае их 8) в виде JSON массива.
Т.е... простейший, может даже и глупый пример: чтобы JSONArray.length возвращало восемь. И так, чтобы можно было доставать их в цикле и, например, выводить в List View.
Спасибо.

A: Я еще не практиковал GSON (с ним удобнее) но все же:
1. Создайте модель Guy:
public class Guy {

    private long id;
    private String name;
    private double lat, lng;
    private boolean status;

    public Guy(long id, String name, double lat, double lng, boolean status){
        this.id = id;
        this.name = name;
        this.lat = lat;
        this.lng = lng;
        this.status = status;
    }

    //getters and setters
    //Alt + Insert

}

2. Парсинг JSON
public List<Guy> parseGuys(JSONObject json) {
    List<Guy> guys = new ArrayList<>();
    JSONObject guysJSON = json.getJSONObject("Guys");
    Iterator<?> keys = guysJSON.keys();
    while(keys.hasNext()) {
        Object value = guysJSON.get((String)keys.next());
        if (value != null && value instanceof JSONObject) {
            JSONObject guyJSON = (JSONObject) value;
            long id = guyJSON.getLong("id");
            String name = guyJSON.getString("name");
            double lat = guyJSON.getDouble("lat");
            double lng = guyJSON.getDouble("lng");
            boolean status = (1 == guyJSON.getInt("status"));
            guys.add(new Guy(id, name, lat, lng, status));
        }
    }
    return guys;
}

3. Создание адаптера (я предпочитаю 'RecyclerView')
public class GuysAdapter extends RecyclerView.Adapter<GuysAdapter.GuyHolder> {

    private List<Guy> guys;

    private class GuyHolder extends RecyclerView.ViewHolder {

        private TextView tv_name;

        public ViewHolder(View itemView) {
            super(itemView);
            tv_name = (TextView) itemView.findViewById(R.id.guy_item_name);
        }

        public void bind(Guy guy) {
            tv_name.setText(guy.getName());
        ]
    }

    public GuysAdapter(List<Guy> guys) {
        this.guys = guys;
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.guy_item, parent, false));
    }

    @Override
    public void onBindViewHolder(GuyHolder holder, int position) {
        holder.bind(guys.get(position));
    }

    @Override
    public int getItemCount() {
        return guys.size();
    }
}

4. Создание адаптера
RecyclerView guysList = (RecyclerView) findViewById(R.id.guysList);
guysList.setLayoutManager(new LinearLayoutManager(this));
GuysAdapter adapter = new GuysAdapter(parseGuys(json));
guysList.setAdapter(adapter);

A: Вообще, у вас Guys в json'е - это словарик, а не массив.
С помощью jackson можно так:
ObjectMapper JsonMapper = new ObjectMapper();

ObjectNode node = JsonMapper.readValue(testStr, ObjectNode.class);

// получаем словарь парней
Map<String, ObjectNode> guys = JsonMapper.readValue(node.get("Guys"), new TypeReference<HashMap<String,ObjectNode>>() {});

// преобразуем в массив
ObjectNode[] guysArray = guys.values().toArray(new ObjectNode[guys.size()]);

Подключение jackson:
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

A: Допустим у вас есть модель:
public class Guy {

    public long id;
    public String name;
    public double lat, lng;
    public boolean status;

}

Так же есть класс:
public class GuysList {

    public final Map<String, Guy> guys = new HashMap<>();

    @JsonAnyGetter
    public Map<String, Object> any() {
        return guys;
    }

    @JsonAnySetter
    public void set(String name, Object value) {
        guys.put(name, value);
    }
}

Теперь вам Jackson с легкостью разберет (если вы берете json из сети - посмотрите на Retrofit + Jackson):
ObjectMapper mapper = new ObjectMapper();
GuysList data = mapper.readValue(testStr, GuysList.class);
// теперь можно вызвать data.values() для получения списка или data.size() для количества


text:
Q: How to automatically previous textfield when clear button press swiftui I am trying to create OTP screen and when the user entered the digit in the first text field and after cursor automatically move to next text field, thus functionality I got it, but I was stuck when the user removes the text in the current text field and how to automatically move to the previous text field.
ScreenShot:-

Code:-
import SwiftUI

struct VerficationCode: View {
@State private var numberOfCells: Int = 6
@State private var currentlySelectedCell = 0

var body: some View {
    HStack {
        Group {
            ForEach(0 ..< self.numberOfCells) { index in
                CharacterInputCell(currentlySelectedCell: self.$currentlySelectedCell, index: index)
            }
        }.frame(width:15,height: 56)
        .padding(.horizontal)
        .foregroundColor(.white)
        .cornerRadius(10)
        .keyboardType(.numberPad)
       }
    }
 }

struct CharacterInputCell: View {
@State private var textValue: String = ""
@Binding var currentlySelectedCell: Int

var index: Int

var responder: Bool {
    return index == currentlySelectedCell
}

var body: some View {
    CustomTextField(text: $textValue, currentlySelectedCell: $currentlySelectedCell, isFirstResponder: responder)
    }
 }

   struct CustomTextField: UIViewRepresentable {

class Coordinator: NSObject, UITextFieldDelegate {

    @Binding var text: String
    @Binding var currentlySelectedCell: Int

    var didBecomeFirstResponder = false

    init(text: Binding<String>, currentlySelectedCell: Binding<Int>) {
        _text = text
        _currentlySelectedCell = currentlySelectedCell
    }

    func textFieldDidChangeSelection(_ textField: UITextField) {
        DispatchQueue.main.async {
            self.text = textField.text ?? ""
        }
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentText = textField.text ?? ""
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        if updatedText.count <= 1 {
            self.currentlySelectedCell += 1
        }
        return updatedText.count <= 1
    }
}

@Binding var text: String
@Binding var currentlySelectedCell: Int
var isFirstResponder: Bool = false

func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
    let textField = UITextField(frame: .zero)
    textField.delegate = context.coordinator
    textField.textAlignment = .center
    textField.keyboardType = .decimalPad
    return textField
}

func makeCoordinator() -> CustomTextField.Coordinator {
    return Coordinator(text: $text, currentlySelectedCell: $currentlySelectedCell)
}

func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
    uiView.text = text
    if isFirstResponder && !context.coordinator.didBecomeFirstResponder  {
        uiView.becomeFirstResponder()
        context.coordinator.didBecomeFirstResponder = true
        }
     }
}

Can someone please explain to me how to back automatically when click on clear button, I've tried to implement but no results yet.
Any help would be greatly appreciated.
Thanks in advance.

A: try it
        import SwiftUI
    public struct PasscodeField: View {

        var maxDigits: Int = 6
        var label = "Enter One Time Password"

        @State var pin: String = ""
        @State var showPin = true
        //@State var isDisabled = false

        var handler: (String, (Bool) -> Void) -> Void

        public var body: some View {
            VStack{
                Text(label).font(.title)
                ZStack {
                    pinDots
                    backgroundField
                }
                showPinStack
            }

        }

        private var pinDots: some View {
            HStack {
                Spacer()
                ForEach(0..<maxDigits) { index in
                    Image(systemName: self.getImageName(at: index))
                        .font(.system(size: 60))
                    Spacer()
                }.frame(minWidth: 0, maxWidth: .infinity)
                .padding(.trailing, -24)
            }
        }

        private var backgroundField: some View {
            let boundPin = Binding<String>(get: { self.pin }, set: { newValue in
                self.pin = newValue
                self.submitPin()
            })

            return TextField("", text: boundPin, onCommit: submitPin)

          // Introspect library can used to make the textField become first resonder on appearing
          // if you decide to add the pod 'Introspect' and import it, comment #50 to #53 and uncomment #55 to #61

               .accentColor(.clear)
               .foregroundColor(.clear)
               .keyboardType(.numberPad)
               //.disabled(isDisabled)

    //             .introspectTextField { textField in
    //                 textField.tintColor = .clear
    //                 textField.textColor = .clear
    //                 textField.keyboardType = .numberPad
    //                 textField.becomeFirstResponder()
    //                 textField.isEnabled = !self.isDisabled
    //         }
        }

        private var showPinStack: some View {
            HStack {
                Spacer()
                if !pin.isEmpty {
                    showPinButton
                }
            }
            .frame(height: 100)
            .padding([.trailing])
        }

        private var showPinButton: some View {
            Button(action: {
                self.showPin.toggle()
            }, label: {
                self.showPin ?
                    Image(systemName: "eye.slash.fill").foregroundColor(.primary) :
                    Image(systemName: "eye.fill").foregroundColor(.primary)
            })
        }

        private func submitPin() {
            //guard !pin.isEmpty else {
                //showPin = false
                //return
            //}

            if pin.count == maxDigits {
                //isDisabled = true

                handler(pin) { isSuccess in
                    if isSuccess {
                        print("pin matched, go to next page, no action to perfrom here")
                    } else {
                        pin = ""
                        //isDisabled = false
                        print("this has to called after showing toast why is the failure")
                    }
                }
            }

            // this code is never reached under  normal circumstances. If the user pastes a text with count higher than the
            // max digits, we remove the additional characters and make a recursive call.
            if pin.count > maxDigits {
                pin = String(pin.prefix(maxDigits))
                submitPin()
            }
        }

        private func getImageName(at index: Int) -> String {
            if index >= self.pin.count {
                return "circle"
            }

            if self.showPin {
                return self.pin.digits[index].numberString + ".circle"
            }

            return "circle.fill"
        }
    }

    extension String {

        var digits: [Int] {
            var result = [Int]()

            for char in self {
                if let number = Int(String(char)) {
                    result.append(number)
                }
            }

            return result
        }

    }

    extension Int {

        var numberString: String {

            guard self < 10 else { return "0" }

            return String(self)
        }
    }


text:
Q: Scala batch processing triggered by size or time I'd like to batch up some events for processing, and have the triggering of the processing for a batch be based on the number of events reaching a certain threshold OR a time interval expiring (whichever happens first).  What should I consider?  Futures?  Akka?  Some more special-purpose library that might exist?

A: Two options come to mind:

*

*Using Akka

*Using Quartz
This depends on your specific architecture, but you can use any form of scheduling. You can use an Akka scheduler to schedule a task to run regularly and use your own internal queue to trigger the batch job if it's full. You can also do very similar things with Quartz but you might have to write more boilerplate code with the benefit of having more flexibility.
If you don't wish to bring in a fairly heavyweight library, I suppose you could implement something yourself, but you would be reinventing the wheel.


text:
Q: cURL: POST request gets treated as GET I made a POST request, printed out header out information and noticed that is gets treated as GET. What is the reason for such behaviour?
HEADER OUT DATA:
GET /inx/aeGDrYQ HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3
Accept: */*
Cookie: PHPSESSID=t762fd0nbi12p3hrgb9sgx9k20; ____ri=4485; safemode=1; session=eyJpdiI6Im1HQzlNR1JhMTNDc0JRelYyRVwveUp6N0JxZG56Z2p5K094eSs3YU5HQ3dzPSIsInZhbHVlIjoiVXBPYzN4TVNReURhVnMxQlZ1TndLZ0dYUjltbUVEcW11bkJJMDdMRVZoZ0hHMjRXZ2p6azlcL1FWXC93NnZWN3oreDcxQms3aGlcL3l0MG1vTjd1V21FcmVCVzFnQjVuMUY5dHBWeUlTbU9NSjJcL1d5TlwvTW11ZWp1eHpNd3d4eFZTamV6aThsNldkdlN3aFo0XC9sTnVnU0tXVDRKbWVBU25VU0hJaDREQ1J5M2xDXC9zRUc5OXhWMWJWWG9jYndhczYyZW4xMkUxb3BoU3FmQmMrNVdzM3RqQmgzeHY1NVJ5RXRTNGZOdmQ4dTRCbmRtWVZBN210QVVEVk1BNTFPc1NQcFU3bnd4NEpKbnRaTFliRWNzbkZaXC9YWUF1Nld1ekZSbjVGRXBuZzNoRlBNND0iLCJtYWMiOiI4OWEwNmMyZGVkYjFiYTlmNDY0MDE5MTQwNzE1YzNhYWJjYTA5YjJ3MWMyZjgwMTViN2MyYmI0OWUyNmMwNjM0In0%3D; toastMsg=2; ts1=11e2bb0a86bfb9669c36Xcc407e1e3b3decefcce

REST OF THE CODE:
$ch = curl_init('https://example.com/login');

$postData = [
    'name'       => $name,
    'pass'       => $pass
];

$postDataStr = http_build_query($postData);

# Append some fields to the CURL options array to make a POST request. I left out headers, since
# they don't change and added return_transfer for echoing end results
$options[CURLOPT_POST] = 1;
$options[CURLOPT_POSTFIELDS] = $postDataStr;
$options[CURLOPT_HEADER]=1;
$options[CURLOPT_COOKIEJAR]=$cookie;
$options[CURLOPT_USERAGENT]= $useragent;

$options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLINFO_HEADER_OUT] = true;

curl_setopt_array($ch, $options);

# Execute
$response = curl_exec($ch);
// echo $response;

$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
echo "Request sent: $request<br>";

A: You're only showing one request, and I suspect it is the second request where the first was a POST and the GET you see here is the one done after a redirect has been followed.
curl may switch to a GET when following a redirect based on which 30x code is in the response and the behavior is guided by the HTTP 1.1 spec (RFC 7230 and friends).


text:
Q: Rails scheduled task behind a load balancer I was wondering how to properly schedule a task for a rails application that sits behind an elastic load balancer.
This task is an automated weekly email that is to be sent out every Monday from the application. We currently have multiple EC2 instances that sit behind a LB.
I was going to use the whenever gem in order to accomplish this and have the schedule in the code repo, but thought it would attempt to run the task from all of our instances.
What can I do to run a scheduled rake task once per week on servers behind a load balancer?

A: As zwippie said

Perhaps this converation is still relevant, it mentions that the tasks will only run on the machine with the :db role.

I believe that roles are the best solution to this problem currently.


text:
Q: migration to AndroidX exception I am migrating a project to AndroidX and have this strange exception.
How do I find which library causes this?
There is mentioned com.android.tools:common:26.3.0 and android.support.design.widget but I do not really understand that
These are build.gradle dependencies:
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.exifinterface:exifinterface:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'

    implementation "com.esri.arcgisruntime:arcgis-android:100.6.0"

    implementation "com.google.android.gms:play-services-location:$googlePlayServicesVersion"

    implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-jackson:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-scalars:2.1.0"
    implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion"
    implementation "com.squareup.okhttp3:logging-interceptor:3.10.0"

    implementation "com.facebook.stetho:stetho:1.5.1"
    implementation "com.facebook.stetho:stetho-okhttp3:1.5.1"
    implementation "com.uphyca:stetho_realm:2.3.0"

    implementation "io.reactivex.rxjava2:rxandroid:2.0.2"
    implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'

    implementation 'org.kodein.di:kodein-di-generic-jvm:6.2.1'
    implementation 'org.kodein.di:kodein-di-framework-android-x:6.2.1'

    implementation 'com.github.ajalt:timberkt:1.5.1'

    implementation 'org.slf4j:slf4j-api:1.7.25'
    implementation 'com.github.tony19:logback-android:2.0.0'

    implementation "com.google.firebase:firebase-core:$firebaseCoreVersion"
    implementation "com.google.firebase:firebase-messaging:$firebaseMessagingVersion"
    implementation "com.google.firebase:firebase-ml-vision:$firebaseVisionVersion"

    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"

    implementation 'net.openid:appauth:0.7.1'

    implementation "commons-io:commons-io:2.5"

    // The Apache Commons Text
    implementation "org.apache.commons:commons-text:1.6"

    implementation "android.arch.navigation:navigation-runtime:$navigation"
    implementation "android.arch.navigation:navigation-runtime-ktx:$navigation"
    implementation "android.arch.navigation:navigation-fragment:$navigation"
    implementation "android.arch.navigation:navigation-fragment-ktx:$navigation"
    implementation "android.arch.navigation:navigation-ui:$navigation"
    implementation "android.arch.navigation:navigation-ui-ktx:$navigation"
    implementation "android.arch.navigation:navigation-safe-args-gradle-plugin:$navigation"

    //implementation "com.scandit.datacapture:core:$scandit_version"
    //implementation "com.scandit.datacapture:barcode:$scandit_version"

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

ERROR:
    FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
> Could not resolve all artifacts for configuration ':app:debugCompileClasspath'.
   > Failed to transform artifact 'common.jar (com.android.tools:common:26.3.0)' to match attributes {artifactType=android-classes, org.gradle.usage=java-runtime-jars}.
      > Execution failed for JetifyTransform: C:\Users\xxx\.gradle\caches\modules-2\files-2.1\com.android.tools\common\26.3.0\1d9b4db75bbe5fe357c8a56db506f2361ebd508d\common-26.3.0.jar.
         > Failed to transform 'C:\Users\xxx\.gradle\caches\modules-2\files-2.1\com.android.tools\common\26.3.0\1d9b4db75bbe5fe357c8a56db506f2361ebd508d\common-26.3.0.jar' using Jetifier. Reason: The given artifact contains a string literal with a package reference 'android.support.design.widget' that cannot be safely rewritten. Libraries using reflection such as annotation processors need to be updated manually to add support for androidx.. (Run with --stacktrace for more details.)

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:38)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:49)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all artifacts for configuration ':app:debugCompileClasspath'.
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.rethrowFailure(DefaultConfiguration.java:1195)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.access$2100(DefaultConfiguration.java:138)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationArtifactCollection.ensureResolved(DefaultConfiguration.java:1634)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationArtifactCollection.getArtifacts(DefaultConfiguration.java:1606)
    at com.android.build.gradle.internal.dependency.ArtifactCollectionWithExtraArtifact.getArtifacts(ArtifactCollectionWithExtraArtifact.java:119)
    at com.android.build.gradle.internal.dependency.ArtifactCollectionWithExtraArtifact.iterator(ArtifactCollectionWithExtraArtifact.java:133)
    at org.jetbrains.kotlin.gradle.plugin.Android25ProjectHandler$wireKotlinTasks$2.invoke(Android25ProjectHandler.kt:230)
    at org.jetbrains.kotlin.gradle.plugin.Android25ProjectHandler$wireKotlinTasks$2.invoke(Android25ProjectHandler.kt:26)
    at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.setupCompilerArgs(Tasks.kt:406)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.setupCompilerArgs(Tasks.kt:355)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAware$DefaultImpls.setupCompilerArgs$default(CompilerArgumentAware.kt:37)
    at org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask.setupCompilerArgs(KaptGenerateStubsTask.kt:83)
    at org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask.setupCompilerArgs(KaptGenerateStubsTask.kt:36)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAware$DefaultImpls.setupCompilerArgs$default(CompilerArgumentAware.kt:37)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAwareKt.prepareCompilerArguments(CompilerArgumentAware.kt:41)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAware$DefaultImpls.getFilteredArgumentsMap(CompilerArgumentAware.kt:34)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAwareWithInput$DefaultImpls.getFilteredArgumentsMap(CompilerArgumentAware.kt:54)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompileTool.getFilteredArgumentsMap(Tasks.kt:48)
    at org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask_Decorated.getFilteredArgumentsMap(Unknown Source)
    at org.gradle.api.internal.tasks.properties.bean.AbstractNestedRuntimeBeanNode$BeanPropertyValue$1$1.create(AbstractNestedRuntimeBeanNode.java:75)
    at org.gradle.util.SingleMessageLogger.whileDisabled(SingleMessageLogger.java:341)
    at org.gradle.api.internal.tasks.properties.bean.AbstractNestedRuntimeBeanNode$BeanPropertyValue$1.get(AbstractNestedRuntimeBeanNode.java:72)
    at com.google.common.base.Suppliers$NonSerializableMemoizingSupplier.get(Suppliers.java:167)
    at org.gradle.api.internal.tasks.properties.bean.AbstractNestedRuntimeBeanNode$BeanPropertyValue.call(AbstractNestedRuntimeBeanNode.java:119)
    at org.gradle.api.internal.tasks.properties.AbstractValidatingProperty.validate(AbstractValidatingProperty.java:37)
    at org.gradle.api.internal.tasks.properties.DefaultTaskProperties.validate(DefaultTaskProperties.java:184)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
    at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:94)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    ... 24 more
Caused by: org.gradle.api.internal.artifacts.transform.TransformException: Failed to transform artifact 'common.jar (com.android.tools:common:26.3.0)' to match attributes {artifactType=android-classes, org.gradle.usage=java-runtime-jars}.
    at org.gradle.api.internal.artifacts.transform.TransformingArtifactVisitor.lambda$visitArtifact$1(TransformingArtifactVisitor.java:61)
    at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:191)
    at org.gradle.api.internal.artifacts.transform.TransformingArtifactVisitor.visitArtifact(TransformingArtifactVisitor.java:50)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ArtifactBackedResolvedVariant$SingleArtifactSet.visit(ArtifactBackedResolvedVariant.java:112)
    at org.gradle.api.internal.artifacts.transform.TransformCompletion.visit(TransformCompletion.java:42)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.CompositeResolvedArtifactSet$CompositeResult.visit(CompositeResolvedArtifactSet.java:83)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ParallelResolveArtifactSet$VisitingSet.visit(ParallelResolveArtifactSet.java:64)
    at org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration.visitArtifacts(DefaultLenientConfiguration.java:256)
    at org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration.access$500(DefaultLenientConfiguration.java:69)
    at org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$2.run(DefaultLenientConfiguration.java:231)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration.visitArtifactsWithBuildOperation(DefaultLenientConfiguration.java:228)
    at org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration.access$200(DefaultLenientConfiguration.java:69)
    at org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$1.visitArtifacts(DefaultLenientConfiguration.java:133)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationArtifactCollection.ensureResolved(DefaultConfiguration.java:1628)
    ... 58 more
Caused by: org.gradle.api.internal.artifacts.transform.TransformException: Execution failed for JetifyTransform: C:\Users\xxx\.gradle\caches\modules-2\files-2.1\com.android.tools\common\26.3.0\1d9b4db75bbe5fe357c8a56db506f2361ebd508d\common-26.3.0.jar.
    at org.gradle.api.internal.artifacts.transform.DefaultTransformerInvoker.lambda$invoke$1(DefaultTransformerInvoker.java:172)
    at org.gradle.internal.Try$Failure.mapFailure(Try.java:182)
    at org.gradle.api.internal.artifacts.transform.DefaultTransformerInvoker.lambda$invoke$2(DefaultTransformerInvoker.java:172)
    at org.gradle.api.internal.artifacts.transform.DefaultTransformerInvoker.fireTransformListeners(DefaultTransformerInvoker.java:219)
    at org.gradle.api.internal.artifacts.transform.DefaultTransformerInvoker.lambda$invoke$3(DefaultTransformerInvoker.java:117)
    at org.gradle.api.internal.artifacts.transform.ImmutableTransformationWorkspaceProvider.lambda$withWorkspace$0(ImmutableTransformationWorkspaceProvider.java:81)
    at org.gradle.cache.internal.LockOnDemandCrossProcessCacheAccess.withFileLock(LockOnDemandCrossProcessCacheAccess.java:90)
    at org.gradle.cache.internal.DefaultCacheAccess.withFileLock(DefaultCacheAccess.java:194)
    at org.gradle.cache.internal.DefaultPersistentDirectoryStore.withFileLock(DefaultPersistentDirectoryStore.java:170)
    at org.gradle.cache.internal.DefaultCacheFactory$ReferenceTrackingCache.withFileLock(DefaultCacheFactory.java:194)
    at org.gradle.api.internal.artifacts.transform.ImmutableTransformationWorkspaceProvider.withWorkspace(ImmutableTransformationWorkspaceProvider.java:76)
    at org.gradle.api.internal.artifacts.transform.AbstractCachingTransformationWorkspaceProvider.lambda$withWorkspace$0(AbstractCachingTransformationWorkspaceProvider.java:54)
    at com.google.common.cache.LocalCache$LocalManualCache$1.load(LocalCache.java:4717)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3444)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2193)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2152)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2042)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3850)
    at com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4712)
    at org.gradle.api.internal.artifacts.transform.AbstractCachingTransformationWorkspaceProvider.withWorkspace(AbstractCachingTransformationWorkspaceProvider.java:53)
    at org.gradle.api.internal.artifacts.transform.DefaultTransformerInvoker.invoke(DefaultTransformerInvoker.java:116)
    at org.gradle.api.internal.artifacts.transform.TransformationStep.lambda$transform$0(TransformationStep.java:104)
    at org.gradle.internal.Try$Success.flatMap(Try.java:102)
    at org.gradle.api.internal.artifacts.transform.TransformationStep.transform(TransformationStep.java:101)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$InitialTransformationNode$1.transform(TransformationNode.java:159)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$ArtifactTransformationStepBuildOperation.call(TransformationNode.java:229)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$ArtifactTransformationStepBuildOperation.call(TransformationNode.java:212)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$InitialTransformationNode.execute(TransformationNode.java:145)
    at org.gradle.api.internal.artifacts.transform.TransformationNodeExecutor.execute(TransformationNodeExecutor.java:37)
    ... 12 more
Caused by: java.lang.RuntimeException: Failed to transform 'C:\Users\xxx\.gradle\caches\modules-2\files-2.1\com.android.tools\common\26.3.0\1d9b4db75bbe5fe357c8a56db506f2361ebd508d\common-26.3.0.jar' using Jetifier. Reason: The given artifact contains a string literal with a package reference 'android.support.design.widget' that cannot be safely rewritten. Libraries using reflection such as annotation processors need to be updated manually to add support for androidx.. (Run with --stacktrace for more details.)
    at com.android.build.gradle.internal.dependency.JetifyTransform.transform(JetifyTransform.kt:118)
    at org.gradle.api.internal.artifacts.transform.LegacyTransformer.transform(LegacyTransformer.java:76)
    at org.gradle.api.internal.artifacts.transform.DefaultTransformerInvoker$TransformerExecution.execute(DefaultTransformerInvoker.java:274)
    at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$1(ExecuteStep.java:33)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:33)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:58)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:35)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:48)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:33)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:39)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
    at org.gradle.internal.execution.steps.CatchExceptionStep.execute(CatchExceptionStep.java:35)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:45)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:31)
    at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:201)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:70)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:45)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:49)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:43)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:32)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:96)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:89)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:54)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:38)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:77)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:90)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:48)
    at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
    at org.gradle.api.internal.artifacts.transform.DefaultTransformerInvoker.lambda$invoke$2(DefaultTransformerInvoker.java:148)
    ... 45 more
Caused by: com.android.tools.build.jetifier.processor.transform.bytecode.AmbiguousStringJetifierException: The given artifact contains a string literal with a package reference 'android.support.design.widget' that cannot be safely rewritten. Libraries using reflection such as annotation processors need to be updated manually to add support for androidx.
    at com.android.tools.build.jetifier.processor.transform.bytecode.CoreRemapperImpl.rewriteString(CoreRemapperImpl.kt:91)
    at com.android.tools.build.jetifier.processor.transform.bytecode.asm.CustomRemapper.mapValue(CustomRemapper.kt:75)
    at org.objectweb.asm.commons.ClassRemapper.visitField(ClassRemapper.java:113)
    at org.objectweb.asm.ClassReader.readField(ClassReader.java:883)
    at org.objectweb.asm.ClassReader.accept(ClassReader.java:694)
    at org.objectweb.asm.ClassReader.accept(ClassReader.java:500)
    at com.android.tools.build.jetifier.processor.transform.bytecode.ByteCodeTransformer.runTransform(ByteCodeTransformer.kt:39)
    at com.android.tools.build.jetifier.processor.Processor.visit(Processor.kt:443)
    at com.android.tools.build.jetifier.processor.archive.ArchiveFile.accept(ArchiveFile.kt:49)
    at com.android.tools.build.jetifier.processor.Processor.visit(Processor.kt:425)
    at com.android.tools.build.jetifier.processor.archive.Archive.accept(Archive.kt:76)
    at com.android.tools.build.jetifier.processor.Processor.transformLibrary(Processor.kt:421)
    at com.android.tools.build.jetifier.processor.Processor.transform(Processor.kt:247)
    at com.android.build.gradle.internal.dependency.JetifyTransform.transform(JetifyTransform.kt:113)
    ... 81 more

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
22 actionable tasks: 8 executed, 14 up-to-date

A: add this line in gradle.properties
android.useAndroidX=true
android.enableJetifier=true

also replace gradels with androidx
and for in design gradel add below gradel
//material design and design
    implementation 'com.google.android.material:material:1.1.0-alpha08'

also check in xml files add all widgets of androidx like below
<androidx.constraintlayout.widget.ConstraintLayout
...
>

</androidx.constraintlayout.widget.ConstraintLayout>

and also replace gradels from java files as below
import androidx.appcompat.app.AppCompatActivity;

A: Maybe your gradle-wrapper properties are too old. Change distributionUrl to the latest and stable gradle and rebuild the project.As well as change the classpath to the latest one.

A: Before you migrate to androidx, update your project to API 28 and corresponding gradle dependencies .
This is prerequisite asper developer guide:
Before you migrate, bring your app up to date. We recommend updating your project to use the final version of the support library: version 28.0.0. This is because AndroidX artifacts with version 1.0.0 are binary equivalent to the Support Library 28.0.0 artifacts.
After that do simple menu option as below to automatically migrating your project to androidx :
With Android Studio 3.2 and higher, you can migrate an existing project to AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.
Reference link:
https://developer.android.com/jetpack/androidx/migrate

A: Try clicking on the Gradle from the sidebar, then under :app, click on assembleDebug from the dropdown.
This should clarify your error.


text:
Q: React/Flux - How to scale stores Reading the Facebook/Flux website they give an example where by they have stores for 'Messages', 'Threads' and 'Unread Threads'. My understanding is that 'Threads' and 'Unread Threads' are the within the same domain. The point being made in their example is that you might want to track the state of the same data but from different contexts?
In my example I'm working with a list of 'leads' and depending on the component I am using (or mode of the component) and I need to view different subsets of the data. The REST call accepts a 'filter' option which I can easily supply through react props but this doesn't feel like a scalable approach:
<LeadsList filterBy="status:active" />

The dashboard I created only concerns itself with 'active' leads and uses the LeadsList component this way. LeadsList could however be used in other places without filtering etc. That was my goal here.
My overall question is: should I create a separate store for 'active leads' or filter through one central store?

A: There is no one right way to do it. You can process filters on the server or the client. You can use one store or many. For a large data set it might be best to process on the server. For a smaller data set processing on the client should be fine. How many stores you use depends on how you want to conceptually manage the data. The goal beyond functionality is clarity and maintainability.
For instance with reflux I can have one store for each logical page and use mixins to combine stores for each unique data set into the page store. That provides a separation of concerns for me while only needing one store be handled by the control component for that page.
Here is an example from https://github.com/calitek/ReactPatterns React.14/ReFluxSuperAgent.

import Reflux from 'reflux';

import Actions from '../actions/sa.Actions';
import AddonStore from './Addon.Store';
import MixinStoreObject from './Mixin.Store';

function _GotData(data) { this.data1 = data; BasicStore.trigger('data1'); }

let BasicStoreObject = {
 init() { this.listenTo(AddonStore, this.onAddonTrigger); },
 data1: {},
 listenables: Actions,
 mixins: [MixinStoreObject],
 onGotData1: _GotData,
 onAddonTrigger() { BasicStore.trigger('data2'); },
 getData1() { return this.data1; },
 getData2() { return AddonStore.data2; },
 getData3() { return this.data3; }
}
const BasicStore = Reflux.createStore(BasicStoreObject);
export default BasicStore;

import React from 'react';

import BasicStore from '../stores/Basic.Store';

let AppCtrlSty = {
 height: '100%',
 padding: '0 10px 0 0'
}

const getState = () => {
 return {
  Data1: BasicStore.getData1(),
  Data2: BasicStore.getData2(),
  Data3: BasicStore.getData3()
 };
};

class AppCtrlRender extends React.Component {
  render() {
  let data1 = JSON.stringify(this.state.Data1, null, 2);
  let data2 = JSON.stringify(this.state.Data2, null, 2);
  let data3 = JSON.stringify(this.state.Data3, null, 2);
  return (

    React 1.4 ReFlux with SuperAgent

    Data1: {data1}

    Data2: {data2}

    Data3: {data3}

  );
 }
}

export default class AppCtrl extends AppCtrlRender {
 constructor() {
  super();
  this.state = getState();
 }

 componentDidMount() { this.unsubscribe = BasicStore.listen(this.storeDidChange.bind(this)); }
 componentWillUnmount() { this.unsubscribe(); }
 storeDidChange(id) {
  switch (id) {
   case 'data1': this.setState({Data1: BasicStore.getData1()}); break;
   case 'data2': this.setState({Data2: BasicStore.getData2()}); break;
   case 'data3': this.setState({Data3: BasicStore.getData3()}); break;
   default: this.setState(getState());
  }
 }
}


text:
Q: Unable to create table from within package I am attempting to create a package in which I drop and create a table using a CTAS query.  This table needs to be refreshed frequently and columns are add/removed all the time from the underlying data.  Since the structure of the table is constantly changing, it would be quite cumbersome to update merge/update queries each refresh to account for the new/missing columns.  Currently, I have external scripts that do simple drops and creates but I need to centralize this in the database; therefore I am attempting to create a package to do it; however, I am having trouble with privileges.
As proof of concept, the following code works when ran as an anonymous block:
create table my_test_table as select * from dual; --create test table

declare
v_count int;
begin
   select count(*) into v_count from all_tab_columns where table_name = upper('my_test_table');
   if v_count >= 1 then
      execute immediate 'drop table my_test_table';
   end if;

execute immediate q'[
create table my_test_table as
select * from dual
]';
end;

select * from my_test_table; -- shows expected results

But when creating a package to do the same thing;
CREATE OR REPLACE PACKAGE test_pkg AS

  PROCEDURE test_procedure;

END test_pkg;

CREATE OR REPLACE package body test_pkg as

procedure test_procedure
is
    v_count int;

begin
        select count(*) into v_count from all_tab_columns where table_name = upper('my_test_table');
        if v_count >= 1 then
            execute immediate 'drop table my_test_table';
        end if;

        execute immediate q'[
        create table my_test_table as
        select * from dual
        ]';

end test_procedure;

end test_pkg;
/

and testing with the following code:
create table my_test_table as select * from dual; --make sure table exists

execute TEST_PKG.TEST_PROCEDURE; --results in errors

select * from my_test_table; --table does not exist; therefore, DROP statement works but not CREATE

I get the following errors (in regards to executing TEST_PKG.TEST_PROCEDURE):
ORA-01031: insufficient privileges
ORA-06512: at test_pkg, line 15

When testing for the existence of the test table after executing the package, I can see that it no longer exists.  This means the DROP statement is working but the CREATE TABLE statement is resulting in the insufficient privileges error.
Any and all insight into what privileges I need to create the table from within the package would be immensely helpful.

A: The package you've created, in the absence of a AUTHID CURRENT_USER clause is a definer's rights package.  It can only do things that are allowed by privileges granted directly to the definer of the package.  "Directly" is the key point here -- privileges granted through enabled roles are not honored during the package execution.
You've probably got the RESOURCE or similar role enabled for your user, which would explain why you can create the table during testing but not via your package procedure.
Try granting the CREATE TABLE and UNLIMITED TABLESPACE system privileges directly to your user and then recreate the package.  (If that works, replace UNLIMITED TABLESPACE with quotas on the appropriate tablespace(s) in your database).

A: Create a table in procedure is only alowed when you have "Create table" or "create any table" privilege but granted directly to user (granted by role is not working).
https://docs.oracle.com/cd/B19306_01/network.102/b14266/authoriz.htm#i1008334

PL/SQL Blocks and Roles
The use of roles in a PL/SQL block depends on whether it is an
anonymous block or a named block (stored procedure, function, or
trigger), and whether it executes with definer's rights or invoker's
rights.
Named Blocks with Definer's Rights
All roles are disabled in any named PL/SQL block (stored procedure,
function, or trigger) that executes with definer's rights. Roles are
not used for privilege checking and you cannot set roles within a
definer's rights procedure.

To check system privileges granted directly to your user (not by role/roles), you can run this query from your user:
SELECT * FROM USER_SYS_PRIVS;


text:
Q: pictures or camera browser I'm trying to do the next:
I have an ImageView and i want it to appears a pictures browser or camera when user touchs it to let him select or take a picture.
I've found that:
private void openPictureBrowser()
{
   Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
   intent.setType("image/*");
   intent.putExtra(Intent.EXTRA_TITLE,"A Custom Title"); //optional
   intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); //optional
   try {
      startActivityForResult(intent, 1);
   } catch (Exception e) {
      e.printStackTrace();
   }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
   switch (requestCode) {
      case 1: {
         if (resultCode == RESULT_OK && data != null && data.getData() != null) {
            String filePath = data.getData().getPath(); //WARNING: this is NOT your real path (in my case, value is set to "/external/images/media/4"
         }
      }
   }
}

What can i do in openPictureBrowser if I want to add the camera?
And what should I do in onActivityResult to set filePath as ImageView background?
Can anybody give me a hint??
Thanxs!

A: public class Set_image extends Activity implements OnClickListener
{
    Button btn_capture_image,btn_share_from_gallery;
    ImageView iv_set_image;
    private static final int REQUEST_CODE = 1;
     private static final int CAMERA_REQUEST = 1888;
    String filePath="";
    Bitmap Main_bitmap;

 @Override
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_image);

        btn_capture_image =(Button) findViewById(R.id.button_capture_image);
        btn_share_from_gallery =(Button) findViewById(R.id.button_share_from_gallery);
        iv_set_image = (ImageView) findViewById(R.id.imageView_set_iamge);

        btn_capture_image.setOnClickListener(this);
        btn_share_from_gallery.setOnClickListener(this);

    }

public void onClick(View v)
{

        if (v == btn_capture_image)
        {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }

        if (v == btn_share_from_gallery)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, REQUEST_CODE);
        }
}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {

        if (requestCode == CAMERA_REQUEST)
        {
            Main_bitmap = (Bitmap) data.getExtras().get("data");
            iv_set_image.setImageBitmap(Main_bitmap);
        }

        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)

            try
             {

                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

              if (cursor.moveToFirst())
              {
                     int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                     filePath = cursor.getString(columnIndex);
                     BitmapFactory.Options options4 = new BitmapFactory.Options();
                     options4.inSampleSize = 1;
                     Main_bitmap = BitmapFactory.decodeFile(filePath, options4);                         iv_set_image.setImageBitmap(Main_bitmap);

               }
                    cursor.close();
             }
             catch (Exception e)
             {
                    e.printStackTrace();
             }
            super.onActivityResult(requestCode, resultCode, data);
}

A: use the following code :
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class LoadImage extends Activity
{
    Activity activity=null;
    Context context=null;

    Button header_left_btn=null;
    Button header_right_btn=null;
    TextView header_text=null;
    TableLayout image_table=null;

    ArrayList<String> image_list=new ArrayList<String>();
    ArrayList<Drawable> image_drawable=new ArrayList<Drawable>();
    String path="";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.header);

        activity=LoadImage.this;
        context=LoadImage.this;

        header_left_btn=(Button)findViewById(R.id.header_left_btn);
        header_right_btn=(Button)findViewById(R.id.header_right_btn);
        header_text=(TextView)findViewById(R.id.header_text);
        image_table=(TableLayout)findViewById(R.id.image_table);

        header_text.setText("Image Table");
        header_left_btn.setText("Select");
        header_right_btn.setText("Clear");
        registerForContextMenu(header_left_btn);

        header_left_btn.setOnClickListener(new OnClickListener(){

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

        header_right_btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                image_list.clear();
                image_drawable.clear();
                deletePhotos();
                updateImageTable();
            }
        });
    }

    public void deletePhotos()
    {
        String folder=Environment.getExternalStorageDirectory() +"/LoadImg";
        File f=new File(folder);
        if(f.isDirectory())
        {
            File[] files=f.listFiles();
            Log.v("Load Image", "Total Files To Delete=====>>>>>"+files.length);
            for(int i=0;i<files.length;i++)
            {
                String fpath=folder+File.separator+files[i].getName().toString().trim();
                System.out.println("File Full Path======>>>"+fpath);
                File nf=new File(fpath);
                if(nf.exists())
                {
                    nf.delete();
                }
            }
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {

        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Post Image");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.camer_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item)
    {
      switch (item.getItemId())
      {
          case R.id.take_photo:
              //Toast.makeText(context, "Selected Take Photo", Toast.LENGTH_SHORT).show();
              takePhoto();
              break;

          case R.id.choose_gallery:
              //Toast.makeText(context, "Selected Gallery", Toast.LENGTH_SHORT).show();
              Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
              photoPickerIntent.setType("image/*");
              startActivityForResult(photoPickerIntent, 1);

              break;

          case R.id.share_cancel:
              closeContextMenu();
              break;
          default:
            return super.onContextItemSelected(item);
      }
      return true;
    }

    public void takePhoto()
    {
         Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
         File folder = new File(Environment.getExternalStorageDirectory() + "/LoadImg");

         if(!folder.exists())
         {
             folder.mkdir();
         }
         final Calendar c = Calendar.getInstance();
         String new_Date= c.get(Calendar.DAY_OF_MONTH)+"-"+((c.get(Calendar.MONTH))+1)   +"-"+c.get(Calendar.YEAR) +" " + c.get(Calendar.HOUR) + "-" + c.get(Calendar.MINUTE)+ "-"+ c.get(Calendar.SECOND);
         path=String.format(Environment.getExternalStorageDirectory() +"/LoadImg/%s.png","LoadImg("+new_Date+")");
         File photo = new File(path);
         intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));
         startActivityForResult(intent, 2);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==1)
        {
            Uri photoUri = data.getData();
            if (photoUri != null)
            {
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();
                Log.v("Load Image", "Gallery File Path=====>>>"+filePath);
                image_list.add(filePath);
                Log.v("Load Image", "Image List Size=====>>>"+image_list.size());

                //updateImageTable();
                new GetImages().execute();
            }
        }

        if(requestCode==2)
        {
            Log.v("Load Image", "Camera File Path=====>>>"+path);
            image_list.add(path);
             Log.v("Load Image", "Image List Size=====>>>"+image_list.size());
            //updateImageTable();
             new GetImages().execute();
        }
    }

    public void updateImageTable()
    {
        image_table.removeAllViews();

        if(image_drawable.size() > 0)
        {
            for(int i=0; i<image_drawable.size(); i++)
            {
                TableRow tableRow=new TableRow(this);
                tableRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
                tableRow.setGravity(Gravity.CENTER_HORIZONTAL);
                tableRow.setPadding(5, 5, 5, 5);
                for(int j=0; j<1; j++)
                {
                    ImageView image=new ImageView(this);
                    image.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

                    /*Bitmap bitmap = BitmapFactory.decodeFile(image_list.get(i).toString().trim());
                    bitmap = Bitmap.createScaledBitmap(bitmap,500, 500, true);
                    Drawable d=loadImagefromurl(bitmap);*/
                    image.setBackgroundDrawable(image_drawable.get(i));

                    tableRow.addView(image, 200, 200);
                }
                image_table.addView(tableRow);
            }
        }
    }

    public Drawable loadImagefromurl(Bitmap icon)
    {
        Drawable d=new BitmapDrawable(icon);
        return d;
    }

    public class GetImages extends AsyncTask<Void, Void, Void>
    {
        public ProgressDialog progDialog=null;

        protected void onPreExecute()
        {
            progDialog=ProgressDialog.show(context, "", "Loading...",true);
        }
        @Override
        protected Void doInBackground(Void... params)
        {
            image_drawable.clear();
            for(int i=0; i<image_list.size(); i++)
            {
                Bitmap bitmap = BitmapFactory.decodeFile(image_list.get(i).toString().trim());
                bitmap = Bitmap.createScaledBitmap(bitmap,500, 500, true);
                Drawable d=loadImagefromurl(bitmap);

                image_drawable.add(d);
            }
            return null;
        }

        protected void onPostExecute(Void result)
        {
            if(progDialog.isShowing())
            {
                progDialog.dismiss();
            }
            updateImageTable();
        }
    }
}

i have got this code from following link :
http://tjkannan.blogspot.in/2012/01/load-image-from-camera-or-gallery.html
Hope this will help you .


text:
Q: Python 3 allows mixing spaces and tabs? I know there are many questions on tabs vs. spaces, but it appears that, contrary to what PEP 0008 says about Python 3, mixing tabs and spaces is not always illegal. Specifically, mixing tabs and spaces in the same block is illegal, but blocks with spaces and blocks with tabs are allowed in the same file.
For example, this throws a TabError on Python 3.4:
for x in range(10):
    print(x)  # Spaces
    print(x)  # Tab

But this runs fine:
for x in range(10):
    print(x)  # Spaces

for y in range(5):
    print(y)  # Tab

Is this by design?
Edit: The question is not whether tabs are better than spaces. The question is whether Python's allowing tabs and spaces in the same file is by design.

A: The test for this is pretty simple (Lib/tests/test_exceptions.py):

    self.raise_catch(TabError, "TabError")
    try: compile("try:\n\t1/0\n    \t1/0\nfinally:\n pass\n",
                 '<string>', 'exec')
    except TabError: pass
    else: self.fail("TabError not raised")

Looking at the code where this error is actually thrown (Parser/tokenizer.c, tok_get()) it looks like this merely compares the indentation kind to what the previous line used, and not what is used throughout the file.
The documentation says (Doc/reference/lexical_analysis.rst, emphasis mine)

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

It's okay to mix tabs and spaces if the "blocks" are completely "separated" by going back to indentation level 0; as there can be no confusion about the program's logic due to tab width settings. The problem with mixing tabs and spaces in Python is that Python assumes that a tab is eight spaces wide, but that the programmer's editor may use something else. For example, code like this:
def my_fun(i):
    if i == 6:
        foo()
------->bar()  # Tab

Will be seen as this with a  tabstop of 4:
def my_fun(i):
    if i == 6:
        foo()
    bar()

Which is obviously not what the program does!
But in cases like:
def my_fun(i):
    if i == 6:
        foo()
        bar()

def my_fun2(i):
--->if i == 7:
--->--->foo()
--->--->bar()

It's okay from a "logic" point of view as no matter how I view tabs, it's always clear what the logic is. It's of course still a bad idea to mix tabs and spaces in a single file, but that's merely a stylistic error, and not a logic error ;-)
So to answer the question: judging from that one line in the documentation, I
would say that this is by design. I can't find a PEP for this, though, and this
case isn't tested. I would be not rely on it that all Python versions in the
future behave the same!

A: Python tries to segment each little block of code so that when you copy and paste, it still works, and you aren't forced to make everything perfect. One of the many beauties of python.
PEP 8 is just a convention for the most readable code, and I recommend that you do follow it, but you don't have to
If you want to look for what PEP 8 encompasses there are several editors that will inspect your code for violations that are legal in python, but not nice. I use PyCharm. PyCharm doesn't like when you use spaces and tabs in the same file and it will get snarky with the squiggle under-linings.


text:
Q: LWJGL - Can the Assimp bindings be used without the core JAR I wanted to update to LWJGL 3 from 2, but searches online shows it doesn't really work (properly? at all?) with Java GUI toolkits.
The code that I am working on has the GL context in an AWT canvas among many other GUI components, and it's not really realistic now to change to a GL-based GUI library.
But at the end of the day, updating GL is not quite important to me, rather what I really want is the Assimp bindings, assuming they are more or less complete.
I thought of just using the Assimp module itself with the existing code, however it seems to require the core LWJGL 3 JAR, which then causes runtime clashes with the LWJGL 2 one.
Is there a way to actually use LWJGL 3 with other GUI in modern times?
Otherwise, can I somehow use the Assimp bindings without using LWJGL itself, without runtime issues?

A: You should be able to use the Assimp-port for Java, which you can find here JAssimp. You can build them from the current master or there shall be precompiled packages ready to use.


text:
Q: Numbering and titling graphs in R-markdown In r-markdown pdf report I need to number and caption all my graphs and nothing I could find on the internet helped. So each picture or graph displayed needs to be something like
"Picture 1: qq-plot of the variable "age"."
The problem is also with two graphs in a single code chunk. To be precise, they aren't in a single merged graph, but two separate graphs with each their own cooedinate system.


text:
Q: Ordering a Rails DataTable column by another value I am building a helpdesk application.  I have a model called TicketDetail, with a table which uses datatables to get its data via JSON.  This is in order to periodically recalculate the time a ticket has been open.  The time taken is formatted by a simple helper so it's in the format "dd:hh:mm", but it should be sorted by the time (stored as a decimal) multiplied by a weighting.  Here's the datatables definition
var table = $('#ticket_details').DataTable({
 order: [[ 8, "desc" ], [ 9, "desc" ], [ 2, "asc" ]],
 stateSave: true,
 deferRender: true,
 ajax: $('#ticket_details').data('source'),
 "columns": [
 { "data": "reference_number" },
 { "data": "location" },
 { "data": "title" },
 { "data": "parent", className: "hidden-md hidden-sm hidden-xs" },
 { "data": { _:"time_display.time", sort: "time_display.decimal_time"}},
 { "data": "created_by", className: "hidden-md hidden-sm hidden-xs" }
 ]
 } );

setInterval( function () {
table.ajax.reload( null, false ); }, 60000 );

Here's a simplified sample record, where the ticket has been open 3 days and 6 hours, with a weighting of x2 (i.e. 3.25 * 2 = 6.5:
{
 data: [
  {
   id: 140,
   parent: null,
   title: "[",
   location: "Bond St",
   ticket_sla: "16 Hours",
   reference_number: "1606210001",
   ticket_sla_weighting: 2,
   time_display: {
   time: "03:06:00",
   decimal_time: 6.5
   }
 ]
}

The problem is that the datatable sorts correctly if I display the decimal_time, but as soon as I put the formatted time in the  class, it sorts simply by the number of days, immediately to the left of the colon. (So 03:06:00 and 03:18:00 would not get sorted properly).

A: For Date/Time sorting in DataTable You need to use it's Sorting plug-ins
For Example,
You need to include this js files :
//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js
//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js

and then, In your jQuery use this as
$.fn.dataTable.moment( 'HH:mm MMM D, YY' ); // Pass your date time format as param

For Deeper reference please check :
Sorting Plugins
Ultimate date / time sorting plugin


text:
Q: Count unique words in a string using dplyr (R) Let's say I have a string as follows:
string <- "the home home on the range the friend"

All I want to do is determine which words in the string appear at least 2 times.
The psuedocode here is:

*

*Count how many times each word appears

*Return list of words that have more than two appearances in the string

Final result should be a list featuring both the and home, in that order.
I am hoping to do this using the tidyverse, ideally with stringr or dplyr. Was attempting to use tidytext as well but have been struggling.

A: We can split the string by space, get the table and subset based on frequency
out <- table(strsplit(string, "\\s+")[[1]])
out[out >=2]

home  the
   2    3

A: library(tidyverse)
data.frame(string) %>%
  separate_rows(string) %>%
  count(string, sort = TRUE) %>%
  filter(n >= 2)

Result
# A tibble: 2 × 2
  string     n
  <chr>  <int>
1 the        3
2 home       2

A: Here is another option using tidytext and tidyverse, where we first separate each word (unnest_tokens), then we can count each word and sort by frequency. Then, we keep only words that have more than 1 observation, then use tibble::deframe to return a named vector.
library(tidytext)
library(tidyverse)

tibble(string) %>%
  unnest_tokens(word, string) %>%
  count(word, sort = TRUE) %>%
  filter(n >= 2) %>%
  deframe()

Output
 the home
   3    2

Or if you want to leave as a dataframe, then  you can just ignore the last step with deframe.

A: Here's an approach using quanteda that prints "the" before "home" as requested in the original post.
library(quanteda)
aString <- "the home home on the range the friend"
aDfm<- dfm(tokens(aString))
# extract the features where the count > 1
aDfm@Dimnames$features[aDfm@x > 1]

...and the output:
> aDfm@Dimnames$features[aDfm@x > 1]
[1] "the"  "home"

A: Yet another possible solution:
library(tidyverse)

data.frame(x = str_split(string, "\\s+", simplify = T) %>% t) %>%
  add_count(x) %>%
  filter(n >= 2) %>%
  distinct %>%
  pull(x)

#> [1] "the"  "home"