text:
Q: Is there a name for era(s) between Old Republic in KOTOR and Clone Wars? Certain eras in TGFFA are well defined (both in-universe, as well as out-of-universe in terms of publishing) and are named, e.g. Old Republic era (KOTOR time), Clone Wars era, New Republic era, etc...
Are there named eras between the time of Old Republic described in KOTOR and Old Republic MMO; and Clone Wars era? If so, what bundles of EU material cover them (the way NJO books cover that era, or Legacy and Downfall books the Legacy era?)

A: According to Wookieepedia, the time period between Knights of The Old Republic and The Phantom Menace overlaps with four broad periods of Galactic History:
Old Sith Wars: 4000 BBY1 - 3950 BBY
This period is dominated by conflicts with various Sith Lords (hence the name), and opens with the events of the Tales of the Jedi comic series. Knights of the Old Republic picks up at the tail end of this period, with the main story of the first game starting in  3956 BBY.

*

*The Knights of the Old Republic video game and its sequel

*The Knights of the Old Republic comic series takes place before the video games, near the end of the Mandalorian Wars. The sequel miniseries Knights of the Old Republic: War is also during this period

*Two eBooks in the Lost Tribe of the Sith series take place in this era: Purgatory and Sentinel
Inter-Sith Wars Period: 3950 BBY - 2000 BBY
The events of SW:TOR occur entirely within this period; although we don't know exactly when the game will end, it's probably safe to assume that it won't last for two thousand years. The most recent TOR expansion, Shadow of Revan, takes place in 3640 BBY.
There's very little fiction that takes place during this period; most of the information we have on it comes from The Essential Atlas, which was intended to be a definitive source for planetary information. Some information can also be found in material related to The Old Republic MMO, especially in-game codex entries.

*

*The Old Republic prose series takes place at the end of this period, as does The Old Republic comic series

*Three of the eBooks in the Lost Tribe of the Sith series take place post-TOR: Pantheon, Secrets, and Pandemonium. The comic miniseries Lost Tribe of the Sith: Spiral also takes place in this period. This series was a tie-in to the Fate of the Jedi series, which takes place in the Legacy period

Draggulch Period: 2000 BBY - c. 1000 BBY
This period coincides almost entirely with the New Sith Wars, and the last century of this period is sometimes called the Republic Dark Age.
Once again, there's very little fiction set in this period. Most information comes from Essential guides and RPG sourcebooks.

*

*Knight Errant, the novel and the comic series

*The first novel in the Darth Bane Trilogy, Path of Destruction
Post-Ruusan Period: c. 1000 BBY - 19 BBY
Also sometimes called the Great Peace of the Republic, Wookieepedia technically calls this the "Fall of the Republic/Rise of the Empire Period." In-universe, this period begins with the Ruusan Reformation, a structural reorganization of the Jedi Order, and the Republic itself to a lesser extent, so significant that it became year 0 in the (in-universe) Galactic calendar. The first 700 or so years of this period is also called the Golden Age of the Old Republic.

*

*The Darth Bane Trilogy concludes in this era

*Star Wars: Jedi, a comic book series about Qui-Gon Jinn's relationship with his first apprentice

*Legacy of the Jedi and it's sequel, Secrets of the Jedi, mostly take place in this period. The last section of each book is set during the Clone Wars

*Jedi Council: Acts of War, a comic book miniseries set shortly before Phantom Menace

*The Jedi Apprentice series, a series of 18 "young reader" novels detailing Obi-Wan Kenobi's apprenticeship under Qui-Gon Jinn

*Qui-Gon and Obi-Wan: The Autorient Express and Last Stand on Ord Mantell

*There were several works focused on the exploits of Darth Maul, including the novels Shadow Hunter and Lockdown, and the Darth Maul comic series

*The Episode I Adventures series of youth novels

*The Star Wars: Republic comics begin in 33 BBY, and carry through until shortly after the events of Revenge of the Sith

*The Jedi Quest series, a young reader's series in the style of Jedi Apprentice; these books document Anakin Skywalker's early training

The above lists of works are incomplete by design. If you're interested in a more complete list of works, Wookieepedia has a helpful timeline of Legends media

1 Dates in Legends are typically based around the Battle of Yavin, the climactic battle in A New Hope, which is 0 ABY; BBY and ABY mean exactly what you'd expect them to

A: Not sure about named eras, but there's the battle of Ruusan/rise of Darth Bane, covered in the Darth Bane trilogy. It occurs 1000 years before the clone wars, so 2000 after the period covered in the Old Republic game. Introduces the sith 'rule of two', setting the stage somewhat for Sidious' rise to power

A: There is virtually no material covering the events between the end of Star Wars: The Old Republic and the beginning of the Darth Bane trilogy. The event we know about between the Galactic War and the New Sith Wars (which is the war that is featured in the Darth Bane trilogy) is referred to as the Darth Desolous conflict.

However, not only is this no longer considered canon due to the legends rebrand, it was also very flimsy from its inception. Its only reference is a databank entry in the Wii and Playstation 2 versions of The Force Unleashed.
However, the New Sith Wars mark the transition period between what (in legends material) is considered the Old Republic era and what is called the Rise of the Empire era.
A reference to mark the transition (more of a discrete event) is the Ruusan Reformation. This is the legends explanation to Chancellor Palpatine's remarks in Episode II.

"I will not let this Republic that has stood for a thousand years be split in two. My negotiations will not fail." - Chancellor Palpatine


text:
Q: List chat messages QuickBlox History Message It is possible to load all history message according to custom parameter.
Currently we set a according to setPageLimit. But i want to use a custom parameter.  . Custom parameter is sh_id,sh_r_id,customer_id, date
private void loadHistory(String dialogId){
    QBDialog qbDialog = new QBDialog(dialogId);
    QBRequestGetBuilder customObjectRequestBuilder = new QBRequestGetBuilder();
    customObjectRequestBuilder.setPagesLimit(150);

    QBChatService.getDialogMessages(qbDialog, customObjectRequestBuilder, new QBEntityCallbackImpl<ArrayList<QBChatHistoryMessage>>() {
        @Override
        public void onSuccess(ArrayList<QBChatHistoryMessage> messages, Bundle args) {

            try {
                qbShopAdpt = new QBShopkeeperChatAdapter(mContext, new ArrayList<QBMessage>(),customer_id,sh_r_id1);
                qbchatlv.setAdapter(qbShopAdpt);
                for(QBMessage msg : messages) {
                    if(customer_id.equals(msg.getProperty("customer_id")) && sh_r_id1.equals(msg.getProperty("sh_r_id")) && SessionManager.getSignIn(mContext).getId()==Integer.valueOf(msg.getProperty("sh_id"))){
                        showMessage(msg);
                    }
                }
            } catch (NullPointerException e) {
                Log.e(Tag, e.toString());
            }catch (NumberFormatException e) {
                Log.e(Tag, e.toString());
            }catch (Exception e) {
                Log.e(Tag, e.toString());
            }
            hideProgress();
        }

        @Override
        public void onError(List<String> errors) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
            dialog.setMessage("load chat history errors: " + errors).create().show();
        }
    });
}

A: Try by this code for save chat may be this i am not shure
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setProperty("save_to_history", "1");

get chat by this
QBDialog qbDialog = new QBDialog("53cfc593efa3573ebd000017");
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.setPagesLimit(100);
QBChatService.getDialogMessages(qbDialog, customObjectRequestBuilder, new
QBEntityCallbackImpl<ArrayList<QBChatMessage>>() {
@Override
public void onSuccess(ArrayList<QBChatMessage> messages, Bundle args) {
 }
 @Override
public void onError(List<String> errors) {

}
});

Try By this code it may be help you try by this link.
Here is Link

redpajama_set_name: RedPajamaStackExchange


text:
Q: OSM editing in JOSM Finally i want to make my own local intranet map server with my changed tiles and nominatim. I just want to make an overview of security cameras in specific area of the map with geocoding (searching addresses).
In JOSM editor I downloaded the specific part of the map i want. Now i want to add new camera from presets to some place (no problem) with a symbol of a camera in the map (problem 1). Then what i want to do is to draw the area, which is monitored by this camera and fill this area with some color (problem 2). Then i want to save this map in osm format – load it to maperitive and generate tiles, which could look like my picture below. I tried to import to the map some picture with importimageplugin in JOSM, but after saving to osm format, loading to maperitive and rendering tiles, the picture wasn't on the tiles (problem 3). Is possible to add icon of a camera and draw colored area of its monitoring in JOSM or in some other software?
I just read tutorials about nominatim install, but now the most important thing is to make the tiles with the security cameras and areas which are monitored by these cameras, because i am not shure, that i am able to install the nominatim, so i will be satisfied with a slippy map.
Sorry for my bad english and knowledge of osm, i am a beginner. I appreciate every answer.
Picture 1 Picture 2


text:
Q: FadeOut content...load new content...FadeIN I want to FadeOut the current holder div, then load in the new content and fade it in.
Everything is working fine...content loads and fades In. I just don't know where and how to put the FadeOut part! So it Fades Out the current div, loads in the new content and then Fades that In!
Help?
$('.menu_home').click(function() {
    var href = $(this).attr('href');

    $('#pageContent').hide().load(href).fadeIn(2000);

    return false;
});

A: Use the callback from fadeOut:
$('#pageContent').fadeOut(2000, function() {
    $(this).load(href).fadeIn(2000);
})


text:
Q: Screen capture app that captures a window even when minimized? I'm looking for a mac app that captures the screen (video) on specific app window (for example, Safari), and keeps recording what that window sees even when minimized to the dock for example.
Or even if a finder window is over it (without recording that finder window).
Anyone knows an app that can achieve what I'm talking about?

A: You are making the assumption that windows are always updated when minimized. This is not the case. This also applies to apps present on other spaces.
In other words, this is not possible.

A: use debut video capture software, works for mac, for the feature you want, not for windows though.


text:
Q: Taking multiple picture with camera using Ionic Our App has a requirement to take multiple images and then display them for upload after the user has finished, Is this possible with IOS and Android camera.  Not seeing any examples.
I have looked at many Cordova plugins, all seem to either support taking one image or selecting multiple from the gallery, not allowing taking multiple images with the camera.
If you have done this or know if this is possible, please help

A: You can use  cordova-plugin-media-capture plugin.This plugin provides access to the device's audio, image, and video capture capabilities.

capture.captureImage
Start the camera application and return information about captured image files.
navigator.device.capture.captureImage(
            CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureImageOptions options]
        );
Description
Starts an asynchronous operation to capture images using the device's camera application. The operation allows users to capture more than one image in a single session.
The capture operation ends either when the user closes the camera application, or the maximum number of recordings specified by CaptureImageOptions.limit is reached. If no limit value is specified, it defaults to one (1), and the capture operation terminates after the user captures a single image.
When the capture operation finishes, it invokes the CaptureCB callback with an array of MediaFile objects describing each captured image file. If the user terminates the operation before capturing an image, the CaptureErrorCB callback executes with a CaptureError object featuring a CaptureError.CAPTURE_NO_MEDIA_FILES error code.

