text:
Q: Is the Empire racist? Throughout the original trilogy of Star Wars, we exclusively see human Empire officers, while the rebels' staff seems to be composed from a large range of species. While a non-human rebel officer is only shown in the Battle of Endor (specifically Admiral Ackbar), I don't remember any non-human Empire officer.
There is the notable exception of Grand Amiral Thrawn, but if I remember from the books (I read those about 15 years ago), it was stated that this was something unusual. There is also Darth Maul, who was not human, but it was before the Emperor's rise to power.
Although "racist" is probably not the correct word, as it's the human versus non-humans species, was the Empire, and so the Emperor, racist?

A: Disney Canon:
Yes, and intentionally so.
In the Star Wars:  Aftermath canon novel series by Chuck Wendig, Sinjir Rath Velus is a former Imperial Loyalty Officer who has defected to the New Republic side.  Here is his analysis:

The prime operator within all Imperial ranks was the human being. "Aliens" were by and large unwelcome within its labyrinthine order because aliens were seen as different. They were serfs and slaves or, at best, obstacles. They needed to be tamed, removed, or ignored...
Sinjir felt the tug of that prejudice himself from time to time, for it was so programmed into them that even near-humans were to receive a measure of distrust. Palpatine and his propaganda machine worked to drive that nail of bigotry deeper by demonstrating how the old Jedi thugs and the scumfroth rebels consisted of many more nonhumans than humans. You could trust a human, the Empire said; aliens would always betray you.
Of course, over time Sinjir learned the foolishness of that, because as it turned out human beings were fairly horrible. Full of treachery! Just brimming with the stuff. He came to believe that the Empire's corruption was precisely because it was xenophobic. It afforded no one any other voice, and so man and machine ruled the Empire together while the rest of the galaxy— despite being predominantly nonhuman in origin— suffered, powerless while under the twisting heel of the Imperial boot.
--  Star Wars:  Aftermath:  Life Debt

One of Sinjir's new allies, Norra Wexley (one of the pilots who flew alongside the Millennium Falcon during the assault on the second Death Star), shares Sinjir's opinion:

Kashyyyk is a prison planet. A worldwide labor camp. The Empire, in its xenophobic monstrousness, saw fit to imprison and enslave the Wookiees there not because they offered a meaningful threat to the Emperor's ascendancy— but because they were different, and because their massive, robust physiology would allow them to work long and hard in extreme conditions. Probably took rather epic effort to work a Wookiee to death. Not that the Empire wouldn't try, she wagers.
--  ibid

A: Yes it was. There were three sources/components to it -

*

*General philosophy of Humanocentrism (bias towards human and near human species). This was subscribed to by many humans in Old Republic, and part of its fabric.

*Specific xenophobia on the part of many of powerful people in the Empire.
Specifically, we can point to Janus Greejatus, rabidly anti-alien member of Palpatine's inner circle and founder of Imperial Department of Redesign, which was instrumental in Empire's antialien policies.

*Internal politics of the Empire.

*

*As we see in the novel Tarkin (as well as partly in Clone Wars), non-Humans made a vast bulk of Separatists, and as such were useful "other"/"enemy"/scapegoat for the Empire and the Emperor in the years after the Clone Wars.

*And we all know that having an "other" is a great tool for a dictatorial government to distract the populous from their poor living conditions and lack of power.

*Having anti-alien bias allowed economic exploitation of non-human species (e.g. enslaving the Wookiees).

*And, as noted in #2, many powerful humans in the Empire were anti-alien and these policies allowed the Emperor to keep them happy (when it wasn't to his own goals' detriment - which is why he was quite happy to trust and elevate Thrawn when it suited him).

A: After some research, it looks like the Empire was racist / xenophobic. This policy even has a name: "Human High Culture"

Human High Culture was the Galactic Empire's codified policy of Humanocentric speciesism. It centered around the belief (long, if privately, held by a minority of Humans in the Human-dominated Core) that Humans were inherently superior to other species.
...
As such, through the repealing of such laws as the Rights of Sentience and the creation of new acts, all nonhumans were made second-class citizens (if citizens at all). Non-Human slavery was re-legalized. Only 'pure' (i.e., those made exclusively by Humans and with no help from nonhumans) works of art (such as operas, holovids, books, etc) were allowed to be produced, viewed, and spread, since only Human culture was worthy enough to be allowed to prosper in the New Order. Non-Humans were 'actively discouraged' to participate in government or join the Imperial military, and Human governors and moffs were placed in command of nonhuman worlds and sectors.

As for the Emperor himself, it's not that clear:

[...] It is debatable to what degree, if at all, Palpatine was a speciesist. Palpatine freely consorted with nonhumans such as Mas Amedda and Sly Moore, as well as taking Darth Maul as an apprentice, of which all were Humanoid, therefore it might be suggested that as a Sith, Palpatine's Humanocentrism was more liberal than that of the standard Imperial sort, possibly due to the fact that Sith throughout history were predominantly either Human or Humanoid. From this viewpoint, it is conceivable that Palpatine's (Sidious) Speciesism was more broadened in that to include certain Humanoid species and he used anti-alien sentiments as a way to divide the beings of the galaxy and help consolidate his rule. After all, one of the worst atrocities Palpatine committed was the destruction [of] the Human-dominated world of Alderaan. He also ordered the creation of an exclusively Human-killing pathogen.

A: Xenophobic is a good way of describing the Empire and Thrawn is a good example. Even though he was a really good strategist and leader, he was sent out to the Outer Rim. Why? He wasn't human. I think it may come from the extremely hierarchical and top-down leadership system they employ.  Systems like this often don't value initiative and change and input from anyone but management or Vader and the Emperor in this case. If you ask me, this may be one of the main reasons why they ultimately failed.

A: Yes; If we go by the Pre-Disney EU, there are only a few nonhuman commanders in the Empire (excluding the Force-sensitives under Palpatine and Vader) - Thrawn being the most prominent example, with others including the Kaleesh General Bentilais san Sk'ar (who was discovered by Thrawn himself and once fought under the future General Grievous) and Grand Moff Bertroff Hissa (who was a near-human hybrid).  Excluding these, it is true that the vast majority of the Galactic Empire was a product of humanocentrism - with few exceptions given to the best and the most loyal nonhumans.  In the Disney Canon, I am really not sure, but would assume so.

A: Speaking out-of-universe, whenever you want to create a side that needs to be seen immediately and forcefully as the enemy, the classic model is the Nazis. Nazis are very easy for audiences to hate, and so anything that evokes that imagery is common fodder for large organized enemy factions. Racism was one of the Nazis' hallmarks, and therefore, whether implied or explicit, it is generally found in most sci-fi and fantasy concerning people you are supposed to hate.
Additionally, the original movie had a limited budget, and all three movies were originally produced before the digital effects revolution. Also, Lucas was specifically trying to avoid the Roddenberry universe, where every week you saw a new race that was basically human with certain tweaks. So, prosthetic makeup was rarely used; I can think of only two significant characters in the original movie that used it, the guy who gets in Luke's face at the bar and Chewie. Pretty much every other character in the original trilogy is a puppet, a guy in a rubber mask, fur coat or tin can, or human. Only the last category had the ability to really act on-set, with facial expressions and sustained speech, so most of the characters in the original trilogy, even on the rebel side, are human(oid). The exceptions are notable; Yoda (puppet), Jabba (puppet with human inside), Ackbar (animatronic mask), Bib Fortuna (Jabba's majordomo, human with prosthetics), and yes they are all non-Empire, but when you really think of it, even the rebels are disproportionately human. It wasn't until the Special Editions, and then Episodes 1-3, that you started seeing CG and highly altered-humanoid character races begin to appear with significant screen time (Jar-Jar, the CG Yoda and droids, the Trade Federation, fantastical animals, etc etc).
In-universe, the near-human exclusivity would probably have stemmed from the fact that Palpatine would have chosen people he trusted (or at least could manipulate) as his high command, who would have chosen their cronies from their personal circles, and so on. From a psychology standpoint those people would have been picked because they were "similar to me" from the perspective of those doing the choosing. In addition, as the Empire tightened its grip, those closest to the Empire's base of power in Coruscant (and thus likely colonized by similar-looking races) would have been more likely to align with the Empire, while those lying further out in the galaxy would have been more likely to break away (even the Old Republic didn't control the entire known galaxy; Tatooine was effectively independent).


text:
Q: Addin OnClick Event on Grid row and open new grid as per the selection Below you can find the code of my grid and every thing is working fine up to here. Now i want to add Click event on RegionProjectname so that when ever i click on the the Region project name row, the RegionProjectID of that column is stored in a session variable and a new grid will open based on the selected row. Please edit or guide me that how i do this .
I had already added Select row in the grid and that also working fine but i commented.
 <asp:GridView ID="ResultGridView" runat="server" AutoGenerateColumns="False" ShowFooter="true"
    DataKeyNames="RegionProjectID"
    AllowPaging="True"
    CellPadding="3"
    OnPageIndexChanging="ResultGridView_PageIndexChanging"
    OnRowDeleting="ResultGridView_RowDeleting"
    CssClass="mGrid"
    OnRowEditing="ResultGridView_RowEditing" OnRowUpdating="ResultGridView_RowUpdating" OnRowCancelingEdit="ResultGridView_RowCancelingEdit" PageSize="15" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2" OnRowCommand="ResultGridView_RowCommand" >
        <Columns>
            <asp:BoundField DataField="RegionProjectID" HeaderText="Region ID" InsertVisible="False"
                ReadOnly="True" SortExpression="RegionProjectID" Visible="false" />
            <asp:TemplateField HeaderText="Region Name" SortExpression="RegionProjectName">
                <EditItemTemplate>
                    <asp:TextBox ID="txtRegion" Width="250px" runat="server" Text='<%# Bind("RegionProjectName") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                <asp:TextBox ID="txtRegion1" runat="server"  Width="250px"></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("RegionProjectName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Edit" ShowHeader="False">
            <EditItemTemplate>
              <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
              <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
            </EditItemTemplate>
            <FooterTemplate>
              <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
            </FooterTemplate>
            <ItemTemplate>
              <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField HeaderText="Delete" ShowDeleteButton="True"  ShowHeader="True" />
           <%-- <asp:CommandField HeaderText="Select" ShowSelectButton="True"  ShowHeader="True" on/> --%>

        </Columns>
        <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
        <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
        <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
        <%--<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />--%>
        <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
    </asp:GridView>
