text:
Q: Why is DotNetNuke text editor control always showing HTML Code with iPad? I have a DotNetNuke custom module where I am using an HTML editor to allow uses to enter some text to be saved to a database.
It is working fine for all browsers except IPad's safari where I get the HTML tags showing in the editor.
What can I do to make Ipad show text formatted (or even as plain text) rather than having these tags appear as they are very confusing to users.
The control is using:
   <%@ Register TagPrefix="dnn" TagName="TextEditor"  Src="~/controls/TextEditor.ascx" %>

             <dnn:TextEditor ID="txtNotes" runat="server" Width="900px" />

The web.config has this:
 <htmlEditor defaultProvider="DotNetNuke.RadEditorProvider">
      <providers>
        <clear />

        <add name="TelerikEditorProvider" type="DotNetNuke.HtmlEditor.TelerikEditorProvider.EditorProvider, DotNetNuke.HtmlEditor.TelerikEditorProvider" providerPath="~/Providers/HtmlEditorProviders/Telerik/" toolsFile="~/Providers/HtmlEditorProviders/Telerik/Config/ToolsDefault.xml" configFile="~/Providers/HtmlEditorProviders/Telerik/Config/ConfigDefault.xml" FilterHostExtensions="True" />
        <add name="DotNetNuke.RadEditorProvider" type="DotNetNuke.Providers.RadEditorProvider.EditorProvider, DotNetNuke.RadEditorProvider" providerPath="~/DesktopModules/Admin/RadEditorProvider" />
      </providers>
    </htmlEditor>

example:
In iPad, I get

Case History Notes - Martha

6/24/11: Referred by Jackie
6/26/11:  Sch. Initial Interview for 6/30; 7:00AM Breakfast at Cafe.

rather than the expected
Case History Notes - Martha 6/24/11: Referred by Jackie 6/26/11:  Sch. Initial Interview for 6/30; 7:00AM Breakfast at Cafe.

A: Safari on the iThings doesn't support contentEditable, which is the feature used for most rech edit panels on the web.

A: Since I do not have an iPad, I am unable to troubleshoot this.  I can confirm that the desktop version of Safari works fine though.  Have you tried this on newer versions of DotNetNuke?  The browser and telerik definitions are updated with every release.  If you cannot upgrade for some reason, I would try upgrading just your telerik controls.  For example, you can try the latest release of the DNN 5 RadEditor Provider by dnnWerk.


text:
Q: PHP Rounding Float Values With Ceil And Result Comparison Is Not As It Must Be I have a PHP function as
function func(){

    function round_up($value, $decPlaces) {
        return ceil($value * pow(10, $decPlaces)) / pow(10, $decPlaces);
    }

    $a=21.31;
    $b=2;
    $c=10.64;
    $d=0.03;

    $xxx=$a;
    $yyy=round_up($b*$c,2)+round_up($d,2);
    $zzz=($xxx===$yyy);

    var_dump($xxx,$yyy,$zzz);
}

This function outputs

float(21.31) float(21.31) bool(false)

It seems xxx equal to yyy but why zzz is false? Where is the problem in this function and result?

A: Just change last line to this to see difference:
var_dump(number_format($xxx, 20), number_format($yyy, 20), $zzz);
Here are some helpful info about the problem:
https://stackoverflow.com/a/3148991/4180451 https://secure.php.net/manual/en/language.types.float.php
https://andy-carter.com/blog/don-t-trust-php-floating-point-numbers-when-equating
and many more... :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error: while Importing data into Redshift I wanted to unload from one database(production) and reload into another database(QA) in Redshift having exact same schema.
I issued S3 load command as following.
copy table(col1,col2,col3,col4) from 's3://<bucket_path>/<file_name>.gzip' CREDENTIALS 'aws_access_key_id=<your_key>;aws_secret_access_key=<your_secret>'  delimiter '|' gzip NULL AS 'null_string';

Got following error.
ERROR:  Failed writing body (0 != XXX) Cause: Failed to inflateinvalid or incomplete deflate data. zlib error code: -3
  error:  Failed writing body (0 != XXX) Cause: Failed to inflateinvalid or incomplete deflate data. zlib error code: -3
  code:      9001
  context:   S3 key being read : s3://<some_s3_bucket>/<some_s3_bucket_file>
  query:     XXXXX
  location:  table_s3_scanner.cpp:355
  process:   query1_23 [pid=2008]
  -----------------------------------------------

A: This happens when you are trying to use Gzip file during copy and it cannot read the file as a Gzip.
If I've made a bad assumption please comment and I'll refocus my answer.


text:
Q: PluginPackager tool - Ocean 2017 I am migrating a Petrel plug-in project (using ocean framework) from  Petrel 2015 version to 2017 version. My post-build event uses PluginPackager.exe tool, that is located in Ocean2015Home (..\Schlumberger\Petrel 2015), but it is not located in Ocean2017Home. Is there a new tool to replace PluginPackager? Or is there a new procedure to create pip file? Or is there something wrong with my Petrel 2017 installation? Thanks in advance.

A: PluginPackager.exe is available with 2017 and is in the Petrel installation directory (OCEAN2017HOME).
A simple approach is to delete the PIP builder project and create a new one.


text:
Q: Why doesn't @media only screen css work with !IMPORTANT;? the only time I can get the css @media to work is if I use
!IMPORTANT; in the css like
@media only screen and (max-width: 600px)
.example {
    padding-left: 2px !IMPORTANT;
}

.example {
    width: 118px;
    position: absolute;
    padding-left: 21px;
    padding-top: 11px;
}

If I don't use !IMPORTANT in the @meda css, the style won't pick up, so the question is, why?
I don't want to use !IMPORTANT; but the css @media won't work with it.
Please help

A: It's working fine for me. Maybe you have another css as well for that class that overwrites it.
.example {
    width: 118px;
    position: absolute;
    padding-left: 21px;
    padding-top: 11px;
    background: red;
}

@media only screen and (max-width: 600px) {
  .example {
      padding-left: 2px;
      background: blue;
  }
}


text:
Q: Help in Handling multiple classes in independent categorical variables and improve performance The dataset has 4 categorical and 1 numerical variable and a timestamp variable. Out of 4, three categorical variables are having more than 100 categories.
I tried doing one-hot encoding on the whole dataset using "pd.get_dummies()" method and the number of columns increased from 6 to 6000. And the time consumption to do the dummy variables took more than 3 minutes.
When you want to use these variables to build an unsupervised model using machine learning to detect anomalies, how should the categorical variables be handled if you have a dataset of a million rows? Should this be considered as a time-series data but you can data for every day but not recorded in fixed intervals? What models can be applied to this kind of dataset?


text:
Q: Angular-xeditable Editable (Bs3) with date and ng-repeat I try to extend a specific example of Angular-xeditable Editable row (Bs3) adding the field "date of birth"
I've created a jsfiddle to describe the problem
http://jsfiddle.net/ffgj62q0/  (right link)

        Name
        Date of b
        Status
        Group
        Edit

      {{ user.name || 'empty' }}

        {{ (user.dob | date:"dd/MM/yyyy") || 'empty' }}

The popup doesn't appear. :-(
I found this example that works with one date field.
http://plnkr.co/edit/Y4ilZ4rITYnjAyq2xAUa?p=preview
Any hint to solve this specific problem, please?
Regards
C.

