text:
Q: Submit a form using AJAX JQuery and ASP.Net with Master Pages I wrote a search program using lucene.net. The search method returns a string containing an html table with the search results. This part works, but I wanted the ability to submit the search without reloading the entire page... So I searched and found that this could be done using AJAX. For whatever reason I cannot get it to work.
I'm not throwing an error. The contents of "Search.aspx" get returned, but it seems like the Submit Method never executes.
Search.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">

    <form name="search" action="">
        <fieldset>
            RPE Search
            <input type="text" name="query" value="" class="sTM" />
            <input type="submit" name="submit" class="sBM" id="submit_btn" value="" />
      </fieldset>
    </form>

</asp:Content>

CodeFile:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class Search : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod]

    public static string Submit(string query)
    {
        SearchDoc seek = new SearchDoc();
        return seek.Search("valve");
    }

}

A: You must have the ScriptModule configured in your web.config to call static page methods like that. If you are running an ASP.NET 3.5 project in Visual Studio using the built-in development web server, make sure this is in your web.config, inside system.web/httpModules:
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

If you are using IIS then make sure this is in your web.config, inside system.webServer/httpModules:
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

If you don't have the right configuration, it is common that a post to Search.aspx/Submit will just return the full page and your web method will not even be called in that case. The role of the ScriptModule is to map this request to the web method and return its return value as the response.

If that does't work (you already have the right configuration), then try to set your request contentType to application/json and perhaps also change the way you pass the query parameter to your web method (also in JSON format):
data: { "query": dataString },
contentType: "application/json; charset=utf-8",
dataType: "json",

See also these similar questions:

*

*Call ASP.NET PageMethod/WebMethod with jQuery - returns whole page

*Jquery AJAX with ASP.NET WebMethod Returning Entire Page

A: Well I recent work with a site in ASP.NET, I add a Webservice to my ASP.NET project, and use this snippet in jQuery:
        var info = {};
        info.Ticket = ticket;
        info.idCategoria = $('#hidCategoria').val();

        var DTO = { 'info': info };

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "MyWebService.asmx/MyTargetFunction",
            data: JSON.stringify(DTO),
            dataType: "json",
            success: function (data) {
                if (data.d != null) {
                    // My Logic
                }
            },
            error: function (data) {
                alert('Error!');
            }
        });

My Webservice are a function like this:
    [WebMethod]
public ResponseInfo CrearTicket(CreateTicketInfo info) {
    ResponseInfo i = new ResponseInfo();
    _info = info;

    try
    {
        // Logic Here
    }
    catch (Exception e)
    {
        i.ResponseCode = ContactoConstants.GENERICERROR;
        i.Message = e.Message;
    }

    return i;
}


text:
Q: How do I consolidate a multi-level Windows boot menu? Well I seem to be having problems loading operating systems that I have recently installed on three partitions.
I had installed Windows XP first, then Windows Server 2003 Standard and finally Windows Vista Ultimate. When the Boot Manager loads it gives me two options:

*

*Earlier versions of Windows

*Windows Vista Ultimate (TM)

Since then if I need to navigate to the selection of Windows XP & Windows Server 2003 I have to select "Earlier versions Of Windows" and then continue to make a selection which seems a bit boring.
So my question is, is it possible to have all the three options to select from any of the three operating systems on a single Boot Manager page?

A: Install EasyBCD in Vista and add EasyLDR entries for the other OSes:

All you need to do is uncheck the checkbox labeled "Automatically detect the correct drive". Subsequently, a drop-down box containing a list of all mounted partitions will appear, and you can choose the Windows XP installation you wish to boot into. Clicking "Add Entry" will cause EasyBCD to automatically create the easyldr#, ntdetect.com, and ebcd.00x files needed to boot into the selected partition. You can then repeat these steps for as many separate legacy NT installs as you have available.

EasyLDR is required instead of simply adding NTLDR entries to prevent a 2 level boot menu. This is what the situation is like at present:

This is what is required:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Static sources not supported for video yet I was trying to play a song using Pyglet, but encountered this error
NotImplementedError: Static sources not supported for video yet.
But the file is mp3 format. I have AVbin11-win64.exe installed (avbin64.dll) which is copied in 'C:\Windows\SysWOW64' Folder, downloaded from https://github.com/AVbin/AVbin/downloads.
Here is the script I am using :
import pyglet
player = pyglet.media.Player()
source = pyglet.media.load(r'C:\Users\MANDAV\Desktop\New folder (2)\Diamond-
Platnumz-All-The-Way-Up-v2.mp3', streaming=False)
player.play()
player.app.run()

A: Your code contains a few issues.
The first being player.app.run(), player doesn't have .app - you're probably looking for pyglet.app.run().
The second thing is that you try to call player.play(), but you never did player.queue(source). So either do source.play() or player.queue(source) (both does exactly the same thing, playing the source directly will create a player in the background.)
The third thing being streaming=False. avbin (10 at least) have issues decoding mp3 as a static source. Not quite sure why, but the project has been dead for soon to be a century (yes, in just a few short years, this code has been dead for 10 years).
Here's a minimal working example:
import pyglet
source = pyglet.media.load('epic.mp3')
source.play()
pyglet.app.run()

Altho, you probably want some more functionality while playing your stuff. So here's a bigger example of how you could put together a start for a music playing application:
import pyglet
from pyglet.gl import *
from collections import OrderedDict

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)

        self.keys = OrderedDict() # This just keeps track of which keys we're holding down. In case we want to do repeated input.
        self.alive = 1 # And as long as this is True, we'll keep on rendering.

        ## Add more songs to the list, either here, via input() from the console or on_key_ress() function below.
        self.songs = ['A.wav', 'B.wav', 'C.wav']
        self.song_pool = None

        self.player = pyglet.media.Player()
        for song in self.songs:
            media = pyglet.media.load(song)
            if self.song_pool is None:
                ## == if the Song Pool hasn't been setup,
                ##    we'll set one up. Because we need to know the audio_format()
                ##    we can't really set it up in advance (consists more information than just 'mp3' or 'wav')
                self.song_pool = pyglet.media.SourceGroup(media.audio_format, None)
            ## == Queue the media into the song pool.
            self.song_pool.queue(pyglet.media.load(song))

        ## == And then, queue the song_pool into the player.
        ##    We do this because SourceGroup (song_pool) as a function called
        ##    .has_next() which we'll require later on.
        self.player.queue(self.song_pool)
        ## == Normally, you would do self.player.eos_action = self.function()
        ##    But for whatever fucky windows reasons, this doesn't work for me in testing.
        ##    So below is a manual workaround that works about as good.

        self.current_track = pyglet.text.Label('', x=width/2, y=height/2+50, anchor_x='center', anchor_y='center')
        self.current_time = pyglet.text.Label('', x=width/2, y=height/2-50, anchor_x='center', anchor_y='center')

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        elif symbol == key.SPACE:
            if self.player.playing:
                self.player.pause()
            else:
                self.player.play()

        elif symbol == key.RIGHT:
            self.player.seek(self.player.time + 15)

        ## == You could check the user input here,
        ##    and add more songs via the keyboard here.
        ##    For as long as self.song_pool has tracks,
        ##    this player will continue to play.

        self.keys[symbol] = True

    def end_of_tracks(self, *args, **kwargs):
        self.alive=0

    def render(self):
        ## Clear the screen
        self.clear()

        ## == You could show some video, image or text here while the music plays.
        ##    I'll drop in a example where the current Track Name and time are playing.

        ## == Grab the media_info (if any, otherwise this returns None)
        media_info = self.player.source.info
        if not media_info:
            ## == if there were no meta-data, we'll show the file-name instead:
            media_info = self.player.source._file.name
        else:
            ## == But if we got meta data, we'll show "Artist - Track Title"
            media_info = media_info.author + ' - ' + media_info.title

        self.current_track.text = media_info
        self.current_track.draw()

        ## == This part exists of two things,
        ## 1. Grab the Current Time Stamp and the Song Duration.
        ##    Check if the song_pool() is at it's end, and if the track Cur>=Max -> We'll quit.
        ## *  (This is the manual workaround)
        cur_t, end_t = int(self.player.time), int(self.player.source._get_duration())
        if self.song_pool.has_next() is False and cur_t >= end_t:
            self.alive=False

        ## 2. Show the current time and maximum time in seconds to the user.
        self.current_time.text = str(cur_t)+'/'+str(end_t) + 'seconds'
        self.current_time.draw()

        ## This "renders" the graphics:
        self.flip()

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

x = main()
x.run()

If you're just interested in playing sounds.
I wholeheartedly recommend Pydub.
Not only does it use libav which is more of a defacto standard when encoding and decoding, but it's also rich in features. Such as converting .mp3 to .wav and you can control audio gain, play two sources at the same time etc.


text:
Q: How to Update Node Value into Existing XML file Using Flash AS3 I have a Xml File having the values, I am using Flash AIR application with Action Script3,
<Home>
  <Name>John</Name >
  <RollNo>102</RollNo >
  <Age>25</Age >
  <Mark>70</Mark >
</Home >

For read the xml file I used the
var xmlLoader:URLLoader = null;
var xmlData:XML = new XML();
xmlLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, LoadingXMLData);
xmlLoader.load(new URLRequest("Details.xml"));

function LoadingXMLData(e:Event):void
{
    xmlData = new XML(e.target.data);
    ParseXML(xmlData);
}

function ParseXML(configData:XML):void
{
    trace("XML Data : " + configData);
}

I want to update a particular node value.
How can I update the value in the existing XML file.
for update the value i have tried
xmlData.replace(xmlData.hostName,"Helooon");
trace("Updated XML Data : " + xmlData);

How to write these in to the existing XML file.

A: To save the XML back to a file you have to use FileReference.save() in the Flash Player, or File with FileStream.writeUTFBytes() in AIR.
EDIT: I see your comment that you are using AIR, so you can use the File class. Here's a quick example:
var file:File = File.documentsDirectory.resolvePath("Details.xml");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes(xmlData);
stream.close();

Note that because the XML is parsed and re-encoded, formatting may change. You can control the formatting output using XML static formatting properties.


text:
Q: Getting TypeError: list indices must be integers when using list[:,colIndex] to get column data as list I have a 2D list (a list of lists) and am trying to use the notation list[:,colIndex] to pull out a single column's data into another list, but I'm getting a TypeError: list indices must be integers error.
for example:
lst = [[1,2,3],[10,12,13]]
lst[:,0]

Returns:
Traceback (most recent call last):
  File "<input>", line 2, in <module>
TypeError: list indices must be integers

I don't understand...
Edit:
Running this in Python 3.9 gives me:
TypeError: list indices must be integers or slices, not tuple

A: It would seem that the [:,colIndex] syntax isn't supported by lists and is available to numpy arrays only :(
However I can use: list(zip(*lst))[colIndex] instead from this answer https://stackoverflow.com/a/44360278/1733467