private void FillVendorGrid()
    {
        dataTable = new DataTable();
        cmd.Connection = conn;
        cmd.CommandText = "SELECT * FROM RegionAndProjectInfo where natureofWorkID= " + ddlnatureOfWork.SelectedValue.ToString(); ;
        ad = new SqlDataAdapter(cmd);
        ad.Fill(dataTable);
        ResultGridView.DataSource = dataTable;
        ResultGridView.DataBind();
    }

    protected void ResultGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        ResultGridView.EditIndex = e.NewEditIndex;
        FillVendorGrid();
    }

    protected void ResultGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        ResultGridView.PageIndex = e.NewPageIndex;
        FillVendorGrid();
    }

    protected void ResultGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        cmd.Connection = conn;
        cmd.CommandText = "DELETE FROM RegionAndProjectInfo WHERE RegionProjectID='" + ResultGridView.DataKeys[e.RowIndex].Values[0].ToString() + "'";
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
        FillVendorGrid();

    }

    protected void ResultGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        TextBox txtRegionname = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtRegion");
        TextBox txtNatureOFWork = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtNatureOFWork");
        cmd.Connection = conn;
        cmd.CommandText = "UPDATE RegionAndProjectInfo SET RegionProjectName ='" + txtRegionname.Text + "'   WHERE RegionProjectID='" + ResultGridView.DataKeys[e.RowIndex].Values[0].ToString() + "'";
        conn.Open();
        cmd.ExecuteNonQuery();
        ResultGridView.EditIndex = -1;
        FillVendorGrid();
        conn.Close();

    }

    protected void ResultGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        ResultGridView.EditIndex = -1;
        FillVendorGrid();

    }

    protected void ResultGridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {

            TextBox txtRegion1 = (TextBox)ResultGridView.FooterRow.FindControl("txtRegion1");
            TextBox txtNatureOFWork1 = (TextBox)ResultGridView.FooterRow.FindControl("txtNatureOFWork1");
            if (txtRegion1.Text != "")
            {
                cmd.Connection = conn;
                cmd.CommandText = "INSERT INTO RegionAndProjectInfo(RegionProjectName, NatureOFWorkID ) Values('" + txtRegion1.Text + "', '" + ddlnatureOfWork.SelectedValue.ToString() + "')";
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            FillVendorGrid();
            conn.Close();
        }
    }

    protected void ddlnatureOfWork_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillVendorGrid();
    }

A: Hello you can try with this code

*

*Firslty add ButtonField in your columns
<asp:buttonfield buttontype="Link" commandname="Add" text="Add"/>

*Add event GridView_RowCommand
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
        if(e.CommandName=="Add")
        {
           int index = Convert.ToInt32(e.CommandArgument);

           GridViewRow row = ContactsGridView.Rows[index];

           Session["YourKey"] = ...;
        }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как добавить коллекцию элементов в переменную Как добавить коллекцию элементов в переменную?
Нужно добавить, каждый второй элемент
Пример что нужно:
var  $item_v = $(".aе");
var  $item_b;

  for(var i_nav4 = 0; i_nav4 < 4 ; i_nav4++){
     //тут мы должны добавлять элементы коллекции объекта $item_v в $item_b

       if(i_nav4 === 1 || i_nav4 === 3 ){
         находим элемент-------->$item_v.eq(i_nav4)
         $item_b <--- добавляем сюда найденный элемент
        }
    }

A: Икебану его, вот вам фильтрация:

$(function() {
  var d = $('div').filter(function(index, elem) {
    return (index % 2 != 0);
  }).clone();
  console.log(d);
  d.css('border', '2px solid tomato').appendTo('body');
});
div {
  margin-bottom: 5px;
}

lorem lorem lorem lorem lorem lorem lorem

2 lorem lorem lorem lorem lorem lorem lorem

lorem lorem lorem lorem lorem lorem lorem

4 lorem lorem lorem lorem lorem lorem lorem

lorem lorem lorem lorem lorem lorem lorem

6 lorem lorem lorem lorem lorem lorem lorem

Результат будет тут:

A: Если я вас правильно понял, то надо как-то так:
var $item_b = {};

for (var attr in $item_v) {
    if (item_b.hasOwnProperty(attr)) item_b[attr] = obj[attr];
}

Более подробно про копирование объектов читайте тут

A:

   var $item_v = $(".ae");
   var $item_b;
   for (var i_nav4 = 0; i_nav4 < 4; i_nav4++) {

     if (i_nav4 === 1 || i_nav4 === 3) {

       $item_b = $item_b ? $item_b.add($item_v.eq(i_nav4)) : $item_v.eq(i_nav4)
     }
   }
   $item_b.css({
     "background-color": "#FF00FF"
   })

0
1
2
3
4
5


text:
Q: React Testing Library: Cannot use import statement outside a module I'm using react testing library for running tests inside a react application.
I've installed the library compress.js which imports the following module import "regenerator-runtime/runtime.js"; inside node_modules/compress.js/src/index.js
When running react-scripts test I receive the following error:
....\node_modules\compress.js\src\index.js:2
    import "regenerator-runtime/runtime.js";

SyntaxError: Cannot use import statement outside a module

I'm using the following version for testing-library:
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^8.0.4",

Is there a way to enable ES Modules imports?


text:
Q: Is there a way to autofill required class / widget properties in vscode / visual studio code flutter? When constructing a class / widget, usually there are some properties that are required and some that are optional (using @required decorator in the class constructor).
It would be nice if vscode automatically fill in the required keys (eg. child:, onTap:) of these properties instead of just telling an error that "The parameter 'requiredParameter' is required.dart(missing_required_param)".
For example
//example of the class with constructors that we want to use
class Product {
  final String id;
  final String title;
  final String description;
  double price;
  String imageUrl;
  bool isFavorite;
  Product({
    @required this.id,
    @required this.title,
    @required this.description,
    this.price,
    this.imageUrl,
    this.isFavorite = false,
  });
}

//desired behavior of autocomplete / shortcut
Product(
    id: ,
    title: ,
    description: ,
)

Currently, what I do is I manually add the required parameter from the class documentation / vscode popup instructions (eg:
The parameter 'price' is required.dart(missing_required_param)
The parameter 'id' is required.dart(missing_required_param)
The parameter 'title' is required.dart(missing_required_param)

)

A: Open VS Code settings.json and add the following:
"dart.previewNewCompletionPlaceholders": true

EDIT 2020-01-21:
Thanks William Terrill for your comment mentioning this, this feature is no longer in preview and can be activated with the following command:
"dart.insertArgumentPlaceholders": true

A: If you are using VSCode, install Dart Data Class Generator

*

*Create a class with properties.

*Place your cursor on the first line of the class, the constructor or
a field.

*Hit CTRL + . to open the quick fix dialog.

*Choose Generate constructor.


text:
Q: azure app service Installation error: EACCES: permission denied, mkdir '/opt/Kudu/local/npm-cache' I am trying to sync the app service which is linked with the bitbucket. when i try to sync data from the bitbucket its showing me below error
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
error /tmp/8da38dcb36cf63a/node_modules/sharp: Command failed.
Exit code: 1
Command: (node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy)
Arguments:
Directory: /tmp/8da38dcb36cf63a/node_modules/sharp
Output:
sharp: Installation error: EACCES: permission denied, mkdir '/opt/Kudu/local/npm-cache'
sharp: Are you trying to install as a root or sudo user? Try again with the --unsafe-perm flag
sharp: Please see https://sharp.pixelplumbing.com/install for required dependencies
warning "@strapi/plugin-users-permissions > @strapi/helper-plugin
anyone can help me ?
what's  the solution

A: The problem is it does npm install on the npm-cache folder, but it does not have rights to do so.
I resolved it with creating a new "Application Setting" on Azure PRE_BUILD_COMMAND with value: mkdir ./npmcache && npm config set cache ./npmcache.
This command is executed before the yarn/npm install + build. It create a new folder, having write rights on it. Then it set this folder as the npm cache folder.


text:
Q: Most pythonic method for initializing class from file? Forgive my Python noob-ism, but I have written this pattern in several other languages, and can't find a boilerplate for Python that seems... pythonic, I guess.
I want a base class that either takes a set of default parameters, or loads itself from a file.  It then has a save() method that saves its instance data to the given named file.
Critically, I want to be able to modify the classes that inherit from the base class to add or remove attributes, and still have the old attributes loaded from the old files.  This code appears to work (2.7):
import pickle
class Thing(object):
    def __init__(self, filename=''):
        self.filename = filename
        if self.filename:
            self._load()
    def save(self):
        with open(self.filename, 'wb') as f:
            pickle.dump(self,f)
    def _load(self):
        try:
            with open(self.filename, 'rb') as f:
                self.__dict__.update(pickle.load(f).__dict__)
            return True
        except:
            return False

Then the inheriting class:
class BiggerThing(Thing):
    def __init__(self, filename='', x=0, y=0):
        self.x = x
        self.y = y
        #self.whoops = 'swell'
        super(BiggerThing, self).__init__(filename)

This seems to work:  I can do:
t = BiggerThing('file.pickle', x=1, y=2)
t.save()

And I'll get the the proper object when I do:
t2 = BiggerThing('file.pickle')

And equally important, if I un-comment the 'self.whoops' line and load the old file, I still get back the object with x=1 and y=2, and can then save() the new object with 'whoops' set.
This just seems like it would be a common pattern for making self-loadable objects, but I haven't seen it like this and wonder if it's because it isn't very pythonic?


text:
Q: Functional Stateless Components and Keys How do you Map a key in a functional component, precisely the 'key' keyword, not just a general index?
I'm using Map in one functional component to create a list of another element, but when I use 'key' to remove the console warning the code breaks.
I can switch the included props to 'index' and get working code, but then get the warning that I am missing a 'key' index in a list.
As per: Stateless React how to pass key
The answer provided does not explain how to pass the specific case of a 'key' (note the keyword key rather than a general index) to a functional component.
// results in an undefined key ie: key=''
const ComponentOne = ({records}) => (
  {records.map( (record, index) => <ComponentTwo data={record} key={index}/>)}
);

