text:
Q: HTTP framework for a python based server serving mobile applications I am working on building a python powered back-end server for a mobile application. I am using MongoDB hosted on the Cloud for storage. The communication between the Application and the server will be mostly JSON. There wont be any HTML involved in this transfer as such.
I am looking for a framework to build my server. I did some research and found (django, Pylons etc) are for full stack server and is not needed for my requirements.
I am confused on how to go about selecting an HTTP framework (web.py, cherrypy etc).
also, i might use Mongoengine as the ODM. I am not sure if this decision is anyway going to affect the framework selection
any ideas?

A: I'd recommend bottle or flask, both of which are very minimal and impose no constraints on you whatsoever. In the case of bottle, it's particularly easy to build a simple RESTful server since it will automatically return JSON from a route that returns a dict:
from bottle import route, run

@route('/user_info/:id'):
def user_info(id):
    user = get_user(id)  # ...do something, lookup user, whatever
    return {'first_name': user.first_name, 'last_name': user.last_name}

run()

A: Pyramid Framework doesnt enforce a templating engine (not a full stack) or a persistence/storage system. It has json and jsonp renderer (no html at all).
It also has a scaffold for jquery mobile app (I havent tried this, so I dont know).

A: I personally prefer web.py, but in your case it is possible to start with basic wsgi app, or something simple as http://werkzeug.pocoo.org/ because it doesn't enforce a specific template engine or database adapter.


text:
Q: print date on same line as other variables in printf I am trying to use system("date") in printf but I would like it on the same line and I do not know how to format it properly. Any suggestions.
printf("Temperature %.2f date %d \n", val, system("date"));

A: The system function returns the exit status of the given external command, which if successful will typically be 0.  The specific command being run is outside of your process so you don't have too much control over what it outputs.
Rather than call an external command, there are functions you can call to get the information you want.
You need to first use the time function, which gives you the time in seconds since the UNIX epoch of 1970-01-01 00:00:00 UTC.  Then pass this to the ctime function which gives you a text representation of the time:
time_t t = time(NULL);
printf("date is %s", ctime(&t));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changes to kotlin class not recognized by Spring Boot? Changes are not reflected in the service response from http://localhost:8080/hi after:

*

*Modifying the response string of SomeController in the code below

*Spring Tool Suite automatically compiles the changes

*Spring Boot DevTools automatically restarts the server

*Request to http://localhost:8080/hi still gives the old response

Somehow they're getting cached, even after running ./gradlew build manually.
Totally different issues: I have Java 1.8 JRE and JDK installed into two directories under Program Files\Java. The project shows the JRE dependency and running build from STS Gradle Tasks window yields the JRE instead of the JDK, even though JAVA_HOME is properly set to the JDK, STS is configured to use the JDK by default (JRE unchecked), and the Spring Boot Project is configured to use the workspace settings (JDK). It seems to be picking up the JRE from the IDE runtime itself, instead of from the settings? I found a work-around by right-clicking the build task and selecting build -> Open Gradle Run Configuration -> Java Home and manually setting this to the same directory as the JDK. I also found a workaround for the project with right-click on project Properties -> Java Build Path -> Libraries, removing JRE System Library and adding the JDK (Add Library... -> JRE System Library -> Workspace default JRE (jdk1.8.0_144)). But, sometimes the project resets itself to the JRE somehow.
Gradle Distribution: Gradle wrapper from target build
Gradle Version: 4.5.1
Java Home: C:\Program Files\Java\jre1.8.0_171

Code
package com.example.demo

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class SomeController {
    @GetMapping("/hi")
    fun hi(): String {
        return "hey"
    }
}

@SpringBootApplication
open class DemoApplication

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}

Configuration

*

*Windows 10 Pro

*Spring Tool Suite 3.9.4.RELEASE

*JDK 1.8

*Kotlin 1.2.41

*Gradle Wrapper 4.5.1

*Spring Boot + DevTools 2.0.3.RELEASE

Setup Steps

*

*New workspace in STS with Gradle Buildship and Kotlin extensions

*Add JDK 1.8 as default

*Create project File -> New -> Spring Starter Project

*

*Gradle (Buildship 2.x)

*Java 8

*Kotlin

*Reactive Web

*DevTools

*Actuator

*Right-click project Configure Kotlin -> Add Kotlin Nature

*Start service Boot Dashboard -> local -> demo [devtools] [:8080]


text:
Q: How to import from sibling module in a package, no changes in module files allowed? Given a folder structure below. Files a.py and b.py generated and can not be changed. File b.py imports file a.py. Init file is empty (can be changed). Using my_package getting an error in b.py:
ModuleNotFoundError: No module named 'a'
How to fix this?
.
└── src
    ├── main.py
    └── my_package
        ├── a.py
        ├── b.py
        └── __init__.py

A: __init__.py :
import sys
sys.path.extend(pkg_directory)
import a
import b

a.py :
def hello():
    print('Hello')

b.py :
import a

test:
>>> import pkg
>>> pkg.a.hello()
Hello
>>> pkg.b.a.hello()
Hello

A: The answer form Derek Eden worked for me. Want to extend it with package init file content I used.
my-package __init__.py file:
import sys
import os.path

this_pkg_path = os.path.dirname(__file__)
sys.path.append(this_pkg_path)

import a
import b


text:
Q: multibar property gives access violation I am creating a barseries programmatically (Delphi2007, TeeChar 7 free edition). I'd like to have adjacent bars in my graph, so I try to create multiple barseries and use the multibar property.
When setting multibar property in main_unit, I get access violation (when debugging, if I inspect the barseries object, I can see the multibar property as "out of bound").
I don't get the error only if I set the property in the unit where the barseries was created. How I can manipulate the barseries externally? Do I have to set a property fotr this purpose in unit1?
Here is a snippet of my code:
unit unit1
type TMyChart = Class
fchart: TChart;
procedure addSinglebarSeries(var X, Y: integer)
....
implementation
function TSignalchart.addSinglebarSeries(var X, Y: integer): TBarSeries;
j, n : integer;
begin
   result := TBarSeries.Create(fChart);
   result.AddXY(x,Y,inttostr(x), clRed);
   barseries.MultiBar := mbStacked;  //here no access violation
end;

----
unit main-unit

implementation
uses TeEngine, TeeProcs, unit1;
procedure myprocedure;
var
 newChart : TMyChart;
 X, Y := array of integer;
 barseries : TBarSeries;
 aX, aY, i: integer;

begin
 //I create the newchart object, I create X, Y

  for i := 0 to length(X) - 1 do
    begin
      aX := X[i];
      aY := Y[i];
      barseries := newChart.addsinglebarSeries(aX,aY);
    end;
   //barseries.MultiBar := mbStacked; //access violation!!
  end;

A: Here's an example of adding 5 multibar stacked series in a TeeChart (D2007). Chart1 is a TChart component dropped from the component palette, and Button1 is a standard TButton placed the same way:
// D2007+ way to easily initialize dynamic arrays
type
  TIntArray=array of Integer;

procedure TForm1.Button1Click(Sender: TObject);
var
  BarSeries: TBarSeries;
  X, Y: TIntArray;
  i: Integer;
begin
  X := TIntArray.Create(1, 2, 3, 4, 5);       // SetLength and initialize rolled into one
  Y := TIntArray.Create(10, 20, 30, 40, 50);  // Nonsense values, of course.
  Chart1.SeriesList.Clear;
  for i := Low(X) to High(X) do
  begin
    BarSeries := TBarSeries.Create(Chart1);
    BarSeries.AddXY(X[i], Y[i]);
    BarSeries.MultiBar := mbStacked;
    Chart1.AddSeries(BarSeries);
  end;
end;

Here's the form after clicking Button1:


text:
Q: AJAX call on dropdown value doesn't display data I am new to using AJAX call function and I am trying to figure out why my dropdown list does not display the data from my database. Okay, the scenario is that I have 2 dropdown list in my form. the first is to select a 'Specialization' and the second is to select a doctor. When I select a specialization, it will load the list of doctors under that particular specialization. The function of the AJAX call is to call the doctors' name in the doctor dropdown list. I am unable to make the list of doctors appear in my dropdown list.
Here are the code for my specialization dropdown list:

  Doctor Specilization
  <select name="specilization" id="specilization" onBlur="getspec()" autocomplete="off" required>
    <?php
                  $sqlspecili = "SELECT S_NAME FROM tblspecilization";
                      $speciliquery = $dbh -> prepare($sqlspecili);
                      $speciliquery->execute();
                      $speciliresults=$speciliquery->fetchAll(PDO::FETCH_OBJ);
                      $specilicnt=1; ?>

    <option selected hidden value="">Select specialization</option>
    <?php if($speciliquery->rowCount() > 0) {
                        foreach($speciliresults as $speciliresults) { ?>
    <option value="<?php echo htmlentities($speciliresults->S_NAME);?>">
      <?php echo htmlentities($speciliresults->S_NAME);?> </option>
    <?php $specilicnt=$specilicnt+1;
                          }
                        } ?>
  </select>

And this is the code for my doctor dropdown list:

  Select Doctor
  <select name="doctor" id="get_doctor_name" autocomplete="off" required>
  </select>

This is the script for my AJAX call:

This is the get_doctor.php which is called in the AJAX call:
<?php
include('incl/conn.php');
if(!empty($_POST['specilization']))
{
    $specilization =:$_POST['specilization'];

    $sql = "SELECT D_ID, D_NAME FROM tbldoctor
            WHERE D_SPECILIZATION=:specilization";

    $query = $dbh->prepare($sql);
    $query->bindParam(':specilization',$specilization,PDO::PARAM_STR);
    $query->execute();
    $results=$query->fetchAll(PDO::FETCH_OBJ);
    $cnt=1;
    <option selected="selected">Select Doctor</option>
    if($query->rowCount() > 0)
    {
        foreach($results as $results)
            { ?>
            <option value="<?php echo htmlentities($results->D_ID);?>" >
                <?php echo htmlentities($results->D_NAME);?>
            </option> <?php
            }
    }
    else
    { ?>
        <option value=""> No Doctor in this specilization</option>
        <?php echo "";
    }
}?>

This is the SQL table for tbldoctor:
CREATE TABLE `tbldoctor` (
  `D_ID` int(11) NOT NULL,
  `D_SPECILIZATION` varchar(255) NOT NULL,
  `D_NAME` varchar(255) NOT NULL,
  `D_GENDER` varchar(255) DEFAULT NULL,
  `D_ADDRESS` longtext DEFAULT NULL,
  `D_FEES` varchar(255) DEFAULT NULL,
  `D_CONTACTNO` varchar(255) DEFAULT NULL,
  `D_EMAIL` varchar(255) DEFAULT NULL,
  `D_USERNAME` varchar(255) NOT NULL,
  `D_PASSWORD` varchar(255) NOT NULL,
  `D_CREATIONDATE` timestamp NULL DEFAULT current_timestamp(),
  `D_LASTLOGIN` varchar(255) DEFAULT NULL
)