text:
Q: Proving a function $u:[0,\infty)^2 \to \mathbb{R}$ cannot preserve an 'order' given to the domain The set $[0,\infty)^2$ is considered to have order $\succeq$, where $\succeq$ is a binary relation satisfying $(x_1,y_1) \succeq (x_2,y_2)$ if $x_1 > x_2$ or ( $x_1 = x_2$ and $y_1 \geq y_2$ ). I am trying to show no function $u:[0,\infty)^2 \to \mathbb{R}$ can preserve this order (strictly), with the codomain ordered in the obvious way.
I would like to suppose it exists for a contradiction and argue that, for $\omega_{x} = (x,1)$ and $\omega_{x}' = (x,2)$, it is necessarily the case that $u(\omega_x') > u(\omega_x)$ for any $x \in [1,2]$, and hence as for each such value $x$ the value of $u$ must increase, and with $x$ belonging to an uncountable set and each increase is strictly positive, and $u$ is strictly monotonic in the orderings, indeed $u(\omega_2)$ would have to be infinitely bigger than $u(\omega_1)$.
However, I am struggling to formulate this answer properly. The argument relies on the cardinality of the reals being uncountable, however it is exactly this that is causing me difficulty in formulating a proof.
How can I go about formulating this idea into a rigorous proof? If possible, I'd like this to not rely on advanced mathematical structures much further than what I have already mentioned.

A: I am assuming that the relation $\{(p,q)\in [0,\infty)^2: p\geq q\ne p\}$ is a linear order.  Suppose $f:[0,\infty)^2\to \Bbb R$  strictly preserves this linear order.
For each $x\in [0,\infty)$ let $S(x)$ be the non-empty real interval $(f(x,0),f(x,1)).$
If $x,x'\in [0,\infty)$ with $x< x'$ then $S(x)\cap S(x')=\phi$ because  $f(x,1)<f(x',0).$
So $\{S(x): x\in [0,\infty)\}$ is an uncountable family of pair-wise disjoint non-empty open subsets of $\Bbb R.$ So $\{S(x)\cap \Bbb Q: x\in [0,\infty)\}$ is an uncountable family of pair-wise disjoint non-empty subsets of $\Bbb Q$, which is impossible because  $\Bbb Q$ is only countable.

A: Pay attention to each vertical line $\{t\}\times[0,\infty)\subseteq[0,\infty)^2$. Each of these vertical lines inherits the order from $[0,\infty)^2$, and the order structure on each vertical line is isomorphic to $[0,\infty)$.
Now suppose for contradiction there is a function $u$ preserving the order strictly. Note that we require $u(\{t\}\times[0,\infty))$ is bounded in $\Bbb R$, i.e. $u(\{t\}\times[0,\infty))\subseteq[a_t,b_t]$ for some $a_t,b_t\in\Bbb R$ depending on $t$. To see why, notice that $u(\{t\}\times[0,\infty))$ is bounded from below because there is a smallest element $(t,0)$ on the vertical line, and is bounded from above because each element in $u(\{t\}\times[0,\infty))$ has to be less than $u(t+1,0)$. Note that you can take $a_t=u(t,0)$. Note also $b_t\gt a_t$ because the increasing-ness is strict. With no risk, pick $b_t=\sup u(\{t\}\times[0,\infty))$.
Let $\varepsilon\gt0$. Since $a_{t+\varepsilon}$ is an upper bound for the set $u(\{t\}\times[0,\infty))$, by definition of supremum, we have $a_{t+\varepsilon}\ge b_t$. So we obtain an uncountable number of closed, bounded and nondegenerate intervals $\{[a_t,b_t]:t\in[0,\infty)\}$ which are distinct from each other in the sense $[a_t,b_t]\not=[a_{t'},b_{t'}]$ whenever $t\not=t'$ due to the relation $a_{t+\varepsilon}\ge b_t$.
Now since those intervals are nondegenerate, we can pick a rational number $r_t$ with $a_t\lt r_t\lt b_t$ for each $t$. This requires axiom of choice. Again, by the relation $a_{t+\varepsilon}\ge b_t$, the $r_t$'s are distinct in the sense $r_t\not=r_{t'}$ whenever $t\not=t'$. We have found an uncountable number of rational numbers $\{r_t:t\in[0,\infty)\}$, a contradiction.


text:
Q: ExtJS 5: Complex grid data - set column editor value I have "complex" data--meaning there are associations in my data--and I'm trying to use these associations in my grid. I create the columns based on some of the data, and because the data is nested in an array, I set a renderer for each column... I also set an editor. The renderer is working just fine, but setting the editor's value is not working out like I thought it would. Here's my code (and Fiddle):
Ext.application({
  name : 'Fiddle',
  launch : function() {
    Ext.define('Phone', {
      extend: 'Ext.data.Model',
      fields: [
        {name: 'phone', type: 'int'},
        {name: 'type', type: 'string'}
      ]
    });
    Ext.define('Person', {
      extend: 'Ext.data.Model',
      fields: [
        {name: 'name', type: 'string'}
      ],
      hasMany: [
        {associationKey: 'phones', model: 'Phone', name: 'getPhonesStore'}
      ]
    });
    var beforeEdit = function(editor, context, eOpts) {
      var grid = context.grid;
      var record = context.record;
      if (grid && record) {
          var phonesStore = record.getPhonesStore();
          var columns = grid.columns;
          if (columns && phonesStore) {
              for (var i = 1; i < columns.length; i++) {
                  var column = columns[i];
                  if (column) {
                      var editor = column.getEditor();
                      if (editor) {
                          alert(phonesStore.getAt(i - 1).get('phone'));
                          editor.setValue(phonesStore.getAt(i - 1).get('phone'));
                      }
                  }
              }
          }
      }
    };
    Ext.define('MyView', {
      extend: 'Ext.grid.Panel',
      store: Ext.create('Ext.data.Store', {
        model: 'Person',
        proxy: {
          type: 'memory'
        },
        data: [
          {name: 'blah', phones: [{phone: 123456789, type: 'Home'}, {phone: 9999999999, type: 'Cell'}]},
          {name: 'bleh', phones: [{phone: 222222222, type: 'Home'}, {phone: 1111111111, type: 'Cell'}]}
        ]
      }),
      plugins: [
        {ptype: 'rowediting', clicksToEdit: 1, listeners: {beforeedit: beforeEdit}}
      ],
      height: 300,
      width: 400,
      initComponent: function() {
        var store = this.getStore();
        if (store) {
          var firstRecord = store.first();
          if (firstRecord) {
            var phonesStore = firstRecord.getPhonesStore();
            if (phonesStore) {
              var columns = [{
                xtype: 'gridcolumn',
                dataIndex: 'name',
                text: 'Name',
                editor: {
                  xtype: 'textfield',
                  hideTrigger: true
                }
              }];
              phonesStore.each(function(phoneRec) {
                columns.push({
                  xtype: 'gridcolumn',
                  text: phoneRec.get('type'),
                  renderer: this.phoneRenderer,
                  editor: {
                    xtype: 'numberfield',
                    hideTrigger: true
                  }
                });
              }, this);
              this.columns = columns;
            }
          }
        }
        this.callParent();
      },
      phoneRenderer: function(value, metaData, record, rowIndex, colIndex) {
        return record.getPhonesStore().getAt(colIndex - 1).get('phone');
      }
    });
    Ext.create('MyView', {
      renderTo: Ext.getBody()
    });
  }
});

In total, I have 3 columns... Name, Home, and Cell. Now you might be thinking, why don't I just have a Cell and Home object instead of the phones array... well, that's not what I'm looking to do, as I don't think that's how to properly structure this data. Anyway, I create these two extra columns when I init my grid.
The problem comes with the editor that I set for the "Home" and "Cell" columns... because I'm using nested data and don't have a proper dataIndex, when the editor renders, it has an empty value for the editor. So I figured try tapping into the beforeedit event, and I can get my values, but unfortunately, it doesn't look like I can set the editor's value, as I'm assuming the startEdit method has some trickery going on.
You'll see that when you click on a row, it alerts the Home and Cell values that I want to set in their editors, but using setValue for the editor doesn't work... does anyone have any insight on how to get this going?

A: I was able to solve this by using the setEditor method (on the column) when the row is clicked:
Ext.application({
  name : 'Fiddle',
  launch : function() {
    Ext.define('Phone', {
      extend: 'Ext.data.Model',
      fields: [
        {name: 'phone', type: 'int'},
        {name: 'type', type: 'string'}
      ]
    });
    Ext.define('Person', {
      extend: 'Ext.data.Model',
      fields: [
        {name: 'name', type: 'string'}
      ],
      hasMany: [
        {associationKey: 'phones', model: 'Phone', name: 'getPhonesStore'}
      ]
    });
    var beforeEdit = function(editor, context, eOpts) {
      var grid = context.grid;
      var record = context.record;
      if (grid && record) {
          var phonesStore = record.getPhonesStore();
          var columns = grid.getView().getGridColumns();
          if (columns && phonesStore) {
              for (var i = 1; i < columns.length; i++) {
                  var column = columns[i];
                  if (column) {
                      column.setEditor({
                          xtype: 'numberfield',
                          hideTrigger: true,
                          value: phonesStore.getAt(i - 1).get('phone')
                      });
                  }
              }
          }
      }
    };
    Ext.define('MyView', {
      extend: 'Ext.grid.Panel',
      store: Ext.create('Ext.data.Store', {
        model: 'Person',
        proxy: {
          type: 'memory'
        },
        data: [
          {name: 'blah', phones: [{phone: 123456789, type: 'Home'}, {phone: 9999999999, type: 'Cell'}]},
          {name: 'bleh', phones: [{phone: 222222222, type: 'Home'}, {phone: 1111111111, type: 'Cell'}]}
        ]
      }),
      plugins: [
        {ptype: 'rowediting', clicksToEdit: 1, listeners: {beforeedit: beforeEdit}}
      ],
      height: 300,
      width: 400,
      initComponent: function() {
        var store = this.getStore();
        if (store) {
          var firstRecord = store.first();
          if (firstRecord) {
            var phonesStore = firstRecord.getPhonesStore();
            if (phonesStore) {
              var columns = [{
                xtype: 'gridcolumn',
                dataIndex: 'name',
                text: 'Name'
              }];
              phonesStore.each(function(phoneRec) {
                columns.push({
                  xtype: 'gridcolumn',
                  text: phoneRec.get('type'),
                  renderer: this.phoneRenderer
                });
              }, this);
              this.columns = columns;
            }
          }
        }
        this.callParent();
      },
      phoneRenderer: function(value, metaData, record, rowIndex, colIndex) {
        return record.getPhonesStore().getAt(colIndex - 1).get('phone');
      }
    });
    Ext.create('MyView', {
      renderTo: Ext.getBody()
    });
  }
});


text:
Q: CanCan authorize all controllers I have CanCan and Rolify set up with ActiveAdmin, and now it's time to force authorization on my controllers.
Do I have to authorize_resource on every controller (We have a couple dozen models and controllers now), or is there a way to apply it to all of my ActiveAdmin controllers?
I tried calling it in a before_filter from ActiveAdmin.setup, but that didn't work.