const ComponentTwo = ({data, key}) =>

    {data}

// This method works but comes with the console warning for a 'missing key'
const ComponentOne = ({records}) => (
  {records.map( (record, index) => <ComponentTwo data={record} index={index}/>)}
);

const ComponentTwo = ({data, index}) =>

    {data}

https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
This link also discusses why using an index as a key is an antipattern, so I'm breaking the rules if I use 'index', but functional components don't allow for the use of 'key' as it's a particular keyword with significant meaning.

A: Try something like that

    const ComponentOne = ({records}) => (
      <React.Fragment>
       {records.map( (record, index) => <ComponentTwo data={record} key={index}/>)}
      </React.Fragment>
    );

You can also pass a unique property from records as key, like id or something like.


text:
Q: Dropdown menu and link to pages in pelican bootstrap theme I'm working with the pelican-bootstrap3 theme and I have a trivial question that I cannot solve by myself.
I have some pages and what I'd like to to is to create a dropdown menu for some pages of another page.
Suppose I have this situation:
├── content
│   ├── pages
│   │   ├── about.md
│   │   ├── courses_list.md
│   │   └── first-corse.md
│   │   └── second-corse.md

and I'd like to have the main navbar with the course-list visible and fist-course and second-course as submenu of the dropdown.
The html piece of code I'm trying (without success) to edit is the base.html:
        {% if DISPLAY_PAGES_ON_MENU %}
            {% for p in pages | sort(attribute=PAGES_SORT_ATTRIBUTE) %}
                {% if p.url %}

                     {{ p.menulabel|default(p.title) }}

                {% endif %}
              {% endfor %}
        {% endif %}

Somebody has had a similar issue?
Thanks to all!

A: Pelican authors does not prefer hierarchical menus (as an antipattern) in its core functionality. Instead, they welcome plugins or theme templates to handle this functionality if necessary.
So it is (merely) on your own to deploy that functionality.
There are (maybe more) themes on github adressing hierarchical menus, like pelican-chameleon theme, using MENUITEMS definition like in this example taken from chameleon readme.
# works with chameleon theme
MENUITEMS = [
    ('Home', '/'),
    ('Archives', [
        ('Tags', '/tags.html'),
        ('Categories', '/categories.html'),
        ('Chronological', '/archives.html'),
        ]),
    ('Social', [
        ('Email', 'mailto: xx@yy'),
        ('Github', 'http://url-to-github-page'),
        ('Facebook', 'http://url-to-facebook-page'),
        ]),
    ]


text:
Q: Convert images to TIFF G4 results in too large files I am converting gif images to java this way:
  File infile = new File(filename);
  BufferedImage bufimg = ImageIO.read(infile);

  ImageWriter writer = ImageIO.getImageWritersByFormatName("tiff").next();
  ImageWriteParam param = writer.getDefaultWriteParam();
  param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
  param.setCompressionType(COMPRESSION_TYPE_GROUP4FAX);
  File outfile = new File(outFilename);
  ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
  writer.setOutput(ios);
  // image4j for reducing to black & white
  BufferedImage convertedImage = ConvertUtil.convert1(bufimg);
  writer.write(null, new IIOImage(convertedImage ,null,null),param);
  writer.dispose();

I also tried it without using image4j:
  IndexColorModel icm = new IndexColorModel(1, 2, new byte[] { (byte) 0,
      (byte) 0xFF }, new byte[] { (byte) 0, (byte) 0xFF },
      new byte[] { (byte) 0, (byte) 0xFF });
  BufferedImage convertedImage = new BufferedImage(bufimg.getWidth(), bufimg.getHeight(),
  BufferedImage.TYPE_BYTE_BINARY, icm);
  cco.filter(bufimg, convertedImage);

Both ways work fine except that the resulting file is much larger than the original gif. tiffinfo (from libtiff) recognizes it as G4, irfanview tells me that the current memory size (image size after reading) is 120 kB (compared to 914 kB filesize).
Am I missing something - how could I reduce the file size of the resulting image?


text:
Q: Push httpProvider interceptor outside of config method For reasons that does not make sense to explain here I need to push an interceptor outside of config method. More specifically in the run method of the module. So I created a global reference to the httpProvider and then in the run method I push the interceptor. But the interceptor's responseError callback is never executed. If I put the same line inside the config method it works. In both cases I change the httpProvider using the reference.
Does anyone have any clue on that? How can I push an httpProvider interceptor outside of config method?

A: As we know that all services/factories are singleton objects. They are instantiated only once. So we need to configure the interceptor before the  service instantiate.
The config function is useful to configure providers before they're actually created. The config method runs just after the angular app boostraps. It's the first method to run. So if you putt he interceptor in config it will modify the service before it's created.
But the run method will execute later. The run function could be useful to perform any kind of initialization after the objects instances registered in the module have already been created.  That's the reason why you're not finding it working.


text:
Q: Getting the location of a mouse click in Matplotlib using Tkinter I am trying to write a simple GUI in python that displays a plot and then allows the user to click on certain key characteristics (turning points etc), which will then be used as a starting point for a fitting algorithm I'm developing.
I found the following thread to get me started; Store mouse click event coordinates with matplotlib
This only seems to give me the pixel locations of the mouse from my computer's perspective. What I would ideally like is to be able to get at the coordinates on the right hand side of the toolbar and use those; it seems a shame to try to write my own pixel->data transform when matplotlib is clearly already doing it for me somewhere.
Here is the code I have so far, if it looks like I'm approaching the problem in the wrong manner please tell me, I'm not too proud to start over.
import matplotlib
matplotlib.use('TkAgg')

import Tkinter as tk

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import MouseEvent
from matplotlib.figure import Figure

import numpy as np

def callback(event):
    print "clicked at", event.x, event.y

root = tk.Tk()

f = Figure(figsize=(5,4), dpi=100)
a = f.add_subplot(111)
t = np.arange(0.0,3.0,0.01)
s = np.sin(2*np.pi*t)

a.plot(t,s)

canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

canvas.mpl_connect('button_press_event',callback)
def callback(event):
    print "clicked at", event.xdata, event.ydata

toolbar = NavigationToolbar2TkAgg( canvas, root )
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

toolbar

root.mainloop()

A: Edit:  I jumped into answering without reading your example completely.  The problems you're having are due to the order that you've defined things in. Basically, you have:
import matplotlib.pyplot as plt

def callback(event):
    print event.x, event.y

fig, ax = plt.subplots()

fig.canvas.callbacks.connect('button_press_event', callback)
def callback(event):
    print event.xdata, event.ydata

When you're connecting the callback, the second function hasn't been defined yet, so it's connecting to the earlier function with the same name.  Either move the callback connection after the function is defined, or just move the function definition up and delete the (unused) first callback function.
Regardless, have a look at matplotlib's transforms to understand how you'd transform between display/pixel coordinates and plot coordinates.   I'll leave my original answer in the hope it helps someone else who comes across this question.

If I'm understanding you correctly, you want the data coordinates where the mouse click occured?
If so, use event.xdata and event.ydata.
As a quick example:
import matplotlib.pyplot as plt

def on_click(event):
    if event.inaxes is not None:
        print event.xdata, event.ydata
    else:
        print 'Clicked ouside axes bounds but inside plot window'

fig, ax = plt.subplots()
fig.canvas.callbacks.connect('button_press_event', on_click)
plt.show()

In general, though, have a look at matplotlib's transforms for transforming between display, figure, axes, and data coordinates.
For example, the eqivalent of event.xdata and event.ydata would be:
x, y = event.inaxes.transData.inverted().transform((event.x, event.y))

It's a bit verbose, but ax.transData is the transformation between display (pixel) coordinates and data coordinates.  We want to go the other way, so we invert the transformation with trans.inverted().  Transforms deal with more than just points (usually you use them to plot something in another coordinate system), so to convert a set of points, we need to call the transform method.
It seems cumbersome at first, but it's actually rather elegant. All plotted artists take a transfom argument that defines the coordinate system they're drawn in. This is how things like annotate allow a location defined by an offset in points from another location in data coordinates.


text:
Q: ¿ Cómo recorrer tablas fila por fila y obtener todos los valores de los elementos? acudo por ayuda debido a que tengo problemas para obtener los valores de una tabla.ya que la tabla tiene elementos como input y select...
Bueno lo que quiero hacer es que me obtenga todos los valores de dicha tabla, en cuanto a input ya me obtiene pero en cuanto a un select aun sigo teniendo problemas y de la misma forma que cada vez que hago un click en el botón "recorrer" no duplique los datos en otras filas como se puede ver en el script..

$(document).ready(function() {
  $("#btn-new").on('click', function() {
    var html = '
' +
      '<input type="text" class="form-control txt" onkeyup="">	' +
      '' +
      '<select name="md" class="form-control sele" id="">' +
      '<option value="0">Seleccionar...</option>' +
      '<option value="1">Kilos</option>' +
      '<option value="2">Metros</option>' +
      '</select>' +
      '	' +
      '' +
      '<select name="ds" class="form-control sele2" id="">' +
      '<option value="0">Seleccionar...</option>' +
      '<option value="1">Lorem ipsum dolor sit amet, consectetur.</option>' +
      '<option value="2">Descripcion numero 02.</option>' +
      '</select>' +
      '	' +
      '<input type="text" class="form-control txt" onkeyup="">	' +
      '<input type="text" class="form-control txt" onkeyup="">	' +
      'Eliminar	' +
      '
';
    $("#tbody").append(html);
  });
  $("#btnRecorrer").on("click", function() {
    var sele = $(".sele option:selected").text();
    var sele2 = $(".sele2 option:selected").text();
    alert(sele + '\n' + " * " + sele2 + '\n');
    $("#tabla tbody tr").each(function(index) {
      var campo1, campo2, campo3, campo4, campo5;
      $(this).find("td input.txt").each(function(index2) {
        switch (index2) {
          case 0:
            campo1 = $(this).val();
            break;
          case 1:
            campo2 = $(this).val();
            break;
          case 2:
            campo3 = $(this).val();
            break;
          case 3:
            campo4 = $(this).val();
            break;
          case 4:
            campo5 = $(this).val();
            break;
        }
      });
      var html = '
' +
        '' + campo1 + '	' +
        '' + campo2 + '	' +
        '' + campo3 + '	' +
        '' + campo4 + '	' +
        '' + campo5 + '	' +
        '
';
      $("#body").append(html);
    });
  });
});
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Ventas C.I.</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <button id="btn-new" class="btn btn-success">Agregar Nuevo</button>

            CANTIDAD
            MEDIDA
            DESCRIPCION
            PRECIO
            TOTAL
            OPCION

      <button id="btnRecorrer" class="btn btn-primary pull-left">Recorrer</button>

            Valor 1
            Valor 2
            Valor 3
            Valor 4
            Valor 5