A: I forked your fiddle (also updated some resources, for example set angularjs to 1.4.8 on the javascript settings of the jsfiddle - "FRAMEWORKS AND EXTENSIONS", and removed angular.min.js from the jsFiddle's external resources).
And then I just added some missing stuff, like explained on the angular-xeditable site (http://jsfiddle.net/cewm89y3/5/)

*

*I added the missing dependency of ui-bootstrap, both to the jsfiddle's resources and to the module.

*Also added e-is-open and e-ng-click attributes just as in the example from angular-xeditable,

... and in my fiddle the datepicker opens.

A: It is problem with X-editable js.
changed x-editable.js
to angular-xeditable - 0.1.9


text:
Q: Expand a div according to the amount of textbox Does anyone knows how can I expand this div text box so the user can see the whole text or is there a way to put a functional scroll. I tried the last one but it does not works. I tried fit-content but it does not work:

the code is:

Thanks for the help!

A: Use <textarea></textarea> with style overflow: auto; max-height: 4em; height: max-content; min-height: 2em;

A: You can add a little JS script:

const tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
    tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;");
    tx[i].addEventListener("input", onInput, false);
}

function onInput() {
    this.style.height = "auto";
    this.style.height = (this.scrollHeight) + "px";
}
textarea{
  resize: none;
}
<textarea></textarea>

I assume that you use this plugin. It is resizing bit at a specific amount of lines it goes into "scrollbar mode". I sadly didn't found a setting to disable the scrollmode.


text:
Q: How to stick a ContentPlaceHolder as the source of a URL in a master page in ASP.NET MVC I have multiple pages that have this pattern:
<iframe frameborder ="0" src="[someURL]" width="100%" height="900">
</iframe>

I want to factor out everything but the URL into a master page so I tried this:
Master Page:
<iframe frameborder ="0" src=<asp:ContentPlaceHolder ID="Url" runat="server" /> width="100%" height="900">
</iframe>

Child Page:
<asp:Content ID="Content2" ContentPlaceHolderID="Url" runat="server">
    "http://myURL"
</asp:Content>

but it doesn't seem to work. I get this error:
Cannot find ContentPlaceHolder 'Url' in the master page
Do I have some syntax error above?

A: It sounds like you want to re-use a snippet such that the View can dictate what the URL of the iFrame is, and the Master holds the actual iFrame.
Consider this potential solution:
The URL is put into ViewData from the Controller. Convention is that Views are dumb. So you could put this iFrame into your Master:
<iframe frameborder ="0" src="<%=ViewData["yourURL"] %>" width="100%" height="900"></iframe>
This requires that your Controller knows, or can find, the URL for the View that's being requested. You could hard-code this right in your Controller method, or pull it from the web.config.

A: I don't think that will work very well...  Could you pass along a URL into ViewData within the controller instead, and inject that?  Or create some component that pulls the correct value from a backend source based on the current URL, or something?
HTH.

A: There are better ways of getting your source into the element but if you need to stick with the implementation you are using you can do this...
<iframe frameborder ="0" src="<asp:ContentPlaceHolder ID="UrlContent" runat="server" />" width="100%" height="900">
</iframe>

Notice that I have quotes before and after the content placeholder. Then you can just have content that looks like this...
<asp:Content ID="Content3" ContentPlaceHolderID="UrlContent" runat="server">
    http://www.stackoverflow.com
</asp:Content>

Intelisense will not like what you are trying to do but it will work.


text:
Q: ASP.NET MVC2: Can you get ModelMetadata.ContainerType from within a collection? I'm trying to call DisplayFor and DisplayForModel to iterate an IEnumerable<> with various element types from within a view. I have Templates defined for each element/Model type.
What I would like to do is check the ViewData.ModelMetadata.ContainerType from within the Template so that Template can determine if it was called as part of a collection.
A simple example:
Index1.aspx: To render a collection of Foos.
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Foo>>" %>
<asp:Content ContentPlaceHolderID="MainPlaceHolder" runat="server">

<%:Html.DisplayForModel()%>

</asp:Content>

Index2.aspx: To render a Foo from Bar.
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Bar>" %>
<asp:Content ContentPlaceHolderID="MainPlaceHolder" runat="server">
    <%:Html.DisplayFor(m => m.Foo)%>
</asp:Content>

Shared\DisplayTemplates\Foo.ascx: A context aware Template for Foo.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Foo>" %>
<%  var tag = typeof(IEnumerable).IsAssignableFrom(ViewData.ModelMetaData.ContainerType) ? "li" : "div";
%>    <<%:tag%>><%:Model.Name%></<%:tag%>>

The problem with this example is that ViewData.ModelMetaData.ContainerType is null in the Template when resolved though Index1.aspx. From what I've read on Brad Wilson's post and others it has to do with the use of IEnumerable and its being an interface.
Is there a way to insure that the ContainerType is set? Perhaps by creating a ModelMetadataProvider? I looked into that breifly but it appears the ContainerType value is determined before and then passed to the Provider.
Any suggestions would be appreciated.

A: Here is a functional solution I've worked out for now but it's limited and problematic because it requires converting collections to lists in the Model and the Templates are not context aware.
Index1.aspx: To render a collection of Foos.
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<Foo>>" %>
<asp:Content ContentPlaceHolderID="MainPlaceHolder" runat="server">
    <%:Html.DisplayForModel("List")%>
</asp:Content>

Shared\DisplayTemplates\List.ascx: Special collection template.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList>" %>

<%  for(int i = 0, count = Model.Count; i < count; i++)
    {
%>
<%:Html.DisplayFor(m => m[i])%>

<%  }
%>

Shared\DisplayTemplates\Foo.ascx: A non-context aware Template for Foo.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Foo>" %>

<%:Model.Name%>

I'd still prefer to handle this scenario in a way similar to how I described it before. So the Model Template can determine for itself how it should format the output instead of having to create special case Templates that are referenced by name by the caller.


text:
Q: How to add framework to an Android Studio Project? I want to work on a framework so that I was following this tutorial. https://medium.com/@kmmraj/android-clean-code-part-1-c66da6551d1
It says to download and locate the framework which I did.
I have added the template to the {ANDROID_STUDIO_LOCATION}/plugins/android/lib/templates/other/ location as the documentation said.
However after this point I do not know how to add this framework to my existing project. Or how am I supposed to use it?
Any help would be appreciated.
Thanks in advance.


text:
Q: Using Panel or PlaceHolder What is the difference between <asp:Panel > and <asp:PlaceHolder > in ASP.NET?
When should you use one over the other?

A: The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.
The Panel does have outer HTML tags but does have some cool extra properties.

*

*BackImageUrl: Gets/Sets the
background image's URL for the panel

*HorizontalAlign: Gets/Sets the
horizontal alignment of the parent's
contents

*Wrap: Gets/Sets whether the
panel's content wraps

There is a good article at startvbnet here.

A: I weird bug* in visual studio 2010, if you put controls inside a Placeholder it does not render them in design view mode.
This is especially true for Hidenfields and Empty labels.
I would love to use placeholders instead of panels but I hate the fact I cant put other controls inside placeholders at design time in the GUI.

A: PlaceHolder control
Use the PlaceHolder control as a container to store server controls that are dynamically added to the Web page. The PlaceHolder control does not produce any visible output and is used only as a container for other controls on the Web page. You can use the Control.Controls collection to add, insert, or remove a control in the PlaceHolder control.
Panel control
The Panel control is a container for other controls. It is especially useful when you want to generate controls programmatically, hide/show a group of controls, or localize a group of controls.
The Direction property is useful for localizing a Panel control's content to display text for languages that are written from right to left, such as Arabic or Hebrew.
The Panel control provides several properties that allow you to customize the behavior and display of its contents. Use the BackImageUrl property to display a custom image for the Panel control. Use the ScrollBars property to specify scroll bars for the control.
Small differences when rendering HTML: a PlaceHolder control will render nothing, but Panel control will render as a
.
More information at ASP.NET Forums

A: As mentioned in other answers, the Panel generates a
 in HTML, while the PlaceHolder does not. But there are a lot more reasons why you could choose either one.
Why a PlaceHolder?
Since it generates no tag of it's own you can use it safely inside other element that cannot contain a
, for example:

        Row 1

    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

You can also use a PlaceHolder to control the Visibility of a group of Controls without wrapping it in a

<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:PlaceHolder>

Why a Panel
It generates it's own
 and can also be used to wrap a group of Contols. But a Panel has a lot more properties that can be useful to format it's content:
<asp:Panel ID="Panel1" runat="server" Font-Bold="true"
    BackColor="Green" ForeColor="Red" Width="200"
    Height="200" BorderColor="Black" BorderStyle="Dotted">
    Red text on a green background with a black dotted border.
</asp:Panel>

But the most useful feature is the DefaultButton property. When the ID matches a Button in the Panel it will trigger a Form Post with Validation when enter is pressed inside a TextBox. Now a user can submit the Form without pressing the Button.
<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
        ErrorMessage="Input is required" ValidationGroup="myValGroup"
        Display="Dynamic" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>

    <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="myValGroup" />
</asp:Panel>

Try the above snippet by pressing enter inside TextBox1

A: A panel expands to a span (or a div), with it's content within it.  A placeholder is just that, a placeholder that's replaced by whatever you put in it.


text:
Q: Is there a way to wrap function calls in a decorator In my flask application, I interact with MongoDB. For resilience, I follow a pattern to wrap the insert/update operations in a retry loop like this -
retry = 3
while (retry>0):
    try:
        response = db.collection_name.insert({'name' : 'somename'})
        if response: #or something relevant to the query.
          #do something
          break
        else:
          #do something else
          break
    except:
        retry-=1

This is a pattern I find myself using for almost all the update/insert operations. Now, I was wondering if there is a way to avoid writing the same loop again and again.
While looking how we can write decorators to decouple an action and apply it on any function we want ex. timing a function run, I wondered if it is possible to do something similar for db calls (or a specific set or instruction) without putting them in a function.


text:
Q: Choose data from the most recent two years for out of sample testing I have a dataset that contains monthly data for the past four decades. I understand that if I use 5-fold cross validation, I need to randomly pick training set and testing set. Can I use data from the most recent two years as the testing set? If so, how should I revise the procedure? Thanks!

A: Yes you can, since standard CV doesn't work for time series data. See:
https://www.otexts.org/fpp2/accuracy.html


text:
Q: Trouble assigning multiple nodejs exports return values to variables I have two files, a main file and a module file. Inside the module file, I export two functions, which return objects. In the main file, I am setting a variable to the return value of each method. However, each variable is set to the return value of the last method called. What am I doing wrong here?
/* main file */
module.exports = function(robot) {
  var startingCharacter = require('./data/starting/character.json'),
      make = require('./includes/make.js');

  return robot.respond(/dungeon me/i, function(msg) {
    var character = startingCharacter,
        weapon = make.weapon(0),
        armor = make.armor(0);

    console.log(weapon); // <- returns value from make.armor(0)
    console.log(armor); // <- returns value from make.armor(0)
  }
};

/* module file */
var random = require('./random.js');

var baseStats = {
  'equipped': 'true',
  'attack': '0',
  'damage': '0',
  'defense': '0',
  'health': '0',
  'luck': '0',
  'passivePower': {},
  'activePower': {}
};

// Generate a weapon
exports.weapon = function(level) {
  var weaponNames = require('../data/nouns/weapon_names.json');
  var thisWeapon = {};

  if (level === 0) {
    var adjNeg = require('../data/adjectives/negative.json');

    thisWeapon = baseStats;
    thisWeapon.name = adjNeg[random(0, adjNeg.length)] + ' ' +  weaponNames[random(0, weaponNames.length)];
    thisWeapon.type = 'weapon';
  }

  console.log(thisWeapon); // <- returns correct value
  return thisWeapon;
};

// Generate armor
exports.armor = function(level) {
  var armorNames = require('../data/nouns/armor_names.json');
  var thisArmor = {};

  if (level === 0) {
    var adjNeg = require('../data/adjectives/negative.json'),
        animals = require('../data/nouns/animals.json');

    var armorName = armorNames[random(0, armorNames.length)];

    thisArmor = baseStats;

    if (armorName === 'Hide') {
      thisArmor.name = animals[random(0, animals.length)] + ' ' + armorName + ' armor';
    }
    else {
      thisArmor.name = adjNeg[random(0, adjNeg.length)] + ' ' + armorName;
    }
    thisArmor.type = 'armor';
  }

  console.log(thisArmor); // <- returns correct value
  return thisArmor;
};

Note: edited with real code, instead of sample code

A: When you do this:
thisArmor = baseStats;

you're not making a copy of the "baseStats" object. Since both methods in the module modify and return a reference to that same object, you get the effect you observe.
There are several ways to implement a shallow copy operation for Node; see this Stackoverflow question. With one of those approaches, you'd start those methods off with a local copy of "baseStats".


text:
Q: Ajax request and jquery conflict I have gallery.php that loads images with src path from a database.
I also have an external main.js that detects a click on a .thumbnail.
Everything works flawlessly until I load different images (another category of images, another set) via ajax.  (the load() function of jquery) Everything shows just fine, but a problem with javascript appears.
After that, I can't retrieve the src attribute of my thumbnail. Here's what I mean.
BEFORE AJAX
Category 1 pictures/thumbnails
';
';
';

And so on...
AFTER AJAX CALL
Category 2 pictures/thumbnails
';
';
';

As you can see, everything is like before. The a tag has the same class as the old est of pictures. But when I call the function containing :
var path = $(this).children().attr("src");

It now returns : undefined instead of ressources/images/imageXSmall.jpg
I tried checking if $(this) returned something else after, but no success.
I was wondering if when an external .php file was loaded via jquery.load(), the link between those newly created  tags and main.js were lost. Like if I had to reload main.js after the jquery.load() function. Or something like that...
Thank you!
EDIT Here's the code:

*

*When clicking on a link to different
category
.linkSubCat being different categories
$(".linkSubCat").click(function(){loadImages($(this).attr("id"));});
then
function loadImages(pCategory) {
    switch (pCategory) {
        case "subCat00":
            $(".pics").load('loadImages.php',{category:0});
            break;
        case "subCat01":
            $(".pics").load('loadImages.php',{category:1});
            break;
        case "subCat02":
            $(".pics").load('loadImages.php',{category:2});
            break;
        case "subCat03":
            $(".pics").load('loadImages.php',{category:3});
            break;
        default:
            $(".pics").load('loadImages.php',{category:0});
            break;
    }
}

loadImages.php
<?php
    $connection = mysql_connect("localhost","root", "") or die("Error Connecting : " . mysql_error());

    if (!mysql_select_db("taktak")) die('Error connecting to database : ' . mysql_error());

    function createThumbPHP() {
        if(isset($_POST['category'])) {
            if($_POST['category'] == 0){
                $imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
                $thumbHtml = '';

                while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
                    $thumbHtml .= '';
                }
            }elseif($_POST['category'] == 1){
                $imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 1");
                $thumbHtml = '';

                while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
                    $thumbHtml .= '';
                }
            }elseif($_POST['category'] == 2){
                $imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 2");
                $thumbHtml = '';

                while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
                    $thumbHtml .= '';
                }
            }elseif($_POST['category'] == 3){
                $imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 3");
                $thumbHtml = '';

                while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
                    $thumbHtml .= '';
                }
            }
        return $thumbHtml;
        }
        else {
            $errorMSG = "Error Loading Images";
            return $errorMSG;
        }
    }

    echo createThumbPHP();