This is the table for tblspecilization:
CREATE TABLE `tblspecilization` (
  `S_ID` int(11) NOT NULL,
  `S_NAME` varchar(255) NOT NULL,
  `S_CREATIONDATE` timestamp NOT NULL DEFAULT current_timestamp()
)

A: don't make it too complex .there are multiple  ways to do this, but this echo "<option value="<?php echo htmlentities($results->D_ID);?>"><?php echo htmlentities($results->D_NAME);?></option> <?php";  is wrong
dont confuse yourself with closing,opening of php tags, try the following
<?php
include('incl/conn.php');
if(!empty($_POST['specilization']))
{
    $specilization =:$_POST['specilization'];

    $sql = "SELECT D_ID, D_NAME FROM tbldoctor
            WHERE D_SPECILIZATION=:specilization";

    $query = $dbh->prepare($sql);
    $query->bindParam(':specilization',$specilization,PDO::PARAM_STR);
    $query->execute();
    $results=$query->fetchAll(PDO::FETCH_OBJ);
    $cnt=1;
    echo '<option selected="selected">Select Doctor</option>';
    if($query->rowCount() > 0)
    {
        foreach($results as $results)
            {
            echo '<option value="'.htmlentities($results->D_ID).'">'. htmlentities($results->D_NAME).'</option>';
            }
    }
    else
    {
       echo '<option value=""> No Doctor in this specilization</option>';
       echo "";
    }
}
?>


text:
Q: Nginx + Cloudflare. Работает www.somedomain.spb.ru, но не работает somedomain.spb.ru Достаточно трудная для меня проблема. Не могу ее пока решить самостоятельно. Все делал по инструкциям. В файлах cert.pem, key.pem валидные ключи. Проверял инструкциями:
openssl rsa -check -in private.key -noout
openssl req -in /etc/ssl/cert.pem -text -noout

Настройки домена в Nginx тоже, один в один.
server {
listen 80;
listen [::]:80;
server_name stb.spb.ru www.stb.spb.ru;
return 302 https://$server_name$request_uri;
}

server {

# SSL configuration

listen 443 ssl http2;
listen [::]:443 ssl http2;
ssl_certificate /etc/ssl/cert.pem;
ssl_certificate_key /etc/ssl/key.pem;
#ssl_client_certificate /etc/ssl/cloudfare.crt;
#ssl_verify_client on;

server_name stb.spb.ru www.stb.spb.ru;

root /var/www/stb.spb.ru/html;
index index.html index.htm index.nginx-debian.html;

location / {
try_files $uri $uri/ =404;
}
}

На cloudflare настроены следующие DNS records:
А stb.spb.ru 84.38.183.29
CNAME www stb.spb.ru

Есть два подозрения, либо что не хватает нужного record для домена без www, либо генератор ключа cloudflare не совсем корректно генерирует сертификат для домена с поддоменом *.spb.ru


text:
Q: WPF databound TextBox cursor position resetting. Possible bug? So I'm having this weird problem. I have a TextBox bound to the ViewModel :
<TextBox DockPanel.Dock="Right" Text="{Binding Path=FilterText, UpdateSourceTrigger=PropertyChanged}"/>

With the content of FilterText, I am filtering a ListBox (which is bound to an ObservableCollection).
Now everything works fine. But after each keystroke, the cursor position of this TextBox keeps resetting to the beginning. And this is happening only with this particular TextBox. I have other bound TextBox working just fine.
I googled it, and found that this happens in .NET4.0. But mainly when there is a string formatting or string to double conversion is involved. But FilterText is simple String property and no double variable is involved anywhere.
Here is the code :
private String _filterText;
public String FilterText
{
    get { return _filterText; }
    set
    {
        if (_filterText != value)
        {
            _filterText = value;
            RaisePropertyChanged("FilterText");
            FilterList(); //this method works fine
        }
    }
}

Can someone please explain why this is happening?
The solutions suggested somewhere else includes changing UpdateSourceTrigger to LostFocus or using an attached behavior to manually set the cursor location. Is there any other simpler solution? Or is this just a bug?

A: Got your source-code and could reproduce the issue. However it wasn't one of those .NET 4 issues cos it had the same issue in .NET 4.5. Actually turns out it's not an issue in .NET at all.
In ManageQuestionViewModel.cs
switch
public void Initialize() {
...
  this.ViewCore.FocusQuestionData();
}

to
public void Initialize() {
...
  // this.ViewCore.FocusQuestionData();
}

you're done :)
oh and you do not need that ResetCaretBehavior you've added to try and work-around this anymore as well


text:
Q: why getting the error "The selector did not match any elements"? my index.html body:
  <body>
    <my-forget>Loading...</my-forget>

    <router-outlet></router-outlet>

    <script>
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            }
        });
        System.import('app/boot')
                .then(null, console.error.bind(console));
    </script>
    </body>
    </html>

and forget.component.ts:
import {Component} from 'angular2/core';
import{RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {LoginComponent} from './login.component';

@RouteConfig([
  {path:'/app', name:'login-page', component:'LoginComponent'},
  {path:'/*other', name:'other', redirectTo:['login-page']}
])

@Component({
  selector: 'my-forget',
  templateUrl: '../templates/forget.component.html',
  directives: [ROUTER_DIRECTIVES]
})
export class ForgetComponent {

}

Ignore routing parts.
I'm getting the following errors:
 Error: Uncaught (in promise): The selector "my-login" did not match any elements
The selector "my-login" did not match any elements
I don't have my-login in these files and i don't need it!
What is wrong?


text:
Q: Recommendations on creating a GUI for an XML configuration file I want to create a Windows GUI to allow the user friendly editing of a configuration that is stored in XML. The XML uses nested elements, typically with attributes for configuration values, in a conventional way. Designing and creating a GUI (probably in C# using a tree control to show the overall structure and a PropertyGrid to edit specific properties) would be a reasonable amount of work. It also seems wrong, to me, to create a completely bespoke application when the problem could be solved much more generally with the XML schema and some additional 'metadata'.
Is anyone aware of any frameworks or libraries (open source ideally, but I would consider commercial at the right price) that would provide a basis for an 'XML configuration file' GUI application?

A: We decided to go the 'C# application with tree control to show overall structure and PropertyGrid to edit specific properties' route in the end. It was less work than we'd anticipated - once the basic application structure was there, we simply added classes for each of the objects that we wanted to be configurable. Each class exposes properties that can be edited by the PropertyGrid, and is responsible for reading/writing its properties to XML in the appropriate format. There may have been easier ways, but this gave us plenty of control without being too time-consuming.
We found the following resources useful during development:

*

*Ordering items in a property grid - http://www.codeproject.com/Articles/6611/Ordering-Items-in-the-Property-Grid

*Controlling the description area height - http://www.codeproject.com/Articles/31497/Gain-Control-Over-PropertyGrid-s-Description-Area

*Solid-dragging splitter - Refresh the panels of a SplitContainer as the splitter moves

A: I'd use XForms, which is available in a number of free and a number of commercial applications (the sets are not disjoint).  You might start by looking at XSLTForms, Orbeon, BettterForms, and EMC Formula.


text:
Q: Fiddler does not capture in the Production environment  Fiddler is suppose to capture/trace https trafic which it does when I run the same in our development and test environment but the same does not trace any information when run in the production environment.
I crosschecked the setting of Fiddle Options, Internet Options and even the WebSite Options in IIS and it is very much similar still I don't understand why it does not trace the traffic in the production enviornment.
Also, at the same time it does not show any errors or warnings for me to trouble shoot further.
Please let me know what should I check for ???
Thanks Again.

A: A problem I've sometimes run into with missing traffic is that the service sending the requests needs to be running under the same account as the person attempting to monitor the traffic (i.e, your account). Go to Computer Management, services, right-click the service in question and modify it to execute using your credentials. You may need to exit and restart Fiddler.


text:
Q: Finding the moment a thrown object is the closest to a point The arc of a thrown object with the initial horizontal speed $v_x$, the initial vertical speed $v_y$ and a gravity of $\frac{625}{64}$ can be described with
$$
x(t) = v_x * t \\
y(t) = v_y * t - \frac{625}{128} * t^2
$$
The difference of the point I want to know the distance and the initial position of the thrown object is $(D_x, D_y, D_z)$.
To make things easier, I work with the square of the distance since the extremes stay at the same $t$. The direction the object is thrown is set with $\alpha$.
$$
d_{square}(t) = (D_x - (t * v_x * cos(\alpha)))^2 + (D_y-y(t))^2 + (D_z - (t * v_x * -sin(\alpha)))^2
$$
Now I derivate $d_{square}(t)$ and set it to zero to find the extremes of $d_{square}(t)$. I search for the last derive's root since I expect it to be what I am looking for.
$$
d'_{square}(t) = 2*(v_x*(D_z*sin(\alpha) - D_x*cos(\alpha) + t*v_x) + (y(t) - D_y)*y'(t))\\
0 = v_x*(D_z*sin(\alpha) - D_x*cos(\alpha) + t*v_x) + (y(t) - D_y)*y'(t)\\
y'(t) = v_y - t * \frac{625}{64}
$$
Now I realize that these put together will result in an ugly cubic function I can't just find roots of without investing some time, and I am not certain how to proceed from there, but I noticed something strange when I asked Wolfram Alpha to find $t$ anyway:
$$
t_{extrema}≈0.10240 * v_y
$$
The approximate roots of the derivate are pretty much always $\frac{v_y}{gravity}$ according to the site with some tiny variations in wild square and cubic roots in the exact result. This surely can't be right, all the other variables have to be significant as well here. Did I do something wrong to this point?


text:
Q: How remove rows of html table? I want to refresh the table but every time the setinterval active the append insert the same rows again, i want that those rows get removed for the new ones
    $(document).ready(function()
{

    function actualizar()
    {
    $.ajax({
        type: "GET",
        url: "editinplace.php?tabla=1"
    })
    //Vector
    .done(function(json)
    {
        json = $.parseJSON(json)
        for(var i=0;i<json.length;i++)
        {
            $('.editinplace').append
            (
                "
"
                +json[i].id
                +"	"
                +json[i].nombre
                +"	"
                +json[i].apellidos
                +"	"
                +json[i].telefono
                +"	"
                +json[i].status
                +"
");
        }
        //
    });

    }
    setInterval(actualizar, 6000);

A: .append will, as the name suggests, append content.
Either do something like $('.editinplace tr').remove(); to remove all the existing rows before appending, or replace .editinplace entirely:
$('.editinplace').replaceWith("
"
+  "
"
...
+ "
");

See http://api.jquery.com/remove/ and http://api.jquery.com/replacewith/ for more info.
Ref comments, for testing the existence, I'd add a data attribute to the rows so that you could search for them easily. E.g. replace "
" with "
".
Then in your for() loop, simply check if it exists yet:
if ($('.editinplace tr[data-id="' + json[i].id + '"]').length == 0) {
    // append
}


text:
Q: Why won't python print this string? It returns fine Python won't print this formatted string. It gripes about a syntax error immediately after the second quote. On the other hand, when I return the same string, it does just fine. I'm probably being dumb, but what's the issue here?
print '{0} lands by turn {1}: {2}'.format(lands, turn, land_drop_prob(lands, turn, lands=lands_in_deck, deck_size = 60))

As mentioned before, if I change "print" to "return", the string returns just fine.

A: Your syntax should works with python 2.X. However, with python 3.X, print syntax has changed. You have to write print("blabla") instead of print "blabla".
>>> print '{0} lands by turn {1}: {2}'.format("a", "b", "c")
  File "<stdin>", line 1
    print '{0} lands by turn {1}: {2}'.format("a", "b", "c")
                                     ^
SyntaxError: invalid syntax
>>> print('{0} lands by turn {1}: {2}'.format("a", "b", "c"))
a lands by turn b: c
>>>


text:
Q: Associate Elastic IP while creating an EC2 Instance using Node.js Is there a way I can specify an existing Elastic IP in the Lambda function that creates an instance of a Windows Server?
I am looking at the documentation at http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#runInstances-property but i do not see any mention of Elastic IP assignment.

A: Elastic IP addresses can only be assigned to an EC2 instance after it has been launched.

*

*Use runInstances to launch your EC2 instance and retrieve the EC2 instance ID.

*Use associateAddress to assign your Elastic IP address to your EC2 instance.


text:
Q: Issue sending JSON from array to web service on Angular I have a table. Every cell of the row tables are form fields. Also, I have two buttons: one button add a new row to the table and a second one whitch send all the rows.
This is for add new blank rows:
$scope.atributs =[];

$scope.addRow = function(){
     var newRow = {nomAtribut: "",tipus: "",mida: "",prioritat: "",obligatori: "",observacions: ""};
$scope.atributs.push(newRow);
                        }

View :

               Nom atribut
                Tipus
                Mida
                Prioritat
                Obligatori
                Observacions

                 <input type="text" ng-model="atribut.nomAtribut" />

                   <select ng-options="option as option.valor for option in options" ng-model="atribut.tipus"></select>

                 <input type="number" ng-model="atribut.mida" />

                     <select ng-options="option as option.valor for option in options" ng-model="atribut.tipus"></select>

                  <input type="checkbox" ng-model="atribut.obligatori" ng-true-value="'YES'" ng-false-value="'NO'">
                  <input type="text" ng-model="atribut.observacions" />

Angular Code for sending data to web Service  :-
$scope.sendRow = function(){
 $http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", $scope.atributs).success(function(data){
                        $scope.status = data;
                    })
                }

Json Array Sending:-
 [{"nomAtribut":"j",
 "tipus":{"idvalors_combo":"3","valor":"Date"},
  "mida":11,"prioritat":"",
  "obligatori":"YES",
  "observacions":"fcefwq"}]

Is all correct and the problem come from the web service? or the angular code is wrong? It's my first try with angular. Thank you.

A: So it looks like your web service wants a single element from your data array at a time.
I think you should modify the sendRow function to take the row index you want to send, like so:
$scope.sendRow = function(atributRow){
 $http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", atributRow).success(function(data){
                        $scope.status = data;
                    })
                }

Then, you can send all rows in a loop by:
angular.forEach($scope.atributs, $scope.sendRow);

or a single row with a specific index:
$scope.sendRow($scope.atributs[0])


text:
Q: Web service not work in loob success I want to use web service to make more webmethod .But it go to loop error in javascript. What is wrong code in web service. If i make web medthod in codebehide my code is work fine. what's wrong when i want to check debug code in web service it can't debug my code in web service. it hard to say,but if u see my code i think u will understand more.
This is my code ajax in javascript
 $.ajax({
            url: "report.asmx/GetreportDoctor",
            data: "{}",
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset-utf-8",
            success: OnSuccess,
            error: OnError
        });
        //for get selected value from codebehide
        $('#<%= ddReport.ClientID%>').change(function () {
                $('#<%= hfSelectedValue.ClientID%>').val($('#<%= ddReport.ClientID%>').val());
            });
    });
    function OnSuccess(data) {
        $('#<%= ddReport.ClientID%>').empty();
        var dt = $.parseJSON(data.d);
        var dropdown = $('#<%=ddReport.ClientID%>');
        var order = "";
        var test = dt.Table1[0][1];
        var num = dt.Table1.length;
        var optGroup;

    }
    function OnError() {
        alert("Failed!!!");
    }