A: Es porque aquí find("td input.txt") solo estás agarrando los input de tipo text, si quieres que te elija los select y text puedes hacerlo con find("input, select") o para todos los tipos de input con find(":input").
Tu código con el segundo:

$(document).ready(function() {
  $("#btn-new").on('click', function() {
    var html = '
' +
      '<input type="text" class="form-control txt" onkeyup="">	' +
      '' +
      '<select name="md" class="form-control sele" id="">' +
      '<option value="0">Seleccionar...</option>' +
      '<option value="1">Kilos</option>' +
      '<option value="2">Metros</option>' +
      '</select>' +
      '	' +
      '' +
      '<select name="ds" class="form-control sele2" id="">' +
      '<option value="0">Seleccionar...</option>' +
      '<option value="1">Lorem ipsum dolor sit amet, consectetur.</option>' +
      '<option value="2">Descripcion numero 02.</option>' +
      '</select>' +
      '	' +
      '<input type="text" class="form-control txt" onkeyup="">	' +
      '<input type="text" class="form-control txt" onkeyup="">	' +
      'Eliminar	' +
      '
';
    $("#tbody").append(html);
  });
  $("#btnRecorrer").on("click", function() {
    $("#body").html(""); // Limpiamos la tabla para que no se dupliquen los datos
    $("#tabla tbody tr").each(function(index) {
      var campo1, campo2, campo3, campo4, campo5;
      $(this).find(":input").each(function(index2) {
        switch (index2) {
          case 0:
            campo1 = $(this).val();
            break;
          case 1:
            campo2 = $(this).val();
            break;
          case 2:
            campo3 = $(this).val();
            break;
          case 3:
            campo4 = $(this).val();
            break;
          case 4:
            campo5 = $(this).val();
            break;
        }
      });
      var html = '
' +
        '' + campo1 + '	' +
        '' + campo2 + '	' +
        '' + campo3 + '	' +
        '' + campo4 + '	' +
        '' + campo5 + '	' +
        '
';
      $("#body").append(html);
    });
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <button id="btn-new" class="btn btn-success">Agregar Nuevo</button>

          CANTIDAD
          MEDIDA
          DESCRIPCION
          PRECIO
          TOTAL
          OPCION

    <button id="btnRecorrer" class="btn btn-primary pull-left">Recorrer</button>

          Valor 1
          Valor 2
          Valor 3
          Valor 4
          Valor 5


text:
Q: Template based XML to CSV conversion I am new to C# and I know this will be a very tough and challenging task for everyone. I have a case where I need to convert template based XML to CSV. I have listed the Template, Sample XML and Expected CSV below.
My Template will have some number of columns which should be the headers in output CSV. We want to match the each column from the Template with XML and check if it is present or not. If Template column value is present in XML the add it into the CSV and if not present then add it as null as given in below example.
Also in given XML example, it has three types of rows

*

*TRX

*TRXR

*TRXC
We have to take only first two types of rows into consideration. We have to ignore the TRXC type rows from the XML.

Given Template

var templeteList = new List<string> //Consider this as my template
        {
           "ID",
           "Name",
           "Address",
           "Phone",
           "Email",
           "Gender"
        };

Sample XML

<?xml version="1.0" encoding="utf-8"?>
<StudentXML>
    <TRX ID="2" Name="Smita" Address="Pune" Gender="F" Phone="987654321"/>
    <TRX ID="2" Name="Ram"  Phone="3554321" Email="ram@mail.com" />
    <TRX ID="1" Name="John" Address="Mumbai" Phone="NULL" Email="John@mail.com" Gender="M" />
    <TRXR ID="3" Name="NULL" Address="Mumbai" Phone="121212" Email="Don@mail.com" Gender="M" />
    <TRXC ID="3" Name="Prem" Address="Mumbai" Phone="121212" Email="Prem@mail.com" Gender="M"/>
</StudentXML>

Expected Output

"ID", "Name",   "Address",    "Phone",           "Email",          "Gender"
"2",   "Smita",  "Pune",      "987654321",       "NULL",            "F"
"2",   "Ram",    "NULL",      "3554321",         "ram@mail.com",    "NULL"
"1",   "John",   "Mumbai",    "NULL",            "ohn@mail.com",    "M"
"3",   "NULL",   "Mumbai",    "121212",          "Don@mail.com",    "M"

I tried to use XML Reader, but it takes to much longer to convert XML to CSV for 0.6 million XML rows.
 var dataSet = new DataSet();
 dataSet.ReadXml("XML File Name");//This line takes to much longer

If anyone can help me out from here, I will be hearty thankful.

A: You can use Linq to XML to get the info first and then process it to convert it in a csv as I show below:
XElement students= XElement.Load("YourXml.xml");
string csv =
    (from el in students.Elements()
     where el.Name!="TRXC"
     select
        String.Format("{0},{1},{2},{3},{4},{5},{6}",
            (string)el.Attribute("ID"),
            (string)el.Attribute("Name"),
            (string)el.Attribute("Address"),
            (string)el.Attribute("Phone"),
            (string)el.Attribute("Email"),
            (string)el.Attribute("Gender"),
            Environment.NewLine
        )
    )
    .Aggregate(
        new StringBuilder(),
        (sb, s) => sb.Append(s),
        sb => sb.ToString()
    );
 string header="ID,"+""+"Name,"+"Address,"+"Phone,"+"Email,"+"Gender,"+ Environment.NewLine;
 File.WriteAllText("yourCSV.csv", header+csv);

StringBuilder will help you to construct the result efficiently. If you try to concat element by element, you are going to create a new string every time you apply that operation which could affect your performance due to your amount of elements. I suggest you to read this Jon Skeet's article for more details
Update 1
You can also do this to create your header:
var templeteList = new List<string> //Consider this as my template
        {
           "ID",
           "Name",
           "Address",
           "Phone",
           "Email",
           "Gender",
           Environment.NewLine
        };
var header=String.Joing(",",templateList);

Update 2
To do the same dynamically you will need to change a little bit my previous query:
var templeteList = new List<string> //Consider this as my template
        {
           "ID",
           "Name",
           "Address",
           "Phone",
           "Email",
           "Gender"
        };
string csv =students.Elements()
                    .Where(el=>el.Name!="TRXC")
                    .Select(el=>{
                                  string result="";
                                  for(int i=0; i<templeteList.Count;i++)
                                  {
                                    result+=((string)el.Attribute(templateList[i])) +",";
                                  }
                                  result+= Environment.NewLine;
                                  return result;
                                })
                    .Aggregate(new StringBuilder(),
                               (sb, s) => sb.Append(s),
                                sb => sb.ToString()
                               );

A: XmlReader is the fastest way to parse XML. You have not shown your code using XmlReader, but you probably did something wrong. However, I can bet that this method is the fastest.
Try this code:
var templateList = new List<string> { "ID", "Name", "Address", "Phone", "Email", "Gender" };

using (var xmlReader = XmlReader.Create("test.xml"))
using (var csvWriter = new StreamWriter("test.csv"))
{
    csvWriter.WriteLine("\"" + string.Join("\",\"", templateList) + "\"");
    xmlReader.MoveToContent();

    while (xmlReader.Read())
    {
        if (xmlReader.NodeType == XmlNodeType.Element
            && xmlReader.Name != "TRXC")
        {
            csvWriter.Write('"');

            for (int i = 0; i < templateList.Count; i++)
            {
                if (xmlReader.MoveToAttribute(templateList[i]))
                    csvWriter.Write(xmlReader.Value);
                else
                    csvWriter.Write("NULL");

                if (i < templateList.Count - 1)
                    csvWriter.Write("\",\"");
            }
            csvWriter.WriteLine('"');
        }
    }
}

Test the code and report the results. If it's performance will be slow (sure?), we can try to speed it up with the use of NameTable.

What is your ultimate goal? It's weird: at first parse xml, creating a csv, then immediately parse the csv, creating something else.
OK, look this code:
IEnumerable<string[]> ParseXml()
{
    var templateList = new List<string> { "ID", "Name", "Address", "Phone", "Email", "Gender" };

    using (var xmlReader = XmlReader.Create("test.xml"))
    {
        yield return templateList.ToArray(); // header
        xmlReader.MoveToContent();

        while (xmlReader.Read())
        {
            if (xmlReader.NodeType == XmlNodeType.Element
                && xmlReader.Name != "TRXC") // exclude TRXC
            {
                string[] result = new string[templateList.Count];

                for (int i = 0; i < templateList.Count; i++)
                {
                    if (xmlReader.MoveToAttribute(templateList[i]))
                        result[i] = xmlReader.Value;
                    else
                        result[i] = "NULL";
                }
                yield return result; // each row
            }
        }
    }
}

Use:
foreach (string[] row in ParseXml())
{
    // process row
    // or
    foreach (string value in row)
    {
        // process value
    }
}

We do not create intermediate csv. We immediately process each string while xml parsing.

A: You can use the MemoryStream to write data from StreamWriter. Then read the MemoryStream using StreamReader as below,
            var templateList = new List<string>
            {
               "ID",
               "Name",
               "Address",
               "Phone",
               "Email",
               "Gender"
            };

            using (XmlReader xmlReader = XmlReader.Create("MyXMLFile.xml"))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (StreamWriter csvWriter = new StreamWriter(memoryStream))
                    {
                        csvWriter.WriteLine("\"" + string.Join("\",\"", templateList) + "\"");
                        xmlReader.MoveToContent();
                        while (xmlReader.Read())
                        {
                            if (xmlReader.NodeType == XmlNodeType.Element &&
                                (xmlReader.Name == "TRX" || xmlReader.Name == "TRXR"))
                            {
                                csvWriter.Write('"');

                                for (int i = 0; i < templateList.Count; i++)
                                {
                                    csvWriter.Write(xmlReader.MoveToAttribute(templateList[i]) ? xmlReader.Value.Replace(",", string.Empty) : null);

                                    if (i < templateList.Count - 1)
                                        csvWriter.Write("\",\"");
                                }
                                csvWriter.WriteLine('"');
                            }
                        }
                        csvWriter.Flush();
                        memoryStream.Position = 0;
                        using (StreamReader streamReader = new StreamReader(memoryStream))
                        {
                            while ((streamReader.ReadLine()) != null)
                            {
                                //Parse your csv line by line
                            }
                        }
                    }
                }
            }


text:
Q: Pegar dados de usuário do JSON por jquery Tenho um json que estou executando através do json-server e esta no endereço: http://localhost:3000/
Dentro dele, tem um escopo de "users", na qual eu gostaria de pegar.
Eu tenho o seguinte script que montei, segue:
$.getJSON(urlParam, function (data) {
        let itens = []
        $.each( data, function (key, val) {
            itens.push( {key, val} )
        })
        return itens
})

Eu gostaria de pegar tanto uma lista de usuários, que seja convertida para json, tanto um usuário apenas.
Segue meu json:
{
  "alunos": [
    {
      "id": 1,
      "nome": "Thiago Cunha"
    },
    {
      "id": 2,
      "nome": "Caroline Cunha"
    },
    {
      "id": 3,
      "nome": "Thalita Cunha"
    }
  ],
  "users": [
    {
      "id": 1,
      "nome": "Thiago Cunha",
      "img": "dist/images/thiago.jpg",
      "status": true
    },
    {
      "id": 2,
      "nome": "Caroline Cunha",
      "img": "dist/images/thiago.jpg",
      "status": true
    },
    {
      "id": 3,
      "nome": "Thalita Cunha",
      "img": "dist/images/thiago.jpg",
      "status": true
    }
  ]
}

Alguém pode me ajudar por favor?

A: Na minha humilde opinião você poderia criar um endpoint diferente para buscar o registro individual do usuário, ficando um para a busca do usuário e outro para todos os usuários.
Por Exemplo: url /users para todos os usuários e a url /user/id  (onde id é a chave primária ou identificador do usuário) para o registro individual do usuário.


text:
Q: radio button getting automatically unchecked after some time i have build a quiz app in VB . Radio  buttons for answers are being selected and accordingly score is being calculated and displayed correctly. But the radio buttons are getting automatically unchecked after sometime and score is reset to 0. i am not being able to figure out why is this happening. can anyone help?

A: It sounds like the form is being unloaded, then displayed again. You can see if this is the case by putting a breakpoint int the form load handler.


text:
Q: Using mmv, how to strip folder names of a "+" I have a bunch of folders with + instead of spaces.
I tried mmv '*+*' '#1_#2' as well as mmv '*\+*' '#1_#2' with the result

+ -> #1_#2 : no match.

and

+ -> #1_#2 : no match.

respectively.
What am I missing?

A: Do it as mmv -r '*+*' '#1_#2'
man mmv says,
-r :   rename source file or directory to target name. The target name must not
       include a path: the file remains in the same directory in all cases. This
       option is the only way of renaming directories under mmv.

A: I haven't used mmv before, but for something like this I'd go into the folder that you want to rename files in, and in a bash shell do something like:
for f in *; do mv "$f" "${f//+/ }"; done

Someone else here showed me this, and I asked about it. the ${f//+/ } is called Bash Shell Expansion. //+/ substitutes a space for a plus.


text:
Q: How can I specify the spring-data-mongodb version using spring-boot? I want to use the latest version of spring-data-mongodb, in order to use the full text search feature, but I don't know how I can specify this using the spring-boot-starter-data-mongodb dependence.
You can read here: maven repository that the spring-data-mongodb version is not specify.
This is my pom file:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.6.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Boot Rest -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <!-- Spring Boot Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- Spring MongoDB integration -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>

A: Spring Boot defines all its dependencies and dependency versions in the spring-boot-dependencies project. This project only contains a pom with only dependencies and versions as properties.
Spring Data releases all of its compatible releases in a so called release train and this makes sure that all dependencies of that version will work together.
When you take a closer look a the pom you will see a maven property named spring-data-releasetrain.version and for the upcoming Spring Boot 1.2 it points to the latest release train version Evans-RELEASE. The 1.1.7 version points to the previous version Dijkstra-SR4. I would suggest an upgrade from 1.1.6 to 1.1.7 just in case.
You're project already has the spring-boot-starter-parent project as its parent so in theory upgrading the Spring Data versions should be as easy as overriding the specified property.
<properties>
    <spring-data-releasetrain.version>Evans-RELEASE</spring-data-releasetrain.version>
</properties>

As mentioned earlier the use of the release train is preferred as this will make sure you get all the compatible versions.

A: You can find that mongodb dependency in the parent project pom file
/../.m2/repository/org/springframework/boot/spring-boot-dependencies/2.3.0.RELEASE/spring-boot-dependencies-2.3.0.RELEASE.pom

That file defines all the dependency version for other libs SpringBoot use
<properties>
    <activemq.version>5.15.12</activemq.version>
    <antlr2.version>2.7.7</antlr2.version>
    ...
    <mongodb.version>4.0.3</mongodb.version>
    ...
</properties>

So if you want to use different version for mongodb, define a properties in your pom file to override the default one like (I think this will only work if you use spring-boot-starter-parent as parent )
<properties>
    <mongodb.version>3.11.2</mongodb.version>
</properties>

A: Answer by @sendon1982 worked for me.  Here is an example of my POM.XML.  I am adding it as an answer here because I could not paste in my pom file as a comment to sendon1982 answer...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>test.barry</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <start-class>test.barry.Main</start-class>
        <mongodb.version>4.1.0</mongodb.version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>4.1.0</version>
        </dependency>
    </dependencies>
</project>


text:
Q: How to specify model artifact name from config.pbtxt file when using .pth extension I am having a pytorch artifact named model.pth but the Triton server is looking only for model.pt file which is by default here https://github.com/triton-inference-server/pytorch_backend/blob/4a971e6b6789310609ca84cf1c532084c1c6edc9/src/libtorch.cc#L209-L215
So, how do I override this config from config.pbtxt file so that I can point it to my .pth file. Which parameter to use in config.pbtxt file to do this ?


text:
Q: Why does this facebook create album code create duplicate albums? I have this code that works fine (in that it creates the album properly). However, it creates two identical albums. I've tried removing message and privacy (not that this should have changed anything, but still). Nothing I try is changing the fact that this code creates two albums. I've even gone so far as to comment it out to ensure that it was the only code firing and no albums were created. I have code after this to post two test pictures and it only posts the pictures to one of the groups. However, I have an exit after this code, so I've ensured it's the only code firing.
Help, Please!
print "Creating album\n";
try {
    $ret_obj = $facebook->api('/me/albums', 'post', array(
        'access_code' => $access_code,
        'name' => 'Coolest Album',
        'message' => 'Coolest Album containing bike stuff',
        'privacy' => array('value'=>'EVERYONE'),
        ));
} catch (Exception $e) {
print_r($e->getMessage());
}
print "Album created\n";`

A: What version of php are using? And, what is the version of the Facebook API? If you use Facebook 2.0, you need php 5.4 or 5.5.
Maybe that could help?

A: The issue was not with the SDK but with Facebook itself. I had created a bug report after doing some more tests. Facebook confirmed and fixed the bug. Basically, it had to do with inappropriate permissions handling.
https://developers.facebook.com/bugs/1435856773345641/


text:
Q: nan on loss function tensorflow I try to build a model that will identify by data and try to see the LOSS function
loss =tf.reduce_mean(-(y_ * tf.log(y)+(1- y_)* tf.log (1-y)))
But as of now I only get NAN on the prediction and printing NAN in the LOSS function
np_labels = np.array(labels)
np_labels = np_labels.reshape([np_labels.shape[0], 1])
features = 910
hidden_layer_nodes = 100
x = tf.placeholder(tf.float32, [None, features])
y_ = tf.placeholder(tf.float32, [None, 1])
W1 = tf.Variable(tf.truncated_normal([features,hidden_layer_nodes], stddev=0.1))
b1 = tf.Variable(tf.constant(0.1, shape=[hidden_layer_nodes]))
z1 = tf.add(tf.matmul(x,W1),b1)
a1 = tf.nn.relu(z1)
W2 = tf.Variable(tf.truncated_normal([hidden_layer_nodes,1], stddev=0.1))
b2 = tf.Variable(0.)
z2 = tf.matmul(a1,W2) + b2
y = 1 / (1.0 + tf.exp(-z2))

loss =tf.reduce_mean(-(y_ * tf.log(y)+(1- y_)* tf.log (1-y)))

update = tf.train.AdamOptimizer(0.01).minimize(loss)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(0,50):
        sess.run(update, feed_dict = {x:fvecs, y_:np_labels})
        print(sess.run(loss, feed_dict={x: fvecs, y_: np_labels}))

      #  sess.run(update, feed_dict = {x:data_x, y_:data_y})
     #   print(sess.run(loss, feed_dict={x: data_x, y_: data_y}))

print('prediction: ', y.eval(session=sess, feed_dict =  {x:[[493.9, 702.6, .....

i want to print the loss
Thanks

A: This is not a TensorFlow-Issue. This results from the very bad idea of implementing the loss-function yourself.
import tensorflow as tf

z2 = tf.random_normal([8, 10]) * 20
y_ = tf.random_uniform([8, 1], minval=0, maxval=10, dtype=tf.float32)

y = 1 / (1.0 + tf.exp(-z2))

loss = tf.reduce_mean(-(y_ * tf.log(y)+(1- y_)* tf.log (1-y)))

with tf.Session() as sess:
    print sess.run(loss)  # will always fail with high prob

Will give Inf just because of missing the log-sum-exp trick which then causes your implementation to fail due to numerical instabilities (a folklore example which produces overflows). Just run this code several times and you get either NaN or Inf.
Solution would be:

*

*replace y = tf.sigmoid(-z2) by y = tf.identity(z2) to just get the untransformed logits

*replace loss = .. by loss = tf.nn.sigmoid_cross_entropy_with_logits(...) to use the numerical stable way

See the docs of sigmoid_cross_entropy_with_logits which explicitly describes this issue.


text:
Q: In Laravel Backpack need to list users with specific role please check the details below, where I have a Organizations module. Where I can create a organization with a owner with role "organization".
The third input is a dropdown where we need to select the user with role "organization"
protected function addOrganizationFields(){
    $this->crud->addFields([
        [
            'name'  => 'name',
            'label' => __('Organization Name'),
            'type'  => 'text',
        ],
        [
            'name'  => 'billing_information',
            'label' => __('Billing Information'),
            'type'  => 'textarea',
        ],
        [
            'name' => 'owner_id',
            'label' => __('Organization Owner'),
            'type' => 'select2',
            'entity' => 'owners_list',
            'attribute' => 'name',
            'model' => "App\User",
        ]
    ]);
}

In the organization module I wrote this code.
public function owners_list(){
    return User::whereHas('roles', function($q){
        $q->where('name', 'member');
    })->get();
}

in the Organization model relationship I wrote this.
But showing the list of all users in the drop-down.
Can anybody please tel me what is to be done.

A: You can eliminate options from your select2 field using the "options" attribute mentioned in the docs - https://backpackforlaravel.com/docs/4.1/crud-fields
    [
        'name' => 'owner_id',
        'label' => __('Organization Owner'),
        'type' => 'select2',
        'entity' => 'owners_list',
        'attribute' => 'name',
        'model' => "App\User",

        // add something like this

        'options'   => (function ($query) {
              return $query->whereHas('roles', function($q){
                              $q->where('name', 'member');
                         })->get();
         }), // force the related options to be a custom query, instead of all(); you can use this to filter the results show in the select
    ]


text:
Q: What are the use cases to substitute cookbook array attribute in chef? Suppose I should setup unattended_upgrades within latest apt=6.1.4 cookbook.
I use following role for that:
{
  "name": "default_base",
  "description": "Role applied to all workstations and servers",
  "json_class": "Chef::Role",
  "default_attributes": {
    "apt": {
      "unattended_upgrades" : {
        "enable": "true",
        "allowed_origins" : [
          "${distro_id}:${distro_codename}-security"
        ],
        "mail": "ops@example.com"
      }
    }
}

But the final part of config looks like:
Unattended-Upgrade::Allowed-Origins {
        "Ubuntu xenial";
        "${distro_id}:${distro_codename}-security";
};

Ubuntu xenial is a array element defined in apt cookbook `attributes/default.rb file. And it's merged with role attribute as described in doc. This is because it is array.
I found only one workaround - is a reset that attribute in default_attributes section in default_base role. Like follows:
"default_attributes": {
  "apt": {
    "unattended_upgrades" : {
      "allowed_origins" : []
    }
  }
}

As a result, the resulting role contains same attribute declaration in same role, but in different precedence levels.
What is this?
Common use case | Good solution | Dirty hack | Unskillful engineer

A: I think you meant the second of those to be override_attributes, which is a workaround for this. Unfortunately the mechanics of array merging in attributes is very tricky and dependent on a lot Chef internals, so that's probably the easiest option.


text:
Q: Symmetricds - Configure data model schema When trying to setup a target to VoltDB, SymmetricDS fails on schema creation (specifically the table - SYM_INCOMING_ERROR).
Is there a setting to change the schema without having to recompile?
[voltdb] - AbstractSymmetricEngine - An error occurred while starting
SymmetricDS

org.jumpmind.db.sql.SqlException: General Provider Error
(GRACEFUL_FAILURE): 'Error: Table SYM_INCOMING_ERROR has a maximum row size
of 2403801 but the maximum supported row size is 2097152'

A: I would export the DDL SQL, fix the issue and apply it using flyway or liquibase


text:
Q: Python working with special character I have this TRADE MARK SIGN character (u"\u2122").
1) How can I print this character in the terminal without UnicodeEncodeError.
2) I want to open chrome with a specific url and in the url there is this special character. Now normally open chrome with specific url like this:
import os
url = "some-kind-of-url-with-™"
os.system("start chrome " + url)

but I get this error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 67: ordinal not in range(128)

How should I open chrome with a specific url and in the url there is this special character ™


text:
Q: clojure returning hello world and nothing in the output I just started learning Clojure and I have my own Clojure script but it's not returning the output that I am hoping for (Hello World). Here is my code:
(ns com.playground.core
  (:gen-class))

(defn -main
  []
  ((defn CHEESE
     []
     (str "Hello World"))

   (CHEESE)))

This is the output that I get in the REPL:
clj꞉com.playground.core꞉>
#'com.playground.core/-main

I want to see Hello World in the output.

A: You have a double parentheses there. Try this:
(defn -main
  []
  (defn CHEESE
    []
    (str "Hello World"))
  (CHEESE))

Of course your MUST call -main, otherwise you'll see nothing:
(defn -main
  []
  (defn CHEESE
    []
    (str "Hello World"))
  (CHEESE))
=> #'com.playground.core/-main
(-main)
=> "Hello World"

I see your define a function inside another function. You should use let or letfn for this purpose.

A: Starting a REPL for the project does not run -main. Running your program produces the following:
Execution error (ArityException) at com.playground.core/-main (core.clj:6).
Wrong number of args (1) passed to: com.playground.core/-main/CHEESE--177

What is happening?

*

*The defn form creates and registers a function under the name
CHEESE in the com.playground.core namespace.

*The defn form returns the created var, which evaluates to the
function.

*The containing ((defn ...) (CHEESE)) form applies the CHEESE function to
(CHEESE), the result of evaluating the CHEESE function without
arguments,

*... which is the string "Hello World".

It doesn't matter what the argument is, because CHEESE has no arity 1 invocation: you can't apply it to any argument.
You can get the same (bad) effect more simply by pulling the defn for CHEESE out of -main. While we're at it, let's drop the str, which has no effect:
(defn CHEESE []
  "Hello World")

(defn -main []
  (CHEESE (CHEESE)))

Execution error (ArityException) at com.playground.core/-main (core.clj:8).
Wrong number of args (1) passed to: com.playground.core/CHEESE

To put it right, we simply drop the (CHEESE)argument:
(defn -main []
  (CHEESE))

producing ...
Process finished with exit code 0

No returned value, but at least it ran. But if we evaluate (-main) in a REPL, ...
(-main)
=> "Hello World"

There.

A: Actually, It's not exactly wrong.
This return is the "return of declaration".
For example, you defined a -main in the com.playground.core namespace.
The return is the symbol of this declaration #'com.playground.core/-main
To print the Hello world message you need to call the function CHEESE after the declaration.

So... about double parenthesis, it's not good, but not impact hehe.
Another point is the function name, it's not good too. Consider using kebab-case.
You also consider keeping the function declaration more explicitly. Something like that;
(ns com.playground.core
  (:gen-class))

(defn CHEESE [] (str "Hello World"))

(defn -main []
  (CHEESE))

But also did it you're not printing the Hello world. Your only declaring a function (CHEESE) that returns a String type.
To print, you need to call a print function.
(ns com.playground.core
  (:gen-class))

(defn hello [] (str "Hello World"))

(defn -main []
  (print (hello)))

I did the evolution of declarations to explain better

So, you can improve the code using the let alternative and the threading macros
Consider use the https://kimh.github.io/clojure-by-example/ and https://tryclojure.org/ to understand these options better :)


text:
Q: Python dis module weird syntax I was looking at the dis module code in python 2.7.10 and line 47 has some weird syntax I don't understand:
Raise typeerror, \
I was wondering what the ',\' code does as?

A: \ is a line continuation character. It means "this statement continues onto the next line".
If your code looks like,
raise Typeerror, \
"expected string, got tuple"

That behaves identically to
raise Typeerror, "expected string, got tuple"


text:
Q: TYPO3 - Hide "Reset user settings to default state" Button in with UserTS I try to hide all fields in the user-settings, that should not be accessible for non-admins.
In the Tab Edit and advanced functions, i've hidden all fiels with this UserTS:
setup {
    fields {
        startModule.disabled = 1
        edit_RTE.disabled = 1
        resizeTextareas_Flexible.disabled = 1
        resizeTextareas_MaxHeight.disabled = 1
        titleLen.disabled = 1
        thumbnailsByDefault.disabled = 1
        edit_docModuleUpload.disabled = 1
        showHiddenFilesAndFolders.disabled = 1
        copyLevels.disabled = 1
        recursiveDelete.disabled = 1
    }
}

After that I realized that there is a button on the bottom, that has no table-definition that I can find out by the chrome developer console:

Does anyone know a way to hide this button with UserTS, to make the whole Tab disappear?
Thanks :)