?>

So everything does what it's supposed to do. Here'sthe problem. This javascript code in main.js :
$(".thumbnail").click(
            function(){
                $('#imageBig img').remove();

                var path = $(this).children().attr("src");
                var newPath = path.substring(0, path.length-9);
                var newPath2 = newPath += ".jpg";

                var imageLoad = new Image();

                $(imageLoad).load(function () {
                    if (--imageLoad == 0) {
                        // ALL DONE!
                    }
                    // anything in this function will execute after the image loads
                    $('#loader').hide();
                    var newImg = $('').attr('src',$(this).attr('src'));
                    $('#imageBig').append( $(newImg) ); // I assume this is the code you wanted to execute
                })
                .attr('src',newPath2);
            }
        )

It removes the img in #imageBig, but doesn't seem to get the path of $(this).children().attr("src"); This script worked perfectly before I loaded different thumbnails (even with the same setup (classes, order, ...))

A: Try using the jQuery "live" event binding, eg
instead of this

$(".thumbnail").click(

use this
$('.thumbnail').live('click',

When using the regular event binders (eg $.click()), the handler is only bound to those elements matched at the time of the call. When you load new elements via AJAX, these will not be bound.
From the jQuery manual

Attach a handler to the event for all elements which match the current selector, now and in the future.


text:
Q: Singularity; get a github repo into the users home directory Aim
The aim is to create a singularity container that installs some packages, then clones a custom package from a git repo and makes it. The user needs to have permission to do things with the custom package, and ideally it would sit in the home directory of the singularity user, but that seems more difficult than I had anticipated.
The singularity will be almost always launched as a shell, it is to contain a group of troublesome custom packages and generate results from them in a repeatable, sharable manner.
Problem
Cloning the git repo seems fine, but the only place I can put it that the user can even see it is /github_repo and it is always owned by root.
I can't get it to the user's home directory because during %post the variable $HOME does not seem to point to the users home directory, it points to /root, and object that are created then belong to root. In fact while /home does exist it is empty, it seems like the user doesn't exist yet.
I have tried cloning to /github_repo then adding
chown -R $USER /github_repo
chmod -R 766 /github_repo

to %post.
The container can be built and run, and when it is running;
$ ls -lh /github_repo
ls: cannot access '/github_repo': Permission denied
total 0
d????????? ? ? ? ?           ? CorrectNameOfGithubFolder
-????????? ? ? ? ?           ? CorrectNameOfGithubFile

So it can see the names of the files and folders, but not their permissions? I didn't even know that was possible. If I don't mess around with permissions in %post it is a perfectly normal file owned by root.
Recipe
This is what I have so far, you should find it builds and runs.
If you want to run it save the recipy as example.def then do
sudo singularity build example.sif example.def
singularity run --containall example.sif

and then try
$ ls -lh /packages

example.def

BootStrap: docker
From: ubuntu:18.04

# commands on the host system
%setup
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    echo "${GREEN}~~~ Getting modified packages from github ~~~ ${NOCOLOUR}"
    export PACKAGES_TMP=/tmp/packages
    rm -fr $PACKAGES_TMP
    mkdir -p $PACKAGES_TMP
    git clone https://github.com/rootpy/rootpy-tutorials.git $PACKAGES_TMP
    cp -R ${PACKAGES_TMP} ${SINGULARITY_ROOTFS}

# get files from the host (but we dont need any)
%files

# what is done when the container is built
%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    # start
    echo "${GREEN}~~~ install apt packages ~~~ ${NOCOLOUR}"
    apt -y update
    # for fetching from repos if needed
    apt -y install git
    # for getting anything else from the net
    apt -y install wget
    # text editors
    apt -y install vim-tiny
    apt -y install nano
    # for making downloaded packages
    apt -y install make

    echo "${GREEN}~~~ Set up a .bashrc ~~~ ${NOCOLOUR}"
    BASHRC=/home/.bashrc
    touch $BASHRC
    echo "alias vim=vim.tiny\n" >> $BASHRC
    # will be called in run

    ## Not working???
    ## the /home/ directory appears empty
    # echo "${GREEN}~~~ Move packages to home dir ~~~ ${NOCOLOUR}"
    MY_HOME=$(ls -l /home/)
    echo in post home is $MY_HOME
    touch ~/test
    touch $HOME/test
    mkdir $HOME/test_dir
    # PACKAGES=$MY_HOME/packages/
    # mv /packages $PACKAGES

    echo "${GREEN}~~~ Give the user permission and control ~~~ ${NOCOLOUR}"
    # this bit does odd things
    PACKAGES=/packages
    chown -R $USER $PACKAGES
    chmod -R 766 $PACKAGES

    echo "${GREEN}~~~ Making the packages ~~~ ${NOCOLOUR}"
    # need to implement

# enviroment variabels instide the container
# sourced at run time not build time
%environment
    export PACKAGES=/packages/
    export BASHRC=/home/.bashrc

# this is executed when the contain is launched with
# singularity run example.sif
%runscript
    MY_HOME=$(ls -l /home/)
    echo at run home is $MY_HOME
    touch ~/runtest1
    touch $HOME/runtest2
    mkdir $HOME/runtest_dir
    ls -lh /
    ls -lh $HOME
    ls -lh $HOME/runtest_dir/
    # source the .bashrc
    echo $BASHRC
    /bin/bash --rcfile $BASHRC

# this would be executed just after build
%test
    echo I havent written any tests

# metadata
%labels
    Author ClumsyCat
    Version v1.0

%help
    to build me
    > sudo singularity build example.sif example.def
    to run me do
    > singularity run --containall --bind /my/out/dir/ example.sif
        the "--containall" flag prevents interactions with your system
        the "--bind /my/out/dir/" mounts a directory in your system
        this allows scripts in that directory to be accessed from the image
        and results from the image to persist in the directory
        It also allows the run script to call .bashrc

A: There are a few things going on here.

*

*Unless there's something you really need on the host system, don't use %setup. It's running as root on the host OS and it's really easy to break things in ways you don't expect.

*By default singularity mounts the running user's $HOME into the container, so anything you put in /home/... is going to be overwritten unless the user uses --no-home. Best practices recommend against installing to $HOME for this reason

*All the steps in %post when you're referencing $USER is setting it to root, because that is the user when it is being run (sudo singularity build ...), so it's actually doing anything

*chmod -R 664 - this is breaking your directories. You need the execute bit in order to actually access the directory, not just read

I've adjusted your sample definition file to work more as you intend. Comments explain why.
BootStrap: docker
From: ubuntu:18.04

%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    PACKAGES=/packages

    # give all files 774 and directories 775 by default
    umask 002

    # start
    echo "${GREEN}~~~ install apt packages ~~~ ${NOCOLOUR}"
    # install everything at once and use apt-get for non-interactive installs
    apt-get -y update && apt-get install -y git wget vim-tiny nano make

    # create a symlink to vim instead of an alias
    ln -s $(which vim.tiny) /usr/local/bin/vim

    echo "${GREEN}~~~ Getting modified packages from github ~~~ ${NOCOLOUR}"
    # git clone in %post instead of %setup
    mkdir $PACKAGES
    cd $PACKAGES
    git clone https://github.com/rootpy/rootpy-tutorials.git

    echo "${GREEN}~~~ Making the packages ~~~ ${NOCOLOUR}"
    # need to implement
    echo do something here

%environment
    export PACKAGES=/packages

%runscript
    echo I am $(whoami)
    echo

    cd $PACKAGES
    echo I am in $PWD
    ls -la --color=auto
    echo

    echo vim is: $(which vim)

Running singularity run --containall example.sif gives:
I am tsnowlan

I am in /packages
total 0
drwxrwxr-x 3 root     root      39 May 28 12:23 .
drwxr-xr-x 1 tsnowlan tsnowlan  60 May 28 12:24 ..
drwxrwxr-x 6 root     root     117 May 28 12:23 rootpy-tutorials

vim is: /usr/local/bin/vim


text:
Q: TypeError: object of type 'generator' has no len()     def sort_shit(self, arr):
        if len(arr) == 1:
            yield arr
        else:
            mid = int(len(arr) / 2)
            l = self.sort_shit(arr[:mid])
            r = self.sort_shit(arr[mid:])
        i = j = 0
        result = []
        while i < len(l) and j < len(r):
            if l[i] < r[j]:
                result.append(l[i])
                i += 1
            else:
                result.append(r[j])
                j += 1
        result += l[i:]
        result += r[j:]
        yield result

Вывод ошибки TypeError: object of type 'generator' has no len()

A: Как и написали в комментарии - у генератора нет длины. Если копнуть глубже, нужно понимать что такое генератор

Генераторы являются простым средством для создания итераторов.
Итератор - тип, позволяющий реализовать поток данных и предлагающий средства для продвижения по нему.
http://pythonz.net/references/named/generator/

Получается что функция-генератор возвращает итератор. Чтобы остановить движение по итератору необходимо исключение StopIteration. Из этого следует, что для того, чтобы получить все элементы итератора, и узнать его длину, необходимо полностью по нему пройтись.
Тут есть два варианта:

*

*Запомнить все элементы итератора - len(list(arr))

*Пересмотреть свой код, и понять что метод-генератор тут особо и не нужен

A: У вас опечатка вконце:
yield result

а надо:
return result


text:
Q: Objective-C How to read text of an array of visibleCells? My code follows as:
NSArray *vis = [tableView1 visibleCells];
    NSLog (@"vis %@", vis);

And I get:
2012-07-04 21:16:44.564 xxx[1933:12e03] vis (
    "<UITableViewCell: 0xb2dcc80; frame = (0 0; 320 80); text = 'xxx1'; autoresize = W; layer = <CALayer: 0xb2dcd60>>",
    "<UITableViewCell: 0x635ea10; frame = (0 80; 320 80); text = 'xxx2'; autoresize = W; layer = <CALayer: 0x6353620>>",
    "<UITableViewCell: 0xb2ddca0; frame = (0 160; 320 80); text = 'xxx3'; autoresize = W; layer = <CALayer: 0xb2ddc70>>",
    "<UITableViewCell: 0x635f7d0; frame = (0 240; 320 80); text = 'xxx4'; autoresize = W; layer = <CALayer: 0x635f650>>"

When I write:
NSString *aText = [vis objectAtIndex:0];
NSLog (@"aText %@", aText);

I get invariably a warning:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'

Is this a kind of multidimensional array? If yes, how can I extract only text?

A: You should rather use:
NSArray *cells = [tableView1 visibleCells];
if ([cells count] > 0) {
    UITableViewCell *cell = [cells objectAtIndex:0];
    NSString *text = cell.textLabel.text;
}

A: The array returned by visibleCells contains UITableViewCell objects, and not NSString objects. You can see that in the output of your NSLog(@"vis %@", vis);.
To get the strings, you'd need to ask the UITableViewCells for them.
In other words:
NSString *aText = [[[vis objectAtIndex:0] textLabel] text];


text:
Q: Solve the system of non-linear equations Solve the system $$\begin{cases}x^2 - yz = 3\\ y^2 - zx = 4\\ z^2 - xy = 5\end{cases}$$ How do I factorize the equation obtained on combining these equations?

A: Observe
\begin{align}
x^2y-y^2z=&\ 3y\\
y^2z-z^2x =&\ 4z\\
z^2x-x^2y =&\ 5x
\end{align}
then adding the three equations yields $3y+4z+5x = 0$. Likewise, we have
\begin{align}
x^2z-z^2y=&\ 3z\\
y^2x-x^2z =&\ 4x\\
z^2y-y^2x =&\ 5y
\end{align}
which gives $3z+4x+5y = 0$. Combining the two equations gives $z = 13y$. Substitute it back into the original equation (for instance equation 2, 3)
\begin{align}
y^2-13xy =&\ 4\\
13^3y^2-13xy =&\ 5*13
\end{align}
which leads to $y^2 = \frac{1}{36}$. The rest will follow immediately.

A: Hint:  subtract each of the second and third equations from the previous one, then:
$$
x^2-y^2 +xz-yz=-1 \;\;\iff\;\; (x-y)(x+y+z)=-1\\
y^2-z^2 +xy-zx=-1 \;\;\iff\;\; (y-z)(x+y+z)=-1
$$
Therefore $\,x-y=y-z \iff y=(x+z)/2\,$, which reduces the system to two unknowns.

A: We see that $$x^2-yz+z^2-xy-2(y^2-xz)=3+5-2\cdot4$$ or
$$(x+z)^2-(x+z)y-2y^2=0$$ or
$$(x+y+z)(x+z-2z)=0.$$
1. $x+y+z=0$ with the first and the second equations of our system.
We obtain $z=-x-y$, which gives
$x^2+xy+y^2=3$ and $x^2+xy+y^2=4$, which is impossible;

*$x+z=2y$ or $z=2y-x$ with the first and the second equations of our system.

After this substitution we'll get the answer:
$$\left\{\left(\frac{11}{6},-\frac{1}{6},-\frac{13}{6}\right), \left(-\frac{11}{6},\frac{1}{6},\frac{13}{6}\right)\right\}$$


text:
Q: Getting the next row while trying to delete a range of rows using vba. What is wrong Sub Keeptop3()
  Dim lastrow As Integer
  lastrow = ActiveSheet.UsedRange.Rows.Count
  For i = 4 To lastrow
    Rows(i).Delete
  Next i
End Sub

I have used the lastrow to find the count of rows. I need only the top 3 rows. I am getting them plus the 5th row.
When I make it i=4, I get the top 2 rows and the 4th row.
What is wrong with my code?

A: When deleting rows, it's a good idea to work backwards.  Try this:
Sub Keeptop3()
Dim lastrow As Integer
lastrow = ActiveSheet.UsedRange.Rows.Count
For i = lastrow to 4 Step -1
    Rows(i).Delete
    Next i
End Sub

A: If just want to keep the first 3 rows, (deleting all other regardless of their contents). Then just delete the range that goes from the 4th row to the last row, verifying that the last row is higher than 3. There is not need, if this is the case, to go one by one.
See code below (notice change of DataType for LastRow variable)
Sub Keeptop3()
Dim lastrow As Long
    With ActiveSheet
        lastrow = .UsedRange.SpecialCells(xlLastCell).Row
        If lastrow > 3 Then .Rows("4:" & lastrow).Delete
    End With
End Sub

A: replace this:
lastrow = ActiveSheet.UsedRange.Rows.Count

with this:
lastrow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row


text:
Q: How to set up a separate wifi SSID with VLAN on OpenWRT? There is a TP-Link TL-WR740N router with OpenWrt 18.06.9 installed. The setup is: 1 SSID, bridged with switch and WAN port, so the router acts like an AP (DHCP disabled, just "converting ethernet to wifi").
With Unifi APs you can add another SSID with VLAN (so 1 SSID will be wihtout VLAN and 1 SSID will be with VLAN). How to do the same with OpenWRT?

A: The solution in this case (TP-Link TL-WR740N router with OpenWrt 18.06.9 installed) is: there is no way to make simultaniously tagged and untagged VLANs on eth0 (Switch ports), so you cannot use untagged VLAN and tagged VLAN, but: you can use eth1 (WAN port) with "Software VLAN" (just adding eth1.N to bridge), this way you can use eth0 (Switch ports) as a switch, connected to either untagged OR tagged VLAN.
Also, if you have only tagged VLANs, you can use any eth0 port to bridge it with different SSIDs. More here: https://forum.openwrt.org/t/how-to-set-up-a-separate-wifi-ssid-with-vlan-on-openwrt/95375/31


text:
Q: I ran this script in my react native development server and now it wont work rm -rf ios/build/; kill $(lsof -t -i:8081); react-native run-ios

I'm not sure what that did but i have a feeling that thats what did the damage
error Could not connect to development server
also getting no bundle url present as an error
    jest-haste-map: Haste module naming collision: functions
  The following files share their name; please adjust your hasteImpl:
    * <rootDir>/functions/package.json
    * <rootDir>/src/config/functions/package.json

ERROR
23:06
Failed to construct transformer:  DuplicateError: Duplicated files or mocks. Please check the console for more info
    at setModule (/Users/arichayo/Documents/mitzvahCenterIos/node_modules/jest-haste-map/build/index.js:620:17)
    at workerReply (/Users/arichayo/Documents/mitzvahCenterIos/node_modules/jest-haste-map/build/index.js:691:9)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 177) {
  mockPath1: 'functions/package.json',
  mockPath2: 'src/config/functions/package.json'
}
ERROR
23:06
(node:642) UnhandledPromiseRejectionWarning: Error: Duplicated files or mocks. Please check the console for more info
    at setModule (/Users/arichayo/Documents/mitzvahCenterIos/node_modules/jest-haste-map/build/index.js:620:17)
    at workerReply (/Users/arichayo/Documents/mitzvahCenterIos/node_modules/jest-haste-map/build/index.js:691:9)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 177)
(node:642) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:642) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

