text:
Q: How to remove a button in a tkinter The problem is that if I want to remove these buttons, which have been allocated space by x and y, it cannot be and does not generate any error or anything else shows as if it did not do any comedy, and when the button is normal it works as it should
import tkinter as t

root = t.Tk()

def click():
    button.pack_forget()

root.maxsize(375, 912)

img = t.PhotoImage(file="background.png")
background = t.Label(root, image=img)
background.pack()

button = t.Button(root, text ="Click\nme", command=click)
button.pack()
button.place(x=157, y=600)

root.mainloop()


text:
Q: Return to main menu when game over java I'm on the finnishing touches my first game and are having issues returning to the main menu when the player lose the game.
Main(Game) class:
public static void main(String[] args) throws InterruptedException {
    Main main = new Main();

This is where the menu is added to my frame. The menu itself is a
  JComponent with graphics and mouselisteners:
main.setMenu();
    while (true) {
        menuChoice = meny.getDecision();
        if (i == 0 && menuChoice == 2) {
            main.run(cp);
        } else if (i > 0) {
            main.run(cp1);
        } else if (menuChoice == 0) {
            System.exit(0);
        }

public void run(Computer cp) throws InterruptedException {
    if (time == 0) {

This is where my frame gets the game's background and so on:
        setWindow(data, player, cp);
        time++;
    }

    //Here's a bunch of irrelevant ifs

    } if (cpScore.returnScore() == 10 && time > 0) {

Here's where you should return to main menu. What needs to be done
here is basically what the mainmethod does at the absolute
beginning (add a Mainmenu-frame that takes input for further
instructions).
}
}

Any ideas?

A: probably the easiest way is to set the main menu into its own method with a  boolean value that is initialised to true, and then the menu proceeds so long as this value is true, when you want to return to the main menu, simply change this value back to false, ending the loop and allowing to return to the main menu method.

A: Create some functions inside of your main class that you can call to do what you are requesting as needed. No one is going to write the code for you, but here are some ideas
if (main.isGameOver() || main.isMainMenuRequested()) {
   main.stopGameThread();
   main.purgeOldGraphicsEtc();
   main.executeMenuThread();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Paperclip resize gives different results locally vs on Heroku I am using the Paperclip gem to resize images. I have noticed some strange behaviour between the conversions locally in my development environment, and on the server at Heroku.
Specifically, when uploading the same source image to each environment, a resulting image size is different.
My config for the attached file in my model:
has_attached_file :image, :styles => {
      :regular => "900x",
      :retina => "1800x",
      :thumb => "96x96#"
    }

The resulting file sizes for the :retina version are ~400k locally and ~1Mb on Heroku.
Is this the result of different imagemagick installs between the two environments? Is there some way to control this behaviour so that the resulting files will at least have consistency?

A: You can use
:convert_options => { :all => '-compress JPEG -depth 8'} # or another compression method

to standardize your resizing.
Here you can find all options you can set in imagemagick.


text:
Q: Why does the following method shows error of return type public static int letterPosition(String word,char a)//returns the position of searched character
{

    int lenght=word.length();

    for (int i=0; i < lenght; i++)
    {

        if(word.charAt(i)==a)
        {
            return i;
        }

    }
}

A: You need to handle the possibility that the loop isn't entered (or if it is entered, that the character isn't found). Add something like
return -1;

at the end of the method (to handle when the character isn't present).

A: Something must be returned, and your return statement is inside the 'if' statement, implying you have to enter the conditional statement to return something. You need to have a return option if the 'if' statement isn't executed.
You can fix this by adding an 'else if' statement after the 'if' statement.

A: please do something like,
public static int letterPosition(String word,char a)//returns the position of searched character
{
    int returnValue = -1;
    if(word != null){ //this will save us from NullPointerException...

    int lenght=word.length();

    for (int i=0; i < lenght; i++)
    {

        if(word.charAt(i)==a)
        {
            returnValue  = i;
            break;
        }

    } //end of for loop
  }//end of if - word != null
  return returnValue;
}


text:
Q: Как запустить сервис в отдельном потоке Имею два сервиса для уведомлений и воспроизведения аудио. Пробовал использовать IntentService, но работало не корректно и насколько я понял, startForegroundService() доступен только в android >= 8.
Также знаю, что можно использовать Thread или Handler, но не имею представления как организовать это, так как не нашел подходящих примеров.
А именно, где организовывать новый поток в самом сервисе, или в активности, или как-то по другому?
Логи для ответа
D/ViewRootImpl@36c1a31[MainActivity]: ViewPostIme pointer 0
D/ViewRootImpl@36c1a31[MainActivity]: ViewPostIme pointer 1
I/System.out: StartService
D/ViewRootImpl@36c1a31[MainActivity]: ViewPostIme pointer 0
D/ViewRootImpl@36c1a31[MainActivity]: ViewPostIme pointer 1
I/System.out: Destroy
// проверка кнопки
D/ViewRootImpl@36c1a31[MainActivity]: ViewPostIme pointer 0
D/ViewRootImpl@36c1a31[MainActivity]: ViewPostIme pointer 1
I/System.out: StartService
// запуск, далее сворачивание приложения
D/ViewRootImpl@36c1a31[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0 1
D/InputMethodManager: prepareNavigationBarInfo() DecorView@fa672d7[MainActivity]
D/InputMethodManager: getNavigationBarColor() -855310
D/InputTransport: Input channel destroyed: 'ClientS', fd=68
I/mali_egl: eglDestroySurface() in
I/mali_winsys: delete_surface() [1080x2340] return
I/mali_egl: eglDestroySurface() out
W/libEGL: EGLNativeWindowType 0x7760d9af50 disconnect failed
D/ViewRootImpl@36c1a31[MainActivity]: Relayout returned: old=(0,0,1080,2340) new=(0,0,1080,2340) req=(1080,2340)8 dur=10 res=0x5 s={false 0} ch=true
D/ViewRootImpl@36c1a31[MainActivity]: stopped(true) old=false
// в течении минуты
I/System.out: Destroy

A: При помощи Thread вот так:
public class MyService extends Service {

    private Thread myThread = new MyThread();

    public MyService() {
        super();
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        // Если поток не запущен, то запустить
        if (!myThread.isAlive())
            myThread.start();

        return ...;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // Поток
    private class MyThread extends Thread {

        @Override
        public void run() {
            // Делаем что-то долгое и нудное/нужное
        }
    }
}

A: Решением для меня стал этот ответ - https://stackoverflow.com/questions/44425584/context-startforegroundservice-did-not-then-call-service-startforeground/46449975#46449975
Это нужно добавить в onCreate()
  if (Build.VERSION.SDK_INT >= 26) {
        String CHANNEL_ID = "my_channel_01";
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);

        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("")
                .setContentText("").build();

        startForeground(1, notification);
    }

Если у вас есть свои уведомления, то вы можете завершать это уведомление в onStartCommand() так:
stopForeground(true);

Да, это не очень красиво, но без вибрации и сигнала не заметно (пропадет через секунду). И не забудьте заменить создание уведомлений в вашем сервисе на
startForeground(123, notification);

Без этого работать на версиях >= api 26 не будет. Но возможно есть и другой способ.


text:
Q: writing in Sharelatex, got "File ended while scanning use of \@xargdef." error While trying to compute my report in ShareLaTeX I got the error stating

"File ended while scanning use of \@xargdef."

I've tried looking through the document for an error in curly bracketing {} but I can't seem to find any, haven't been able to find anything on what \@xargdef is either, any help is greatly appreciated.
I made a gist for the code of the document since it is quite long here: https://gist.github.com/ZzimonNanoq/527855642ed275fc0c67
the error message in its entirety is as follows:
File ended while scanning use of \@xargdef.
<inserted text>
\par
<*> main.tex

I suspect you have forgotten a `}', causing me
to read past where you wanted me to stop.
I'll try to recover; but if the error is serious,
you'd better type `E' or `X' now and fix your file.

! Emergency stop.
<*> main.tex

*** (job aborted, no legal \end found)

Here is how much of TeX's memory you used:
7316 strings out of 495028
109339 string characters out of 6181497
229851 words of memory out of 5000000
10500 multiletter control sequences out of 15000+600000
3940 words of font info for 15 fonts, out of 8000000 for 9000
14 hyphenation exceptions out of 8191
42i,0n,43p,1192b,38s stack positions out of 5000i,500n,10000p,200000b,80000s
!  ==> Fatal error occurred, no output PDF file produced!

A: There are two problems noted in your source document.

*

*Definition of \namesigdate is missing a closing brace.  The correct code would be:
\newcommand{\namesigdate}[2][5cm]{%
  \begin{tabular}{@{}p{#1}@{}}
    #2 \\[2\normalbaselineskip] \hrule \\[15pt]
  \end{tabular}}

*Either \begin{comment} used unnecessarily on line 61 or it is not ended promptly in the document.
Fixing the above two issues will solve the problems.


text:
Q: n-th child affecting every n-th child no matter how nested So I am using the nth-child selector to insert an iframe. The basic logic is .selector-div :nth-child(3) where I would select the 3rd child of the div and insert the iframe. The problem is that when I use this selector is will traverse nested elements and look for any 3rd child of nested elements. For example here is a basic structure of the code

random text

 text here
        link
        keyword
        iframe also placed here

iframe here

more text

I do not want the iframe to be embed in that  element but the selector is putting it there as well. Any suggestions?
I tried using :nth-of-type and p:nth-child but I need the insertion of the iframe to be the 3rd element.


text:
Q: How ActiveMQ guarantee msg sent at least once? I have a producer send msg to a ActiveMQ broker, and a consumer subscribe from the same topic. I know that the broker can persist the msg, so as soon as the msg reaches the broker, it can be guaranteed available for the consumer. (right?)
But what happen if the network between producer and ActiveMQ broker is broken, in this case is there a way to guarantee the at-least-once sent? like, the producer itself can persist msg before sending to the ActiveMQ broker?

A: In order for the guarantee to be established the message must reach the broker, if the network is down then the burden is on you to capture the send error and retry the send at a later time.  The ActiveMQ client offers no persistent storage for what it sends, you can use the failover transport and the client will retry the send on reconnect but it the application is shutdown and you haven't provided some means of recovery on restart then there isn't anything more the client can do.


text:
Q: Create a database I want to try to create a database but I get the following error:

Error Code: 1192. Can't execute the given command because you have active locked tables or an active transaction.

The database that I want to create is related to a bank whose tables are: customer, account and operation.
I don't know if I really have PK's or FK's but when creating it I get that error.
-- -----------------------------------------------------
-- Schema Bank
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `Bank` ;

-- -----------------------------------------------------
-- Table `Bank`.`Customer`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Bank`.`Customer` (
  `idCustomer` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `lastname` VARCHAR(45) NOT NULL,
  `DNI` VARCHAR(10) NOT NULL,
  `phone` INT(10) NULL,
  PRIMARY KEY (`idCustomer`)
 ) ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `Bank`.`Account`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Bank`.`Account` (
  `idAccount` INT NOT NULL AUTO_INCREMENT,
  `Customer_idCustomer` INT NOT NULL,
  `numAccount` INT(10) NOT NULL,
  `accountType` VARCHAR(45) NOT NULL,
  `balance` FLOAT (10) NOT NULL,
  `currency` VARCHAR(3) NOT NULL,
  PRIMARY KEY (`idAccount`),
  FOREIGN KEY (`Customer_idCustomer`) REFERENCES `Bank`.`Customer`(idCustomer) ON DELETE CASCADE
  )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `Bank`.`Transaction`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Bank`.`Transaction` (
  `idTransaction` INT NOT NULL AUTO_INCREMENT,
  `Customer_idCustomer` INT NOT NULL,
  `Account_idAccount` INT NOT NULL,
  `transactionType` VARCHAR(45) NOT NULL,
  `transactionDate` DATE  NOT NULL,
  PRIMARY KEY (`idTransaction`),
  CONSTRAINT FOREIGN KEY (`Customer_idCustomer`) REFERENCES `Bank`.`Customer`(idCustomer) ON DELETE CASCADE,
  UNIQUE KEY (idTransaction),
  FOREIGN KEY (`Account_idAccount`) REFERENCES `Bank`.`Account`(idAccount) ON DELETE CASCADE
  )
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

I'm not sure if I have the database well implemented

A: Could it be so easy that you have running transactions that are not commited yet?
Or that the word  transaction are an reserved word?


text:
Q: Retrieving Value from a WebElement using XPATH in Javascript I have a WebElement which has a xpath as "//input[@type='date']" and it has a value as '11/08/2020'. I am using document.evaluate as below in javascript:
document.evaluate("//input[@type='date']", document, null, XPathResult.ANY_TYPE, null).
I am trying to retrieve the value (i.e. '11/08/2020'). I tried all the below mentioned options, but these options are not working

*

*document.evaluate("//input[@type='date']", document, null, XPathResult.ANY_TYPE, null).value ->
It shows 'undefined'

*document.evaluate("//input[@type='date']", document, null, XPathResult.ANY_TYPE, null).stringValue ->
It shows "Failed to read the 'stringValue' property from 'XPathResult': The result type is not a
string."

*document.evaluate("//input[@type='date']", document, null, XPathResult.ANY_TYPE, null).numberValue ->
It shows "Failed to read the 'numberValue' property from 'XPathResult': The result type is not a
number."

The 'ResultType' of the XpathResult is "4".
Could you please help me to know how I can retrieve the value from the WebElement.
Thanks...


text:
Q: Event listener for end of video I have a symbol button that starts to play a video (but and video are on frame 1 of the root timeline).
I would like the timeline to go to frame 2 (and show some text) at the end of the video.
Please can someone help point me in the right direction?
I would be most grateful.


text:
Q: Splitting a string in R Consider:
x<-strsplit("This is an example",split="\\s",fixed=FALSE)

I am surprised to see that x has length 1 rather than length 4:
> length(x)
[1] 1

like this, x[3] is null. But If I unlist, then:
> x<-unlist(x)
> x
[1] "This"    "is"      "an"      "example"
> length(x)
[1] 4

only now x[3] is "an".
Why wasn't that list originally by length 4 so that elements can be accessed by indexing? This gives troubles to access the splitted elements, since I have to unlist first.

A: This allows strsplit to be vectorized for its input argument. For instance, it will allow you to split a vector such as:
x <- c("string one", "string two", "and string three")

into a list of split results.
You do not need to unlist, but rather, you can refer to the element by a combination of its list index and the vector index. For instance, if you wanted to get the second word in the second item, you can do:
> x <- c("string one", "string two", "and string three")
> y  <- strsplit(x, "\\s")
> y[[2]][2]
[1] "two"

A: That's because strsplit generates a list containing each element (word).
Try
> x[[1]]
#[1] "This"    "is"      "an"      "example"

and
> length(x[[1]])
#[1] 4


text:
Q: Cannot convert json that have null type I need to deserialize this json using NewtonsoftJson:
{
    "players": [
    {
        "player_id": "331574",
        "team_id": "95",
    },
    {
        "player_id": "331575",
        "team_id": "95",
    }],
    "coach":
     {
        "id": "249197",
        "first_name": "Guillermo",
    }
}

so I have this class:
 public class Squad
    {
        public List<Player> players { get; set; }
        public Coach coach { get; set; }

        public class Coach
        {
            public int id { get; set; }
            public string first_name { get; set; }
        }

        public class Player
        {
            public int player_id { get; set; }
            public int team_id { get; set; }
        }
    }

for deserialize I use:
return JsonConvert.DeserializeObject<Squad>(content);

now sometimes I get the coach null:
 {
    "players": [
    {
        "player_id": "331574",
        "team_id": "95",
    },
    {
        "player_id": "331575",
        "team_id": "95",
    }],
    "coach": []
  }

So I implemented the converter suggested in this question: How to handle both a single item and an array for the same property using JSON.net
in particular, the only edit I did was:
[JsonConverter(typeof(SingleOrArrayConverter<object>))]
 public Coach coach { get; set; }

but I get this error when deserialize:

Can not cast objects of type 'System.Collections.Generic.List`1 [System.Object]' on the 'Coach' type.

A: You just need to change Coach to be List<Coach>
class Program
{
    static void Main(String[] args)
    {
        var str1 = "{\"players\":[{\"player_id\":\"331574\",\"team_id\":\"95\",},{\"player_id\":\"331575\",\"team_id\":\"95\",}],\"coach\":{\"id\":\"249197\",\"first_name\":\"Guillermo\",}}";
        var obj1 = JsonConvert.DeserializeObject<Squad>(str1);

        var str2 = "{\"players\":[{\"player_id\":\"331574\",\"team_id\":\"95\",},{\"player_id\":\"331575\",\"team_id\":\"95\",}],\"coach\":[]}";
        var obj2 = JsonConvert.DeserializeObject<Squad>(str2);
    }
}

public class Squad
{
    public List<Player> players { get; set; }

    [JsonProperty("coach")]
    [JsonConverter(typeof(SingleOrArrayConverter<Coach>))]
    public List<Coach> coach { get; set; }
    public class Coach
    {
        public int id { get; set; }
        public string first_name { get; set; }
    }

    public class Player
    {
        public int player_id { get; set; }
        public int team_id { get; set; }
    }
}

class SingleOrArrayConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>();
        }
        return new List<T> { token.ToObject<T>() };
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}


text:
Q: MySQLi query about Is Empty Table Or Not? I'm trying to know is some table is empty or no, now I am realized this issue with this code:
// if table is empty it must return TRUE, if full FALSE

private function isEmpty($tableName)
{

    if ($result = $this->mysqli->prepare("SELECT COUNT(*) FROM ?"))
    {

            $result->bind_param("s",$tableName);
            $result->execute();
            $row_cnt = $result->num_rows;

            if (empty($row_cnt))
            {

                    return TRUE;

            }
            else
            {

                    return FALSE;

            }

    }

}

this code seems not a really perfect, I would like to know is there a better way to get the same results, but using predicat SQL EXISTS or something else? Thank you.
updated:
thanks for comments and answer, but anyway I dont have a clue how to do it, it's calls an error:
$mysqli = new mysqli("localhost","root","","database");

if ($result = $mysqli->prepare("SELECT COUNT(*) FROM `talbe` LIMIT 1"))
{

    $row = $result->fetch_row();

    echo "<pre>";
    print_r($row);
    echo "</pre>";

    $result->close();

}
$mysqli->close();

[Sat Jun 09 11:25:34 2012] [error] [client 127.0.0.1] PHP Fatal error:
  Call to undefined method mysqli_stmt::fetch_row() in
  F:\server\sites\home\test.loc\www\empty.php on line 9

updated:
$mysqli = new mysqli("localhost","root","","db");

if ($result = $mysqli->query("SELECT * FROM `table` LIMIT 1"))
{

    if ($obj = $result->fetch_object())
    {

        echo "NOT EMPTY";

    }
    else
    {

        echo "empty";

    }

    $result->close();

}
$mysqli->close();

this is it.

A: COUNT(*) is fine for determining if a table is empty, providing the table doesn't have huge number of rows.
Another alternative would be SELECT (something) FROM ${table} LIMIT 1; if that returns a result then the table isn't empty.
But are you sure it's possible to set table name via a parameter like that in mysqli?  I didn't think it was, need to check.


text:
Q: Payment with Stripe on Rails I have followwed many tutorials from the internet to find out how to payment with card credit. All i go so far is:
My payment form:
<%= form_for(@payment, :html => {:id => 'payment-form'}) do |f| %>

                <%= f.label :name %>
                <%= f.text_field :name, :class => 'form-control' %>

                <%= f.label :phone %>
                <%= f.text_field :phone, :class => 'form-control' %>

                <%= f.label :address %>
                <%= f.text_area :address, :class => 'form-control' %>

                <%= f.label 'Payment Type' %>
                <%= f.select :pay_type, Payment.pay_types.keys, {},:class => 'form-control' %>

                Card Number
                <input type="text" size="20" autocomplete="off" data-stripe="number" id="number" class="credit-number form-control" placeholder = "**** **** **** ****" value = "4242424242424242" pattern="[\d ]*" />

                Security Code/CVC
                <input type="text" size="4" autocomplete="off" data-stripe="cvc" id="cvc" class="credit-scurity form-control" placeholder="***" value = "123" pattern="\d*" />

                Expiration (MM/YYYY)
                <input type="text" size="2" data-stripe="exp_month" id="exp-month" class="card-expiry-month form-control" placeholder="MM" pattern="\d*" />
                 /
                <input type="text" size="4" data-stripe="exp_year" id="exp-year" class="card-expiry-year form-control" placeholder="YYYY" pattern="\d*" />

                <%= f.submit 'Place order', :class => 'btn btn-primary btn-payment' %>

        <% end %>

And the script in this form:
jQuery(function ($) {
  var show_error, stripeResponseHandler;
  $("#payment-form").submit(function (event) {
    var $form;
    $form = $(this);
    $form.find("input[type=submit]").prop("disabled", true);
    Stripe.card.createToken($form, stripeResponseHandler);
    return false;
  });
  stripeResponseHandler = function (status, response) {
    var $form, token;
    $form = $("#payment-form");
    if (response.error) {
      show_error(response.error.message);
      $form.find("input[type=submit]").prop("disabled", false);
    } else {
      token = response.id;
      $form.append($('<input type="hidden" name="stripeToken" />').val(token));
      $("[data-stripe=number]").remove();
      $("[data-stripe=cvv]").remove();
      $("[data-stripe=exp-year]").remove();
      $("[data-stripe=exp-month]").remove();
      $form.get(0).submit();
    }
    return false;
  };

  show_error = function (message) {
    $("#flash-messages").html('
×
' + message + '

');
    $('.alert').delay(5000).fadeOut(3000);
    return false;
  };
});

payments.controller:
def create
    @payment = Payment.new(payment_params)
    Stripe.api_key = "sk_test_Hm0ywtd94a4e27SHOfzVJLpZ"
    @cart = current_cart
     @amount = @cart.total_price.to_i * 100

      token = params[:stripeToken]
      debugger
      # Create a Customer
      customer = Stripe::Customer.create(
        :description => params[:email],
        :card => token
      )

  charge = Stripe::Charge.create(

    :customer    => customer.id,
    :amount => @amount, # amount in cents, again
    :currency => 'usd',
    :card => token,
    :description => params[:email]
  )
    if @payment.save
        @payment.add_line_items_from_cart(current_cart)
        Cart.destroy(session[:cart_id])
        session[:cart_id] = nil
        redirect_to root_path
    else
        render 'new'
    end
end

Now i get the error: "Cannot charge a customer that has no active card"
I'm try debugging and the problem is:
token = params[:stripeToken]

the params[:stripeToken] is nil then token is nil too.
Please help me

A: George, if params[:stripeToken] is nil it's a good bet it's never being appended to the form in the first place. Look at your javascript:
 if (response.error) {
  show_error(response.error.message);
  $form.find("input[type=submit]").prop("disabled", false);
} else {
  token = response.id;
  $form.append($('<input type="hidden" name="stripeToken" />').val(token));

My best guess is you're getting an error which prevents your $form.append code from happening.
To test my theory you should inspect the form in question for errors.
https://developers.google.com/web/tools/chrome-devtools/javascript/


text:
Q: How I can add an object to a list in python? def guardar(self):

    sAux=""

    combobox=self.ui.cmbItems.currentText()

    cantidad=str(self.ui.spinBox.value())

    subtotal=self.ui.txbSeleccion.text()

    costounidad=self.ui.txbCostoU.text()

    sAux=cantidad+"--"+combobox+" $(unidad)"+costounidad+" $(total)"+subtotal
    self.ui.textBrowser.append(sAux)

I want to pull the sum of the subtotal (I'm using qt4 if in doubt)
anyone know how I can do?, thanks


text:
Q: How can i adjust my iframe I'm trying to adjust my iframe with one scrollbar and auto height the iframe but i dont know how. How can i do that?. The code is here

A: You can just allow the iframe taking the full width and hide the body overflow. For this, modify your HTML to following,

And use the following CSS,
    iframe{
        min-width:100px;
        width:100%;
        height:100%;
    }
    body{
        overflow:hidden;
        height: 100%;
        margin: 0px;
        padding: 0px;
    }
    html {
        height: 100%;
    }

A: adding the following to the head section  of the code might solve the problem

add this as an atttribute inthe iframe element
onload='javascript:resizeIframe(this);'


text:
Q: How do I determine a React Native Navigation tab button's accessibility ID? I'm trying to determine why one of my tests (using appium to drive a React Native app on the iOS simulator) is failing to find one of the React Native Navigation tabs in our app by the value provided as its testID.  The test is using elementByAccessibilityId, and only seems to fail when the simulator is running iOS 10.0 vs. succeeding on 10.2 and 10.3.  I'd like to verify that the accessibilityIdentifier has been set from the testID correctly, but (a) the buttons do not seem to appear in the React Developer Tools Inspector; and (b) neither the Accessibility Inspector that ships with XCode 8.3.3 nor the one that ships with 9.1 seems to display this field (though apparently the tools for 9.1b2 did).
The answer I'm hoping for is either:

*

*How do I ensure that the correct accessibilityIdentifier is set on the Navigation tab buttons, so I can continue investigating why appium is unable to find the button?

*or; does anyone know why appium is able to find the tab under 10.2 & 10.3 but NOT under 10.0?  I didn't find anything via web search indicating some change to accessibility APIs across 10.0 -> 10.2.

Also, if I'm barking up the wrong tree or missing something completely separate, guidance is appreciated.

A: I discovered that our team is using a fork of React Native Navigation, which makes it difficult for me to determine whether this is a bug in RNN itself or was introduced into our fork.  Still unclear what the root cause is or why it would be platform specific.
However, I am able to work around this issue by using label instead of testID in the tab definition provided to RNN.  This has the side effect of adding text labels, but that is probably more correct than having no text labels anyway.


text:
Q: Getting html content from one page and adding it to my website I have affiliated with expedia and I am using their API system. One of their requirements for launching the site is adding the terms and agreements to my page and they give us this page: http://travel.ian.com/index.jsp?pageName=userAgreement&locale=en_US&cid=xxx. I do not want to go to a different site, and I can not copy and paste the information because of updates. I also prefer not to use an iframe. Does anyone have any ideas on how to do this? Here is a webpage using this on their site with their domain: http://www.helloweekends.com/terms.htm. Does anyone know how they did this? Any help would be greatly appreciated!

A: Since it originates from another domain, it wouldn't be possible to use JavaScript, due to the same origin policy. Also, relying on JavaScript for the update would be trouble for users who has JavaScript disabled, as they wouldn't see the terms. Since you don't want to use an iframe, or copy the content, I guess your best shot would be to scrape their page with a server-side language of your choice, and then display it on your page.
Scraping can be a bit tricky though, if you rely on their markup. If they change their markup, there is a chance that your script will break, thus stop updating the terms.
There are various tutorials available on how to scrape sites. Here are a few PHP examples:

*

*Web scrape with PHP

*PHP Screen Scraping Tutorial
Note Make sure that they allow you to scrape the page prior to implementing it, so that you don't violate their rules.

A: Do you know if their API serves something with JSON? A JSONP call can get the values to you, but it will make your page rely on javascript for the users to see the updated page.
Another option is to use PHP of any other server side language to get the contents of the url, process it and return the block you require.

A: I would suggest the load() function offered by jQuery. It makes a simple AJAX call to retrieve a file, and you could even use a selector to only grab part of the page. For example, load the contents of a HTML page into a div:
$('#div_id').load('my_file.html');

Or just load a part of the page:
$('#div_id').load('my_file.html #main_text_id');


text:
Q: When limit of derivative of uniformly convergent sequence of functions is equal to derivative of limit function? Suppose $\{f_n(x)\}\to f(x)$ [uniformly] on $X$.
We know we can't claim much about convergence of derivative $\{f'_n(x)\}$, and it may not even be pointwise convergent.
All the counter-examples I have seen till date, appear to have either non-differentiable sequence of functions or pointwise divergent derivatives or non differentiable limit function.
But, what if at some point $x_0$, $\{f'_n(x_0)\}$ converges and $f'(x_0)$ exists. Can we claim that both are equal? If not, is there any strong condition, which can ensure that equality holds?
EDIT
After some digging I have found a counterexample  :-
$$f_n(x)= \dfrac { x } { 1 + n ^ { 2 } x ^ { 2 } } \to f(x)=0 \text{ [uniformly] }  \quad \text{for } x\in [-1,1]  $$
$$f _ { n } ^ { \prime } ( x ) = \frac { 1 - n^2x ^ { 2 } } { \left( 1 + n^2x ^ { 2 } \right) ^ { 2 } }$$
Here, $f_n'(0)\to 1 \ne f'(0)$
Still not clear about the second part. Is there any condition, which only need uniform convergence of $\{f_n\}$, pointwise convergence of $f'_n(x_0)$ and existence of $f'(x_0)$, which can ensure that $f'_n(x_0)=f'(x_0)$ ?

A: What about $\cos(nx)/n$? We have $\cos(nx)/n\rightrightarrows 0$ everywhere. And $$(\cos(nx)/n)'=\sin(nx).$$
We note that $\sin(n0)\to 0$. However $\sin(nx)\not\rightarrow 0=0'.$
There is a stronger condition that we can use, namely if $f'_n\rightrightarrows g$ on $[a,b]$, and $f_n(x_0)\to c$ for some $c\in\mathbb{R}$ and $x_0\in[a,b],$ then there exists a function $f$ such that $f_n\rightrightarrows f$ on $[a,b]$ and on $[a,b]$ we have $f'=g$. This is Theorem $7.17$ In Rudin's Book Principles of Mathematical Analysis.


text:
Q: Is it possible to apply primary key on the text fields in android database I have created a simple table that contains the name and email id's of the persons. When i am giving the create query like this:
"create table contacts (name text not null, email text primary key not null);"
But this is not working. I'm not getting any exception or error while running nor the primary key is working. While browsing the table using SQLite browser i observed that there are only four data types:

Is it possible to apply primary key only on integer? What is the case if i want primary key on text fields. Thank you. This is the code that i used:
public class DBAdapter {

public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "contacts";
private static final int DATABASE_VERSION = 2;

private static final String DATABASE_CREATE =
    "create table contacts (_id integer primary key autoincrement, "
    + "name text not null, email text not null);";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        try {
            db.execSQL(DATABASE_CREATE);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }
}

//---opens the database---
public DBAdapter open() throws SQLException
{
    db = DBHelper.getWritableDatabase();
    return this;
}

//---closes the database---
public void close()
{
    DBHelper.close();
}

//---insert a contact into the database---
public long insertContact(String name, String email)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_EMAIL, email);
    return db.insert(DATABASE_TABLE, null, initialValues);
}

//---deletes a particular contact---
public boolean deleteContact(long rowId)
{
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

//---retrieves all the contacts---
public Cursor getAllContacts()
{
    return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
            KEY_EMAIL}, null, null, null, null, null);
}

//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
    Cursor mCursor =
            db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
            KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,
            null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

//---updates a contact---
public boolean updateContact(long rowId, String name, String email)
{
    ContentValues args = new ContentValues();
    args.put(KEY_NAME, name);
    args.put(KEY_EMAIL, email);
    return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}

A: as per the faq of sqlite documentation, using TEXT as a datatype for primary key should work.
i used your query and here it is, the table is created.
CREATE TABLE contacts ( email text primary key not null, name text not null);

INSERT INTO contacts VALUES ('sample@email.com', 'sample')
INSERT INTO contacts VALUES ('people@email.com', 'sample')

now here is where it went wrong.
when i ran this again
INSERT INTO contacts VALUES ('sample@email.com', 'sample')

nothing happened, no errors.
But it did not update the record. so i conclude data integrity is there but you don't get any feedback about the failure.

A: SQLiteDatabase.insertOrThrow() should throw an exception if the value could not be inserted.
Also its return values, as well the one from SQLiteDatabase.insert() is the rowid of the inserted row or -1 if it fails. You should opt for any of these alternatives in your code.


text:
Q: MacBook Pro (13-inch, 2016, Two Thunderbolt 3 ports) - Increasing Battery Life Hi How to effective Battery charge in MacBook Pro (13-inch, 2016, Two Thunderbolt 3 ports).
As per my previous experience , i was using MacBook Air and i charge it 100 % and wait till drain then again Charge it. I used it two years, with in two years. Battery got damaged.I am worry about my new MacBook Pro.
My Doubts are-
1- Charge it 100% and wait upto 20 % and again charge full.
2- Charge 100% and Wait till it drain 1% and again charge it.
2- Always Charge MacBook Pro, when it is in use
3- How to increase Battery life of MacBook Pro
I have gone through it https://discussions.apple.com/thread/5689236?tstart=0 . but really not able to understand key points.
Please help me out to increase Battery life of my mac book pro


text:
Q: C# ERROR Operator * cannot be applied to operands of type 'string' and 'string' public partial class Form1 : Form
{
    string principal, rate, years;
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        principal = loantextBox4.Text;
        rate = ratetextBox5.Text;
        years = yearworktextBox2.Text;

        outputlabel5.Text = principal * ((rate * (1 + rate) ^ years) / ((rate + 1) ^ years) - 1))));

What needs to be fixed I keep getting an error saying operator "*" cannot be applied to operands of type 'string' and 'string'.

A: You cannot apply mathematical operations on a string variable and thus you need an int or double type. I have used int. Secondly When you try to get the TextBox data in the int variable it would not be possible because TextBox.Text would return a string. Now You can convert the TextBox.Text to a int using Convert.ToInt32. If you try to put the values of the Textbox to int variable without conversion, it will give you an error stating

Cannot implicitly convert type 'string' to 'int'

and it would not even compile the program.
Whereas letz say if the user input in not a number and it we try to Convert it. For example the user input is "Mohit" and when it tries to convert the Convert.ToInt32("Mohit"); it will throw an exception. stating

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

You can avoid getting exception or to handle the wrongly input from the user you can use Try and Catch Block
Hope this code will give you the idea
public partial class Form1 : Form
{
    int principal, rate, years;
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        principal = Convert.ToInt32(loantextBox4.Text);
        rate = Convert.ToInt32(ratetextBox5.Text);
        years = Convert.ToInt32(yearworktextBox2.Text);

        outputlabel5.Text = (principal * ((rate * (1 + rate) ^ years) / ((rate + 1) ^ years) - 1)).ToString();

A: You can't multiply strings.  You can, however, multiply numbers.  Convert your numeric strings to numbers.  For example:
int years;
if (!int.TryParse(yearworktextBox2.Text, out years))
{
    // string value wasn't numeric, maybe show an error?
    // probably return from here as well, since the logic can't continue
}
// here the "years" value can be used for calculations

Remove the string variables you have, replace them with numeric values (int, decimal, double, etc. where appropriate) which are populated by parsing the input strings using .TryParse() (and handling errors accordingly), then you can use those values in your calculations.

A: Because all of your inputs are strings. You can't multiply a string.
What you need to do instead is change them to a number format. Probably just int should be fine.


text:
Q: Redmine under sub-directory on nginx My vhost configuration: http://pastebin.com/ZyXUmQtx (only one domain on this installation)
I've been racking my head and Google for a solution the last two days and can't quite seem to come up with a solution that works.
My setup (from the above configuration):

*

*IP.Board 3.4 installation in %root_domain%/forums/

*IP.Content 2.3 installation in %root_domain/forums/ (with external access index.php on the top-level)

*Redmine 2.2.2 install at /usr/share/redmine (this is working because Thin is running and there are no errors in either log file)

*Stale phpMyAdmin configuration at /usr/share/phpmyadmin/ that also kinda doesn't load html/css properly.

*Symlink to /usr/share/redmine/public to /srv/www/tiberian-genesis.net/public_html/redmine
I'm trying to get redmine setup to run under %root_domain%/redmine/, but I keep getting a 404 page from my IP.Content installation.
Accessing it takes me to the url: /redmine/login?back_url=http://redmine_thin_servers/redmine/ (which now that notice it, it seems to not like my upstream...)
In case someone requests the Thin configuration file:
---
pid: /var/run/thin/redmine.pid
group: tgmod
prefix: /redmine
timeout: 30
log: /var/log/thin/redmine.log
max_conns: 1024
require: []

max_persistent_conns: 512
environment: production
user: tgmod
servers: 1
daemonize: true
chdir: /usr/share/redmine
socket: /var/run/thin/redmine.sock

I'm out of ideas here.
Thanks in advance!

A: I just ended up setting it up on a sub-domain. I wanted to try to proxy it on a sub-directory, but my main website kept interfering with the rules.


text:
Q: Using an ellipse as a threshold for Nearest function The Nearest function can receive as a threshold parameter a radius to look for elements inside that. From the documentation:

Nearest[data,x,{n,r}] give up to the n nearest elements to x within a radius r

What about if instead of a circle I want to use an ellipse as a threshold? So I would have an X and Y limit for the Nearest function.
I know that Nearest can receive a DistanceFunction as a parameter but I can't think of how to use that for this purpose.
Any ideas?

A: DistanceFunction is one way to go. For example, the code below generates a random set of points in the box with all elements drawn from -1 to 1 and then selects the 20 points that are closest to the point {0.5, 0} (in the sense of an ellipse defined by the matrix a). In the example, a is tall and skinny, but could have any orientation and scale.
data = RandomReal[{-1, 1}, {100, 2}];
a = {{2, 0}, {0, 1/2}};
f[x_, y_] := Norm[a.(x - y)];
nf = Nearest[data, {0.5, 0}, 20, DistanceFunction -> f];
ListPlot[nf, PlotRange -> {{-1, 1}, {-1, 1}}]

A: I guess one method would be to take the larger radius of your ellipse to collect all possible candidates with
Nearest[data,x,{n,r}]

and after that filter them with e.g. Select to find all points that are inside your ellipse.

A: The simplest solution is to rescale the data.  Suppose we have a distance limit of $r_x = 2$ and $r_y = 1$ and a point set
data = {{x1,y1}, {x2,y2}, ...}

Instead of working with data and these two radii, work with a single radius $r=1$ and the dataset
dataScaled = {{0.5 x1, y1}, {0.5 x2, y2}, ...}

Finally, transform the results back to the original coordinate system.
This can be generalized for arbitrary affine transformations, including rotations.
For example, let's assume that the ellipse is rotated 30 degrees and it has dimensions 2 and 1.  This can be obtained from a circle by using the following transformation matrix:
backtrafo = N[RotationMatrix[30*Degree] . {{2, 0}, {0, 1}}]

Let's visualize it!
Graphics[GeometricTransformation[Circle[], AffineTransform[backtrafo]], Frame -> True]

We need to apply the reverse transformation of this on our data and use the result in Nearest:
trafo = Inverse[backtrafo];

Nearest[trafo.# & /@ data -> data, trafo.point, {n, 1}]

This will give us the all the points within the rotated ellipse drawn around point.

Let's test the method visually.  Generate some points:
data = RandomReal[{-2, 2}, {100, 2}];

Find the points within the ellipse centred on the origin:
pointsWithin = Nearest[trafo.# & /@ data -> data, trafo.{0, 0}, {Infinity, 1}];

And finally visualize all points together with the ellipse:
Graphics[{
  GeometricTransformation[Circle[], AffineTransform[backtrafo]],
  Point[data], {Red, Point[pointsWithin]}}, Frame -> True]

Technical comment: An advantage of this method compared to using a DistanceFunction is that a custom DistanceFunction will prevent Nearest from using a very efficient quad-tree data structure, and it will resort to a much slower pairwise-distance calculation.

Thanks to Michael E2 for suggestion on simple and efficient code!


text:
Q: Handling Oracle Procedures returning nested table types in Java I am using Java to invoke Oracle procedures and some these procedures have their OUT parameters as nested table types.
I need to then process the data in the nested table types and even their metadata (attributes of nested table) are required for processing.
OracleCallableStatement stmt = null;
//Build the call here
StringBuilder call = new StringBuilder("{call ");
call.append(procName);
call.append("}");

System.out.println(call.toString());

conn = _motifUserDataSource.getConnection();
System.out.println("PREPARING : "+call.toString());
stmt = (OracleCallableStatement)conn.prepareCall(call.toString());
// The return parameter is an ARRAY type (nested table)
stmt.registerOutParameter(1, OracleTypes.ARRAY, "TABLE_NTT");
stmt.execute();

// Get the return value and covert it into a JDBC ResultSet
ARRAY array = (ARRAY) ((OracleCallableStatement)stmt).getOracleObject(1);
rs=array.getResultSet();

ResultSetMetaData metadata = rs.getMetaData();

Problem:
When I try the above code, I get the following error
Caused by: java.sql.SQLException: Unsupported feature: getMetaData
at oracle.jdbc.driver.ArrayDataResultSet.getMetaData(ArrayDataResultSet.java:1013)
at com.Testdb.execCheckRefCursorData

I need this metadata to identify the attributes/column names which is required during the processing stage.
Any inputs on how I can handle nested table type OUT parameters and extract both the data and metadata information from them using Resultset?


text:
Q: Visual Studio not detecting Forms I have checked out an existing WinForms using SDK-Style csproj file, and Visual Studio does not detect the forms as forms that can be designed. As such, the WinForms designer cannot be used.
I can also reproduce this issue by creating a new net6 WinForms project and then deleting the csproj.user file containing information about the SubType. After reading about similar bugs in previous Visual Studio versions, the forms should be automatically detected and added to csproj.user file. However, this does not appear to happen for me.
Visual Studio version: 17.4.4
csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

A: After further testing and contact with Visual Studio support, I figured out that the issue is related to the "Run code analysis in separate process" setting. If this setting is disabled, Visual Studio does not detect the forms on its own. After enabling it, everything works as expected.

A: It's possible that the csproj file is missing some necessary references or metadata for the WinForms designer to work correctly. You can try adding the following lines to your csproj file to specify the  of your form files and to include the WinForms designer target:
<PropertyGroup>
  <TargetWinForms>true</TargetWinForms>
</PropertyGroup>

<ItemGroup>
  <Compile Update="Form1.cs">
    <SubType>Form</SubType>
  </Compile>
  <Compile Update="Form1.Designer.cs">
    <DependentUpon>Form1.cs</DependentUpon>
    <SubType>Form</SubType>
  </Compile>
</ItemGroup>

Replace Form1.cs and Form1.Designer.cs with the names of your actual form files.
If this doesn't work, you can try recreating the project with the WinForms template in Visual Studio to ensure that all necessary references and metadata are included. Then, copy your existing source code into the new project.


text:
Q: "The Python ssl extension was not compiled. Missing the OpenSSL lib?" error when installing Python using pyenv While installing Python using pyenv, I am getting the following error:
ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib?

I am using Ubuntu 18.04 Bionic Beaver How do I solve this issue?

A: If the python version you are trying to install is equal or lower than 2.7.12, it does not support OpenSSL1.1.0, so you would need to replace libssl-dev with libssl1.0-dev.
Ubuntu 18.04 is the first official release to switch to OpenSSL1.1.0 which is why you might not have been impacted with this in the past.
Reference:
https://github.com/pyenv/pyenv/issues/945
https://github.com/pyenv/pyenv/wiki/common-build-problems#error-the-python-ssl-extension-was-not-compiled-missing-the-openssl-lib

A: check you version: openssl version
pyenv install 3.9 #ok
pyenv install 3.10 #error
Currently Python versions 3.6 to 3.9 are compatible with OpenSSL 1.0.2,
1.1.0, and 1.1.1. For the most part Python also works with LibreSSL >= 2.7.1
with some missing features and broken tests.

A: According to the documentation, a simple:
pip install pyopenssl

should do the job. If pip is not installed, run
sudo apt install python-pip

and then run the command again.


text:
Q: window.print div element showing whole page on android chrome (prints div section on win 10 chrome) I'm trying to print the text inside the div on android chrome
This works on windows 10 chrome
but on android chrome, it prints, but shows the whole page
with header and print button.
Any help appreciated
<!DOCTYPE html>

 Test print

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

            I'm trying to print the text inside the div on android chrome

            This works on windows 10 chrome

            but on android chrome, it prints, but shows the whole page

            with header and print button.

        <button  id="print" onclick= "printDiv('PrintMe')" > Print </button>


text:
Q: Is creating an inheritance chain of WinForms going to bite me? Suppose I have a base form Main1 which may need to be altered slightly, including perhaps adding additional Controls and altering the size/location of existing Controls.  Those base Controls which I need to alter I set to 'protected' in the designer.  So I have another form, Main2, that derives from Main1.  Then I have another form, Main3, which has even more additions/alterations but needs the additions of the 2nd form.  And so forth.  My inheritance chain looks like:
MainX : Main(X - 1) : ... : Main2 : Main1
This works great and allows me to have designer support when moving around and resizing Controls, but I am always wary of inheritance in general and especially when I have a chain this big.
Am I going to pay for this later?

A: Inheritance is your friend.
Another approach would be to use nested master pages, which may make more sense depending on your application. I'd avoid creating new classes just to change control size or other markup-related content.

A: I've done this a lot in the past (admittedly not much past 3 or so levels deep) and it's worked pretty well. From time to time the controls seemed to disappear in my "inheriting" form (normally at creation time), but that was back in VS2002/2003 and .net 1.0/1.1. As long as I could call up the finished form successfully (i.e. all controls present and correct) everything was OK.


text:
Q: Sorting products with Ajax I am trying to sort products using ajax but somehow the products won't get sorted.
$(document).ready(function() {
  //sort in ajax
  $("#sort").on('change', function(e) {
    e.preventDefault();

    var sort = $("#sort").val();
    var url = $(location).attr('href');

    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });

    $.ajax({
      url: url,
      method: 'POST',
      data: {
        sort: sort,
        url: url
      },
      success: function(data) {
        $('.filter_raffles').html(data);
        console.log(sort, url);
      }
    })
  });
});

I tried to console.log the chosen sort and url, and it show those results.

What's wrong with my code?


text:
Q: Reverse proxy with httputil and gorilla/mux I've been trying to reverse proxy some of my requests internally with httputil.NewSingleHostReverseProxy(*Url)
I noticed that gorilla mux is not happy with this so I found a fix online that solved the issue for GET requests.
However, it seems like like GET is the only request that will be reverse proxied correctly.
u = generated URL with url.Parse
api.Path("/feature").Methods("POST").HandlerFunc(handler(httputil.NewSingleHostReverseProxy(u)))

func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        r.URL.Path = mux.Vars(r)["path"]
        p.ServeHTTP(w, r)
    }
}