Example
  // capture callback
var captureSuccess = function(mediaFiles) {
    var i, path, len;
    for (i = 0, len = mediaFiles.length; i < len; i += 1) {
        path = mediaFiles[i].fullPath;
        // do something interesting with the file
    }
};

// capture error callback
var captureError = function(error) {
    navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};

// start image capture
navigator.device.capture.captureImage(captureSuccess, captureError, {limit:2});


text:
Q: In Vulkan how am I supposed to know if the buffer usage flag TRANSFER_SOURCE needs to be used? There's a bit of a chicken and the egg issue I'm dealing with. I create a buffer, and if that buffer is going to be allocated to device-local memory then there's the possibility that the memory type I can use for that buffer will NOT be host-visible, and so I need to set the VK_BUFFER_USAGE_TRANSFER_DST_BIT flag on the buffer, and use a host-visible staging buffer. The problem goes like this:
auto bufferUsageBits = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT /* | VK_BUFFER_USAGE_TRANSFER_DST_BIT*/;
// The second flag should be set only if the memory requirements queries later
// tell me there's no device-local AND host-visible memory types
VkBuffer vkBufferHandle;
VK::createBuffer(size, bufferUsageBits, VK_SHARING_MODE_EXCLUSIVE, &vkBufferHandle);

vkGetBufferMemoryRequirements();
// Only know do I now if I need a staging buffer and the buffer I'm creating needs to be transfered to.

I could do two things as far as I can see:

*

*If the device is integrated or CPU type then assume that the buffer won't need the transfer flag set.

*Set the flag anyway whether it's integrated/CPU or discrete.

How am I supposed to deal with this?

A: If you create a VkBuffer and the memory requirements for it are such that it needs to allow being the destination of a transfer operation, then... create a new VkBuffer with the destination transfer usage bit set (and delete the old one).
It's just a VkBuffer. It doesn't really do anything until its bound to memory. Indeed, it's a good idea in a real application to create multiple speculative buffers to figure out where you intend to arrange your buffer memory usage.


text:
Q: Bootstrap tags input not working with jquery I am using Bootstrap tags input to make tags inside text input,in the documentation:

Just add data-role="tagsinput" to your input field to automatically
  change it to a tags input field.

But when using jquery before function:
$('#addrun').click(function () {
            $('#addrun').before('<input type="text" value="Amsterdam,Washington,Sydney,Beijing" data-role="tagsinput" />');
        });

it is displayed like any text input with text inside and no tags.
any help ??

A: I made it working following ways. It was showing problem $(..).tagsinput() was not found and I could now update the tags with new values.
I removed first and last line from file bootstrap-tagsinput.js, that is '(function ($) {' and '})(window.jQuery)'.
And called the below two lines where tags was required to display and update.
$("input[data-role=tagsinput]").tagsinput('removeAll');
$("input[data-role=tagsinput]").tagsinput('add', 'New Value');

A: Bootstrap is run at page load as an self-executing function. By adding a new element to the DOM - By that time, bootstrap-tagsinput.js wouldn't know anything about it. So you'll have to Initialise it after adding it to the DOM document via JavaScript.
To refresh input tags (Bootstrap Tagsinput Docs):
$('input').tagsinput('refresh');

So for you, you'd need to:
/**
 * On <div id="addrun"> on click,
 * pre-apend it with an new Input
 *
 * Then refresh Bootstrap.
**/
$('#addrun').click(function(){

     $('#addrun').before(
         '<input type="text" '+
         'value="Amsterdam,Washington,Sydney,Beijing" '+
         'data-role="tagsinput" />'
     );

     //Now run bootstrap.js to re-search
     //new data-* elements
     $('input').tagsinput('refresh');
});

Hope that helps! Although, the above $('input') will refresh every <input> tag in the whole document, so you could instead give the prepended <input> tag an .class or an #ID for quicker access =)
Update:
As koala_dev did correctly mention within the comments, you probably wouldn't need to initialise it via $('selector').tagsinput('refresh') but rather just:
     $('#selecor').tagsinput();

.tagsinput('refresh') would normally be actioned on an .tagsinput() input that's already initialised with new options given.


text:
Q: JQuery. Remove a previous sibling in the DOM tree I have the next code dynamically created using JQuery. Theere are multiple row class divs placed one under the other.

    ....

    ....

After i create these divs I have a "pointer" to a specific div which is of class row. In JQuery, how do i make it so I go down the DOM tree, until i reach the div of class line_type and download_value and remove them both, and also I'd like to go one more node down, at the div of type email and change some of it's CSS attributes.
I was not able to find anything on the web, maybe it's cause i'm a noob at these still.

A: Assuming row_pointer points to the row in question:
$('.line_type, .download_value', row_pointer).remove();
$('.email', row_pointer).css(...);

A: I have a "pointer" to a specific div which is of class row ->
Assuming that you have the this object of the corresponding div with class row.. then you can use .find to get the line_type and download_value inside that div.
$(this).find('.line_type').remove();
$(this).find('.download_value').remove();

Then you can use the same .find to get the div with class email and access the .css
$(this).find('.email').css(/* You code*/);

A: check this out
$('div.row').bind('click', function() {
    $this = $(this);
    $('div.line_type, div.download_value', $this).remove();
      $('div.email', $this).css('background-color', 'red');
});

http://jsfiddle.net/YvyE3/


text:
Q: Handling a Many-to-Many Dimension when all dimensional values have 100% importance I'll at least try to keep this succinct.
Let's suppose we're tracking the balances of accounts over time.  So our fact table will have columns such as...
Account Balance Fact Table

*

*(FK)AccountID

*(FK)DateID

*...

*Balance

*...

Obviously you have an Account Dimension Table and a Date Dimension Table.  So now we can easily filter on Accounts or Dates (or date ranges, etc.).
But here's the kicker... Accounts can belong to Groups -- any number of Groups at a given Date.  Groups are simply logical abstractions, and they have no tangible meaning aside from reporting purposes.  An Account being in 0, 1, or 17 groups doesn't affect its Balance in any way.  For example, AccountID 1 may be in Groups 38, 76, 104, and 159.  Account 2 may be in Group 1 (which has a Group Description of "Ungrouped".  Account 3 may be in seventeen groups (real example).
As an added bonus, our users are completely non-technical.  They don't know SQL, they have no experience with relational databases, and have historically done all of their work in a convoluted Excel solution.  Right now we're building a dimensional model they can slice and filter with PowerPivot, though these Account Groups are threatening to turn an otherwise ruthlessly simple Star Schema into something complex enough that the users will balk and return to their current spaghetti solution.
So let's look at our options...
Boolean Method
The Boolean method is not feasible.  We have about 570,000 different accounts, but more importantly, 26,000 different groups.  This would also be a devil for end-users to filter, since they're non-technical and are relying on very simple tools to get this done.
Multiple Column Method
In theory this could work, however, we do have some accounts that belong to 17 groups.  Again, the groups are really just logical groups -- they have no meaning, but they are required by the business for reporting purposes.  Having end-users filter out groups from 17 different columns isn't going to go over well in user-acceptance, and would likely result in users refusing to use the solution (and I don't blame them).
Bridge Table
This count work, but we do have 26,000 different groups.  I'm not finding this to be user-friendly.
Since I'm not liking my options, I can only assume there's a better way other than snowflaking... unless snowflaking IS the only way.  If someone could lend a hand and explain their rationale it'd be appreciated.

UPDATE: For clarification, an example I think everyone here can relate to is imagine you can list keyword skills on a resume.  They all relate to the same person, but you can have any number of skills.  The skills don't effect any of individual measures on a resume -- i.e. 'C++' isn't more valuable than 'C#' -- you can't put all the resume/skill combinations in the fact table or you'd end up double counting (or well more than double ;) ).
I think the best I'm going to be able to do here is to create an outrigger table for groups.  I'm not a fan of it, but I think it's the only real option I have.
So now we have...
Account Balance Fact Table

*

*(FK)AccountID

*(FK)DateID

*...

*Balance

*...

Account Dimension

*

*(PK)AccountID

*Account Name

*...

*(FK)Account Group Key

Account Group Outrigger

*

*(PK)AccountGroupID

*(PK)AccountID)

*Account Group Name

A: I would say you've got to start from the interface.  How would users like to do their filtering in an ideal world?
I think I would end up going for a bridge or factless fact table or something like that.  Perhaps a surrogate key on the fact table and a many-many link table from that to group membership.
It's definitely tough - and the interface and usage cases has to be made workable, so I'd start from there.  Perhaps something will shake out of how they do this reporting - like equivalence classes in the groups or some way they partition the account space.  Maybe there is a hierarchy or organization to the groups which make it more manageable and may inform a simpler design.

A: If I correctly understood your question this should be okay:
CREATE TABLE IF NOT EXISTS `accounts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `accounts_groups` (
  `account_id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL,
  `start_date` date NOT NULL,
  `end_date` date DEFAULT NULL,
  UNIQUE KEY `account_group` (`account_id`,`group_id`,`start_date`),
  KEY `group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE IF NOT EXISTS `account_balances` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_id` int(11) NOT NULL,
  `date` date NOT NULL,
  `balance` decimal(11,2) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `account_id` (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

ALTER TABLE `accounts_groups`
  ADD CONSTRAINT `accounts_groups_ibfk_1` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`),
  ADD CONSTRAINT `accounts_groups_ibfk_2` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`);