i got this error in expo chrome cli


text:
Q: Programmatically start appengine autoscaled instance Is there any way in appengine api to programmatically restart the instance or make it stop so that appengine will spawn another server instance? The reason is during our application servlet, warmpup servlet initialization, due to some network errors, some services are not properly initialized. This causes error when request arrives. We want to know how should we handle this ? Is there any way to handle warmup servlet init exceptions and make container aware so that it will spawn another one.

A: Use gcloud app instances list to get the instances, and then gcloud app instances delete to kill the instance.
Hope this helps!


text:
Q: dynamic rgb color generator not giving all desirable colors i wanted to make a pure js rgb color picker,but i am getting a mixture of red and green.no blue or purple effect is visible.
why i am not getting any color rather than blue and green?
how i can do that?
<html>
<head>
<style>

</style>
</head>
<body>

<script type="text/javascript">
        var Canvas = document.createElement('canvas');
        var i=0,j=0,a=0,r=0;g=0;
        Canvas.width = 256;
        Canvas.height = 256;
        Canvas.style.position="relative";
        Canvas.style.top="0px";
        Canvas.style.border = '3px solid black';
        for(r=0;r<256;r++){
            for (g=0;g<256;g++){

               var context = Canvas.getContext('2d');
                context.beginPath();
                context.moveTo(i,j);
                context.strokeStyle = 'rgb(' + r + ', ' + g + ','+a+')';

                context.lineTo(i,j+1);
                context.stroke();
                context.closePath();
                a++;

                    if(a==256){
                a=0;
                }
                j++;
                if(j==256){
                i++;
                j=0;
                }

            }
        }

        document.body.appendChild(Canvas);

    </script>

</body>

A: You are overwriting your colors because i,j are repeating themselves
To get all possible rgb pixel colors you would need 256 canvases that are sized 256x256.
Here's an example of a colorwheel that fits better on a single canvas:

A Demo:  http://jsfiddle.net/m1erickson/fsn56/
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 100;
var counterClockwise = false;

for(var angle=0; angle<=360; angle+=1){
    var startAngle = (angle-2)*Math.PI/180;
    var endAngle = angle * Math.PI/180;
    context.beginPath();
    context.moveTo(x, y);
    context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
    context.closePath();
    context.fillStyle = 'hsl('+angle+', 100%, 50%)';
    context.fill();
}


text:
Q: Starting Node with Forever and --prof option V8 Log file not created I am trying to run my Node App using "forver" module , I also want to pass "--prof" option for profiling my app.
The command I am using is

NODE_ENV=staging PORT=3000 NODE_CONFIG_DIR="/domains/serving/src/config" forever start -c "node --prof" -l /var/log/forever.log -e /var/log/forever_error.log -o /var/log/forever_output.log -a /domains/serving/src/bin/www

Or

NODE_ENV=staging PORT=3000 NODE_CONFIG_DIR="/domains/serving/src/config" forever start -c "node --debug=3048 --prof" -l /var/log/forever.log -e /var/log/forever_error.log -o /var/log/forever_output.log -a /domains/serving/src/bin/www

Things work fine when running on my local machine , but the same command when executed on server multiple things fail
1) forever list command shows one process running but there is no process listening on port 3000
2) The profiler log file (v8.log) is not created I tried with find command

sudo find / -iname "v8.log"

My local machine is Ubuntu
The server config is as follows
Output of following commands

uname -e
Linux MSSSKAMITMI 2.6.32-431.29.2.el6.x86_64 #1 SMP Tue Sep 9 21:36:05 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
node -v
v0.12.0

If I run the node command without forever on Server and local every thing works fine the log files are created process listening on port 3000 and I can also make request and get response.

NODE_ENV=staging PORT=3000 NODE_CONFIG_DIR="/domains/serving/src/config" node --debug=3048 --prof /domains/serving/src/bin/www

A: As of node.js v0.12 or io.js 1.0, the v8 logging is now per-isolate, so the filenames are of the format isolate-<hex isolate address>-v8.log.


