text:
Q: Custom Javascript Ajax for ASP.NET I've written some basic Javascript functions and would like to learn how to enable asynchronous postbacks within a C# 4.0/ASP.net project using this JS code.
For example, I have a script that increments a number when clicked.  When clicked again, the number is decremented.  I basically load the number from a database, then hide one  and show another with the corresponding decremented number on click.  This is not complicated javascript; its a simple example.  Now when I click the button I want to send this increment/decrement call back to the server to update the database's number.
I realize that I can accomplish something akin to this example using the AJAX Control Toolkit's toggle button.  I, however, want to know how to use my OWN javascript to create AJAX functionality.
How do I accomplish this using C# and my custom Javascript code?
I'm not opposed to using the ASP.net AJAX library, I just don't want to use a ready built control.  I want to learn the process of creating my own AJAX functionality.  I would presume that I will have to use an asp:UpdatePanel, but I don't know how to call C# functions from the client side.
My javascript is not jQuery, in fact I want nothing to do with jQuery until I learn more about javascript and this process.

A: Simple with no UpdatePanel:
First, add a Generic Handler to your project (.ashx). This will act as our Http endpoint. Our javascript will call it. We could (and probably should), use a web service endpoint but that requires processing the response and complicates the example. A handler returns plain text.
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler
{
    // We'll use a static var as our "database".
    // Feel free to add real database calls to the increment
    // and decrement actions below.
    static int TheNumber = 0;

    public void ProcessRequest(HttpContext context)
    {
        string action = context.Request.QueryString["action"];
        if (!string.IsNullOrEmpty(action))
        {
            if (action == "increment")
                TheNumber++;   //database update and fetch goes here
            else if (action == "decrement")
                TheNumber--;   //database update and fetch goes here
        }
        context.Response.ContentType = "text/plain";
        context.Response.Write(TheNumber);
    }

    public bool IsReusable { get { return false; } }
}

Next, create your web page and add the async javascript.
<%@ Page Language="C#"%>

    <form id="Form1" runat="server">

    The Number: 0

        <asp:Button ID="Button1" runat="server" Text="Increment"
            OnClientClick="callHandler('increment');return false;" />

        <asp:Button ID="Button2" runat="server" Text="Decrement"
            OnClientClick="callHandler('decrement');return false;" />

    </form>

The final flow is:

*

*A web page user clicks the Increment or Decrement button which calls our javascript

*Our javascript sends a request with the desired action in the querystring to Handler.ashx

*Handler.ashx reads the querystring, increments or decrements its static variable, and returns the value

*Our callback receives the value and updates our UI.

A: if your using an UpdatePanel it's very simple with a JavaScript call to __doPostBack. See here for example.

A: Have a look at this tutorial around AJAX
http://www.w3schools.com/Ajax/Default.Asp
It will give you an overview of using Javascript to GET and POST data using AJAX.
Hope this helps.

A: Here's a link on how you can incorporate ASP.NET C# with your custom Javascript code.
http://msdn.microsoft.com/en-us/library/bb386450.aspx
It also contains a sample VS 2010 project here:
http://go.microsoft.com/fwlink/?LinkId=185646
Here's generally what's going on here:
In the AjaxIScriptControl solution:
SampleTextBox.cs - takes care of rendering the script control on the page; and attachment to client javascript code (the js file)
SampleTextBox.js - takes care of client side functionality and generates Javascript object of control via prototype
Notes:

*

*This example leverages existing
ASP.NET's built-in control (you
notice SampleTextBox inherits Textbox
and IScriptControl) but you can
render any type of HTML control if
you inherit ScriptControl class
instead.

*This solution also chose to separated
the Script control code and website
code in two projects but you can
easily make it into one.

*You can easily leverage another Javascript library in your JS file
In my experience so far, this is the one of the more elegant way to incorporate server side code with client side if you are to create re-useable controls for your website.  You leverage server side power to do the initial rendering while provide client side capabilities through Javascript.

