Paste an image from clipboard to a cell in Excel

Question: I want to paste an image from clipboard to an excel cell using vba.
i could find a code like this :
If My.Computer.Clipboard.ContainsImage() Then
Dim grabpicture = My.Computer.Clipboard.GetImage()
PictureBox1.Image = grabpicture
End If

but here grabpicture variable is an object. how to update a cell from an image object.
like this,
Sheet1.Range("D11").Value = grabpicture

Answer: To move image from one sheet to another through clipboard standard methods Copy-Paste are used. For Paste method you must define the range where the image is to be pasted, for example (you may skip Destination parameter):
Worksheets("Sheet1").Range("C1:C5").Copy
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("D1:D5")

A picture is inserted in the specified region, but some peculiarities exist:

for Office 2003 pasted image is not binded exactly to upper-left
corner of the range; if you define an alone cell the image may get
the position more left and lower, even may get the adjacent cell; so
you must execute realign procedure using Top and Left  properties
(see below);
for Office 2003 pasted picture IS NOR selected, so special procedure
must be done to identify the image in Shapes collection;
for Office 2007 image is selected and binded to upper-left corner of
the specified range, so Selection property can be used to change the
image property in the collection (Name for example);
pasted image index in Shapes collection becomes the upmost BUT AMONG
THE PICTURES set (Type=msoPicture); in Office 2003 Shapes are
groupped so that first is the block of controls (Lstbox, Combobox,
etc.) and images block is latter, so pasted image index is in fact
the last in all collection; for Office 2007 images block turns out to
be BEFORE the block of controls, therefore you should search the
index of the last pasted image between the elements of IMAGE BLOCK
(see example below);
to deselect pasted image (not to delete it by accident) you should
move focus to any cell/ for example as Range("A1").Select.

Hence, to write a universal program that works correctly either in Office 2003, or Office 2007 environment you should:

first, use special procedure to find out the pasted image (the reference, or index, of it in Shapes collection);
second, make image alignment to upper-left corner of the range where the image is pasted;
third, move focus to another cell.

Below is the Function that defines the index of last pasted image in the Shapes collection:
Function GetIndexPastedPicture() As Integer
' Pasted picture has the upmost index among the PICTURE block
' But it is not necessarily the last inde[ in whole collection
' set reference to target sheet with pasted image
Set ThisDBSheet = Workbooks("BookName.xls").Worksheets("SheetName")
Dim sh As Shape, picIdx As Integer
picIdx = 0 ' initial value of index in Shapes collection, starts from 1
For Each sh In ThisDBSheet.Shapes
    If sh.Type = msoPicture Then ' image found
        picIdx = sh.ZOrderPosition ' image index
    End If
Next
' after For loop, picIdx - is the last index in PICTURE block
GetIndexPastedPicture = picIdx
End Function

Then (assuming that Clipboard already has the proper image) the procedure  to paste image looks like following:
Sub InsPicFromClipbrd(sInsCell As String, sPicName As String)
' Image is pasted to cell with name sInsCell,
' it is aligned to upper-left corner of the cell,
' pasted image gets name sPicName in Shapes collection
' set reference to target sheet with pasted image
Set ThisDBSheet = Workbooks("BookName.xls").Worksheets("SheetName")
ThisDBSheet.Paste Destination:=Range(sInsCell) ' paste image fom clipboard
c1 = GetIndexPastedPicture() ' get index of pasted image (see above)
With ThisDBSheet.Shapes.Item(c1) ' correct the properties of the pasted image
    .Top = Range(sInsCell).Top ' top alignment
    .Left = Range(sInsCell).Left ' left alignment
    .Name = sPicName ' assign new name
End With
Range("I18").Activate ' move focus from image
End Sub 'InsPicFromClipbrd

Answer: Pictures are not inserted into cells. Pictures are inserted onto the sheet and then may be aligned so that the top left corner visually matches top left corner of some cell.
To insert a picture from the clipboard, you use Sheet1.Paste().
Answer: Good evening...
This bit of code will copy whatever image is in your windows PC clipboard and paste it to a worksheet tab "Sheet1" and then copy it to a new chart.  The chart will then be exported as a jpg file to a network folder with name given in the code.
Sub Count_Shapes_click()
    ' NOTE: Count_Shapes is a command button
' NOTE: MyChart is the new chart where the image will eventually be copied to
'       in order to then be exported as a jpg file
Dim MyChart As Chart

' NOTE: The workbook sheet "Sheet1" will be made the active sheet
Sheet1.Activate

' NOTE: This will past whatever is currently in the clipboard to the active sheet
'       So, make sure that your image is what was most recently copied
'
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("A1:zz10")

' NOTE: This is creating the new Chart
    Set MyChart = Charts.Add

' NOTE: This is name the new chart
MyChart.Name = "HELLO"

' NOTE: This is moving the chart to the sheet where the picture is
Set MyChart = MyChart.Location(Where:=xlLocationAsObject, Name:="Sheet1")

' NOTE: This is making the width and height of the MyChart equal to whatever image you copied to the clipboard
MyChart.ChartArea.Width = Sheet1.Shapes(2).Width
MyChart.ChartArea.Height = Sheet1.Shapes(2).Height

' NOTE: This is removing the shape container boarder
MyChart.Parent.Border.LineStyle = 0

' NOTE: This is copying the image that was pasted to the sheet "Sheet1"
Sheet1.Shapes(2).Copy

' NOTE: This is selecting or making active the ChartArea of MyChart
MyChart.ChartArea.Select

' NOTE: This is pasting the image that was just copied via VBA of EXCEL into the MyChart ChartArea
MyChart.Paste

' NOTE: This is exporting the MyChart to a jpg file.
'       Filename:="location of folder\name of the file.XXX"
'       FilterName:="jpg" read about this at - > https://learn.microsoft.com/en-us/office/vba/api/Excel.Chart.Export
MyChart.Export Filename:="J:\TEMP\LIBERTY\Images\HI Me.jpg", FilterName:="jpg"

' NOTE: Make cell (Row 1, Column A) the active cell
Sheet1.Cells(1, 1).Activate

' NOTE: Delete the Chart you created earlier
Sheet1.ChartObjects(Sheet1.ChartObjects.Count).Delete

' NOTE: Delete the (hopefully) only 1 shape (image pasted ealier) on the sheet "Sheet1"
Sheet1.Shapes(1).Delete

End Sub
Comment: Using the chart object to save the shape is a good idea. To make the chart  fill transparent, you can add 'MyChart.ChartArea.Format.Fill.Visible = msoFalse.'


Starcraft II Public Test?

Question: I have just realized there is a new menu item called "Starcraft II Public Test" which I think has been installed with one of the latest updates.
What is this?
I'm not very comfortable with launching executables whose function I don't know.
Answer: It launches a beta of the upcoming release of patch 1.2
Info: http://us.battle.net/sc2/en/blog/1334972
Comment: Did every user get this? It says I need a full US account, but I have an EU account. Downloaded game version in English though.  When I run it, it says that some server is not available.
Comment: @Bora From the article: To participate in the public test you must have a full North America product license.

Starcraft II Public Test?


Firestore: How to set DocumentListenOptions in JavaScript?

Question: While using Firebase-Firestore database, I need to set some configuration parameters accesible via DocumentListenOptions using the Web javascript sdk.
I've found many examples of this in java and other languages, but it seems there is no documentation for JavaScript.
Am I missing something?
Thanks!
Answer: The DocumentListenOptions you're pointing to is a part of the Android API.
In the web API there's no special type for this: just pass { includeMetadataChanges: true } as options to the onSnapshot method, as described here:
https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#onSnapshot
Cheers,
-Gil


Allowing users to select all items except few

Question: I have a list of country names (eg below)

I want the user to be able to either select a few countries or, select all countries except a few.
Now, this can be done using a select all button by selecting all items and then unchecking the ones that are not required. However, this creates a long query to be sent to the backend.
For example, if I want to select all countries except Argentina, the query would look something as follows:
select(Australia, Austria, Belgium...)

I want to transform this query to just
except(Argentina)

How do I display/convey the user that he/she can either select countries that he wants details about or countries that he doesn't want details about?
Comment: one way can be like this answer, https://ux.stackexchange.com/a/54782/9749
Comment: The 'long query' problem of Select All can be solved like this: Have an internal boolean `collectionModeExcept`; once the user hits Select All, internally change the `collectionModeExcept` to `true`, and start building a list with all _unselected items_ as the user unselects a checkbox. This way, you won't need to send the full list of checkbox selections.
Answer: First, you should try to avoid deciding how something should behave on-screen based on the technical constraint of what you send to the server. You can use JavaScript to reflect some modified version of the selection as hidden inputs for submission without it affecting the UI.
Having said that, I think this is a good candidate for the list builder UI pattern (also called a dual list), which would allow you to add or remove individual items to the selection. You could add buttons for "Add all" or "Remove all" too. I suspect that would be a more natural interaction:

Image credit: Microsoft Windows Design Guidelines for List Boxes
Comment: Nice. I thought about this one too. Unfortunately it takes up a lot of space - and it's hardly suitable for mobile devices. But it's a great solution.
Comment: Good point about the form factor affecting the best solution here. I admit I would probably use a checkable list on mobile, with an option to select all items (and then deselect unwanted options). I would definitely deal with the technical constraint of posting the data to the server efficiently as a code problem rather than a UI problem though, and my gut says "invert selection" is an unnecessary complication.
Answer: From the user perspective the most easy way is an "inverted" selector.
E.g. I know software where I check two boxes and than invert the selection before I press the "search" button.
But this requires a certain level of instruction and abstraction by the user.
One possible solution to skip the "invert" step would be to provide two buttons:

Search in all marked countries
Search everywhere exept in marked countries

I think this is the most convenient one.


How to continuously delete old fluentd logs from elasticsearch?

Question: A Fluentd log collector writes to Elasticsearch which eventually fills up the disk. How to limit them to a month, for example?
Part of the Fluentd config (using Kubernetes):
<code><match kubernetes.**>
  @type elasticsearch_dynamic
  host elasticsearch.default.svc.cluster.local
  port 9200
  include_tag_key true
  logstash_format true
  logstash_prefix kubernetes-${record['kubernetes']['pod_name']}
</match>
</code>
"Curator" for Elasticsearch, can delete "indexes", but I don't know what indexes Fluentd creates, when it stops using them and what does it mean to delete an index when there are still useful new logs in it?
Comment: I'll edit the answer with an example to fit this pattern
Comment: See answer below
Comment: @untergeek, I can't apply the answer to the task in hand.
Comment: Show me an example of the indices that are created.  You can use Elasticsearch's `_cat` API to show that: curl localhost:9200/_cat/indices (replace localhost with elasticsearch.default.svc.cluster.local, or whatever dns or ip you use)
Comment: Like this: `kubernetes-elasticsearch-2173889150-fj2gh-2017.11.30`. I've already implemented a cron job for deleting the old ones. It does roughly what's needed.
Answer: Curator will delete indices for you, regardless of whether Logstash, fluentd, or some other app made them.  This example will work with the index pattern you provided in the above comments.
<code>---
actions:
  1:
    action: delete_indices
    description: >-
      Delete indices older than 30 days (based on index name), for kubernetes-elasticsearch-
      prefixed indices. Ignore the error if the filter does not result in an
      actionable list of indices (ignore_empty_list) and exit cleanly.
    options:
      ignore_empty_list: true
      disable_action: true
    filters:
      - filtertype: pattern
        kind: prefix
        value: kubernetes-elasticsearch-
      - filtertype: age
        source: name
        direction: older
        timestring: '%Y.%m.%d'
        unit: days
        unit_count: 30