And this is my webmethod code in web service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
 [System.Web.Script.Services.ScriptService]
// implementation
 public class report : System.Web.Services.WebService{
[WebMethod]
    public static string GetreportDoctor()
    {
        String daresult = null;
        SqlDataReader dr;
        DataTable dt = new DataTable();
        DataSet ds = new DataSet();

        SqlConnection EMR_Conn = new SqlConnection(@"Data Source=192.168.24.36;Initial Catalog=EMR;Persist Security Info=True;User ID=sa;Password=bpk$1234");
        EMR_Conn.Open();
        SqlCommand cmd_select = new SqlCommand("select rowID, code, create_by FROM MED_main where type = 1 order by create_by", EMR_Conn);
        dr = cmd_select.ExecuteReader();
        dt.Load(dr);
        ds.Tables.Add(dt);
        daresult = DataSetToJSON(ds);
        return daresult;
    }
    private static string DataSetToJSON(DataSet ds)
    {
        Dictionary<string, object> dict = new Dictionary<string, object>();
        foreach (DataTable dt in ds.Tables)
        {
            object[] arr = new object[dt.Rows.Count + 1];

            for (int i = 0; i <= dt.Rows.Count - 1; i++)
            {
                arr[i] = dt.Rows[i].ItemArray;
            }

            dict.Add(dt.TableName, arr);
        }

        JavaScriptSerializer json = new JavaScriptSerializer();
        return json.Serialize(dict);
    }
  }

this is result when i run web service
This web service is using http://tempuri.org/ as its default namespace.
Recommendation: Change the default namespace before the XML Web service is made public.
How can i do when i create webmethod in codebehide is work fine but i can not add more webmedthod in code behide .if it can please tell .thank you so much.


text:
Q: What's this symbol mean? I know its probably been answered before, but I'm not really sure what to google to find the answer.

A: It indicates position tolerance in inches and (mm).
More info on this pdf.

As comments in the question and this answer point out, the "M" in a circle stand for "Maximum Material Condition", as in largest pin width or smallest hole.

A: Which is a Drawing layout for the Machining, with the GD&T positioning tolerance
The position tolerance M symbol represents Maximum material condition If there is L symbol That represents Least Material Condition.


text:
Q: Why in Quotient Group we need normal subgroup? For a group $G$ and a normal subgroup $N$ of $G$, the quotient group of $N$ in $G$, written $G/N$ and read "$G$ modulo $N$", is the set of cosets of $N$ in $G$.
Question : Why in the defintion of Quotient Group we need subgroup $N$ to be normal?

A: Let $G$ be a group and let $e$ denote its identity.
Forming a quotient $G/\sim$ of group $G$ is actually forming a partition on $G$ such that $[a][b]=[ab]$ is a well defined multiplication. Here $[a]$ and $[b]$ are elements of the partition that are represented by $a\in[a]$ and $b\in[b]$ respectively.
The multiplication is well defined if $[a'b']=[ab]$ whenever $a'\in[a]$ and $b'\in[b]$. Further it is not difficult to prove that $[e]$ will be a subgroup and will work as identity of the quotient.
Now if $a\in[e]$ and $g\in G$ then we find $$[gag^{-1}]=[g][a][g^{-1}]=[g][e][g^{-1}]=[geg^{-1}]=[e]$$This proves the necessity of: $$a\in[e]\implies gag^{-1}\in[e]$$
So $[e]$ is bound to be a normal subgroup.

A: We define the multiplication of two cosets $gN$ and $hN$ to be $ghN$. So, if $N$ is not a normal subgroup of $G$, then this multiplication will not be well defined, i.e. there may be two different and non-equal values for $(gN)(hN)$.

A: That is to have a well-defined group law on the quotient: for $a,b\in G$, we need to check that , if $a'\equiv a\mod H$,  $b'\equiv b\mod H$*, we want that $a'b'\equiv ab\mod H$.
Explicitly, this means that, if $a'=ah$, $\;b'=bk\;$ for some $h,k\in H$, we must have
$$a'b'(=ah\mkern1.5mubk)=ab \mkern1.5mu\ell\quad\text{for some }\enspace \ell\in H.$$
In particular, we must have
$$a'a^{-1}=aha^{-1}\in H\enspace\text{for any }h\in H,~a\in G, $$
which exactly means $H$ is normal in $G$.

A: Just as an example: take the (not normal) subgroup $\{i,(23)\}=H\subset S_3$, where $i$ is the identity. Indeed, $$H_{(132)}=\{(132),(12)\}=H_{(12)}$$ and $$H_{(123)}=\{ (123),(13)\}=H_{(13)}.$$ However, $H_{(132)\circ (123)}=H_i$, which is different from $H_{(12)\circ (13)}=H_{(132)}$, so that our operation isn't well-defined.


text:
Q: how have 6 recyclerview by same class and same cardview and 6 different arraylist? I'm a self-learning.I have 3 recyclerview by 3 different arraylist but same cardview. How can I have one adapter class for this recylerviews ?
I write following code but it isn't true.
public class Main extends AppCompatActivity {

public static ArrayList <String> mainLinkImg1 = new ArrayList<>();//arraylists have valus
public static ArrayList <String> mainLinkImg2 = new ArrayList<>();
public static ArrayList <String> mainLinkImg3 = new ArrayList<>();

RecyclerView mainRecRow1,mainRecRow2,mainRecRow3;

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

    mainRecRow1 = (RecyclerView) findViewById(R.id.mainRec1);
    mainRecRow2 = (RecyclerView) findViewById(R.id.mainRec2);
    mainRecRow3 = (RecyclerView) findViewById(R.id.mainRec3);