ALTER TABLE `account_balances`
  ADD CONSTRAINT `account_balances_ibfk_1` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`);


text:
Q: Defining a ring homomorphism from $\mathbb{C}\left [ x_1, \dots, x_n \right ]/\left ( f_1, \dots, f_r \right )$ I am working on a problem in Artin's Algebra related to the algebraic geometry talked in Chapter 11. The problem number is 9.2., F.Y.I.
Here goes the problem:

Let $f_1, \dots, f_r$ be complex polynomials in the variables $x_1, \dots, x_n$, let $V$ be the variety of their common zeros, and let $I$ be the ideal of the polynomial ring $R = \mathbb{C}\left [ x_1, \dots, x_n \right ]$ they generate. Define a ring homomorphism from the quotient ring $\bar{R} = R/I$ to the ring $\mathcal{R}$ of continuous, complex-valued functions on $V$.

I attempted to use the correspondence theorem w.r.t. the variety of a set of polynomials, i.e. the maximal ideals bijectively correspond to the point in $V$ and we may somehow define the continuous functions there. However I cannot come up with any idea further. Also, the term 'continuous' here seems redundant since I expect the homomorphism will carry polynomials to polynomials.
I appreciate your participation and will be thankful to anything from hints to full solution.

A: It's easier than it looks.  To each element $h + I$ in $R/I$, associate the function $\phi: V \rightarrow \mathbb{C}$ by setting
$$\phi(t_1, ... , t_n) = h(t_1, ... , t_n)$$
for every $(t_1, ... ,t_n)$.  Check that this doesn't depend on the specific coset representative you use.

A: You can define $\psi\colon\mathbb{C}[x_1,x_2,\dots,x_n]\to\mathcal{R}$ by defining $\psi(g)$, for $g\in\mathbb{C}[x_1,x_2,\dots,x_n]$, as
$$
\psi(g)\colon (t_1,\dots,t_n)\in V\mapsto g(t_1,\dots,t_n)\in\mathbb{C}
$$
It's easy to see that $\psi(g)$ is continuous and that $\psi$ is a ring homomorphism.
Since $f_1,f_2,\dots,f_r\in\ker\psi$, we have $I\subseteq\ker\psi$. Therefore the homomorphism factors through $\mathbb{C}[x_1,x_2,\dots,x_n]/I$: there exists a unique ring homomorphism $\phi\colon\mathbb{C}[x_1,x_2,\dots,x_n]/I\to\mathcal{R}$ such that $\phi\circ\pi=\psi$, where $\pi\colon\mathbb{C}[x_1,x_2,\dots,x_n]\to\mathbb{C}[x_1,x_2,\dots,x_n]/I$ is the canonical map to the quotient ring.


text:
Q: KeyEvent not being generated by JFrame java? I have a java program with a JFrame and 3 JButtons in it. I have added a keylistener to jframe. When i run the program a jframe window is opened and the first button is selected by default. My problem is that a KeyEvent is not being generated by this JFrame.
Now, besides adding a KeyListener to the jframe, i also added a KeyListener to the buttons.
Now the keyevent is being generated by the buttons.
How do I make the JFrame generate KeyEvent instead of the JButton generating them ??
Actually, my main purpose is building keyboard shortcuts for the buttons.

A: The key event is called on the currently focused component (which is usually not the JFrame)

A: Have a look here How to Use Key Bindings.
An alternative to keylistener.
Here is a little Example it has a Button with focus and process a KeyEvent (F2).
On F2-clicked the Key-Binding process a ButtonClick which performed a System.out print.
public class Example {
    static public void main( String[] s ) {
        EventQueue.invokeLater( new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.getContentPane().setLayout( new BorderLayout() );
                frame.setBounds( 50, 50, 600, 600 );
                frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                final JButton button = new JButton( new AbstractAction("MyButton") {
                    @Override
                    public void actionPerformed( ActionEvent e ) {
                        System.out.println("Button Clicked");
                    }
                });
                frame.getContentPane().add( button );
                frame.getRootPane().setDefaultButton( button );

                KeyStroke f2 = KeyStroke.getKeyStroke("F2");
                frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(f2, "clickButton");
                frame.getRootPane().getActionMap().put("clickButton", new AbstractAction() {
                    @Override
                    public void actionPerformed( ActionEvent e ) {
                        button.doClick();
                    }
                });
                frame.setVisible( true );
                // the Button has the focus
                button.requestFocus();
                // generate a KeyEvent 'F2'
                KeyboardFocusManager.getCurrentKeyboardFocusManager().dispatchKeyEvent( new KeyEvent( frame, KeyEvent.KEY_PRESSED, 0, f2.getModifiers(), f2.getKeyCode(), f2.getKeyChar() ) );
            }
        });
    }
}


text:
Q: Bluetooth and Fingerprint ApI in android studio I needed a help can anyone suggest me if it is possible to implement both
Bluetooth API and Fingerprint API in android studio for a particular project and
some advice please.
Thanks.


text:
Q: How to clear ssh keys from windows that are used by git to login? I learned from other questions here (please correct me if I am wrong), that github identifies users based on the ssh keys that it sees on my computer (in the .ssh folder). Now, here's an odd one:
I have 2 regular, free, github accounts. Let's say they're Auser and Buser.
At the moment I'm not really using Buser, and I need to only use Auser. In the past, I have used Buser as well.
Currently in my .ssh folder I have only 2 files id_rsa and its corresponding id_rsa.pub. I know I'm not supposed to keep by pub like around like this, but that's beside the point at the moment.
So, I went to Auser's setting page on github and uploaded the pub. Next thing I do is check that everything is set properly so I:
$ ssh -T git@github.com
Hi userA! You've successfully authenticated, but GitHub does not provide shell access.

So far, so good, so I start working, stage, commit, push, no errors. Then I check my work on github:

Buser commited 2 minutes ago

I figure that probably Buser has the same ssh key set up, even though I read that github doesn't allow, and prevents this to happe. I login to github in browser with Buser to check what key is set up. I was already kind of excited that I was found a bug in github which allowed me to use the same key on 2 accounts. Not little was my surprise when I saw that no key is actually saved Buser's settings under SSH keys.
More, possibly relevant details:

*

*Buser, or the email associated with Buser is nowhere in git config settings, not at global level, not at repository level.

*No github related credentials are saved in Windows, unless they are saved with a completely different name that doesn't resemble github.

*Buser does not have push permissions to the newly created repository of Auser, to which it obviously pushed.
My foremost problem is that I can't push under Auser, but my curiosity is more on how am I able to push as Buser to the repository owned by Auser, without Buser even having any ssh key set up?
Are there any other mechanism by which git bash uses to login to github, in order to push, apart from ssh keys?


text:
Q: weird issue - cssSelector unable to find objects using css structure I am facing a weird issue when locating elements using cssSelector with webdriver.
On a fresh environment that I setup on Windows, cssSelector is unable to find objects when the identification is done using the structure of the CSS – for example findElement(By.cssSelector(elementId > div(1) > span(1))).
Identification works fine if done by id only - findElement(By.cssSelector(elementId)).
We are using WebDriverWait everywhere, so it's not a timing issue. In fact, it's not even waiting for the specified interval. It quits within milliseconds with error similar to the stack trace given at the bottom.
The same code runs fine on all fresh Linux environments and my old Windows environment. I have followed the same environment setup steps everywhere.

*

*Get Eclipse Java EE Helios SR2

*Install Maven from the 'Help > Install New Software' option – http://m2eclipse.sonatype.org/sites/m2e

*Setup TestNG from the 'Help > Install New Software' option – http://beust.com/eclipse

*Set the -vm argument in eclipse.ini

*Import my project into eclipse – thus the same maven version, TestNG version etc. gets specified everywhere.

Any idea why this is happening on all Windows environments that I am setting up now?
STACK TRACE SAMPLE

org.openqa.selenium.WebDriverException: Unable to find element with
  css selector == #GraphicalPane > div:nth-of-type(1) >
  div:nth-of-type(1) > img (WARNING: The server did not provide any
  stacktrace information) Command duration or timeout: 344 milliseconds
  Build info: version: '2.19.0', revision: '15848', time: '2012-02-08
  16:25:03' System info: os.name: 'Windows 7', os.arch: 'x86',
  os.version: '6.1', java.version: '1.6.0_25' Driver info:
  driver.version: RemoteWebDriver   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at
  org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:170)
    at
  org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:123)
    at
  org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:439)
    at
  org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:226)
    at
  org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:291)
    at org.openqa.selenium.By$ByCssSelector.findElement(By.java:406)    at
  org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:218)
    at my.domain.product.webconsole.Hardware$10.apply(Hardware.java:589)
    at my.domain.product.webconsole.Hardware$10.apply(Hardware.java:1)
    at
  org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:201)
    at
  my.domain.product.webconsole.Hardware.findobject1(Hardware.java:587)
    at
  my.domain.product.testsuite.testcase1(HardwareApplianceRack.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)     at
  org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)   at
  org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)    at
  org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)  at
  org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at
  org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)    at
  org.testng.TestRunner.run(TestRunner.java:617)    at
  org.testng.SuiteRunner.runTest(SuiteRunner.java:334)  at
  org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)  at
  org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)   at
  org.testng.SuiteRunner.run(SuiteRunner.java:240)  at
  org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)  at
  org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)   at
  org.testng.TestNG.runSuitesSequentially(TestNG.java:1197)     at
  org.testng.TestNG.runSuitesLocally(TestNG.java:1122)  at
  org.testng.TestNG.run(TestNG.java:1030)   at
  org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)     at
  org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)  at
  org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

A: instead of
(elementId > div(1) > span(1))

try using
elementId>div:first-child>span:first-child

Have you checked e.g. in firepath whether you element has been located properly?


text:
Q: Can't find my App in Google Android market I have published an app with this AndroidManifest.xml:
<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="false"
/>
<uses-sdk android:minSdkVersion="3" />

and with publish options

Copy Protection = ON (Helps prevent copying of this application from
  the device. Increases the amount of memory on the phone required to
  install the application.), Locations = all Locations

but i found that some device can't find it in the market, including Acer liquid, Sony Ericsson x10 mini pro, and even a Samsung Galaxy S
Any suggestions?

A: Screen sizes are just one factor that's taken into account when deciding whether an application should show up in Android Market.
In particular, <uses-feature> tags in your manifest can also cause your application to become hidden. Even if you aren't declaring any of these, certain <uses-permission> tags can cause features to get implicitly required.
For example, if you request the android.permission.CAMERA permission, the android.hardware.camera.autofocus feature will automatically get required unless you say otherwise. Not all devices have a hardware autofocus, and your application won't be shown on these devices.
See the documentation on <uses-feature> for more info: http://developer.android.com/guide/topics/manifest/uses-feature-element.html
Also, keep in mind that if you have copy protection (aka forward-locking) enabled, your application won't show up on certain devices. The recommended alternative is to use the Android licensing service:
http://android-developers.blogspot.com/2010/07/licensing-service-for-android.html
(It's also worth noting that forward-locking will be disappearing in a few months, so you definitely should look at the licensing service if you're concerned about this. See the blog post I linked to above for more information.)


text:
Q: Make sure that HomePage is under your MultiProvider/Provider. This usually happens when you are creating a When I sing in from HomePage this happen
Error: Could not find the correct Provider above this HomePage Widget
This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:

*

*You added a new provider in your main.dart and performed a hot-reload.
To fix, perform a hot-restart.

*The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.

*You used a BuildContext that is an ancestor of the provider you are trying to read.
Make sure that HomePage is under your MultiProvider/Provider.
This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // Will throw a ProviderNotFoundError, because `context` is associated
    // to the widget that is the parent of `Provider<Example>`
    child: Text(context.watch<Example>()),
  ),
}

consider using builder like so:
Widget build(BuildContext context) {
  return Provider<Example>(
    create: (_) => Example(),
    // we use `builder` to obtain a new `BuildContext` that has access to the provider
    builder: (context) {
      // No longer throws
      return Text(context.watch<Example>()),
    }
  ),
}

this is my main.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cor/%20crud/addproduct.dart';
import 'package:flutter_cor/home/homepage.dart';
import 'package:flutter_cor/login.dart';
import 'package:flutter_cor/providers/product_provider.dart';
import 'package:flutter_cor/providers/user_provider.dart';
import 'package:flutter_cor/signup.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
import 'package:splashscreen/splashscreen.dart';

import 'ProductOverview.dart';
import 'Colors.dart';

bool islogin;

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
var user = FirebaseAuth.instance.currentUser;
if (user == null) {
  islogin = false;
} else {
  islogin = true;
}
runApp( MaterialApp(

    debugShowCheckedModeBanner: false,
    home: new MyApp(),
    theme: ThemeData(

        primaryColor: prColor,
        scaffoldBackgroundColor: scaffoldBackgroundColor,
        textTheme: TextTheme(
            headline6: TextStyle(fontSize: 20, color: Colors.white))),
    routes: {
      "login": (context) => Login(),
      "signup": (context) => SignUp(),
      "homepage": (context) => HomePage(),
      "addproduct": (context) => AddProduct(),
      "productOverview" :(context)=> ProductOverview(),
    }));
}

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
  return   SplashScreen(
      useLoader: false,
      seconds: 7,
      backgroundColor: Colors.white,
      image: new Image.asset("images/market.gif"),
      photoSize: 220,
      navigateAfterSeconds: ForSplash(),
    );

}
}

class ForSplash extends StatelessWidget {
@override
Widget build(BuildContext context) {
  return MultiProvider(providers: [
  ChangeNotifierProvider<ProductProvider>(
  create: (context)=>ProductProvider(),),

    ChangeNotifierProvider<UserProvider>(
      create: (context)=>UserProvider(),),

  ],
  child: Builder(
    builder:(BuildContext newContext){
     return  islogin == false? Login():HomePage();
    }
  )

  );
}
}

I dont understand what doing please help me


text:
Q: datapicker in typescript won't see d.ts mapping when using the JQueryUI to have a datapicker I referenced the included the JQueryUI.js file in a script tag and then had the code below in the "onLoad" function.
$(function () {
    // initialize the JQuery datepicker to use our standard dd MMM yyyy format
    let x = $(".datepicker").datepicker({
        dateFormat: "d M yy"
    });
});

Now that I'm moving to typescript, I have downloaded the typescript mappings file and included it in the typings folder just like the JQuery.d.ts but the project won't compile because it says ".datepicker does not exist in JQuery"
Any thoughts on what is happening?

A: Since the datepicker() method is not part of jQuery, the definition won't contain it. Try adding the definition for jQuery UI too!
Typings:
typings install dt~jqueryui --save --global

Tsd:
tsd install jqueryui --save

Or the file: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/jqueryui


text:
Q: Creating list and elements with specific id in firebase with angularJS I'm trying to create the following structure in Firebase with its AngularJS API, without any success:
For example, in the https://something.firebaseio.com/
+ {element: "node"}        // https://something.firebaseio.com/element
+ {array:                  // https://something.firebaseio.com/array
          {Name1: "element#1"},   // https://something.firebaseio.com/array/Name1
          {Name2: "element#2"}
  }

Also, what is the correct method to set/get these values from Firebase?
I'm doing it this way, but it seems wrong:
$scope.app = $firebase(new Firebase("https://something.firebaseio.com/"));
$scope.array = app.$child('array');
$scope.array.$push({Name1: "element#1"}); // I know it creates uid in firebase for this object
$scope.app.$set({element: "node"});

please let me know in the comments if it's still not clear
thanks,


text:
Q: Showing ProgressBar while next activity loads I have an activity called PasswordActivity.  Once the user inputs the correct password, the next activity is started using the startActivity method.  The next activity takes a while to launch because there are some tasks that must be performed before the UI is ready.  I don't want the user to think that the app froze at the PasswordActivity, so I want to add some kind of progress bar.  I would like to make the progress bar show actual progress of the next activity's loading progress, not just a spinning bar.  Can I do this in the PasswordActivity or in a splash screen loading activity between the activities, or is this not possible?

A: depends on your nature of work you are doing
if using Asynctask
                 new AsyncTask<String, String, String>() {
                    @Override
                    protected void onPreExecute() {
                        mProgresDialog = ProgressDialog.show(LauncherActivity.this,"App Name","Loading...");
                        super.onPreExecute();
                    }

                    @Override
                    protected String doInBackground(String... strings) {
                        //To Do
                        return status;
                    }

                    @Override
                    protected void onPostExecute(String mStrStatus) {
                        super.onPostExecute(mStrStatus);
                        if(mProgresDialog != null && mProgresDialog.isShowing()){
                            mProgresDialog.dismiss();
                        }
                    }
                }.execute("");

A:  btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              progressdialog.show();
                Intent in= new Intent(aa.this,
                     bb.class);
                startActivity(in);
          progressdialog.dismiss();
                finish();
            }
        });


text:
Q: Swapping two items in a javascript array
Possible Duplicate:
Javascript swap array elements

I have a array like this:
this.myArray = [0,1,2,3,4,5,6,7,8,9];

Now what I want to do is, swap positions of two items give their positions.
For example, i want to swap item 4 (which is 3) with item 8 (which is 7)
Which should result in:
this.myArray = [0,1,2,7,4,5,6,3,8,9];

How can I achieve this?

A: Just reassign the elements, creating an intermediate variable to save the first one you over-write:
var swapArrayElements = function(arr, indexA, indexB) {
  var temp = arr[indexA];
  arr[indexA] = arr[indexB];
  arr[indexB] = temp;
};
// You would use this like: swapArrayElements(myArray, 3, 7);

If you want to make this easier to use, you can even add this to the builtin Array prototype (as kennebec@ suggests); however, be aware that this is generally a bad pattern to avoid (since this can create issues when multiple different libraries have different ideas of what belongs in the builtin types):
Array.prototype.swap = function(indexA, indexB) {
   swapArrayElements(this, indexA, indexB);
};
// You would use this like myArray.swap(3, 7);

Note that this solution is significantly more efficient than the alternative using splice(). (O(1) vs O(n)).

A: You can just use a temp variable to move things around, for example:
var temp = this.myArray[3];
this.myArray[3] = this.myArray[7];
this.myArray[7] = temp;

You can test it out here, or in function form:
Array.prototype.swap = function(a, b) {
  var temp = this[a];
  this[a] = this[b];
  this[b] = temp;
};

Then you'd just call it like this:
this.myArray.swap(3, 7);

You can test that version here.

A: The return value from a splice is the element(s) that was removed-
no need of a temp variable
Array.prototype.swapItems = function(a, b){
    this[a] = this.splice(b, 1, this[a])[0];
    return this;
}

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

alert(arr.swapItems(3, 7));

returned value: (Array)
    0,1,2,7,4,5,6,3,8,9


text:
Q: Add new shipping method in NopCommerce I want to add new shipping methods in the Shipping step, during check out process. Where in Admin section should I add them? And How? So far I tried in Config > Shipping > Shipping Methods section. But it didn't help me.

A: You have to develop new Plugin for your new shipping Method. If you cannot find your desired shipping method in the nopcommerce marketplace. Once you develop plugin you have to install and then there will be your shipping method in in the checkout screen.


text:
Q: Sum of possible all possible $x$ such that $51 \equiv 3 \pmod{x}$ I was asked this  simple following question:

What is the sum of all positive integers $x$ such that :
  $$51\equiv 3 \pmod{x}$$

My answer is $118$ (and I am pretty sure it's right but would like to check because there are other answers also),
My solution is this :
$$51=kx+3 \Rightarrow 48=kx\quad $$ and $ x>3$ , therefore only $4,6,8,12,16,24,48$ are possible values for $x$ .
Have I missed anything?

A: $51 \equiv 3 \pmod x \iff 48 \equiv 0 \pmod x$
thus $x=1,2,3,4,6,8,12,16,24,48$ and their sum is
$S = 124$.

A: Why the restriction that $x>3$? It also works when $x\in\{1,2,3\}.$
Aside from that, it looks fine.

A: $51\equiv 3 \pmod x$ iff $x|51-3=48$. Divisors of $48$ are $1,2,3,4,6,8,12,16,24,48$ .


text:
Q: Magento backend - CMS edit page broken This is what I see when I browse cms edit page in magento:

This bug is not visible in cms block edit page or category/product edit pages. Just the CMS > Page.
I tried updating to the latest version (1.9.3.8) and disabling all extensions. Non of these worked. Also, there's no javascript error on page.
Any ideas how to fix this?

A: Make sure all CSS files have been updated to 1.9.3.8 in skin/adminhtml/default/default and try the site in incognito mode.
Make sure all layout and template files in app/code/design/adminhtml were replaced and cache flushed or var/cache directory deleted.
If you are using a custom adminhtml theme, disable it entirely.

A: The bug was caused by en extension called Magento Twitter Cards
(https://github.com/laurent35240/magento-twittercards).
Disabling all extensions in local.xml file did not disable the adminhtml layout that caused this issue.
In order to solve this I commented Twitter Cards tab in file
app/design/adminhtml/default/default/layout/twittercards.xml


text:
Q: Pandas: dynamically add rows before & after groups I have a Pandas data frame:
pd.DataFrame(data={"Value": [5, 0, 0, 8, 0, 3, 0, 2, 7, 0], "Group": [1, 1, 1, 1, 2, 2, 2, 2, 2, 2]})

   Value  Group
0    5.0      1
1    0.0      1
2    0.0      1
3    8.0      1
4    0.0      2
5    3.0      2
6    0.0      2
7    2.0      2
8    7.0      2
9    0.0      2

Also I calculated the cumulative sum with respect to two rows for each group:
{"2-cumsum Group 1": array([5., 8.]), "2-cumsum Group 2": array([7., 5.])}

E.g. array([5., 8.]) because array([5.0, 0.0]) (rows 0 and 1) + array([0.0 + 8.0]) (rows 2 and 3) = array([5., 8.]).
What I now need is to append exactly two rows at the beginning of df, in-between each group and at the end of df so that I get the following data frame (gaps are for illustration purposes):
    Value  Group
0    10.0      0    # Initialize with 10.0
1    10.0      0    # Initialize with 10.0

2     5.0      1
3     0.0      1
4     0.0      1
5     8.0      1

6     5.0      0    # 5.0 ("2-cumsum Group 1"[0])
7     2.0      0    # 8.0 ("2-cumsum Group 1"[1])

8     0.0      2
9     3.0      2
10    0.0      2
11    2.0      2
12    7.0      2
13    0.0      2

14    7.0      0    # 5.0 ("2-cumsum Group 2"[0])
15    5.0      0    # 8.0 ("2-cumsum Group 2"[1])

Please consider that the original data frame is much larger, has more than just two columns and I need to dynamically append rows with varying entries. E.g. the rows to append should have an additional column with "10.0" entries. Also, calculating the cumulative sum with respect to some integer (in this case 2) is variable (could be 8).
There are so many occasions where I need to generate rows based on other rows in data frames but I didn't find any effective solutions other than using for-loops and some temporary cache lists that save values from previous iterations.
I would appreciate some help.
Thank you in advance and kind regards.

My original code applied to the exemplary data, in case anybody needs it. It's very confusing and ineffective so only consider it if you really need to:
import pandas as pd
import numpy as np

# Some stuff
df = pd.DataFrame(data={"Group1": ["a", "a", "b", "b", "b"],
                        "Group2": [1, 2, 1, 2, 3],
                       "Group3": [1, 9, 2, 1, 1],
                       "Value": [5, 8, 3, 2, 7]})

length = 2
max_value = 20

g = df['Group1'].unique()
h = df["Group2"].unique()
i = range(1,df['Group3'].max()+1)

df2 = df.set_index(['Group1','Group2','Group3']).reindex(pd.MultiIndex.from_product([g,h,i])).assign(cc = lambda x: (x.groupby(level=0).cumcount())//length).rename_axis(['Group1','Group2','Group3'],axis=0)
df2 = df2.loc[~df2['Value'].isna().groupby([pd.Grouper(level=0),df2['cc']]).transform('all')].reset_index().fillna(0).drop('cc',axis=1)

values = df2["Value"].copy().to_numpy()
values = np.array_split(values, len(values)/length)
stock = df2["Group1"].copy().to_numpy()
stock = np.array_split(stock, len(stock)/length)

# Generate the "Group" column and generate the "2-cumsum" arrays
# stored in the "volumes" variable
k = 0
a_groups = []
values_cache = []
volumes = []
for e, i in enumerate(values):
        if any(stock[e] == stock[e-1]):
            if np.any(i + values_cache >= max_value):
                k += 1
                volumes.append(values_cache)
                values_cache = i
            else:
                values_cache += i
            a_groups.extend([k] * length)
        else:
            k += 1
            if e:
                volumes.append(values_cache)
            values_cache = i
            a_groups.extend([k] * length)
volumes.append(values_cache)
df2["Group"] = a_groups

print(df2[["Value", "Group"]])
print("\n")
print(f"2-cumsums: {volumes}")

"""Output

   Value  Group
0    5.0      1
1    0.0      1
2    0.0      1
3    8.0      1
4    0.0      2
5    3.0      2
6    0.0      2
7    2.0      2
8    7.0      2
9    0.0      2

2-cumsums: [array([5., 8.]), array([7., 5.])]"""


text:
Q: JSTL attributes persisting through tiles/jsp:include I am currently using JSTL and Tiles (though i'm pretty sure this problem is not tiles issue) for a web application.
I would like to, at the template level include a "setVars" file that is a simple file that include a slew of JSTL variables
e.g.
testPageVars.jsp
<c:set var="currentPage" value="testPage" scope="request" />
<c:set var="forward" value="newPage" scope="request" />
...
<c:set var="test" value="true" scope="request" />

this would be included somewhere on the main layout. However it seems as though these dont persist through a  or a  or a
It seems as though they dont get "compiled" (not sure if thats the correct word)
so in my mainLayout.jsp
<jsp:include page="testPageVars.jsp"/>
<c:if test="${test == 'true'}>
   TEST WORKED
</c:if>

does not function.
Any thoughts on how to get my desired effect? Currently the only solution I have come up with is moving those values into the Java (I'm using struts) and have them set there. Which doesn't scale as well as I would like.
EDIT
tiles-def.xml
<definition name="main.layout" path="/jsp/mainLayout.jsp">
        <put name="actionVars" value="/jsp/testVars.jsp"/>
    </definition>

mainLayout.jsp
    <tiles:insert attribute="actionVars"/>
    <c:if test="${test == 'true'}">
       TRUE TWICE
    </c:if>

testVars.jsp
<c:set var="test" value="true" scope="request"/>
<c:if test="${test == 'true'}">
    TRUE
</c:if>

A: Forgot to add the tag libs on the var file.


text:
Q: The roots of the equation $z^2+pz+q=0,$ where $p,q$ are complex numbers, are .. I am stuck with the following problem that says:

The roots of the equation $z^2+pz+q=0,$ where $p,q$ are complex numbers, are represented by the points $A,B$ on the complex plane. If  $OA=OB$ and $\angle AOB=2 \beta,$ where $O$ is the origin, prove that $$p^2=4q \cos^2 {\beta}$$.

My try: The roots of the equation $z^2+pz+q=0,$is given by $\frac12(-p+\sqrt{p^2-4q})$ and $\frac12(-p-\sqrt{p^2-4q})$
Let $z=\frac12(-p+\sqrt{p^2-4q}) $ and $\bar{z}=\frac12(-p-\sqrt{p^2-4q})$ . Then, the line $AB=z-\bar{z}=\sqrt{p^2-4q}$.
Now using the fact $OA=OB$ and $\angle AOB=2 \beta,$ I get $$2 \beta=\arctan \frac{\sqrt{p^2-4q}}{p}+\arctan \frac{\sqrt{p^2-4q}}{p} \implies \beta=\arctan \frac{\sqrt{p^2-4q}}{p}$$.After deduction, I get from here $$p^2=(2p^2-4q)\cos^2\beta$$.
Now, I am stuck. Can someone help?

A: Let $A(z_1)$,$B(z_2)$, $z_1=r(\cos\theta_1+i\sin\theta_1)$, $z_2=r(\cos\theta_2+i\sin\theta_2)$ and $\theta_1-\theta_2=2\beta$,
where $r\geq0$ and $\{\theta_1,\theta_2\}\subset[0,2\pi).$
Thus, $$q=z_1z_2=r^2(\cos(\theta_1+\theta_2)+i\sin(\theta_1+\theta_2))$$ and
$$-p=z_1+z_2=r(\cos\theta_1+\cos\theta_1+i(\sin\theta_1+\sin\theta_2))=$$
$$=2r\left(\cos\frac{\theta_1+\theta_2}{2}\cos\beta+i\sin\frac{\theta_1+\theta_2}{2}\cos\beta\right)=2r\cos\beta\left(\cos\frac{\theta_1+\theta_2}{2}+i\sin\frac{\theta_1+\theta_2}{2}\right).$$
Id est,$$p^2=4r^2\cos^2\beta\left(\cos\frac{\theta_1+\theta_2}{2}+i\sin\frac{\theta_1+\theta_2}{2}\right)^2=$$
$$=4r^2\cos^2\beta(\cos(\theta_1+\theta_2)+i\sin(\theta_1+\theta_2))=4q\cos^2\beta$$
and we are done!

A: $p$ and $q$ are complex,
so you have to look at
the real and imaginary parts
of $p$ and
$\sqrt{p^2-4q}$
to get
$z-\bar{z}$.


text:
Q: How to setup VS Code for dart I am developing a project with flutter. But I recently wanted to make a pure dart project. So I pressed "Dart: New Project" on visual studio code. It gave me these options to choose from:

*

*AngularDart Web App,

*Bare-bones Web App,

*Console Application,

*Dart Package,

*StageXL Web app,

*Web server.

I pressed each of them because I didn't know which one was right for just playing around with dart. But after, I could not figure out where to right my dart code. Can anyone please help?


text:
Q: HttpClient Angular 4.4.3 CSRF and CORS How is a CORS setup supposed to work with Angular's XSRF protection?  Absolute URLs are just ignored, but I need XSRF to work with absolute URLs too. Shouldn't this be configurable with HttpClientXsrfModule.withOptions()? It seems like an oversight in the code.
Specifically, I see this in the Angular code:
https://github.com/angular/angular/blob/master/packages/common/http/src/xsrf.ts#L77-L84
// Skip both non-mutating requests and absolute URLs.
// Non-mutating requests don't require a token, and absolute URLs require special handling
// anyway as the cookie set
// on our origin is not the same as the token expected by another origin.
if (req.method === 'GET' || req.method === 'HEAD' || lcUrl.startsWith('http://') ||
    lcUrl.startsWith('https://')) {
  return next.handle(req);
}


text:
Q: Regex match a specific string I am trying to extract the string <Num> from within Barcode(_<Num>_).PDF using Regex. I am looking at Regular Expression Language - Quick Reference but it is not easy. Thanks for any help.
    Dim pattern As String = "^Barcode(_+_)\.pdf"
    If Regex.IsMatch("Barcode(_abc123_).pdf", pattern) Then
        Debug.Print("match")
    End If

A: If you are trying to not only match but also READ the value of  into a variable, then you will need to call the Regex.Match method instead of simply calling the boolean isMatch  method.  The Match method will return a Match object that will let you get to the groups and captures from your pattern.
Your pattern would need be something like "Barcode\(_(.*)_\)\.pdf"-- note the inner parenthesis which will create a capture group for you to obtain the value of the string between the underscores..  See a MSDN docs for examples of almost exactly what you are doing.

A: I don't know the regex in VB, but I can offer you a website to examine the correctness of your  regex:   Regex Tester.  In this case, if the <Num> is numbers, you can use "Barcode(_\d+_).pdf"

A: Just for the record, this is what I ended up using:
    'set up regex
    'I'm using + instead of * in the pattern to ensure that if no value is
    'present the match will fail
    Dim pattern As String = "Barcode\(_(.+)_\)\.pdf"
    Dim r As Regex = New Regex(pattern, RegexOptions.IgnoreCase)

    'get match
    Dim mat As Match
    mat = r.Match("Barcode(_abc123_).pdf")

    'output the matched string
    If mat.Success Then
        Dim g As Group = mat.Groups(1)
        Dim cc As CaptureCollection = g.Captures
        Dim c As Capture = cc(0)
        Debug.Print(c.ToString)
    End If

.NET Framework Regular Expressions


text:
Q: How do I generate permutations consisting of all elements in multiple ordered sets (preferably incorporating element priority)? I am doing some self study and have come up with a problem I'm not sure how to go about solving. Please correct me if I've used any term incorrectly. Purely mathematical or Python approaches are fine.
I have ordered sets:
$A = \{a_1, a_2, a_3, a_4, a_5\}$
$B = \{b_1, b_2, b_3\}$
$C = \{c_1, c_2, c_3, c_4, c_5, c_6\}$
$D = \{d_1, d_2, d_3, d_4, d_5, d_6\}$
Let's say each $a,b,c,d$ has two properties: the first defining its position within the order of its respective set, and the second a binary priority for the output. (e.g. $a_1 = (1,1), a_2 = (2,0), a_3 = (3,1)$).
I want to generate permutations that contain every element of $A,\ B,\ C,$ and $D$ such that order is preserved from within each set, i.e. $(a_1, b_1, a_2, ...)$ is fine, but $(a_2, a_1, ...)$ is not.
Additionally, as part of the output, I want to minimize (frontload) the positions of certain elements (e.g. $a_1, d_2, a_5$ each have priority over $a_2, a_4,$ or $d_1$).
Desired end result: $X = (x_1, x_2, x_3, ..., x_{20})$ where each $x$ is an element from $A, B, C,$ or $D$.
How can I find solutions?

A: Remark
Assuming you want to generate all the solutions, you can solve the problem without priority output, and then iterate and apply the priority output to the collection of all solutions.
I'll present you the first thing that falls on my mind - a structure of the problem that shows how you can recursively generate all permutations while satisfying the condition of preserving the order within sets.
If however you need only to output (and generate) the top priority permutations as a subset of all permutations (which would be preferred if the total number of all permutations is very large), then you'll need to prioritize those permutations while generating the solutions.

The general problem
Generally, lets have sets $A_1,A_2,A_3,\dots,A_m$, where $i$th one has $n_i=|A_i|$ elements $a^{i}_1,a^{i}_2,a^{i}_3,\dots,a^{i}_{n_i}$.
We want to get all permutations that satisfy the condition that the order is preserved from within each set. (The order being defined by indices of elements: $a^i_j\lt a^i_{j+1},j\in\{1,\dots,n_i\}$.)

The base case
If $m=1$ then the only such permutation is ordered $A_1$, that is: $X^1=(a^{1}_1, a^{1}_2, a^{1}_3, \dots, a^{1}_{n_1})$.
If $m=2$, then each such permutation is of form $X^2=(A^2_1, a^{1}_1, A^2_2, a^{1}_2, A^2_3, a^{1}_3, \dots, A^2_{n_1}, a^{1}_{n_1}, A^2_{n_1+1})$,   where $A^2_k$ are ordered, mutually disjoint, subsets of $A_2$ such that order is preserved: $\max A^2_j < \min A^2_{j+1}$.
Now simply partition $A_2$ into sets $A^2_k$ in all valid ways to get all $X^2$ permutations.
You can satisfy the order preservation $\max A^2_j < \min A^2_{j+1}$ property by keeping track of some index $M$, and iterating elements of $A_2$ in order.
That is, $a^2_1$ can be put into any of $A^2_1,\dots,A^2_{n_1+1}$ sets, then $a^2_2$ can be put into any of $A^2_{M_1},...,A^2_{n_1+1}$ where $M_1$ is the index of set $A^2_{M_1}$ where $a^2_1$ was placed, then $a^2_3$ can be put into any of $A^2_{M_2},...,A^2_{n_1+1}$ where $M_2$ is now the index of set $A^2_{M_2}$ where $a^2_2$ was placed, $\dots$ and so on for all $a^2_i$.
You should have $\binom{n_1+n_2}{n_2}$ solutions for $m=2$, where $\binom \square \square$ is the binomial coefficient.
Example:
$A_1=\{a^1_1,a^2_2,a^3_3\}=A=\{a_1,a_2,a_3\}$
$A_2=\{a^2_1,a^2_2\}=B=\{b_1,b_2\}$
First iteration, we insert $b_1$ in all valid ordered $A^2_k=B_k$ subsets to get:
$(b_1,a_1,a_2,a_3),(a_1,b_1,a_2,a_3),(a_1,a_2,b_1,a_3),(a_1,a_2,a_3,b_1)$
Second iteration, we insert $b_2$ in all valid ordered $A^2_k=B_k$ subsets from previous iteration, to get:
$M_1=1\implies(b_1,b_2,a_1,a_2,a_3),(b_1,a_1,b_2,a_2,a_3),(b_1,a_1,a_2,b_2,a_3),(b_1,a_1,a_2,a_3,b_2)$
$M_1=2\implies(a_1,b_1,b_2,a_2,a_3),(a_1,b_1,a_2,b_2,a_3),(a_1,b_1,a_2,a_3,b_2)$
$M_1=3\implies(a_1,a_2,b_1,b_2,a_3),(a_1,a_2,b_1,a_3,b_2)$
$M_1=4\implies(a_1,a_2,a_3,b_1,b_2)$
There is no $b_3$ so we are done (no third iteration).
We have $10$ solutions yielded by last iteration, as expected: $\binom{3+2}{2}=\binom{5}{2}=\frac{5!}{2!3!}=10$.
Now you can print these in what ever order of output priority you like.

The general case
You can continue to build permutations for $m+1$ sets on top of permutations for $m$ sets, using the same algorithm as in the base case.
Lets say you have all solutions (permutations) $s\in S_m$ for case $m$. Then to get $S_{m+1}$, apply the same algorithm as in base case, but instead of single $(A_1,A_2)$ pair, we are applying it to all pairs $(s,A_{m+1}),s\in S_m$.
Adding on to the last example, if we introduce the set $A_3=C=\{c_1,c_2,c_3,c_4\}$,
Then we are now applying the base case to:
$s=\{s_1,s_2,s_3,s_4,s_5\}\in S_2=\{(b_1,b_2,a_1,a_2,a_3),(b_1,a_1,b_2,a_2,a_3),\dots,(a_1,a_2,a_3,b_1,b_2)\}$
 $C=\{c_1,c_2,c_2,c_4\}$
For every $s$. You are expecting $\binom{5+4}{4}=126$ solutions (permutations) for every $s$. Since we have ten such solutions $|S_2|=10$, in total we have $10\cdot126=1260$ solutions that are $\in S_3$, for this particular example.

The example in question,
$A = \{a_1, a_2, a_3, a_4, a_5\}$
$B = \{b_1, b_2, b_3\}$
$C = \{c_1, c_2, c_3, c_4, c_5, c_6\}$
$D = \{d_1, d_2, d_3, d_4, d_5, d_6\}$
Would have $\binom{5+3}{3}\binom{8+6}{6}\binom{14+6}{6}=56\cdot3003\cdot38760=6\text{ }518\text{ }191\text{ }680>6\cdot10^9$ solutions.
Which can be generated by applying base case to $A,B$ to get $S_2$, then base case to all $s\in S_2,C$ to get $S_3$, and finally the base case to all $s\in S_3,D$ to get all $X=(x_1,x_2,\dots,x_{20})\in S_4$, as mentioned in the general case.


text:
Q: Как сделать чтобы при запуске проекта открывался другой url? Всем привет! Столкнулся с проблемой, что не знаю как правильно открыть правильный url при самом первом запуске проекта. Нужно чтобы при запуске, например, открывался http://localhost:3000/projects... Буду очень благодарен за помощь! (вроде можно сделать это через useEffect, но оно просто багует)

A: Укажите в package.json свойство "homepage": "/projects".


text:
Q: IOS6 How can I listen to Interface orientation. Not device orientation I need to know when orientation switch from portrait to landscape and vise versa.
If I choose to listen to UIDeviceOrientationDidChangeNotification I get face up, face down etc, but I need to run code only when there is a interface rotation.
I could do as http://the.ichibod.com/kiji/how-to-handle-device-rotation-for-uiviews-in-ios/
- (void)deviceOrientationDidChange:(NSNotification *)notification {

 //Obtaining the current device orientation
  UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

 //Ignoring specific orientations
  if (orientation == UIDeviceOrientationFaceUp || orientation == UIDeviceOrientationFaceDown     || orientation == UIDeviceOrientationUnknown || currentOrientation == orientation) {
   return;
  }

  [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(relayoutLayers) object:nil];
  //Responding only to changes in landscape or portrait
  currentOrientation = orientation;
}

What is the best approach?

A: I had similar problems orientating my views when using device orientation. It has up, down, left and right but also unknown and another which I yet to figure it out what it means (int 5 on the enum, 0 being Unknown). Anyways, what I ended up resorting to was to detect the status bar orientation. That remains more consistency for what the user is seeing.
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

Hope this helps.


text:
Q: How can i use full CPU resources with Gitlab server? I installed Gitlab server in an AWS EC2 instance, with 36 CPU cores.
But in monitoring tab in Gitlab admin page, Gitlab seems to recognize only 10 cores.
I cannot find this kind of parameters in Gitlab configuration file.
How can i use full CPU resource with Gitlab server?
Gitlab monitoring page shows 10 cores in this system


text:
Q: How to use a batch_size of Keras tensor at the model building time? I want to use an external program as a custom operation.
Because automatic gradient would be not available, I wrote the code to provide gradients by using numerical methods. However, because it have to compute the batch_size number of derivatives,
I wrote it to get batch_size from the shape of x.
Following is an example using numpy function as an external program
f(x) = np.sum(x**2)
(In fact, for this simple numpy function, no loop over batch_size is necessary. But, it is written for general external function.)
@tf.custom_gradient
def custom_op(x):
    # without using numpy, use external function
    # assume x shape = (batch_size,3)
    batch_size= x.shape[0]
    input_length = x.shape[1]
    # assert input_length==3
    yout=[] # shape should be (batch_size,1)
    gout=[] # shape should be (batch_size,3)
    for i in range(batch_size):
        inputs = x[i,:] # shape (3,)
        y = np.sum(inputs**2) # shape (3,)
        yout.append(y) # shape (1,)
        # compute differences
        dy = []
        for j in range(len(inputs)):
          delta = np.zeros_like(inputs)
          delta[j] = np.abs(inputs[j])*0.001
          yplus = np.sum((inputs + delta)**2) # change only j-th input
          grad = (yplus-y)/delta[j] #shape (1,)
          dy.append(grad)
        gout.append(dy)
    yout = tf.convert_to_tensor(yout,dtype='float32') # (batch_size,)
    yout = tf.reshape(yout,shape=(batch_size,1)) # (batch_size,1)
    gout = tf.convert_to_tensor(gout,dtype='float32') # (batch_size,)
    gout = tf.reshape(gout,shape=(batch_size,input_length)) # (batch_size,1)
    def grad(upstream):
        return upstream*gout
    return yout, grad

x = tf.Variable([[1.,2.,3.],[2.,3.,4.]],dtype='float32')
with tf.GradientTape() as tape:
    y = custom_op(x)
tape.gradient(y,x)

and found it works.
However, when I tried to use it in the keras model , for example,
def construct_model():
    inputs = tf.keras.Input(shape=(3,)) #input array
    x      = tf.keras.layers.Dense(1)(inputs)
    outputs = custom_op(x)
    model = tf.keras.Model(inputs=inputs, outputs=outputs)
    optimizer = 'adam'
    model.compile(loss='mean_squared_error',
                optimizer=optimizer,
                metrics=['mean_absolute_error', 'mean_squared_error'])
    return model

model = construct_model()

it gives errors
because kerasTensor "inputs" does not have specified batch_size.
I tried to specify batch_size as "tf.keras.Input(shape=(3,),batch_size=2)".
However, it also raises errors because of the use of kerasTensor.
How should I change the custom_op to be compatible with keras?


text:
Q: How to set the permissions of my driver file using udev rules I am trying to set the permissions on my device driver file to read/write for all users using udev rules but it does work.
here the udev rules :
SUBSYSTEM=="lpc*", KERNEL=="lpc?*", DRIVER=="lpc", GROUP="users", MODE="0666"

When I test it using :
sudo udevadm test $(udevadm info -q path -n /dev/lpc_peach)2>&1

this is what i get at the bottom lines :
preserve permissions /dev/lpc_peach, 020600, uid=0, gid=0
preserve already existing symlink '/dev/char/248:0' to '../lpc_peach'

I can't identify what is wrong! Any help will be useful.
Edit 1 : When I run udevadm info -q all -n /dev/lpc_peach here is what I get:
P: /devices/virtual/lpc_spartan/lpc_peach
N: lpc_peach
E: DEVNAME=/dev/lpc_peach
E: DEVPATH=/devices/virtual/lpc_spartan/lpc_peach
E: MAJOR=247
E: MINOR=0
E: SUBSYSTEM=lpc_spartan


text:
Q: Rescaling after feature scaling, linear regression Seems like a basic question, but I need to use feature scaling (take each feature value, subtract the mean then divide by the standard deviation) in my implementation of linear regression with gradient descent. After I'm finished, I'd like the weights and regression line rescaled to the original data. I'm only using one feature, plus the y-intercept term. How would I change the weights, after I get them using the scaled data, so that they apply to the original unscaled data?

A: Suppose your regression is y = W*x + b with x the scaled data, with the original data it is
y = W/std * x0 + b - u/std * W

where u and std are mean value and standard deviation of x0. Yet I don't think you need to transform back the data. Just use the same u and std to scale the new test data.


text:
Q: How can I add a placeholder and multiline text input to my form fields? React Native How can I add a placeholder and multiline text input to my form fields? React Native?
I want to add a placeholder in my subject line and I want to have my message field multiline
I have tried to add placeholders and multilines but I dont think I am using it correctly. please help me out
    import React, { Component } from 'react';
    import { View, StyleSheet, Button, TextInput } from 'react-native';

import t from 'tcomb-form-native';

const Form = t.form.Form;

const User = t.struct({
name: t.String,
email: t.String,
subject: t.String,
message: t.String
});

const formStyles = {
  ...Form.stylesheet,
 formGroup: {
 normal: {
  marginBottom: 10
},
},
controlLabel: {
normal: {
  color: 'blue',
  fontSize: 18,
  marginBottom: 7,
  fontWeight: '600'
},
// the style applied when a validation error occours
error: {
  color: 'red',
  fontSize: 18,
  marginBottom: 7,
  fontWeight: '600'
 }
 }
}

const options = {
fields: {
name: {
  error: 'Please enter your name',

},
email: {
  error: 'Please enter your email adress'
},
message: {
  error: 'Please enter message'
 },
},
stylesheet: formStyles,
};

export default class App extends Component {
handleSubmit = () => {
const value = this._form.getValue();
console.log('value: ', value);
}

render() {
return (
  <View style={styles.container}>

    <Form
      ref={c => this._form = c}
      type={User}
      options={options}
    />
    <Button
      title="Send Message"
      onPress={this.handleSubmit}
    />
   </View>
  );
 }
}

const styles = StyleSheet.create({
container: {
justifyContent: 'center',
marginTop: 50,
padding: 20,
backgroundColor: '#ffffff',

 },
});

https://snack.expo.io/SJiexSeiW
Link to my code so far to view in snack expo


text:
Q: Read a sound backward with DirectSound Is it possible to read a sound backward with the managed version of DirectSound?
If not is there another library allowing to make it easily?

A: You can use the WaveFileReader and WaveFileWriter classes from NAudio to reverse a WAV file. You need to make sure you use the BlockAlign property of the WaveFormat to read all the bytes for a single sample (4 for stereo 16 bit audio).
    public static void ReverseWaveFile(string inputFile, string outputFile)
    {
        using (WaveFileReader reader = new WaveFileReader(inputFile))
        {
            int blockAlign = reader.WaveFormat.BlockAlign;
            using (WaveFileWriter writer = new WaveFileWriter(outputFile, reader.WaveFormat))
            {
                byte[] buffer = new byte[blockAlign];
                long samples = reader.Length / blockAlign;
                for (long sample = samples - 1; sample >= 0; sample--)
                {
                    reader.Position = sample * blockAlign;
                    reader.Read(buffer, 0, blockAlign);
                    writer.WriteData(buffer, 0, blockAlign);
                }
            }
        }
    }


text:
Q: From RDD pipeline to DF Pyspark This question appeared well trodden as I started looking for help, but I haven't found a solution yet. In fact, you might find a few you see as possible duplicates, but I think I have tried them all in the last few hours. From what I understand, sqlContext is going to do the trick here, but I am open to any answer that works. I'm using Spark 2.1
I am starting with an id list that I am pulling down from mongodb.
Sample output:
[u'182028', u'161936', u'12333', u'120677']
'rated_game_ids_lst type:' <type 'list'>

I then move on to try creating an RDD that I want to turn into a DF:
user_unrated_games = ugr_rdd.filter(lambda x: x[1] not in rated_game_ids_lst).map(lambda x: (19, x[1], x[2]))

Sample output:
'user_unrated_games:' [(19, u'174430', 3.4), (19, u'169786', 3.4)]
'user_unrated_games type:' <class 'pyspark.rdd.PipelinedRDD'>

and a sample of the urg_rdd I use above (first row):
'ugr_rdd:'[Row(user_id=5, game_id=u'182028', rating=9.15)]
'ugr_rdd_type:' pyspark.rdd.RDD

I then try this:
df = sqlContext.createDataFrame(user_unrated_games, ['user_id', 'game_id', 'rating'])

That method fails so I tried this:
user_unrated_games = ugr_rdd.filter(lambda x: x[1] not in rated_game_ids_lst).map(lambda x: Row(user_id=19, game_id=x[1], rating= x[2]))

Sample output:
('user_unrated_games type:', <class 'pyspark.rdd.PipelinedRDD'>)
('user_unrated_games:', [Row(game_id=u'174430', rating=3.4, user_id=19), Row(game_id=u'169786', rating=3.4, user_id=19)])

and then this:
df = sqlContext.createDataFrame(user_unrated_games)

Both of these attempts give this error:
IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':"

From there, I started trying combinations of changing the types of "user_id", etc., tried passing the RDD as is, tried to convert my pipeline to an RDD...frankly I tried a lot of things, but the two above look the closest to what seem to work for others.

A: The issue is that you need to specify the schema including data types when calling the createDataFrame method.  Something like this should do the trick:
from pyspark.sql.types import *

rdd = sc.parallelize([(19, 174430, 3.4), (19, 169786, 3.4)])

schema = StructType( [
    StructField('user_id', IntegerType()),
    StructField('game_id', IntegerType()),
    StructField('rating', FloatType())
    ])

df = spark.createDataFrame(rdd, schema)

df.show()

NOTE:  I've tested this using spark 2.1.0.  In this case spark is a SparkSession object.


text:
Q: How to check if the batch pool nodes are idle in data factory I am using a Python code that creates the batch pool using the Azure SDK for Python. I have deployed this code in function apps and I am using it in data factory to create the batch pool. I want to check if the nodes have started or if they are in idle state before I run the rest of components in the pipeline. Is there any way I can check this in data factory?

A: No, there isn't a way can check it in Data Factory. Data Factory will call and run the Azure function directly.

A: Yes, there is no direct way to check the node status via ADF. But you can consider below workaround to achieve the same via ADF using Web Activity.

*

*Step 1: Make an API to call Azure Batch services to get to your node
status details. We can leverage web activity in Azure data factory
to do the same.

*Step 2: Based on response from Step 1, Invoke execution of your
pipeline further activities.
Check below links to know more details about Batch Service API and Web activity


text:
Q: Update timeout in Codebuild in a codepipeline using CDK I have the aws-simple-cicd pipeline deployed from https://github.com/awslabs/aws-simple-cicd. I tried to increase the code build timeout by going to https://github.com/awslabs/aws-simple-cicd/blob/main/lib/projects/deploy-project.ts and adding
timeout: Duration.hours(3),

at line 41.
Then I ran :
cdk synth

cdk deploy

I didn't see this change reflected in the CFN output or the deployment. What is going wrong here? Wat do I need to do in order for the codebuild timeout to be increased in CDK IaC. (I do not wish to change it directly on the aws console).


text:
Q: haproxy ACL - log misses as well as hits? I have the following haproxy config file. Note I'm using tcp mode on the frontend and backend, not HTTP.
The acl is intended to only allow certain hosts in the same AWS VPC to access the frontend. Simple verification using telnet shows that TCP connections are accepted from the allow-listed hosts and rejected from others.
Logging shows the connection attempts from allow-listed hosts at the default logging level (info I believe).
I tried debug level, but still no log of acl rejected connection attempts.
While that's desirable for live usage (to avoid swamping the logs), for development and debug it would be reassuring to at least be able to see failed attempts.
Is there way to do that? I've looked at https://www.haproxy.com/blog/introduction-to-haproxy-logging/ and https://www.haproxy.com/documentation/hapee/latest/onepage/#8.3 already.
I'm using version 2.6.1 on Amazon Linux.
global
    log /dev/log local0
    chroot      /var/lib/haproxy

    maxconn     4000
    # unused options as this config needs root privilege and pidfile is already specified
    #pidfile     /var/run/haproxy.pid
    #user        haproxy
    #group       haproxy
    daemon
    stats socket /var/lib/haproxy/stats

defaults
    log                     global
    timeout connect 5000ms
    timeout client 5000ms
    timeout server 5000ms

frontend  main
    # See "bind" documentation at https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#4.2-bind
    bind *:5000 accept-proxy
    mode tcp
    # Detailed connection logging
    option tcplog
    # Allow only certain hosts (client MTAs) to use this proxy - does this have to come before the backend
    acl valid_client_mta_hosts src 127.0.0.1 172.31.25.101
    tcp-request connection reject if !valid_client_mta_hosts
    use_backend out

backend out
    mode tcp
    # See "source" documentation at https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#4.2-source
    source 0.0.0.0 usesrc clientip
    # See "server" documentation at https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#4.2-server
    server foo 0.0.0.0

frontend stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 10s
    stats admin if LOCALHOST


text:
Q: Cannot assign through subscript to Swift String I have a class that contains a name, an image, a dashed form of the name, and the length of the name. For example, I could have "dog", an image of a dog,  "---", and name length 3.
I just want to set name and pic for each object and have dashName and nameLength set automatically.
class Answer {
    var name = "name"
    var image: UIImage?
    var dashName = "name"
    var nameLength = 0

    init(){

        var a = 0
        nameLength = name.characters.count

        while a <= nameLength {
            if (name[a] == " ") {dashName[a] = " "}
            else {dashName[a] = "-"}
            a += 1
        }
    }
}

The problem is the error that says: "cannot assign through subscript: subscript is get-only" and another error that says: "subscript is unavailable: cannot subscript String with an Int"

A: Because String's subscript operator is get-only, use map method instead, like:
class Answer {
    var name = "name"
    var image: UIImage?
    var dashName = "name"
    var nameLength = 0

    init(){
        dashName = String(name.map {$0 == " " ? " " : "-"})
    }
}

A: As mentioned before,
Swift's String class is what other languages call a StringBuilder class, and for performance reasons, Swift does NOT provide setting character by index; If you don't care about performance a simple solution could be:
public static func replace(_ string: String, at index: Int, with value: String) {
    let start = string.index(string.startIndex, offsetBy: index)
    let end = string.index(start, offsetBy: 1)
    string.replaceSubrange(start..<end, with: value)
}

Or as an extension:
extension String {
    public func charAt(_ index: Int) -> Character {
        return self[self.index(self.startIndex, offsetBy: index)];
    }

    public mutating func setCharAt(_ index: Int, _ new: Character) {
        self.setCharAt(index, String(new))
    }

    public mutating func setCharAt(_ index: Int, _ new: String) {
        let i = self.index(self.startIndex, offsetBy: index)
        self.replaceSubrange(i...i, with: new)
    }
}

Note how above needs to call index(...) method to convert integer to actual-index!? It seems, Swift implements String like a linked-list, where append(...) is really fast, but even finding the index (without doing anything with it) is a linear-time operation (and gets slower based on concatenation count).

A: The subscript operator for String is get-only, which means you can only read from a string using it, and have to use something else to write to a mutable String.
You can solve this issue, and clean up the code by using a map function on name
Swift 4
class Answer {
    var name = "name"
    var image: UIImage?
    var dashName = "name"
    var nameLength = 0

    init()
    {
        nameLength = name.count
        dashName = name.map { $0 == " " ? " " : "-" }.joined()
    }
}

Swift 3
class Answer {
    var name = "name"
    var image: UIImage?
    var dashName = "name"
    var nameLength = 0

    init()
    {
        nameLength = name.characters.count
        dashName = name.characters.map { $0 == " " ? String(" ") : String("-") }.joined()
    }
}


text:
Q: An intuitive meaning of the area under the PR curve? Wikipedia says that an interpretation of the area under the ROC curve is: "the area under the curve is equal to the probability that a classifier will rank a randomly chosen positive instance higher than a randomly chosen negative one".
But is it the same interpretation of the area under the PR curve? If not, can you please give me an intuitive interpretation for it like the above?
Edit: PR == Precision-Recall

A: The area under the PR-Curve is ill-defined. Because there is no well-defined precision at recall 0: you get a division by zero there.
You also cannot close this gap easily - it may be anything from 0 to 1, depending on how well your retrieval works.
There is a common approximation to this - AveP, average precision.

A: Well, I will try to give some intuition close to the one of Wikipedia as you may desire. The PR-AUC can be thought of as the probability that a classifier will rank a randomly chosen "positive" instance (from the retrieved predictions) higher than a randomly chosen "positive" one (from the original positive class). It should be noted that this is based on my own interpretation and may be subject to error.
In another Wikipedia page, the following text is relevant "precision (also called positive predictive value) is the fraction of retrieved instances that are relevant, while recall (also known as sensitivity) is the fraction of relevant instances that are retrieved".
PR-Curve is a very important metric, especially, when dealing with imbalance datasets. I would advise looking at this study for further details.
From a different persepctive, I would say that when both sensitivity and precision are of importance to the experimenter, then we can think of them as exploration and exploitation terms, respectively. Basically, you may limit strictly the threshold of predictions over the positive class, allowing a very high precision but at the cost of less exploration (i.e. lower sensitivity) (or new insights about the the positive class). Relaxing this constraint, can allow for exploring those cases that we predict as positives and never thought they are.
One would want to always maximize both but for certain cases, this might be very difficult and in some applications, sacrificing one towards enhancing the other is preferable.


text:
Q: Stop double-clicking of submit button with Javascript Here's my situation. I have a submit button. When clicked, some backend/database validation takes place and if everything's good, submit the form and disable the button so the form can't be submitted twice. If it does not pass validation, submittal cannot take place and the button stays active, so the user can resubmit the form. It sounds simple but I can't make it work. This is a C# web application.
I have tried to add the code to the button on page load. When the submit button is clicked and if validation fails, remove the code that disables the button. But here is my problem. Since the "disable" code is removed and the user fixes any error and resubmit, the button can be clicked more than one as the code is no longer there.
I do not want to use Ajax for this because the backend check is very complicated. Is there another way to do it? I've tried to add the "disable" code on "load" but it does not work on post back when the validation fails.
 if (window.addEventListener)
        window.addEventListener("load", lockSubmit, false);
    else if (window.attachEvent)
        window.attachEvent("onload", lockSubmit);
    else window.onload = lockSubmit;

Any help is appreciated.

A: Try the snippet below
window.onload = function(){

  // Insert the following function somewhere in your .js file / section
  (function prevent_over_submitting(){
    var form = document.forms.theform;
    if(form || form.nodeName == 'FORM'){
      form.onsubmit = function(){
        form.submit.value = 'Proccesing...';
        form.submit.disabled = true;
      };
    }
  })();

};

While your form should look something like this one
<form id="theform" method="post" action="">
    <input type="text" name="firsname" value="" />
    <input type="text" name="lastname" value="" />
    <input type="submit" name="submit" value="submit" />
</form>

Here is a working jsBin so you can play around.

Update:
The logic behind the snippet above
// server-side code (rather in pseudo-code this time)
if(form_has_been_submitted){               // check if the form has been submitted
    errors[] = validate_data(post_data);   // call the method to validate data
    if(errors_array_is_empty){             // if everything is fine
        submit_data();                     // submit data
        redirect_or_do_something;          // (maybe) do other things
    }                                      // otherwise don't do anything
}

// validation method
validate_data(post){ // the only argument here represents all your form data
    error = array;
    if(post['firstname'] == wrong){  // check for error
        error['firstname'] = 'Check your firsname'; // if you found one, push it to the error array
    }
    if(post['lastname'] == wrong){   // the same as in previous case
        error['lastname'] = 'Check your lastname'; // the same as in previous case
    }
    return error; // return that array, it might be full or empty
}

// client-side code
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>MyApplication</title>

    <form id="theform" method="post" action="">
        <input type="text" name="firsname" value="" />

        <% (error['firstname'] ? error['firstname'] : "") %>
        <input type="text" name="lastname" value="" />

        <% (error['lastname'] ? error['lastname'] : "") %>
        <input type="submit" name="submit" value="submit" />
    </form>

As you can see, the JavaScript snippet above only disables the submit button onclick to prevent over-submitting; it will be enabled once the page is loaded again. This isn't my favorite way of validation but I followed your logic.

A: you can add this code in the onclick function:
First, add a global javascript variable, say var click = false;
and add this condition before validation occurs:
if(click){
    return false
} else {
    your normal validation code
}

if your page reloads each time you submit, then there is no need to add anything further, but if doesn't then add setInterval method which will reset the click variable for next use if validation fails.
The state of the click variable will remain true after first click and will further stop multiple clicks, unless page reloads or we reset the variable manually through code.


text:
Q: How to convert std::vector> dataVector to Eigen::MatrixXd rtData(dataVector.size(), 2) Is there a fast way to make conversion below?
use "std::vector<std::pair<double, double>> dataVector" to initialize "Eigen::MatrixXd rtData(dataVector.size(), 2)"

A: I am assuming you wish to create a two column matrix from bunch of pairs stacked in a vector.
As far I can see in the documentation MatrixXd is typedef of Matrix<double,dynamic,dynamic> so first potential issue is that you wish to fill matrix of double by int values.
Since MatrixXd is merely a typedef I don't think there is a suitable constructor in Eigen library for you to do quick conversion.
Simply write a code or a function that iterates through your vector and populates the matrix. In C++14:
int itt=0;
for (const auto& [first, second] : dataVector)
{
   rtData(itt,0) = first;
   rtData(itt,1) = second;
   itt++;
}

That is a neat for loop that can go through vector of pairs, you still need the index of the elements, as Eigen matrices do not have push_back methods as STL.
Note again that I would advise MatrixXi if you are populating it with integers and not doubles.

A: Assuming sizeof(std::pair<int,int>) == 2*sizeof(int) (i.e., std::pair is not adding any padding) you can use an Eigen::Map of a row-major integer matrix, then cast it to double. Something like this:
typedef Eigen::Matrix<int, Eigen::Dynamic, 2, Eigen::RowMajor> MatrixX2i_r;
Eigen::MatrixXd rtData
    = Eigen::Map<MatrixX2i_r const>(&(dataVector[0].first), dataVector.size(), 2).cast<double>();

You can also use that expression directly without storing it into a MatrixXd (conversion will happen on the fly, every time the expression is used -- so if you use rtData multiple times, it could still be better to store it once).


text:
Q: Python Analysis: Type Checking Mode in VS CODE I changed the settings "Python Analysis: Type Checking Mode" to strict mode
enter image description here
And I get an error while checking for an instance of str,
def is_name(name: str) -> bool:
    if isinstance(name, str):
        return True

Unnecessary isinstance call; "str" is always an instance of
enter image description here
Is this a code problem or a settings problem?

A: This happens because you already annotated the name parameter as str, so it seems silly to narrow the type again after that with isinstance.
I personally find the error message a bit misleading because from a runtime perspective name could of course be something else (up until the isinstance check), i.e. it is technically not "always an instance of str". But from a static type checker's perspective that complaint makes sense.
Python is a dynamically typed language and that philosophy carries over to type annotations. There is a reason they are also referred to as "type hints". It is extremely un-pythonic to strictly check the argument types inside a function.
That is what the annotations are for. They tell the user of the function: "These are the types I expect in the body of this function. You can pass something else, but it might cause errors, unexpected behavior or break everything. Do it at your own peril."
I assume there is more going on in your actual function because right now it seems semantically redundant. But my suggestion is to get rid of the isinstance check. Did you decide to annotate the name parameter with the type str? Good. Then proceed in the function body under the assumption that that is what the argument will be. It is not your job, to check the type. It is the caller's job to call your function properly (or handle the consequences).


text:
Q: Uploading files through Ajax are duplicate I want to uploads file through Ajax and FormData objects. Why my files are duplicate ?

var button = document.querySelector('#send');
document.querySelector('#send').addEventListener('click', sendForm, false);
function sendForm(e) {
  e.preventDefault();
  var formElement;
  var formData;
  var xhr;
  var JSONObject;
  formElement = document.querySelector('#form');
  formData = new FormData(formElement);
  var fileInput = document.querySelector('#file');
  var files = fileInput.files;
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    formData.append('file[]', file, file.name);
  }
  console.log(...formData);
  xhr = new XMLHttpRequest();
  /**/
}
<form id="form">
 <label for="firstname">Prénom
  <input type="text" name="firstname" id="firstname" size="30" />
 </label>
 <label for="lastname">Nom
  <input type="text" name="lastname" id="lastname" size="30" />
 </label>
 <input type="file" name="file[]" id="file" multiple>
 <button id="send" type="submit">Submit</button>
</form>

What's wrong with my code? Is my loop incorrect?
Thanks.

A: Because you are manually appending your files to the formData, where they already are.
After commenting unnecessary code, your code works fine.

var button = document.querySelector('#send');
document.querySelector('#send').addEventListener('click', sendForm, false);
function sendForm(e) {
  e.preventDefault();
  var formElement;
  var formData;
  var xhr;
  var JSONObject;
  formElement = document.querySelector('#form');
  formData = new FormData(formElement);
  var fileInput = document.querySelector('#file');
  /*
  The code that appends files in the formData, where thhey already here :
  var files = fileInput.files;
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    formData.append('file[]', file, file.name);
  }*/
  console.log(...formData);
  xhr = new XMLHttpRequest();
  /**/
}
<form id="form">
 <label for="firstname">Prénom
  <input type="text" name="firstname" id="firstname" size="30" />
 </label>
 <label for="lastname">Nom
  <input type="text" name="lastname" id="lastname" size="30" />
 </label>
 <input type="file" name="file[]" id="file" multiple>
 <button id="send" type="submit">Submit</button>
</form>