text:
Q: How to add multiple question to a variable in AMOS? My questions is from  path analysis.
I have a model with 11 variables (DTPB: Decomposed Theory of Planned Behavior), and I publish questionnaire with likert-scale (1 to 5). Each of this 11 variables have 2, 3 or 4 questions in my questionnaire.
I draw my model in AMOS, but i don`t know how to connect these questions to their variables.

A: As I discuss here on Slide 17, you would usually use the elipse drawing tools to draw the latent factors and then add observed variables using the the tool represented by the following icon:

You can then drag and drop the observed questions into the boxes.


text:
Q: Font Size and Font Family in Nokia QT Which font is supported by the Nokia phones(s60)? I used the Arial,Arial Narrow but I could not see clearly.( I'm developing apps based on the nokia qt sdk in mac 10.6)

A: You can use QFontDatabase to query the fonts available on your device.


text:
Q: Is it possible to send TCP message using Webservices Asp.net or need WCF I need to develop a WebSevice which takes its input and forwards this input using TCP.
Is it possible for Asp.net Webservices ? Or Should I use WCF etc..
I have to know if it is possible to create a web service that should be like a bridge between the two: it waits for an incoming request, forwards it to the required TCP port.
Simple samples are always welcome :)

A: I think Asp.net is possible to use TCP , but I think you should use WCF.
This will give you most  things 'out of the box' (serialize /deserialize, open/close socket )
There are good examples here, here and good reading here

A: I used the sample project and it worked.


text:
Q: Get layout as desired on orientation change I have an xml file like this. On vertical orietation everything is looking perfect. But when the orientation changes, i dont get a layout as i desired,means things are not aligned.How can i make it correct.Thanks in advance
 <RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:background="@drawable/bg"
   android:orientation="vertical">

 <ImageView android:id="@+id/imageVi" android:layout_width="wrap_content"
   android:src="@drawable/header" android:layout_height="wrap_content">
    </ImageView>
 <TableLayout android:id="@+id/tableLayout2" android:layout_width="match_parent" android:layout_height="match_parent">
         <TableRow android:id="@+id/tableRowe"  android:layout_width="wrap_content" android:layout_height="50dip">
           </TableRow>
  <TableRow android:id="@+id/tableRowe"  android:layout_width="wrap_content" android:layout_height="550dip">
           </TableRow>
          <TableRow android:id="@+id/tableRow4"  android:layout_width="wrap_content" android:layout_height="wrap_content">
               <Button  android:layout_width="80dip" android:layout_marginLeft="20dip"  android:layout_marginTop="120dip" android:layout_height="80dip" android:background="@drawable/sched" android:id="@+id/sched"></Button>

        <Button  android:layout_width="80dip" android:layout_marginLeft="20dip"  android:layout_marginTop="120dip" android:layout_height="80dip" android:background="@drawable/viewsched" android:id="@+id/viewsched"></Button>
               <Button   android:layout_width="80dip" android:layout_marginLeft="20dip"  android:layout_marginTop="120dip" android:layout_height="80dip" android:background="@drawable/template" android:id="@+id/template"></Button>
       </TableRow>

          <TableRow android:id="@+id/tableRow5" android:layout_width="5dip" android:layout_height="wrap_content">
            <TextView android:text="Add new" android:minLines="3" android:textColor="@color/black" android:gravity="center" android:layout_width="20dip" android:layout_height="50dip" android:id="@+id/text_coutdet_city"></TextView>
          <TextView android:text="View Scheduler" android:minLines="3" android:textColor="@color/black" android:gravity="center" android:layout_width="20dip" android:layout_height="50dip" android:id="@+id/text_coutdet_city"></TextView>
          <TextView android:text="Message Templates" android:minLines="3" android:textColor="@color/black" android:gravity="center" android:layout_width="20dip" android:layout_height="50dip" android:id="@+id/text_coutdet_city"></TextView>

          </TableRow>

           <TableRow android:id="@+id/tableRow6" android:layout_width="wrap_content" android:layout_height="wrap_content">
           <Button  android:layout_width="80dip" android:layout_marginLeft="20dip"  android:layout_marginTop="10dip" android:layout_height="80dip"  android:background="@drawable/upcmng" android:id="@+id/upcmng"></Button>
        <Button   android:layout_width="80dip" android:layout_marginLeft="20dip"  android:layout_marginTop="10dip" android:layout_height="80dip"  android:background="@drawable/log" android:id="@+id/log"></Button>
               <Button   android:layout_width="80dip" android:layout_marginLeft="20dip"  android:layout_marginTop="10dip" android:layout_height="80dip"  android:background="@drawable/help" android:id="@+id/help"></Button>
         </TableRow>

        <TableRow android:id="@+id/tableRow7" android:layout_width="wrap_content" android:layout_height="wrap_content">
              <TextView android:text="Upcoming birthdays" android:minLines="3" android:textColor="@color/black" android:gravity="center" android:layout_width="20dip" android:layout_height="50dip" android:id="@+id/text_coutdet_city"></TextView>
       <TextView android:text="Birthday Log" android:minLines="3" android:textColor="@color/black" android:gravity="center" android:layout_width="20dip" android:layout_height="50dip" android:id="@+id/text_coutdet_city"></TextView>
       <TextView android:text="Help" android:minLines="3" android:textColor="@color/black" android:gravity="center" android:layout_width="20dip" android:layout_height="50dip" android:id="@+id/text_coutdet_city"></TextView>
       </TableRow>

      </TableLayout>

A: Two ways of doing it.

*

*Creating a separate layout as described in docs

Landscape layout When you want a different design for landscape, put
  your layout XML file inside /res/layout-land. Android will
  automatically look here when the layout changes. Without this special
  landscape layout defined, Android will stretch the default layout.

*

*Setting the width and height parameters appropriately.

A: Create a new XML File named exactly like your XML File above an put it in a folder named layout-land.
This is the XML File which Android will use for your Activity in Ladscape Mode.
Now just change it to match your ideas of the landscape View.

A: You should specify RelativeLayout parameters, for example:
<ImageView android:id="@+id/imageVi"
    ...
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    ... >
</ImageView>

<TableLayout
    ...
    android:layout_alignTop="@id/imageVi"
    android:layout_alignParentLeft="true"
    ... >

        ...
</TableLayout>


text:
Q: Sine wave frequency estimation with scipy.least_squares on Python I am trying to estimate the sine wave frequency using scipy.least_squares with Python.  I cannot understand why it does not work.
My code is:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import least_squares

def generate_data(t, A0, A, omega, phase):
    y = A0 + A * np.sin(omega * t + phase)
    return y

#  Init params
A0 = 0
A = 7.744444
omega = 2*np.pi*1 #2*np.pi*0.2
phase = np.pi/2
t_min = 0
t_max = 100
#  Model of sine
t_model = np.linspace(t_min, t_max, 100)
y_model = generate_data(t_model, A0= A0, A=A, omega=omega, phase=phase)
plt.plot(t_model,y_model)

#  Target func
def fun(x, t, y):
    return (x[0]*np.sin(x[1] * t + x[2])) - y

x0 = np.ones(3)
res_lsq = least_squares(fun, x0, args=(t_model, y_model))

res_robust = least_squares(fun, x0, loss='soft_l1', f_scale=0.1, args=(t_model, y_model))
print('res_robust.x,',res_robust.x[1], 'expect:',omega)
print('res_lsq.x = ', res_lsq.x[1], 'expect:',omega)


text:
Q: jquery autocomplete: passing additional parameters I am trying to pass a couple of additional parameters in my jquery autocomplete URL parameter. I am trying to make a call as follows:
$('#subcommodityFrom').autocomplete({

        url: '/ABC/XYZ.action?autocompleteTest=&ids='+ $('#commodityFrom').val() + '&',
        minChars: 0,
        max: 10,
        width: 150,
        scroll: true
    }).focus(function() {
        $(this).autocomplete('search', $(this).val())
    });

In the above, 'autocompleteTest' is the server side handler method for the autocomplete call and 'subcommodityFrom' is the id of the text field for which autocomplete is implemented. 'commodityFrom' is another text field which is also populated using an autocomplete call. This value is always empty when checked in server side handler method.
However, if I try to pass a static value like:
`url: '/ABC/XYZ.action?autocomplete=&ids='abc', the correct value can be obtained in the handler method when testing as:
String query = getRequest().getParameter("ids");

What can be missing here?


text:
Q: Capture logging message in python 3 I would like to capture the logs printed by a python program, and save it to either a variable or a file. Is there any way to achieve this without adding handlers or modifying logger config? (this is because the logger class will be used by many other modules, and we want it to be generic)
Code snippet:
import logging
from io import StringIO
from contextlib import redirect_stdout

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")

with StringIO() as buf, redirect_stdout(buf), open("test.txt", "w+") as f:
    logger.debug("Debug message")
    logger.info("Info message")
    logger.error("Error message")
    buf.flush()
    f.write(buf.getvalue())

Console output:
xxxx-xx-xx xx:xx:xx,xxx DEBUG Debug message
xxxx-xx-xx xx:xx:xx,xxx INFO Info message
xxxx-xx-xx xx:xx:xx,xxx ERROR Error message

What confuses me is, since logger prints all the logs to stdout by default, redirecting stdout using context manager should do the trick. However, the logs are still printed to the console, and nothing is written to file. Any idea?

A: Logging library already have a utility for that.
Suppose you want to start logging event in file my.log then
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.info('Some info')
logging.warning('Some warning')
logging.debug('Debug messages')

For more check the python documentation.
Edit: OP asked if there is alternative way to do that without using basicConfig method. Here is another approach I found that utilize file handler. Using this you can declare a file handler separately and then assign it to a logger.
logger = logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")