A: If you create your C# functions as WCF REST Services or older-style Script Services, then you can easily call your service methods from your JavaScript using a basic XmlHttpRequest (no jQuery or UpdatePanels needed).
Here's a quick jsFiddle I put together: http://jsfiddle.net/ndVeS/
This sample has two text boxes; you enter a value in the first one, click the button, and then that value is passed to a service (an echo service) and returned in the callback.  The JavaScript code takes that value and populates the second textbox with it.
You could define a C# WCF RESTful service like this:
[ServiceContract]
public class EchoService : IEchoService {
  [WebGet(UriTemplate="EchoMe?val={theValue}, ResponseFormat=WebMessageFormat.Json)]
  public string EchoMe(string theValue) {
    return theValue;
  }
}

If you handle your calls this way, you can separate out your service logic from your presentation (ASPX files), and this allows for easier testing and you can also separate responsibilities from those who build the UI from those that build the business functionality.
I have to admit I'm more of a jQuery person when it comes to this, but I thought it's a great exercise to figure out how the XmlHttpRequest works under the hood.  It makes you appreciate what jQuery (or similar framework) provides.
Here's a nice overview of the XmlHttpRequest object and how to use it: http://www.jibbering.com/2002/4/httprequest.html
I hope this helps.

A: function GetXmlHttpObject(handler) {
var objXMLHttp = null
if (window.XMLHttpRequest) {
    objXMLHttp = new XMLHttpRequest()
}
else if (window.ActiveXObject) {
    objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp;

}
function GetDropDown() {
function stateChanged(StatesUpdated) {

    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
        document.getElementById('updateplace').innerHTML = xmlHttp.responseText;
        //"updateplace" is you div id which will hold the new data or new page
        if (navigator.appName != "Microsoft Internet Explorer") {

        }
    }
    else {
        //alert(xmlHttp.status);
    }
}

xmlHttp = GetXmlHttpObject()
if (xmlHttp == null) {
    alert("Browser does not support HTTP Request");
    return;
}

    url = "xyz.aspx" //this might be sent to any post data
    url = url + "&sid=" + Math.random();

    xmlHttp.onreadystatechange = stateChanged;

    xmlHttp.open("GET", url, true);

    xmlHttp.send(null);

}
with the above code you can send data to any .cs file also where you can change the data and load it in a new page which will load in the update div and the method should redirect to the new aspx file.
I hope you got the logic :)
if you have any doubts reach me @ sankalpa.sam@gmail.com

A: I know it's not MVC that you're doing, but have a look at the MVC section of the ASP.NET site and you will find a lot of examples of AJAX calls there - MVC doesn't use those dreadful script-soup creating .NET objects.  Most will probably be using jQuery - this is an open-source javascript library that can plug into any web app and provides some really nice functionality.

A: Maybe u r looking for this:
function ajaxscript(){
$.ajax({
                  type: "POST",
                  url: |url/methodName|,
                  data: |variable_name|,
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: |some javascript here|,
                  error: |some javascript here|
            });


text:
Q: Converting Template to Responsive. Font size, Width in %age, but how about Padding and Margins I want to override Font Size and Page view using
@media screen and (max-device-width: 640px){
body
{
font-size: 1.2em;
max-width: 80%;  }
}

Where Font Size should increase to 1.2 and width to be reduced by 80%
But the same is not happening due to absolute values in CSS
Is adopting a %age would help in achieving the goal for example
.innerpage-bodycontainer-left p { font: normal 11px Arial, Helvetica, sans-serif; }

Does replacing Font Size in Em will work on
.innerpage-bodycontainer-left p { font: normal .6875em Arial, Helvetica, sans-serif; }

For Width
.innerpage-bodycontainer-left-text-container .pageing-box{ width:1000px; float: left; }

Replacing it in %age
.innerpage-bodycontainer-left-text-container .pageing-box{ width:100%; float: left; }

But - can i leave Padding and Margins in absolute pixel or is it also required to change them in percentage before adopting media query.
I am a novice in css, has to attempt to convert site to responsive - your advise on % terms for width and Font size in em would assist me in right direction
Thanks

A: You can set width in %age and px, fonts in em, %age or px.
It is up to you to decide wether to change the margin as well or leave them in pixels.
About %age:

Works better if you declare the width of every relative elements.

For example:
html,body {
  width:100%;
  min-width:100%;
}

.mycontainer {
  width:75%; /* will work properly because we have its parent width */
}

...

About em:

1em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px.

I'd recommend setting font-size in px in the body tag and only touch paragraphs, links and headings. Example:
body {
  font-size:16px;
}

h1 {
  font-size:2em; /* this is equal to 16*2 = 32px */
}

@media(max-width:768px) {
    h1 {
      font-size: 1.5em; /* smaller font on mobile. 1.5em == 16+8 == 24px */
   }
}

I usually define a standard margin/padding and leave them untouched, while changing the rest of the page with media queries. For example:
.mycontainer {
   margin:15px;
   padding:15px;
   font-size:20px;
   width:50%;
   height:200px; /* having a fixed height will help you a lot */
}

/* not specifing margin will leave them untouched */
@media(max-width:992px) {
 .mycontainer {
    font-size:14px;
    width:80%;
    height:300px;
  }
}

/* or you can use em */
@media(max-width:768px) {
  .mycontainer {
    font-size: 0.8em;
    width:100%;
    height:400px;
    margin:10px; /* here I'm changing the margin for mobile */
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting a PyQGIS script that works for one input to work with multiple inputs A script I have written to perform a number of tasks on a single input needs amending to work with multiple inputs given an input folder. The working script is this and takes a input raster through some processes to output a shp:
##in_rast=raster
##out_shp=output vector

#Take grid and create extent
out1=processing.runalg('gdalogr:rastercalculator', in_rast,'1',None,'1',None,'1',None,'1',None,'1',None,'1','A>0',None,5,None,None)
#Ratser extent to polygon
out2=processing.runalg('gdalogr:polygonize', out1['OUTPUT'],'DN',None)
#Calculate area m^2 and add to new field 'Area_m2'
out3=processing.runalg('qgis:fieldcalculator', out2['OUTPUT'],'Area_m2',0,10.0,3.0,True,'$area',None)
#Select polygons >5m^2 and extract to new shp
out4=processing.runalg('qgis:extractbyattribute', out3['OUTPUT_LAYER'],'Area_m2',3,'5',None)
#Fill holes less than 200m^2
out5=processing.runalg('qgis:fillholes', out4['OUTPUT'],200.0,out_shp)

I have made a start on updating this to work on multiple inputs but being relativity new to python my understanding of the correct methods to use has reached its limit. The updated script looks as follows, only working and outputting for the first process:
##Input_raster=multiple raster
##result_ras=folder

import os

layers = Input_raster.split(';')
for raster in layers:
    result_name = os.path.splitext(os.path.basename(raster)) [0] + "_Extent.tif"
    out1=processing.runalg('gdalogr:rastercalculator', raster,'1',None,'1',None,'1',None,'1',None,'1',None,'1','A>0',None,5,None,result_ras + "/" + result_name)

The question is; how can I continue to write the rest of the processes into my script? I am only interested in the output for the final step so all intermediate outputs can be saved as temp. Ultimately I'd like the output to take the name of the original input raster and append _Outline.shp.

A: Can you just add the remaining processes to the loop:
layers = Input_raster.split(';')
for raster in layers:
    result_name = os.path.splitext(os.path.basename(raster)) [0] + "_Extent.tif"
    out1=processing.runalg('gdalogr:rastercalculator', raster,'1',None,'1',None,'1',None,'1',None,'1',None,'1','A>0',None,5,None,result_ras + "/" + result_name)
    out2=processing.runalg('gdalogr:polygonize', out1['OUTPUT'],'DN',None)
    out3=processing.runalg('qgis:fieldcalculator', out2['OUTPUT'],'Area_m2',0,10.0,3.0,True,'$area',None)
    out4=processing.runalg('qgis:extractbyattribute', out3['OUTPUT_LAYER'],'Area_m2',3,'5',None)
    out5=processing.runalg('qgis:fillholes', out4['OUTPUT'],200.0,out_shp)

I guess out_shp is the name of the output shapefile, so you will need to generate a new name for each layer - you can do this just the same way that you generate result_name, just use .shp instead of .tif

A: Following the comments from James & Joseph I added the other processes inside the loop. The script now appears to be producing the desired results:
##Input_raster=multiple raster
##result_shp=folder

import os

layers = Input_raster.split(';')
for raster in layers:
    result_name = os.path.splitext(os.path.basename(raster)) [0] + "_Extent.tif"
    out1=processing.runalg('gdalogr:rastercalculator', raster,'1',None,'1',None,'1',None,'1',None,'1',None,'1','A>0',None,5,None,result_shp + "/" + result_name)
    out2=processing.runalg('gdalogr:polygonize', out1['OUTPUT'],'DN',None)
    out3=processing.runalg('qgis:fieldcalculator', out2['OUTPUT'],'Area_m2',0,10.0,3.0,True,'$area',None)
    out4=processing.runalg('qgis:extractbyattribute', out3['OUTPUT_LAYER'],'Area_m2',3,'5',None)
    shp_name = os.path.splitext(os.path.basename(raster)) [0] + "_out.shp"
    out5=processing.runalg('qgis:fillholes', out4['OUTPUT'],200.0,result_shp + "/" + shp_name)

Thanks for the help


text:
Q: Get poster variable from omdbapi using AJAX call I am using the OMDb API for getting some film information.
The function I use is this one:
function getImage(titel) {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "http://www.omdbapi.com/?t=" + titel,
        success: function(data){
            return data.Poster;
        },
        async:false,
        error: function() {
            return "Image not found.";
        }
    });
}

An example I get returned by the server:
{
   "Title":"The Godfather",
   "Year":"1972",
   "Rated":"R",
   "Released":"24 Mar 1972",
   "Runtime":"2 h 55 min",
   "Genre":"Crime, Drama",
   "Director":"Francis Ford Coppola",
   "Writer":"Mario Puzo, Francis Ford Coppola",
   "Actors":"Marlon Brando, Al Pacino, James Caan, Diane Keaton",
   "Plot":"The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",
   "Poster":"http://ia.media-imdb.com/images/M/MV5BMjEyMjcyNDI4MF5BMl5BanBnXkFtZTcwMDA5Mzg3OA@@._V1_SX300.jpg",
   "imdbRating":"9.2",
   "imdbVotes":"755,007",
   "imdbID":"tt0068646",
   "Type":"movie",
   "Response":"True"
}

The titel given is parameter is filled, and the data returned by the omdbapi is correct.
Only the data.Poster is not working. What am I doing wrong?

A: function getImage(titel) {
$.ajax({
    type: "GET",
    dataType: "json",
    url: "http://www.omdbapi.com/?t=" + titel,
    success: function(data){
        return $.get(data.Poster);
    },
    async:false,
    error: function() {
        return "Image not found.";
    }
});
}

Try it and whether it works.
You can refer this link to get some more information.


text:
Q: How can a ASP.Net UserControl draw svg before the page is finished loading? I don't know if I'm asking the question correctly so apologies if I am using the wrong terminology.  I typically write my own servers, javascript, etc in vi.  I've been given a project to enhance a VB.Net / ASP.Net application and I'm having some troubles figuring out how to get the user control to render BEFORE the page finishes loading.
When I use normal browser as the viewer, everything works OK.  When I try to use generate the page as a report, the report generator spits out the PDF while my JavaScript graph drawing stuff is still in it's initialize functions.
They are using EvoPDF as the PDF generator.  It appears the page is being considered complete after the page is loaded but before the javascript is executed.
I admit I'm a bit lost when it comes to ASP.NET, but I know HTML/HTTP/JavaScript very well.
How can I force the page load to wait until my usercontrol finishes rendering, or otherwise solve my problem?
Thank you

A: When you use evopdf, the PdfConverter has a property called ConversionDelay.
This by default is set to 0.
If the problem is due to the page rendering too quickly then setting this may solve your problem.

A: You cannot get VB.NET to render something before the page has loaded.  It is a server side language and the page must load all of the way to get the response from the server.
However it sounds like you may just need something like the domready function in JQuery.  Where the page loads and then you execute your javascript.  Right now it seems you might just be executing your javascript as the page is loading and you may need to wait for the full response from the server to start your script.
But no ASP.NET cannot draw or do anything until the page is loaded unless you are going to use some sort ajax functionality to get data from the server.


text:
Q: How to structure a more complex Angular 2 application? I am currently doing some research about Angular 2 and it seems like a lot of stuff changes so i wanted to rebuild a very common use case for my projects which looks something like this in Angular 1 to get the basics. But i stumbled upon some general questions about how to structure an Angular 2 application.
Let me give you an example how i solve this in Angular 1 right now.

*

*Basically it is not a single page application

*I just use directives to extend the DOM

*I do not need a routing

    <my-autocomplete></my-autocomplete>

    <my-navigation-menu></my-navigation-menu>

    <my-main-app>

        <my-filter facet="one" />
        <my-filter facet="two" />
        <my-filter facet="three" />

    </my-main-app>

Now for the Angular 2 structure.

    <base href="/elasticsearch_frontend/">
    <title>Angular 2 QuickStart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

<my-autocomplete></my-autocomplete>

<my-main-app></my-app>

So the problem is the following:
It seems like that everything must be in the root of the application. I am more used to the Angular 1 style, where i used to use the directives to html tree. Now in Angular 2 i used the application component as a container to initialize my application.

*

*So how could i structure my components to achive a similar result in Angular 2?

*Might it be better to build two independent applications instead? One for the autocomplete and one for the main application, even if they share the same resources (currently via a service)

*I think that i do not need the template in the app.component.ts but if i remove it i will get this error: angular2.dev.js:23730 ORIGINAL EXCEPTION: Component 'AppComponent' must have either 'template' or 'templateUrl' set. Like said before, i just want to extend the DOM and initialize the directives in one place.

main.ts
import {bootstrap}    from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';

import {AppComponent} from './app.component';

bootstrap(AppComponent, [ROUTER_PROVIDERS]);

app.ts
import {Component, OnInit} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';

import {SearchService} from './search.service';
import {CatalogComponent} from './catalog.component';
import {AutocompleteComponent} from './autocomplete.component';

@Component({
    selector: 'my-app',

    template: `

{{title}}

    `,
    directives: [AutocompleteComponent],
    providers: [
        SearchService
    ]
})

export class AppComponent implements OnInit {
    public title = 'Elasticsearch Products Prototype';

    public queryParams : String[] = [];

    ngOnInit() {

    }
}

A: Micronyks is right : Components annotations (@Component) need a template or templateUrl attribute whereas Directices annotations dont - so consider using directives if you don't need html to replace.
About the structure, if you take a look at TourOfHeroes Google tutorial (https://angular.io/docs/ts/latest/tutorial/) you will find out that you need  :

*

*index.html with JS scripts included and xx-app tag

*main.ts file including bootstrap App component

*app.component.ts with template containing many xxx-xxx tags

And for your folder structure you can have a folder for your components, services, templates,..


text:
Q: Why is VGA connector has only one pin for red color data but is composed of 8 bits? VGA connectors have 15 pins, three of these are used for color data of red, blue and green. Based on this project, each color has a width of 8 bits. However if under the scheme of 8-bit color, each color will have 8 bits of data. (Upon further inspection, 8-bit color means 3 bits red, 3 bits green and 2 bits blue) How can you have multiple bits of data in one pin?

A: A VGA signal cable uses analog signals for R, G, and B. H-sync and V-sync are... digital sync pulses.. but the color channels need to be converted into a digital signal through a sampling process to be fed into an LCD.
Traditionally these signals were fed into a CRT with a red, green, and blue cathode ray, and so these signals were simply modulated into the beam intensity of each.

A: The VGA color signals are analog, between 0 and 0.7V. 8-bit resolution is just a limitation of implementation. Depending on your DAC, you could have more bits (e.g. 8 bits per color).

A: The VGA color signals are analog- 700mV for full brightness and 0mV for minimum.


text:
Q: Is it possible to use mootools and jQuery both together I have to use mootools and jquery files together. But there is a conflict occurs while using both together. Is there any solution to avoid this conflict?

A: Yes, you'll have to include this code just after you include your jQuery and before you include Mootools.
<script>
    var j$ = jQuery.noConflict();
</script>

You'll then want to find/replace all jQuery $ references with j$, preferably using the automated tool found in most code editors.

You also have another option, a closure. It would look something like this, if I remember correctly:
(function($) {
  //jQuery stuff
})(jQuery);

You'll want to move all your existing code inside this function. It scopes the $ variable so you can do business with jQuery as usual within the closure, then use Mootools outside of it.

A: It is (possible to use both libraries together).
From the official jQuery site on how to make it work with other libraries:
http://docs.jquery.com/Using_jQuery_with_Other_Libraries


text:
Q: Reverse direction of loop through an array containing functions, without jQuery I have the following Javascript which aims to enable users to cycle backwards and forwards through a number of menus using an array of functions executed by an eventListener...
var i = 0;
var steps = [
  function one() {do something},
  function two() {do something},
  function three() {do something},
  function four() {do something},
  function five() {do something}
]
//loops forward through array *successfully*
document.getElementById('forward').addEventListener("click", function() {
  steps[i]();
}
//loops backwards through array *unsuccessfully*
document.getElementById('backward').addEventListener("click", function() {
  steps[i]().reverse();
}

The first eventListener function is successful in looping through the array, however, the second eventListener function backward, fails to loop through the array in reverse (to little suprise).
Firstly, I am unsure on how to loop an array, that contains functions, in reverse.
Secondly, I am wondering if it's possible to loop an array in reverse from a particular point in that array; essentially, if the array has looped through, and had gone no further than function three(), is there a script that will allow a user to loop backwards to functions two() then one(), then forward again?
I have read a number of questions here on StackOverflow concerning array.reverse(), however none that I've found seem to concern the presence of functions and/or reversing the loop mid-array.
So thank you for any answers, they're greatly appreciated!

A: I don't think you need to loop over the array. You need to "manage state", which means you increment and decrement i. After updating the state, you find the right function using steps[i] and call it.

var activeMenuIndex = 0;

var steps = [
  function one() {console.log("activate menu 1") },
  function two() {console.log("activate menu 2") },
  function three() {console.log("activate menu 3") },
  function four() {console.log("activate menu 4") },
  function five() {console.log("activate menu 5") }
];

var activateCurrentMenu = function() {
  var activator = steps[activeMenuIndex];

  if (activator) {
    activator();
  } else {
    console.log("Out of bounds!");
  }
};

var nextMenu = function() {
  // TODO: Check for out of bounds
  activeMenuIndex += 1;
  activateCurrentMenu();
};

var prevMenu = function() {
  // TODO: Check for out of bounds
  activeMenuIndex -= 1;
  activateCurrentMenu();
};

document.getElementById('forward').addEventListener("click", nextMenu);
document.getElementById('backward').addEventListener("click", prevMenu);
<button id="backward">back</button>
<button id="forward">next</button>

To answer the question though: looping over an array of functions is no different than looping over any other array. You can use a for block, or use foreach.
If you want to loop over an array in reverse, you can call .reverse().foreach (which mutates the original array).

A: Is this what you're looking for? Looping through array

   var steps = [
    function one() { console.log("1") },
    function two() { console.log("2") },
    function three(){ console.log("3") },
    function four() { console.log("4") },
    function five() { console.log("5") }
    ]
    //loops forward through array
    function forward(i){
      steps.slice(0,i).forEach(function(el){ el(); });
    }
    //loops backwards through a the reversed aarray
    function backward(i) {
      steps.reverse().slice(0,i).forEach(function(el){ el(); });
    }

    forward(3);
    backward(3);


text:
Q: Проверка наличия символа в строке C++ Задача такова: необходимо ввести символ и проверить к какому алфавиту и регистру
он принадлежит. С латинскими буквами все нормально,но проблемы возникают с кириллицей. Подскажите что не так в моей программе.
Код данной задачи:
setlocale(LC_ALL,"Russian");
char i;
cin >> i;

char ENG [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char eng [] = "abcdefghijklmnopqrstuvwxyz";
char RU [] = "АБВГДЭЕЖЗЫИКЛМНОПРСТУФХЦЧШЩЬЪЮЯЁ";
char ru [] = "aбвгдеёжзыиклмнопрстуфхцчшщьъюяё";

for (int h = 0;h <= 26;h++)
{
if(i == ENG[h]){cout  <<"ENG";break;}
if(i == eng[h]){cout <<"eng";break;}
                                        }
for (int b = 0;b <=33;b++)
{
    if(i == RU[b]){cout  <<"RU";break;}
    if(i == ru[b]){cout <<"ru";break;}
                                        }

return a.exec();
                                        }

A: Для проверки символа по ограниченному нулем массиву char используйте strchr, т.е. условие if(strchr(массив, символ)) вместо цикла.
P.S. Использовать i для символа, а b, h для индексов, это "удачный" способ затруднить чтение кода...


text:
Q: Check whether both of the multiselect dropdown is selected i am creating two dropsdowns like this
var drp_nt = $('<select />', {
                               'id'     : 'drp_' + nt,
                               'name'   : 'drp_' + nt+'[]',
                               on: {
                                        change: check_data
                                        },
                               'multiple': true});

var drp_cnt = $('<select />', {
                              'id'     : 'drp_' + cnt,
                              'name'   : 'drp_' + cnt+'[]',
                              on: {
                                        change: check_data
                                        },
                              'multiple': true});

Now i am defining the check_data_function like this
function check_data()
{
    if($("select option:selected").length==2)
        alert('Two Dropdown Selected');
    else
        alert($("select option:selected").length);
}

I want to enable a button when both of the dropdown has some of the options selected.
in the above fragment of the code, the problem is, if i select 2 options from dropdown drp_nt, and select no option from drp_cnt, then also the alert 'Two Dropdown Selected' is taking place.
I want to have the alert 'Two Dropdown Selected' take place when both of the dropdowns will have some options selected. If one is having something selected while the other one don't, then the alert 'Two Dropdown Selected' won't take place
How can i achieve this?

A: This will do the trick:
function check_data() {
    if ($('select option:selected').parent().length == 2) {
        alert('Two Dropdown Selected');
    }
}

The idea is that you still select selected options, but then you get their parent select elements and verify that there are exactly two of them.
Check the demo below.

$('select').change(check_data);

function check_data() {
    if ($('select option:selected').parent().length == 2) {
        alert('Two Dropdown Selected');
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple>
    <option>Text 1</option>
    <option>Text 2</option>
    <option>Text 3</option>
    <option>Text 4</option>
</select>

<select multiple>
    <option>Text 1</option>
    <option>Text 2</option>
    <option>Text 3</option>
    <option>Text 4</option>
</select>

A: you are selecting both dropdown in jquery using select
**
function check_data()
{
    if($("select option:selected").length==2)
        alert('Two Dropdown Selected');
    else
        alert($("select option:selected").length);
}

**
$('select') will select both dropdown. So when you check in jquery, after you selected two in one drop down, this will give you result as two selected. So you need to check like following
    function check_data()
{
    if($("#id1 option:selected").length>1 && $("#id2 option:selected").length>1)
        alert('Two Dropdown Selected');
    else
        alert('select any one of the option from both dropdown');
}

A: You can do this by filtering the list of selects so that you get only those with options selected and then check the length

$(function(){
  $(document).on('change','select',function(){
      var selectsWithOptionsSelected = $('select').filter(function(){
          return $('option:selected',this).length>0;
      });
      alert(selectsWithOptionsSelected.length);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select rows="3" multiple>
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</select>
<select rows=3 multiple>
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</select>

You may want to fiddle with the selectors to only target the select instances you're interested in, for example you could give them a class and use that in both selectors (select.myClassName)

A: Use jQuery().each
function check_data()
{
  var counter = 0;
  jQuery('select').each(function() {
    if(jQuery(this).find('option:selected').length == 2) {
      counter++;
    }
  });
  if(counter == jQuery('select').length)
      alert('Two Dropdown Selected');
  else
      alert($("select option:selected").length);
  }

A: Here's another alternative just for giggles:
function check_data() {
    $('select:has(option:selected)').length > 1 && alert('Foo');
}


text:
Q: how to lookup dns records with indy in delphi How can I lookup DNS records with Indy in Delphi?  For example, SRV records, SPF records, TEXT records, etc.
I know we can use nslookup directly from Windows, but I want to do this with Indy, or any other Delphi component.
I tried searching Google, and I found something like this:
function ReverseDNSLookup(IPAddress: String; DNSServer: String =
SDefaultDNS; Timeout: Integer = 30; Retries: Integer = 3) : string;
var
  AIdDNSResolver: TIdDNSResolver;
  RetryCount: Integer;
begin
  Result := '';
  IPAddress := ReverseIP(IPAddress);

  AIdDNSResolver := TIdDNSResolver.Create(nil);
  try
    AIdDNSResolver.QueryResult.Clear;
    AIdDNSResolver.WaitingTime := Timeout;
    AIdDNSResolver.QueryType := [qtPTR];
    AIdDNSResolver.Host := DNSServer;

    RetryCount := Retries;
    repeat
      try
        dec(RetryCount);

        AIdDNSResolver.Resolve(IPAddress);

        Break;
      except
        on e: Exception do
        begin
          if RetryCount <= 0 then
          begin
    //            if SameText(e.Message, RSCodeQueryName) then
    //              Result := FALSE
    //            else
                  raise Exception.Create(e.Message);
            Break;
          end;
        end;
      end;
    until false;

    if AIdDNSResolver.QueryResult.Count > 0 then
      Result := AIdDNSResolver.QueryResult.DomainName;
  finally
    FreeAndNil(AIdDNSResolver);
  end;
end;

But all it is for is looking up IP addresses.  I want SRV and TEXT records, and maybe SPF records.

A: TIdDNSResolver is what you are looking for.  The example you show is only using a small subset of what TIdDNSResolver supports.  You simply need to set the TIdDNSResolver.QueryType property to specify the type(s) of record(s) you want to query, and then loop through the TIdDNSResolver.QueryResult collection to access the individual records.  TIdDNSResolver supports SRV and TXT records, for example:
var
  DNS: TIdDNSResolver;
  I: Integer;
  Record: TResultRecord;
  Txt: TTextRecord;
  Srv: TSRVRecord;
begin
  DNS := TIdDNSResolver.Create(nil);
  try
    DNS.WaitingTime := Timeout;
    DNS.QueryType := [qtTXT, qtService];
    DNS.Host := 'some.dns.server';

    DNS.Resolve('some.hostname');

    for I := 0 to DNS.QueryResult.Count -1 do
    begin
      Record := DNS.QueryResult[I];
      case Record.RecType of
      begin
        qtTXT: begin
          Txt := TTextRecord(Record);
          // use Txt.Text as needed...
        end;
        qtService: begin
          Srv := TSRVRecord(Record);
          // use Srv.OriginalName, Srv.Service, Srv.Protocol, etc as needed...
        end;
      else
        // something else...
      end;
    end;
  finally
    DNS.Free;
  end;
end;

TIdDNSResolver does not support the SPF record type (code 99) that was defined in RFC 4408 in 2006:

This document defines a new DNS RR of type SPF, code 99.  The format of this type is identical to the TXT RR [RFC1035].  For either type, the character content of the record is encoded as [US-ASCII].
It is recognized that the current practice (using a TXT record) is not optimal, but it is necessary because there are a number of DNS server and resolver implementations in common use that cannot handle the new RR type.  The two-record-type scheme provides a forward path to the better solution of using an RR type reserved for this purpose.

That record type was later obsoleted by RFC 7208 in 2014:

SPF records MUST be published as a DNS TXT (type 16) Resource Record (RR) [RFC1035] only.  The character content of the record is encoded as [US-ASCII].  Use of alternative DNS RR types was supported in SPF's experimental phase but has been discontinued.
In 2003, when SPF was first being developed, the requirements for assignment of a new DNS RR type were considerably more stringent than they are now.  Additionally, support for easy deployment of new DNS RR types was not widely deployed in DNS servers and provisioning systems.  As a result, developers of SPF found it easier and more practical to use the TXT RR type for SPF records.
In its review of [RFC4408], the SPFbis working group concluded that its dual RR type transition model was fundamentally flawed since it contained no common RR type that implementers were required to serve and required to check.  Many alternatives were considered to resolve this issue, but ultimately the working group concluded that significant migration to the SPF RR type in the foreseeable future was very unlikely and that the best solution for resolving this interoperability issue was to drop support for the SPF RR type from SPF version 1.  See Appendix A of [RFC6686] for further information.
The circumstances surrounding SPF's initial deployment a decade ago are unique.  If a future update to SPF were developed that did not reuse existing SPF records, it could use the SPF RR type.  SPF's use of the TXT RR type for structured data should in no way be taken as precedent for future protocol designers.  Further discussion of design considerations when using new DNS RR types can be found in [RFC5507].


text:
Q: Exclude IPhone 3GS from App (Adobe Air)
Possible Duplicate:
Can I restrict my iPhone app from being used by iPhone3G's?

I have build an application for IOS and it runs fine on IPhone 4 (and above) and all IPads.
Just the 3GS seens to lack power to run it well. Can i exclude the app for these devices?
I have found using UIRequiredDeviceCapabilities and http://developer.apple.com/library/ios/#documentation/General/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html to limit apps using required Capabilities. But i can not find something to just exclude the 3GS. Does anyone know ?

A: Add UIRequiredDeviceCapabilities key to info.plist file and front-facing-camera as required value. If I am correct, 3GS doesn't have a front camera. Here is the apple documentation with all possible values. As mentioned by  TonyMkenu in comments, check this link for UIRequiredDeviceCapabilities and Device Compatibility Matrix


text:
Q: Accidentally installed phpmyadmin as root user While trying to install phpmyadmin, I accidentally installed it as a root user.
Beginning of the story, I was editing the httpd.conf file of Apache. To avoid permission issues while running some commands, i did sudo su - on the terminal. Thereafter without exiting from root user, I installed phpmyadmin using the following commands
cd /Library/WebServer/Documents/
tar -xvf ~/Downloads/phpMyAdmin-3.5.2.2-english.tar.gz
mv phpMyAdmin-3.5.2.2-english/ phpmyadmin
cd phpmyadmin
mv config.sample.inc.php config.inc.php

But now when I try to install yii at /Library/WebServer/Documents/, i get the following error
PHP Warning – yii\base\ErrorException

mkdir(): Permission denied

Is there any way I can remove the root user privilege from phpmyadmin without uninstalling?
Operating system: OS MAC Mavericks

A: chown with the -R flag (recursive) is probably what you want.  (The following may not apply exactly to your circumstances so please consider it carefully before running).
Of course, replace {YourUsername} with your actual username.  The commands below just change the owner of the files and not the group.  If you need to change the group name also, the new name goes after the colon:
cd /Library/WebServer/Documents/
chown -R {YourUsername}: phpmyadmin

A: I got the solution to this problem, just simple...
All works with rights on folders in Yii.
Applied the chmod command recursively across yii/ directory. The following is the command snippet for reference:
Editors-Mac:Documents cborkotoky$ chmod -R 777 yii
Editors-Mac:Documents cborkotoky$ pwd
/Library/WebServer/Documents
Editors-Mac:Documents cborkotoky$ ls -l
total 80

-rw-r--r--    1 cborkotoky  wheel   3726 Dec 11  2013 PoweredByMacOSX.gif
-rw-r--r--    1 cborkotoky  wheel  31958 Dec 11  2013 PoweredByMacOSXLarge.gif
drwxr-xr-x    5 cborkotoky  wheel    170 Feb 28 23:18 firstProject
-rw-r--r--    1 cborkotoky  wheel     44 Jun 28  2014 index.html.en
drwxrwxrwx@ 112 cborkotoky  wheel   3808 Feb 28 14:03 phpmyadmin
-rw-r--r--    1 cborkotoky  wheel     23 Feb 26 17:59 test.php
drwxrwxrwx    4 cborkotoky  wheel    136 Mar  1 02:03 yii


text:
Q: Need to read input of two JTextfields after a button is clicked I'm working on a program that launches an applet that will demonstrate how the Extended-Euclid algorithm performs. I have two JTextFields that values will be entered in and need to be read/converted to ints, etc. I'm having trouble actually reading the input values to start with.
Updated question:
I've made changes to my code after reading the first answer. Instead of using a DocumentListener I'm doing everything in my actionPerformed method as suggested but when I try testing I'm still getting errors.
This is my current actionPerformed:
public void actionPerformed(ActionEvent event) {
    System.out.println(event.getActionCommand());
    String quotient = "";
    nText = nField.getText();
    mText = mField.getText();

    if("Find GCD".equals(event.getActionCommand())){
        int nInt = Integer.parseInt(nText);
        int mInt = Integer.parseInt(mText);
        int q = mInt/nInt;
        quotient = (Integer.toString(q));
    }
    else quotient = "n/a";
    //NOT the gcd, just to see if this will display
    gcd.setText(quotient);
    gcd.setEditable(false);
}

(note: gcd is another JTextField, but just needs to display the outcome)
Now after clicking my button, I'm getting these errors printed out in the console:

Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
      at EuclidApplet.actionPerformed(EuclidApplet.java:87)
      at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
      at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
      at java.awt.Component.processMouseEvent(Unknown Source)
      at javax.swing.JComponent.processMouseEvent(Unknown Source)
      at java.awt.Component.processEvent(Unknown Source)
      at java.awt.Container.processEvent(Unknown Source)
      at java.awt.Component.dispatchEventImpl(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Window.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
      at java.awt.EventQueue.access$000(Unknown Source)
      at java.awt.EventQueue$1.run(Unknown Source)
      at java.awt.EventQueue$1.run(Unknown Source)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
      at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
      at java.awt.EventQueue$2.run(Unknown Source)
      at java.awt.EventQueue$2.run(Unknown Source)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
      at java.awt.EventQueue.dispatchEvent(Unknown Source)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.run(Unknown Source)

I'm getting a NullPointerException at the line where I set
nText = nField.getText();

but I'm still not sure why I'm not able to get the text that's been inserted into my JTextField. Every example I've found shows that this should work but I can't get it to. Thanks.

A: Solution: don't use a DocumentListener as that's not only overkill, it's wrong. If you want the value on button push, then get the value(s) in the button's action, not from a DocumentListener.  If your getting values from within the button's action listener doesn't work, then let's figure out what you're doing wrong and help you solve that error.
In fact, I see that you tried to do this once, but commented it out:
System.out.println(event.getActionCommand());
System.out.println(event.getID());
String quotient = "";
//nText = nField.getText();  // **** here ****
//mText = mField.getText();  // **** and here ****

so uncomment these lines and get rid of your DocumentListener.
A problem I see below is that you are trying check if Strings are equivalent using the == operator:
if("Find GCD" == event.getActionCommand()){
    int nInt = Integer.parseInt(nText);
    int mInt = Integer.parseInt(mText);
    int q = mInt/nInt;
    quotient = (Integer.toString(q));
}

Don't do this as this can work sometimes and fail at other times.  You don't really care if the two Strings are the same object (which is what the == operator tests), but rather you want to know if they contain the same string data. For this you should use the equals or equalsIgnoreCase method:
if ("Find GCD".equals(event.getActionCommand())) {
    int nInt = Integer.parseInt(nText);
    int mInt = Integer.parseInt(mText);
    int q = mInt/nInt;
    quotient = (Integer.toString(q));
}

A:
I'm getting a NullPointerException at the line where I set nText = nField.getText();

That probably because you defined nField as both a class variable and a local variable. The problem is that you are trying to reference the class variable which is null.
The solution is to get rid of the class variable.


text:
Q: Issues getting the Address API in Play Services 4.3 to work I've setup the Google Play Services 4.4 library in my project and I've been trying to get address picker to show. Here is my activity code to call the API (javadoc):
GoogleApiClient client = new GoogleApiClient.Builder(this).addApi(Address.API).useDefaultAccount().build();
client.connect();
Address.requestUserAddress(client, null, 1000);

And this is my onActivityResult code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1000 && resultCode == RESULT_OK) {
        UserAddress address = UserAddress.fromIntent(data);
        Toast.makeText(this, address.toString(), Toast.LENGTH_LONG).show();
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

Whenever I run the app, no picker is shown and logcat displays this:
05-13 14:30:43.204: D/AddressRetreiver(2489): Is cached profile null?true
05-13 14:30:43.212: W/GLSUser(2505): GoogleAccountDataService.getToken()
05-13 14:30:43.212: W/GLSActivity(2505): [apc] Status from wire: BadUsername status: BAD_USERNAME
05-13 14:30:43.216: E/GetWalletProfileTask(2489): [<<default account>>:1]GoogleAuthException when getting auth token

Does anyone see what is wrong with this code?
Update:
I was using an emulator with GApps installed. I tried a device and that also didn't work. Then I removed the useDefaultAccount() from the GoogleApiClient.Builder call. This worked on my device but not on my emulator. Though now Google Play Services crashes with the following log:
05-14 12:17:38.265: E/AndroidRuntime(10184): FATAL EXCEPTION: main
05-14 12:17:38.265: E/AndroidRuntime(10184): Process: com.google.android.gms.ui, PID: 10184
05-14 12:17:38.265: E/AndroidRuntime(10184): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.google.android.gms/com.google.android.gms.wallet.address.RequestUserAddressActivity}: java.lang.NullPointerException: null reference
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.app.ActivityThread.access$800(ActivityThread.java:145)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.os.Handler.dispatchMessage(Handler.java:102)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.os.Looper.loop(Looper.java:136)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.app.ActivityThread.main(ActivityThread.java:5149)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at java.lang.reflect.Method.invokeNative(Native Method)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at java.lang.reflect.Method.invoke(Method.java:515)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at dalvik.system.NativeStart.main(Native Method)
05-14 12:17:38.265: E/AndroidRuntime(10184): Caused by: java.lang.NullPointerException: null reference
05-14 12:17:38.265: E/AndroidRuntime(10184):    at bkm.a(SourceFile:27)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at com.google.android.gms.wallet.address.RequestUserAddressActivity.onCreate(SourceFile:106)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.app.Activity.performCreate(Activity.java:5231)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-14 12:17:38.265: E/AndroidRuntime(10184):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
05-14 12:17:38.265: E/AndroidRuntime(10184):    ... 11 more

Seems to be an issue with the library.


text:
Q: Are there more even numbers than odd numbers? Very simple 'yes-or-no' question, but I can't find the answer anywhere. My gut feeling says the number of odd and even numbers are equal but I managed to write up something that contradicts my intuition. Although I still think my gut feeling is right, I can't find any logical or mathematical errors with my "proof". Can somebody please look it over and tell me which one of me is right?

Statement 1: For every positive odd integer $o$ there is an even integer $e=o+1$.
Statement 2: For every positive integer $n$ there is an negative integer i.e. $-n$.

Conclusion 1: The number of positive odd integers ($O_{positive}$) is equal to the number of positive even integers ($E_{positive}$). If there is a negative equivalent for every positive integer then the number of negative odd integers ($O_{negative}$) is equal to the number of negative even integers ($E_{negative}$).
In short: $$O_{positive}=E_{positive}=O_{negative}=E_{negative}$$

Statement 3: The number zero is "neutral" (neither positive nor negative).
Statement 4: The number zero is an even integer.

Conclusion 2:
$$\begin{align}
O_{total} & = O_{positive} + O_{negative} + O_{neutral} \\
          & = O_{positive} + O_{negative} + 0 \\
          & = O_{positive} + O_{negative}
\end{align}$$
And:
$$\begin{align}
E_{total} & = E_{positive} + E_{negative} + E_{neutral} \\
          & = E_{positive} + E_{negative} + 1 \\
\end{align}$$
So:
$$\begin{align}
E_{total} & = O_{total} + 1 \\
E_{total} & > O_{total}\\
\end{align}$$
Right? As an engineer I use math daily, but that doesn't make me a mathematician. So please be gentle :)

A: First things first - there are an infinite number of both even numbers and odd numbers.
It's important to realize that $\infty$ (infinity) is not a number. Therefore it doesn't really make sense to talk about the "number" of even or odd numbers, or to write statements like $E_{\rm even}+1$, because that's assuming that $E_{\rm even}$ is a number that you can sensibly add $1$ to.
However, perhaps surprisingly it does make sense to ask if there are more even numbers than odd numbers. That is, you can compare two infinite quantities, or compare a finite quantity and an infinite quantity, even if you can't meaningfully add and subtract infinite quantities.
They way we define more, less and the same for infinite quantities is as follows. For two collections $A$ and $B$ (say $A$ are the even numbers and $B$ are the odd numbers) we say that

*

*If you can associate every item in $A$ with a unique item in $B$, and vice versa, then $A$ and $B$ are the same size.

*If you can associate every item in $A$ with a unique item in $B$, but not vice versa, then $B$ is bigger than $A$.

*If you can associate every item in $B$ with a unique item in $A$, but not vice versa, then $A$ is bigger than $B$.
In your case, you can associate every even number $n$ with the odd number $n+1$, and you can associate every odd number $m$ with the even number $m-1$ (assuming 0 is even) so therefore there are just as many odd numbers as even numbers.
This can lead to seemingly paradoxical results, because e.g. you can associate every whole number $n$ with the even number $2n$, and every even number $m$ with the whole number $m/2$, so there are just as many even numbers as whole numbers, even though the even numbers are a subset of the whole numbers.

A: As there is a bijection
$$
f(x) = x + 1
$$
sending any odd number to an even, this shows that the sets have equal size.
Here, I assumed that the natural numbers start with $1$, if they should start with $0$, simply define the same function on the even numbers.


text:
Q: Making a subdirectory redirect to another file I am working on an instant messaging application for android. I want to create a webpage which redirects the user to a profile inside the application.
So if the user opens "example.com/user/Name", it will redirect him to another page sending the "Name" as an argument. The application handles opening the profile and showing it.
I have got the application working but am unsure how to make the redirecting to work. The Name changes according to the user. What is the best to way to redirect without making multiple directories for each user?
Thanks in advance,
Aditya

A: The question is quite broad. You could try using a JavaScript to post the Name. The script could run on page load, so when the user goes to "example.com/user/Name" the script runs. Get the post function to send Name as a variable whilst redirecting the user?


text: Q: Unable to map the subject to a Salesforce.com user AssertionId I am new on salesforce, working on SAML2.0 using OKTA with salesforce. I have choose Salesforce(Federation ID)application on OKTA and follow the instruction given in OKTA, but failed to login in Salesforce using SAML2.0, It's come back as log out. I checked SAML Validator and find following errors.


text:
Q: In GTK, how do I get the actual size of a widget on screen? First I looked at the get_size_request method. The docs there end with:

To get the size a widget will actually use, call the size_request() instead of this method.

I look at size_request(), and it ends with

Also remember that the size request is not necessarily the size a widget will actually be allocated.

So, is there any function in GTK to get what size a widget actually is? This is a widget that is on-screen and actually being displayed, so GTK definitely has this information somewhere.

A: This should be it (took some time to find):

The get_allocation() method returns a gtk.gdk.Rectangle containing the bounds of the widget's allocation.

From here.


text:
Q: On MAC OS machine. How can we convert date in 2017-01-09T09:35:26Z to Timestamp using shell script I tried some conversion methods but failed. I couldn't interpret the input date format correctly.
Below is the command i used to convert
date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"
And i am looking for a command that works for every Time Zone

A: Well, what a hassle for such a simple question. (PS: I think it was downvoted for not showing an error message, and the use of the OSX tag might better be replaced for macOS if you are on an up-to-date Mac).
The first problem I found out by reading this post. It explains that in order for your command to work the abbreviations need to be in the system language. This can be solved by adding LANG=C in front of your command.
However, your command still delivered the following error:
Failed conversion of ``Tue Sep 28 19:35:15 EDT 2010'' using format ``%a %b %d %T %Z %Y''
date: illegal time format
usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
            [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

Then, when looking into man date I found this line explaining the -f argument:

-f    Use input_fmt as the format string to parse the new_date provided rather than using the default
               [[[mm]dd]HH]MM[[cc]yy][.ss] format.  Parsing is done using strptime(3).

Then, in man strptime I read:

Bugs - The %Z format specifier only accepts time zone abbreviations of
  the local
       time zone, or the value "GMT".  This limitation is because of ambiguity
       due to of the over loading of time zone abbreviations.  One such example
       is EST which is both Eastern Standard Time and Eastern Australia Summer
       Time.

So, I was able to execute your command either like so:
LANG=C date -j -u -f '%a %b %d %T %Z %Y' 'Tue Sep 28 19:35:15 GMT 2010' +%s
Or, like so,
TZ=EDT LANG=C date -j -u -f '%a %b %d %T %Z %Y' 'Tue Sep 28 19:35:15 GMT 2010' +%s
But both aren't actually what you where looking for I guess..
You thus seem to be bitten by a known bug in the default macOS version of strptime.
EDIT
However, if you would have a list with the offset of each timezone (the offset towards GMT), you could do something like:
TZ=EDT LANG=C date -juf '%a %b %d %T %z %Y' 'Tue Sep 28 19:35:15 -0400 2010' +%s
Have a look at this post for more possibilities.


text:
Q: Can Oracle JDBC 11g R2 (11.2.0.3) driver connect to Oracle 10g R10 db I am about to install JDBC 11g R2 driver to connect to Oracle 10g release 10.2.0.4 64bit server.
Is the choice of driver correct ?

A: Yes, no problem, you can connect with 11g jdbc driver to 10g.


text:
Q: Content-Disposition setting for Apache Tomcat 8 In web.xml file of apache tomcat located at "C:\Program Files\Apache Software Foundation\Tomcat 8.0\conf\web.xml", we can set the Content-Type of http header.
I need to also set Content-Disposition, what and where the changes are required for the same?

A: Write a Filter.
An UrlRewriteFilter may help you.
https://wiki.apache.org/tomcat/AddOns


text:
Q: Compiling vim with the breakindent patch, I now have characters that won't display correctly After compiling vim (I really wanted the breakindent feature, which wasn't available in vanilla vim for some reason), it won't display certain characters, like curly quotes or bullet points. Furthermore, it gives me an error for a line that has been commented out in a syntax file: Not an editor command: " Vim Syntax Script. I would have thought it would understand the " in the beginning of the line as indicative of a comment. I don't have these issues is the normal vim from the repos.

A: Your distro likely has other patches applied to vim to make it fit your environment. By compiling it yourself you are missing out on all the work they have done to make it fit your system.
You should probably figure out how to compile using the distro compile system instead of from scratch. Once you can compile the version and patch set from your distros source repository, then you can tweak that process to add your other patch and things should wind up smoother for you.


text:
Q: What is a good method for producing a unary plus/minus sign that always works? Say I have a macro that does something in math mode (say, change the mathalphabet). This macro, \somecommand, takes one argument. I might want use is like this, feeding an empty argument into it: \(\somecommand{} +x\). I also want the plus sign before x to be a unary operator.
I find that whether a plus or minus sign is considered unary or binary is, while clear in theory, not always obvious upon first inspection:
\documentclass{article}

\newcommand{\zeroArgCommand}{}
\newcommand{\oneArgCommand}[1]{}

\begin{document}

\noindent
\(                    +x\) \\ % unary:  "+x"
\(\zeroArgCommand     +x\) \\ % unary:  "+x"
\(\zeroArgCommand{}   +x\) \\ % binary: " + x"
\(\oneArgCommand{}    +x\) \\ % unary:  "+x"
\(\oneArgCommand{}{}  +x\) \\ % binary: " + x"

\end{document}

In the light of this, I am wondering about the best way of defining a unary plus/minus sign.
Intuitively I would write \(\somecommand{} {+} x\) or \(\somecommand{} {+ x}\), but I am wondering about expert opinion about a method that for sure works in all contexts.
This question was posed because in another thread, a user suggested that defining a \unaryplus macro is clearer than \somecommand {+} x. (I think what that commenter had in mind was that the reader might not be familiar with the arity of \somecommand.)

Addendum: Is there a good way to define a macro \genuineunaryplus that produces a + but that in a context <before>\genuineunaryplus<after> attaches to <after> as a unary operator but has spacing to <before> exactly as if the \genuineunaryplus were not there? That is, a macro such that if the spacing between <B> <A> is of length/type L, the expression <B>\genuineunaryplus<A> will produce <B> +<A> in the output, with the spacing between <B> and + exactly like the spacing would be between <B> and <A> if the \genuineunaryplus were not there, namely L?
Answer idea for addendum: David Carlisle's comment below outlines a possible answer for this addendum.

A: The inspection of the math list happens after expansion (and after assignments). It is an extra stage just applicable to math mode that converts the math list into a horizontal list that is then typeset as a normal horizontal list.
So there is no real connection between the macro structure and the math spacing, It does not matter whether the thing to the left of the + has arguments or not, it just matters what it expands to (nothing in your example) so your example is equivalent to
\noindent
\(                    +x\) \\ % unary:  "+x"
\(     +x\) \\ % unary:  "+x"
\({}   +x\) \\ % binary: " + x"
\(    +x\) \\ % unary:  "+x"
\({}  +x\) \\ % binary: " + x"

and as your comments show a binop like + gets binary spacing if it is between two mathord atoms such as {} or x.
Your example (from elsewhere, with \somecommand being a zero-argument macro)
\(\somecommand{} {+} x\)

is
\({} {+} x\)

Here the {+} construct makes a mathord so you get no spacing. My comment that this was probably bad markup was mainly related to the trailing {} after \somecommand it is OK to do that habitually in text mode to avoid dropping spaces but in math mode it's usually has an effect.
\(\somecommand{} {+ x}\)

is
\({} {+ x}\)

so here the math list has two, not three, mathord atoms: {} and +x. In this simple case it doesn't affect the spacing, but the inner expression is a single atom, so {+x} (and not x) would take any superscripts etc, and as it is an inner list linebreaking is suppressed and any white space is forced to its natural width (again not relevant here); basically in math node {...} is a box command like \hbox{....}.
There are in fact two choices for a unary math sign, a mathord or a mathop, it's easy to get an ad hoc mathord by using {+} but it is probably more consistent to declare the operators explicitly.

1 $a-+b$

2 $a-{+}b$

3 $a-\mathord{+}b$

4 $a-\mathop{+}b$

5 $x+y$

6 $x{+}y$

7 $x\mathord{+}y$

8 $x\mathop{+}y$

As you see from (1) if two binop atoms are adjacent the second one effectively turns into a mathord so you get the spacing as in (2) or (3) although arguably as a prefix operator giving it mathop spacing (with a small gap before its argument) is more consistent.
either way you don't want to be filling you document expressions with weird {} constructs and \mathxx primitives, just define
\unaryplus{{+}}

or whatever version you like and then use
a + \unaryplus b

and it will all work out OK.


text:
Q: Django query does not update when database changes I have a weird problem, I think it comes from the cache between django and postgres but not so sure.
I have multiple tables in database but the problem only happens with one of them. Let's say the SpeakingSession table. Everytime I make a change like add a new instance, edit an instance, the call api request does not return the change; the data is only updated when I restart the apache2 server.
For example: I have 7 SpeakingSession records, then I add a new one. But the print command below returns 7.
class SpeakingSessionViewSet(viewsets.ModelViewSet):

    queryset = SpeakingSession.objects.all()

    def list(self, request):
        print(self.queryset.count())
        return super(SpeakingSessionViewSet, self).list(request)

So I restart the apache2 server, then it returns 8.
Any idea how to fix this problem? Thank you very much!
This is my model and my serializer:
class SpeakingSession(models.Model):

    sessionDefinition = models.ForeignKey('SessionDefinition', on_delete=models.CASCADE)
    startTime = models.TimeField()
    endTime = models.TimeField()
    participants = models.ManyToManyField('Profile', default=None, blank=True)

class SpeakingSessionSerializer(serializers.ModelSerializer):

    class Meta:
        model = SpeakingSession
        fields = ('id', 'sessionDefinition', 'startTime', 'endTime', 'participants')

A: Try using Model.refresh_from_db

If you need to reload a model's values from the database, you can use
  the refresh_from_db() method. When this method is called without
  arguments the following is done:
All non-deferred fields of the model are updated to the values
  currently present in the database. Any cached relations are cleared
  from the reloaded instance.

https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.refresh_from_db


text:
Q: How can we resolve "Cannot Edit an Item Outside of the transaction" in LightSwitch? Error: How can we resolve "Cannot Edit an Item Outside of the transaction" in LightSwitch?

Solution: Please your solution and reopen it.
for more detail please click here.

A: I found this error occurs after updating an external data source particularly RIA services. The only workaround I have found is to delete the data source and reimport it with a different name.


text:
Q: Using Case Statements I'm using int[] arrays as a reference. I wondering if my use of case statements is sound or if it will cause errors down the line.
This is my code:
    int switcheroo = intarray[0];
    int foo = intarray[1];
    boolean size = false;
    boolean biggersize = false;

    switch (switcheroo) {

    case 0:
        switch (foo) {
        case 1:
            doSomething(switcheroo); //change switcheroo somehow.
            break;
        case 2:
            doSomethingElse(switcheroo); //change switcheroo differently.
            break;
        }
    case 1:
        size = true;
        break;
    case 2:
        biggersize = true;
        break;
    default:
        break;
    }

Unless it's a coincidence, this is working to ripple the changes from the nested case statement into the other cases, as I want.
My questions are:
Will this nesting causes trouble further down the line?
Is the lack of a break; after a case bad practice?
Thanks.
Edit: The methods which change switcheroo in the middle of the switch statements were put there for responses to that. I will not be doing this is my program.

A: Nesting won't cause trouble down the line exactly, but it can be confusing to read. Adding comments and/or other documentation will really help future coders (and yourself in a week!) understand this by looking at it.
The lack of a break isn't a bad practice by itself, but it is something that -most- case statements have, so I would add a comment at the end like // no break, allow fall-through.
So both cases boil down to good documentation.
These points are perpendicular to the fact that I don't think this code does what you think it will do.
The case clause is not reevalauted every time you come across one - they're just points to jump to for the switch. So in your example, you will always end up in case 1 if you start at case 0 - you'll never end up at case 2 from case 0.
If I were to restructure this, here's what I would do. Instead of using int, I would use enum:
enum Foo { GOOD_FOO, BAD_FOO }
enum Switcharoo { BAR, BAZ, BAQ, ESCAPE }
enum Size { NONE, REGULAR, BIGGER }

Foo foo = ... // assigned somewhere
Switcharoo roo = ... // assigned somewhere
Size size = NONE;

// use a while loop to reevalulate roo with each pass
while(roo != Switcharoo.ESCAPE) {
    switch(roo){
        case BAR:
                switch(foo) {
                    case GOOD_FOO: foo = doSomething(foo); break;
                    case BAD_FOO: foo = doSomethingElse(foo); break;
                }
            break;
        case BAZ:
            roo = Switcharoo.ESCAPE;
            size = Size.REGULAR;
            break;
        case BAQ:
            roo = Switcharoo.ESCAPE;
            size = Size.BIGGER;
            break;

    }
}

A: RE: Is the lack of a break; after a case bad practice?
If you don't include a break after each case statement the flow will continue trough the next statements, so the code for more than one option will be executed.
From the Java Tutorial:

Another point of interest is the break statement. Each break statement
  terminates the enclosing switch statement. Control flow continues with
  the first statement following the switch block. The break statements
  are necessary because without them, statements in switch blocks fall
  through: All statements after the matching case label are executed in
  sequence, regardless of the expression of subsequent case labels,
  until a break statement is encountered.

Check http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html to learn more details about switch statements.

A: In case foo is neither 1 nor 2, is switcheroo supposed to continue to case 1? If yes, your code is correct. If not, you need to add a break before case 1

A: switch operator is a kind of conditional if operator. And a bunch of if operators may report that you need to involve object polymorphism in your code instead of making sequental if-switch operators.
Consider re-arranging your data to classes/objects and process them using polymorphism approach. It will make your code more reliable, more manageable and just more beautiful.

A: Im not sure if i understood your first question, can you give me some more information (concrete maybe)?
Concerning the second question, there's nothing wrong about not having a break statement after a case, as long as you know that the code will continue to execute till it finds a break statement.

A: If there are only 2 alternatives, prefer an if/else. Fewer lines of code and no break issues.

Will this nesting causes trouble further down the line?

A problem is that such switch nesting is hard to read: I had to look at the code twice before I noticed that you were using a nested switch. This can be a maintenance issue, but that isn't a reason not to use a nested switch, just use this sparingly, adjust your indentation to clarify what's going on, and comment on the usage.

Is the lack of a break; after a case bad practice?

Falling through by omitting the  break can also lead to maintenance/debugging issues, but I don't consider it bad practice. It is, after all, intrinsic in the design of the switch statement. A fall through comment is always welcome so that the next guy - or you, revisiting your code months later - knows that the fall-through is intentional.

A: well..It seems the only thing you lack here is readability. Do this type of nesting only if you are forces to do.
Is the lack of a break; after a case bad practice?

not bad rather it is a good practice to avoid unsual behaviour. Your code will continue executing to your last case in absensce of this Break.
Add break in your first outer case too.

A: I'd recommend avoiding nesting and fall-through in combination. At least personally, I tend to expect that every case ends with a break, so I'd use fallthrough only in cases where it's very easy to spot, and leads to clearer code than an if..else, such as:
switch (foo) {
    case 0:
    case 1:
        doSomething();
        break;

    case 2:
        doSomethingElse();
        break;

    default:
        break;
}

That is, with either empty or very simple (one statement) case bodies. In your case, refactoring the body of the first case into a method would probably work:
void changeSwitcheroo(int foo, int switcheroo) {
    switch (foo) {
        case 1:
            doSomething(switcheroo); //change switcheroo somehow.
            break;
        case 2:
            doSomethingElse(switcheroo); //change switcheroo differently.
            break;
    }
}

// ...

int switcheroo = intarray[0];
int foo = intarray[1];

switch (switcheroo) {
    case 0:
        changeSwitcheroo(foo, switcheroo);
    case 1:
        size = true;
        break;
    case 2:
        biggersize = true;
        break;
    default:
        break;
}

(This is mostly arguing readability and style. The meaning of the switch will still be "if switcheroo is 1, jump into the middle of case 0.)


text:
Q: I want to see only my URL in the URL line on a browser I have developed a WEB site www.panos-oliveoil.gr
When a customer surfing in my web site at the URL line watching the full paths from my site folders.
What can I do; regardless where the customer is surfing; in the URL Line to see a Standard Name. Like my web URL only
I'm developing in VB with VS2010; please in case you want to assist me use this Language

A: If you're really trying to have JUST your base url in the navigation bar then you'll have to do some trickery. The url shows for a reason, so you know where you're at. The only way I can think of to trick your browser into only showing the base url is to use iframes. You'd do this like:
<iframe src="www.panos-oliveoil.gr"></iframe>

A: The final solution here is that:
What ever I want to do on my WEB site the URL  must be there sowing the details for the place where the surfer is
Most close to this is the answer from Graham.


text:
Q: Using ActiveRecord to query an aliased association with QueryMethod.references Does anyone know how to query an aliased association table with the #references method in ActiveRecord (Rails 4)? Is this the best way to approach filtering results on an aliased association?
The model with aliases:
class UserReadingLevel < ActiveRecord::Base
  belongs_to :assessor, class_name: "User", foreign_key: :assessor_id
  belongs_to :student, class_name: "User", foreign_key: :student_id
end

in console:
student = FactoryGirl.create :user, roles: ["student"]
teacher = FactoryGirl.create :user, roles: ["teacher"]
tutor = FactoryGirl.create :user, roles: ["tutor"]
rl1 = FactoryGirl.create :user_reading_level, assessor: teacher, student: student, reading_level: "c"
rl2 = FactoryGirl.create :user_reading_level, assessor: tutor, student: student, reading_level: "d"

the attempted query:
assessment = student.user_reading_levels.references(:assessors).where(assessor: { id: 2 })

the error message:
G::UndefinedTable: ERROR:  missing FROM-clause entry for table "assessor"
LINE 1: ...WHERE "user_reading_levels"."student_id" = $1 AND "assessor"...
                                                             ^
: SELECT "user_reading_levels".* FROM "user_reading_levels"  WHERE "user_reading_levels"."student_id" = $1 AND "assessor"."id" = 2

This is the library method I'm trying to use, but it doesn't specify aliased tables:
ActiveRecord::QueryMethods.referencess


text:
Q: Can Civilization 2 be modded/patched to always allow all research options? In Civilization 2 (Specifically ''Civ2: Multiplayer Gold Edition'') is there some way you can edit the rules.txt or something to make it so that when you've given the options to select a tech it will always allow you to select every tech you have the requirements for?
Specifically, when starting a new game, I usually research Code of Laws and Ceremonial Burial, but then Monarchy won't show up right away, and I'll have to research something else before I can research Monarchy.
And it's just really annoying.

A: All technologies for which you have the prerequisites are always available when you're playing a scenario.
So the way to get around the restriction is turn your regular game into a scenario. That is quite easy to do. As soon as you started your game, showing your blinking settler, open the Cheat menu, choose Toggle Cheat Mode and confirm. Then pick the last item in the cheat menu, Save As Scenario. As soon as you've saved it, Quit the game and open your newly saved scenario from the main menu using Begin Scenario.
The only information you get to see about your game that you normally wouldn't is who your opponents are, since you have to pick who to play when you start the scenario. Also, your game may get scored differently or end up being marked as a scenario if it ends up in the Hall of Fame (I forgot how that works), but other than that the game should play about the same. Except of course, that you can choose among all technologies.
If you think this is too much, well, cheating, maybe you'll find it interesting to know that [there's a pattern to which technologies exactly are unavailable. You can find the details described here: http://apolyton.net/showthread.php/2512
In short, depending on the number of technologies you have researched, about one third of all technologies are made unavailable. To be more precise, that is done according to the following table:
2 Advanced Flight      0 Alphabet           1 Amphibious Warfare
2 Astronomy            0 Atomic Theory      1 Automobile
2 Banking              0 Bridge Building    1 Bronze Working
2 Ceremonial Burial    0 Chemistry          1 Chivalry
2 Code of Laws         0 Combined Arms      1 Combustion
2 Communism            0 Computers          1 Conscription
2 Construction         0 The Corporation    1 Currency
2 Democracy            0 Economics          1 Electricity
2 Electronics          0 Engineering        1 Environmentalism
2 Espionage            0 Explosives         1 Feudalism
2 Flight               0 Fundamentalism     1 Fusion Power
2 Genetic Engineering  0 Guerrilla Warfare  1 Gunpowder
2 Horseback Riding     0 Industrialization  1 Invention
2 Iron Working         0 Labor Union        1 The Laser
2 Leadership           0 Literacy           1 Machine Tools
2 Magnetism            0 Map Making         1 Masonry
2 Mass Production      0 Mathematics        1 Medicine
2 Metallurgy           0 Miniaturization    1 Mobile Warfare
2 Monarchy             0 Monotheism         1 Mysticism
2 Navigation           0 Nuclear Fission    1 Nuclear Power
2 Philosophy           0 Physics            1 Plastics
2 Plumbing             0 Polytheism         1 Pottery
2 Radio                0 Railroad           1 Recycling
2 Refining             0 Refrigeration      1 The Republic
2 Robotics             0 Rocketry           1 Sanitation
2 Seafaring            0 Space Flight       1 Stealth
2 Steam Engine         0 Steel              1 Superconductor
2 Tactics              0 Theology           1 Theory of Gravity
2 Trade                0 University         1 Warrior Code
2 The Wheel            0 Writing

If you have not researched any technologies yet (not counting those you got for free at the start), all technologies except the first one that's available (i.e. for which you have the prerequisites) in the second column (marked with zeroes) will be unresearchable. After you discovered one technology, the technologies in the third column become unavailable (except the first one). With two technologies it's the technologies in the first column that are affected. When you have three technologies you're back to missing technologies from the second column etc.


text:
Q: Extracting a single line containing the highest value in a given column from a text file from each consecutively numbered sub-group/family Within my text file, I would like to take the line containing the highest value present in column 3, from each consecutively numbered family (i.e. family_1, family_2 etc.) from column 2 and input these data into a new text file.
Input data:
TTGSCA  family_1    18.123083   681 36349   1
TTGSCA  family_1    18.123083   681 36349   1
CTTRAG  family_2    17.844843   685 37001   1
CTYAAG  family_2    16.95983    657 36170   1
.GCCAAR family_3    19.436863   698 35844   1
WGCCAA. family_3    19.99668    747 38506   1
.GCCAAS family_3    17.037859   599 31922   1
WGCCAA. family_3    19.99668    747 38506   1
CCACTK  family_4    17.200712   776 44550   1
CCACTY  family_4    18.86465    727 38616   1
MCACTT  family_4    18.0871 737 40399   1
MCACTT  family_4    18.0871 737 40399   1
YCACTT  family_4    19.369513   804 43376   -1
CCAYTT  family_4    16.193245   752 44296   1
CCAYTT  family_4    16.193245   752 44296   1
SCACTT  family_4    19.759317   687 34686   1

Output data:
TTGSCA  family_1    18.123083   681 36349   1
CTTRAG  family_2    17.844843   685 37001   1
WGCCAA. family_3    19.99668    747 38506   1
SCACTT  family_4    19.759317   687 34686   1

I'm not sure whether to use grep or awk, and how to combine these into a single function.

A: With GNU datamash (and a little help from cut):
$ datamash -Wf groupby 2 max 3 < file.txt | cut -f1-6
TTGSCA  family_1    18.123083   681 36349   1
CTTRAG  family_2    17.844843   685 37001   1
WGCCAA. family_3    19.99668    747 38506   1
SCACTT  family_4    19.759317   687 34686   1

A: I think datamash is probably the best tool, but here is a sort-unique alternative:
<infile sort -k2,2V -k3,3n | awk 'NR==1 || $2!=p; { p=$2 }'

A: Below is a cleaner way of getting the desired output than my previous answer. It does require sort to be used twice but it's a lot better than having sort, grep, and tail being used four times.
sort -k3r numbers | awk '!seen[$2]++' | sort -k2

Output:
TTGSCA  family_1    18.123083   681 36349   1
CTTRAG  family_2    17.844843   685 37001   1
WGCCAA. family_3    19.99668    747 38506   1
SCACTT  family_4    19.759317   687 34686   1


text:
Q: Merging 2 data frame with matched column names; each matched column next to each other I wish to merge two data frames that have the same length and column names in a way that I can have the values of the columns with the same name next to each other.
A simple example
ex1<-data.frame( c(1:5), c(2:6), c(9:13) )
ex2<-data.frame( c(12:16), c(23:27), c(100:104) )
colnames(ex1)=c("a","b","c")
colnames(ex2)=c("a","b","c")

This would give
> ex1
  a b  c
1 1 2  9
2 2 3 10
3 3 4 11
4 4 5 12
5 5 6 13

> ex2
   a  b   c
1 12 23 100
2 13 24 101
3 14 25 102
4 15 26 103
5 16 27 104

What I want is:
> comb_ex
  a  a b  b  c   c
1 1 12 2 23  9 100
2 2 13 3 24 10 101
3 3 14 4 25 11 102
4 4 15 5 26 12 103
5 5 16 6 27 13 104

Also, once the data frames are merged, how could I rename the columns, mantaining its original name, but adding an index so I could identify from which data frame those values came from?
> comb_ex
  a1 a2 b1 b2 c1  c2
1  1 12  2 23  9 100
2  2 13  3 24 10 101
3  3 14  4 25 11 102
4  4 15  5 26 12 103
5  5 16  6 27 13 104

A: This seems pretty self-explanatory. Look at the help pages for ?cbind.data.frame, ?make.unique, ?'names<-' and ?"[" for further explanation.
> comb <- cbind(ex1,ex2)
> names(comb) <- make.unique(names(comb))
> comb[sort(names(comb))]
  a a.1 b b.1  c c.1
1 1  12 2  23  9 100
2 2  13 3  24 10 101
3 3  14 4  25 11 102
4 4  15 5  26 12 103
5 5  16 6  27 13 104


text:
Q: What Is AVR Mode In UPS Software Management? When UPS was disconnected from power source and 25W desk lamp was connected to it, all was normal:

But as soon as i have unplugged it and plugged in 95W fan, AVR "Normal" changed to up arrow:

Can somebody explain what does up arrow mean?

A: There's a high chance this is related to motors being inductive loads, which can be difficult for an inverter without any form of correction.  Your lamp is a perfect example of a resistive load, so no power-factor correction is required at all.  Devices with transformers (most the equipment you'd usually run on a UPS) start leaning into inductive, but a motor is the textbook example of a difficult load.
I must admit I've little idea why this is manifesting as AVR; usually AVR is used to correct for brownouts (undervoltages) in the supply, so shouldn't be required at all when running on battery.

A: I have UPS with that same software and the AVR mode stands for automatic voltage regulation.
Basically the UPS has internal regulator which is supposed to provide stable voltage when the input voltage does out of a specified range.
The only reason I can think of now that could be causing the AVR to turn on is if somehow the inverter is producing too low voltage at the output so that it needs to pass through AVR. The UP arrow means that AVR is increasing voltage while the DOWN arrow means that AVR is decreasing voltage.


text:
Q: How do I create JSON array in this specific structure This is the array format [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}] I got from my angular form that having a dynamic table with columns name and number respectively.
I want to convert above mentioned array into the below mentioned format to store in database.
"name": [
            {
                "first_name": "Rose",
                "formatted_name": "Rose",
            },
            {
                "first_name": "smith",
                "formatted_name": "Smith",
            },
        ] ,

"phones": [
            {
                "phone": "+919224512555",
                "type": "HOME"
            },
            {
                "phone": "+91975555224",
                "type": "HOME",
            }
        ],

I'm using angular for front-end development and laravel for back-end

A: I think maybe this would be better way of doing it
const data = [
  { name: "Rose", number: "+919224512555" },
  { name: "smith", number: "+91975555224" },
]

const mapped = {
    "name": data.map((item) => ({
        first_name: item.name,
        formatted_name: item.name, // do your own formatting here
    })),
    "phone": data.map((item) => ({
        phone: item.number,
        type: item.number, // do your own processing here
    }))
}

console.log(mapped)

hope it benefits you

A: You could do with Array#reducer

const arr = [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}];

const res = arr.reduce((a,{name,number})=>{
       a.name = a.name||[];
       a.name.push({first_name:name,formatted_name:name});
       a.phones = a.phones||[];
       a.phones.push({phone:number,type:'HOME'});
       return a;
},{})

console.log(res)

A: The below code should do help you restructure your JSON object
const req_body = [
    { name:"Rose", number:"+919224512555" },
    { name:"smith", number:"+91975555224"}
]

const restrutured_body = {
    name: [],
    phone: []
};

req_body.forEach((item) => {
    restrutured_body.name.push({
        first_name: item.name,
        formatted_name: item.name
    });

    restrutured_body.phone.push({
        phone: item.number,
        type: 'HOME'
    });
});

console.log(restrutured_body);


text:
Q: Updating value for \graphicspath within document I am familiar with \graphicspath and have used it in numerous papers where all of my figures are in a single directory.
However, I am now working on a larger project and I have images hierarchically organized by year and month (i.e. all of the images for entries created during July 2016 are in ./Figures/2016/07).
I realize I could generate a long list of folders in the preamble declaration of \graphicspath, but I'd prefer simply updating the setting w/in the document so that for a given section of the document the \graphicspath is {Figures/2016/07} and in the next section it reset to {Figures/2016/08}.
Is there a straightforward way to do this?
UPDATE:  I have added \listfiles to the preamble and updated the body so it has
\makeatletter \show\Ginput@path \makeatother

\graphicspath{{Figures/2016/07/}}

\makeatletter \show\Ginput@path \makeatother

And posted a copy of the .log file here
To me it looks like the new path is used once and then it reverts back to the path set in the preamble which is {Figures/}.
Here's an example.
> \Ginput@path=macro:
->Figures/.
l.3398 \makeatletter \show\Ginput@path
                                       \makeatother
?
> \Ginput@path=macro:
->{Figures/2016/07/}.
l.3402 \makeatletter \show\Ginput@path
                                       \makeatother
?
[94] [95]

...
[97]

Package hyperref Warning: Difference (2) between bookmark levels is greater
(hyperref)                than one, level fixed on input line 3505.

<Figures/2016/07/IMG_0152.JPG, id=2868, 2788.4175pt x 1643.13875pt>
File: Figures/2016/07/IMG_0152.JPG Graphic file (type jpg)

<use Figures/2016/07/IMG_0152.JPG>
Package pdftex.def Info: Figures/2016/07/IMG_0152.JPG used on input line 3515.
(pdftex.def)             Requested size: 430.00653pt x 253.38011pt.

Overfull \hbox (199.15846pt too wide) in paragraph at lines 3514--3516
[]\OT1/cmr/m/n/10.95 Notes on board from our dis-cus-sion. []
 []

...

LaTeX Warning: File `IMG_0161_and_0162_composite.png' not found on input line 3
936.

! Package pdftex.def Error: File `IMG_0161_and_0162_composite.png' not found.

See the pdftex.def package documentation for explanation.
Type  H <return>  for immediate help.

A: There is nothing fancy about \graphicspath. You can use it in the preamble or within the document environment, and update it as you need it.
Note that updating it from
\graphicspath{{<pathA>}}

to
\graphicspath{{<pathB>}}

will remove <pathA> from the selected graphics locations.


text:
Q: How to display a ProgressDialog in an AsyncTask? My Android app got one AsyncTask which gets me data from my server. When I pull a few rows from the database then it's done very fast and I don't need a loading animation while it is getting fresh data.
When I pull 2,3k rows from the database, that might slow things down so I decided to use some indicator (loading animation), so the user knows that data is collecting in the background. I got one activity Fill_in_phone where I call the asyncTask named GetOcitanja.
My code for the AsynTask is:
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

public class GetOcitanja extends AsyncTask<Object, Void, String> {

Activity  _context;
String _str_mesg;
String _str_naslov;
public ProgressDialog progress;
public GetOcitanja(Activity context, String str_naslov, String str_message){
    this._context = context;
    this._str_naslov = str_naslov;
    this._str_mesg = str_message;
}

@Override
protected void onPreExecute() {
    //super.onPreExecute();
    progress = ProgressDialog.show(_context, _str_naslov,
            _str_mesg, true);
    progress.show();

}

@Override
protected void onPostExecute(String s) {
    //super.onPostExecute(s);
    progress.dismiss();
}

@Override
protected String doInBackground(Object... params) {

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpRequest = new HttpGet(Config.url_get_ocitanja_async_taks);
    String odg="";

    try {
        HttpResponse response = httpClient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        odg = EntityUtils.toString(entity, HTTP.UTF_8);

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return odg;
}

As you can see, I put a 2 seconds sleep time to simulate a large dataset. I call this AsyncTask in my Fill_in_Data activity:
GetOcitanja asyncTask=new GetOcitanja(Fill_in_phone.this, "a","b");
asyncTask.execute();
String response="";
try {
        response= asyncTask.get();
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    } catch (ExecutionException e1) {
        e1.printStackTrace();
    }
}

I followed a few solutions from SO and nothing helped. What did I do wrong?

A: Place your ProgressDialog in onPreExecute, sample code below:
private ProgressDialog pdia;

@Override
protected void onPreExecute(){
   super.onPreExecute();
        pdia = new ProgressDialog(yourContext);
        pdia.setMessage("Loading...");
        pdia.show();
}

@Override
protected void onPostExecute(String result){
   super.onPostExecute(result);
        pdia.dismiss();
}

https://stackoverflow.com/a/25998219/5202007

A: public GetOcitanja(Activity context, String str_naslov, String str_message){
    this._context = context;
    this._str_naslov = str_naslov;
    this._str_mesg = str_message;
    progressDialog = new ProgressDialog(_context);
    progressDialog.setTitle("Progress");

}

can you try create progress dialog inside constructor

A:   response= asyncTask.get();

remove that.
You have already an asyncTask.execute().
Handle the response in onPostExecute().
I asked you before how you called your async task as i supposed you used .get(). You are calling it twice and are only showing that now.


text:
Q: How can I set the file output location in ogr2ogr? Whenever I use ogr2ogr to convert files the output is saved to the following directory:
C:\Users[UserName]\AppData\Local\VirtualStore
Is there anyway I can set this directory to something else?

A: You can set the output file location by adding it to the ogr2ogr command arguments; for example:
ogr2ogr -f geoJSON -s_srs EPSG:27700 -t_srs EPSG:4326 c://somedirectory/outputfilename inputfilename


text:
Q: Relational Database tables I have a table Player where playerID is the primary key. Then I have a table Game where gameDate is the primary key (of type DATETIME). Each game is played by 2 players and each player can play many games. So I believe there is a many to many relationship between Player and Game. I want to store both players for each game. I thought of adding player1ID and player2ID on the Game table or to have a bridge table PlayerPlaysGame with playerID and gameDate and then try to find who played the same game so that I get the pair. Any advice as to how I should design my database would be really helpful. Thanks

A: Given that a game can only ever have two players, I suggest the following design:
create table PLAYER
(
  playerid   INTEGER PRIMARY KEY,
  -- add your other columns here
);

create table GAME
(
  gameid     INTEGER PRIMARY KEY,
  gamedate   DATETIME,
  player1id  INTEGER,
  player2id  INTEGER,
  -- add your other columns here
);

If you required a differing number of players per game, then I would have designed it differently - with your requirements there is no need to add an extra table & increase the query complexity.
Also note that I have made gameid the PRIMARY KEY. Using a DATETIME as the PK is generally not a good idea - what would happen if two games were created simultaneously?
You'll also probably want to add foreign keys to/from GAME.player1id/player2id and PLAYER.playerid.


text:
Q: How to use setInterval with react useEffect hook correctly? I tried to create a simple timer app with ReactJS and found the below code on the internet.
Does the function that we passed to the useEffect will execute with the dependency change or does it recreates with every dependency change and then execute?
Also I console log the return function of the useEffect and it runs with every render. Does it run only when the component unmount? or with every render?
import { useEffect,  useState } from "react";

const App = () => {
  const [isActive, setIsActive] = React.useState(false);
  const [isPaused, setIsPaused] = React.useState(true);
  const [time, setTime] = React.useState(0);

  React.useEffect(() => {
    let interval = null;

    if (isActive && isPaused === false) {
      interval = setInterval(() => {
        setTime((time) => time + 10);
      }, 10);
    } else {
      clearInterval(interval);
    }
    return () => {
      console.log("cleanup");
      clearInterval(interval);
    };
  }, [isActive, isPaused]);

  const handleStart = () => {
    setIsActive(true);
    setIsPaused(false);
  };

  const handlePauseResume = () => {
    setIsPaused(!isPaused);
  };

  const handleReset = () => {
    setIsActive(false);
    setTime(0);
  };

  return (
    <div className="stop-watch">
      {time}
      <button onClick={handleStart}>start</button>
      <button onClick={handlePauseResume}>pause</button>
      <button onClick={handleReset}>clear</button>
    </div>
  );
};

export default App;

A: The code inside the useEffect hook will run every time a dependency value has been changed. In your case whenever isActive or isPaused changes state.
This means that the reference to the interval will be lost, as the interval variable is redefined.
To keep a steady reference, use the useRef hook to have the reference persist throughout state changes.
const App = () => {
  const [isActive, setIsActive] = useState(false);
  const [isPaused, setIsPaused] = useState(true);
  const [time, setTime] = useState(0);
  const interval = useRef(null)

  useEffect(() => {
    if (isActive && !isPaused) {
      interval.current = setInterval(() => {
        setTime((time) => time + 10);
      }, 10);
    } else {
      clearInterval(interval.current);
      interval.current = null;
    }

    return () => {
      clearInterval(interval.current);
    };
  }, [isActive, isPaused])

  ...
}