    mainRecRow1.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
    mainRecRow2.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
    mainRecRow3.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));

    AdapterRecMain adapterRecMainRow1 = new AdapterRecMain(this,mainLinkImg1);
    mainRecRow1.setAdapter(adapterRecMainRow1);
    adapterRecMainRow1.UpdateItem();

    AdapterRecMain adapterRecMainRow2 = new AdapterRecMain(this,mainLinkImg2);
    mainRecRow2.setAdapter(adapterRecMainRow2);
    adapterRecMainRow2.UpdateItem();

    AdapterRecMain adapterRecMainRow3 = new AdapterRecMain(this,mainLinkImg3);
    mainRecRow3.setAdapter(adapterRecMainRow3);
    adapterRecMainRow3.UpdateItem();

    }
}

and my adapter class...
public class AdapterRecMain extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private ArrayList<String> picLink;

public AdapterRecMain (Context con, ArrayList<String> imgLink){
    context= con;
    picLink.addAll(imgLink);
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View view = LayoutInflater.from(context).inflate(R.layout.main_cardview_item1,parent,false)
//main_cardview_item1 is my cardview layout and just has a imageview
    return new CellFeedViewHolder(view);
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    final CellFeedViewHolder myHolder = (CellFeedViewHolder) holder;
    Picasso.with(context).load(picLink.get(position)).into(myHolder.mainImgRec);

}

public void UpdateItem()
{
    notifyDataSetChanged();
}

@Override
public int getItemCount() {
    return picLink.size();
}

private class CellFeedViewHolder extends RecyclerView.ViewHolder {
    ImageView mainImgRec;
    CardView card;
    public CellFeedViewHolder(View view) {
        super(view);
        mainImgRec = (ImageView) view.findViewById(R.id.mainCardViewImg);
        card = (CardView) view.findViewById(R.id.mainCardView1);
    }
}
}

Now what can I do ?

A: I had mistake when I make Array list in my Adapter class
public static ArrayList <String> mainLinkImg1 = new ArrayList<>();


text:
Q: Display stored database image on webpage using session? Hi I'm trying to store image into database using session and its successfully done but problem is that its can't display on my webpage when I upload the page and click on save button the previous pic display again but the new pic save into database successfully  and I want to store the pic on my folder also the coding is as following
The Html page coding is as following
<form class="form" action="accountsetting.php" method="post" enctype="multipart/form-data">

<?php echo $_SESSION['user']['fullname']; ?>

<?php echo $_SESSION['user']['username']; ?>

                    <input class='input' type='hidden' name='id' value="<?php echo $_SESSION['user']['id']; ?>" />
                    <input id="avatar" type="file" name="avatar" hidden="" accept="image/png, image/jpeg, image/jpg">
                    <button id="uploadBtn" type="button" class="btn btn-primary btn-file " >
                         &nbsp Upload Avatar
                    </button>

                        <button class="btn btn-primary " type="submit" name="profile">Save Changes</button>

</form>

The PHP coding is as following
$id = "";
if(isset($_POST['profile'])) {
    $id = $_SESSION['user']['id'];
    $file=addslashes(file_get_contents($_FILES["avatar"]["tmp_name"]));
    $query = "UPDATE users SET avatar = '$file' WHERE id = '$id'";
    $query_run = mysqli_query($db,$query);

    if($query_run) {
        echo '';
    } else {
        echo '';
    }
}

Session from HTML page side
<?php
include('../functions.php');
if (!isLoggedIn()) {
    $_SESSION['msg'] = "You must log in first";
    header("location: /uploadimg/loginform.php");
}

if (isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['user']);
    header("location: /uploadimg/loginform.php");
}
if(isset($_SESSION['success']))
{
    echo $_SESSION['success'];
    unset($_SESSION['success']);
}
if(isset($_SESSION['user']['fullname']))
{

}
?>

Session from PHP page side
<?php
session_start();

function isAdmin()
{
    if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
        return true;
    }else{
        return false;
    }
}

function isLoggedIn()
{
    if (isset($_SESSION['user'])) {
        return true;
    }else{
        return false;
    }
}


text:
Q: How to subtract geometry in pygame? I am trying to make a logic in which i can subtract the geometrical shapes. Lets say i have to subtract a circle from a rectangle.
The idea is to draw each point of the rectangle as a single individual point using win.set_at(). And then when we need to subtract the circle from the rectangle we an simply calculate that the point on which we are drawing and completing our square lies or not in the circle. If it lies then don't set pixels else draw the pixel. This is my code:

import pygame

WIDTH, HEIGHT = 700, 500

win = pygame.display.set_mode((WIDTH, HEIGHT))

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

def drawer(window, x, y, radius, s_l, s_w, s_x, s_y):
    for i in range(0, HEIGHT):
        for j in range(0, WIDTH):
            distance = (x - j)**2 + (y - i)**2
            if not distance <= radius**2 and i >= s_y and j >= s_x and i <= s_w + s_x and j <= s_l + s_y:
                window.set_at((j, i), BLACK)

c_x, c_y = 130, 150
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    win.fill(WHITE)
    drawer(win, c_x, c_y, 30, 100, 100, 100, 100)
    pygame.display.flip()

pygame.quit()

But is it is quite slow. Can you suggest a better way (more optimized algorithm) of doing it.

A: For a good performance I suggest to use pygame.mask. Draw the shapes on pygame.Surface objects and create masks from the surfaces:
mask1 = pygame.mask.from_surface(shape1)
mask2 = pygame.mask.from_surface(shape2)

Invert the mask of the second shape and create the overlapping mask. Finally, create a new _Surface: from the overlapping mask:
mask2.invert()
subtract_maks = mask1.overlap_mask(mask2, (0, 0))
subtract_shape = subtract_maks.to_surface(setcolor = "red", unsetcolor=(0, 0, 0, 0))

Minimal example

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

shape1 = pygame.Surface((200, 200), pygame.SRCALPHA)
pygame.draw.circle(shape1, "white", (100, 100), 100)
shape2 = pygame.Surface((200, 200), pygame.SRCALPHA)
pygame.draw.rect(shape2, "white", (25, 50, 150, 100))

mask1 = pygame.mask.from_surface(shape1)
mask2 = pygame.mask.from_surface(shape2)

mask2.invert()
subtract_maks = mask1.overlap_mask(mask2, (0, 0))
subtract_shape = subtract_maks.to_surface(setcolor = "red", unsetcolor=(0, 0, 0, 0))

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *background.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
[pygame.draw.rect(background, color, rect) for rect, color in tiles]
run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            print(pygame.key.name(event.key))

    window.blit(background, (0, 0))
    window.blit(subtract_shape, (50, 50))
    pygame.display.flip()

pygame.quit()
exit()


text:
Q: Why use const in C#? What's the point of ever using const?
It is more restrictive than static readonly:

*

*across assemblies, changes to a constin a dependency won't be reflected in its consumers

*you can only use const for certain primitive types

with both these restrictions in mind, perhaps among others I am not aware of,  why ever use const?
Why not always use static readonly to maintain consistency of style?

A: Things declared const are true compile-time constants, and thus may occur in constant-expressions. This means you can use them in the following contexts, where static readonly variables may not appear[1]:

*

*Values of other constants: const int OTHER = N;

*Explicit values of enum members: enum Foo { Bar = N }

*Default arguments: void Fn(int i = N)

*case labels: case N: and goto case N;

*Attribute values: [Value(N)]

*(rather irrelevant) array creation with initializers: new int[N] { 1, 2, 3 }
[1] https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#constant-expressions


text:
Q: localhost works in Edge but not in Chrome I'm doing an on-line Java course and created a very simple server.  Using Edge as client it works but not with Chrome.  I've tried turning off firewall and some of the things suggested here (WAMP server localhost wont work with Chrome) and elsewhere, but they all seem to be overly complicated changes to Windows files.  Surely there's a config setting somewhere?!
In Edge it's fine, in Chrome it returns this whether I use localhost:999 or 127.0.0.1:999. I've tried other ports too.
This page isn't working
127.0.0.1 sent an invalid response.
ERR_INVALID_HTTP_RESPONSE
Here is my code in case needed.
public static void main(String[] args) {
    try (
        ServerSocket aServer = new ServerSocket(999);
        Socket cn = aServer.accept();
         BufferedReader bis = new BufferedReader(new InputStreamReader(cn.getInputStream()));
        BufferedOutputStream bos = new BufferedOutputStream(cn.getOutputStream());)

        {
            String line = bis.readLine();
        while(line != null && !line.equals(""))
        {
            System.out.println(line);
            line = bis.readLine();
        }

        bos.write("Hello from java TCP Server!".getBytes());

    } catch (IOException ex) {
        System.out.println("Error in connnection: " + ex.getMessage());
    }
}

Any help appreciated.

A: Web browsers require that the server speaks HTTP protocol. A proper server response would be:
BufferedOutputStream bos = new BufferedOutputStream(System.out);

byte[] message="Hello from java TCP Server!".getBytes();

bos.write("HTTP/1.1 200 OK\r\n".getBytes());
bos.write("Content-Type: text/plain\r\n".getBytes());
bos.write(("Content-Length: "+message.length+"\r\n").getBytes());
bos.write("\r\n".getBytes()); // empty line between HTTP header and HTTP content
bos.write(message);

You may test your program with another tool that speaks plain TCP sockets. Ich recommend "Netcat" (command: nc). Download for Windows: http://stefanfrings.de/avr_tools/netcat-win32-1.12.zip


text:
Q: Cannot copy/paste anymore in tmux 2.1 I just update to tmux 2.1(OS X10.11.3 Terminal.app),  and my .tmux.conf(accroding to http://joehanchoi.com/quick-fixes-for-tmux-2-1-on-osx/)
set-option -g mouse on
bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'"
bind -n WheelDownPane select-pane -t= \; send-keys -M

but the problem is after I start tmux, the mouse pointer becomes a plus: +, and I cannot copy/paste anymore.
And right click on Terminal does not work, no popups
How to solve this?

A: There are two factors:

*

*Terminal.app in El Capitan recognizes (some of) xterm's escape sequences for the mouse.

*tmux 2.1 has some changes — for the (xterm) mouse protocol

This was discussed extensively in  Mouse scrolling in tmux 2.1 on OSX no longer auto-starts #145 , but no one suggested a different configuration than the one you are using.


text:
Q: Allow remote connection to this computer using WinAPI I need to set Allow remote connections to this computer on, so I want to know If I can enable it by using WinAPI.

Does anyone know If this can be done with any function?

A: for this you need set next registry keys:
HKLM\System\CurrentControlSet\Control\Terminal Server\fDenyTSConnections = 0
HKLM\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\UserAuthentication = (IsDlgButtonChecked() == BST_CHECKED)
HKLM\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\SecurityLayer = 0 or 1 or 2

if radio-button not selected you need set only
HKLM\System\CurrentControlSet\Control\Terminal Server\fDenyTSConnections = 1

also you need enable "@FirewallAPI.dll,-28752" Firewall group by next code:
HRESULT EnableFirewallRule(PCWSTR cgroup, VARIANT_BOOL enable)
{
    if (BSTR group = SysAllocString(cgroup))
    {
        INetFwPolicy2* pNetFwPolicy2;

        HRESULT hr = CoCreateInstance(__uuidof(NetFwPolicy2), 0, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pNetFwPolicy2));

        if (!FAILED(hr))
        {
            hr = pNetFwPolicy2->EnableRuleGroup(NET_FW_PROFILE2_ALL, group, enable);

            pNetFwPolicy2->Release();
        }
        SysFreeString(group);
        return hr;
    }
    else return E_OUTOFMEMORY;
}