# create file handler
fh = logging.FileHandler('my.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)


text:
Q: In an SQL XQuery result set, is there a way to make the "value" operator return null on missing elements? When getting values out of xml attributes, using the xquery value operator, missing attributes are returned as null. Is there a way to do the same thing without resorting to CASE WHEN N.exists('path')=0 THEN NULL ELSE n.value('path') END?
This SQL:
DECLARE @val xml
SET @val = '<records>
  <record attrval="attrval">
    <stringvalue>some value</stringvalue>
    <intvalue>1</intvalue>
  </record>
  <record>
    <intvalue>1</intvalue>
  </record>
  <record>
    <stringvalue>another value</stringvalue>
  </record>
</records>'

SELECT N.query('stringvalue').value('/', 'varchar(100)') AS stringvalue,
       N.query('intvalue').value('/', 'int') AS intvalue,
       N.value('@attrval', 'varchar(100)') AS attrval
FROM @val.nodes('//record') as T(N)

Results in:
[stringvalue]       [intvalue]  [attrval]
some value          1           attrval
                    1           NULL
another value       0           NULL

And I would like to get:
[stringvalue]       [intvalue]  [attrval]
some value          1           attrval
NULL                1           NULL
another value       NULL        NULL

Without doing:
SELECT CASE WHEN N.exists('stringvalue')=1 THEN N.query('stringvalue').value('/', 'varchar(100)') ELSE NULL END AS stringvalue,
       CASE WHEN N.exists('intvalue')=1 THEN N.query('intvalue').value('/', 'int') ELSE NULL END AS intvalue,
       N.value('@attrval', 'varchar(100)') AS attrval
FROM @val.nodes('//record') as T(N)

Note that in this case I can't just use attribute values because there is a limit on the length of the attributes imposed by SQL Server and some of my data exceeds that.
Also, there is a related question but the answer is not applicable because I need to distinguish between empty and missing: SQL Server xQuery return NULL instead of empty

A: SELECT N.value('stringvalue[1]', 'varchar(100)') AS stringvalue,
       N.value('intvalue[1]', 'int') AS intvalue,
       N.value('@attrval', 'varchar(100)') AS attrval
FROM @val.nodes('//record') as T(N)

A: Is this what you are looking for:
   SELECT NULLIF(N.query('stringvalue').value('/', 'varchar(100)'),'') AS stringvalue,
       N.query('intvalue').value('/', 'int') AS intvalue,
       N.value('@attrval', 'varchar(100)') AS attrval
   FROM @val.nodes('//record') as T(N)

Using NULLIF ( expression , expression ) where the first expression is the expression returned from the data and the second is the expression to compare it to and if equal, it will return a NULL.


text:
Q: How to use Vagrant-proxyconf in multiple environments At work I am behind a proxy server and have configured vagrant to use it through the vagrant-proxyconf plugin. It works great and no problems or complaints there.
Vagrant.configure(2) do |config|
  if Vagrant.has_plugin?("vagrant-proxyconf")
    config.proxy.http      = "http://proxy.server.com:8080"
    config.proxy.https     = "http://proxy.server.com:8080"
    config.proxy.no_proxy  = "localhost, 127.0.0.1"
  else
    raise Vagrant::Errors::VagrantError.new, "Plugin missing: vagrant-proxyconf"
  end

The problem that I'm having is when I take my computer home to do some work. Is there a way to easily turn off the proxy settings?

A: You can turn off proxy by adding
config.proxy.enabled = false

to your Vagrantfile but you need to edit the file to make the change (true/false flag). you can also use external config file if you already have but it still requires a file edit
what I would try based on this answer is something like
vagrant true/false up

and in your Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

proxy_val = ARGV[0]

Vagrant.configure(2) do |config|
  if Vagrant.has_plugin?("vagrant-proxyconf")
    config.proxy.enabled   = proxy_val
    config.proxy.http      = "http://proxy.server.com:8080"
    config.proxy.https     = "http://proxy.server.com:8080"
    config.proxy.no_proxy  = "localhost, 127.0.0.1"
  else
    raise Vagrant::Errors::VagrantError.new, "Plugin missing: vagrant-proxyconf"
  end

If you have some ruby skills you can even come up with something nicer but this gives you an idea
Note turns out even if proxy is disabled, the proxy value are still set as mentioned from the doc

This disabling keeps proxy configurations for applications on the
  guest. The configurations must be cleared before disabling if needed.

so another possibility using the above proposal is to do something like
# -*- mode: ruby -*-
# vi: set ft=ruby :

proxy_val = ARGV[0]

Vagrant.configure(2) do |config|
  if Vagrant.has_plugin?("vagrant-proxyconf")
    config.proxy.enabled   = proxy_val
    if (proxy_val)
      config.proxy.http      = "http://proxy.server.com:8080"
      config.proxy.https     = "http://proxy.server.com:8080"
      config.proxy.no_proxy  = "localhost, 127.0.0.1"
    else
      config.proxy.http      = ""
      config.proxy.https     = ""
      config.proxy.no_proxy  = ""
  else
    raise Vagrant::Errors::VagrantError.new, "Plugin missing: vagrant-proxyconf"
  end


text:
Q: Pyspark - Join timestamp window against timestamp values Is there any effective way of joining a list of timestamp windows against a list of timestamp values?
The dataframe A has these values:
+------------------------------------+---------------------------------------------+----------------------+
|userid       |                    window                   |total_unique_locations|
+------------------------------------+---------------------------------------------+----------------------+
|da24a375-962a|[2017-06-04 03:20:00.0,2017-06-04 03:25:00.0]|2                     |
|0fd2b419-d6ec|[2017-06-04 03:50:00.0,2017-06-04 03:55:00.0]|2                     |
|c8159400-fe0a|[2017-06-04 03:10:00.0,2017-06-04 03:15:00.0]|2                     |
|a4336494-3a10|[2017-06-04 03:00:00.0,2017-06-04 03:05:00.0]|3                     |
|b4590016-1af2|2017-06-04 03:45:00.0,2017-06-04 03:50:00.0] |2                     |
|03b33b0a-e94e|[2017-06-04 03:30:00.0,2017-06-04 03:35:00.0]|2                     |
|e5e4c972-6599|[2017-06-04 03:25:00.0,2017-06-04 03:30:00.0]|5                     |
|345e81fb-5e12|[2017-06-04 03:50:00.0,2017-06-04 03:55:00.0]|2                     |
|bedd88f1-3751|[2017-06-04 03:20:00.0,2017-06-04 03:25:00.0]|2                     |
|da401dab-e7f3|[2017-06-04 03:20:00.0,2017-06-04 03:25:00.0]|2                     |
+------------------------------------+---------------------------------------------+----------------------+

where the data type of window is struct<start:timestamp,end:timestamp>
And the dataframe B has these values:
+------------------------------------+------------------+
|userid       |eventtime            |distance           |
+------------------------------------+------------------+
|9f034a1d-02c1|2017-06-04 03:00:00.0|0.17218625176420413|
|9f034a1d-02c1|2017-06-04 03:00:00.0|0.11145767867097957|
|9f034a1d-02c1|2017-06-04 03:00:00.0|0.14064932728588236|
|a3fac437-efcc|2017-06-04 03:00:00.0|0.08328915597349452|
|a3fac437-efcc|2017-06-04 03:00:00.0|0.07079054693441306|
+------------------------------------+------------------+

I tried to use the regular join but it does not work as the window and eventtime have different data types.
A.join(B, A.userid == B.userid, A.window == B.eventtime).select("*")

Any suggestions?

A: The less efficient solution is to join or crossJoin with beteween:
a.join(b, col("eventtime").between(col("window.start"), col("window.end")))

The more efficient solution is to convert eventtime to a struct with the same definition as used for existing window. For example:
(b
    .withColumn("event_window", window(col("eventtime"), "5 minutes"))
    .join(a, col("event_window") == col("window")))

A: You cannot join these two since the data type of window and eventtime are different.
val result = A.join(B,
  A("userid") === B("userid") &&
  A("window.start") === B("eventtime") ||
  A("window.end") === B("eventtime"), "left")

Hope this helps!


text:
Q: Name Lookup - operator>> Not Found I fail to understand the reason why the code below does not compile. Live.
Thank you.
#include <iostream>
#include <iterator>
#include <sstream>

using namespace std;

namespace N
{
  class C
  {
  public: enum class E { a, b, c };
  };
}

using U = N::C::E;

istream& operator>>( istream& is, U& e )
{
  //...
  return is;
}

int main()
{
  istringstream ss{ "0 1 2" };

  U e;
  ss >> e; // fine

  istream_iterator<U> ii( ss ); // binary '>>': no operator found which takes a right-hand operand of type '_Ty' (or there is no acceptable conversion)

}

A: https://en.cppreference.com/w/cpp/language/adl

Because of argument-dependent lookup, non-member functions and non-member operators defined in the same namespace as a class are considered part of the public interface of that class (if they are found through ADL)

So, move istream& operator>>( istream& is, C::E& e ) into the namespace N.


text:
Q: Reboot sometimes hangs My machine sometimes does not properly reboot. I am not sure what triggers it to work or not work. It happens sometimes both during automatic reboots when unattended-upgrades tries to reboot as well as during manual reboot (sudo shutdown -r now).
It seems the machine will stop the services but not actually perform the hardware reboot in the end. If I connect a screen, the last system messages displayed are:
[timestamp] watchdog: watchdog0 did not stop
[timestamp] reboot: Restarting system

I know that it is not just a delay issue, it will stay like this for days and not reboot.

*

*OS: Debian GNU/Linux 9 (stretch)

*Kernel: Linux 4.9.0-8-amd64 #1 SMP Debian 4.9.110-3+deb9u4 (2018-08-21) x86_64 GNU/Linux

*Hardware: Asus VivoMini Intel N3000

Any ideas what might be wrong?

A: For the watchdog module that times the time-out and hard resets, the system is simply saying that part can't turn off since the system didn't give the module enough time. This is a normal thing and can be safe to shut down the system manually when it occurs.

A: It looks like the watchdog is still running when the kernel tries to reboot, and the system still fails to reboot. That indicates a possible firmware/hardware issue: when the kernel stops running, the watchdog should eventually (typically within 10 minutes) force the system to reboot even if the kernel fails to trigger it in the normal way.
If the exact model is Asus VivoMini UN45, here is a list of BIOS updates for it. When you select "Show all" on that page, you'll see that many of the updates have a comment "Improve system stability". If you have a version that is older than one of those updates, updating the BIOS might very well fix your problem.
To know your current BIOS version, run sudo dmidecode -s bios-version. With Asus PCs and motherboards, this command should report a four-digit number that corresponds to the versions listed on the Asus support page for that specific model.


text:
Q: How can I find the matching values from a column within 3 or more grouped dataframes? I have grouped data frames (in my case three data frames grouped together ).  I want to find the intersection between all three data frames based on a value in a column.
I have been playing around with the dplyr intersect function but don't see how I can use this with my grouped data frames.  I want to find all rows within all three data frames that have the same Start.Coord value.
Here is one failed attempt with the resulting error message:
SameWithinTreatment <= SorbitolGroup %>% group_by(Sample) %>% intersect(Start.Coord)
Error in intersect_data_frame(x, y) : object 'Start.Coord' not found

Obviously I need another parameter to give to intersect().  I see that intersect() doesn't seem to be the function I need but it seems that there must be a way to do what I need.
I have done a lot of searching but everything I find only works with 2 data frames.
Here is some example data from my grouped data frames.  There is one row with a common Start.Coord value between these three: the row with 8805 as the Start.Coord.
  Start.Coord Stop.Coord Sample      Coverage normalized.coverage Average.Normalized.Covera~ SD.of.Normalized.Covera~ TwoSD
        <int>      <int> <chr>          <int>               <dbl>                      <dbl>                    <dbl> <dbl>
1        1019       1023 X1.combined       19                  18                       9.91                     3.98  7.95
2        1510       1514 X1.combined       19                  18                       9.91                     3.98  7.95
3        1514       1518 X1.combined       19                  18                       9.91                     3.98  7.95
4        1520       1524 X1.combined       19                  18                       9.91                     3.98  7.95
5        8805       8809 X1.combined       19                  18                       9.91                     3.98  7.95
6       48185      48189 X1.combined       19                  18                       9.91                     3.98  7.95

  Start.Coord Stop.Coord Sample Coverage normalized.coverage Average.Normalized.Coverage SD.of.Normalized.Coverage TwoSD
        <int>      <int> <chr>     <int>               <dbl>                       <dbl>                     <dbl> <dbl>