</code>


bootstrapValidator ajax submit error "404 Page Not Found"

Question:

<form id="myform" method="post"></form>
<button type="submit">ok</button>

When I press submit button,then it goes "404 Page Not Found" error; But I don't know what's wrong with the code?
I have no problem on validate, but on ajax submit, thanks!
Comment: how console.log looks?
Comment: Does the file at `./ajax/ajaxSubmit.php` exist? Can you reach it directly in the browser?
Comment: The file at ./ajax/ajaxSubmit.php exist and reachable in browser
Comment: There shows nothing in Chrome javascript console
Answer: Finally,it works! There is an answer.
But I still have no idea why it went wrong :(

<form id="myform" method="post"></form>
<button type="submit">ok</button>


call "shouldOverrideUrlLoading" method on webview.goBack()

Question: I'm loading all my pages inside shouldOverrideUrlLoading method on webview (mainly to track the current page url and do some modifications).
My problem is that the back button ( eg: webview.goback() method ) bypasses the above function.
Is there any way i can explicitly call both the goback() and shouldOverrideUrlLoading() methods.
public boolean shouldOverrideUrlLoading(WebView view, String url){
//get current url and do some modifications to html}

public boolean onKeyDown(int keyCode, KeyEvent event) {
     if ((keyCode == KeyEvent.KEYCODE_BACK) && web1.canGoBack()) {
         webview.goBack();
         return true;
      }
      return super.onKeyDown(keyCode, event);
}

Answer: Looking at your code seems like once the shouldOverrideUrlLoading method is called based on some logic for a specific URL Action you need the Webview go back method. I would suggest you to use the following method inside the activity:
@Override
public void onBackPressed() {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && web1.canGoBack()) {
        webview.goBack();
    } else {
        super.onBackPressed();
    }
}

which does exactly the same as onKeypressed. (Used onBackPressed instead of onKeypressed but write this code inside the Activity class but not inside the custom WebViewClient.
Call the onBackPressed() inside your shouldOverrideUrlLoading. Try this, should work.


Only select if the main entry is certified

Question: Please consider the following schema:
CREATE TABLE users
(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL
);

CREATE TABLE mashup_x
(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    date VARCHAR(255),
    warranty VARCHAR(30) NOT NULL,
    userid VARCHAR(30) NOT NULL,
    mainthread VARCHAR(50),
    certified VARCHAR(50)
);

INSERT INTO users VALUES (1, "John");
INSERT INTO users VALUES (2, "Adam");

INSERT INTO mashup_x
VALUES (1, 1540804136000, 1, 2, 1, 0); /*this is a main entry with sub entries below*/

INSERT INTO mashup_x
VALUES (2, 1540804256000, 1, 1, 1, 1);

INSERT INTO mashup_x
VALUES (3, 1540804256000, 1, 1, 1, 1);

INSERT INTO mashup_x
VALUES (4, 1540804136000, 1, 2, 4, 1); /*this is a main entry with NO sub entry below*/

Attempted query:
select
    mashup_x.id as ok, users.name, mashup_x.certified, mashup_x.mainthread
from
    mashup_x, users
where
    users.id = mashup_x.userid
    and certified = 1
    and mashup_x.id != mainthread
    and (select certified from mashup_x
         where id = mainthread and id = mashup_x.id and certified = 1) = 1
order by
    mashup_x.date desc

http://sqlfiddle.com/#!9/0f3537/1
If main entry is not certified, sub entries should NOT be shown, how do you know they are sub entries? You see that in mainthread column of the subentries which is assigned with the id of the mainentry.
Currently it picks any main entry even if I selected only the one with which has the id same as sub entries mainthread
And as you can see main entry 1 is NOT certified but main entry 4 (which has no sub entries) is , and it still shows the sub entries of main entry 1. What am I doing wrong?
Comment: Please provide a relevant and minimal sample data showcasing your requirements, and expected output. Refer this link on how to frame a good SQL question: [Why should I provide an MCVE for what seems to me to be a very simple SQL query?](https://meta.stackoverflow.com/q/333952/2469308)
Comment: Thanks for the tip, I will do it now
Comment: I added it now, I hope it is clearer and more simple now
Comment: [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was replaced with the *proper* ANSI `JOIN` syntax in the ANSI-**92** SQL Standard (**more than 25 years** ago) and its use is discouraged
Answer: If you want to have cetified subEntries of certified mainEntries as the result, you can try below code:

select mashup_x.id as ok, users.name, mashup_x.certified, mashup_x.mainthread
from mashup_x left join users on mashup_x.userid = users.id
where mashup_x.mainthread in (
    select mashup_x.id
    from mashup_x
    where mashup_x.certified = 1 and mashup_x.id = mainthread
)
and certified = "1" and mashup_x.id != mainthread
order by mashup_x.date desc

as you can see, I try to filter main entries by a subquery in Where clause. additionally, please consider that it is better to use standard script for join.
Comment: I just checked it on SQLFiddle and it works, both my answer and yours work but since you posted before me I will give you the best answer :) Thanks for the help
Comment: Actuall yours is even better and onpoint of what I wanted, I learned some new things from it as well, this should definitely be used and you did it as simply and near my code as possible, big ups.
Answer: I found it, I had to use left joins so this is the solution
    SELECT
      *
   FROM
      mashup_x ta
         LEFT JOIN mashup_x Lta
            ON ta.mainthread = Lta.id
         LEFT JOIN users xa
            ON xa.id = ta.userid

   WHERE
           ta.certified = 1 and ta.id != ta.mainthread AND Lta.id = Lta.mainthread
        AND Lta.certified = 1

Comment: Please check my answer too. I tried to use `join` once and I think it has better performance when you have large amount of data.
Comment: I will check it once SQLfiddle works again, it loads forever for me.


.htaccess & .htpasswd equals 500 error

Question: I+m trying make a folder on my server protected by .htaccess & .htpasswd. When I try to enter the folder in question I'm asked for a password like I want. But then when the page is loaded I get a 500 error, which also happens on all pages on my site now. With ErrorDocument 500 it says:
This webpage has a redirect loop
The webpage at http://example.com/test/folder/ has resulted in too many redirects.
...
This is what my .htaccess file looks like:
ErrorDocument 500 http://184.108.40.206/test/appload/
AuthName "Restricted Area"
AuthType Basic
AuthUserFile /test/folder/admin/.htpasswd
require valid-user

Can anyone see a problem or something that I've missed to make it work?
EDIT: I had the rewrite rule to prevent the 301 error I get for to many redirects. (Found in another solution but it didn't help.) So I just want to get rid of the 500 error.
Comment: what happens if you remove the line : `ErrorDocument 500 http://220.127.116.11/test/appload/`
Comment: Then it gives me only the 500 error and doesn't mention to many redirects! :(
Comment: ok, what else is in your htaccess file ?
Comment: these are the only five lines I have!
Comment: I think your 500 error does not come from you htacces. if you remove the directory protection, does it work properly ? if yes, check that mod_auth is installed in apache
Comment: I just tried adding line by line and the one that gives the error is: require valid-user. I will check mod_auth.
Comment: Do you have any other .htaccess files anywhere else in the web folders? Also, if you remove this .htaccess completely do you still get a 500 error?
Answer: When you are putting the file path for the AuthUserFile, make sure you use the FULL filepath from your root directory, for example:
AuthUserFile /var/www/html/test/folder/admin/.htpasswd

A similar issue was discussed in this thread:
htaccess / htpasswd in subdir

.htaccess & .htpasswd equals 500 error


Morita contexts and Noetherianity/affineness

Question:
Let $(R\,,\, S\,,\, _RM_S\,,\, _SN_R\,,\, f\,,\, g)$ be a Morita context with $NM=S$ and $R$ right Noetherian. Show that $S$ is right Noetherian as well. If we further assume $R$ is an affine $\mathbb{k}$-algebra (for some commutative ring $\mathbb{k}$), show that $S$ is as well.

I've tried to mimic a bit of what I've seen in some texts I've skimmed through, but it hasn't helped so far. I've been trying to find an inclusion of the lattice of submodules of $S$ into the lattice of submodules of $R$; perhaps it's better to try and do it directly.... But I don't know how to relate the Morita context to a chain of ideals of $S$.
Any help is appreciated
Comment: When is a ring "k affine"?
Comment: So for instance, you consider $F[x]$ is an affine $F$ algebra, right? Hmm, that's interesting: I do not ever recall hearing that being an affine $k$ algebra is Morita invariant, although it wouldn't surprise me. Does this property have a module theoretic characterization?
Comment: Whoops! I meant to assume that $R$ is an affine $\mathbb{k}$-algebra. It has been edited
Comment: I have no idea what you mean by "affine algebra" either. [Wikipedia](http://en.wikipedia.org/wiki/Affine_algebra) seems to indicate you might mean "finitely generated algebra"?
Comment: Yes, "affine" means it is finitely generated as an algebra over $\mathbb{k}$. Sorry for not being clear; I thought it conventional terminology
Comment: Honestly, I don't know, but I doubt it. One might naively expect something dealing with modules being finitely generated, but this is generally a stricter requirement than an algebra being finitely generated. So again, I don't know, but my suspicion is no
Answer: Probably the way to think of it is to establish the functor $F(-):Mod-R\to Mod-S$ isomorphic to $-\otimes_R M$ for a progenerator $_RM_S$ and then look at the properties it preserves.
First establish that if $N_R$ is finitely generated, then so is the left $S$ module $F(N)$. Then, identifying the submodules of $F(N)$ as images of submodules of $N$ ia $F$, you can easily say that all submodules of $F(N)$ are finitely generated.
Applying this to $N_R=R_R$ would finish the job.

Actually it is probably possible to argue directly with a correspondence of submodules using $F$ and a counterpart inverse functor $G$, but I lack the experience to state that confidently.


C++ Error with Data Types

Question: I keep getting a compilier error whenever I run this... I am quite sure it is just something stupid that I am overlooking, so I though I would let you guys try.
#include <iostream>
#include <string>

using namespace std;

class hi
{
public:
    string run()
    {
        hi = "Hello.";
        return hi;
    }
private:
    string hi;
}

int main()
{
    bool end = false;
    string in = "";
    string out = "";

    hi hi;

    while(end != true)
    {
        cout << "Input a Command: ";
        cin >> in;
//        if(in == "help")
//        {
//            out = help.run;
//        }
        if(in == "hi")
        {
            out = hi.run;
        }

        cout << out;
        in = "";
    }
    return 0;
}

I keep getting these errors:
|6|error: new types may not be defined in a return type|
|6|note: (perhaps a semicolon is missing after the definition of 'hi')|
|18|error: two or more data types in declaration of 'main'|
||=== Build finished: 2 errors, 0 warnings ===|

Comment: Please paste your code in your question, instead of providing an outside link. StackExchange regulations.
Comment: Codereview is for reviews of working code. It's not for getting your code to work.
Comment: needs a semi-colon at the end of the class definition (hi). Why is the member given the same name as the class? What is hi::hi ? A data member or a constructor?
Answer: Near the end of your program you are closing more curly brackets than you have opened. You need to remove the curly bracket right before return 0;
Also you need to terminate your definition of class hi with a semicolon after the closing curly bracket, right before the definition of main().
Comment: Sure, no problem. Another happy customer.
Comment: What is hi::hi ? A constructor or the string member? There is no particular reason to give the member variable the same name as the class even if it does compile.
Answer: You forgot the semi-colon after your class definition.

C++ Error with Data Types


Restore firefox data

Question: I've installed 20.04, so I copied firefox folder that is in Mozilla hidden folder inside home entirely from 16.04 and pasted on the same folder on new system. Is that the way it's meant to be? I don't know if I did something wrong Thanks.
Answer: Don't know if this is on-topic but according to Mozilla

Enter about:profiles in address bar
Create a new profile and then close firefox
Paste your old profile files in the new profile folder replacing any files there
Start firefox and you can set the new profile as default by going back to step 1
Comment: Yes it works. Another idea would be to close firefox, delete the `.mozilla` created folder and copy back the saved one. In both case, review files perms after copy
Comment: Thank you. I was afraid that .mozilla folder contained firefox browser itself, and that if I did that I would copy firefox version of 16.04 in 20.04, creating a mess.

Restore firefox data


How to change carousel image slider arrows color only on the second slide?

Question: how can i change the carousel image slider indicator arrows color only on the second image slide???
On the first slide i want to be black color, but when the image slide to 2nd slide i want to set the indicators to white color.
Is this possible???
I tried to create id tag on second slide, but its not helped, someone who is expert in CSS know how to do this???
The big problem is i can't target in CSS only the second slide carousel icons, and i don't know how to do this.
And i want to target the second image slider arrow icon in CSS to set the arrow color to white.
carousel-control-next, .carousel-control-prev
Here is the HTML code,this is the Carousel image slider sample:

Hello

World

    Previous

    Next

Comment: Do you need to do this because you can't see the indicators on the second slide?
Comment: Yes,the picture what i use too much dark,and the arrow indicators is on black color.So i want to change to white color.
Comment: Could you edit the image so they display on both light and dark backgrounds? eg add some shadow/glow to reveal the outline?
Answer: You may need to do some javascript, first attatch an id to the element you want to modify, then control in which slide you are at to modify the class of saved element.


Flex: Save an editable datagrid via a CFC

Question: I have an editable datagrid which I need to be able to save with other form fields via a CFC in ColdFusion.
Basically the aim is that there are a number of locations retrieved via an RO which make up the first column the remaining columns are types of data i.e. demographics, client notes, appointments etc, the idea is that the user tick each of the checkboxes in the grid to indicate that they are happy to share the type of data with those locations. It has to be done this way as the locations may change so there could be two or four or more over time.
The code runs so far runs and looks good but the saving bit is driving me nuts!! Please help.
Thanks in advance
:)
the code (abreviated for reasons of sanity) is below:
public function handleconsentResult(event:ResultEvent):void {
            consentDatagrid.dataProvider = event.result;
            }
<mx:RemoteObject id="consentQuery"
    destination="ColdFusion"
    source="Build3.consent"
    showBusyCursor="true">
    <mx:method name="getconsent" result="handleconsentResult(event)" fault="fault(event)" />

<mx:DataGrid id="consentDatagrid" creationComplete="init()" width="98%" wordWrap="true" textAlign="center">
                        <mx:columns>
                            <mx:DataGridColumn headerText="Organisation" width="100" textAlign="left" id="Location" dataField="LocationName" wordWrap="true"/>
                            <mx:DataGridColumn headerText="Demographics"  width="100" wordWrap="true" textAlign="center" itemRenderer="mx.controls.CheckBox" rendererIsEditor="true" editorDataField="ClientDemographics" />
                            <mx:DataGridColumn headerText="Appointments"  width="100" wordWrap="true" textAlign="center" itemRenderer="mx.controls.CheckBox" rendererIsEditor="true" editorDataField="ClientAppointments"/>
                            <mx:DataGridColumn headerText="Activity"  width="70" wordWrap="true" textAlign="center" itemRenderer="mx.controls.CheckBox" rendererIsEditor="true" editorDataField="ClientActivity"/>
                            <mx:DataGridColumn headerText="Notes" width="50" wordWrap="true" textAlign="center" itemRenderer="mx.controls.CheckBox" rendererIsEditor="true" editorDataField="ClientNotes"/>
                        </mx:columns>
                    </mx:DataGrid>

Answer: It sounds like what you want to do is return the entire contents of the DataGrid back as a member of the rest of your form data. I'm still learning Flex, but I believe it would automatically be converted from an ArrayCollection to a Query since you're using AMF.
Since you're not using a dataProvider attribute for your DataGrid, I assume you're binding an ArrayCollection object to the DataGrid in the init function you're calling from the creationComplete event. In that case, you'll want to do the opposite before returning the form data to the server: copy the DataGrid values back to a variable you're returning.
Alternatively, you could use a bindable ArrayCollection variable, so that when the DataGrid is updated by the user, the ArrayCollection variable is already updated and you can simply return it back to ColdFusion.
Answer: I don't know Flex in CF but have you determined if you want to save them all at once or on some sort of "Save" or "Submit" action?
If you are going to save them all at once then this post on Iterating over a ColdFusion Query in Flex may be helpful.
Otherwise I would just put a Listener on the onChange event in each cell and write it in real time.
Answer: I needed to do something similar and I found it worked nicely to create a "data set" object in actionscript and an analogous CFC that would map to each other.  From flex, call the remote method passing the actionscript object, then on the CF side it will be translated as to the cfc.
[RemoteClass(alias = "model.DataSet")] **//maps to the CFC**
[Bindable]
public class DataSetVO
{

    public var rows:Array;

    public function DataSetVO()
    {

    }

}

The CFC is like this. Make sure to set the alias attribute to match the alias set in the RemoteClass of the actionscript object:
<cfcomponent name="DataSet"  alias="model.DataSet">
<cfproperty name="rows" type="array" />
</cfcomponent>

The CFC method to save the data can be like
    <cffunction name="saveToFile" access="remote" returntype="numeric" hint="">
    <cfargument name="dataSet" type="model.GPDataSet" required="true" />

    <cfreturn 0 />
</cffunction>

The call from flex is like:
 //make a remote call to save the grid
 //populate your VO with the contents of the grid, in this case I have an object
 //that gives me one, basically iterate over the dataprovider of the grid
var myVO:DataSetVO = myDataSet.getAsVO();
//calling the remote CFC passing the VO that will be mapped to a CFC on the server
cfsvc.saveToFile(myVO);

Mapping complex objects from Flex to CF can be a little tricky but once it's set up it very nice.
These articles may be helpful
http://www.jeffryhouser.com/index.cfm/2007/10/9/Why-does-ColdFusion-return-a-CFC-to-Flex-as-a-generic-object
http://mxbase.blogspot.com/2008/07/passing-custom-objects-between-flex-and.html


PyQt Rounded progress bar

Question: Inspired from the post and code here Any PyQt circular progress bar?
I am trying to embed four rounded progress bar in my gui application. In my gui I do not need border of the progress bar and base rectangle. How can I remove these two in the code of paintEvent.
<code>    def paintEvent(self, event):
        outerRadius = min(125,110)
        baseRect = QtCore.QRectF(1, 1, outerRadius-2, outerRadius-2)  # I don't want this rectangular shape behind circular bar

        buffer = QtGui.QImage(outerRadius, outerRadius, QtGui.QImage.Format_ARGB32)
        buffer.fill(255)

        p = QtGui.QPainter(buffer)
        p.setRenderHint(QtGui.QPainter.Antialiasing)

        # data brush
        self.rebuildDataBrushIfNeeded()

        # background
        self.drawBackground(p, buffer.rect())

        # base circle
        self.drawBase(p, baseRect)

        # data circle
        arcStep = 360.0 / (self.max - self.min) * self.value
        self.drawValue(p, baseRect, self.value, arcStep)

        # center circle
        innerRect, innerRadius = self.calculateInnerRect(baseRect, outerRadius)
        self.drawInnerBackground(p, innerRect)

        # text
        self.drawText(p, innerRect, innerRadius, self.value)

        # finally draw the bar
        p.end()

        painter = QtGui.QPainter(self)
        painter.drawImage(0, 0, buffer)

    def drawBackground(self, p, baseRect):
        p.fillRect(baseRect, self.palette().background())

    def drawBase(self, p, baseRect):
        bs = self.barStyle
        if bs == self.StyleDonut:
            p.setPen(QtGui.QPen(self.palette().shadow().color(),  self.outlinePenWidth))
            p.setBrush(self.palette().base())
            p.drawArc(baseRect,1,116)
        elif bs == self.StylePie:
            p.setPen(QtGui.QPen(self.palette().base().color(), self.outlinePenWidth))
            p.setBrush(self.palette().base())
            p.drawArc(baseRect,1,116)
        elif bs == self.StyleLine:
            p.setPen(QtGui.QPen(self.palette().base().color(), self.outlinePenWidth))
            p.setBrush(Qt.Qt.NoBrush)
            p.drawArc(baseRect.adjusted(self.outlinePenWidth/2, self.outlinePenWidth/2, -self.outlinePenWidth/2, -self.outlinePenWidth/2))

    def drawValue(self, p, baseRect, value, arcLength):
        # nothing to draw
        if value == self.min:
            return

        # for Line style
        if self.barStyle == self.StyleLine:
            p.setPen(QtGui.QPen(self.palette().highlight().color(), self.dataPenWidth))
            p.setBrush(Qt.Qt.NoBrush)
            p.drawArc(baseRect.adjusted(self.outlinePenWidth/2, self.outlinePenWidth/2, -self.outlinePenWidth/2, -self.outlinePenWidth/2),
                      self.nullPosition * 16,
                      -arcLength * 16)
            return

        # for Pie and Donut styles
        dataPath = QtGui.QPainterPath()
        dataPath.setFillRule(Qt.Qt.WindingFill)

        # pie segment outer
        dataPath.moveTo(baseRect.center())
        dataPath.arcTo(baseRect, self.nullPosition, -arcLength)
        dataPath.lineTo(baseRect.center())

        p.setBrush(self.palette().highlight())
        p.setPen(QtGui.QPen(self.palette().shadow().color(), self.dataPenWidth))
        p.drawPath(dataPath)

    def calculateInnerRect(self, baseRect, outerRadius):
        # for Line style
        if self.barStyle == self.StyleLine:
            innerRadius = outerRadius - self.outlinePenWidth
        else:    # for Pie and Donut styles
            innerRadius = outerRadius * self.donutThicknessRatio

        delta = (outerRadius - innerRadius) / 2.
        innerRect = QtCore.QRectF(delta, delta, innerRadius, innerRadius)
        return innerRect, innerRadius

    def drawInnerBackground(self, p, innerRect):
        if self.barStyle == self.StyleDonut:
            p.setBrush(self.palette().alternateBase())

            cmod = p.compositionMode()
            p.setCompositionMode(QtGui.QPainter.CompositionMode_Source)

            p.drawEllipse(innerRect)

            p.setCompositionMode(cmod)

    def drawText(self, p, innerRect, innerRadius, value):
        if not self.format:
            return

        text = self.valueToText(value)

        # !!! to revise
        f = self.font()
        # f.setPixelSize(innerRadius * max(0.05, (0.35 - self.decimals * 0.08)))
        f.setPixelSize(innerRadius * 1.8 / len(text))
        p.setFont(f)

        textRect = innerRect
        p.setPen(self.palette().text().color())
        p.drawText(textRect, Qt.Qt.AlignCenter, text)

    def valueToText(self, value):
        textToDraw = self.format

        format_string = '{' + ':.{}f'.format(self.decimals) + '}'

        if self.updateFlags & self.UF_VALUE:
            textToDraw = textToDraw.replace("%v", format_string.format(value))

        if self.updateFlags & self.UF_PERCENT:
            percent = (value - self.min) / (self.max - self.min) * 100.0
            textToDraw = textToDraw.replace("%p", format_string.format(percent))

        if self.updateFlags & self.UF_MAX:
            m = self.max - self.min + 1
            textToDraw = textToDraw.replace("%m", format_string.format(m))

        return textToDraw

    def valueFormatChanged(self):
        self.updateFlags = 0;

        if "%v" in self.format:
            self.updateFlags |= self.UF_VALUE

        if "%p" in self.format:
            self.updateFlags |= self.UF_PERCENT

        if "%m" in self.format:
            self.updateFlags |= self.UF_MAX

        self.update()

    def rebuildDataBrushIfNeeded(self):
        if self.rebuildBrush:
            self.rebuildBrush = False

            dataBrush = QtGui.QConicalGradient()
            dataBrush.setCenter(0.5,0.5)
            dataBrush.setCoordinateMode(QtGui.QGradient.StretchToDeviceMode)

            for pos, color in self.gradientData:
                dataBrush.setColorAt(1.0 - pos, color)

            # angle
            dataBrush.setAngle(self.nullPosition)

            p = self.palette()
            p.setBrush(QtGui.QPalette.Highlight, dataBrush)
            self.setPalette(p)

class TstWidget(QtGui.QWidget):
    def __init__(self):
        super(type(self), self).__init__()

        self.bar = QRoundProgressBar()
        self.bar.setFixedSize(400, 400)

        #self.bar.setDataPenWidth(3)
        #self.bar.setOutlinePenWidth(3)
        self.bar.setDonutThicknessRatio(0.85)
        self.bar.setDecimals(1)
        self.bar.setFormat('%p %')
        # self.bar.resetFormat()
        self.bar.setNullPosition(180)
        self.bar.setBarStyle(QRoundProgressBar.StyleDonut)
        self.bar.setDataColors([(0., QtGui.QColor.fromRgb(0,159,80)), (0.5, QtGui.QColor.fromRgb(255,255,0)), (1., QtGui.QColor.fromRgb(255,255,0))])

        self.bar.setRange(0, 100)
        self.bar.setValue(85)

        lay = QtGui.QVBoxLayout()
        lay.addWidget(self.bar)
        self.setLayout(lay)

    def main():
        app = QtGui.QApplication(sys.argv)
        ex = TstWidget()
        ex.show()
        app.exec_()
if __name__ == '__main__':
    main()
</code>
Comment: Can you minimise this to a relevant and concise example, exhibiting the issue?
Comment: I have edited the code to let only paint event remains. Now in that paint event base rect is drawn and the bar consists of outer circle and inner circle and has got color for border. I dont need border in that.
Answer: if you are adding it to a QWidget and you need it transparent you can do it like this
<code>progress = QRoundProgressBar()
progress.setStyleSheet("background-color: #ffffff")
</code>
note that "#ffffff" is the color of the background so set it accordingly

PyQt Rounded progress bar


How to find the right key when decryption is not decodable with PyCryptodome

Question: I am new to cryptology. There is a file.aes that is encrypted using AES with 128-bit key and ECB. I have no clue what format the original file is. I am given a set of keys that I was told one of them will decrypt it correctly. So I wrote a python script with PyCryptodome as below:
from Crypto.Cipher import AES

keys = [some 32 character keys]

file_in = open("file.aes", "rb")
ciphertext = file_in.read()

for key in keys:
    print (key)
    cipher = AES.new(str.encode(key), AES.MODE_ECB)
    data = cipher.decrypt(ciphertext)
    print(data)

For all keys the decryption returns bytes data that is not comprehensible like this:
b'\xdd\xc1\xd4\x80\xd5\xe6\x92\xe7\xf3/\n\xa4\x90\x0b\x98(\x8a\xb8\xdf\xd1K\n\xeagW\xe9f\x80\xef9\x8e\xd5...'

I tried to decode it with ascii, utf-8, utf-16, utf-32 hoping to see plaintext and they all return UnicodeDecodeError:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa7 in position 0: ordinal not in range(128)

How do I find the right encoding for the data?
I also start wondering if the original file was also just a incomprehensible binary file. How do I know which decryption was successful and correct when I can't identify it by just reading it?

Edit:
As suggested I tried encrypt and decrypt a utf-8 encoded plain file as below. Decrypted with no issue.
from Crypto.Cipher import AES

key = b'ipu9TUv54yv]isFMh5@;t.5w34E2Ry@{'
cipher = AES.new(key, AES.MODE_ECB)

file_in = open("file", "rb")
data = file_in.read()
length = 16 - (len(data) % 16)
data += bytes([length]) * length

ciphertext = cipher.encrypt(data)
print(ciphertext)

plaintext = cipher.decrypt(ciphertext)
print(plaintext.decode())

Update: New thoughts. Since I am testing on a bunch of keys that are mostly not valid, it is probably normal that the decrypted data is decodable and return error. I should use try and except. I should also try all codecs that python listed in the documentation.
from Crypto.Cipher import AES

keys = [some 32 character keys]
codecs = [all codecs]

file_in = open("file.aes", "rb")
ciphertext = file_in.read()

for key in keys:
    print (key)
    cipher = AES.new(str.encode(key), AES.MODE_ECB)
    data = cipher.decrypt(ciphertext)
    for codec in codecs:
        try :
            print(data.decode(codec))
        except:
            pass

After adding decode and try-except on the print statement, trying all encoding, I found none of keys would print anything.
Comment: You can't knw if your decryption was successful if you can't confirm the decrypted data is correct. Have you tried encrypting a known file using your code to make sure it decrypts it?
Answer: I found a way to successfully decrypt it with OpenSSL instead.
Write a script that calls OpenSSL with the set of keys, python bash or bat doesn't matter. It will create a output file no matter the key is right or wrong, the file can be overwritten but we do not care about that. If the key is wrong it prints bad decrypt error and exit with code 1. Find the key where it prints nothing or exit with code 0. Than take the key to decrypt separately. In my case I have found 8 keys and only one of them turns out to be readable.
Here's python implementation of the idea:
keys = [a list of all possible keys]

for key in keys:
    # out.txt will be repeatedly overwritten
    command = "openssl enc -d -aes-128-ecb -in file.aes -out out.txt -K " + key
    output = os.system(command)
    # If OpenSSL exited with code 0
    if (output == 0):
        # Generates a separate file for that key
        command = "openssl enc -d -aes-128-ecb -in file.aes -out " + key + ".txt -K " + key
        output = os.system(command)


"Missing parameter type" in for-comprehension when overloading flatMap

Question: I wrote my own Either-like monad class called Maybe with either a value or an error object inside it. I want objects of this class to combine with Future, so that I can turn a Maybe[Future[T], E]] into a Future[Maybe[T, E]]. Therefore I implemented two flatMap methods:
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

sealed abstract class Maybe[+E, +V] {

  def map[W](f: V ⇒ W ): Maybe[E, W] = this match {
    case Value(v) ⇒ Value(f(v))
    case Error(_) ⇒ this.asInstanceOf[Error[E, W]]
  }

  def flatMap[F >: E, W](f: V ⇒ Maybe[F, W]): Maybe[F, W] = this match {
    case Value(v) ⇒ f(v)
    case Error(_) ⇒ this.asInstanceOf[Error[F, W]]
  }

  def flatMap[W](f: V ⇒ Future[W]): Future[Maybe[E, W]] = this match {
    case Value(v) ⇒ f(v).map(Value(_))
    case Error(_) ⇒ Future.successful(this.asInstanceOf[Error[E, W]])
  }
}

final case class Value[+E, +V](value: V) extends Maybe[E, V]
final case class Error[+E, +V](error: E) extends Maybe[E, V]

However, when I use the for comprehension to combine a Maybe and a Future which holds another Maybe the Scala compiler gives me the error message missing parameter type at the line of the outer generator:
def retrieveStreet(id: String): Future[Maybe[String, String]] = ...

val outerMaybe: Maybe[String, String] = ...

val result = for {
      id ← outerMaybe // error message "missing parameter type" here!
      street ← retrieveStreet(id)
    } yield street

But when instead of using for I call the flatMapand mapmethods explicitly, it works:
val result2 =
  outerMaybe.flatMap( id => retrieveStreet(id) )
            .map( street => street )

(I also get this error message when I try to combine a Maybe with another Maybe in a for comprehension.)
So the questions are:

Shouldn't these two alternatives behave exactly the same? Why does the compiler figure out the correct flatMap method to call, when calling flatMap explicitly?
Since apparently the compiler is confused by the two flatMap implementations, is there a way to tell it (by a type specification anywhere) which one should be called in the for comprehension?

I am using Scala 2.11.8 in Eclipse.
Comment: I am surprised, your flatMap overload even compiles (most probably, scalac is just confused, and shows you a wrong error. Try removing the for comprehension and seeing if it compiles then).
Comment: The reason I think it should not compile is that both versions of `flatMap` have the same signature after type erasure. That's not allowed. I don't think it is possible to do what you want here,  but will be happy to find out if someone can prove me wrong.
Comment: @Dima If the problem is the same signature, why does the alternative notation (`flatMap`/`map`) work?
Answer: I can't give you a comprehensive answer, but running it through scalac -Xprint:parser, I can tell you that the 2 alternatives actually desugar slightly differently, there's a good chance this is the source of your issue.
val result1 = outerMaybe
  .flatMap(((id) => retrieveStreet(id)
  .map(((street) => street))));

val result2 = outerMaybe
  .flatMap(((id) => retrieveStreet(id)))
  .map(((street) => street))


Gnome 3 always show ALT+x keyboard shortcuts

Question: I found out that "gtk-auto-mnemonic = 0" is supposed to turn the underlined keyboard shortcuts back on but neither "gtk-auto-mnemonic = 0" nor "gtk-auto-mnemonic = 1" at the end of every theme file made any difference.
Is this advice only valid for Gnome 2?
How can I make the shortcuts always visible, not just when I press ALT?
I did it with
locate gtkrc | grep themes | xargs -I @ echo "echo \"gtk-auto-mnemonics = 0\" >> @" | sudo sh

And verified with (both with zero and one, as I tried both):
~$ locate gtkrc | grep themes | xargs grep auto
/usr/share/gimp/2.0/themes/Default/gtkrc:gtk-auto-mnemonics = 1
/usr/share/gimp/2.0/themes/Small/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Adwaita/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Adwaita/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Clearlooks/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Crux/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Default/gtk-2.0-key/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Emacs/gtk-2.0-key/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/HighContrast/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/HighContrastInverse/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Industrial/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/LowContrast/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Mist/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Raleigh/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/Redmond/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/ThinIce/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1
/usr/share/themes/bubble/gtk-2.0/gtkrc:gtk-auto-mnemonics = 1

Answer: Try:
$ dconf write /org/gnome/desktop/interface/automatic-mnemonics false

According to its schema: Only show mnemonics on when the Alt key is pressed. Whether mnemonics should be automatically shown and hidden when the user presses the Alt key..
Alternatively, you can use dconf-editor to change the value.
You will need to re-start the application in order the change makes effect.
Comment: Did you try it? Did you try to close the application and open it again?
Comment: This makes my keybinds *never* show up instead of just when I press alt.
Comment: This works for most of the applications I use, except Vinagre. I took a peek at its source and it seems to have underlines characters where I would expect mnemonics to appear, but they don't...
Comment: [Doesn't work for me](http://askubuntu.com/questions/329668/always-show-keyboard-shortcuts-in-gnome), I'm afraid. And yes, I did restart the application.
Comment: Which application? The setting depends on the application using dconf.  Older applications might still using gconf.
Comment: In my ubuntu 12.04 I don't have a "dconf" command, but your answer lead me in the right direction and the command that worked for me was:

    gsettings set org.gnome.desktop.interface automatic-mnemonics false


Some more clarity on "==" and "is" in Python

Question: This is a small program that works as a arithmetic calculator. I have read previous questions here, but there is still a doubt. In my code, I have used 'is' and not == in my while loop, but my loop does not stop. That is kind of unexpected because the variable ask is getting assigned by a new object if the user presses 'n' when asked for input. I'd be grateful if someone can have a look on the code and help.
def Add(x,y):
    add = x+y
    print("Answer:",add)

def Sub(x,y):
    sub = x-y
    print("Answer:",sub)

def Mult(x,y):
    product = float(x*y)
    print("Answer:",product)

def Div(x,y):
    if y!=0:
        div=float(x/y)
        print("Answer:",div)
    else:
        print("Invalid input!")

ask='y'
while(ask is 'y' or 'Y'):

    x=float(input("\nEnter x:"))
    y=float(input("Enter y:"))

    print("\nCALCULATOR:")
    print("\nPlease select any of the following options:")
    print("1.Add")
    print("2.Subtract")
    print("3.Multiplication")
    print("4.Division")
    opt=int(input("\nYour option:"))

    if(opt is 1):
        Add(x,y)

    elif(opt is 2):
        Sub(x,y)

    elif(opt is 3):
        Mult(x,y)

    elif(opt is 4):
        Div(x,y)

    else:
        print("Invalid option!")
    ask=input("\nDo you want to continue?(y/n or Y/N)")

Comment: The while loop does not stop because `anything or 'y'` is always `True`. See here: http://stackoverflow.com/q/15112125/1639625
Comment: I believe `while( ask in ['y','Y'])` is what your are looking for. I believe the way your current statement is evaluated is `(ask is 'y') or 'Y'` which is always `True`, per @tobias_k
Answer: is compares object identity. But there are many different string objects, that have the value 'y'. So always compare with == if you want to compare values.
Besides or is a boolean operation on two expressions and not lexical or.
So the condition have to be:
while ask == 'y' or ask == 'Y':
    ...

or more compact:
while ask in ['y', 'Y']:
    ...

or with the help of lower method:
while ask.lower() == 'y':
    ...

Comment: This is correct, but just to clarify a little: in Python, a non-empty string converted to boolean evaluates to `True`. So your while condition is equivalent to `while (ask is 'y') or (True):`.
Comment: @bjudson: wrong, `ask is 'y' or 'Y'` evaluates to `True` (if `ask` is equal to `'y'`) or to `'Y'` otherwise. Now, the `while`-condition is evaluated to a boolean, so `True` stays true or `'Y'` finally becomes `True`.
Comment: Edited comment to clarify I was referring to string to boolean conversion
Answer: As Daniel mentions in his excellent answer, in Python, the is for identity, not equality. In case you don't know what that means, I will offer a brief explaination.
is compares if two variables are referencing the same object in memory, not if they are equal. For example
im_a_list = [1,2,3]
im_a_similar_list = [1,2,3]

now,
im_a_list is im_a_similar_list

will be False, whilst
im_a_list == im_a_similar_list

is True. on the otherhand, if you have
im_a_list = im_seriously_the_same_list = [1,2,3]

then
im_a_list is im_seriously_the_same_list

will evaluate to True


How do I specify bags in the management condition interface?

Question: Having located the magma layer as well as a good source for sand, I'm eager to get glass production up and running, for trade and defense purposes.
In order to better automate things, I set up a glass furnace that doesn't take general orders, but has a specific order to gather sand 10 times whenever there are less than 50 sand-bearing-items available.
However, in order to avoid running completely out of bags I also want to add a conditional not to start the job if there are less than 20 empty bags available, and this is where I run into trouble.
You can specify 'empty items' as a trait, and 'boxes and bags' as a category, but that category includes wooden chests and rock or metal coffers, neither of which are suitable. On the other hand, material doesn't have categories like 'all leather' or 'all yarn' but only specific 'aardvark leather' or 'sheep yarn' or 'ramie cloth'.
This makes the latter test essentially useless since I have a different work order to make sure I always have at least 20 rock coffers available for when I need to create a new bunch of rooms.
Any suggestions?
Answer: You could try removing the condition for empty bags and instead have the stockpile set to [g]ive resources (and perhaps take as well, I am unsure if the empty bags produced are considered "produced" by the furnace) to that glass furnace, and ensure that it can contain 50 or so sand bags.
This will require that you also ensure it has fuel, but since you mentioned magma I am presuming you intend to make a magma glass furnace so that should not pose an issue.
This way, you will always have 50 bags either empty or full in that stockpile but they will only ever be used by that glass furnace for collecting sand or making glass, so you are free to put other bags elsewhere and they will not be used.
Do note that eventually your glassmakers will become very fast at crafting and will likely outpace your sand collection unless you have many dwarves on it.
Comment: Hi. Thanks for this answer, but I think I wasn't quite clear enough with my question. What I want is to restrict the 'gather sand' job to not activate unless there is at least a margin of 20 or so empty bags -- not boxes -- available. This is because I need to have a reserve for milling and plant processing as well.
Comment: There is no way to directly do that, which is why I suggested a specific stockpile of bags for the gather sand job. The job interface might (I don't remember) work with this, so if you set the to job for that glass furnace to run when there are less than 20 bags then it might only check in the specific stockpile you have set to give to the furnace.
Answer: My solution to this problem is to limit the amount of sand bags:
Create a job "collect 5 sand" with condition "amount of sand-bearing items at most 8" (item: boxes&bags; trait: sand-bearing).
Then create a bin-less sandbag sockpile next to your glass workshop which can contain ca. 20 sand bags (furniture->sandbag). This way your whole glass industry will ever use only ca. 15 bags in total. No input/output-stockpiles needed if no other stockpile accepts sandbags.


Is there a notation for "exists but not necessarily unique"?

Question: Somes it is useful to write "there exists not necessarily unique value such that..."
For instance, for any convex function $f$, there exists a (not necessarily unique) global minimizer $x$.
Since "there exists a unique" is written as $\exists !$, is it possible to write something like $\exists \not!$.
Is there a standard notation for this?
Comment: Is $\exists$ not good enough?
Comment: The emphasis is part of the meaning of $\exists$. If someone doesn't understand this, the problem isn't lack of expressiveness by the symbol $\exists$, but rather the person in question not understanding what $\exists$ means.
Comment: @JonatanB.Bastos Yes, it is enough, but sometimes you really would like to emphasize that the existence of a certain object is not necessarily unique
Comment: There is no common way in logic to denote that you aren't assuming something.  What that would even mean isn't unambiguous.
Answer: The phrase is simply "there exists", notated $\exists$.
In English, if you wanted to emphasize that you don't mean "there exists a unique ...", then you might say "there exists at least one ...".
Symbolically, there should be no need for this emphasis.
Comment: @Krish: "I'm not saying that it's unique" is different from "I am saying that it's not unique". The OP and my answer are talking about the former.
Comment: +1 for distinguishing between using English and symbols. You can always explain things in words rather than symbols, and doing so is generally clearer and more expressive.
Comment: I think you mean "there exists at least two..." to emphasize that it's not unique. Small typo.
Answer: You may consider emphasizing the possible non-uniqueness in a footnote. It doesn't make the text heavier (only by the size of your footnote indicator) and you can even afford a small comment regarding why this is important to you.


Good strategy for using git to collaborate with a designer on a ruby on rails project?

Question: I am developing a Ruby on Rails app, and am working with a designer who is not very experienced with rails or with git.  I'm new to using git on a team, but I've used it on my own projects for a while.
What is the easiest way to manage allowing the designer to make the CSS/view edits and push the changes to our git repo, while also being able to review and approve the changes?
Thanks!
Comment: It's probably not a good question for SO. Anyway, for review process, I recommend you to use `forks` and `pull-requests`, both supported by GitHub and Bitbucket.
Answer: In my team, we use Vagrant for providing a VM that runs the same everywhere. It requires a bit of configuration before it works properly.
We use Github along with Hub to create easy pull-requests. The requests can then be reviewed and merged with the GUI provided on Github website.
The process is then as following:

Connect to the VM
Create a feature branch with git checkout -b new-branch (from UTD master)
Commit and push your code
Create the pull-request with hub pull-request [options]
Get the code reviewed and merged on Github

To make it easier, you can add whichever git GUI to the process, but I find the command-line to be extremely efficient and it requires little knowledge for the process you seek.
Answer: A combination of Vagrant, which you can use to package up an easy-to-run version of the application, combined with a Git GUI client makes it a lot easier for a non-programmer designer to work on your project.


ColdFusion 11 with Standalone Solr Pre-install

Question: I need to install Solr on its own server for scalability/multiple CF connections. However I am confused as to how CF 11 does this. The Standalone services installer seems to be for the Express Install.
Adobe does not support a non-ColdFusion Solr install. So do I need to install a full CF 11 install on my Solr server and open it up for remote connection?
Or do I use CF Express with the stand-alone installer?
This is running a legacy application, and I need to mimic a normal coldfusion install as much as possible.
Answer: You can in fact use a non-ColdFusion Solr install with ColdFusion.  Using the CFSolrLib library, you can interact with an external Solr server using the component included in the library.  I'm personally running Solr 5.2 with a ColdFusion 11 application using this library.
http://cfsolrlib.riaforge.org/
Comment: That will be great for future deployments, however this is a legacy app. I cannot make changes to it now.
Comment: That does limit your options.  In CF 11, the Solr service is no longer separate.  It's lumped into an "Add on services pack" like you mentioned above.  That standalone services pack can be installed by itself on a remote server.  No need to install full CF.  Just point your Solr config to the correct IP address in your CF Administrator after you install and you should be functional.
Comment: Oh, and by default, the CF 11 Solr service uses port 8987, so make sure you have that one open between the two servers.


Mason2 wrong utf8 encoding with the "go" method

Question: Bit long question, because AFAIK Poet/Mason2 isn't the very often used framework - so I'm trying to be detailed.
Two years ago I asked a question how to make Mason2 utf8 clean. As far as i know, here isn't much new in Mason/Poet in this field - and unfortunately today I meet another problem. Simple test case:
$ poet new my   #create new poet application
$ cd my

Override some methods, allowing to use utf8 in the components:
add to ./lib/My/Mason/Compilation.pm
override 'output_class_header' => sub {
    return join("\n",
        super(), qq(
            use utf8;
            use Encode qw(encode decode);
        )
    );
};

The above adds to each compiled Mason component the use utf8....
Also need encode the output from Mason (Plack need bytes), so in: ./lib/My/Mason/Request.pm
override 'run' => sub {
    my($self, $path, $args) = @_;
    my $result = super();
    $result->output( Encode::encode('UTF-8', $result->output()) );
    return $result;
};

Now, can create a component such page.mc for example with a content:
% sub { uc($_[0]) } {{
a quick brown fox jumps over the lazy dog.
διαφυλάξτε γενικά τη ζωή σας από βαθειά ψυχικά τραύματα.
árvíztűrő tükörfúrógép.
dość gróźb fuzją, klnę, pych i małżeństw!
эх, чужак, общий съём цен шляп (юфть) – вдрызг!
kŕdeľ šťastných ďatľov učí pri ústí váhu mĺkveho koňa obhrýzať kôru a žrať čerstvé mäso.
zwölf boxkämpfer jagen viktor quer über den großen sylter deich.
% }}

After running a poet app bin/run.pl you can go to: http://0:5000/page and will get a correct content.

A QUICK BROWN FOX JUMPS OVER THE LAZY DOG. ΔΙΑΦΥΛΆΞΤΕ ΓΕΝΙΚΆ ΤΗ ΖΩΉ
  ΣΑΣ ΑΠΌ ΒΑΘΕΙΆ ΨΥΧΙΚΆ ΤΡΑΎΜΑΤΑ. ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP. DOŚĆ GRÓŹB
  FUZJĄ, KLNĘ, PYCH I MAŁŻEŃSTW! ЭХ, ЧУЖАК, ОБЩИЙ СЪЁМ ЦЕН ШЛЯП (ЮФТЬ) –
  ВДРЫЗГ! KŔDEĽ ŠŤASTNÝCH ĎATĽOV UČÍ PRI ÚSTÍ VÁHU MĹKVEHO KOŇA OBHRÝZAŤ
  KÔRU A ŽRAŤ ČERSTVÉ MÄSO. ZWÖLF BOXKÄMPFER JAGEN VIKTOR QUER ÜBER DEN
  GROSSEN SYLTER DEICH.

But when create another component, say go.mc with a content
% $m->go('/page');

the internal redirect (the go method) somewhat mess up the content and will produce:

A QUICK BROWN FOX JUMPS OVER THE LAZY DOG. ÎÎÎΦΥÎÎÎΤÎ
  ÎÎÎÎÎΠΤΠÎΩΠΣÎΣ ÎÎ Î ÎÎÎÎÎΠΨΥΧÎÎÎ
  ΤΡÎÎÎÎΤÎ. ÃRVÃZTÅ°RÅ TÃKÃRFÃRÃGÃP. DOÅÄ GRÃŹB
  FUZJÄ, KLNÄ, PYCH I MAÅÅ»EÅSTW! ЭХ, ЧУÐÐÐ, ÐÐЩÐÐ
  СЪÐРЦÐРШÐЯР(ЮФТЬ) â ÐÐРЫÐÐ! KÅDEĽ Å
  ŤASTNÃCH ÄATĽOV UÄà PRI ÃSTà VÃHU MĹKVEHO KOÅA OBHRÃZAŤ
  KÃRU A ŽRAŤ ÄERSTVà MÃSO. ZWÃLF BOXKÃMPFER JAGEN VIKTOR QUER
  ÃBER DEN GROSSEN SYLTER DEICH.

Strange, the $m->visit() works correctly. So, somewhere in Poet/Mason is need do something to get correct output for the go method.
Could anyone help?
Comment: Could please the down-voter tell me what is wrong with the question?
Answer: I've been working on a plugin for Mason to deal with encoding. $result->output is the wrong place to encode output, because visit will run a subrequest, encoding its own content at the end, before returning to the original component, which then re-encodes everything when it completes. So the content in the visit gets encoded twice. I'm surprised you are having a problem with go, because that discards all previous content and starts again, which should be OK.
Have a look at https://github.com/davebaird/mason-plugin-withencoding


PySpark value with comma doesn't contain comma?? (Trying to cast to ArrayType(StringType()))

Question: I am running PySpark v1.6.0, and I have a column of string values (according to .printSchema), but when I attempt to filter the rows according to cases where the column value starts with a "[" character or contains a "," character, in both cases, it's saying that the rows that I'm expecting to evaluate to True are still False...
When I run the code:
col_name = "attempt_params_attempt_response_id"
resultDF.select(col_name, resultDF[col_name].like(",")).show(50)

I get:

I don't understand how this is possible because the string value clearly contains a comma, so that row should return true, not false.
Similarly, when I try casting the rows to ArrayType(StringType()) (which is my ultimate goal), it also behaves as if my rows don't contain a comma...
When I run the code:
from pyspark.sql.types import ArrayType, IntegerType, StringType

col_name = "attempt_params_attempt_response_id"
resultDF.withColumn(col_name,
                    split(resultDF[col_name], ",\s*")
                    .cast(ArrayType(StringType()))).select(col_name).show(40)

I get the results:

I wonder if perhaps there's some sort of bizarre encoding issue that is causing the character , to not match the character that in the data appears to be a , character... but I really am not sure. Any ideas on why this is happening and how I can actually get the cast to work without creating the text of a multi-dimensional array?
Answer: In the case your pattern is wrong. like is equivalent to SQL like using simple regular expression, so , matches only literal ,.
df = spark.createDataFrame([("[0,2,3]", ), (",", )], ("text", ))
df.withColumn("contains_comma", col("text").like(",")).show()

+-------+--------------+
|   text|contains_comma|
+-------+--------------+
|[0,2,3]|         false|
|      ,|          true|
+-------+--------------+

To get a match you should add leading and trailing wildcards:
df.withColumn("contains_comma", col("text").like("%,%")).show()

# +-------+--------------+
# |   text|contains_comma|
# +-------+--------------+
# |[0,2,3]|          true|
# |      ,|          true|
# +-------+--------------+

In the second case there is no problem at all. Since you split on , the first item will contain a leading [
df.withColumn("contains_comma", split("text", ",\s*")[0]).show()

+-------+--------------+
|   text|contains_comma|
+-------+--------------+
|[0,2,3]|            [0|
|      ,|              |
+-------+--------------+

and the last trailing ]. You should strip these if you don't want them in the output, for example using regexp_replace:
split(regexp_replace("text", "^\[|\]$",  ""), ",")

Comment: I was able to get your example to work after modifying your regex pattern to `"^\[|\]$"`
Comment: I also tried .startsWith("["), and those cases were all false too. Do I also need to add a wildcard for that to work?
Comment: For `startsWith` no. It uses fixed value as a pattern. However without [reproducible exmample](https://stackoverflow.com/q/48427185/6910411) it is not possible to say what is the problem, and it doesn't seem to directly related to the ones you have described here.


How do you select all records in a 24-hour time period and summarize the data in SQL?

Question: I have a SQL 2014 table containing hourly records of gas meter consumption.  Each record contains the DATETIME date along with the meter identifier and the associated gas consumption for the past hour.  The problem I am having is we need to know the total daily consumption beginning with the 10:00 am record thru the 9:00 am record of the following day.  This time period is considered our "Gas Day".  My ending result is to have each gas meter listed with a summary of gas consumption for each "Gas Day".  Listed below is a sample of my data:
MeterID    LogDate    Consumption
1007643 2015-10-30 01:00:00:00   19
1007643 2015-10-30 02:00:00:00   27
1007643 2015-10-30 03:00:00:00  26
1007643 2015-10-30 04:00:00:00  27
1007643 2015-10-30 05:00:00:00  26
1007643 2015-10-30 06:00:00:00  26
1007643 2015-10-30 07:00:00:00  38
1007643 2015-10-30 08:00:00:00  50
1007643 2015-10-30 09:00:00:00  35
1007643 2015-10-30 10:00:00:00  45
1007643 2015-10-30 11:00:00:00  46
1007643 2015-10-30 12:00:00:00  44
1007643 2015-10-30 13:00:00:00  38
1007643 2015-10-30 14:00:00:00  45
1007643 2015-10-30 15:00:00:00  35
1007643 2015-10-30 16:00:00:00  47
1007643 2015-10-30 17:00:00:00  44
1007643 2015-10-30 18:00:00:00  40
1007643 2015-10-30 19:00:00:00  27
1007643 2015-10-30 20:00:00:00  48
1007643 2015-10-30 21:00:00:00  48
1007643 2015-10-30 22:00:00:00  48
1007643 2015-10-30 23:00:00:00  28
1007643 2015-10-31 00:00:00:00  6
1007643 2015-10-31 01:00:00:00  6
1007643 2015-10-31 02:00:00:00  6
1007643 2015-10-31 03:00:00:00  7
1007643 2015-10-31 04:00:00:00  6
1007643 2015-10-31 05:00:00:00  6
1007643 2015-10-31 06:00:00:00  7
1007643 2015-10-31 07:00:00:00  6
1007643 2015-10-31 08:00:00:00  6
1007643 2015-10-31 09:00:00:00  6
1007643 2015-10-31 10:00:00:00  15
1007643 2015-10-31 11:00:00:00  96
1007643 2015-10-31 12:00:00:00  45
The ending result for the example above, which contains more records than needed for one (1) "Gas Day" is to begin adding the Consumption column beginning with the 2015-10-30 10:00:00:00 record and ending with the 2015-10-31 09:00:00:00 record.  The query would return the following:
1007643 2015-10-31 645
I am sure this is very simple, but I am new to SQL and would appreciate any help.
Answer: To find the totals for each 'gas day' for each Meter ID, you could do something like this:
SELECT [MeterID], MAX(CONVERT(DATE, [LogDate])), SUM([Consumption])
FROM tblName
GROUP BY [MeterID], DATEDIFF(hh,'1900-01-01 10:00:00', [LogDate])/24

Answer: Assuming the name of the table is GAS, the date field is DT, and the field you want to sum is AMT, it would be something like this, if you wanted to get the total for yesterday (pseudo-SQL):
SELECT SUM(AMT) FROM GAS WHERE DT BETWEEN ('2015-12-15 00:10:00') AND ('2015-12-16 09:00:00')

Comment: This would work if I only wanted to get one day in my query.  I need all records for each day for each meter summarized.  Thanks!


Do nomads in Banished wait?

Question: In Banished, if you have a batch of nomads asking entry and do not want to deny them per se, but just wait a little bit to stabilize your existing population, will they wait?
In other words, if you neither deny or accept, will they wait until you do one of those, no matter how long they are left waiting?
Answer: No, Nomads will continue and go somewhere else if you don't respond within a few seasons.
Comment: that is, they WILL wait, but not forever.
Comment: Which is what I wrote. Hence the last part of my answer.
Comment: Just that starting that with "No" isn't the most clear way of putting it is all when they answer is actually "Yes, but"

Do nomads in Banished wait?


Question on the free BA on countably many generators

Question: Let $A$ be the free Boolean algebra of countably many generators. As a Boolean algebra, it is isomorphic to the field $F$ of clopen subsets of its Stone space, namely, the Cantor space $X=2^\omega$.
It is known that $A$ is atomless, countably infinite, and incomplete. Since $A$ and $F$ are isomorphic, $F$ is also atomless, countably infinite, and incomplete.
Consider now the smallest subfield $F_0=\{\emptyset,X\}$ of clopen subsets of $Z$. Does $F_0$ inherit the properties of $F$, that is, is $F_0$ also atomless (trivially), countably infinite, and incomplete?
This question may be naive, but I just cannot decide whether or not $F_0$ inherits the properties of $F$, especially, if I consider that there exists a Boolean epimorphism of $A$ into $F_0$.
Comment: $F$ is completely irrelevant to the question.  You just have a (very simple!) Boolean algebra $F_0=\{\emptyset, X\}$.  Have you tried simply answering any of your questions about this Boolean algebra directly?
Answer: No, for all three parts. $\{\emptyset,X\}$ has an atom, namely $X$. It is not countably infinite because it is finite; its cardinality is $2$. And it is complete: Any subset containing $X$ has $X$ as its least upper bound, and any subset not containing $X$ has $\emptyset$ as its least upper bound.


How to add data to an ellipse QT

Question: I have a function in which i draw an ellipse to a scene which is on a QGraphicsView, in another function i have a click event that checks if you have clicked the same XY as the ellipse and then iterates over a map to see if that XY is assigned to a specific object if it is that Object is returned
however iv been looking into finding a way so that when an ellipse is clicked it just has data bound to it instead of having to search the xy etc to find the data
i found the function setdata which allows you to assign data to an item however seeing as my function simply draws and adds data i have no idea how to actully extract the data thats cound to it, i have a feeling its because i need to add an item which is a scene and the data should be bound to the item but i dont know how thats done and searching the docs hasnt given me any answers
heres my function
void GUI::paintDot(double x, double y, double Id)
{
    // Decalre a QPen for Painting dots
    QPen pen;

    // set the pen colour
    pen.setColor(Qt::white);

    if(x < m_height && y < m_width)
    {
        // Add ellipse at the x y position passed in
        scene2->addEllipse(x, y, 1.5, 1.5, pen, QBrush(Qt::SolidPattern))->setData(0, Id);
    }
}

0 being just an arbitrary key value which will need to change to something that actually represents a key value, but for the sake of this example its fine
Answer: You're not showing the code where you are trying to get the data back (eg, in a event handler that caches a mouse press or something).  So I'm not positive what your issue actually is, but it should be as simple as:
QVariant v = ellipseObject->data(0);

And then you extract your value out of that depending on the datatype you put in.  In your case, you put in a double:
 double d = v.toDouble();

(and obviously those two lines could be combined without the need for variable v)

How to add data to an ellipse QT


Referring leaflet popup for bring to front or back

Question: I am building application shows data on a leaflet map as popups using vue.js. I want to use "bringToFront" function that is part of leaflet object, on leaflet popup. How can I call the function - whether as L object, or l-popup component?
Vue-leaf-let library enables rendering leaflet elements as components like "l-marker" or "l-popup". functions like "l-add" for markers, for example, are used by adding "@" symbols (as vue component).
Unfortunately I haven't found any way of conditionally use bringToFront() or bringToBack functions for popup layers.
I have tried passing @bring-to-front="condition" into the component like doing so with @add of marker;
Using ":ref" on popup bring the "vue" component without leaflet methods.
Component:
``` <l-layer-group ref="layerGroup">
            <l-marker v-for="items"
                      :ref="`someRef`"
                      :lat-lng="item"
                   //succeed:
                      @add="($event)=>open($event, item)">
                <l-popup :lat-lng="item"
                         //not succeed`enter code here`
                          @bring-to-front => someFunc()
                         :ref="`popup${someDiffId}`">
                    <popup-content :key=item.key" :item="item"/>
                </l-popup>
            </l-marker>
        </l-layer-group>```

from @open I use:
```            open(event, item) {
                const marker = event.target;
                this.$nextTick(() => {
                    marker.openPopup()
                    condition? marker._popup.bringToFront():marker._popup.bringToBack()
                    setTimeout(() => {
                        marker.remove()
                    }, 30000)
                })
            }
```

By using "@add" on marker by referring "marker._popup" I succeed, but not from $this.refs and not from watchers.
Referring the object from ":ref" is referring to a vue component without @bringToFront method, so I am using reference from marker.
Answer: Well, When using all components inherits "layer" of leaflet - using "@add" inside make the reference of rendering to map/marker/layer as "leaflet object",
That's mean just add "@add":
<l-popup  @add="($event)=>func($event, leafletItem)">

and inside func:
  methods: {
         func(event, leafletItem){
          const popup = event.target;
          condition ? popup.bringToFront() : popup.bringToBack()
        }
    }

Answer: @bring-to-front is not event of adding to map leaflet object, while @add - is the event, so @add($event) will have reference to leaflet object.
Bevause of that you just use "@add" for popup component.


upload image from imageview to firebase Android

Question: i have an activity with some images in a recycler view. I want to upload them into firebase storage as profile pictures but i don't know how.
I have an activity with 2 image view: the first upload images from phone gallery the second one open this activity below. My idea is: click one image, it uploads the image clicked to firebase and when is finished return to last activity because user need to choose a nickname too.
package it.evilsecret.evilsecretappfinal;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ImageSelection extends AppCompatActivity {

private static final int CHOOSE_IMAGE = 101;
ImageView imageView;
RecyclerView recyclerView;
ImageAdapter imageAdapter;
List<Image> imageList;
ProgressBar progressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.imageselectionpopup);

    imageList = new ArrayList<>();
    recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 3));

    imageList.add(
            new Image(R.drawable.alis, "Alis"));
    imageList.add(
            new Image(R.drawable.astaroth, "Astaroth"));
    imageList.add(
            new Image(R.drawable.chris, "Chris"));
    imageList.add(
            new Image(R.drawable.sarah, "Sarah"));
    imageList.add(
            new Image(R.drawable.vanessa, "Vanessa"));

    imageAdapter = new ImageAdapter(this, imageList);
    recyclerView.setAdapter(imageAdapter);

Comment: Possible duplicate of [How to save bitmap to Firebase](https://stackoverflow.com/questions/40885860/how-to-save-bitmap-to-firebase)
Answer: To do this you have to convert the image to bitmap (convert image to bitmap)and then compress it. After that you have to upload it to firebase cloud link to firebase cloud
Answer: Convert to Bitmap first...
Bitmap bitImage = BitmapFactory.decodeResource(getResources(), imageList.get(0));

Then compress it to reduce its size...
bitImage.compress(Bitmap.CompressFormat.PNG, 100, outputStream);

Refer this link..
https://www.simplifiedcoding.net/firebase-storage-tutorial-android/


Is there a way to fix my Minecraft SMP map?

Question: Due to the change in the world generation method, I went and found a map seed that was suitable for using MCEdit to paste our old structures into it.  The only problem is, there is a region around spawn (which I moved a ways from the original staring position using the editor) that is completely uneditable.

Blocks can neither be mined nor placed
Doors don't function properly (door splits between the top half and lower half, changes randomly when interacted)
Chests won't open.

Immediately outside that area, though, everything behaves fine.  I don't know if the behavior is limited to a particular chunk or not.  Could deleting something like session.lock work?  Maybe a file permissions issue?  Currently no one is using the server yet and have a backup of the world, so I should be able to fiddle with it with no risk.
Other info:

Minecraft 1.0.0
Vanilla server (no mods)

Any ideas?
Comment: @pppery Are both symptoms of the same cause? The questions are sufficiently different to warrant helpfulness for others, I think.
Answer: This is a feature of the vanilla minecraft server. Blocks within a certian radius of the player spawn are unbreakable to non op'ed players. This is so you can make a jail that somone connecting to the server will spawn in and only a op can let them out. This is to allow open servers but prevent drive by greifing.
I do not know if there is a way to turn this off. The best option is just move the spawn in MCEdit to somewhere outside of town.


What is the point $\{∞\}$?

Question: The set of all rational points in an elliptic curve $C$ over $ℚ$ is denoted by $C(ℚ)$ and called the Mordell-Weil group, i.e.,
$C(ℚ)=\{\text{points on } $C$ \text{ with coordinates in } ℚ\}∪\{∞\}$.
1) What is the points $\{∞\}$?
2) If we ignor the torsion part of $C(ℚ)$ then what is the coordinates of $\{∞\}$?
Answer: $\infty$ is the point at infinity on the elliptic curve; its identity element. If your elliptic curve is given by an equation in Weierstrass form -- e.g. an equation like $y^2 = x^3 + Ax + B$ -- then the projective coordinates of $\infty$ are $(0 : 1 : 0)$.
If you are not familiar with projective geometry, then you need to either learn it, avoid asking the question of "where" $\infty$ is, or adopt a heuristic such as "$\infty$ is at the 'end' of every vertical line". (but you should probably learn projective coordinates sooner rather than later)

What is the point $\{∞\}$?


The Guid Is not passed Correctly in MVC4?

Question: Hi the GUID is not passed  correctly.
My Tables
Customer
CustomerID uniqueidentifier primarykey not null,
DisplayName varchar(100)
PrintName varchar(100)
CustomerAddress Table
CustomerAddressID uniqueidentifier primarykey not null,
CustomerID uniqueidentifier null,
AddressID  uniqueidentifier null
Address
AddressID uniqueidentifier primarykey not null,
DisplayName varchar(100)
Street varchar(100)
Location varchar(100)
AreaID Uniqueidentifier null,
Pincode varchar(100)
My Model
public class CustomerModel1
    {
        public System.Guid CustomerID { get; set; }
        public string DisplayName { get; set; }
        public string PrintName { get; set; }
}

public partial class CustomerAddressModel
    {
        public System.Guid CustomerAddressID { get; set; }
        public Nullable<System.Guid> CustomerID { get; set; }
        public Nullable<System.Guid> AddressID { get; set; }

   }

 public partial class AddressModel
    {
        public System.Guid AddressID { get; set; }
        public string DisplayName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public Nullable<System.Guid> AreaID { get; set; }
        public string PinCode { get; set; }
   }

My ViewModel
   public class CustomerViewModel
   {
    public System.Guid CustomerID { get; set; }
    public string CustomerName { get; set; }
    public System.Guid CustomerAddressID { get; set; }
    public System.Guid AddressID { get; set; }
    public string Address { get; set; }
    public string Street { get; set; }
    public string Location { get; set; }
    public Nullable<System.Guid> AreaID { get; set; }
    public string PinCode { get; set; }
 }

public class VisitorsEntities1 : DbContext
{

public DbSet   Customer { get; set; }
public DbSet CustomerAddress { get; set; }
public DbSet Address { get; set; }
}

My Controller
  public ActionResult Create()
    {
        VisitorsEntities1 db = new VisitorsEntities1();

 ViewBag.AreaID = new SelectList(db.Area, "AreaID", "DisplayName",   "PrintName");

   return View();
    }

    [HttpPost]
   public ActionResult Create(CustomerViewModel viewmodel)
    {

 ViewBag.AreaID = new SelectList(db.Area, "AreaID", "DisplayName",   viewmodel.AreaID);
       var Cusobj = Guid.NewGuid();
       var CusAddobj = Guid.NewGuid();
       var Addobj = Guid.NewGuid();

      var Customerobj = new Customer()
        {
            CustomerID = Cusobj,
        DisplayName = viewmodel.CustomerName,
        PrintName = viewmodel .CustomerName
   };

  var CustomerAddressobj = new CustomerAddress()
        {
            CustomerAddressID = CusAddobj,
            CustomerID = viewmodel.CustomerID,
            AddressID = viewmodel.AddressID
         };

      var Addressobj = new Address()
        {
            AddressID = Addobj,
            DisplayName= viewmodel.CustomerName,
            Street=viewmodel.Street,
            Location= viewmodel.Location,
            AreaID = viewmodel.AreaID,
            PinCode= viewmodel.PinCode
  };
     db.Customer.Add(Customerobj);
        db .CustomerAddress.Add(CustomerAddressobj );
        db.Address.Add(Addressobj);

   db.SaveChanges();

   return View()
 }

Here the AreaID is SubForm So I used ViewBag to bring dropdown in the View and Pass the Guid. Now my issue is with Customer Address Table.
 var CustomerAddressobj = new CustomerAddress()
        {
            CustomerAddressID = CusAddobj,
            CustomerID = viewmodel.CustomerID,
            AddressID = viewmodel.AddressID
         };

Here CustomerAddressID is new Guid is working fine. But

   CustomerID = viewmodel.CustomerID,
   AddressID = viewmodel.AddressID

The Guid is not passed correctly for this two lines . In table these column is 00000-0000-0000-0000 It didnt show any error and also its not passing the GUID correctly. I donno what the issue is. Please any one help to resolve these problem?
Error
My Error
Thanks.
Comment: what are you getting in `viewmodel.CustomerID` and `viewmodel.AddressID` ?
Answer: Try using specual attributes to automatically generate Guid key on insert.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public System.Guid CustomerID  { get; set; }

Here Key says it is primary key, DatabaseGenerated instructs to make key field auto-generated
EDIT
Note, that auto-generated identity fields are assigned to new entity only after save:
using (var db = new Context())
{
    var customer = new Customer();

    // Here customer.CustomerID is empty

    db.Customers.Add(customer);
    db.SaveChanges();

    // Here customer.CustomerID is assigned
}

Comment: ok and i use this                                                                                var CustomerAddressobj = new CustomerAddress()
        {
            CustomerAddressID = CusAddobj,
            CustomerID = viewmodel.CustomerID,
            AddressID = viewmodel.AddressID
         };


Python 3: Flattening nested dictionaries and lists within dictionaries

Question: I am dealing with a complex nested dictionary and list data structure. I need to flatten the data and bring all nested items to level 0. See below example for more clarity :
{a:1,b:2,c:{c1:[{c11:1,c12:2,c13:3},{c21:1,c22:2,c23:3}],d1:[{d11:1,d12:2,d13:3},{d21:1,d22:2,d23:3}]},x:1,y:2}

i need to flatten this to:
{a:1,b:2,c_c1_c11:1, c_c1_c12:2,c_c1_c13:3,c_c1_c21:1,c_c1_c22:2,c_c1_c23:3, c_d1,d11:1...and so on}

I took reference from the first answer in this post, but it can only work if i have nested dictionaries, and not if lists are nested within dictionaries and more dictionaries nested within those lists.
I modified the code a bit to fit my use case, but this code doesn't work
def flattenDict(d):
node_map = {}
node_path = []
def nodeRecursiveMap(d, node_path):
    for key, val in d.items():
        if ((type(val) is not dict)&(type(val) is not list)):
            node_map['_'.join(node_path + [key])] = val
        if type(val) is list:
            def nodeListRecursion(val,node_path):
                for element in val:
                    if ((type(element) is not dict)&(type(element) is not list)) : node_map['_'.join(node_path + [key])] = element
                    if type(element) is list: nodeListRecursion(element,node_map)
                    if type(element) is dict: nodeRecursiveMap(element, node_path + [key])
            nodeListRecursion(val,node_path)
        if type(val) is dict: nodeRecursiveMap(val, node_path + [key])
nodeRecursiveMap(d, node_path)
return node_map

The indentation is getting messed up when i paste my code here. But i would really appreciate any help here.
Answer: I think you're overcomplicating things.  You start from a dictionary, with keys and values.  Its values are either a dictionary or a list of dictionaries which you want to recurse down, or they're not, in which case you want to leave it alone.  So:
def flatten(d):
    out = {}
    for key, val in d.items():
        if isinstance(val, dict):
            val = [val]
        if isinstance(val, list):
            for subdict in val:
                deeper = flatten(subdict).items()
                out.update({key + '_' + key2: val2 for key2, val2 in deeper})
        else:
            out[key] = val
    return out

gives me
In [34]: nested = {'a': 1, 'b': 2, 'c': {'c1': [{'c11': 1, 'c12': 2, 'c13': 3}, {'c21': 1, 'c22': 2, 'c23': 3}], 'd1': [{'d11': 1, 'd12': 2, 'd13': 3}, {'d21': 1, 'd22': 2, 'd23': 3}]}, 'x': 1, 'y': 2}

In [35]: flatten(nested)
Out[35]:
{'a': 1,
 'b': 2,
 'c_c1_c11': 1,
 'c_c1_c12': 2,
 'c_c1_c13': 3,
 'c_c1_c21': 1,
 'c_c1_c22': 2,
 'c_c1_c23': 3,
 'c_d1_d11': 1,
 'c_d1_d12': 2,
 'c_d1_d13': 3,
 'c_d1_d21': 1,
 'c_d1_d22': 2,
 'c_d1_d23': 3,
 'x': 1,
 'y': 2}

Comment: Upvoted. Very clever to use `val = [val]` to process dict values in the same way as list values.
Comment: Thanks, this works. I just realized, that in my actual data, the key's are repeating across different subdicts within a list. Because of this, the final flattened output had only the last subdict (overwriting the ones above it).
Comment: Not a good solution. For example for nested = {'asd': [{'a': 'hi'}, {'a': 'hi2'}]} you will lose the value 'hi'. And crash for lists of non-dicts for example: nested = {'asd' : ['a', 'b' ] }
Comment: @DanielBraun: you're correct that for inputs which are shaped differently from the OP's, you'll need a different solution. That's.. not unexpected.
Comment: @DSM I presumed the unique field naming was ops way of conveying the idea and not a known attribute of the input
Comment: This was neat - I have been trying to test a nested `dotmap.DotMap`/`OrderedDict`/`dict`  for custom/non-builtin types - and rather than traversing it I first convert it to a flattened object before the (now easy) loop over the values - thank you
Answer: In my project, I am using an updated version of function from DSMs answer to flatten dict which may contain other dict or list or list of dict. I hope it will be helpful.
def flatten(input_dict, separator='_', prefix=''):
    output_dict = {}
    for key, value in input_dict.items():
        if isinstance(value, dict) and value:
            deeper = flatten(value, separator, prefix+key+separator)
            output_dict.update({key2: val2 for key2, val2 in deeper.items()})
        elif isinstance(value, list) and value:
            for index, sublist in enumerate(value, start=1):
                if isinstance(sublist, dict) and sublist:
                    deeper = flatten(sublist, separator, prefix+key+separator+str(index)+separator)
                    output_dict.update({key2: val2 for key2, val2 in deeper.items()})
                else:
                    output_dict[prefix+key+separator+str(index)] = value
        else:
            output_dict[prefix+key] = value
    return output_dict

Answer: Updated DSMs answer to support a list of dictionaries with the same keys by concatenating the index with the key without adding much complexity to code.
code:
def flatten(d):
    out = {}
    for key, val in d.items():
        if isinstance(val, dict):
            val = [val]
        if isinstance(val, list):
            for subidx, subdict in enumerate(val):
                deeper = flatten(subdict).items()
                out.update({key + f'_{subidx}' + '_' + key2 + f'_{idx}': val2
                            for idx, (key2, val2) in enumerate(deeper)})
        else:
            out[key] = val
    return out

Input:
nested = {'a': 1,
          'b': 2,
          'c': {'c1': [{'c11': 1, 'c12': 2, 'c13': 3}, {'c21': 1, 'c22': 2, 'c23': 3}],
                'd1': [{'dd1': 1, 'dd2': 2}, {'dd1': 3, 'dd2': 4}]}, # same keys
          'x': [{'xx1': 1, 'xx2': 2}, {'xx1': 3, 'xx2': 4}], # same keys
          'y': 2}

Output:
{'a': 1,
 'b': 2,
 'c_0_c1_0_c11_0_0': 1,
 'c_0_c1_0_c12_1_1': 2,
 'c_0_c1_0_c13_2_2': 3,
 'c_0_c1_1_c21_0_3': 1,
 'c_0_c1_1_c22_1_4': 2,
 'c_0_c1_1_c23_2_5': 3,
 'c_0_d1_0_dd1_0_6': 1,
 'c_0_d1_0_dd2_1_7': 2,
 'c_0_d1_1_dd1_0_8': 3,
 'c_0_d1_1_dd2_1_9': 4,
 'x_0_xx1_0': 1,
 'x_0_xx2_1': 2,
 'x_1_xx1_0': 3,
 'x_1_xx2_1': 4,
 'y': 2}


Finding Number of Ordered Solutions to Equation

Question: $$  A \times B \times C \times D \times E \times F = 7 \times 10^7 $$
How can I find the number of ordered solutions for integers (I mean for integers $A,B,C,D,E,F$) so that they can satisfy the above equation?
Answer: The factorization of $7 \times 10^7 $ is simply $2^7 \times 5^7 \times 7 $.
Suppose for now we restrict the search for positive integer solutions only.
For non-negative integers $x_i, y_i, z_i $, let $A = 2^{x_1} \cdot 5^{y_1} \cdot 7^{z_1}, B = 2^{x_2} \cdot 5^{y_2} \cdot 7^{z_2} , \ldots, F = 2^{x_6} \cdot 5^{y_6} \cdot 7^{z_6} $.
Then their product is $2^7 \times 5^7 \times 7^1 = 2^{\sum_{j=1}^6 x_j} \times 5^{\sum_{j=1}^6 x_j} \times 7^{\sum_{j=1}^6 x_j} $.
$ \Rightarrow \displaystyle \sum_{j=1}^6 x_j = 7, \sum_{j=1}^6 y_j = 7, \sum_{j=1}^6 z_j = 1 $.
By Stars and Bars, like TravisJ pointed out, we have $ {7+6 - 1 \choose 6-1} = {12 \choose 5} $ ordered solution for $<x_i>$ and $<y_i>$, and ${1+6 - 1 \choose 6-1} = 6 $ ordered solution for $<z_i>$.
Multiplying them together gives a total of $ {12 \choose 5} ^2 \times 6 = 3763584 $ ordered solution for positive integers $A$ to $F$.
If we drop the constraint for positive integers, then we could have:
Case 1: 6 Positive integers
Case 2: 4 positive integers, 2 negative integers
Case 3: 2 positive integers, 4 negative integers
Case 4: 6 Negative integers
Combining all these cases together yields a total of
$3763584 \times \left [ {6 \choose 0} + {6 \choose 2} + {6 \choose 4} + {6 \choose 6} \right ] = 120434688 $ ordered solutions.
Comment: @Fermat Thank You. Hopefully it helps the OP.
Comment: Is that the final answer?
Comment: Yes if that's what youre looking for
Answer: This is essentially the same as: How many ways are there to express a number as the product of groups of three of its factors? except instead of needing 3 distinct numbers you need 6.
First, factor $7\times 10^{7}=2^{7}5^{7}7^{1}$.  Then apply the idea there.  Keep in mind that your stars and bars method has a $5$ bars instead of $2$ in the solution.  I'll let you read the post to see why it is true, but the final answer will be $\binom{7+5}{5}\binom{7+5}{5}\binom{1+5}{5}$.


Prototype Js : How to iterate over some of the Json objects

Question: How to iterate over this kind of Json object in Prototype Js ( not Jquery)
There are also sub objects with value indexs
I want to populate multi select box with given values.
data = object(
    0 => object(
        'label' = > 'test1',
        'value' = > 1
    ),
    1 => object(
        'label' = > 'test1',
        'value' = >
        0 = > object(
            'label' = > 'sub testing1',
            'value' = > 1
        ),
        1 = > object(
            'label' = > 'sub testing2',
            'value' = > 1
        ),
    ),
    3 = > object(
        'label' = > 'test3',
        'value' = >
        0 = > object(
            'label' = > 'sub testing - test 3',
            'value' = > 33
        ),
    )
)

Answer: I haven't used Prototype in a while but try this:
data.each(function(i){
    console.log(i.label); // or whatever you need to do
});

Comment: @ShahidNajamAfridi - you understand this code does exactly what you are asking.  You are the one who is being rude.
Comment: I don't want one line code. i want to parse value and label to populate multiselect.
Comment: So go ahead and write that code. We're not going to do all of your work for you.
Comment: Don't be rude. Ok? you understand?
Comment: I didn't ask you to do that. OK. Get lost