A: I made an initializer: config/initializers/active_admin-cancan.rb
module ActiveAdmin
  class ResourceController
    # If you don't skip loading on #index you will get the exception:
    #
    #     "Collection is not a paginated scope. Set collection.page(params[:page]).per(10) before calling :paginated_collection."

    load_resource :except => :index
    authorize_resource

    def scoped_collection
      end_of_association_chain.accessible_by(current_ability)
    end
  end
end

Borrowed from another user's code, but now I can't find the source any more.


text:
Q: How can someone say I'm fantastic the first time we meet? Normally, after you've met a person at least twice you can select to say they're fantastic. They won't receive this rating until the next time you meet, which means that nobody should be able to say I'm fantastic until we've met at least 3 times.
However, there have been Miis that have said I'm fantastic on the second time we meet and today one said it when we've never met before. How can this happen?

A: Did you find those Miis from SpotPass and not classic StreetPass? Because in an hotspot you can receive people's Mii but that person may not "meet" your Mii at the same time. I know this because a friend of mine has met my Mii through SpotPass but I haven't met his one that day.
Probably that person have met you more than 3 times (giving you the "Fantastic"), and the first time you've received its Mii in your Plaza you've actually got the "Fantastic".

A: I have a theoretical answer that hinges on a technical detail that I cannot confirm is true, but it's something.
Here's the deal. If A and B meet, and B then changes their StreetPass Mii to C, then the next time they meet, A will meet C for the first time while B/C will meet A for the second time. This should trigger the "am I fantastic?" on B/C's system while leaving A in the dark.
So, this is what I think could happen:

*

*A meets B. B meets A.

*A meets B again. B meets A again. Both elect to send a fantastic the next time the two meet.

*B changes to C.

*C meets A. C sends "I think A is fantastic".

*A meets C. A receives a fantastic despite never having seen C before. A's "I think B is fantastic" is never sent (as A doesn't meet B)...until C changes back to B, probably.

Note that this working depends on the following detail being true: once a fantastic is fired, it no longer matters which Mii sent it, only which Mii it's targetted at.


text:
Q: New MessagingStyle on API < 24 I just stumbled upon the new MessagingStyle described here: https://developer.android.com/guide/topics/ui/notifiers/notifications.html (last paragraph)
I investigated further and found such a class also as a NotificationCompat.Style variant.
This is the code I tried:
public class MainActivity extends AppCompatActivity {

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

        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                .notify(123, new NotificationCompat.Builder(this)
                        .setContentTitle("Test")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentText("4 new messages")
                        .setStyle(new NotificationCompat.MessagingStyle("Me")
                                .setConversationTitle("Team lunch")
                                .addMessage("Hi", 123, null) // Pass in null for user.
                                .addMessage("What's up?", 234, "Coworker")
                                .addMessage("Not much", 345, null)
                                .addMessage("How about lunch?", 456, "Coworker")).build());
    }
}

This is basically just the default Activity generated when creating a new project and the sample code taken from the linked website.
Now my problem: The extended style is not shown on APIs below 24. I tested on a device with API 23. When running on an emulator with API 24, it works.
The documentation states:

Helper class for generating large-format notifications that include multiple back-and-forth messages of varying types between any number of people.
  If the platform does not provide large-format notifications, this method has no effect. The user will always see the normal notification view. [...]

But versions since KitKat do provide large-format notifications.
Is the documentation not clear enough or am I doing something wrong?

A: Update: this is fixed as of the 25.0.0 Support Library release and NotificationCompat.MessagingStyle now backports much of the styling to previous versions of Android.
Previous answer:
As per this bug report, MessagingStyle currently does not do any special formatting prior to Android N. The bug report is marked as FutureRelease which means that the work is done and it will support pre-N devices with a more rich formatting in a future version of the Support Library.
If you wish to use it now, you can certainly build your own pre-N version of the notification (using a BigTextStyle if the version of Android is less than N for example).

A: If I am reading the source code correctly, the fallback for pre-24 devices has not been implemented as of the time of this writing. So, at the moment, it gives you something that compiles, and delegates properly to the native implementation on API Level 24+ devices, but will not show the messages on older devices.

A: Additional note: check your imports and make sure you use the android.support.v7.app.NotificationCompat class
instead of android.support.v4.app.NotificationCompat, because even in 25.2.0, using MessagingStyle with the "v4" builder does not show anything in devices with API < 24.


text:
Q: TypeScript and tsconfig.json file for NuxtJS I have a project with NuxtJS (in ./src/client/) and NestJS (in ./src/server/).
The tsconfig.json for NuxtJS is an extension of tsconfig.json for global project.
I don't know how I can do to the project works.
https://github.com/pirmax/nuxt-and-nest/tree/develop
I have an error on NuxtJS when I go to root page:

bundle export should be a function when using { runInNewContext: false
  }.

If I delete all traces of NestJS in my project, NuxtJS starts well, but when I add my configurations in tsconfig.json, the project gives me this error.
My tsconfig.json in ./src/client/
{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "rootDir": ".",
    "target": "es5",
    "lib": ["dom", "es2015"],
    "module": "es2015",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "noImplicitThis": false,
    "strictNullChecks": true,
    "removeComments": true,
    "suppressImplicitAnyIndexErrors": true,
    "allowSyntheticDefaultImports": true,
    "allowJs": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"]
    }
  }
}