text:
Q: Trying to get how many members with specific role discord.js v12 I'm trying to count members of specific role but i'm getting error, message.guild.fetchMembers() is not a function
    let guild = await message.guild.fetchMembers();
    let roleID = '3933783737379';
    let memberCount = guild.roles.get(roleID).members.size;
    message.channel.send(memberCount + " members have this role!");
});

So if i just delete guild variable to make the code the code like this

let roleID = '3933783737379';
    let memberCount = message.guild.roles.get(roleID).members.size;
    message.channel.send(memberCount + " members have this role!");

He will count him self if he has it and count the owner only no one else counted
Is there any idea how to make this work?

A: message.guild.fetchMember(); is not a thing in discord.js v12.

Discord.js v12 its message.guild.members.fetch();

Also members.fetch(); returns a GuildMemberCollection -> GuildMemberManager.fetch()not a guild object. Just await the fetch function and it should work with your second code! :)


text:
Q: The name GridView does not exist in the namespace http://schema.microsoft.com/client/2007 I am experiencing a pretty weird issue in my Windows phone 8.1 Silverlight project. I cannot use ListView et GridView in my XAML. It gives me that error: "The name GridView does not exist in the namespace http://schema.microsoft.com/client/2007 "
I have the correspnding references into my project.
Does anybody have any idea?