This works fine for GET requests, but when sending a POST or PATCH the receiving http method is set as GET. I have confirmed that the proxy's r.Method is POST on one end and GET on the other.
Has anyone encountered this issue before, or know what could be causing this?

A: This error was caused by the route returning a 301 still unclear why. ReverseProxy's fallback behavior on 301, 302, 303 is to support RFC 2616
https://github.com/golang/go/issues/18570
This rewrites the Method to GET


text:
Q: Как правильно сверстать заголовок с задним фоном? Есть тег main и в нем есть заголовок(h1), но у заголовка сзади фон(только у заголовка). И я думаю по семантике лучше обернуть этот заголовок в header, но тогда если я правильно понимаю заголовок будет озаглалавлять только header, тогда получается единственный вариант обернуть его div(заголовок)?

A: В тег header обычно размещают логотип и навигацию. Ваш h1 это уже main. Вполне нормально, если для задания фона вы h1 обернёте в div или section.

A: Вы можете сделать хоть вот так.

body {margin: 0;}

h1 {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  margin: 0;
  background: url('//i.imgur.com/raz226g.png') no-repeat center center / cover;
  text-align: center;
  color: #fff;
}

Заголовок
с задним
фоном

По сути, вам никто не запрещает так делать.

A: Обычно на практике верстальщики используют стили для h1-h6, p, span только визуальные (font-size, color, font-family ....)
Поэтому да, лучше завернуть его в div, а этот div в header, так как он более тяготеет к верхней части страницы.