My tsconfig.json in ./ (root)
{
  "compilerOptions": {
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "lib": ["es2015"],
    "target": "es5",
    "sourceMap": true,
    "allowJs": true,
    "outDir": "./dist",
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./*"
      ],
      "@app/*": [
        "./src/client/*"
      ],
      "@server/*": [
        "./src/server/*"
      ]
    }
  },
  "include": [
    "src/server/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

A: Here is the example I put together which is showcasing use of Typescript with Nuxt.

A: It is possible to specify custom tsconfig.json to Nuxt App. There is an option https://typescript.nuxtjs.org/guide/setup/#typecheck in nuxt.config.json which allows to point Nuxt to your tsconfig.json like this:
typescript: {
  typeCheck: {
    typescript: {
      configFile: './tsconfig.nuxt.json'
    }
  }
},

Other options https://github.com/TypeStrong/fork-ts-checker-webpack-plugin#typescript-options


text:
Q: In Mass Effect When You Save Either Ashley or Kaiden I know you have to save either Ashley or Kaiden in Mass Effect but I'm not sure if they appear in 2 or 3. I'm just wondering, really.

A: Do either of them appear in Mass Effect 2 and / or 3 depending on who you save in Mass Effect 1
Yes
The impact of either choice is felt through the franchise, in one way or another but that's true for most decision points in the series. Remember that the game is written in a way that nothing is ever free.

A: Yes. If you import your previous save, then whichever one's life you save will appear in Mass Effect 2.
If they then survive Mass Effect 2, and you then import your save to Mass Effect 3, they will appear in that game as well.
They may be a romance option as well, depending on your character's sex and decisions.
This means you could potentially have a continuing romance with a single character throughout the whole series, making this one of the more significant choices in the series.

A: Assuming you will import your game save between chapters, the survivor will briefly appear on ME2 and will be a major NPC in ME3.


text:
Q: Клик по чекбоксу внутри div Подскажите, столкнулся со следующей проблемой, есть такая штука на HTML:

$('.check_group').click(function () {
    var check = $(this).children('input')[0];
    check.checked = !check.checked;
    alert(check.checked);
    //Дальше собираюсь убирать/показывать все чекбоксы в соседних div
});

  <input type="checkbox" />
  - Выбрать все

Так вот, при клике на checkbox - меняется состояние чекбокса, а потом срабатывает jQuery и состояние меняется обратно.
Как сделать так чтобы при клике по диву/чекбоксу - менялся чекбокс и появлялся алерт о том что что-то произошло.

A: Во первых - зачем именно так? Можно же добавить label и стилизовать нужным образом.
Во вторых - повесть обработчик на check_group input[type=checkbox] и отменять пересылку события выше по DOM-у. ЕМНИП, prevendDefault

A: Нашел временное решение проблемы:

$('.check_group').click(function (e) {
    var check = $(this).children('input')[0];
    if (e.target.tagName == "INPUT") {
         check.checked = !check.checked;
    }
    check.checked = !check.checked;
    alert(check.checked);
    //Дальше собираюсь убирать/показывать все чекбоксы в соседних div
});

  <input type="checkbox" />
  - Выбрать все

Но очень буду рад другим примерам без использования "target" (я знаю что в данном случае его можно сделать более "человеческим" но мне пока не подходит)


text:
Q: Swift: Contact delegates not working? Im creating a simple game that involves collision detection and using a tutorial as a guide. Ive copied the code almost verbatim (changing constant names, etc) and have set it so that when two objects collide, one should disappear and the game over screen should pop up(have yet to write code for that, but you get it).
When I run the project, I have absolutely no errors, yet my sprite just moves over the obstacle without doing what it should. Was wondering if anyone could help me figure this out.
Edit: My code--
}
func obstaclePhysics() {
    let obstacle = SKSpriteNode(imageNamed: "fruit_strawberry_100")
    obstacle.physicsBody = SKPhysicsBody(circleOfRadius: obstacle.size.width / 4)
    obstacle.physicsBody?.dynamic = false
    obstacle.physicsBody?.affectedByGravity = false
    obstacle.physicsBody?.allowsRotation = false
    obstacle.physicsBody?.categoryBitMask = BodyType.obstacle.rawValue
    obstacle.physicsBody?.contactTestBitMask = BodyType.player.rawValue
    obstacle.physicsBody?.collisionBitMask = 0

}
}

func didBeginContact(contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask |             contact.bodyB.categoryBitMask
switch(contactMask) {
case BodyType.player.rawValue | BodyType.obstacle.rawValue:
    let secondNode = contact.bodyB.node
    secondNode?.removeFromParent()
    let firstNode = contact.bodyA.node
    firstNode?.removeFromParent()
default:
    return
}

}


text:
Q: JAVA : how to extract youtube URL from facebook.com/l.php?u= I m developing an Android app ,
and , in this step , I want to feed a database with a "Facebook user youtube video request",
when a user click in a Youtube video from facebook , an intent catch the URL , but i found that URL is like that :
https://m.facebook.com/l.php?u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD148dv1G3E4&h=KAQGHuQwG&s=1&enc=AZNGSlqUPqFIDzzjZHddvdQlAkwGkAHJy7YxLMEX7Bfi7-1PE97FOtxHPq73XJ_mKf_Dh50D_YHBxrIiIJ1HnWCbesQO4f19EVtaV-ovXqHnXw
For this original one :
https://www.youtube.com/watch?v=D148dv1G3E4
How can I transform with JAVA (regex or other tool) the facebook.com/l.php?u= URL to the www.youtube.com/watch?v= one ?
Thanks

A: In this simple example, you could to something like this:

String oldUrl = "https://m.facebook.com/l.php?u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD148dv1G3E4&h=KAQGHuQwG&s=1&enc=AZNGSlqUPqFIDzzjZHddvdQlAkwGkAHJy7YxLMEX7Bfi7-1PE97FOtxHPq73XJ_mKf_Dh50D_YHBxrIiIJ1HnWCbesQO4f19EVtaV-ovXqHnXw";
String newUrl;
List args= URLEncodedUtils.parse(oldUrl , Charset.defaultCharset());
for (NameValuePair arg:args) {
    if (arg.getName().equals("u")) {
        newUrl = URLDecoder.decode(arg.getValue(), "UTF-8");
    }
}

First, get the encoded youtube url, then decode it and store it in newUrl.


text:
Q: Center of Odd Dihedral Group So I'm trying to prove the center of $D_n$ only has the identity for odd $n$ greater than or equal to 3. I know that since $D_n$ for $n$ greater than 2 is non-Abelian, the flips and the rotations do not commute in general. Additionally, I know that the only other element that can commute with every element (rotation by 180 degrees) is not going to be in an odd dihedral group- I just have a hard time saying why it holds. My question is how do I formalize this, going forward?
Edit: My question is different from the other that was pointed out, as I'm proving the center is trivial whereas the other question is an if and only if regarding an element in the center.

A: In a dihedral group with $2n$ elements, there is a cyclic subgroup of order $n$ such that all of its elements are conjugate (within the dihedral group) to their inverses.
If an element $x$ of the cyclic group of order $n$ is central in the dihedral group, then it can only be conjugate to itself. Hence the only elements in the cyclic subgroup which are in the center of the dihedral group are equal to their inverses. So we must have $x = x^{-1}$ for all such $x$. Hence, when $n$ is odd we must have $x = 1$ for any such $x$ , as a group of odd order contains no element of order $2$.
When $n$ is odd, the only element in a cyclic group of order $n$ which is its own inverse is the identity.

A: Suppose we define the dihedral group $D_{2n} = \{ r,s | s^2 = e, r^n = e \}$. The definition of the center of a group G is $Z(G) = \{zg = gz | g\in G\}$. Also, $r^is = sr^{-i}$, for $0\leq i\leq n$. An element $z$ is in the center iff it commutes with both $r,s$. So the element $z=r^i s^k\in Z(D_{2n})$ given $zr=rz$ and $zs=sz$. This is the same as $r^i s^k r=r^{i+1} s^{k}$. This reduces to $s^kr=rs^k$ by left multiplication by $r^i$. $k$ is modulo 2, so we can have $k=0$ or $k=1$. If $k=0$ then this is fine. But now, consider $k=1$. Then $rs=sr$ but $D_{2n}$ is non-commutative for $n\geq 3$. Then we require that $k=0$ and $z=r^i\in Z(D_{2n})$. Using our second condition, $zs=sz=r^is=sr^i$. But $r^is = sr^{-i} = sr^i$, so $sr^{-i} = sr^i$. Left multiplying by $s$, and right multiplying by $r^i$, we obtain $s(sr^i)r^i = s(sr^{-i})r^i = e = r^{2i}$ by that $s^2=e$. Then $n|2i$. Since $n$ is odd and $0\leq i < n$, then $i=0$. Recall that $z=r^i\in Z(D_{2n})$. Then $z=r^0=e\in Z(D_{2n})$ for any element $z\in Z(D_{2n})$. Then $\{e\} = Z(D_{2n})$.


text:
Q: Why do we need a 4th constructor for Lollipop? I started a project targeting Android Lollipop (21), and created a custom view. When I generated constructors for the view, I got a new 4th constructor which takes more params than the others.
public class FooView extends FrameLayout {
  public FooView(Context context) {
    super(context);
  }

  public FooView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public FooView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  // This 4th constructor
  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  public FooView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
  }
}

My question is, why do we need it? What would happen if I remove this constructor and run the app on Lollipop?

A: Information from official doc

public View (Context context, AttributeSet attrs, int defStyleAttr,
  int defStyleRes)
Added in API level 21
Perform inflation from XML and apply a class-specific base style from
  a theme attribute or style resource. This constructor of View allows
  subclasses to use their own base style when they are inflating.
When determining the final value of a particular attribute, there are
  four inputs that come into play:

*

*Any attribute values in the given AttributeSet.

*The style resource specified in the AttributeSet (named "style").

*The default style specified by defStyleAttr.

*The default style specified by defStyleRes.

*The base values in this theme.

  Each of these inputs is considered in-order, with the first listed
  taking precedence over the following ones. In other words, if in the
  AttributeSet you have supplied  , then
  the button's text will always be black, regardless of what is
  specified in any of the styles.
Parameters

*

*context The Context the view is running in, through which it can access the current theme, resources, etc.

*attrs   The attributes of the XML tag that is inflating the view.

*defStyleAttr    An attribute in the current theme that contains a reference to a style resource that supplies default values for the
  view. Can be 0 to not look for defaults.

*defStyleRes A resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not
  be found in the theme. Can be 0 to not look for defaults.


text:
Q: JQuery: How do you change a graphic on a mouse hover event? Using JQuery, how do I change a map icon whenever I mouse hover over a row in an HTML table/div?
Here is an example:
http://www.sfsunriseidx.com/homes/94131/?uuid=9ed7269b-5327-4c88-ba15-f700ed343d69&source=REDIR
Notice when you mouse hover over a home listing on the left, the corresponding map icon on the right changes.
Question: how do I emulate this functionality using JQuery?

Update: It was suggested below that an ID linked the two elements. If that is the case, how would you still accomplish this?

A: Use the for="" attribute in html, like
Hover Link

On the image:

jQuery, using the hover function to animate the corresponding ID, the same one in the for:
$(".mapHover").hover(function() {
  $("#" + $(this).attr('for')).animate({"left": "-=50px"}, "slow");
}, function() {
  $("#" + $(this).attr('for')).animate({"right": "+=50px"}, "slow");
});

A: Probably both elements are linked by a ID..

A: Something like this:
$(document).ready(function() {
    var googleMap = $("#googleMaps");

    $('a', '#mapLinks').hover(function() {
        var index = $(this).index(this);
        $('img:eq(' + index + ')', googleMap).animate({
            width: '+=10%'
        });
    }, function() {
        var index = $(this).index(this);
        $('img:eq(' + index + ')', googleMap).animate({
            width: '-=10%'
        });
    });
});

Just make sure you change the "#googleMaps" and "#mapLinks" thing :)


text:
Q: How to do a "if... then, but also if.... then but if neither do...." I have made a simple application to play the game FizzBuzz in c++, although this isn't necessarily a c++ question, what is the best way to make an if statement so it does the following:
if(x) then: a,
if(y) then: b,
if(x) and if(y) then: a and b,
if neither then:
this is my current approach:
#include <iostream>
using namespace std;

int main ()
{
    int factor1 = 7;
    int factor2 = 15;
    bool found = false;
    string factor1_word = "Fizz";
    string factor2_word = "Buzz";
    int n = 1000;
    for (int i = 1; i < n+1; i++)
    {
        if (i % factor1 == 0)
        {
            cout << factor1_word;
            found = true;
        }
        if (i % factor2 == 0)
        {
            cout << factor2_word;
            found = true;
        }
        if (found == 0)
        {
            cout << i;
        }
        cout << endl;
        found = false;
    }
    return 0;
}

which works but I feel like it isn't the most readable nor the best way to do it.
Any advice would be great, thanks.

A: You want to achieve this "if(x) then: a, if(y) then: b, if(x) and if(y) then: a and b, if neither then:". Obviously you imply however, that you do NOT want the "a"-reaction in case of "x & y" on top of the reaction specifically for that case; and that you generally only want one reaction.
That is all, code it exactly like that.
if     (x && !y)  { a(); }
else if(y && !x)  { b(); }
else if(x &&  y)  {a(); b(); /* or maybe a_and_b() to make sense */}
else {/* nothing */}

The  && ! implement the "but not if ...". Note the logical AND operator && instead of the bit-operator & (which I got wrong initially, more or less a typo), which onyl by chance gets the desired behaviour in some cases.
The  elses make the "always only one".
The last else {}, without an if turns the "do nothing for 'neither x nor y'" into
"do nothing for any case not explicitly covered". That is a practice I recommend, to always code the "everything else" explicitly, for a chance to notice when you did not actually all possible cases.
For getting all the (in this case of two binary inputs four) cases cleanly sorted out, read up on Karnaugh Veitch diagrams ( https://en.wikipedia.org/wiki/Karnaugh_map )and the corresponding logic optimisations.

A: for (int i = 0; i < n; ++i)
always start from zero since 0 is the the starting index in most data structures like arrays or vector, and try to keep your code simple and easy to read, the way u did is most efficient way to do it because the runtime efficiency of that for loop is going to be of order o(n) whatever the case maybe
you can use (!found) instead of (found==0)

A: for (int i = 0; i < n; ++i)
always start from zero since 0 is the the starting index in most data structures like arrays or vector, and try to keep your code simple and easy to read, the way u did is most efficient way to do it because the runtime efficiency of that for loop is going to be of order o(n) whatever the case maybe
you can use (!found) instead of (found==0)


text:
Q: Javascript error during validation I want to validate the form when submit button clicked . Here in this case form is submitting if validation returns error.I dont know much about js. Any help is appreciable.

var check = function() {
  if (document.getElementById('password').value ==
    document.getElementById('confirm_password').value) {
    document.getElementById('message').style.color = 'green';
    document.getElementById('message').innerHTML = 'matching';
  } else {
    document.getElementById('message').style.color = 'red';
    document.getElementById('message').innerHTML = 'not matching';
  }
}
<form action="<?php echo site_url().'/login_controller/registration' ?>" role="form" enctype="multipart/form-data" onsubmit='check();' method="POST">

    Password
    <input type="password" class="form-control" placeholder="Password" id="password" name="psw" required>

    Repeat Password
    <input type="password" class="form-control" placeholder="Repeat Password" id="confirm_password" name="rpsw" required>

    <input type="submit" class="btn btn-primary" name="submit" value="save">

</form>

A: You need to return true or false from the check() function to indicate whether to proceed or prevent the form submission.
Here's the updated check() function.

var check = function() {
      if (document.getElementById('password').value ==
          document.getElementById('confirm_password').value) {
          document.getElementById('message').style.color = 'green';
          document.getElementById('message').innerHTML = 'matching';
          return true;
      } else {
          document.getElementById('message').style.color = 'red';
          document.getElementById('message').innerHTML = 'not matching';
          return false;
      }
  }
<form action="<?php echo site_url().'/login_controller/registration' ?>" role="form" enctype="multipart/form-data" onsubmit='return check();' method="POST">

    Password
    <input type="password" class="form-control" placeholder="Password" id="password" name="psw" required>

    Repeat Password
    <input type="password" class="form-control" placeholder="Repeat Password" id="confirm_password" name="rpsw" required>

    <input type="submit" class="btn btn-primary" name="submit" value="save">

</form>

Here's additional update in the html.
Replace onsubmit='check();' with onsubmit='return check();' in the form opening tag.

A: Use e.preventDefault(); when password not matched.

$('form').submit(function(e){

  if (document.getElementById('password').value ==
    document.getElementById('confirm_password').value) {
    document.getElementById('message').style.color = 'green';
    document.getElementById('message').innerHTML = 'matching';
  } else {
    document.getElementById('message').style.color = 'red';
    document.getElementById('message').innerHTML = 'not matching';
    e.preventDefault();
  }

});

<form action="" role="form" enctype="multipart/form-data" method="POST">

    Password
    <input type="password" class="form-control" placeholder="Password" id="password" name="psw" required>

    Repeat Password
    <input type="password" class="form-control" placeholder="Repeat Password" id="confirm_password" name="rpsw" required>

    <input type="submit" class="btn btn-primary" name="submit" value="save">

</form>

A: *

*Never call anything submit in a form, it hides the submit event handler

*You need to use onsubmit="return check()" and then

*return false from the function.

var check = function() {
  if (document.getElementById('password').value ==
      document.getElementById('confirm_password').value) {
      document.getElementById('message').style.color = 'green';
      document.getElementById('message').innerHTML = 'matching';
      return true;
  }
  // no need for else after a return:
  document.getElementById('message').style.color = 'red';
  document.getElementById('message').innerHTML = 'not matching';
  return false;
}

It is generally better to use unobtrusive coding, so give your form an ID and try
window.onload=function() {
  document.getElementById("myForm").onsubmit=function() {
    if (document.getElementById('password').value ==
      document.getElementById('confirm_password').value) {
      document.getElementById('message').style.color = 'green';
      document.getElementById('message').innerHTML = 'matching';
      return true;
    }
    // no need for else after a return:
    document.getElementById('message').style.color = 'red';
    document.getElementById('message').innerHTML = 'not matching';
    return false;
  }
}

A: For form validations, its better using Jquery validation plugin. It is very simple and needs Jquery library included in it. Try this https://jqueryvalidation.org/. Please refer this js fiddle also https://jsfiddle.net/jfc62uof/6/
    <form action="javascript:void(0)" id="myform" role="form" enctype="multipart/form-data" method="POST">

        Password
        <input type="password" class="form-control" placeholder="Password" name="psw" id="psw">

        Repeat Password
        <input type="password" class="form-control" placeholder="Repeat Password" name="rpsw">

        <input type="submit" class="btn btn-primary" name="submit" value="save">

    </form>

A: Modify your script like following:
var check = function() {

  var error_flag = true;

  if (document.getElementById('password').value == document.getElementById('confirm_password').value) {
      document.getElementById('message').style.color = 'green';
      document.getElementById('message').innerHTML = 'matching';
      error_flag = true;
  } else {
      document.getElementById('message').style.color = 'red';
      document.getElementById('message').innerHTML = 'not matching';
      error_flag = false;
  }

  return error_flag
}

Also little bit adjustment here: onsubmit='return check();'
<form action="<?php echo site_url().'/login_controller/registration' ?>" role="form" enctype="multipart/form-data" onsubmit='return check();' method="POST">


text:
Q: Smooth animation in keyboardWillShow doesn't work with UITextView Solution which worked for me
After struggling for days I finally manage to find the fix for view animation issue. For me keyboardWillChangeFrameNotification worked. The solution is discussed in the following thread:
Move textfield when keyboard appears swift

I've a bunch of views embedded inside stack view along with text view. I've given text view height of <= 120. In keyboardWillShow view doesn't animate despite adding code as required. I've played with duration value but it's all same result. I was wondering if it's due to text view? How to fix it?
@objc func keyboardWillShow(notification:NSNotification) {

    guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }

    let keyboardScreenEndFrame = keyboardValue.cgRectValue
    let keyboardFrame = view.convert(keyboardScreenEndFrame, from: view.window)

    if #available(iOS 11.0, *) {
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height - view.safeAreaInsets.bottom, right: 0)
    } else {
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height, right: 0)
    }

    scrollView.scrollIndicatorInsets = scrollView.contentInset

    let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height + keyboardFrame.height - scrollView.bounds.size.height)
    scrollView.setContentOffset(bottomOffset, animated: true)

    UIView.animate(withDuration: 0.5, animations: { () -> Void in
        self.view.layoutIfNeeded()
    })
}