1       8805      8809 X2          167                 166                        122.                      21.7  43.4
2       11874      11878 X2          169                 168                        122.                      21.7  43.4
3       12042      12046 X2          169                 168                        122.                      21.7  43.4
4       18321      18325 X2          175                 174                        122.                      21.7  43.4
5       25187      25191 X2          167                 166                        122.                      21.7  43.4
6       25308      25312 X2          194                 193                        122.                      21.7  43.4

  Start.Coord Stop.Coord Sample Coverage normalized.coverage Average.Normalized.Coverage SD.of.Normalized.Coverage TwoSD
        <int>      <int> <chr>     <int>               <dbl>                       <dbl>                     <dbl> <dbl>
1        8805       8809 X3          132                 131                        94.4                      16.7  33.5
2       10340      10344 X3          135                 134                        94.4                      16.7  33.5
3       11874      11878 X3          141                 140                        94.4                      16.7  33.5
4       12042      12046 X3          137                 136                        94.4                      16.7  33.5
5       18209      18213 X3          133                 132                        94.4                      16.7  33.5
6       18218      18222 X3          143                 142                        94.4                      16.7  33.5

So I would like to get back a new data frame that looks like this:
Start.Coord Stop.Coord Sample Coverage normalized.coverage Average.Normalized.Coverage SD.of.Normalized.Coverage TwoSD
8805       8809 X1.combined       19                  18                       9.91                     3.98  7.95
8805      8809 X2          167                 166                        122.                      21.7  43.4
8805       8809 X3          132                 131                        94.4                      16.7  33.5

Is there a way to accomplish this?

A: If your 3 data frames have the same column names use rbind to combine them
SorbitolGroup<- rbind(df1,df2,df3)
then add
Start.Coord to group_by:
SorbitolGroup %>% group_by(Sample,Start.Coord)
If you want to count the number of observations in both groups
SorbitolGroup %>% group_by(Sample,Start.Coord) %>% tally()

A: it sounds like you need to use filter(), in addition to what @W148SMH suggested.
a <- data.frame(sample='a',value=sample(1:10,10,T))
b <- data.frame(sample='b',value=sample(1:10,10,T))
c <- data.frame(sample='c',value=sample(1:10,10,T))

df <- rbind(a,b,c)
summary(df)

df %>% filter(value==9)
df_new <- df %>% filter(value==9) # new data frame including all cases with value==9

df %>% count(sample,value)

df %>% group_by(sample,value) %>%
  summarise(...) # to summarise other variables at each level of sample and value


text:
Q: List comprehension in python not evaluating correctly I am a beginner in python and am trying to teach myself. I have a tic-tac-toe game I have been working on for a while now but I cannot make it detect ties. I am using a list to store the values and list comprehension to detect ties/wins. The problem is that the program is not evaluating correctly. It returns False when it should return True.
This is my function that detects the tie:
def tied():
        nonlocal tie
        if all([x in ['X', 'O'] for x in o_gb[0]] + [x in ['X', 'O']
              for x in o_gb[1]] + [x in ['X', 'O'] for x in o_gb[2]]):
        tie = True

It always return a list of False even if There are X's or O's in the list.
Here is all of my code:
    import numpy as np

    def ticTacToe():
        x_win = False
        o_win = False
        tie = False
        o_gb = [['_'for x in range(3)]for y in range(3)]
               gb = np.array(o_gb).T

        def win():
            nonlocal x_win, o_win
            if (all(x in ['X'] for x in gb[0]) or all(x in ['X']for x in
               gb[1])or all(x in ['X'] for x in gb[2])):
                x_win = True
            if (all(x in ['O'] for x in gb[0]) or all(x in ['O'] for x in
               gb[1])or all(x in ['O'] for x in gb[2])):
                o_win = True

        def win2():
            nonlocal x_win, o_win
            if (all(x in ['X'] for x in gb[:, 0]) or all(x in ['X']for x in
               gb[:, 1]) or all(x in ['X'] for x in gb[:, 2])):
                x_win = True
            if (all(x in ['O'] for x in gb[:, 0]) or all(x in ['O']for x in
               gb[:, 1]) or all(x in ['O'] for x in gb[:, 2])):
                o_win = True

        def win3():
            nonlocal x_win, o_win
            if (all(x in ['X'] for x in np.diag(gb)) or all(x in ['X'] for x
               in np.diag(np.fliplr(gb)))):
                x_win = True
            if (all(x in ['O'] for x in np.diag(gb)) or all(x in ['O'] for x
               in np.diag(np.fliplr(gb)))):
                o_win = True

        def tied():
            nonlocal tie
            if all([x in ['X', 'O'] for x in o_gb[0]] + [x in ['X', 'O']for
               x in o_gb[1]] + [x in ['X', 'O'] for x in o_gb[2]]):
                tie = True
        while 1:
            print(gb)
            xm = input('X\'s move(x,y): ').split(',')
            xm = [int(i) for i in xm]
            if gb[xm[0]-1, xm[1]-1] not in ['X', 'O']:
                gb[xm[0]-1, xm[1]-1] = 'X'
            else:
                 print('You can\'t move there, now you lose a turn!')
            win()
            win2()
            win3()
            tied()
            print(gb)
            if o_win or x_win or tie:
                break
            om = input('O\'s move(x,y): ').split(',')
            om = [int(i) for i in om]
            if gb[om[0]-1, om[1]-1] not in ['X', 'O']:
                gb[om[0]-1, om[1]-1] = 'O'
            else:
                print('You can\'t move there, now you lose a turn!')
            win()
            win2()
            win3()
            tied()
            if o_win or x_win or tie:
                break
            if x_win:
                print('X wins!')
            elif o_win:
                print(gb)
                print('O wins!')
            else:
                if o_win:
                    print(gb)
                print('Tie!')
            while 1:
                done = input('Again?(y/n)')
                if done in ['y']:
                    ticTacToe()
            else:
                break

Any help would be appreciated, thanks!

A: all checks for all, you need any (and simplify your code):
def tied():
    nonlocal tie
    if any(x in 'XO' for i in o_gb[:3] for x in i):
        tie = True

then simplify it like this in all functions


text:
Q: Tutorials for problems with Xilinx's microblaze IP Stack My team is using the microblaze and we're having some trouble with the ip stack.
I am usually not an embedded programmer but I would like to learn how to help.
Are there any tutorials about IP stacks? What are they? How are they programmed? How can I troubleshoot problems in the IP stack?
Basically any info would help me.
Thanks in advance,
Omer.
Edit:
According to our electronic engineer this is the problem:
We are using lwIP on the Spartan-3A DSP S3D1800A circut while using BSB and it microblaze on it.
We're trying to use the Echo Server demo that has been given to us and it's supposed to open a port to telnet and echo any message recivied from there but it doesn't do that.
We have absolutly no idea what's wrong there.

A: TCP/IP lean by Jeremy Bentham
http://www.iosoft.co.uk/tcplean.php

A: First, it's good to know which IP stack you're using. Are you using e.g. lwIP stack or uIP stack? They are popular stacks for embedded platforms. You could have a look at the documentation for those stacks, for an introduction to the main concepts. There are functional examples around for those stacks on a variety of platforms.
lwIP

*

*Documentation wiki (a bit sparse)

*Function documentation

*lwIP Example from Xilinx (it includes some Microblaze material)

A: As far as troubleshooting goes, you can search for relevant keywords on Xilinx forum.
Different IP stack implementations for Microblaze have been around for a few years, so chances are you'll find a lot of useful stuff there.