EnableFirewallRule(L"@FirewallAPI.dll,-28752", VARIANT_TRUE);

yes, this not documented properly. however can found some info about this.
are radio button (Allow remote connections to this computer) selected depended only from fDenyTSConnections ( 0 or 1 (!= 0) ) - you can test it by changing value in regedit and reopen System Properties/Remote dialog
some proof on the MSND - Using Remote Desktop

A value of 0 for the fDenyTSConnections registry value means that
  Remote Desktop is enabled on the system, while a value of 1 means that
  Remote Desktop is disabled. If you later decide you want to disable
  Remote Desktop on your Server Core installation, type cscript
  %windir%\system32\scregedit.wsf /ar 1 at a command prompt.

UserAuthentication - [0 or 1 ] control Network Level Authentication checkbox (1 checked, 0 - unchecked) (again you can changing value in regedit and reopen System Properties/Remote dialog - or check/uncheck this this box and view in regedit)

In the Properties pane, click the box to the right of the
  UserAuthentication setting and type 1 to require Network Level Authentication, as shown here.

SecurityLayer - [0 or 1 or 2] - look the Table 6-1 The SecurityLayer Setting Values
and the last for firewall (this is begin from vista)

In the Properties pane, type C:\Windows\system32\netsh advfirewall
  -firewall set rule group="Remote Desktop" new enable=yes

so we need enable rule group="Remote Desktop"
now look at this technet.microsoft.com link

For example, to enable Remote Desktop, use the following:
  <Group>@FirewallAPI.dll,-28752</Group>

how is Enabling a Group exist example on MSDN. my code snipet bassed on this


text:
Q: Output result of queries to dataset in Model Builder I am running a number of spatial queries on a dataset in model builder and want the number of selected features to be saved in a table. I don't want the features themselves but just the number of features that the query found. Is this possible?

I want
ID| Site       |   Number
1 | Brisbane   | 9789
2 | Towoomba   | 8389
etc...

A: Using the summary statistics tool will only get you half way there, it will give you one table per selection with the count of unique FID/OID. Geoprocessing tools honor selection layers and will only sum the selected features.
To compile the tables into a single table it is necessary to, for each sum table, add a Site field and calculate the name. Then the tables can be merged and exported to text format in the model. This will not do pipe delimited, to achieve this it is necessary to open the csv file and find & replace "," with "|".
As stated in the comment, there is a Get Count tool for modelbuilder but this is for condition branching and I don't know a way to get the output of this into a file using just modelbuilder. In python it wouldn't be a problem, the count could be written to a text file in pipe delim format using file operations!

A: Thanks Everyone...
In the end it was quicker just to write a small script to get this with the Get Count Tool.
The script is
import arcpy
id=arcpy.GetParameterAsText(0)
fieldName=arcpy.GetParameterAsText(1)
RowCount=arcpy.GetParameterAsText(2)
logFile=r'D:\scratch\GetCountTool_output.txt'
log = open (logFile, 'a')
log.write(id+"|"+fieldName+"|"+RowCount)
log.close


text:
Q: How to use the same Activity for 3 different tabs in TabActivity with different inputs I have an TabActivity which has 3 Tabs reusing the same Activity  for all the 3 tabs.
I am differentiating by means of extras(intent.putextras()) which i shall display the contents of each tab
Now the problem is when we switch the tab from each other the extra values which i passed through Intent is coming wrong for the second tab.
As i understood when we created the FirstTab, the only Activity is created and so the contents are drawn as per it.
when we add the secondTab the intent storing the extra value
and again when we creating the third tab the Intent over-writing the extra value.
so when ever we are switching to 2nd tab, i'm receiving the 3rd Tab extra value and hence showing wrong contents to the user.
here is the code,
public class ContentsTab extends TabActivity implements OnTabChangeListener{

public static final String _ID = "_id";
public static final int ID_1 = 1;
public static final int ID_2 = 2;
public static final int ID_3 = 4;

private TabHost mTabHost;
private static Intent newIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

newIntent = new Intent(this, ShowContents.class);

mTabHost = getTabHost();

    newIntent.putExtra(_ID, ID_1);
mTabHost.addTab(mTabHost.newTabSpec(INT_EXT_MEM)
            .setContent(newIntent)
            .setIndicator("one"));

    newIntent.putExtra(_ID, ID_2);
    mTabHost.addTab(mTabHost.newTabSpec(EXT_MEM)
            .setIndicator("two")
            .setContent(newIntent));

    newIntent.putExtra(_ID, ID_3);
    mTabHost.addTab(mTabHost.newTabSpec(INT_MEM)
            .setContent(newIntent)
            .setIndicator("three"));

    mTabHost.setCurrentTabByTag("one");

    mTabHost.setOnTabChangedListener(this);
}

@Override
public void onTabChanged(String tabId) {
    //This is only coming once the Tab is changed
    Log.d(TAG, "onTabChanged arg0 = "+tabId);
 }
 }

showcontents.class
public class ShowContents extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras();

    int mId_ContentType;

    mId_ContentType = extras != null? extras.getInt(_ID): -1;

    updateData(mId_ContentType);

  }
 }

Here the illustration,
when user presses tab1, ShowContents.class should receive 1 as extras and same with tab2 and tab3, but the following values are received
Tab1 - 1
Tab2 - 4(correct value should be 2)
Tab3 - 4
Tab1 and Tab3 values are coming correct.
Is there any alternative to send the correct extra parameters to Tab2? using the same class Activity?
Please help me
Thanks for your time :)

A: You need to have 3 different instances of the activity. You can do something like this
newIntent1 = new Intent(this, ShowContents.class);
newIntent2 = new Intent(this, ShowContents.class);
newIntent3 = new Intent(this, ShowContents.class);

Then use these 3 instances for 3 tabs. Should be fine like this.


text:
Q: How to get the profile photo of facebook user who is registered my site with facebook registration application(not using mvc) I am developing a web page default.aspx.(Not an mvc application) with a facebook registration plugin.I need to get the profile picture of user who is logging into my application using their facebook id.I saw fql examples but i dont know how to implement it in c# code behind page. I was able to get the profile information in code behind.Please help me how to get the profile picture from user who is registering my page .i am using c# 2008

A: If you are getting the FacebookID just generate the image URL
 <img src="https://graph.facebook.com/FacebookIDOrUserName/picture"/>

http://developers.facebook.com/docs/reference/api/
If you need to download the image:
Image image = null;
string URL = "https://graph.facebook.com/FacebookIDOrUserName/picture";

HttpWebRequest req = (System.Net.HttpWebRequest)HttpWebRequest.Create(URL);
req.AllowWriteStreamBuffering = true;
req.Timeout = 20000;

WebResponse resp = req.GetResponse();
System.IO.Stream stream = resp.GetResponseStream();

image = Image.FromStream(stream);

resp.Close();


text:
Q: Memcache response: "bad command line format" on Google Cloud Platform with large values using node.js Modifying the example found on the Google App Engine Documentation to store a large string results in an response Error: bad command line format
Often subsequent requests will then be met with Error: Server at <IP>:11211 not available as if something in the set function briefly knocks the server offline.
Tried running in GAE's shared Memcache as well as with a dedicated 1GB (10,000 MCU per second per GB) with no difference.
Multiple nodejs memcached libraries as well as large Buffer and JSON formatted values all return the same error. All of my research appears to show that this error tends to come from a 'key' greater than 250 characters, but not from a large value (since attempt below is well short of both the Memcache quota and the 1MiB limit per value).
Here's a full app.js to demonstrate:
'use strict';

var express = require('express');
var Memcached = require('memcached');

var app = express();

// The environment variables are automatically set by App Engine when running
// on GAE. When running locally, you should have a local instance of the
// memcached daemon running.
var memcachedAddr = process.env.MEMCACHE_PORT_11211_TCP_ADDR || 'localhost';
var memcachedPort = process.env.MEMCACHE_PORT_11211_TCP_PORT || '11211';
var memcached = new Memcached(memcachedAddr + ':' + memcachedPort);

app.get('/', function(req, res, next) {
  memcached.get('foo', function(err, value) {
    if (err) { return next(err); }
    if (value) {
        console.log('Exists');
      return res.status(200).send('Value: ' + value);
    }

    var str = "";

    // Make a big string
    var loops = 1000;
    // works with loops = 10, fails with loops = 1000
    for(var i = 0; i < loops; i++){
        str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    }

    memcached.set('foo', str, 60, function(err) {
      if (err) { return next(err); }
      console.log('Created');
      return res.redirect('/');
    });
  });
});

var server = app.listen(process.env.PORT || 8080, '0.0.0.0', function() {
  console.log('App listening at http://%s:%s', server.address().address,
    server.address().port);
  console.log('Press Ctrl+C to quit.');
});

The same large string can be manually set in Memcache using the Google Cloud Console form. Subsequent calls to retrieve the value also work. Am I drastically miscalculating MCU based on the value size?
When running locally (OSX) I experience zero issues and am able to store very large values. Error only occurs with deployed code. Any advice or direction is much appreciated.

A: There is currently a bug in the Memcache proxy preventing values of over 4kb being written. There is a buffer in between which is truncating the packet confusing the memcache server. For the time being, any data over 4kb should be stored in some sort of database (cookies won't work either since cookies also can't be stored over 4kb). I will update this question once the issue is fixed.
Edit: Issue should now be fixed.


text:
Q: Background "Jumps" on revealing sidebar with content I am trying to make a sidebar that reveals on pressing a button.
Everything works fine until I put some content in the sidebar. The background jumps when the sidebar is revealed.
Here is sample code:

 document.getElementById('btn').addEventListener('click', ()=>{
            let sidebar = document.getElementById('sidebar');
            sidebar.style.width = '40vw';
            let p = document.querySelector('#sidebar p');
            p.style.display = 'block';
        })
 *{
        margin: 0;
        padding: 0;
    }

    #main{
        display: flex;
    }
    #sec1{
        width: 60vw;
        height: 100vh;
        background: red;
    }

    #sec2{
        width: 40vw;
        height: 100vh;
        background-color: #bdd9d4;

    }

    #sidebar{
        width: 0;
        height: 100vh;
        position: absolute;
        top: 0;
        right:0;
        z-index: 1;
        transition: width .5s;
        background: green;
    }

    #sidebar p{
        display: none;
    }

        <button id="btn">Open Sidebar</button>

Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam sapiente amet similique? Architecto dolor, nulla neque natus incidunt labore dignissimos? Mollitia reprehenderit rerum unde iusto, consequatur explicabo molestiae cumque vero!