===
   extension FirstViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {

        let estimatedSize = textView.sizeThatFits(textView.frame.size)

        if estimatedSize.height > textViewMaxHeight {
            if estimatedSize.height - textViewMaxHeight < textView.font!.lineHeight && !didExpandTextView {

                didExpandTextView = true

                var contentInset:UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: self.savedKbHeight, right: 0.0)

                if let v = self.tabBarController?.tabBar {
                    contentInset.bottom -= v.frame.height
                }

                scrollView.contentInset = contentInset
                scrollView.scrollIndicatorInsets = contentInset

                if textView.isFirstResponder {
                    let fr = textView.frame
                    scrollView.scrollRectToVisible(fr, animated: false)
                }
            }

            textView.isScrollEnabled = true
            textView.showsVerticalScrollIndicator = true

        } else {
            if let lineHeight = textView.font?.lineHeight, Int(estimatedSize.height / lineHeight) != numberOfLines {
                numberOfLines = Int(estimatedSize.height / textView.font!.lineHeight)

                var contentInset:UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: self.savedKbHeight, right: 0.0)

                print("contentInset: \(contentInset)")
                scrollView.contentInset = contentInset
                scrollView.scrollIndicatorInsets = contentInset

                if textView.isFirstResponder {
                    let fr = textView.frame
                    scrollView.scrollRectToVisible(fr, animated: false)
                }

                didExpandTextView = false
            }

            textView.isScrollEnabled = false
        }
    }

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

A: Try this approach:
    func textViewDidChange(_ textView: UITextView) {

        let estimatedSize = textView.sizeThatFits(textView.frame.size)

        textView.isScrollEnabled = estimatedSize.height > textViewMaxHeight

        if !textView.isScrollEnabled {
            let maxBottom = self.view.frame.height - self.savedKbHeight

            // Use following line if you have Extended Edges set
            // let maxBottom = self.view.frame.height - self.savedKbHeight - topLayoutGuide.length - bottomLayoutGuide.length

            var r = self.textView.frame
            r.size.height = estimatedSize.height
            let tvBottom = self.scrollView.convert(r, to: self.view).maxX
            if tvBottom > maxBottom {
                self.scrollView.scrollRectToVisible(r, animated: true)
            }
        }
    }

Edit Note: This is not intended to be Production Ready code. There are many things that affect layout / positioning, and there is no guarantee that just "dropping this in" will work in all situations.


text:
Q: Using RewriteCond to match only a page or a directory having the same name I am trying to do a redirect of a file and folder using .htaccess. I want to add a RewriteCond directive before the RewriteRule to match only example.com/place/sta-ana.html and example.com/place/sta-ana directory. I tried this:
RewriteCond %{REQUEST_URI} ^place/sta-ana(\.html|/.*)?
RewriteRule ^place/sta-ana(\.html|/.*)? /place/santa-ana$1 [L,NC,R=301]

and this:
RewriteCond %{THE_REQUEST} ^place/sta-ana(\.html|/.*)?
RewriteRule ^place/sta-ana(\.html|/.*)? /place/santa-ana$1 [L,NC,R=301]

but both only work for redirecting place/sta-ana.html and not the directory and its files like place/sta-ana/santiago.html and place/sta-ana/santiago/lourdes.html. How can I get the code(s) above to also redirect the sta-ana directory to the santa-ana folder:
example.com/place/sta-ana.html => example.com/place/santa-ana.html
example.com/place/sta-ana/santiago.html => example.com/place/santa-ana/santiago.html
example.com/place/sta-ana/santiago/lourdes.html => example.com/place/santa-ana/santiago/lourdes.html

A: Looks like you don't need a RewriteCond. Just this rule will do the job:
RewriteRule ^place/sta-ana(\.html|/.*)$ /place/santa-ana$1 [L,NC,R=301,NE]

Make sure this is your topmost rule and you must clear your browser cache completely before testing this change.


text:
Q: Empty textbox on mousclick in combination with language change in WPF I have a textbox with a default text. When I focus the textbox it is cleared so I can write, and if I unfocus without writing anything the default text reappears.
I also have two radiobuttons for selecting the language. The languages are provided as xaml resourcefiles and the default text in the textbox is connected to that using DynamicResource.
My problem is that the language change only work as long as I haven't focused the textbox. If I focus the textbox and then unfocus it without changing anything, the textbox no longer changes language.
I'm guessing that is because once it's changed (cleared) it's no longer linked to the dynamic resource, because WPF considers my onfocus changes as user input, but I can't figure out how to get around that and make it change language even if I've clicked the textbox.
The second textbox don't have any focus behaviour and in that one the language change works as it should, i.e. it changes the language as long as I haven't actually written something.
MainWindow xaml:
<Window x:Class="Textbox_langauge_buggseek.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Textbox_langauge_buggseek"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox x:Name="TextBox" HorizontalAlignment="Left" Height="46" Margin="84,55,0,0" TextWrapping="Wrap" Text="{DynamicResource ResourceKey=TB}" VerticalAlignment="Top" Width="334" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
    <TextBox x:Name="TextBox_Copy" HorizontalAlignment="Left" Height="46" Margin="84,123,0,0" TextWrapping="Wrap" Text="{DynamicResource ResourceKey=TB}" VerticalAlignment="Top" Width="334"/>
    <RadioButton x:Name="En" Content="En" GroupName="Lang" HorizontalAlignment="Left" Margin="391,216,0,0" VerticalAlignment="Top" Checked="En_Checked" IsChecked="True"/>
    <RadioButton x:Name="Se" Content="Se" GroupName="Lang" HorizontalAlignment="Left" Margin="391,234,0,0" VerticalAlignment="Top" Checked="Se_Checked"/>

</Grid>
</Window>

MainWindows cs:
using System;
using System.Windows;
using System.Windows.Controls;

namespace Textbox_langauge_buggseek
{
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        SetLanguageDictionary();
    }

    //*****************************************************************************************

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox box = sender as TextBox;
        box.Text = box.Text == (string)this.Resources["TB"] ? string.Empty : box.Text;
    }

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        TextBox box = sender as TextBox;
        box.Text = box.Text == string.Empty ? (string)this.Resources["TB"] : box.Text;
    }

    //*****************************************************************************************

    private void En_Checked(object sender, RoutedEventArgs e)
    {
        SetLanguageDictionary("En");
    }

    private void Se_Checked(object sender, RoutedEventArgs e)
    {
        SetLanguageDictionary("Se");
    }

    //*****************************************************************************************

    private void SetLanguageDictionary(string language = "En")
    {
        ResourceDictionary dict = new ResourceDictionary();
        switch (language)
        {
            case "Se":
                dict.Source = new Uri("..\\Resources\\Se.xaml", UriKind.Relative);
                break;
            default:
                dict.Source = new Uri("..\\Resources\\En.xaml", UriKind.Relative);
                break;
        }
        this.Resources.MergedDictionaries.Add(dict);
    }
}
}