text:
Q: How to add SwatchLegend to a graph? I created a random graph with each vertex colored randomly.
I would like to add a SwatchLegend to the graph to indicate the value corresponding to a color. How can I do that?
Here's my code for the graph.
color = Map[# -> ColorData[3][RandomInteger[{1, 5}]] &, Range[100]];
g1 = RandomGraph[{100, 500}, VertexStyle -> color, VertexSize -> 1.5]

Here's my code for the legends.
legend = SwatchLegend[Table[ColorData[3][i], {i, 1, 5}], Automatic];

How can I combine the two?

A: You can use Legended:
Legended[g1, legend]

Alternatively, you can use the option Epilog:
RandomGraph[{100, 500}, VertexStyle -> color,  VertexSize -> 1.5,
 Epilog -> Inset[legend, Scaled @ {1.1, .5}], ImagePadding -> 40]

A: In general, you can use any type of legends inside the plotting routines:
Plot[
 {Sin@x, Cos@x}, {x, -Pi, Pi},
 PlotStyle -> {Red, Blue},
 PlotLegends ->
  Placed[SwatchLegend[{Red, Blue}, {"Sin", "Cos"}], Right]
 ]

However, the kglr's way allows making legends for any objects (like arbitrary graphics).


text:
Q: How to access parent controller $scope values in child controller     var parent = angular.module('parent', ['swxSessionStorage']);

    parent.controller('parent', [

        $scope.idMenu = [{
                label : "id1",
                value : 1
            }]

$scope.name=[abc,def];
     /**
         * Calling child controller
         */

        var childView = $scope.$new(true);
        $controller('child',{$scope:childView});
        $scope.someMetod = function(){
            childView.getChildData();
        }
        }

        --------------
    parent.controller('child', [
    $scope.getChildData = function(){
        $scope.idMenu.value
    }

I'm not able to access parent $scope.idMenu in Child controller?
But Im able to access $scope.name,which is just an array,but Im not able to access JsonArray.
What could be the reason?

A: In parent controller
$scope.$broadcast('event_name', function (){
//action on event
});

In child controller
$scope.$on('event_name', function () {
//data required to pass in parent controller
});

A: The best way would be to use a service.
app.service('dataService', function() {
  var dataList = [];

  function addData(data) {
    dataList.push(data);
  };

  function getData() {
    return dataList;
  };

  return {
    add: addData,
    get: getData
  };
});

In your parent controller, store the information via the service:
app.controller('parent', function($scope, dataService) {
  $scope.addMyData = function(obj) {
    dataService.addData(obj);
  };
});

And in the child controller, retrieve the information via the service:
app.controller('child', function($scope, dataService) {
  $scope.products = dataService.getData();
});

You cannot inject $scope into the service but you can store data.


text:
Q: What video editing software should I use to make screencast videos with external audio? I want to make screencast videos and record audio externally. What video editing software should I use? This is for an online class in introductory logic that I'm terribly late putting together.
To clarify: I want to record external audio, not internal. I want to highlight lines in a PDF while talking about the material.
I tried recordMyDesktop but it doesn't seem to have an external audio option.

A: You probably missed it, but recordMyDesktop does have the option to capture audio from your input device.
Once you launch recordMyDesktop, you should see a window similar to the following one:

You just need to check the box next to 'Sound Quality'. Then it will capture the audio from your microphone along with capturing the desktop.

In order convert the file format to something YouTube friendly you may use OpenShot which provides some templates for YouTube friendly output (refer to this answer).


text:
Q: Default value not setting Boolean Field Pgsql In my project I have created a boolean field with default value as false using django models. But whenever I am trying to save into that table I am getting the error saying that null value in column "dmz" violates not-null constraint
what could be the reason. What am doing wrong
This is my model field
 dmz = models.BooleanField(default=False, blank=False)

Edited
When I did the
python manage.py sqlmigrate subnets 0014_subnet_dmz
I am getting  the generated sql as this
ALTER TABLE "subnets_subnet" ADD COLUMN "dmz" boolean DEFAULT true NOT NULL;
ALTER TABLE "subnets_subnet" ALTER COLUMN "dmz" DROP DEFAULT;

ie default value is dropping . How can I preserve this ?


text:
Q: How to send 2 events one after the other with botframework webchat? I customized the BotFramework Webchat to send 2 events to my bot.
The first one is for the RGPD, we are reminding to the user which information is saved and for what purpose. The second one is a "greeting" message (the bot say "Hi ...").
But with the dispatch method, both events are sent almost at the same time and sometimes, the webchat display the greetings message first, whichi is not what I expect.
Here is the sample.
createStore({}, function (_ref) {
        var dispatch = _ref.dispatch;
        return function (next) {
            return function (action) {
                 if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
                    dispatch({
                        type: 'WEB_CHAT/SEND_EVENT',
                        payload: {
                            name: 'rgpd',
                            type: 'event'
                        }
                    });

                    dispatch({
                            type: 'WEB_CHAT/SEND_EVENT',
                            payload: {
                                name: 'greeting',
                                type: 'event'
                            }
                        });
                 }
            }
        }
}

So how can I send the greeting event always after the rgpd event ?
I tried using a simple window.setTimeout, but, it's not a good solution as I don't know how much time will directline take to handle the first call and the result is the same as before.
Any ideas ?
Thanks

A: I would recommend dispatching one event and sending two activities from the bot.
Bot Framework SDK v4 (Node)
this.onEvent(async (context, next) => {
  if (context.activity.name === 'webchat/join') {
    await context.sendActivities([{ text: 'General Data Protection Regulation' }, { text: 'Backchannel Welcome Message sent from `onEvent`!' }]);
  }
  await next();
});

Web Chat v4 - Store Middleware
const store = createStore(
  {},
  ({ dispatch }) => next => async action => {
    if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
    dispatch({
      type: 'WEB_CHAT/SEND_EVENT',
      payload: {
        name: 'webchat/join'
      }
    });
  }
  return next(action)
});

Screenshot

A: I would suggest looking into Javascript promises as they are meant to solve problems with asynchronous task. There are some great writeups here and here.
Something like the following:
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
  new Promise(function() {
    dispatch({
        type: 'WEB_CHAT/SEND_EVENT',
        payload: {
            name: 'rgpd',
            type: 'event'
        }
    });
  }).then(function() {
    dispatch({
      type: 'WEB_CHAT/SEND_EVENT',
      payload: {
          name: 'greeting',
          type: 'event'
      }
    });
  });
}


text:
Q: Upload file to Cloudinary Meteor I am using the following html to allow the user to upload images:
<input class="upload" type="file" id="upload">

I have the following method to upload to Cloudinary:
      cloud : function (source) {
      cloudinary.uploader.upload(source, function(result) { console.log(result) },
      { public_id: "test" });

  },

And the following to detect input and call the method:
'change #upload': function(event, template) {
          var imgVal = document.getElementById("upload");
          Meteor.call("cloud",imgVal);
      },

I receive this error:
Exception while invoking method 'cloud' TypeError: Object #<Object> has no method 'match'
I20150813-10:10:38.007(-4)?     at C:\Users\Raj\art\.meteor\local\isopacks\npm-container\npm\node_modules\cloudinary\lib\uploader.js:61:34
I20150813-10:10:38.007(-4)?     at call_api (C:\Users\Raj\art\.meteor\local\isopacks\npm-container\npm\node_modules\cloudinary\lib\uploader.js:368:22)
I20150813-10:10:38.008(-4)?     at Object.exports.upload (C:\Users\Raj\art\.meteor\local\isopacks\npm-container\npm\node_modules\cloudinary\lib\uploader.js:58:12)
I20150813-10:10:38.008(-4)?     at [object Object].Meteor.methods.cloud (app\art.js:132:28)
I20150813-10:10:38.008(-4)?     at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1617:1)
I20150813-10:10:38.008(-4)?     at packages/ddp/livedata_server.js:648:1
I20150813-10:10:38.008(-4)?     at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
I20150813-10:10:38.008(-4)?     at packages/ddp/livedata_server.js:647:1
I20150813-10:10:38.009(-4)?     at [object Object]._.extend.withValue (packages/meteor/dynamics_nodejs.js:56:1)
I20150813-10:10:38.009(-4)?     at [object Object]._.extend.protocol_handlers.method (packages/ddp/livedata_server.js:646:1)
=> Meteor server restarted

What can I do to fix this?

A: Image Upload dont support the Meteor.call function.
Try:
'yourcollection'.allow({ <-- without the ''.
  insert: function() {return true},
  update: function() {return true},
});

put it in your lib/yourcollection.js

A: cloudinary.uploader.upload expects the first argument file to be a string. You are sending an HTMLInputElement.
You can extract the selected file(s) as a base64 encoded string from the input element using the files property and FileReader:
'change #upload': function(event, template) {
    var imgVal = document.getElementById("upload");
    var files = imgVal.files; // FileList object

    // Loop through the FileList and upload each image file.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          Meteor.call("cloud",e.target.result);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  },

(Source adapted from http://www.html5rocks.com/en/tutorials/file/dndfiles/.)
Please note that cloudinary_npm was designed for server side operation - however I believe the above code would work.


text:
Q: A/B testing Optimizely and Google Analytics with Screen Resolution=(not set) We've setup an A/B in Optimizely to test a completely new design:
http://offerta.se
that we're testing against our legacy design:
http://offerta.se/?classic=1
Optimizely is setup to redirect 50% of our CPC traffic to the legacy design.
The old design is beating the new with about 10% better convertion rate and in trying to fiqure out why we started looking at if there was anything standing out in Google Analytics.
Optimizely creates the events with labels "New design" and "Legacy design" for us in GA.
And filtering on these and looking at "Screen Resolution=(not set)" we see some weird numbers:

If we remove all traffic with "Screen Resolution=(not set)" the new design instead performs 10% better than the old.
Anyone that can enlighten me?


text:
Q: Ajax Not working Properly. i am trying to register customer and want live checking of email is registered with us or not. mobile number is registered with us, i am not getting the required result in both the event it give me same result if its registered of not. can you please help me. result in both event is  ///"Already Registered with this E-mail";
if(isset($_POST['name'])){
$sellerEmail =$_POST['name'];

    $query_verify_mob= new ParseQuery("Vyapari");
    $query_verify_mob->EqualTo("sellerEmail", $sellerEmail);
    $result=count($query_verify_mob);

if($result ==1)
{
    echo "Already Registered with this E-mail...";

}
else
{
    echo "Email ID is Available...";
}}.

A: 0 input in what ParseQuery is, aniway u must just check the count of emails with that input email.
Instead of $result == 1 u should use $result > 0.


text:
Q: Robolectric 3.0 - java.lang.NoClassDefFoundError: android/support/v7/appcompat/R$styleable when testing library module I recently upgraded my Robolectric from 2.4 to 3.0-rc3 and after a lot of wrestling with it, I've narrowed it down to this last error where a few cases fail because of this issue:
java.lang.NoClassDefFoundError: android/support/v7/appcompat/R$styleable

It passes like 99% of the cases, but a few are failing because of this. The other components of my application all pass with flying colors, and I've only seen it happen in my module.
I looked it up and it seems that the problem stems from Robolectrie 3.0 not generating the R.java files. However, there didn't seem to be a solution for it, save for some build.gradle hack that didn't work for me. I also already tried editing targetSDKs and making sure the AppCompat theme was set in the manifest, to no avail.
build.gradle:
apply from: rootProject.file('src/build/groovy/android-library.gradle')

dependencies {
    compile project(':myApplication')

    compile('com.application:player:') {
    exclude module: 'support-v4'
}

    compile "com.android.support:support-v4:19.1.0"
    compile 'com.android.support:cardview-v7:21.0.+'
    compile "com.android.support:appcompat-v7:22.1.0"
}

Does anybody have any idea how to fix this? It's sinking a lot of my time!

A: Robolectric 3.0 has started to separate several shadow classes out into different artifacts. You probably just need to add shadows-support-v4 as a dependency (while keeping the *-v7 dependencies from com.android.support).

A: I had experienced the same issue.
This is what I did to remediate it.
Assume you have included following libraries
    support-v4, com.android.support.v7's appcompat lib, robolectric 3.0 and junit and the reference to the apkib you are testing (as per sschuberth and other contributors of this thread)
Suppose the activity under test is XXXActivity.
In order to populate our context in our unit test case - we utilize
    Robolectric.buildActivity(XXXActivity.class).create().start().resume().get();
I changed it to
    Robolectric.buildActivity(XXXMockActivity.class).create().start().resume().get();
where XXXMockActivity merely sets a theme before invoking the super.onCreate().
public class XXXMockActivity extends XXXActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_AppCompat_Light_DarkActionBar);
        super.onCreate(savedInstanceState);
    }
}

A: I simply ignored the test - there doesn't seem to be a solution for this problem. As someone commented on my original question, this is an open issue found here:  github.com/robolectric/robolectric/issues/1796
If you're having the same problem, I wouldn't spend too much time on it.


text:
Q: Breaking sentences up What is the right term for breaking or dividing a sentence into fragments, wherein each fragment still contains a thought/meaning?
e.g.:

Sports can ostracize people/ who are not very good at them./

A: The process of splitting up and analysing a sentence grammatically to see how it works is called scanning the sentence. I'm not sure if that's what you mean?


text:
Q: echo end of url without backslash http://www.mywebsite/product-tag/animal/
How to I echo animal without the backslash and in big caps like this:
ANIMAL

A: $link = 'http://www.mywebsite/product-tag/animal/';
$parts = explode( '/', $link );
echo(strtoupper($parts[4]));

If you want auto searching, then you need to use preg_match.

A: <?php
$string = 'http://www.mywebsite/product-tag/animal/';
$urlparts = explode("/", $string);

$animal = ($string[strlen($string)-1] == '/'? $urlparts[count($urlparts)-2] : end($urlparts));
echo strtoupper($animal);
?>

A: actually I just figured it out
$r = $_SERVER['REQUEST_URI'];
$r = explode('/', $r);
$r = array_filter($r);
$r = array_merge($r, array());

$endofurl = $r[1];
echo $endofurl;


text:
Q: can't install pyaudio can't build weel error Mac xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
error: command '/usr/bin/gcc' failed with exit code 1
[end of output]
ERROR: Failed building wheel for PyAudio
Failed to build PyAudio
ERROR: Could not build wheels for PyAudio, which is required to install pyproject.toml-based projects
I get this error how to solve this ?
Mac user
it gives me can't build weel even tho I tired many Methods posted here