Lorem ipsum dolor sit amet consectetur adipisicing elit. Reprehenderit doloremque sit delectus exercitationem reiciendis? Sunt, dolore ut cum, quod aliquam porro et similique, deleniti voluptatum neque maiores sed! Optio, fugit ipsam sequi quae incidunt pariatur hic deleniti! Eos atque vel praesentium delectus necessitatibus illo, iste officia modi nobis, est voluptatem sequi a quo quae quidem labore architecto magni aspernatur? Doloremque, libero fugiat accusantium asperiores aspernatur officiis numquam velit ullam dolore aliquam vitae tenetur, eaque vel deleniti! Eum magni officiis nihil?

How do I stop the Jump without removing the content?
I also tried playing with variations of display and visibility to hide the elements.

A: The "jump" is caused by the fact that when you click on the button, the offset width of your text can't really fit in the div that is growing. In other words, there is an instant, where the div that contains the text is something like 1px while your text is really bigger. So, there is many solutions including:

*

*Hide the text overflow (it may work but the text will still "dance" while the div is growing)
I was thinking of something like :
   #sidebar p{
       display: none;
       overflow: hidden;
   }

*Put a delay before displaying the text so the div will have enough time to be wide enough for the text :)

 document.getElementById('btn').addEventListener('click', ()=>{
     let sidebar = document.getElementById('sidebar');
     sidebar.style.width = '40vw';
     let div = document.querySelector('#sidebar div');

     let text = div.children[0].innerText;
     div.children[0].innerText = "";
     div.style.display = 'block';

     setTimeout(()=>{
       div.children[0].innerText = text;
     }, 500)
 })
*{
        margin: 0;
        padding: 0;
    }

    #main{
        display: flex;
    }
    #sec1{
        width: 60vw;
        height: 100vh;
        background: red;
    }

    #sec2{
        width: 40vw;
        height: 100vh;
        background-color: #bdd9d4;

    }

    #sidebar{
        width: 0;
        height: 100vh;
        position: absolute;
        top: 0;
        right:0;
        z-index: 1;
        transition: width .5s;
        background: green;
    }

    #sidebar div{
        display: none;
    }

        <button id="btn">Open Sidebar</button>

Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam sapiente amet similique? Architecto dolor, nulla neque natus incidunt labore dignissimos? Mollitia reprehenderit rerum unde iusto, consequatur explicabo molestiae cumque vero!

A: As stated in the previous answers, your content jumps because you are animating the width of the container. The content (text) within it, will always try to fit, and this is why your have this effect.
In order to prevent this, do not animate the width, but animate the position.
#sidebar{
    width: 0;
    height: 100vh;
    position: absolute;
    top: 0;
    right:0;
    z-index: 1;
    transition: transform .5s; /* modified */
    background: green;

    transform: translateX(120%); /* added */
}

#sidebar.showSidebar {
    transform: translateX(0);
}

Remove this part from your code:
#sidebar p{
    display: none; /* need to remove this from your code */
}

You might also need to add overflow-x: hidden to the Parent Element of your sidebar (in this case, the ), if horizontal scrollbars appear.

And this is the only JS required:
document.getElementById('btn').addEventListener('click', function(){
    document.getElementById('sidebar').classList.add('showSidebar');
});

To hide the .sidebar again, you just need to remove the .showSidebar class :
document.getElementById('sidebar').classList.remove('showSidebar');

Using transform: translate() within CSS transitions is more efficient than using 'width' or 'right', as it doesn't cause layout/reflow (recalculation of the whole elements' size and/or position). It, along with opacity, are the only two transitionable properties that only affect the 'composition' part of the rendering of the webpage.
high-performance-animations article - the exact same principles apply to transitions also.

A: I've got a much more elegant solution than my previous attempt which I deleted as it caused an unwanted scrollbar. Simply add a child DIV for the sidebar contents with a fixed width and put overflow hidden on the sidebar. The sidebar can grow in width revealing the fixed width content which is hidden by the overflow. Any good?

 document.getElementById('btn').addEventListener('click', ()=>{
            let sidebar = document.getElementById('sidebar');
            sidebar.style.width = '40vw';
            let p = document.querySelector('#sidebar p');
            p.style.display = 'block';
        })
 *{
        margin: 0;
        padding: 0;
    }

    #main{
        display: flex;
    }
    #sec1{
        width: 60vw;
        height: 100vh;
        background: red;
    }

    #sec2{
        width: 40vw;
        height: 100vh;
        background-color: #bdd9d4;

    }

    #sidebar{
        width: 0;
        height: 100vh;
        position: absolute;
        overflow: hidden;
        top: 0;
        right:0;
        z-index: 1;
        transition: width .5s;
        background: green;
    }

    #sidebar-contents {
        width: 40vw;
    }

    #sidebar p{
        display: none;
    }

        <button id="btn">Open Sidebar</button>

Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam sapiente amet similique? Architecto dolor, nulla neque natus incidunt labore dignissimos? Mollitia reprehenderit rerum unde iusto, consequatur explicabo molestiae cumque vero!

Lorem ipsum dolor sit amet consectetur adipisicing elit. Reprehenderit doloremque sit delectus exercitationem reiciendis? Sunt, dolore ut cum, quod aliquam porro et similique, deleniti voluptatum neque maiores sed! Optio, fugit ipsam sequi quae incidunt pariatur hic deleniti! Eos atque vel praesentium delectus necessitatibus illo, iste officia modi nobis, est voluptatem sequi a quo quae quidem labore architecto magni aspernatur? Doloremque, libero fugiat accusantium asperiores aspernatur officiis numquam velit ullam dolore aliquam vitae tenetur, eaque vel deleniti! Eum magni officiis nihil?


text:
Q: Content-Type in GET method not getting populated Setting Content-Type for GET method is not getting populated using Apache Camel-Http component.
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");

Whereas the same is working when using POST method.
Understood that there is no body for method GET. A strange thing is, if body is set to empty string("") Content-Type is being passed but the method type also changes to POST.
exchange.getIn().setBody("");

2.13.1 is the Camel version that i am currently using. Tried with the latest versions too, still the same. Is there something that i am missing.
Service mandates to pass Content-Type.

A: In the Camel source there is a test for this kind of scenario: https://github.com/apache/camel/blob/master/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerContentTypeTest.java
In both the test cases the body need to be set. You should see this in camel-http4:
https://github.com/apache/camel/blob/master/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java#L482-L582
and camel-http too:
https://github.com/apache/camel/blob/master/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java#L447-L506
If you decide to use Http4/http component then you'll need to set a body.
There is also this very old discussion on nabble:
http://camel.465427.n5.nabble.com/Http4-Set-Header-Content-Type-not-passing-through-to-the-HTTP-Request-td5746414.html


text:
Q: How to remove share menu on embed live stream? Please how to remove on pause , share menu , in this embed code ?
<script>
                          $(document).ready(function(){
                                $('#ansalive_player_mod2').empty();
                                $('#ansalive_player_mod2').flash(
                                    {
                                      src: '/player.swf',
                                      width: 680,
                                      height: 400,
                                      quality:'high',
                                      allowfullscreen: 'true',
                                      flashvars: { file: 'n24stream?adbe-live-event=news24', streamer: 'rtmp://66.55.93.203/livepkgr/', image: '/news24/live/emisionet/img/live3.png', skin: '', autostart:  'true', volume: '50',  quality:'medium', stretching: 'exactfit' }
                                    },
                                    { version: 2 }
                                );
                            });
</script>

A: Use this copy of player.swf, it does not have the share menu on pause - http://player.longtailvideo.com/player.swf


text: Q: How much does the existence of hyperplane arrangements depend on the underlying field? Given an arrangement of hyperplanes $H_i$ in $V$ a vector space over a field $k$, we have the associated incidence structure. Not all realisable incidence structures can occur over all fields however, a stupid example is taking more hyperplanes $H_i$ than the total number of hyperplanes when over a finite field. I am wondering if there are more subtle realisability obstructions, eg, is $k$ infinite sufficient to realise all realisable incidence structures? What about $k$ algebraically closed? This seems like a very natural question, so I'm sure someone has thought about it before, so a reference would be much appreciated.


text:
Q: Concatenate of firstName and lastName and perfom searching on this 2 property using Gremlin queries     "label":"employee",
    "id": "64c268cc-6a39-4eba-a312-79103a97b837",
    "entityType":"employee",
    "organizationId": "d7081ebb-4685-4cb5-ba24-027eeb815a27",
    "floorId":"36577019-0587-4a15-b784-4b2b0df7a1da",
    "officeId": "7632d466-66e2-4c38-a40b-9d1deec61e69",
    "firstName": "Sarfaraz",
    "lastName": "Shaikh",
    "phoneNumber": "9874152362",
    "department": "Data",
    "teams": "[.Net","Devops"],
    "deviceId": "RAHS898HAJHS",
    "devicetype": 1 ,
    "timestamp": 1586173968,
    "isActive": True/False

Above is the vertex property for employee, I want to perform concatenation on firstName and lastName and also searching on this properties using gremlin queries, Azure cosmos graphDB supports only case sensitive data, and I am not able to perform case sensitive search.
Let say in the database if firstName property store 'sarfaraz' and I search for 'Sa' it should give me this result 'sarfaraz'.

A: The current Gremlin Query Language does not have any string manipulation capabilities built in so you can not for example do something like concatenate two strings using Gremlin steps. If the graph database you are using supports in line lambdas/closures then you can do it that way but a lot of graph DBs prevent that for security reasons among others. The Gremlin text predicates are case sensitive. Some graph DBs support integration with an external index such as Elastic Search. In those cases, case insensitive search is possible.


text:
Q: Issue creating class objects from within the method of another class, and adding them to lists Python So this has been confusing me for a couple of days now, I have three classes one called Page:
class Page:

   def __init__(self, pageName, sectionIBelongTo="Uncategorised"):
        self.mySection = sectionIBelongTo
        #each page belongs to only one section
        self.name = pageName

Which must have an assigned section object:
class Section:

    childPages = []

    def __init__(self, padName):
        self.name = padName

    def addSection(self, pageObject):
        self.childPages.append(pageObject)