En language xaml:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:system="clr-namespace:System;assembly=mscorlib">

<system:String x:Key="TB">Text in the TextBox!</system:String>

</ResourceDictionary>

Se language xaml:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:system="clr-namespace:System;assembly=mscorlib">

<system:String x:Key="TB">Text i textrutan!</system:String>

</ResourceDictionary>

A: Yes, when you set TextBox.Text in codebehind, the text does not know anymore that it has to take a value from the Rersource. To avoid it you can change the text using pure XAML, with Triggers.
Remove TextBox's event handlers and add a style like this:
    <TextBox x:Name="TextBox"  HorizontalAlignment="Left" Height="46" Margin="84,55,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="334">
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <Trigger Property="IsFocused" Value="true">
                        <Setter Property="Text" Value="" />
                    </Trigger>
                    <Trigger Property="IsFocused" Value="false">
                        <Setter Property="Text" Value="{DynamicResource ResourceKey=TB}" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>


text:
Q: Android app crashed on Samsung devices after change of font style I have a problem with an application when I tried to change the device's font (Samsung Galaxy Tab3), that being that my application crashes. In this case, the application is running in the background when I make the font change.
Steps:

*

*Launch the app

*Open device settings using status bar

*Change device's font style

*Return to the app using recent apps

*Crash

I tried to test this scenario on other devices and can't reproduce it. My app crashed only on the Samsung device and only when the system font style changes.
Attached the log crash:
07-22 12:26:09.359: E/AndroidRuntime(8110): FATAL EXCEPTION: main
07-22 12:26:09.359: E/AndroidRuntime(8110): java.lang.NullPointerException
07-22 12:26:09.359: E/AndroidRuntime(8110):     at com.acs.nomad.app.widget.h.a(Unknown Source)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at com.acs.nomad.app.b.ap.m(Unknown Source)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at com.acs.nomad.app.d.v.onPause(Unknown Source)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.app.FragmentManagerImpl.removeFragment(FragmentManager.java:1129)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.app.BackStackRecord.popFromBackStack(BackStackRecord.java:662)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1450)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.app.FragmentManagerImpl$2.run(FragmentManager.java:444)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1401)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.os.Handler.handleCallback(Handler.java:615)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.os.Looper.loop(Looper.java:137)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at android.app.ActivityThread.main(ActivityThread.java:4949)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at java.lang.reflect.Method.invokeNative(Native Method)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at java.lang.reflect.Method.invoke(Method.java:511)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
07-22 12:26:09.359: E/AndroidRuntime(8110):     at dalvik.system.NativeStart.main(Native Method)

A: Stock Android doesn't have a change device's font style
It must be a Samsung TouchWiz thing. May be, you should check out the Samsung specific SDKs.
But if I were you, I'd listen for the change in font style through a Broadcast Receiver. Find out which broadcast to listen to by using a Broadcast Monitor app from Google Play.
And then, I'd swallow the nullpointer exception and I'd restart the Activity whenever that happened. I realize this is a drastic action, but until you find out how the font style is causing the nullpointer exception, that's probably the only work around.


text:
Q: Why doesn't this excel formula work? {=SUM(IF(AND(X3:X130="WEST",AF3:AF130="Yes"),1,0))}

It is supposed to check to see how many times a given row has "WEST" in column X and "Yes" in column AF, and I know in the worksheet this happens at least 10 times but the formula always returns zero.

A: I'm afraid the construction is incorrect. You can't use logical operators in this way. For further explanation I think you might need an answer from Microsoft.
However there may be an alternative that suits:
=SUMPRODUCT((X3:X130="WEST")*(AF3:AF130="Yes"))

Note for this Enter is sufficient.


text:
Q: how to disable keyboard in next activity in android studio i had problem in keyboard . i made search activity and there i call edit text when i search for anything and by clicking that search the keyboard still activate in another activity . how can i stop it. i tried too much but i need someone help
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_activity);
    searchText = (EditText) findViewById(R.id.Search_Field);
    searchText.addTextChangedListener(this);
    resultView = (ListView) findViewById(R.id.Display_Result);
    resultView.setOnItemClickListener(this);

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(SearchActivity.this, web_activity.class);
        intent.putExtra("url", links[position]);
        startActivity(intent);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

A: try that in onItemClick before startActivity
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

A: write this in your web_activity.class onCreate method
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

i hope this will work in your case thank you

A: You can simply add this to your activity
        <activity android:name=".activities.YourSampleActivity"
        android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
        android:windowSoftInputMode="stateAlwaysHidden"
        />


text:
Q: excel formula for searching a range of cells in an another range of cells Need a formula for searching a range of cells in an another range of cells.
Please find sample data in image :

A: Use MATCH function:
B1 =IF(ISNA(MATCH(A1,C$1:C$4,0)),"No","Yes")

Copy the formula down. You can adjust C$1:C$4 as needed.
From the example shown, I am assuming you need exact matches.
But if you want to return Yes, even if the cell is not an exact match as long as the string is found in the looked up array, you can use this:
B1 =IF(ISNA(MATCH("*"&A1&"*",C:C,0)),"No","Yes")


text:
Q: I have a CGridview with a list of patients and I need a button url in the grid so that it prints the update page of the current record? I need to get the details of the patients in my CGridview when I click an icon in the grid it should print the details (which is in the update page) of the patients.
Already tried window.print() and (.class).printPage() but don't know how to implement those?

A: In you CGridView call (probably in your admin view of your patient views), add an additional button like so:
array(
    'class'=>'CButtonColumn',
    'template'=>'{printbutton}{view}{update}{delete}',
    'buttons'=>array(
        'printbutton' => array(
            'label'=>'Print',
            'imageUrl'=>Yii::app()->request->baseUrl.'/images/print_icon.png',
            'url'=>'Yii::app()->createUrl("patient/printitem", array("id"=>$data->id))',
         ),
    ),
),

You will see that this:

*

*References an image (in this example stored in *image/print_icon.png*) to be used as the icon

*References a Controller/Action URL (in this example patient/printitem) and passes it the id of the patient record that was clicked

This Controller/Action must now select the patient record, and then render a view, something like:
public function actionPrintitem(){
    $model = Patient::model()->findByPk($_REQUEST['id']);
    $this->render("printitem",array(
        "model" => $model
    ));
}

Now, in this view (which you will have to create), simply put a window.print(); to fire once the page has loaded, which will open the browser print window


text:
Q: JavaScript: How to Define a Non-Enumerable Method without using Object.defineProperty? I want to add a method to Object, but now all arrays and object have it. When I use for(.. in ..), it is enumarated and this is a problem for my software. So, I need to make my method non-enumerable.
I know there is a Object.defineProperty(), but it is not supported by old browser (which are still around) and even latest versions of Konqueror.
Is there another way to make a method non-enumerable?

A: No. That's why it's considered bad practice to use JavaScript's for..in without immediately checking for hasOwnProperty. I.e., you should always do:
for (var item in obj) {
    if (obj.hasOwnProperty(item)) {
        // ...
    }
}

Tools like JSLint will report an error in your code if you use for..in without a hasOwnProperty check.

A: For ECMAScript 3 (used in old browser), you cannot change the enumerable attribute.
If you want to filter the method, maybe you can check the type of the object in for(..in..).


text:
Q: C++ MurmurHash3 returning same value for different key I am confused with how should i call MurmurHash3_x86_128() when i have lot of key value. The murmurhash3 code can be found https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp. Method definition is given below.
void MurmurHash3_x86_128 ( const void * key, const int len,
                   uint32_t seed, void * out )