A: Have you checked the alias of the namespace? Maybe you can also post some code so that we can be able to see. its likely to be
schemas.microsoft.com/client/2007

schemas not schema


text:
Q: Sorting a number of lists based on two lists in Java I have four lists as follows:
    ArrayList<String> tempNameList = new ArrayList<>();
    ArrayList<String> tempPhoneList = new ArrayList<>();
    ArrayList<String> tempAddressList = new ArrayList<>();
    ArrayList<String> tempBirthdayList = new ArrayList<>();

Each list contains records related to the other lists by index. I am trying to sort all the lists in ascending order by the person's Name and Birthday. I have tried using Collections.sort() but it only supports a single list at a time.
How do I sort all the lists by name and birthday?

A: Sorting of multiple lists of the same size is possible following these steps:

*

*Create an array/list of indexes according to the sorting rules (first by names, then by birthdays in appropriate YYYYMMDD format, etc.)

List<String> names  = Arrays.asList("bbb", "aaa", "bbb", "aaa");
List<String> phones = Arrays.asList("1023456", "1324560", "1227890", "1446752");
List<String> bdays  = Arrays.asList("20001122", "19980105", "20010614", "19990507");

int[] indexes = IntStream.range(0, names.size())
    .boxed()
    .sorted(Comparator.comparing(names::get).thenComparing(bdays::get))
    .mapToInt(Integer::intValue)
    .toArray(); // -> [1, 3, 0, 2]