Section also has a list of all child notes.  This is all managed through a single Book class object:
class Book:
    Sections = []

    def __init__(self):
        print "notebook created"

    def addSection(self, secName):
        sectionToAdd = Section(secName)

        self.Sections.append(sectionToAdd)

    def addPage(self, bufferPath, pageName, pageSection="Uncategorised"):
        #Create a page and add it to the appropriate section

        for section in self.Sections:
            if section.name == pageSection:
                sectionToSet = section
        #Search list of sections for matching name.

        newPage = Page(pageName, sectionToSet)
        #Create new page and assign it the appropriate section object

        self.Sections[self.Sections.index(sectionToSet)].addSection(newPage)
        #Add page to respective section's list of pages.

Which as you can see holds a list of all of its sections.  So I import these classes from another file and try to fill up my book like so:
myBook = Book()

myBook.addSection("Uncategorised")
myBook.addSection("Test")
myBook.addSection("Empty")
#Create three sections

myBook.addPage("belongs to uncategorised")
#Add page with no section parameter (uncategorised).
myBook.addPage("Belongs to test", "Test")
#Add page to section "Test"
myBook.addPage("Belongs to uncategorised again")
#Another uncategorised page

for x in range(0, 3):
    print "Populated section '", myBook.Sections[x].name, "', with: ", len(myBook.Sections[x].childPages), " child pages."

The output shows that all three sections are created fine, but every section has 3 child pages, if I print the names of the pages it appears that every page has been added to every section.
I would hugely appreciate anyone being able to spot my silly mistake.
Thanks in advance! :)

A: Making childPages an instance attribute, not a class attribute, should solve your problem:
class Section:

    def __init__(self, padName):
        self.name = padName
        self.childPages = []

    def addSection(self, pageObject):
        self.childPages.append(pageObject)


text:
Q: Tabs show as per button not working using bootstrap 5? I'm using bootstrap 5 i have one modal for login and register but but there is two bootstrap tabs inside one modal and i want to display tab as per button click but this is not working.
When i click on login button then inside modal login tab should be active and if i click on register button then inside modal register tab should be active.
Giving this error in console:-
Uncaught TypeError: Cannot read property 'show' of null
My Code:

 $('.register-btn').click(function() {
        $('#loginModal').modal('show');
        var triggerEl = document.querySelector('[data-bs-target="#register"]')
        bootstrap.Tab.getInstance(triggerEl).show()
    })
    $('.login-btn').click(function() {
        $('#loginModal').modal('show');
        var triggerE2 = document.querySelector('[data-bs-target="#login"]')
        bootstrap.Tab.getInstance(triggerE2).show()
    })
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <button type="button" class="btn btn-primary register-btn">
        Register
    </button>
    <button type="button" class="btn btn-primary login-btn">
        Login
    </button>

                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

                                    <button class="nav-link active" id="login-tab" data-bs-toggle="tab" data-bs-target="#login" type="button" role="tab" aria-controls="login" aria-selected="true">Login</button>

                                    <button class="nav-link" id="register-tab" data-bs-toggle="tab" data-bs-target="#register" type="button" role="tab" aria-controls="register" aria-selected="false">Register</button>

                                    <form>

                                            Mobile Number
                                            <input type="text" class="form-control">

                                            <button class="btn btn-primary btn-block">Login</button>

                                    </form>

                                    <form>

                                            Full Name
                                            <input type="text" class="form-control">

                                            <button class="btn btn-primary btn-block">Register</button>

                                    </form>

Thanks for your efforts!

A: You can trigger the click to simulate clicking the tab.

$(".register-btn").click(function () {
  $("#register-tab").trigger("click");
  $("#loginModal").modal("show");
});
$(".login-btn").click(function () {
  $("#login-tab").trigger("click");
  $("#loginModal").modal("show");
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <button type="button" class="btn btn-primary register-btn">
        Register
    </button>
    <button type="button" class="btn btn-primary login-btn">
        Login
    </button>

                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

                                    <button class="nav-link active" id="login-tab" data-bs-toggle="tab" data-bs-target="#login" type="button" role="tab" aria-controls="login" aria-selected="true">Login</button>

                                    <button class="nav-link" id="register-tab" data-bs-toggle="tab" data-bs-target="#register" type="button" role="tab" aria-controls="register" aria-selected="false">Register</button>

                                    <form>

                                            Mobile Number
                                            <input type="text" class="form-control">

                                            <button class="btn btn-primary btn-block">Login</button>

                                    </form>

                                    <form>

                                            Full Name
                                            <input type="text" class="form-control">

                                            <button class="btn btn-primary btn-block">Register</button>

                                    </form>


text:
Q: Rails ActiveRecard validation fail I'm having some trouble saving a model
class AmazonMovie < ActiveRecord::Base
  attr_accessible :asin_buy, :asin_rent, :movie_id, :on_prime, :on_prime_prev, :price_buy, :price_buy_prev, :price_rent, :price_rent_prev, :url, :updated_at, :created_at

  belongs_to :movie
  has_many :amazon_movie_changes, :dependent => :destroy

  validates :movie_id, presence: true, uniqueness: true

  AWS_QPS_THRESHOLD = 1.0

  before_create :init

  def init
    self.on_prime_prev = false
  end

  def update_changes

...
There's another class
class AmazonMovieChange < ActiveRecord::Base
  attr_accessible :amazon_movie_id, :buy_change, :movie_id, :on_prime, :on_prime_prev, :price_buy, :price_buy_prev, :price_rent, :price_rent_prev, :prime_change, :rent_change

  belongs_to :movie
  belongs_to :amazon_movie

  validates_presence_of :movie_id, :amazon_movie_id

....
When I created a model like the following:
=> #<AmazonMovie id: nil, movie_id: 16918, asin_buy: "B00FSTCUGA", price_buy: 7.99, price_buy_prev: nil, asin_rent: "B00FST7SX0", price_rent: 3.99, price_rent_prev: nil, on_prime: false, on_prime_prev: false, url: "http://www.amazon.com/Strongman-Stanless-Steel/dp/B...", created_at: nil, updated_at: nil>

I'm getting the following save failure:
ActiveRecord::RecordInvalid: Validation failed: Amazon movie changes is invalid
    from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/validations.rb:56:in `save!'
    from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/attribute_methods/dirty.rb:33:in `save!'
    from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:246:in `block in save!'
    from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:295:in `block in with_transaction_returning_status'
    from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/database_statements.rb:192:in `transaction'
    from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:208:in `transaction'
    from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:293:in `with_transaction_returning_status'
    from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.8/lib/active_record/transactions.rb:246:in `save!'
    from (irb):145
    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.8/lib/rails/commands/console.rb:47:in `start'
    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.8/lib/rails/commands/console.rb:8:in `start'
    from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

UPDATE:
I realized by removing the before_create :init this model saves without errors. My original intent was to default this field as false instead of NULL. Is there something wrong in my syntax? Or this is not the right way to default a field?


text:
Q: Selenium - Button is clickable First time and second time throws exception I am running UI ATPs. In that I have different buttons, when try to click on button first time - it is clickable. But Second time when I try to click if same button also it gives me exception:
This is really unexpected behavior at my end. Because, Same tests are running on other people's machine. I cross checked Selenium ,chromedriver ,Chrome versions. All are same.
Chrome : Version 64.0.3282.140 (Official Build) (64-bit)
Chrome driver: 2.35.0
Selenium : 1.0.19.0
Code for ButtonClick:
public static void SafeClick(this IWebElement element, int intervalInSeconds = 1, int timeoutInSeconds = 30)
        {
            bool success = false;
            int counter = 0;
            while (!success && counter < timeoutInSeconds)
            {
                try
                {
                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(intervalInSeconds));
                    element.Click();
                    success = true;
                    return;
                }
                catch (Exception ex)
                {
                    counter += intervalInSeconds;
                }
            }

            Assert.Fail(element.ToString() + " was unable to be clicked.");
        }


text:
Q: Filter with CoffeeScript list comprehensions The CoffeeScript docs state that list comprehensions should be able to do the select/filter operations:

They should be able to handle most
  places where you otherwise would use a
  loop, each/forEach, map, or
  select/filter.

You'd imagine you could do something in one line like result = item for item in list if item % 2 == 0
However the closest I can come is
list = [1,2,3,4]
result = []
for item in list
  if item % 2 == 0 then result.push item

Whats the most concise way to filter a list in CoffeeScript?

A: Unless you are trying to squeeze every ounce of performance out, I would create a filter function like this:
filter = (list, func) -> x for x in list when func(x)

or if you want to add it to the prototype of every array:
Array::filter = (func) -> x for x in @ when func(x)

and then write: (respectively)
result = filter mylist, (x) -> x % 2 == 0

or
result = mylist.filter (x) -> x % 2 == 0

For reference, this is the javascript that gets generated:
var filter, result;
filter = function(list, func) {
    var x, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = list.length; _i < _len; _i++) {
        x = list[_i];
        if (func(x)) {
            _results.push(x);
        }
    }
    return _results;
};
Array.prototype.filter = function(func) {
    var x, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = this.length; _i < _len; _i++) {
        x = this[_i];
        if (func(x)) {
            _results.push(x);
        }
    }
    return _results;
};
result = filter(mylist, function(x) {
    return x % 2 === 0;
});
result = mylist.filter(function(x) {
    return x % 2 === 0;
});

There is a similar question here

A: result = (item for item in list when item % 2 == 0)

edit : added result =


text:
Q: How to convert relative object coordinates to absolute I have a button on form, which opens popup menu. I need to open this popup menu right under button. ShowPopup function accepts absolute desktop coordinates. How to calculate absolute coordinates, if I know button position on form?
Currently I'm using this trick:
Private Type RECT
    Left As Long
    Top As Long
    Right As Long
    Bottom As Long
End Type

Private Declare Function GetWindowRect Lib "user32.dll" (ByVal hWnd As Long, lpRect As RECT) As Long
Private Declare Function GetFocus Lib "user32" () As Long

Private Sub Command1_Click()
    Dim r As RECT
    Dim chwnd As Long
    Dim h As Long

    Me.Text1.SetFocus
    chwnd = GetFocus
    Me.Command1.SetFocus
    h = GetWindowRect(chwnd, r)
    CommandBars("PopupMenu").ShowPopup r.Left, r.Bottom
End Sub

It works, but additional TextBox Text1 right under the button, which allows to get absolute position using API is not really good solution, wanted to calculate instead of using artificial "bookmarks"


text:
Q: Is there a way to export kibana visualization data automatically for some time period? I want to get/export kibana enhanced data table's data automatically to a external file(.csv,excel...) or database like my sql. I know there is a way get data manually  but i want to do it automatically from some constant time period(like one day) frequently?

A: Go to relevant vizualization

*

*Inspect -> view -> Requests -> Request
and copy the request that create visualization and
goto dev tool console and paste it.

*Should add
GET [index pattern]/search
above the request