I am passing different key value using a for loop as shown below but still the hash value return is same. If i am removing for loop and passing individual key value then the value is different. What am i doing wrong ?
int main()
{
uint64_t seed = 100;
vector <string> ex;
ex.push_back("TAA");
ex.push_back("ATT");

for(int i=0; i < ex.size(); i++)
{

uint64_t hash_otpt[2]= {};

cout<< hash_otpt << "\t" << endl;
const char *key = ex[i].c_str();
cout << key << endl;
MurmurHash3_x64_128(key, strlen(key), seed, hash_otpt); // 0xb6d99cf8
cout  << hash_otpt << endl;

}

return 0;

A: The line
cout  << hash_otpt << endl;

is emitting the address of hash_otpt, not its contents.

A: It should be
cout << hash_otpt[0] << hash_otpt[1] << endl;

Basically the 128-bit hash is split and stored in two 64-bit unsigned integers (the MSBs in one and the LSBs in another). On combining them, you get the complete hash.


text:
Q: The Hawaiian language has only 12 letters: what is the probability a randomly selected 3 letter "word" The Hawaiian language has only 12 letters: the vowels a, e, i, o and u and the consonants h, k, l, m,n,p and w   what is the probability a randomly selected 3 letter "word" begins with a consonant and ends with 2 different vowels?
I did
$$\left(\frac 7{12}\right)\left(\frac 5{11}\right)\left(\frac 4{11}\right)= \frac {140}{1320}$$
did I make this too simple? I keep doubting everything I am doing!

A: Your answer would be correct if you were making selections of letters "without replacement" -- e.g., if you wrote each letter on a card, shuffled the cards, and then dealt out three of them in order.  But this isn't how random words are usually thought of, as evidenced in the constraint that the word end in two different vowels.  For the problem with replacement, the denominators on the left should all be $12$, for an answer of $(7/12)(5/12)(4/12)=140/1728=35/432$.

A: Let's first look at the total possible combinations. This is 12^3, as every space in the word can be one of 12 letters. Now we calculate the quantity of words that start with a consonant and end with two [edit: different] vowels. This is 7 * 5 * 4. So the answer would be
$$
(7 * 5 * 4) / (12^3) = 140/1728 = 0.081.
$$
---
Another interesting case aside from your problem arises if we have a pool of letters where we cannot use members of the pool twice, and there are repeats of certain letters. For example, for "abb", our combinations would be:
abb, bab, bba. We always divide our final answer by the number of repeats of each letter. Thus our calculation would be 3 * 2 * 1 / 2.
So if we had to rearrange "abbccc", we make our normal calculation 6 * 5 * 4... = 720, and then divide this by repeats of a (1), repeats of b (2), and repeats of c (3), to find 720/ (1 * 2 * 3) = 120.

A: Each letter in the 3-letter word may be any of the twelve alphabets. So, the total number of cases are $n=12^3=1728$. Thus, the words aaa and hhh are also in the sample space $\Omega$.
There are 7 consonants, so there are 7 ways to choose the first letter. There are 5 vowels, so there are 5 ways to choose the second and 4 ways to choose the third letter (since the vowels shouldn't be repeated). The number of cases favorable to the event are, therefore, $m=7\times5\times4=140$.
$P(A)=\frac{m}{n}=\frac{140}{1728}$


text:
Q: How can I make my dynamically sized lightboxes overflow/scroll correctly? I'm sure I'm doing something obvious wrong, but I haven't been able to figure it out. My lightboxes size dynamically (percentage width), and I want the content within the lightboxes to scroll vertically as needed on smaller screens without displacing the border (actually a box-shadow) around the content.
As an added caveat, I need the "container" div to have dynamic height. When I set the container div to height: 100%, the lightbox functions like I want (see code below), but when I remove the height setting, the overflow no longer works right.
This demo of my lightboxes in action should help clarify my question:
http://viewer.zmags.com/publication/a82492b9?viewType=pubPreview
Here's my CSS:
html{
height: 100%;}

body {
font-family: Verdana, sans-serif;
font-weight: 400;
font-size: 12pt;
color: #FFFFFF;
padding: 0px;
margin: 0px;
background: #FF0000;
height: 100%;
overflow: hidden;}

div.container {
background-color: #6d6d6d;
padding: 20px;
height: 100%;
overflow: hidden;}

div.content {
background-color: #6d6d6d;
overflow: auto;
max-height: 100%;
margin: 0px auto;}

div#tab1 {
box-shadow: 0 0 0 1px #FFFFFF inset, 0 0 0 4px #be854C inset;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;}

And my HTML:

Lightbox content here.

A: If your browser support requirements allow it, consider absolutely positioning your .container div, and setting its top, left, etc appropriately:
div.container {
  background-color: #6d6d6d;
  padding: 20px;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

That has some downsides if you're trying to position other elements on the page, but for a lightbox, it's a reasonable solution.


text:
Q: Javascript random color change I am trying to select random divs and change background-color. Only 8 items should be visible at a time, If there are more colors in array, it shows randomly.
Sometimes same div repeats. How can I make it more random?

var c = ["123abc", "12abc3", "abc123", "1dcb23", "1876c3", "a34523", "165423", "1dcb23", "E53E3E", "7B341E", "D69E2E", "48BB78", "38B2AC", "ED64A6"];
var sub;
var shuffled;
var l = document.getElementsByClassName('item');
function disp(){
  var i = 0;
  var s = setInterval(function(){
    var ran = Math.floor(Math.random() * l.length);
    l[ran].style.backgroundColor = '#' + sub[i];
    var opacity = 0;
    function MyFadeFunction() {
     if (opacity<1) {
        opacity += .1;
        setTimeout(function(){MyFadeFunction()},50);
     }
     l[ran].style.opacity = opacity;
    }
    MyFadeFunction();
    i++;
    if(i == sub.length){
      i = 0;
      clearTimeout(s);
      shufflearray();
    }
  }, 1500);
}
function shufflearray(){
  var a = [];
  shuffled = c.sort(() => Math.random() - 0.5);
  sub = shuffled.slice(8, shuffled.length - 1);
  disp();
}
shufflearray();
.item{
  width: 50px; height: 50px; float: left; margin: 10px;
}

Codepen - https://codepen.io/felixaj/pen/LYNZbZY

A: It sounds like you want every .item element to have a random background color, but you don't want the colors to repeat unless you've run out of colors to pick from. To accomplish this, all you need to do is shuffle the colors array and apply the colors in their shuffled order to each div. When you run out of shuffled colors, refill them. It's very simple to do this with rando.js' randoSequence function (which is cryptographically secure), or you can use this post to do the shuffling yourself.

var colors = ["#123abc", "#12abc3", "#abc123", "#1dcb23", "#1876c3", "#a34523", "#165423", "#1dcb23", "#E53E3E", "#7B341E", "#D69E2E", "#48BB78", "#38B2AC", "#ED64A6"];
var shuffledColors = [];

for(var i = 0; i < document.getElementsByClassName("item").length; i++){
  //refill shuffledColors with shuffled info from the colors variable if empty
  shuffledColors = shuffledColors.length ? shuffledColors : randoSequence(colors);

  //grab the next value from shuffledColors and apply it to the next div
  document.getElementsByClassName("item")[i].style.backgroundColor = shuffledColors.pop().value;
}
.item {
  height: 20px;
}

This line is what allows you to use rando.js in your javascript, so don't forget to put this in the head of your HTML document if you want to use the randoSequence function:

Just for fun...
It's not the easiest to read, but this js can actually be written in two lines, which is kind of fun:
var colors = ["#123abc", "#12abc3", "#abc123", "#1dcb23", "#1876c3", "#a34523", "#165423", "#1dcb23", "#E53E3E", "#7B341E", "#D69E2E", "#48BB78", "#38B2AC", "#ED64A6"], shuffledColors = [];
for(var i = 0; i < document.getElementsByClassName("item").length; i++) document.getElementsByClassName("item")[i].style.backgroundColor = (shuffledColors = shuffledColors.length ? shuffledColors : randoSequence(colors)).pop().value;

A: To never repeat animating a div (or a color) until all divs in the 'set' have been animated, you can splice a random element out of a copy of a subset (set) of your main color array untill there are no more items and then at that point create another subset (set) array from your main colors and reapeat the process. I added a console log in the below snippet to show a little more about what is happening.
NOTE:
As for fading visual elements via javascript, the snippet will get buggy if you leave the page because it should use a webworker (or css) to do the fading so the timer is not throttled when the page is hidden which throws off the animation.

const tileTotal = 8;
let colors = ["123abc", "12abc3", "abc123", "1dcb23", "1876c3", "a34523", "165423", "1dcb23", "E53E3E", "7B341E", "D69E2E", "48BB78", "38B2AC", "ED64A6"];
let startingColors = colors.slice(0, tileTotal);
const tiles = document.getElementById('tiles');
let tile;
startingColors.forEach(color => {
  tile = document.createElement('div');
  tile.classList.add('tile');
  tile.style.backgroundColor = '#' + color;
  tiles.appendChild(tile);
});

const randomize = (amt) => {
  const allRandomColors = colors.sort(() => Math.random() - 0.5);
  return allRandomColors.slice(0, amt);
}

let randColorsOrig = randomize(tileTotal);
let randColors = Array.from(randColorsOrig);
let count = 0;
let fadeInterval;
function colorize() {
  let randLoc = Math.floor(Math.random() * randColors.length)
  let color = randColors.splice(randLoc, 1)[0];
  let index = randColorsOrig.indexOf(color);

  fadeInterval = setInterval(fade.bind(null, index, color), 50);
  ++count;

  console.log(`fading color ${'#' + color} at tile index ${index}`)

  if (count == tileTotal) {
    clearTimeout(fadeInterval)
    console.log('resetting colors and indices')
    count = 0;
    randColorsOrig = randomize(tileTotal);
    randColors = Array.from(randColorsOrig);
  }
}

let opacity = 0;
function fade(index, color) {
  tiles.childNodes[index].style.opacity = opacity;
  tiles.childNodes[index].style.backgroundColor = '#' + color
  opacity < 1 ? (opacity += .1) : (opacity = 0, clearInterval(fadeInterval));
}

setInterval(colorize, 1500);
#tiles {
  display: flex;
}

.tile {
  width: 6rem;
  height: 6rem;
  margin-top: 1rem;
  margin-right: 1rem;
}

A: An alternative is to create two arrays for colors, where one would have the first 8 colors and in the same order as each div, the second would have the new colors that would be added randomly.
Example:

var c1 = ["123abc", "12abc3", "abc123", "1dcb23", '12098c', "1876c3", "a34523", "165423"];
//
var c2 = ["E53E3E", "7B341E", "D69E2E", "48BB78", "38B2AC", "ED64A6"]

var l = document.getElementsByClassName('item');

function callme() {
   let rand1 = Math.floor(Math.random() * l.length)
   let rand2 = Math.floor(Math.random() * c2.length)

  l[rand1].style.backgroundColor = '#' + c2[rand2]

  let c3 = c1[rand1]
  c1[rand1] = c2[rand2]
  c2[rand2] = c3

}
setInterval(callme, 1500)
.item{
  width: 50px; height: 50px; float: left; margin: 10px;
  color: white;
}

I reduced the code to make the idea clear


text:
Q: Why does $q(t) \to-i\hbar \frac{\delta}{\delta J(t) }$ for the generating functional of a perturbed harmonic oscillator? When computing a generating functional, $Z[J]$, in terms of the generating functional of Green functions, $Z[0]$, in my lecturer's notes we reach the following terms:
$$Z[J]= \mathcal{N} \int Dq \hspace{1mm}\text{exp} \left( \frac{-i}{\hbar} \int dt V(q(t))\right)\text{exp}\left(\frac{i}{\hbar} \int ds \hspace{1mm} L_0 (q(t), \dot{q}(t)) + J(s) q(s)\right)\tag{1}$$
$$Z[J]= \mathcal{N} \int Dq \hspace{1mm}\text{exp} \left( \frac{-i}{\hbar} \int dt V\left(-i\hbar\frac{\delta}{\delta J(t) }\right)\right)\text{exp}(...)\tag{2}$$
Can anyone explain to me the identity used for the substitution, $q(t) = -i\hbar\frac{\delta}{\delta J(t)}$ , as this makes no sense to me.
I believe the $-i\hbar$ is just a convention but I don't understand why does $q(t) \to -i\hbar \frac{\delta}{\delta J(t)}$?

A: Since
$$q(t)e^{i\int ds J(s)q(s)} = - i\frac{\delta}{\delta J(t)}e^{i\int ds J(s)q(s)},$$
we can write for an arbitrary functional of $q(t)$
$$F[q(t)]e^{i\int ds J(s)q(s)} =
\sum_{n=0}^{+\infty}\int dt_1...dt_n\frac{\delta^n F[q(t)]}{\delta q(t_1)...\delta q(t_n)}|_{q(t)=0}q(t_1)...q(t_n)e^{i\int ds J(s)q(s)}=\\
\sum_{n=0}^{+\infty}\int dt_1...dt_n\frac{\delta^n F[q(t)]}{\delta q(t_1)...\delta q(t_n)}|_{q(t)=0}
(- i)^n\frac{\delta}{\delta J(t_1)}...\frac{\delta}{\delta J(t_n)}
e^{i\int ds J(s)q(s)}=\\
F\left[- i\frac{\delta}{\delta J(t)}\right]
e^{i\int ds J(s)q(s)}.$$
In general, such relations are easier to derive first in terms of ordinary derivatives, before switching to functional ones, where the time arguments and integrals clutter the essence. (Derivation rules are identical.)


text:
Q: Create A view with fixed percentage of width in all orientations in React-Native I want to create a view - that contains a Card - always with '90%' width of the window, whenever the device is vertical or horizontal, or Component is in a parent or not.
What I tried:
1 Using percentage
( width: '90%'):
It works well if I use my card separately on the main view of my screen, but when I use my card on a  horizontal ScrollView with other cards I can see many cards, but I want to see only one card before scrolling.
2  Using React.Dimensions
( Dimensions.get('window').width*0.9 with some padding) :
It works perfectly when I use a card separately or even with many inside a scrollView but when I change the orientation of the screen it takes less width of the screen than '90%'.
3 Using flex basis based on this answer
Is there any better way to achieve my goal?

A: You might wanna look at this package https://github.com/marudy/react-native-responsive-screen
This package doesn't require any orientation change support. It's just one file actually, so you might wanna take a look at that


text:
Q: Return result from google analytics callback I'm trying to return the clientId from google analytics. The proper way to get the clientId is through the following.
ga(tracker)->
  clientId = tracker.get('clientId')

But I would like to encapsulate so I can get the result with a function. I've been trying to do something like this. It still returns undefined. I would be grateful if I could get some help how to achieve it.
getClientId = (callback) ->
  ga(tracker)->
    clientId = tracker.get('clientId')
    if clientId
      return callback("&gaId=" + clientId)
    else
      return callback('')
    )

getString = (string) -> return string

result = getClientId(getString)


text:
Q: Does a polynomial exist such that $|P(x)| < a$ for some real $a$ and all real $x$? I'm pretty sure the answer is in the negative.
Can someone show me the proof?

A: Only constant polynomial will do the job. If $P$ has degree $d\geq 1$, assuming it WLOG monic, we have $|P(x)|\geq \frac{|x|^d}2$ for $|x|$ large enough, as $\lim_{x\to +\infty}\frac{P(x)}{x^d}=1$.

A: The answer is no.
Write
$$
P(x)=ax^n+\text{terms of lower degree}
$$
with $a\neq0$ and $n\geq1$. Then
$$
\lim_{x\to\infty}P(x)=\pm\infty
$$
according to the sign of $a$. This shows that $|P(x)|$ is unbounded.

A: (The question has been changed since the answer below was posted, so it no longer applies)
$P(x)=-x^2$ is less than 17 for all real $x$.

A: I think there exist such if $n\rightarrow\infty$ where $n$ is the order of the polinomial. For example when you have a cosine and use the taylor series expansion then you will get a polinomial and this polinomial will be bounded by the absolute value. Since the polinomials are of not infinite degree then $|P(x)|$ can not be bounded.


text:
Q: organization chart triangle plot I would like to create a triangle plot with organization structure (hierarchy) showing the number of employees at each level in different companies.
Here is some example data:
mylabd <- data.frame (company = rep(c("A", "B", "C"), each = 7),
skillsDg = rep(c("Basic", "HighSc", "Undgd", "MAST", "PHD", "EXPD", "EXECT"), 3),
number = c(200, 100, 40, 30, 10, 0, 0,
           220, 110, 35, 10, 0, 4, 1,
           140, 80, 120, 50, 52, 52, 3)
           )
   company skillsDg number
1        A    Basic    200
2        A   HighSc    100
3        A    Undgd     40
4        A     MAST     30
5        A      PHD     10
6        A     EXPD      0
7        A    EXECT      0
8        B    Basic    220
9        B   HighSc    110
10       B    Undgd     35
11       B     MAST     10
12       B      PHD      0
13       B     EXPD      4
14       B    EXECT      1
15       C    Basic    140
16       C   HighSc     80
17       C    Undgd    120
18       C     MAST     50
19       C      PHD     52
20       C     EXPD     52
21       C    EXECT      3

The objective is to reflect how different companies hire different skilled or degree workers.
The hypothetical figure is this (although color fill is not perfect).

The idea is that the width of line at each stage is proportional and then lines are connected. If there is no category in subsequent level, it will not be connected (like in company B). I couldn't find a program that can do this and neither could figure out. Any idea ?
Edit:
I do not alot about R, but here is my how my idea is shaping. It divides each line segment into two from a point to make it symetical. The drawn horizontal lines are then connected.

A: Using the grid package, we can have someting like this:

mylabd <- data.frame (company = rep(c("A", "B", "C"), each = 7),
                      skillsDg = rep(c("Basic", "HighSc", "Undgd", "MAST", "PHD", "EXPD", "EXECT"), 3),
                      number = c(200, 100, 40, 30, 10, 0, 0,
                                 220, 110, 35, 10, 0, 4, 1,
                                 140, 80, 120, 50, 52, 52, 3)
)

## to comapre we need o have the same scales for all organizations
nskills <- nlevels(mylabd$skillsDg)
ncompany <- nlevels(mylabd$company)
barYscale <- c(0,  nskills) * 1.05
barXscale <- c(0, max(mylabd$number) )* 1.05
## the global scene
vp <- plotViewport(c(5, 4, 4, 1),
                   yscale = barYscale,
                   layout = grid.layout(nrow=1,ncol=nbars))

pushViewport(vp)
grid.rect()
grid.yaxis(at=c(1:nlevels(mylabd$skillsDg)),label=unique(mylabd$skillsDg))
grid.grill()

## split data by companya
data.splitted <- split(mylabd,f=mylabd$company)
lapply(1:3,function(company){

  x <- data.splitted[[company]]
  vv <- x$number
  companyName <- unique(x$company)

  pushViewport(viewport(layout.pos.col=company,
                        xscale = barXscale,
                        yscale = barYscale))
  grid.rect()
 # grid.xaxis(at= mean(x$number),label = companyName)
  grid.xaxis()
  grid.polygon(x  = unit.c(unit(0.5,'npc')-unit(vv/2,'native'),
                           unit(0.5,'npc')+unit(rev(vv)/2,'native')),
               y  = unit.c(unit(1:nmeasures,'native'),
                           unit(rev(1:nmeasures),'native')),
               gp=gpar(fill = rainbow(nmeasures)[company]))
  grid.polygon(x  = unit.c(unit(0.5,'npc')-unit(vv/2,'native'),
                           unit(0.5,'npc')+unit(rev(vv)/2,'native')),
               y  = unit.c(unit(1:nmeasures,'native'),
                           unit(rev(1:nmeasures),'native')),
               id = c(1:nmeasures,rev(1:nmeasures)),
               gp=gpar(fill = NA))

  grid.text( x = unit(0.5,'npc'),
             y = unit(0.5,'native'),
             label = unique(x$company))

  popViewport()

})

popViewport()

A: I don't know of any function doing that but here is one from scratch:
my1 <- data.frame (company = rep(c("A", "B", "C"), each = 7), skillsDg = rep(c("Basic", "HighSc", "Undgd", "MAST", "PHD", "EXPD", "EXECT"), 3), number = c(200, 100, 40, 30, 10, 0, 0, 220, 110, 35, 10, 0, 4, 1, 140, 80, 120, 50, 52, 52, 3) )

my2 <- split(my1,my1$company) #split your dataframe into a list where each element is a company
# The next line create the layout
layout(matrix(1:(length(my2)+1), nrow=1), width=c(1,rep(4,length(my2))))
# Then we draw the x-axis:
par(mar=c(3,0,3,0))
plot(NA,axes=F, xlim=c(0,1),ylim=c(1,nlevels(my1$skillsDg)))
axis(side=4,tick=F,labels=unique(my1$skillsDg),
     at=seq_along(unique(my1$skillsDg)), las=2, line=-4)
# Then we apply a graphing function to each company:
lapply(my2,function(x){
    par(mar=c(3,0,3,0))
    plot(NA, xlim=c(-max(my1$number),max(my1$number)),
             ylim=c(1,nlevels(my1$skillsDg)),axes=F)
    title(sub=x$company[1],line=1)
    abline(h=seq_along(x$skillsDg), col="grey80")
    polygon(x=c(x$number,rev(-1*x$number)),
            y=c(seq_along(x$skillsDg),rev(seq_along(x$skillsDg))),
            col=as.numeric(x$company))
    })

Edit:
You can of course add whatever you want inside the graphing function in lapply (but in some case it might mean changing a little the dimensions of the graph):
layout(matrix(1:(length(my2)+1), nrow=1), width=c(1,rep(4,length(my2))))
par(mar=c(3,0,3,0))
plot(NA,axes=F, xlim=c(0,1),ylim=c(1,nlevels(my1$skillsDg)))
axis(side=4,tick=F,labels=unique(my1$skillsDg),
    at=seq_along(unique(my1$skillsDg)), las=2, line=-4)
lapply(my2,function(x){
    par(mar=c(3,0,3,0))
    plot(NA, xlim=c(-max(my1$number)-50,max(my1$number)+50),
        ylim=c(1,nlevels(my1$skillsDg)),axes=F)
    title(sub=x$company[1],line=1)
    abline(h=seq_along(x$skillsDg), col="grey80")
    text(x=x$number+5, y=seq_along(x$skillsDg)+.1, label=x$number, pos=4)
    polygon(x=c(x$number,rev(-1*x$number)),
        y=c(seq_along(x$skillsDg),rev(seq_along(x$skillsDg))),
        col=as.numeric(x$company))
    })

A: Different chart than you asked for, but an attempt to follow some common visualization principles:
library(ggplot2)
mylabd$skillsDg <- factor(mylabd$skillsDg, levels = c("Basic", "HighSc", "Undgd", "MAST", "PHD", "EXPD", "EXECT"))
p <- ggplot(data=mylabd, aes(x=skillsDg, y=number, fill = skillsDg))
p <- p + geom_bar(stat = "identity") + coord_flip()
p <- p + facet_wrap( ~ company, ncol = 1, nrow=3)
plot(p)


text:
Q: Запрос для получение даты в нормальном формате Всем привет. Есть база, там дата хранится в таком состоянии - 2014-10-21.
Как сделать SQL-запрос, чтобы получить дату в нормальном состоянии, т.е. 21.10.2014?
A: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
A: $date = "2014-10-21";
$code = explode("-",$date);
echo $code[2].'.'.$code[1].'.'.$code[0];

А если так попробовать?
А вообще дату в базе обычно хранят в секундах с 1970 года, а при выборке формируют как хотят


text:
Q: making application System Critical Process how can i make a Critical System Process so that it can't be ended from task manager in C#?

A: In general, it is not possible to do so because it would take away control from the user. Windows even allows you to kill highly critical processes such as csrss.exe (don't try killing it, please, instant BSOD is guaranteed).
The very good reasons why this is so have been very well explained by Raymond Chen:

The arms race between programs and users

If you don't want users to kill your process make it a service and take away administrator privileges from your users.

A: may be a little late but this is the code I use
    [DllImport("ntdll.dll", SetLastError = true)]
    private static extern void RtlSetProcessIsCritical(UInt32 v1, UInt32 v2, UInt32 v3);
    [DllImport("advapi32.dll", SetLastError = true)]

    private static extern bool SetKernelObjectSecurity(
         IntPtr handle,
         int securityInformation,
         [In] byte[] securityDescriptor
     );

calling the function on C#
RtlSetProcessIsCritical(1, 0, 0);

just note that

*

*you need administrator for this

*causes BSOD whenever you close the process

to go back to normal just do
RtlSetProcessIsCritical(0, 0, 0);