text:
Q: Authentication token always null in kernel.request event in Symfony 2? I'm tring to write a basic listener for kernel.request event in Symfony 2. Service definition is pretty simple and annotations come from JMSDiExtraBundle.
The problems is that $context->getToken() is always null even the user is fully authenticated:
/**
 * @Service("request.set_messages_count_listener")
 *
 */
class RequestListener
{

    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    private $container;

    /**
     * @InjectParams({"container" = @Inject("service_container")})
     *
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @Observe("kernel.request", priority = 255)
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $context = $this->container->get('security.context');
        var_dump($context->getToken()); die();
    }

}

I think my security setup is working fine. What could be the problem then?
secured_area:
    pattern:    ^/app/
    switch_user: true
    form_login:
        check_path: /app/login_check
        login_path: /app/login
        default_target_path: /app/dashboard
        always_use_default_target_path: true
    logout:
        path:   /demo/secured/logout # TODO
        target: /demo/               # TODO

access_control:
    - { path: ^/app/login,    roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/app/users,    roles: ROLE_MNG_USERS }
    - { path: ^/app/messages, roles: ROLE_MNG_USERS }
    - { path: ^/app/roles,    roles: ROLE_MNG_PACKAGES_FEATURES }
    - { path: ^/app/packages, roles: ROLE_MNG_PACKAGES_FEATURES }
    - { path: ^/app/,         roles: ROLE_USER }

A: With priority = 255, your listener is called BEFORE the security firewall (priority = 8, look here).
Try to change your priority.


text:
Q: Como visualizar dados de um banco de dados Cordova? Gostaria de saber se existe um meio de acessar e visualizar dados gravados de um banco de dados Cordova?
Tenho uma aplicação mobile (Android e iOS) e sei que posso visualizar os registros usando log ou alert mas, existe alguma forma de visualizar estes dados no aparelho seja por um aplicativo ou outro meio?
Aplicativos Android nativos usavam o SQLite Database Browser mas não funciona com o Cordova.
Obrigado pela resposta e desculpe a demora! Tentei adicionar o ip, hostname e não é concluído o processo de adicionar o pc no smartphone. Apresenta erro informando que não foi localizado. Ao tentar deixar o smartphone localizar algum pc em rede, também não localiza.

A: *

*No seu Desktop instale no Navegador chrome a extensão Adobe Edge Inspect CC.

*No seu Dispositivo Movel instale o App "Edge Inspect"

*Coloque os dois na mesma rede Wifi.

*No seu Dispositivo Movel crie uma Connection informando o IP do seu Desktop.
Seu dispositivo móvel agora conversa com o Desktop e facilita Debug e visualização de ativos no Dispositivo.
No site da Adobe diz que funciona com Android e iOS mas eu só usei com iOS até agora. Você não deverá ter problemas com o Android.
O Desktop deve ser Windows ou MAC OS X. Eu só testei no MAC OS X.

A: O Google Chrome implementou uma nova tecnologia que permite fazer Debugging remoto por meio do navegador em qualquer elemento que utilize WebKit, por exemplo uma WebView em um App, como o Cordova utiliza ou o navegador.
Para isso é necessário possuir o Chrome 32 no computador e no dispositivo, um cabo usb e os drivers para usuários Windows.
Para ativar o Debugging remoto você deve ir em opções de desenvolver no Android (Configurações -> Programador na versão 4.4.2 do Android).
Depois você deve ativar a Depuração USB.
No computador acesse o endereço about:inspect no Google Chrome para ativar a funcionalidade.
O processo é simples e não deve causar problemas. Quando tudo estiver pronto conecte seu aparelho por meio de um cabo USB. Na primeira vez o aparelho ira pedir para aceitar uma chave RSA, feito isso você pode começar o debug remoto indo no menu do Google Chrome --> Ferramentas --> Inspecionar Dispositivos.


text:
Q: How can I do a capacity planning of my web application and decide the deployment architecture? I have an ASP.net web application deployed on the small AWS instance (Dual Core AMD, 2.60 GHz, 1.7 GB RAM). I would like to perform load testing on this server for 300 concurrent users and for future, I want to design the tentative capacity planning and deployment architecture for 250,000 registered users for my application.
I am very new person in this area and have not done any kind of load testing before.

The Use-case and scenario of my
  application will be as below:
Scenario - 250, 000 registered users in database
Concurrency – 5% - 7% - approximately 17,500
Each user has a book shelf and
  assuming each user is subscribed for
  10 books. Each book is of around 25 MB
  in size with 400 pages
Use cases

*

*User Login

*

*Database authentication & authorization

*View Book Shelf with book images

*

*Book Shelf (.swf) - 400 KB (gets loaded for each user)

*10 book images will be loaded (20KB per image)(approximately)

*catalog.xml - 30 KB / user for allocated for the user

*Note: Approximately 650KB of data is gets downloaded on to client
  machine

*Browse book : On clicking a book image following files & its sizes will
  be downloaded to clients machine

*

*One time

*Reader.swf - 950 KB (first download)

*XML data's of approximately 100 KB / per book (on click)

*

*Book.xml

*Annotation.xml

*Catalog.xml

*Usersettings.xml 40KB*4 = 160 KB per user (.swf)

*Note: Approximately 1200KB of data is gets downloaded on to client
  machine

Could someone please suggest how can I proceed with this?
Very much thanks in advance,
Amar

A: Completing the first goal (test 300 users) is pretty straightforward - choose a load testing tool, build the scenarios and test. Then tune/optimize and repeat.
But I think your bigger question is how to approach testing and planning for your full capacity - which you say is ~18k concurrent users.  First, make sure that number (7% of user base) is the peak concurrency, not average.  You need to test the peak.
So assuming that you are planning a load-balanced multiple-server cluster to handle that load, the next step is to determine the maximum capacity of a single web/app server, without the load-balancer in place. This gives you a baseline that you can use to judge the performance of the cluster. This is a really important step and many of our clients skip this step, to their own detriment. It is important because there are many conditions under which a load-balanced system does not scale linearly with the number of servers in the cluster. Ideally it should and good systems get pretty close. You'd be surprised how frequently we see systems that don't scale well at all. We've even seen a few systems that actually have lower capacity as a cluster than a single server could handle on its own.
Once you have that baseline established, you can make a preliminary estimate about the total number of servers you'll need and you can build your cluster. I recommend next testing with 2 web/app servers.  This should nearly double your capacity.  If it doesn't then  you need to determine why before moving on to larger tests.  Likely candidates are the load balancer setup or the database (if a single database server is servicing all the web/app servers). Occasionally something more fundamental to the application architecture is at play.
When you are satisfied that scaling from 1 to 2 servers is performing optimally, then you can proceed to scale up to your full cluster and test maximum capacity. Be prepared to back-track if you don't see the scalability you expected - test with 3, 4, 5 servers, etc.
I hope that helps!  Good luck :>

A: This link: http://support.microsoft.com/kb/231282, has links to some tools to stress test your website.
This is obviously a complicated area, so you may have 2.5 million registered users (really that many?), but how many are concurrent, and what areas of the website will they be using.
All of these things (and many more), will impact the capacity planning for your system.


text:
Q: In Oracle, how do you select multiple values from a related table and store them in a single column? I'm selecting columns from one table and would like to select all values of a column from a related table when the two tables have a matching value, separate them by commas, and display them in a single column with my results from table one.
I'm fairly new to this and apologize ahead of time if I'm not wording it correctly.

A: It sounds like what you're trying to do is to take multiple rows and aggregate them into a single row by concatenating string values from one or more columns. Yes?
If that's the case, I can tell you that it's a more difficult problem than it seems if you want to do it using portable SQL - especially if you don't know ahead of time how many items you may get.
The Oracle-specific solution often used in such cases is to implement a custom aggregate function - STRAGG(). Here's a link to an article that describes exactly how to do so and has examples of it's usage.
If you're on Oracle 9i or later and are willing to live with using undocumented functions (that could change in the future), you can also look at the WM_CONCAT() function - which does much the same thing.

A: You want a row aggregation or concatenation function, choices are:

*

*If you are using Oracle 11gR2, there is a built-in function to aggregate strings with a delimiter called LISTAGG(column, delimiter).

*If you are using any earlier release of Oracle database, you can use WM_CONCAT(column) function, however you have no choice of delimiter and will have to use something like TRANSLATE(string, string_to_replace, replacement_string) function to change the delimiter afterwards if your data does not contain commas.

*As mentioned by LBushkin, you can create a custom function in your schema to perform row aggregation for you. Here is PL/SQL code example for one: http://www.oracle-base.com/articles/misc/StringAggregationTechniques.php#user_defined_aggregate_function


text:
Q: Compact injective operator and cardinality Let $X$ be Banach, $T: X\rightarrow X $ compact injective. Then $\#X \leq \#\text{ran}T \leq \#\mathbb{R}$ because compact operators have separable range. Thus, no compact injective operator $X\rightarrow X$ exists if $X$ has cardinality that is greater than the continuum.
Do you have another proof of the fact that there doesn't always exist $T: X\rightarrow X$ compact injective, that doesn't use cardinality?

References: Cardinality of separable metric spaces and Cardinality approach


text:
Q: SQL Server 2008 R2 Job Launched Step 1 hundreds of times I have an ETL SSIS package that is scheduled via job to run nightly at 7pm. It is the only step in the job, and the failure action is "quit the job reporting failure". The server is Windows Server 2008 R2, and the SQL Server version is 2008 R2. There is also an instance of SQL Server 2012 installed on this server, but the services are not started for that instance.
I've made no changes to the job, package, or server, and tonight it behaved strangely. When I look at the history of the job and expand tonight, it shows starting step 1 over 400 times, all at exactly 7 PM. It looks like it just kept launching it until the transaction log filled the entire drive and had no more space to grow, then exited the job reporting failure. I shrunk the transaction log by setting recovery mode to simple and running DBCC SHRINKFILE. I then restarted all of the SQL services for that instance and re-ran the job. So far, it seems to be running as expected, although I suppose time will tell.
I did a search of stack overflow and have seen nothing like this mentioned. We're actually starting a project to virtualize the box, then upgrade to 2012, so this may end up being one of those oddball things that never happens again, but I thought I'd ask in case anyone has any idea why this might have happened.

A: open the job step and go to the advanced tab. Look at the retry attempts. could it be that it has a big number? this would make the step run many times if it fails.
:


text:
Q: MBP resolution changes when connected to an external display Until recently, I was able to connect an external display to my 2013 MBP Retina without a problem. As of the past week or so, connecting an external display results in the resolution of the MBP changing from 2880x1800 to 1440x900. The external resolution is unaffected. I'm unaware of any particular system changes prior to when this problem started.
I use Display Menu to manage the resolutions of both displays and this has worked well for me for the past year or so.
The problem sounds like it's the same as described here: Is there a setting to make the Mac not change resolution when connecting to an external display? except that I'm not trying to mirror the MBP display and mirroring is not switched on.

A: I guess you have selected Scaled resolution with "More space" option for your MBP screen.
Have a look at that once you connect the second screen. For me connecting external display switches this option to "Default" for my MBP screen automatically.


text:
Q: my first EKS - error: You must be logged in to the server (Unauthorized) I've seen this error in many previous questions, but as a complete beginner I'm not sure if those questions were relevant to my situation.

*

*I've created a cluster called wiz_try using the AWS EKS gui.
When it asked for a role, I've created a new one with EKS policy AmazonEKSClusterPolicy.

*I've download AWS ICL and configured it. Also downloaded Kubectl.

*checked that I see the cluster:
aws eks --region eu-central-1 describe-cluster --name wiz_try --query cluster.status

ACTIVE

*ran

aws eks update-kubeconfig --name wiz_try --region eu-central-1
this has created a config file:
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: *******
    server: https://***.gr7.eu-central-1.eks.amazonaws.com
  name: arn:aws:eks:eu-central-1:399222411859:cluster/wiz_try
contexts:
- context:
    cluster: arn:aws:eks:eu-central-1:399222411859:cluster/wiz_try
    user: arn:aws:eks:eu-central-1:399222411859:cluster/wiz_try
  name: arn:aws:eks:eu-central-1:399222411859:cluster/wiz_try
current-context: arn:aws:eks:eu-central-1:399222411859:cluster/wiz_try
kind: Config
preferences: {}
users:
- name: arn:aws:eks:eu-central-1:399222411859:cluster/wiz_try
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      args:
      - --region
      - eu-central-1
      - eks
      - get-token
      - --cluster-name
      - wiz_try
      command: aws

*

kubectl get svc
error: You must be logged in to the server (Unauthorized)
I tried solving by running
aws eks update-kubeconfig --name wiz_try --region eu-central-1 --role-arn arn:aws:iam::***:role/EKS_cluster_role
as this is the role I created, but this is not helping.
what am I missing?
Thanks


text:
Q: How to clean bad data from huge csv file So I have huge csv file (assume 5 GB) and I want to insert the data to the table but it return error that the length of the data is not the same
I found that some data has more columns than I want
For example the correct data I have has 8 columns but some data has 9 (it can be human/system error)
I want to take only 8 columns data, but because the data is so huge, I can not do it manually or using parsing in python
Any recommendation of a way to do it?
I am using linux, so any linux command also welcome
In sql I am using COPY ... FROM ... CSV HEADER; command to import the csv into table

A: You can use awk for this purpose. Assuming you field delimiter is comma (,) this code can do the work:
awk -F\, 'NF==8 {print}' input_file >output_file

A: A fast and dirty php solution as single command line:
php -r '$f=fopen("a.csv","rb"); $g=fopen("b.csv","wb"); while ( $r=fgetcsv($f) ) { $r = array_slice($r,0,8); fputcsv($g,$r); }'

It reads file a.csv and writes b.csv.


text:
Q: Vue.js Modular Application I have a SPA app in Vue.js 2 and laravel for backend. and now, we need to add a modular approach to it. so for example, we can install new modules to it. and once the module is enabled, we extend the  main SPA to add the components, routes from the module. but it can be enabled/disabled from a market place in real time. i am not sure, how it is possible, anyone who already worked on something like this?
for laravel, i already achieved to make modules, completely standalone, and import routes, controllers etc using service providers. but for vue.js because its a SPA, i am not sure if its possible.
i tried to create the components seperate and include the script files dynamically, but with this, i cannot create the new vue-router routes.


text:
Q: C# - Updating GUI using non-main Thread I have a program that has Classes

*

*GUI

*Upload

*and a buffer between the 2 classes - ie used to communicate between the 2 classes .

The Upload class uses Process to run an command line FTP app.  I want to return what output produced by the FTP app to be displayed in a textbox in the GUI.
I have tried using the following code that has been truncated.
Upload Class (beginProcess() is a method used to start the Thread (not shown here)):
public delegate void WputOutputHandler(object sender, DataReceivedEventArgs e);
class Upload
{
    private WputOutputHandler wputOutput;

    beginProcess()
    {
        Process pr = new Process();
        pr.StartInfo.FileName = @"wput.exe";
        pr.StartInfo.RedirectStandardOutput = true;
        pr.StartInfo.UseShellExecute = false;
        pr.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        pr.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived);
        pr.ErrorDataReceived += new DataReceivedEventHandler(OnDataReceived);
        pr.Start();
        pr.BeginOutputReadLine();
        pr.WaitForExit();
    }

    public void OnDataReceived(object sender, DataReceivedEventArgs e)
    {
        if(wputOutput != null)
        {
            wputOutput(sender, e);
        }
    }

    public event WputOutputHandler WputOutput
    {
        add
        {
            wputOutput += value;
        }
        remove
        {
            wputOutput -= value;
        }
    }
}

Buffer Class:
public void EventSubscriber()
{
    uploadSession.WputOutput += Main.writeToTextBoxEvent;
}

Main Class:
public void writeToTextBoxEvent(object sender, DataReceivedEventArgs e)
{
    if(this.textBox1.InvokeRequired)
    {
        MethodInvoker what now?
    }
    else
    {
        textBox1.Text = e.Data;
    }
}

As you can see, when it come to the Main method's writeToTextBoxEvent, I've ran out of ideas.  I'm not sure whether doing a UI update using a custom event is even the best way to do it.  If someone could point me in the right direction I would be most grateful.

A: How about this:
public void writeToTextBoxEvent(object sender, DataReceivedEventArgs e)
{
    if(this.textBox1.InvokeRequired)
    {
        // In .Net 2.0
        this.textBox1.BeginInvoke(new MethodInvoker(() => writeToTextBoxEvent(sender, e)));

        // In .Net 3.5 (above is also possible, but looks nicer)
        this.textBox1.BeginInvoke(new Action(() => writeToTextBoxEvent(sender, e)));
    }
    else
    {
        textBox1.Text = e.Data;
    }
}

The advantage for this method against Richard solution is you don't need to write the executing code twice (within the BeginInvoke() and again in the else path).
Update
If you're on .Net 3.5 make it as an extension method:
public static class ControlExtensions
{
    public static void SafeInvoke(this Control control, Action action)
    {
        if (control.InvokeRequired)
        {
            control.Invoke(action);
        }
        else
        {
            action();
        }
    }

    public static void SafeBeginInvoke(this Control control, Action action)
    {
        if (control.InvokeRequired)
        {
            control.BeginInvoke(action);
        }
        else
        {
            action();
        }
    }
}

And use it that way:
public void writeToTextBoxEvent(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
    // Write it as a single line
    this.textBox1.SafeBeginInvoke(new Action(() => textBox1.Text = e.Data));

    this.textBox1.SafeBeginInvoke(new Action(() =>
        {
            //Write it with multiple lines
            textBox1.Text = e.Data;
        }));
}

A: if(this.textBox1.InvokeRequired)
{
   Action a = () => { textBox1.Text = e.Data; };
  textBox1.Invoke(a);
}

I.e. use a delegate (which can be a closure to capture local variables) with the Invoke method. This will dispatch the delegate to be executed on the textbox's thread. Invoke will return when the delegate has completed execution.
There is also an asynchronous version when you don't need to wait (BeginInvoke).
EDIT: Forgot that because Invoke takes a Delegate type inference fails, so use local. NB you can of course create the delegate at an earlier point and use it in both branches to avoid duplicate code.

A: Here is a popular extension mechanism:
public static void InvokeIfRequired(this System.Windows.Forms.Control c,
                                    Action action) {
    if (c.InvokeRequired) {
        c.Invoke((Action)(() => action()));
    }
    else {
        action();
    }
}

Usage:
public void writeToTextBoxEvent(object sender, DataReceivedEventArgs e) {
    this.textBox1.InvokeIfRequired(() => { textBox1.Text = e.Data; }
}

A: If you want a responsive UI, you need a worker thread and the main thread to update the UI.
I think you need a worker thread to look for data being received and then from your worker thread use a delegate to write data to your TextBox.
Something like :
public delegate void textBoxWriteDelegate(string msg);

private void textBoxWrite(string sMess) {
  textBox.AppendText(sMess);
}

And from your worker thread :
Invoke(new textBoxWriteDelegate(textBoxWrite), new object [] { "Launching ftp cmd line .... \n" });

Sorry it's net 1.1  ;) There's a better way to write delegates in 2.0 and higher...

A: I created a little helper for that:
class LayoutsEngine
{
    internal static void ThreadSafeDoer(Form Form, Delegate Whattodo)
    {
        if (!Form.IsDisposed)
        {
            if (Form.InvokeRequired)
            {
                Form.Invoke(Whattodo);
            }
            else
            {
                Whattodo.DynamicInvoke();
            }
        }
    }
}

and am using it like this:
    LayoutsEngine.ThreadSafeDoer(this, new MethodInvoker(delegate()
    {
         txtWhatever.Text=whatever();
         //  and any other GUI meddling
    }));

Also, if anyone has a way to reduce MethodInvoker() here, please comment.


text:
Q: TDD and Factory Pattern I am new to TDD. I try to implement an application that reads a configuration from a file and do some things.
I have a conf element interface:
interface ConfElement{
    doSomething()
}

then I have a two ConcreteConfElement that implements ConfElement:
ConcreteConfElementA:
class ConcreteConfElementA implements ConfElement{
     private propA;

     doSomething()
}

ConcreteConfElementB:
class ConcreteConfElementB implements ConfElement{

     private propB;

     doSomething()
}

then I have a factory that create ConcreteConfElementA and ConcreteConfElementB read from Configuration object passed to factory;
ConfElementFactory(){
  public ConfElementFactory(Configuration conf)

  ConfElement createConf(){
     if(conf.hasElA){
         return new ConcreteConfElementA();
     }
     else{
         return new ConcreteConfElementB();
     }
  }
}

How can I test factory method ? Is it well designed for TDD?

A: With TDD you need to write the tests first, before the production code. TDD encourages design patterns to emerge overtime, rather than straight away.

*

*Write a test for use case 1

*Implement enough code to pass this test (no interfaces!)

*Test Passes

*Write a test for use case 2

*Implement enough code to pass this test

*Test Passes

*Refactor to remove duplicate (hint: The Factory pattern emerges!)

This way the code is 100% tested and no need to worry of the pattern is testable or not. Refactoring is a key element of TDD.

A: It should be relatively easy to test the conditional logic of your factory.
Two tests could be:

*

*Instantiate a Configuration object with hasEla to be true.  Instantiate Element factory with the test Configuration object and assert that an instance of ConcreteConfElementA has been returned.

*Repeat step one but set hasEla to false, and assert that ElementB has been returned.

I believe this particular factory is testable, because it allows the caller to inject the Configuration.


text:
Q: Can Jack ever take a hit without getting stunned? The more I use Jack, the more useless he seems (as a defender). One of the things he is able to do in battle is act as a human shield for one of the other party members, however, every single time I've done this and the person he was defending was attacked, he became Stunned and was unable to act for roughly 3 turns. After realizing that Jack was the only one in the party who can use items, it didn't make much sense anymore to use him to Defend if he was going to be Stunned every single time he took a hit.
Is Jack eventually able to take more than a single hit before becoming Stunned? Is there always a chance that he doesn't become Stunned and I've just been incredibly unlucky? Or is Jack fated to become Stunned whenever he takes a hit?


text:
Q: Question about constructing complex entire function How to construct an entire function for infinitely many prescribed values?
i.e. I hope to find an entire function $f$ given $f(z_k) = w_k$ ($w_k$ might not be zero) for a sequence of $\{z_k\}$ with no finite accumulation points.
Can anyone give me some idea? Thanks!

A: The usual way to do this is to combine Mittag-Leffler's theorem with the Weierstrass factorization theorem.  Weierstrass gives you an entire function
$g(z)$ which has a simple zero at each $z_k$.  Mittag-Leffler gives you a meromorphic function $h(z)$ with a simple pole at each $z_k$ where $w_k \ne 0$, and residue $w_k/g'(z_k)$ there.  After removing the removable singularities at each
$z_k$,  $f(z) = g(z) h(z)$ is the desired function.


text:
Q: Kile '[PDFLaTeX] failed to start' when using TeX Live 2013 + self compiled Kile On Ubuntu 13.04 I installed Tex Live 2013 and then compiled Kile from source (in order to avoid the large amount of dependencies that come with Ubuntu's version of Kile). Kile runs, but when I tried to compile a .tex file using PDFLaTeX I got the following error message:
[PDFLaTeX] failed to start

How do I make Kile find PDFLaTeX?

A: It turns out that you need to run Kile once as root. In a terminal enter:
sudo kile

Let Kile start, then close it and run Kile as normal. You should now be able to compile!


text:
Q: What is the type of/how do I initialize 'currentDevice' in this code? I'm trying to tell the camera in my app (which is build around OpenFrameworks) to auto focus. After reading this SO post I read through the AV Foundation Programming Guide on how to set the focus mode. The code they give as an example is:
if ([currentDevice isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
    CGPoint exposurePoint = CGPointMake(0.5f, 0.5f);
    [currentDevice setExposurePointOfInterest:exposurePoint];
    [currentDevice setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
}

I haven't been able to figure out how to initialize currentDevice outside the if statement, and it's not in the documentation. How should it be initialized/what type is it? Thanks.

A: You can read more about the AVCaptureDevice Class Reference
It refers to front or the back side camera. And don't forget to import the AVFoundation.framework


text:
Q: Reading MS Word document in C#, dollar sign, special characters are ignored I am reading a word document (Word 97) word by word, returning text ignores dollar sign and any special characters. I have set encoding to
 (var wordEncode = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;)
at document open time but it doesn't seem to work.
Here is my code:
var wordEncode = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
Document document = app.Documents.Open(@"C:\Transcript.doc", ReadOnly: true, Encoding: wordEncode);

for (int i = 1; i < document.Words.Count; i++)
{
    textOftheWord = document.Words[i].Text.ToString().Trim().ToLower();
}

Example: document contains $587 but after reading it in a program, variable "textOftheWord" has 587, $ sign doesn't come through.Similarly, any special characters and numbers with decimals, all ignored.
Your help is greatly appreciated,Thanks!

A: Hopefully this will help:
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object miss = System.Reflection.Missing.Value;
object path = @"C:\Transcript.doc";
object readOnly = true;
Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
string totaltext = "";
for (int i = 0; i < docs.Paragraphs.Count; i++)
{
     totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
}
Console.WriteLine(totaltext);
docs.Close();
word.Quit();

I was able to get $578 in the variable using that.
Similar question is asked here: Read from word document line by line
Original answer here: http://mantascode.com/c-how-to-parse-the-text-content-from-microsoft-word-document/


text:
Q: How to change body style on vaadin How to change body tag  style on vaadin? I am using .v-sa but it does not work and .v-generated-body neither.

A: I just assume you want to change the background color. If not, please specify what properties of the body element you are trying to style.
Most probably the theme defines a background color for the .v-app element, which is on top of the body element (and 100% high), so you never see the background you define for the body.
So you either need to set the .v-app background to transparent and set your preferred background to body, or just set your preferred background directly to .v-app.

A: Popup windows appear as sibling v-app elements (with added v-overlay-container) under the body.  So if you want to add a classname at runtime that applies to the main ui along with all popup windows, you DO NEED to access the body element directly.  We have had a specific use case that required this.
body v-generated-body
- v-app
- v-app v-overlay-container
- v-app v-overlay-container

Here is the code we used:
String additionalClassName = "my-selector";
com.vaadin.ui.JavaScript.eval("document.body.class +=  ' " + additionalClassName + "';");

There are other (better) ways to get the Javascript executed, such as adding an extension to your container, setting the classname in the shared state, and updating the element from the client side.  This approach would prevent the Vaadin runtime from wiping out your changes when it resyncs the client.  I don't think the body tag is subject to that situation though, so this eval hack might serve your purposes in production.


text:
Q: Parse a .txt file with "" I have a text file of the following form
"0ec62f05-3e87-4143-b417-1571d8634d07","""906823B1-F2D8-4C35-93FB-4C39CB01A8A8""","""Promo_1""",2015-08-27,2015-09-02,700302,,,,12.3.1.1,"""11802,11925,11368""",2017-27-01,"""""""
........

how to remove unnecessary "",
that need to be single

A: The line seems to be compliant with quoted csv format.
For your line, I get this:
l = ['''"0ec62f05-3e87-4143-b417-1571d8634d07","""906823B1-F2D8-4C35-93FB-4C39CB01A8A8""","""Promo_1""",2015-08-27,2015-09-02,700302,,,,12.3.1.1,"""11802,11925,11368""",2017-27-01,"""""""''']

import csv

cr = csv.reader(l)
for row in cr:
    print(row)

each row is a list like this:
['0ec62f05-3e87-4143-b417-1571d8634d07', '"906823B1-F2D8-4C35-93FB-4C39CB01A8A8"', '"Promo_1"', '2015-08-27', '2015-09-02', '700302', '', '', '', '12.3.1.1', '"11802,11925,11368"', '2017-27-01', '"""']

now for a regular file:
import csv

with open("file.csv") as f:
  cr = csv.reader(f)
  for row in cr:
      print(row)

to remove the unnecessary quotes, just replace row by [x.strip('"') for x in row]

A: This is a really primitive solution after reading, but it is simply, easy to understand.
while(text.count('""')):
    text = text.replace('""', '"')

A: Yes, if you use string.replace with the double quotes inside the single quote, they will get replaced
 oldstring = '"""906823B1-F2D8-4C35-93FB-4C39CB01A8A8"""'
 newstring = oldstring.replace('"""', '"')

newstring will appear as "906823B1-F2D8-4C35-93FB-4C39CB01A8A8"

A: I'd split the line by the commas (following the CSV convention), strip all speech marks "" - then go round in a loop, adding the speech marks back to each element of the CSV file.  Something like this...
string strippedLine = line.Replace("\"", "");
string[] row = strippedLine.Split(',');

string formattedRow = string.Empty;
string comma = string.Empty;

for (int i = 0; i <= row.Length; i++)
{
    formattedRow += comma + "\"" + strippedLine + "\"";   // <-- Rebuild the line here
    comma = ",";
}

So at the end of it, formattedRow will be how you want that line to be.


text:
Q: How to call a function asynchronously in Javascript so that we can handle its callback and stop its execution when the time is out? I have a function that solves a puzzle in a browser. It might take a very long time to finish and I want to stop its execution if the runtime exceeds 30 seconds. Something like this:
function solve(puzzle) {
    // A loop to solve a puzzle that might take minutes to run
    while (notSolve){
        keepFindingSolution(); // This is not a loop
    }
    return solution;
}

let solution = solve(veryHardPuzzle);
if (solution && solution.solved) {
    // Do something
}
console.log("Other executions");

So, I don't want to block the UI thread when solving the function so that users can still interact with the website. I also want to get the solution from the solve(veryHardPuzzle) once it's done, or break the execution of the function if the time is out.
I tried some different approaches below, but none of them work for me:
Wrap the solve() function in setTimeout()
setTimeout(function () {
    let solution = solve(veryHardPuzzle);
    if (solution && solution.solved) {
        // Do something
    }
}, 30000);
console.log("Other executions");

This approach (from https://stackoverflow.com/a/26616321/6308776) doesn't block the UI thread, and the other executions are executed happily. However, it just basically waits 30 seconds before executing the inner solve(veryHardPuzzle) function (please correct me if I'm wrong). If the solve(veryHardPuzzle) function runs longer than 30 seconds then it would block the thread.
clearTimeout() once the solve() is done
let timerId = setTimeout(function () {
    let solution = solve(veryHardPuzzle);
    clearTimeout(timerId);
    if (solution && solution.solved) {
        // Do something
    }
}, 30000);
console.log("Other executions");

I thought that this would stop the timeout() after the solution is found, but it technically waits 30 seconds before the solver(veryHardPuzzle) is executed.
After doing some research, I realized setTimeout() might not the thing I want. Do you have any ideas or techniques on how to solve this?

A: The easiest way to handle asynchronous (like) behavior is with a Promise.
In this case you could do something like this:
function doLongThing() {
  let success = false;
  return new Promise(function(resolve, reject) {

    //set timeout so if success is false after 30 seconds, reject promise.
    setTimeout(function () {
      if(!success) reject();
    }, 30000)

    //another set timeout to prevent blocking UX thread
    setTimeout(function () {
      //do long running thing
      let solution = solve(veryHardPuzzle);

      //thing finished
      success = true;

      //pass result into resolve method so consumer can use it
      resolve(solution);
    });
  })
}

then you could do this:
doLongThing().then(function(solution) {
  //do something with solution
}).catch(function() {
  //timed out
});

console.log("Other executions");

A: A few comments have hinted at this, but the answer is not in how you call solve, but rather in how solve iterates over each "try" (I'm assuming this is how your solver works). If after each try your solver will break out of the event loop (the essence of async JS), then the main thread will have opportunities to do the other work it needs to do like handle mouse clicks or paint the UI. There are a few ways to do this, but maybe Promises is the easiest to visualize and has the best browser support (though some polyfills may be necessary for some IE versions).
var timeIsUp = false

function trySolution (puzzle, solution) {
  return new Promise(function (resolve, reject) {
    if (!solution) reject('no solution found')

    if (timeIsUp) reject('time up!')

    if (puzzle + solution !== 'wrong') { // idk lol
      resolve({solution: solution, success: true})
    } else {
      resolve({solution: solution, success: false})
    }
  }
}

// solve is now recursive with each iteration async
function solve (puzzle, solutions) {
  trySolution(puzzle, solutions[0])
    .then(function (result) {
      if (result.success) {
        solve(puzzle, solutions.slice(1))
      }
    })
    .catch(function (err) {
      console.error(err)
    })
}

// do the deed
solve(puzzle, solutions) // puzzle is undefined error lol

setTimeout(function () {
  timeIsUp = true
}, 30000)


text:
Q: Screen resolution resets in Vista All:
We have several machines exhibiting the same problem:  Occasionally, the screen resolution of the machine will reset to 800x600.  After the problem occurs, the only way to correct it is to reboot.  If you try to reset the screen resolution in settings, etc., you don't get any errors, but the resolution doesn't change (oddly, if you select any resolution other than the previous one (which is the one that you want), it works).
This usually happens either as a result of the console being locked, or after a remote desktop session, where the machine in question was the host.
All of the machines exhibiting the problem are running Windows Vista, they have various nVidia graphics cards, and they either have a single, large monitor (27"), or dual 21" monitors.  They are all various flavors of Dell workstations.
We've tried updating the video drivers to no avail.  These same machines also exhibit other video problems.  For example:

*

*the screen sometimes goes black when Windows switches to the secure desktop (for UAC checks).

*the screen often goes black when attempting to unlock a locked console (sometimes you can't see anything, sometimes it is all black except for password textbox, which is visible).
This has affected probably a dozen high-end workstations.  Has anyone else seen this problem?

A: I've had my Dell Vista (and Windows-7) laptop and desktop behave a bit like this.
In my laptop's case, if I suspend the laptop undocked, then unsuspend docked when attached to a new monitor (or one the computer hasn't seen for a while) the video mode goes 800x600 until I define the resolution on the monitor correctly.
I would also have issues where if I suspended the laptop on a dock which was using the external monitor as the primary, when unsuspending undocked I would have a totally black screen.  I would then have to type in the password to login blind.  I worked out that this was because the video-display applet (either the built-in or the supplied nVidia one) only ran once the user had logged in.
Upgrading to Windows-7 and making a habit of hibernating rather than suspending turns out to be a more-or-less effective work-around, even if hibernating is much slower than suspending.
My desktop, which is an older Dell Dimension 5150, would also go all-black when the UAC popped up -- except for the UAC window.  I think this was because the video chipset wasn't supported properly under Vista for Aero.  Under Windows-7 it is better, but there is still a 5-second wait for the UAC to pop up, during which time the monitor is all black.  I blame this on the stone-aged video chipset in this computer.

A: I had the screen resizing issues with Vista Ultimate x64 on an nVidia GeForce 8600 GT when the monitor came back from Power Saving mode.
What's notable about this bug is that, at least on my machine, it only started with the mid-2009 x64 drivers.
I have since upgraded to Windows 7 Ultimate x64 (yay MSDN), and the problem went away.  Clearly, this isn't an option for you, but you may want to see if drivers from early 2009 exhibit the same problems.

A: This is not an answer, I'm afraid. Unfortunately, I don't think that any of the factors that you mentioned are relevant to the problem (from which I also suffer) -- for example, it's also been seen with ATI graphics cards, non-Dell monitors, laptops and desktops, Vista RTM, SP1, SP2, and Windows 7. There's a long thread about it here, which has been going for at least 8 months, but it has yet to be resolved :-(