*Click the mark at right corner of dev console and click copy as cURl

*Paste it to a script with frequet timeout(daily, weekly...) and get the output to a .json file


text:
Q: Is [bʊt] (Northern England) analyzed as an allophone of /bʌt/? In some/most Northern England accents, words that have [ʌ] in RP (or standard varieties of English) are pronounced with [ʊ]. So hut, cut, shut etc are pronounced with [ʌ]* in Southern British English but with [ʊ]** in Northern English accents.
Are Northern accent classified as separate accents and have been assigned a separate phonemic inventory or are they analyzed as a dialect of the Southern English accent and those pronunciations are analyzed as allophones of the pronunciations in Southern English?
In short, is [bʊt] of Northern English analyzed as an allophone of /bʌt/ or does Northern English have its separate phonology and analyzed as /bʊt/?

... * and **: I'm not sure about the exact vowel quality but to avoid confusion between "phonemic" and "phonetic" transcriptions, I use square brackets.


text:
Q: displaying radio button values on different textbox

    <?php

        for($i = 0; $i < 2; $i++)
        {
            echo "

            <input type='radio' value='Blue' name='radio1'>Blue</input>
            <input type='radio' value='White' name='radio1'>White</input>
            <input type='radio' value='Red' name='radio1'>Red</input>
            <input id='buttoncheck1' type='button' name='btn' value='Click'></input>

            <input type='text' id='btn_get' name='get_btn_value'></input>

            ";
        }

    ?>

I can clearly get all the values of the radio buttons in this code but the only problem I've been solving for almost 3 days is that I cant display the value on other textbox. all the values from all the radio button groups are only displayed on the first textbox produced by the loop. please help me . thanks!

A: id values should always be unique.  You can change your duplicated ids to class values and do the following:
$('input[type=button]').click(function ()
{
    var $parent = $(this).parent();
    var var_name = $parent.find("input[name='radio1']:checked").val();
    $parent.find('.btn_get').val(var_name);
});


text:
Q: restart time after pause i'm trying to do a little countdown in tkinter (python)
i already manage to get this working but when i paused when it starts it starts from the begining.
how can i make the pause button continue the actual time after pause?
thanks
    def countdown(self):

    if self.state == True:

        if (self.mins == 0) and (self.secs == 0):
            self.display.config(text="Done!")
            self.state = False
        else:
            self.display.config(text="%02d:%02d" % (self.mins, self.secs))

            if self.secs == 0:
                self.mins -= 1
                self.secs = 59
            else:
                self.secs -= 1

            self.master.after(1000, self.countdown)

def start(self):
    if self.state == False:
        self.state = True
        self.mins = self.minutes
        self.secs = self.seconds
        self.countdown()

def pause(self):
    if self.state == True:
        self.state = False

A: class Counter:
    def __init__(self, minutes, seconds):
        self.minutes = minutes
        self.seconds = seconds
        self.state = False
    def countdown(self):
        if self.state == True:
            if (self.mins == 0) and (self.secs == 0):
                print("Done!")
                #self.display.config(text="Done!")
                #self.state = False
            else:
                #self.display.config(text="%02d:%02d" % (self.mins, self.secs))
                if self.secs == 0:
                    self.mins -= 1
                    self.secs = 59
                else:
                    self.secs -= 1
                #self.master.after(1000, self.countdown)
    def start(self):
        if self.state == False:
            self.state = True
            self.mins = self.minutes
            self.secs = self.seconds
            self.countdown()

    def pause(self):
        if self.state == True:
            self.state = False
            #Add these lines into your code#
            self.minutes = self.mins
            self.seconds = self.secs
obj1 = Counter(10,40)
obj1.start()
obj1.pause()
obj1.start()
print(obj1.minutes, obj1.seconds)

I modified your code to run on my computer. I added two line in pause method.
Edit: Indentation errors are fixed.


text:
Q: Duplicate in array to how to remove it - JavaScript Basically I have an array, like this:
const companies = [
  {
    name: "Company One",
    category: "Finance, Finance, Technology, Auto, Same, Same, same",
    start: 1981,
    end: 2004
  }
]

In category, I want to write a .map or if statement to find the value matches the value if so remove all the extra values (Same for example) and just leave one instance of it.
So far what I have done is this:
const newSingles = companies.map(function(company) {
  if (company.category === company.category) {
    console.log("cats match remove and leave one");
    //This is where I am stuck?!
  };
});

It's driving me a little crazy as I was going to use .pop() but not sure how to. What can I try next?

A: So thank you for all the help everybody, it is very kind to get help!
If I put all my categories in their own array:
const companies = [
  {
    name: "Company One",
    category: ["Finance", "Finance", "Technology", "Auto", "Same",
               "Same"],
    start: 1981,
    end: 2004
  }
];

Then do this:
companies.map(it =>
    it.category = it.category.reduce((previous, currItem) => {
        if (!previous.find(
                    x => x.toLowerCase() === currItem.toLowerCase()))
            previous.push(currItem);
        return previous;
    }, []));

That gives me an output of the following:
[
  {
    name: 'Company One',
    category: [ 'Finance', 'Technology', 'Auto', 'Same' ],
    start: 1981,
    end: 2004
  }
]

Again thank your for your help :)

A: Try Array.filter(), do not use an if statement inside .map()
Maybe this will help you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

A: You should split your category and you need to find the unique values in your category array list. Try something like;
var category = ["Finance", "Finance", "Technology", "Auto", "Same", "Same", "same" ];
var uniques= category.filter((item, i, ar) => ar.indexOf(item) === i);

console.log(uniques);

With a little change, your new implementation would be something like this;
const newSingles = companies.map(function(company) {
const category = company.category.filter((item, i, ar) => ar.indexOf(item) === i);
  return {
   ...company,
   category
  }
});

And here is your new result;
[
  {
    name: "Company One",
    category:[ "Finance", "Technology", "Auto", "Same", "same"],
    start: 1981,
    end: 2004
  }
]


text:
Q: Bootable USB doesn't show as boot option I'm using a Dell Inspiron 5590, it came with Windows, I want to install Ubuntu instead. I downloaded the 18.04.5 image file and made a bootable USB device with Rufus following the ubuntu tutorial. The problem is, when booting, the USB device doesn't show in the Boot Options.
What I've tried:

*

*Tested in USB ports 3.0 and 2.0

*Tested flash drive in another notebook (It works)

*Tested with and without Secure Boot.

*Tried two "builds" of the bootable USB: Partition scheme: MBR + Target system: BIOS or UEFI AND with Partition scheme: GPT + Target system: UEFI (non CSM).

Also:

*

*I'm not looking to dual boot this, just linux is fine.

*USB Boot Support is enabled

*I didn't tried with Legacy Boot, because the BIOS says that this mode is not supported in the platform.

*Contacted Dell before purchase to be sure the hardware was compatible with Linux. (Also contacted the Dell support for help, useless in this case)

*BIOS is up to date.

What else can I try in order to have my bootable USB to be recognized by the Boot Manager?

A: Some BIOSes have difficulty with USB sticks over 4 GB. If the USB stick that you have tried previously is larger than that size, try one that is less than 4GB.

A: Well, if anyone is facing similar issues, I solved mine by replacing the USB flash drive.
It was a Sony 16gb, it works fine both within the OS and as a bootable device in other notebook, but for some reasons in this notebook it didn't. Replaced with a SanDisk 16gb and it worked.


text:
Q: Two's complement in ASN.1 Unaligned PER I've recently had to work with ASN.1 Unaligned PER encoded data. I'm having a problem understanding how UPER does two's complement integer encoding in the SEQUENCE data type.
It seems to be flipping the most significant bit incorrectly (poor choice of words). For positive integers, the leading bit is 1 and for negative, it's 0. I assume that there's a method to the madness here but after a days work it seems I can't dig it out of the ITU-T standard nor can I figure it out on my own. I suspect it is because the INTEGER's are wrapped in the SEQUENCE type, but I don't understand why it would do this. I should point out that my understanding of ASN.1 is very limited.
A simple example, let's say I have the following schema
BEGIN
    FooBar ::= SEQUENCE {
      Foo INTEGER (-512..511),
      Bar INTEGER (-512..511)
    }
END

And I'm encoding the following, as Unaligned PER
test FooBar ::=
{
   Foo 10,
   Bar -10
}

Result of the encoding as hex and binary string and respectively expected values.
HEX:           0x829F60
BIN:           100000101001111101100000

EXPECTED HEX:  0x02BF60
EXPECTED BIN:  000000101011111101100000

Any ideas as to what's happening here?

A: "Foo" and "Bar" should be lowercase.
Your impression that the most significant bit is "flipped" derives from the particular choice of minimum and maximum permitted values of foo and bar in your definition of FooBar.
The permitted value range of foo, in your definition above, is -512..511. In PER, the encoding of foo occupies 10 bits. The least permitted value (-512) is encoded as 0 (in 10 bits). The next permitted value (-511) is encoded as 1 (in 10 bits). And so on.
If you define FooBar2 in the following way
FooBar2 ::= SEQUENCE {
   foo2 INTEGER (1234..5678),
   bar2 INTEGER (1234..5678)
}
foo2 will be encoded in 13 bits (just enough to hold a value between 0 and 4444=5678-1234), with the value 1234 being encoded as 0000000000000, the value 1235 being encoded as 0000000000001, and so on.

A: If you follow the rules in X.691, you will end up at 11.5.6 (from 13.2.2).  This encodes these values, which are constrained whole numbers, as offsets from the lower bound, and therefore as positive values.  So, 10 is encoded as 522 and -10 as 502 (decimal, respectively).
Edit: someone suggested a clarification on the calculations.  Your lower bound is -512.  Since 10 = -512 + 522, the offset encoded for 10 is 522.  Similarly, since -10 = -512 + 502, the offset encoded for -10 is 502.  These offsets are then encoded using 10 bits.  Therefore, you end up with:
value  offset  encoded bits
-----  ------  ------------
   10     522    1000001010 (522 in binary)
  -10     502    0111110110 (502 in binary)


text:
Q: Azure relay hybrid connection listener not reestablishing when internet is disrupted I have CUSTOM azure hybrid connection listener service running on premise with below mention code as MSDN suggested, but listener not getting reestablished when on premise INTERNET connectivity get disrupted.
Only 1 out of 10 times, listener getting reestablished with below code, when on premise INTERNET is disrupted
// Opening the listener establishes the control channel to
// the Azure Relay service. The control channel is continuously
// maintained, and is reestablished when connectivity is disrupted
  await listener.OpenAsync(cts.Token);

//Below delegate not getting called when INTERNET plugged off from
//listener running machine
  listener.Offline += listener_Offline;

What changes required to reestablish listener to azure hybrid connection 10 out of 10 times?. Please advice.