*Reorder each of the input lists according to the indexes.
A separate method may be created for this:

private static List<String> sort(List<String> list, int[] indexes) {
    return Arrays.stream(indexes).mapToObj(list::get).collect(Collectors.toList());
}
// ...
System.out.println(sort(names,  indexes)); -> [aaa, aaa, bbb, bbb]
System.out.println(sort(phones, indexes)); -> [1324560, 1446752, 1023456, 1227890]
System.out.println(sort(bdays,  indexes)); -> [19980105, 19990507, 20001122, 20010614]

However, it would be more natural to create a container object to combine the values from the different input lists, which has become quite simple after introducing record classes in Java 16, and the sort these objects:
record Person(String name, String phone, String bday) {}

List<Person> persons = IntStream.range(0, names.size())
    .boxed()
    .map(i -> new Person(names.get(i), phones.get(i), bdays.get(i)))
    .sorted(Comparator.comparing(Person::name).thenComparing(Person::bday))
    .collect(Collectors.toList());

persons.forEach(System.out::println);

Output:
Person[name=aaa, phone=1324560, bday=19980105]
Person[name=aaa, phone=1446752, bday=19990507]
Person[name=bbb, phone=1023456, bday=20001122]
Person[name=bbb, phone=1227890, bday=20010614]


text:
Q: MySQL did not use index in SUM with GROUP BY query I just created a table with:
CREATE TABLE `table_test` (
`time` date NOT NULL,
`line_id` char(36) NOT NULL,
`location_id` char(36) NOT NULL,
`placement_id` char(36) NOT NULL,
`flight_id` char(36) NOT NULL,
`impressions` int(11) DEFAULT `0`,
PRIMARY KEY (`time`,`line_id`,`location_id`,`placement_id`,`flight_id`),
KEY `table_test_IDX` (`time`,`placement_id`,`line_id`,`impressions`) USING
BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Then when I try to execute a query:
SELECT
  time,
  placement_id,
  line_id,
  SUM(impressions) AS totalImpress
FROM
  table_test
WHERE
  time BETWEEN '2017-11-01' AND '2017-11-30'
GROUP BY time , placement_id , line_id;

It always uses Using where; Using temporary; Using filesort, in this case, I want the query uses table_test_IDX.
What did I do wrong here?
Many thank.

A: If you peruse the MySQL documentation for optimization of aggregation queries, you will find that there are two methods to optimize a GROUP BY query, namely loose and tight index scans.  However, one caveat for either of these scans is that the only aggregate functions used in the select list are MIN or MAX.  Because you are selecting a SUM, these optimizations are not available.
It makes sense to use an index which can benefit your WHERE clause, because that might let us discard records from the result set early on in the query plan.  However, in order to compute a sum for each group, MySQL has to touch each record in the remaining table.  There is no way around this in order to get a sum, so it does not really matter how we access all these records.

A: I presume you are using UUIDs?  Change CHAR(36) to CHAR(36) CHARACTER SET ascii.  Better would be to pack them into `BINARY(16).  (See http://mysql.rjweb.org/doc.php/uuid .)  This shrinks the size from 108 to 36 to 16.
You say it is using filesort, etc, but is it using PRIMARY?  Please provide the EXPLAIN SELECT ....
But, to get even more speed up, consider building and maintaining "Summary table(s)".  (See http://mysql.rjweb.org/doc.php/summarytables .)  If you had one row in a summary table per combo of (time , placement_id , line_id), the GROUP BY and SUM could be removed.  (If you summarize by hour, you would still need those.)


text:
Q: Adding a delay to submenu dropdown - bootstrap3 I can add a delay to the normal bootstrap3 dropdown menu, but in this instance I only want the delay on the submenu I've created (which isn't out the bootstrap box) - however the jquery used should still work. I need the delay so users can move the cursor to it easily without it closing (because the cursor may drift outside the a:hover element).
Take a look at this bootply - http://bootply.com/101522 and please help or advise why this isnt working!
jQuery('li.dropdown-submenu').hover(function () {
    jQuery(this).find('ul.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function () {
    jQuery(this).find('ul.dropdown-menu').stop(true, true).delay(200).fadeOut();
});

A: You need to remove (from your CSS):
.dropdown-submenu:hover > .dropdown-menu{
    display:block;
}

This is causing it to show up instantly. I tried it in your bootply and it works perfectly.
Good Luck!


text:
Q: Turn Off macOS Mojave Screenshot Preview Thumbnails with defaults write command I'm reading this article, it works.
But how can I turn off macOS Mojave screenshot preview thumbnails with defaults write command?
I just don't know the key value to use.

A: The domain is com.apple.screencapture and the key is show-thumbnail.
So:
defaults write com.apple.screencapture show-thumbnail -bool TRUE

and
defaults write com.apple.screencapture show-thumbnail -bool FALSE


text:
Q: Jenkins trigger another job for specific branch I'd have a pipeline with some jobs until the deploy like that:
(unit test) -> (integration test) -> (package) -> (deploy)
but I'd like to run the jobs (unit test) and (integration test) in all branches,
and run jobs (package) and (deploy) only on changes on branch master.
How can I do it? Are there a conditional trigger plugin?

A: If you have a fixed number of branches, it's easiest to have separate Jenkins jobs for each branch.  If you use a single job to build multiple branches, it will be hard to tell which branch a particular build ran on when you look at the build history.
You can create the jobs for different branches by copying from an existing job via the UI, or you could look at the Job DSL plugin if you want to automate job creation and make it easy to create jobs for new branches.

A: UPDATE: 2018
The flexible publish plugin (github) can do this now.
You can specify run conditions (e.g. based on the a regex match of GIT_BRANCH) and a flexible set of actions to take when conditions match.
I am using this to trigger downstream deployment jobs only for the develop branch of one of our repositories.


text:
Q: Which Org should be submitted for Security Review? We are planning to List our App in App Exchange.We have already created a developer account with the help of partner portal.We are currently in Security Review Step.Looking at the video it was mentioned that we have to submit the test org for Review and not the one in which Managed Package was created.
Out of the following, which one has to be submitted?

*

*Does it mean we should create a test org from hub and install the managed package created from developer account?

*Can we submit the developer account with managed package directly?

*Should we move all the code created in developer account to test org and then submit the same for review?

A: You have to submit the org in which you have developed your managed package.
You need to give credentials of Other dev org just for testing(which they perform).
You don't have to move code anywhere.
All the best!!

A: It's always better to spin a new test org and install the package you want to get it reviewed for security review .
You don't want to be giving your developer org where all code resides because security review wants to actually see how a package looks when Installed in a subscriber org .
You do not need to move all the code to another org .The other org can just have a latest package installed .

Also note that security review takes time (6 weeks apprx) and during that time you can continue working on feature update or fixing bugs without any interruptions if you do not submit your developer org


text:
Q: Error 'The request timed out' when uploading files in parallel on AWSS3 I have a problem with the parallel upload in AWSS3
I'm using
AWSTask(forCompletionOfAllTasks:tasks).continueWithBlock({task -> AWSTask in

to upload files in parallel on S3. It works well with small amount of file, but when I'm sending more than 50 files in parallel, I have a lot of timeout error and I don't understand why.
I tried several time to load 150 files in parallel and I have a timeout after the 60th file was uploaded with success. There is around 50 timeout error which take around 1 or 2 minutes, after that, the upload continue and at the end all the files are uploaded successfully but these timeout slow a lot the upload...
I see the errors in the logs but I don't know how to catch it in the code, the upload request (AWSS3TransferManagerUploadRequest) didn't return an error, so I cannot display an error to inform the user that something goes wrong.
Has anybody an idea how to solve the problem? And if there is no solution for the timeout, do you know how to catch the error for at least display an error on the screen?
I already tried to change the timeoutIntervalForRequest/timeoutIntervalForResource but it doesn't change anything.
The error is (fifty times or more):
20 AWSiOSSDK v2.4.8 [Error] AWSURLSessionManager.m line:212 | -[AWSURLSessionManager URLSession:task:didCompleteWithError:] | Session task failed with error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=https://s3.amazonaws.com/***/user-72358/project-***/***.jpg?partNumber=1&uploadId=***, _kCFStreamErrorCodeKey=-2102, NSErrorFailingURLKey=https://s3.amazonaws.com/***/user-***/project-***/***.jpg?partNumber=1&uploadId=***, NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x1dc69d80 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102}}}

And here is my code :
func uploadAllFileRequests(imageArray:[String], completion:(filedataReturned:FileData?, uploadOfFileSucceeded: Bool, error: NSError?)-> Void,progress:(totalSent: Int64, totalExpect: Int64)-> Void) -> Void
    {
        var tasks = [AWSTask]()

        let keyCred     = s3CredentialsInfo?.key
        AWSS3TransferManager.registerS3TransferManagerWithConfiguration(serviceConfiguration, forKey: keyCred)
        let transferManager:AWSS3TransferManager = AWSS3TransferManager.S3TransferManagerForKey(keyCred)

        for imageFilePath:String in imageArray {
            ...

            let keyOnS3     = "\(keyCred!)/\(filename)"

            // url image to upload to s3
            let url:NSURL   = NSURL(fileURLWithPath: filedata.getFullpath())

            // next we set up the S3 upload request manager
            let uploadRequest = AWSS3TransferManagerUploadRequest()
            uploadRequest?.bucket = s3CredentialsInfo?.bucket
            uploadRequest?.key = keyOnS3
            uploadRequest?.contentType = type
            uploadRequest?.body = url

            // Track Upload Progress through AWSNetworkingUploadProgressBlock
            uploadRequest?.uploadProgress = {(bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in
                dispatch_sync(dispatch_get_main_queue(), { () -> Void in
                    progress(totalSent: currentTotal, totalExpect: totalSize)
                })
            }

            tasks.append(transferManager.upload(uploadRequest).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock:{task -> AWSTask in
                if(task.result != nil){
                    // upload success
                    print("-> upload successfull \(keyOnS3) on S3")
                    completion(filedataReturned:filedata, uploadOfFileSucceeded: true, error: nil)
                }else{
                    print("->task error upload on S3 : \(task.error)")
                }
                return task
            }))
        }
        AWSTask(forCompletionOfAllTasks:tasks).continueWithBlock({task -> AWSTask in
            print("-> parallel task is \(task)")
            if(!task.cancelled && !task.faulted){
                // upload success
                print("-> upload successfull  on S3")
            }else{
                print("->error of parallel upload on S3")
                completion(filedataReturned:nil, uploadOfFileSucceeded: false, error: task.error)
            }
            return task
        })
    }

I'm using AWSCore and AWSS3 cocoapods version 2.4.8
Thanks in advance for your help
Stéphanie

A: The error of time out comes once your network is slow, for this you just have to increate time out in configuration.
In your case
let serviceConfiguration = AWSServiceConfiguration(region: convertedRegion, credentialsProvider: credentialsProvider)
configuration?.timeoutIntervalForRequest = 60 // in seconds


text:
Q: "Requested value 'APIObject' was not found." error with SOAP Create/Update Requests from WSDL We have been working with integration tools that are very strict about the use of the Marketing Cloud WSDL "as is".
At the moment we are working on a mc.test.exacttarget.com account.
The issue is that when we use the WSDL here (https://webservice.test.exacttarget.com/etframework.wsdl) our requests do not include the xsi:type="" attribute on the  tag.
The concern here is that without the xsi:type="DataExtensionObject" (for example) we get an error for our calls for Requested value 'APIObject' was not found.
Is there a way to designate the APIObject in the structure provided from the WSDL? We see APIObject underneath 'Container' but have not been successful in creating a call that adds data.
Essentially: we need an alternative to declaring xsi:type="" if one exists. Hopefully through the WSDL structure itself.

Example call that does not work. xsi:type="DataExtensionObject" not included on  tag which is what code.exacttarget.com includes in all of their examples. We generate this from the WSDL through an interface.
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
   <soap:Header>
      <wsse:Security soap:mustUnderstand="1">
         <wsse:UsernameToken>
            <wsse:Username>xxxxxx</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">yyyyy</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </soap:Header>
   <soap:Body>
      <UpdateRequest xmlns="http://exacttarget.com/wsdl/partnerAPI">
    <Options>
        <SaveOptions>
            <SaveOption>
                <PropertyName>*</PropertyName>
                <SaveAction>UpdateAdd</SaveAction>
            </SaveOption>
        </SaveOptions>
    </Options>
    <Objects>
        <CustomerKey>invoice_example_table</CustomerKey>
        <Properties>
            <Property><Name>PrimaryKey</Name><Value>Post1</Value></Property>
        </Properties>
    </Objects>
</UpdateRequest>
   </soap:Body>
</soap:Envelope>

Since the construction of the envelope does not provide a method for defining xsi:type="" inside the  tag, we are hoping there are other elements we can bring into the envelope from the WSDL where we can define APIObject as to not receive the error described.


text:
Q: Using dat.gui slider triggers orbit controls I'm building an origami simulator, I want to be able to 'fold' the paper using a dat.gui slider. I want to also include orbital controls.
However, when I click on the slider and subsequently move my mouse out of the dat.gui window, the orbital controls have been triggered causing the model to jump to a different orientation.
Is there a way to prevent orbital controls from being triggered when I click in the dat.gui window?

A: Quoting the docs:

Constructor
  OrbitControls( object : Camera, domElement : HTMLDOMElement )
  object: (required) The camera to be controlled.
domElement: (optional) The HTML element used for event listeners. By default this is the whole document, however if you only want to the controls to work over a specific element (e.g. the canvas) you can specify that here.

In other words, to restrict the OrbitControls so that they don't enable when you click on the GUI, you must supply a reference to the canvas (renderer.domElement) or container (a div that contains the canvas) as second argument to the constructor. Happy coding! (And folding!)

A: My solution to your question is to: have dat.GUI "listen" to the values controlled by OrbitControls (the camera), so that the values are in sync between the two different "controllers" (OrderbitControls and dat.GUI), like so:
let gui = new dat.GUI();
let folder1 = gui.addFolder("Camera Position");
folder1.add(camera.position, "x", -100, 100).listen();
folder1.add(camera.position, "y", -100, 100).listen();
folder1.add(camera.position, "z", -100, 100).listen();

The listen() function on a tracked variable in dat.GUI will keep the values in sync, and relieve the "jumpiness" you are experiencing.
Reference to dat.GUI Controller functions documentation:
dat.gui

A: OrbitControls has an "enabled" property (in fact, I believe all of the controls have an "enabled" property - might want to check though). So if you have
orbitControls = new THREE.OrbitControls(...);
...
// in your dat.GUI block of code (or wherever you want to disable orbitControls)
orbitControls.enabled = false;
// this should disable orbitControls, and when you want to use orbitControls again, just do
orbitControls.enabled = true;


text:
Q: how to add multiple records in mysql using php? for example i have an array of images of a specific location lets say of new york...which i want to store in mysql... these images are coming directly from wikipedia...how can i insert these images in a loop with each image entry would get the same location name?..like this
1|Newyork|img1.jpg
2|Newyork|img2.jpg
3|Newyork|img3.jpg...so on...
what i have done so far is..
foreach($images as $record)//'$images' is the array of images..
{
$sql="INSERT INTO `search`(`id`, `name`, `image`) VALUES ('','".$data"','".$record."',} //$data is the  name of location

A: if I understood well, even if I don't see your array, sth like that would be the query loop:
//if id is a primary key autoincrement
foreach ($images as $data => $record){
$dbh->query("INSERT INTO search (name, image) VALUES ('".$data."','".$record."') ");
}

but most possibly the array is of that form
for($i=0; $i<count($images); $i++){
$dbh->query("INSERT INTO search (name, image) VALUES ('".$images[$i]['data']."','".$images[$i]['record']."') ");
}

It depends of the array form.


text:
Q: HTMLAgilityPack and System.NullReferenceException Hello this is my first time posting but long time user.  I searched for quite a while but couldn't find anything here that would help.
I am trying to scrape information from my works time keeping system.  They Use Work Force Optimization.  The site is terrible and im trying to make life easier for my employees.
var web = new HtmlWeb();
        web.PreRequest = delegate (HttpWebRequest webRequest)
        {
            webRequest.Timeout = 1200000;
            return true;
        };
        NetworkCredential cred = new NetworkCredential("MyUserName", "MyPassword");
        var proxy = new WebProxy() { UseDefaultCredentials = true };
        var doc = web.Load("https://wfo.company.com/WFO/default/WFM/ScheduleEditor#", "GET", proxy, cred);

        string test = doc.DocumentNode.SelectSingleNode("//*[@id=\"mainContentScheduleEditor\"]/div[3]/ul/li[1]/div[1]/div").InnerText;

The nullException happens when it runs the string test line.  Below is the html from the site I pulled from chrome.

            Sunday, 12/6/2015

I wasn't sure if I should have posted the whole 2000 lines here but this is the element that I wanted to get the inner text of it should simply return the weekday and date of that portion of the schedule.
Thanks for you help in advance I hope provided enough information.


text:
Q: How to I add a simple jquery slider to a Sharepoint 2010 web part I am trying to add the following code to the html of a sharepoint web part by clicking on "Edit HTML Source". I am using a jquery plugin from the http://unslider.com/ website. When I try to submit the code below into the sharepoint web part's html, I get the message: "the HTML source you entered might have been modified". As a result, all I see are two bulletted lines of text. I'm fairly new to sharepoint and jquery. Is making text or picture slideshow a lot more complicated in sharepoint than the code below would suggest?

Slider 1

Slider 2

A: Indeed, when you changed manually the html of a page, SharePoint'll often change the content and the output'll not be the same.
I think this article'll help you to understand what happens and what's your option :
http://sharepoint.hannahswain.eu/2014/10/10/adding-a-code-snippet-to-page-content-on-sharepoint-2013/
The Embedded command and the text file should help you.

A: SharePoint will usually clean out any JavaScript added directly into the source of a content editor web part (although it'll leave in HTML and CSS).
Instead of adding the JavaScript directly into the source of a content editor web part, save it into a text file and upload it to a library on your site.
Then, in your content editor web part, click the drop-down in the corner and choose the option to edit the web part properties. The properties panel should appear on the side of the screen.
In the "Content Link" field in the web part properties, enter the URL of your uploaded text file. The content editor web part will then render whatever's in that text file, including HTML, CSS, and (most importantly) JavaScript.
This has the added benefit of allowing you to use the same snippet of HTML/JS on multiple pages. If you need to make changes, you can change the contents of that file without having to edit the page(s) again.