text:
Q: External File Writing Not Completed When I write to an external file in Pascal the external file is not written completely even though the coding was flawless.
procedure save;
  {Menyimpan data penerbangan ke dalam file eksternal}
      begin
         write('> ');
     write('nama file: ');
     readln(namafisik);
     assign(d,namafisik);
     {$I-};
     rewrite(d);
     {$I+};
     if (IOresult=0) then
         begin
            for i:=1 to Neff do
             writejadwal(i);
         end;
      end;

procedure writejadwal(i:integer);
{Menuliskan jadwal ke file eksternal pada indeks ke-i}
      begin
           write(d,T.KodePenerbangan[i]);
           write(d,' | ');
           write(d,T.KotaKeberangkatan[i]);
           write(d,' | ');
           write(d,T.KotaKedatangan[i]);
           write(d,' | ');
           if ((T.TKeberangkatan[i].Day) < 10 ) then
              begin
                   x:=T.TKeberangkatan[i].Day;
                   str(x,y);
                   s:=y;
                   write(d,'0'+s);
              end
           else
               begin
               write(d,T.TKeberangkatan[i].Day);
               end;
           write(d,':');
           if ((T.TKeberangkatan[i].Month) < 10 ) then
              begin
                   x:=T.TKeberangkatan[i].Month;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKeberangkatan[i].Month);
               end;
           write(d,':');
           write(d,T.TKeberangkatan[i].Year);
           write(d,' | ');
           if ((T.TKeberangkatan[i].Hour) < 10 ) then
              begin
                   x:=T.TKeberangkatan[i].Hour;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKeberangkatan[i].Hour);
               end;
           write(d,':');
           if ((T.TKeberangkatan[i].Minute) < 10 ) then
              begin
                   x:=T.TKeberangkatan[i].Minute;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKeberangkatan[i].Minute);
               end;
           write(d,' | ');
           if ((T.TKedatangan[i].Day) < 10 ) then
              begin
                   x:=T.TKedatangan[i].Day;
                   str(x,y);
                   s:=y;
                   write(d,'0'+s);
              end
           else
               begin
               write(d,T.TKedatangan[i].Day);
               end;
           write(d,':');
           if ((T.TKedatangan[i].Month) < 10 ) then
              begin
                   x:=T.TKedatangan[i].Month;
                   str(x,y);
                   s:=y;
                   write(d,'0'+s);
              end
           else
               begin
               write(d,T.TKedatangan[i].Month);
               end;
           write(d,':');
           write(d,T.TKedatangan[i].Year);
           write(d,' | ');
           if ((T.TKedatangan[i].Hour) < 10 ) then
              begin
                   x:=T.TKedatangan[i].Hour;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKedatangan[i].Hour);
               end;
           write(d,':');
           if ((T.TKedatangan[i].Minute) < 10 ) then
              begin
                   x:=T.TKedatangan[i].Minute;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKedatangan[i].Minute);
               end;
           write(d,' | ');

           if (T.TKedatanganImplementasi[i].Day=0) then
              writeln(d,'__:__:____ | __:__ | __:__:____ | __:__')
           else
           {MULAI}
           begin
           if ((T.TKeberangkatanImplementasi[i].Day) < 10 ) then
              begin
                   x:=T.TKeberangkatanImplementasi[i].Day;
                   str(x,y);
                   s:=y;
                   write(d,'0'+s);
              end
           else
               begin
               write(d,T.TKeberangkatanImplementasi[i].Day);
               end;
           write(d,':');
           if ((T.TKeberangkatanImplementasi[i].Month) < 10 ) then
              begin
                   x:=T.TKeberangkatanImplementasi[i].Month;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKeberangkatanImplementasi[i].Month);
               end;
           write(d,':');
           write(d,T.TKeberangkatanImplementasi[i].Year);
           write(d,' | ');
           if ((T.TKeberangkatanImplementasi[i].Hour) < 10 ) then
              begin
                   x:=T.TKeberangkatanImplementasi[i].Hour;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKeberangkatanImplementasi[i].Hour);
               end;
           write(d,':');
           if ((T.TKeberangkatanImplementasi[i].Minute) < 10 ) then
              begin
                   x:=T.TKeberangkatanImplementasi[i].Minute;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKeberangkatanImplementasi[i].Minute);
               end;
           write(d,' | ');
           if ((T.TKedatanganImplementasi[i].Day) < 10 ) then
              begin
                   x:=T.TKedatanganImplementasi[i].Day;
                   str(x,y);
                   s:=y;
                   write(d,'0'+s);
              end
           else
               begin
               write(d,T.TKedatanganImplementasi[i].Day);
               end;
           write(d,':');
           if ((T.TKedatanganImplementasi[i].Month) < 10 ) then
              begin
                   x:=T.TKedatanganImplementasi[i].Month;
                   str(x,y);
                   s:=y;
                   write(d,'0'+s);
              end
           else
               begin
               write(d,T.TKedatanganImplementasi[i].Month);
               end;
           write(d,':');
           write(d,T.TKedatanganImplementasi[i].Year);
           write(d,' | ');
           if ((T.TKedatanganImplementasi[i].Hour) < 10 ) then
              begin
                   x:=T.TKedatanganImplementasi[i].Hour;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKedatanganImplementasi[i].Hour);
               end;
           write(d,':');
           if ((T.TKedatanganImplementasi[i].Minute) < 10 ) then
              begin
                   x:=T.TKedatanganImplementasi[i].Minute;
                   str(x,y);
                   write(d,'0'+y);
              end
           else
               begin
                    write(d,T.TKedatanganImplementasi[i].Minute);
               end;
           writeln(d);
           end;
           {SELESAI}
      end;

By the way jadwal is Indonesian for English

A: The coding wasn't quite flawless. In particular, you don't seem to be closing the file.

A: The problem is that you don't close or flush.  Most languages try to minimize calling the OS for write, and do that by writing only if enough bytes have been accumulated. (128 bytes standard, but this can be increased with settextbuf). Probably your file is a multiple of 128bytes.
flushing or closing writes out the remains of the buffer.


text:
Q: Add auto-increment column to an existing table and create foreign key I am using SQL Server 2014. There are two tables T1 and T2 with relational data. These tables have more than 100000 rows.
T1 has a primary key ID (varchar) and T2 is mapped with this ID (varchar).
I want to add another auto increment column AutoId (int) to the table T1, and I want to add column AutoId to table T2 as well.
Then I want to update AutoId in T2 from T1 based on the existing ID.
What is the easiest way to solve this?

A: you can use trigger After Insert
This is for new Records

CREATE TRIGGER [schema_name.]trigger_name
ON table_name
AFTER  {[INSERT],[UPDATE],[DELETE]}
[NOT FOR REPLICATION]
AS
{sql_statements}

or its for one time  the best way is update :
This is for Old Records
update t2
set t2.ID2 = t1.ID2
 from table1 t1
join table2 t2 on t1.id= t2.id

A: You can create AutoID using IDENTITY on T1 table even though it has PRIMARY KEY and existing data.
You can update that AutoID in T2 table using JOIN with ID Primary key.
Please check below query for your answer.
CREATE TABLE T1(ID VARCHAR(50) PRIMARY KEY)

CREATE TABLE T2(T2ID INT IDENTITY, ID VARCHAR(50))

INSERT INTO T1(ID)
VALUES ('V1'),('V2'),('V3'),('V4'),('V5')

INSERT INTO T2(ID)
VALUES ('V1'),('V2'),('V3'),('V4'),('V5')

SELECT ID FROM T1
SELECT T2ID,ID FROM T2
Go

ALTER TABLE T1
ADD AutoID INT NOT NULL IDENTITY(1,1)
GO

ALTER TABLE T2
ADD AutoID INT
Go

SELECT ID,AutoID FROM T1
SELECT T2ID,ID, AutoID FROM T2
Go

UPDATE TT
SET TT.AutoID = T.AutoID
FROM T1 AS T
INNER JOIN T2 AS TT ON TT.ID = T.ID
GO

SELECT ID,AutoID FROM T1
SELECT T2ID,ID, AutoID FROM T2

DROP TABLE T1
GO
DROP TABLE T2
GO

Demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't create unsigned column in Laravel 7 I am building management application using laravel. I am trying to create the tables 'role_user' in laravel, but when I run the 'php artisan migrate' command, I get the following:  BadMethodCallException
Method Illuminate\Database\Schema\Blueprint::name does not exist. Can anyone tell what do you mean by this error?

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->name();
            $table->timestamps();
        });
    }

but if i tring to migrate that i see
λ php artisan migrate
Migrating: 2020_06_07_055653_create_roles_table

   BadMethodCallException

  Method Illuminate\Database\Schema\Blueprint::name does not exist.

  at E:\laragon\www\os\vendor\laravel\framework\src\Illuminate\Support\Traits\Macroable.php:103
     99|      */
    100|     public function __call($method, $parameters)
    101|     {
    102|         if (! static::hasMacro($method)) {
  > 103|             throw new BadMethodCallException(sprintf(
    104|                 'Method %s::%s does not exist.', static::class, $method
    105|             ));
    106|         }
    107|

  • Bad Method Call: Did you mean Illuminate\Database\Schema\Blueprint::rename() ?

  1   E:\laragon\www\os\database\migrations\2020_06_07_055653_create_roles_table.php:18
      Illuminate\Database\Schema\Blueprint::__call("name", [])

  2   E:\laragon\www\os\vendor\laravel\framework\src\Illuminate\Database\Schema\Builder.php:166
      CreateRolesTable::{closure}(Object(Illuminate\Database\Schema\Blueprint))

A: Instead:
$table->name();

It supposed to be:
$table->string('name', 32); // change 32 to max length

Why?
There is no "name" type in MySQL (or any other DB engine). You probably was misleaded because of ->id() or ->timestamps(). Also there is no "id" column type, but this works because in Laravel this was made as shortcut (because it is often used).
So there is no difference if you use:
$table->id().
$table->timestamps();

Or
$table->bigIncrements('id');
$table->timestamp('created_at', $precision)->nullable();
$table->timestamp('updated_at', $precision)->nullable();

Because it is doing same thing under hood anyway.
Read more in docs.

A: You can change your code to :
    Schema::create('roles', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });

A: Change
$table->id()

to
$table->bigIncrements('id');


text:
Q: CreateDIBSection: Return value vs error The documentation of CreateDIBSection states:

If the function succeeds, the return value is a handle to the newly
  created DIB, and *ppvBits points to the bitmap bit values.
If the function fails, the return value is NULL, and *ppvBits is NULL.

However, directly after that it states:

This function can return the following value [...] ERROR_INVALID_PARAMETER

So, what is meant by this last sentence? I can hardly imagine that it really returns that value (possibly it actually calls SetLastError). Is this somewhere thoroughly documented?

A: This is simply an error in the current version of the documentation!
The CreateDIBSection always returns an HBITMAP. If the function fails, then it will return 0 (NULL), and you can call GetLastError. GetLastError will return ERROR_INVALID_PARAMETER.
This is the standard way that all GDI functions work, not to mention the fact that it is impossible for a function return both NULL and an error code. I was also able to dig up an old version of the MSDN documentation for this function (circa 2008), and it confirms that the current version of the online documentation is indeed erroneous:


text:
Q: Field Service Lightning Managed Packages I am trying to implement FSL in my developer edition and I could not find the URL to install Managed packages for both Base and Lightning Package. Can someone help me on that?

A: Below is a link through which you can install the Field Service Lightning Managed Package.
There are also links to the documentation and a guide for migration to the new standard object model of FSL.
https://fsl.secure.force.com/install/

A: Yes you need to ask Salesforce.I had the same issue with enabling field service in my client org.


text:
Q: Currency converter PHP echo in pop-up I don't know how I can do popup with result in my currency converter with API http://api.nbp.pl/. This is my code:
<?php

if (isset($_POST['kwota']) && isset($_POST['waluta']) && is_numeric($_POST['kwota']) && is_numeric($_POST['waluta'] )){
switch ($_POST['waluta']) {
case 1:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/usd/'))->rates[0]->mid;
break;
case 2:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/eur/'))->rates[0]->mid;
break;
case 3:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/jpy/'))->rates[0]->mid;
break;
case 4:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/gbp/'))->rates[0]->mid;
break;
case 5:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/aud/'))->rates[0]->mid;
break;
default:
$przelicznik = 1;
}

$wynik = $_POST['kwota']/$przelicznik;
echo $wynik;
}

?>

A: The API is public, so you tecnically don't need PHP to do so, you can fetch the exchange rate and show the results using javascript/jQuery directly.
Here's an example on how to do so using jQuery:
<form id="exchange">
    <input type="text" name="price" title="price">
    <select name="currency" title="currency">
        <option value="1">USD</option>
        <option value="2">EUR</option>
        <option value="3">JPY</option>
        <option value="4">GBP</option>
        <option value="5">AUD</option>
    </select>
    <input type="submit" value="calculate">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    $('#exchange').on('submit',function(e){
        e.preventDefault();
        var value = $(this).find('[name="price"]').val();
        if(!value) {
            alert("Insert a valid value");
            return false;
        }
        switch ($(this).find('[name="currency"]').val()) {
            case "1":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/usd/';
                break;
            case "2":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/eur/';
                break;
            case "3":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/jpy/';
                break;
            case "4":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/gbp/';
                break;
            case "5":
                $link = 'http://api.nbp.pl/api/exchangerates/rates/a/aud/';
                break;
            default:
                alert('Error');
                return false;
        }
        console.log($link);
        $.getJSON($link,function(result){
            alert(value/result.rates[0].mid);
        });
    });
</script>


text:
Q: Show the two events closest to today in the future (ACF) I want to display the two dates that are closest to the current date, but only if they're in the future. I'm using the ACF date-picker for this.
I'm not very good at php, so I'd appreciate if someone could point me in the right direction!

A: you could try something like:
$args = array(
   'post_type' => 'your_post_type',
   'posts_per_page' => 2,
   'meta_query' => array(
        'key'           => 'your_field_key',
        'compare'       => '>',
        'value'         => date('Y-m-d H:i:s'),
        'type'          => 'DATETIME'
   )
);

Hope that helps?


text:
Q: Wpf : How to make a letter pop out of the border how do make a letter pop out of the border?

I want to express it like this picture
I wrote a letter in the text on Border,
The letters are covered like in the picture.
Can you make this stick out like the picture below?
How can solve this?

this is my xaml code
<Window x:Class="TestProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestProject"
    Width="800"
    Height="600"
    Title="ItemsControl 엘리먼트 : Template/ItemsPanel/ItemTemplate/ItemContainerStyle 속성 사용하기"
    FontFamily="나눔고딕코딩"
    FontSize="16">
    <Window.Resources>
        <local:TaskCollection x:Key="TaskCollectionKey" />
    </Window.Resources>
    <Grid>
        <ItemsControl
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            ItemsSource="{Binding Source={StaticResource TaskCollectionKey}}">
            <ItemsControl.Template>
                <ControlTemplate TargetType="ItemsControl">
                    <Border
                        BorderBrush="Black"
                        BorderThickness="3"
                        CornerRadius="15">
                        <ItemsPresenter />
                    </Border>
                </ControlTemplate>
            </ItemsControl.Template>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <DataTemplate.Resources>
                        <Style TargetType="TextBlock">
                            <Setter Property="HorizontalAlignment" Value="Center" />
                        </Style>
                    </DataTemplate.Resources>
                    <Grid>
                        <Ellipse
                            Stroke="Black"
                            StrokeThickness="3"
                            Fill="Gold" />
                        <StackPanel
                            HorizontalAlignment="Center"
                            VerticalAlignment="Center">
                            <TextBlock
                                Margin="5"
                                Text="{Binding Path=Priority}" />
                            <TextBlock
                                Margin="5"
                                Text="{Binding Path=TaskName}" />
                        </StackPanel>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemContainerStyle>
                <Style>
                    <Setter Property="Control.Margin" Value="10"  />
                    <Setter Property="Control.Width"  Value="100" />
                    <Setter Property="Control.Height" Value="100" />
                    <Style.Triggers>
                        <Trigger
                            Property="Control.IsMouseOver" Value="True">
                                <Setter Property="Control.ToolTip"
                                    Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                                        Path=Content.Description}" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ItemsControl.ItemContainerStyle>
        </ItemsControl>
    </Grid>
</Window>

A: If you put the textblock in a canvas, that will not clip.
                    <StackPanel
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center">
                        <TextBlock
                            Margin="5"
                            Text="{Binding Path=Priority}" />
                        <Canvas>
                        <TextBlock
                            Text="{Binding Path=TaskName}" />
                        </Canvas>
                    </StackPanel>


text:
Q: stm32 HAL timer interrupt settings do not work I am using STM32F4x nucleo HAL lib, and try to set timer interrupt.
It does not work. Here are the settings for timer interrupt:
 // Timer is configured to be triggered  every .05 secs.

 __TIM4_CLK_ENABLE();

  Tim4Handle.Init.Prescaler = 16400;

  Tim4Handle.Init.CounterMode = TIM_COUNTERMODE_UP;

  Tim4Handle.Init.Period = 20;

  Tim4Handle.Instance = TIM4;

  Tim4Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;

  if ( HAL_TIM_Base_Init(&Tim4Handle) != HAL_OK )

   {

       Error_Handler();

    }

  TIM_SlaveConfigTypeDef sSlaveConfig;

  TIM_MasterConfigTypeDef sMasterConfig;

  sSlaveConfig.SlaveMode = TIM_SLAVEMODE_RESET;

  sSlaveConfig.InputTrigger = TIM_TS_ITR0;

  if (HAL_TIM_SlaveConfigSynchronization(&Tim4Handle, &sSlaveConfig) != HAL_OK)

 {

    Error_Handler();

  }

  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;

  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;

  if (HAL_TIMEx_MasterConfigSynchronization(&Tim4Handle, &sMasterConfig) != HAL_OK)

{

    Error_Handler();

 }

HAL_TIM_Base_Start_IT(&Tim4Handle);
HAL_NVIC_SetPriority(TIM4_IRQn, 0, 1);
HAL_NVIC_EnableIRQ(TIM4_IRQn);

here is my interrupt routine(it is never got called):
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
   // send gpio signal to scope
}

would you please help me to see any problem?


text:
Q: How to use colored patterns inside transparent image I'm trying to create a game (Middle Age concept), but i'm stuck in forming the shields. I want every colony to have his own unique shield, which will be consisted by:

*

*Shield shape (14 shapes)

*Pattern (12 patterns)

*Color (16 x 2 colors, since every pattern will have 2 color choices)

*Symbol (12 symbols)

I've already created the shield shapes using photoshop. Every shield shape will have its border and it will be transparent inside and outside.
My goal is every user to be able to choose the pattern, the 2 colors and the symbol of his shield, which will represent his faction.
There is one way to create all these different combinations and put them by using css and jquery, but this option will demand a huge number of colored patterns:
14 shapes x 12 patterns x 16x2 colors = 5.376 (different colored patterns at least).
So my questions are:

*

*How can i show the picture correctly when someone click's on the shield icons? In order to change the main shield by clicking on one of the smaller shapes underneath, i used the following jquery code, but for some unexplained reason it doesn't work on fiddle, while it properly works on my local server.
jQuery(function($) {
    $("#shield-1").click(function() {
        $('.modal-shield img').attr('src',function(i,e){
            $(this).attr('src', "path/to-image/shield-1.png");
        });
    });
});

*How can i present inside the shield its own pattern, according to each different shape? Can i use the option "overflow" on css, in order to fill his interior transparent part and then with jquery to create the patterns?

*How can i change the color of the pattern?

*Is there a way to save as an image the result of all those options, in order to later show the shield on different sizes?
If it's possible, i would like to use css and Jquery, but if this option isn't possible can i use svg and Jquery?
PS. I created a fiddle, but since i don't know how to include it here i will add it to my next comment.

A: For anyone having the same problem about question #1, i used the following updated jquery code to change main shield by clicking on shapes underneath
jQuery(function($) {
    $("[id^='shield-']").click(function() {
        var mysrc = $(this).attr("src");
        $('.modal-shield img').attr('src',function(i,e){
            $(this).attr('src', mysrc);
        });
    });
});

When any id starts with "shield_" clicked, variable "mysrc" get's his src attribute, and then changes class "modal-shield" img with "myscr" value..
Hope it help's someone...


text:
Q: Java - regex parse string Trying to parse out names with given samples
++++++++++++++++++SELIZABETH+COLLAZO+++++++++++++++++++
+++++++++++++++++++PALOMA+CORREA+++++++++++++++++++++++
+++++++++++++++++++NOAH+BLAKEMORE++++++++++++++++++++++

I've tried
//++(.*?)+(.*?)//++

but that's way off.
Would like to parse out the first and last name to two strings.

A: You can use this regex (\w+)\+(\w+) or \+{2,}(.*?)\+(.*?)\+{2,} with Pattern like this :
String str = "++++++++++++++++++SELIZABETH+COLLAZO+++++++++++++++++++\n"
        + "+++++++++++++++++++PALOMA+CORREA+++++++++++++++++++++++\n"
        + "+++++++++++++++++++NOAH+BLAKEMORE++++++++++++++++++++++";

Pattern pattern = Pattern.compile("(\\w+)\\+(\\w+)");// or instead "\\+{2,}(.*?)\\+"(.*?)\\+{2,}
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    System.out.println(matcher.group(1) + " " + matcher.group(2));
}

Outputs
SELIZABETH COLLAZO
PALOMA CORREA
NOAH BLAKEMORE


text:
Q: How to transition label text I'm trying to transition chart labels and have managed to transition to a new position and change the fill but I can't get it to update with the new items data.  Is this possible?
example on jsfiddle
var margin = { top: 50, right: 100, bottom: 100, left: 100 },
    width = 1000 - margin.left - margin.right,
    height = 450 - margin.top - margin.bottom,
    Items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5",
             "Item 6", "Item 7", "Item 8",    "Item 9", "Item 10"],

svg = d3.select("#chart").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var Labels = svg.selectAll(".dLabel")
    .data(Items); // select the data points and set their data

gEnter = Labels.enter()
    .append("text")
    .text(function (d) { return d; })
    .attr("x", 0)
    .attr("y", function (d, i) { return i * 40; })
    .style("text-anchor", "end");

Labels.exit().remove();

Items = ["Item 9", "Item 10", "Item 8", "Item 7", "Item 6",
         "Item 5", "Item 4", "Item 3", "Item 2", "Item 1"];

Labels.transition().duration(1500).ease("exp-in-out")
    .attr("fill", "red")
    .attr("transform", function (d) { return "translate(" + 50 + "," + 0 + ")"; });


text:
Q: filter a new customfield Phreeze I am using Phreeze to create an application.
Everything goes right but when I want to filter in a template a custom field (tagtypeName) it doesn't do it.
I have the model in model.js:
model.TagModel = Backbone.Model.extend({
    urlRoot: 'api/tag',
    idAttribute: 'id',
    id: '',
    name: '',
    type: '',
    TagtypeName: '',
    baja: '',
    defaults: {
        'id': null,
        'name': '',
        'type': '',
        'baja': ''
    }
});

My criteria is TagCriteria.php:
public function GetFieldFromProp($propname)
    {
        switch($propname)
        {
            case 'TagtypeName':
                return 'tagtype.id';
            case 'Id':
                return 'tag.id';
            case 'Name':
                return 'tag.name';
            case 'Type':
                return 'tag.type';
            case 'Baja':
                return 'tag.baja';
            default:
                return parent::GetFieldFromProp($propname);
                //throw new Exception('Unable to locate the database column for the property: ' . $propname);
        }
    }

My reporter is:
public $Id;
    public $Name;
    public $Type;
    public $Baja;
    public $TagtypeName;
/*
* GetCustomQuery returns a fully formed SQL statement.  The result columns
* must match with the properties of this reporter object.
*
* @see Reporter::GetCustomQuery
* @param Criteria $criteria
* @return string SQL statement
*/
static function GetCustomQuery($criteria)
{
    $sql = "select
        `tagtype`.`name` as TagtypeName
        ,`tag`.`id` as Id
        ,`tag`.`name` as Name
        ,`tag`.`type` as Type
        ,`tag`.`baja` as Baja
    from `tag`
    inner join `tagtype` on `tagtype`.`id`=`tag`.`type`";

    // the criteria can be used or you can write your own custom logic.
    // be sure to escape any user input with $criteria->Escape()
    $sql .= $criteria->GetWhere();
    $sql .= $criteria->GetOrder();

    return $sql;
}

the view has:

and in my controller I've changed the Tag to my reporter:
$tags = $this->Phreezer->Query('TagReporter',$criteria)->GetDataPage($page, $pagesize);

So when I go to the page I see the table instead of with the type id, it has the name of the type from my custome query as needed

but when I filter, no data is found with the new custom field:

Does anyone know how to handle this problem?

A: The problem was that I had to change the reporter count and put the inner joins:
static function GetCustomCountQuery($criteria)
    {
        $sql = "select count(1) as counter from `tag`
        inner join `tagtype` on `tagtype`.`id`=`tag`.`type`";

        // the criteria can be used or you can write your own custom logic.
        // be sure to escape any user input with $criteria->Escape()
        $sql .= $criteria->GetWhere();

        return $sql;
    }

Doing this it works OK for me!


text:
Q: ios could not locate NSManagedObjectModel , NSInternalConsistencyException I know similar questions have been asked but they all have different answers and none seem to help me.
So, I've got an app called TherapistScheduler, which has therapistScheduler.xcdatamodel in a /Data folder at the root of the project. Inside that folder is a Session.h and Session.m file, which match up with my Session entity in my data model.
My app delegate has the functions managedObjectContext, managedObjectModel, and persistantStoreCoodinator in it.
Inside my applicationDidFinishLaunching method, I've added a view controller (loginViewController) over the top of my rootViewController (which is a tabBarController), and  I'm trying to access my Session entity from there.
I'm using the following code to try and save a value - this is throwing the error:
  // create session
Session *session = (Session *) [NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:self.managedObjectContext];
[session setSessionHash:strUserhash];

The loginViewController.h file contains:
NSManagedObjectContext *managedObjectContext; // in the interface declaration

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; // after the interface

The loginViewController.m file contains
@synthesize managedObjectContext;

Do I need to do something in the loginViewController viewDidLoad to initialise the managedObjectContext? I'm a bit lost as to how this all works. I want to be able to access the data stored in the managedObjectContext from any view I switch to on the tab bar.
I know I'll probably need to add more code to the question, but I don't know what else is needed.
The error I'm getting is this:
TherapistScheduler[40752:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Session''
*** Call stack at first throw:
(
0   CoreFoundation                      0x02581919 __exceptionPreprocess + 185
1   libobjc.A.dylib                     0x0295b5de objc_exception_throw + 47
2   CoreData                            0x0004525b +[NSEntityDescription entityForName:inManagedObjectContext:] + 187
3   CoreData                            0x0007cd8b +[NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] + 59
4   TherapistScheduler                  0x000030ce -[LoginViewController processLoginForUserhash:andType:] + 142
5   TherapistScheduler                  0x000039fa -[LoginViewController connectionDidFinishLoading:] + 330
6   Foundation                          0x01f91666 -[NSURLConnection(NSURLConnectionReallyInternal) sendDidFinishLoading] + 108
7   Foundation                          0x01f915bf _NSURLConnectionDidFinishLoading + 133
8   CFNetwork                           0x02b8d9f1 _ZN19URLConnectionClient23_clientDidFinishLoadingEPNS_26ClientConnectionEventQueueE + 285
9   CFNetwork                           0x02c56c72 _ZN19URLConnectionClient26ClientConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XClientEvent18XClientEventParamsEl + 402
10  CFNetwork                           0x02c570ea _ZN19URLConnectionClient26ClientConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XClientEvent18XClientEventParamsEl + 1546
11  CFNetwork                           0x02c570ea _ZN19URLConnectionClient26ClientConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XClientEvent18XClientEventParamsEl + 1546
12  CFNetwork                           0x02b82dfe _ZN19URLConnectionClient13processEventsEv + 100
13  CFNetwork                           0x02b82c95 _ZN17MultiplexerSource7performEv + 247
14  CoreFoundation                      0x02562d7f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
15  CoreFoundation                      0x024c11dd __CFRunLoopDoSources0 + 333
16  CoreFoundation                      0x024c07c6 __CFRunLoopRun + 470
17  CoreFoundation                      0x024c0280 CFRunLoopRunSpecific + 208
18  CoreFoundation                      0x024c01a1 CFRunLoopRunInMode + 97
19  GraphicsServices                    0x02de62c8 GSEventRunModal + 217
20  GraphicsServices                    0x02de638d GSEventRun + 115
21  UIKit                               0x00215b58 UIApplicationMain + 1160
22  TherapistScheduler                  0x00001f3d main + 125
23  TherapistScheduler                  0x00001eb5 start + 53
24  ???                                 0x00000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'

A: I had to refer to the managedObjectContext as a property of the app delegate not self.  So it looked like appDelegate.managedObjectContext.

A: When you passed the managedObjectContext, I think what you did is like this:
TimelineTableViewController * timelineTableViewController;
timelineTableViewController = [TimelineTableViewController alloc];
[timelineTableViewController initWithStyle:UITableViewStylePlain];
timelineTableViewController.managedObjectContext = self.managedObjectContext;
//...

and then in TimelineTableViewController's viewDidLoad: method, you wanted to fetch the data by managedObjectContext, huh?
I debugged this issue and found that TimelineTableViewController's viewDidLoad: will be dispatched quicker than timelineTableViewController.managedObjectContext = self.managedObjectContext; (where you passed the managedObjectContext from parent (or the AppDelegate) to child). So when you were trying to fetch the data, the managedObjectContext is nil actually. That's why you got this issue:

'+entityForName: could not locate an NSManagedObjectModel for entity name 'Session''

WORKAROUND:
What you have to do is to make sure that the managedObjectContext is not nil when you need to fetch the data:
TimelineTableViewController * timelineTableViewController;
timelineTableViewController = [TimelineTableViewController alloc];
timelineTableViewController.managedObjectContext = self.managedObjectContext;
[timelineTableViewController initWithStyle:UITableViewStylePlain];
// ...

I just solved this issue by this way (no need to use AppDelegate's managedObjectContext directly).


text:
Q: Increment a column if string appears in dataframe I want to increment the s_number column if the word "LIVE" appears in another column. The first column will always be "LIVE", and then any occurrence of "LIVE" will always be in a group of 2. I want to increment the s_number column after the second occurrence, I'm not sure how to go about this
 Electric  s_number
   LIVE      1
   EARTH     1
   NEUTRAL   1
   NEUTRAL   1
   LIVE      1
   LIVE      2
   EARTH     2
   NEUTRAL   2

A: Using shift and the column itself to create the bool , then do cumsum
((df.Electric=='LIVE')&(df.Electric.shift()=='LIVE')).cumsum()+1
Out[278]:
0    1
1    1
2    1
3    1
4    1
5    2
6    2
7    2
Name: Electric, dtype: int32


text:
Q: Excel pivot table reading from xml Can Excel 2007 use an external xml file as the connection for a pivot table?  I am able to filter the dialog by xml when specifying a type of data however I get an error saying that it is not a valid datasource.

A: After importing the data to a sheet, you can then create a pivot table using the imported data. You can have a pivot table looking directly to an outside source.


text:
Q: The matplotlib chart changes when I change the index in python pandas dataframe I have a dataset of S&P500 historical prices with the date, the price and other data that i don't need now to solve my problem.
        Date      Price
0     1981.01     6.19
1     1981.02     6.17
2     1981.03     6.24
3     1981.04     6.25
.       .           .
and so on till 2020

The date is a float with the year, a dot and the month.
I tried to plot all historical prices with matplotlib.pyplot as plt.
plt.plot(df["Price"].tail(100))
plt.title("S&P500 Composite Historical Data")
plt.xlabel("Date")
plt.ylabel("Price")

This is the result. I used df["Price"].tail(100) so you can see better the difference between the first and the second graph(You are going to see in a sec).
But then I tried to set the index from the one before(0, 1, 2 etc..) to the df["Date"] column in the DataFrame in order to see the date in the x axis.
df = df.set_index("Date")
plt.plot(df["Price"].tail(100))
plt.title("S&P500 Composite Historical Data")
plt.xlabel("Date")
plt.ylabel("Price")

This is the result, and it's quite disappointing.
I have the Date where it should be in the x axis but the problem is that the graph is different from the one before which is the right one.
If you need the dataset to try out the problem here you can find it.
It is called U.S. Stock Markets 1871-Present and CAPE Ratio.
Hope you've understood everything.
Thanks in advance
UPDATE
I found something that could cause the problem. If you look in depth at the date you can see that in month #10 each is written as a float(in the original dataset) like this: example Year:1884 1884.1. The problem occur when you use pd.to_datetime() to transform the Date float series to a Datetime. So the problem could be that the date in the month #10, when converted into a Datetime, become: (example from before) 1884-01-01 which is the first month in the year and it has an effect on the final plot.
SOLUTION
Finally, I solved my problem!
Yes, the error was the one I explain in the UPDATE paragraph, so I decided to add a 0 as a String where the lenght of the Date (as a string) is 6 in order to change, for example: 1884.1 ==> 1884.10
df["len"] = df["Date"].apply(len)
df["Date"] = df["Date"].where(df["len"] == 7, df["Date"] + "0")

Then i drop the len column i've just created.
df.drop(columns="len", inplace=True)

At the end I changed the "Date" to a Datetime with pd.to_datetime
df["Date"] = pd.to_datetime(df["Date"], format='%Y.%m')
df = df.set_index("Date")

And then I plot
df["Price"].tail(100).plot()
plt.title("S&P500 Composite Historical Data")
plt.xlabel("Date")
plt.ylabel("Price")
plt.show()

A: The easiest way would be to transform the date into an actual datetime index. This way matplotlib will automatically pick it up and plot it accordingly. For example, given your date format, you could do:
df["Date"] = pd.to_datetime(df["Date"].astype(str), format='%Y.%m')
df = df.set_index("Date")
plt.plot(df["Price"].tail(100))

Currently, the first plot you showed is actually plotting the Price column against the index, which seems to be a regular range index from 0 - 1800 and something. You suggested your data starts in 1981, so although each observation is evenly spaced on the x axis (it's spaced at an interval of 1, which is the jump from one index value to the next). That's why the chart looks reasonable. Yet the x-axis values don't.
Now when you set the Date (as float) to be the index, note that you're not evenly covering the interval between, for example, 1981 and 1982. You have evenly spaced values from 1981.1 - 1981.12, but nothing from 1981.12 - 1982. That's why the second chart is also plotted as expected. Setting the index to a DatetimeIndex as described above should remove this issue, as Matplotlib will know how to evenly space the dates along the x-axis.

A: I think your problem is that your Date is of float type and taking it as an x-axis does exactly what is expected for taking an array of the kind ([2012.01, 2012.02, ..., 2012.12, 2013.01....]) as x-axis. You might convert the Date column to a DateTimeIndex first and then use the built-in pandas plot method:
df["Price"].tail(100).plot()

A: It is not a good idea to treat df['Date'] as float. It should be converted into pandas datetime64[ns]. This can be achieved using pandas pd.to_datetime method.
Try this:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('ie_data.csv')
df=df[['Date','Price']]
df.dropna(inplace=True)

#converting to pandas datetime format
df['Date'] = df['Date'].astype(str).map(lambda x : x.split('.')[0] + x.split('.')[1])
df['Date'] = pd.to_datetime(df['Date'], format='%Y%m')

df.set_index(['Date'],inplace=True)

#plotting
df.plot() #full data plot
df.tail(100).plot() #plotting just the tail

plt.title("S&P500 Composite Historical Data")
plt.xlabel("Date")
plt.ylabel("Price")
plt.show()

Output:


text:
Q: Two "text" fields in Android Studio (visual layout editor) Just that: i see two "text" fields in androidstudio layout visual editor, and i'm wondering what's the difference between them.

i mean that i see 2 "text" on in the property window of a textView (see image, on the right)
and in the autogenerated xml file it appears like this

so what's the deal with android:text and tools:text xml attributes?
If anyone can answer, thaks a lot in advance.

A: tools namespace used for layout preview, so it will render in preview but not be rendered on device.
You can learn more here: developer.android.com


text:
Q: Why Vector3 is struct type in unity? According to the docs, unities Vector3 are value types.
Also according to the docs "By default, on assignment, passing an argument to a method, and returning a method result, variable values are copied. In the case of value-type variables, the corresponding type instances are copied".
Not an expert in performance, pointers and so on, but I think its fact that passing arguments by reference instead by value to avoid making copies of instances is a good practice regarding performance. Indeed that's why most of the types in c# are reference types.
Same for the RaycastHit struct.
From as far as I researched classes and structures have the following basic differences

*

*classes are reference types and structs are value types

*structures do not support inheritance

*structures cannot have default constructor

For my none of this would justify giving up the performance of ref types benefit,so, mainly Vector3 where in any game there are going to be vectors passed around as arguments so copied all over the app,what is the reason of it being struct type?

A: When comparing classes (reference types) vs. structs (value types) in regards of performance, we can't say one is more performant to the other. The answer is: "It depends".
Classes are allocated on the heap, and are garbage collected, which is an overhead compared to structs.
Structs, as you mentioned, are copied when being passed, which is also an overhead compared to classes (this is not much of overhead of the size of the struct is small, that's why the design guidelines mentions a size limit when choosing structs).
Some general rules per design guidelines are:

✔ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
❌ AVOID defining a struct unless the type has all of the following characteristics:

*

*It logically represents a single value, similar to primitive types (int, double, etc.).

*It has an instance size under 16 bytes.

*It is immutable.

*It will not have to be boxed frequently.

Practically, you should benchmark for your specific scenario when you're in doubt.


text:
Q: Read from AWS Secret Manager during .net core Startup I have a .net core 3.1 web application that reads a variable from the AWS secret manager. I successfully make the call to the secret manager from within one of the controllers. But I'd instead like to make this call once during startup, and have this value available within my application to consume (rather than making the AWS secret manager call every time the controller is hit).
What is the best approach to use here? Should I use caching?


text:
Q: Search for image selection tool in macOS like gwenview I numerically generate many images where the set of parameters is encoded in the filenames (e.g. mf2d-m_100-r_9.5-mf_1-ph_0-c_0.7-....png)
On Linux I can conveniently browse my images with gwenview with the option to scale the preview size and add several filters (in my case name based).
Is there something similar for macOS with scalable preview size and file selection filter? Finder seems to be inappropriate.


text:
Q: PHP SDK Lookup API and SMS Pricing I would like to validate a phone number and get the price that it would cost to send a SMS to that phone number.
I can do this with 2 API calls, however according to https://www.twilio.com/docs/sms/api/pricing you can do this with 1 call? "Prices can be retrieved at a country level directly via the Pricing Messaging Countries resource or for a specific phone number by leveraging the Lookup API and Pricing Messaging Countries resource.".
Am I overlooking something? or can this not be done?

A: I'm Matt from Twilio's PHP content team. I've been looking through V2 of the Lookup API but don't see anything to do with it returning pricing information. That said, I'll take it up internally to find out more for you.


text:
Q: My C# with MySql backend database code runs well in VS 2019, but after compile, executable will breaks on first query and throws an exception. And it wasn't like this just a day ago. Can someone give me a clue as to where and what to look for the bug? Thanks.
Error Message

A: Try put breakpoints, and check variables on each step.
Also, some code can help.


text:
Q: How to connect multiple digital sensors with single wire? I am new to Arduino, and I have a problem that I can't solve on my own.
I am trying to connect multiple PIR motion sensors with a single wire, in parallel and onto one pin on my Arduino.
I am thinking of putting a different resistor on every sensor so when motion is detected and electricity goes through the sensor, the Arduino can detect how much voltage has come to Arduino. I don't know, this is the only solution I could come up with.

A: Make a DAC converter with the outputs (through the 1k internal resistor).
The bit of the binary value of voltage is directly related to the PIR which has detected something.
EDIT: R1 should be 2*RR.


text:
Q: xpages display the document history In some 'old' lotus notes applications, we created a history of each document: who created the doc, every person which edited it + the respective dates. The code contained several libraries in lotusScript.
For xpages, is there any snippet / sample working example which I could use? I found this but I couldn't download any example ...

A: ValueChangeListeners allow you to capture changes to specific components. I've used them to create audit trails in customer applications before.
Tony McGuckin has an XSnippet for it:
http://openntf.org/XSnippets.nsf/snippet.xsp?id=server-side-value-change-events-listeners
Declan Lynch covered it in a blog post:
http://www.qtzar.com/using-a-valuechangelistener-to-build-an-audit-trail/
Don McNally has also done a blog post:
http://dmcnally.blogspot.co.uk/2013/02/xpages-detecting-and-logging-field.html

A: I don't know of any pre-done snippet yet.  But this becomes a lot easier in XPages especially if expand into Java.  When I create an application these days I basically convert the document to a Java object.  I don't do this yet but it would be easy to store in the object a Map of all the fields and their current values and then on save, look for differences and then write them out to a log document.
this could be done without java of course.  Create an map object in scope.  Populate it on loading of the document and on save do the compare and write.

A: Something went wrong with that project on OpenNTF (don't ever use an ampersand in the name). I'm the original author of that custom control. AFter some digging I found a direct url to the project here.


text:
Q: Cannot trigger ChromeLogger Handler in Codeigniter4 I am new to php and its framework. I have followed the official guide line about how to add the ChromeLogger in Logger.php. I have also added the chrome extension for Chrome Logger.
How do I see any logging information on my controller?
Logger.php
<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class Logger extends BaseConfig
{
    ...
    public $handlers = [

        //--------------------------------------------------------------------
        // File Handler
        //--------------------------------------------------------------------

        'CodeIgniter\Log\Handlers\FileHandler' => [

            /*
             * The log levels that this handler will handle.
             */
            'handles'         => [
                'critical',
                'alert',
                'emergency',
                'debug',
                'error',
                'info',
                'notice',
                'warning',
            ],

            /*
             * Leave this BLANK unless you would like to set something other than the default
             * writeable/logs/ directory. Use a full getServer path with trailing slash.
             */
            'path'            => WRITEPATH . 'logs/',

            /*
             * The default filename extension for log files. The default 'php' allows for
             * protecting the log files via basic scripting, when they are to be stored
             * under a publicly accessible directory.
             *
             * Note: Leaving it blank will default to 'php'.
             */
            'fileExtension'   => 'php',

            /*
             * The file system permissions to be applied on newly created log files.
             *
             * IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
             * integer notation (i.e. 0700, 0644, etc.)
             */
            'filePermissions' => 0644,
        ],

        /**
         * The ChromeLoggerHandler requires the use of the Chrome web browser
         * and the ChromeLogger extension. Uncomment this block to use it.
         */
        'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [
            /*
                  * The log levels that this handler will handle.
                  */
            'handles' => [
                'critical', 'alert', 'emergency', 'debug',
                'error', 'info', 'notice', 'warning'
            ],
        ]
    ];
}

News.php
<?php

namespace App\Controllers;

use App\Models\NewsModel;
use CodeIgniter\Controller;

class News extends Controller
{
    public function index()
    {
        log_message('info', 'News Index page is visited');
        $model = new NewsModel();

        $data = [
            'news'  => $model->getNews(),
            'title' => 'News archive',
        ];

        echo view('templates/header', $data);
        echo view('news/overview', $data);
        echo view('templates/footer');
    }

}

A: First of all check your threshold in app\Config\Logger.php:
public $threshold = 4;

factory default is 4, but to log 'info' level messages $threshold should be 7!
Second, you can verify that you server is sending ChromeLogger data in your browser Dev tools (Network -> Header -> Response). Header:
X-ChromeLogger-Data: ...
should be included.
Third, looks like original ChromeLogger extension is not working in Chrome, but it works fine in Firefox. Log message should be in Dev tools Console.
I installed this extension:
Server log by Rasmus Schultz
It works by adding log info in new Dev tools tab "Server Log".
it also supports new log header X-ServerLog-Location.


text: Q: FlowlayoutPanel not displaying all it's child control I am having a flowlayoutpanel which is having multiple child control panel . Child panels are being added dynamically . There is one trackbar which provide the functionality to resize the child panels ( with background image). While resizing the child panels flowlayoutpanel is not able to display all the child panels and it's display empty spaces in the bottom . Looking for help thanks in advance.


text:
Q: Change duplicate handling of records How can defaults of First Name and Last Name from Leads module duplicate handling "fields to be matched on" can be replaced with custom fields?
I need to overwrite that default behavior so some records can be merged when my custom criteria matches


text:
Q: How can I have previous value of checkbox in Spring? Is it possible to have the previous value of checkbox along with new value?
My problem is, I have to execute some code, only if the value of checkbox is true, also if it was already true, then I am not suppose to perform the same action again.
Currently what I am doing is , for every checkbox I am having previous value holder too. If the value is changed only then I perform the action ( and it is true ), and set value of previous value holder to the new value.

A: You can add a change listener to the checkbox. When the checkbox changes the state, you can directly call your special code.
Or when you have a preference page, in which the checkbox is inside, you have to store the state of the preference page and check, if you have changed states inside.

A: Are you using the spring mvc JSP tablib or velocity/freemarker macros?
If you are, they should be ouputting a hidden field with the existing value of the checkbox in the HTML with an underscore "_" in front of it. Spring does this to help determine whether the checkbox was unchecked or just not submitted.
You should be able to appropriate this hidden field for your purposes, i.e. you can check for the value of the hidden field and compare it to the actual checkbox field value.
See Spring MVC 2.5 Checkbox tag

A: To do this properly you will need to do the comparison without relying on the client side to record the old value as this could allow tampering.
On submit, Spring MVC rebuilds the old version of the command before updating it with the new values submitted from the client. You will need to save the old value somewhere before the bind phase begins.
To do this, in the formBackingObject method (which gets called again after a POST submit), put a copy of the value in the request object. Then in the onSubmit method, you can retrieve the value from the request for the comparison. You could also record it in a different field on the command.
I find this SimpleFormController cheat sheet very helpful for figuring out the execution order of the methods. It should help you out here too.


text:
Q: Socket.io package not installing in window 7 Node.js Hi Friends i am tryeng to install socket.io module using npm install socket.io. Its not working  i got following error:
npm WARN package.json an-hybrid-app@0.1.0 No README.md file found!
npm http GET https://registry.npmjs.org/socket.io
npm http 200 https://registry.npmjs.org/socket.io
npm http GET https://registry.npmjs.org/socket.io-client/0.9.11
npm http GET https://registry.npmjs.org/policyfile/0.0.4
npm http GET https://registry.npmjs.org/base64id/0.1.0
npm http GET https://registry.npmjs.org/redis/0.7.3
npm http 304 https://registry.npmjs.org/socket.io-client/0.9.11
npm http 304 https://registry.npmjs.org/policyfile/0.0.4
npm http 304 https://registry.npmjs.org/redis/0.7.3
npm http 304 https://registry.npmjs.org/base64id/0.1.0
npm http GET https://registry.npmjs.org/ws
npm http GET https://registry.npmjs.org/active-x-obfuscator/0.0.1
npm http GET https://registry.npmjs.org/uglify-js/1.2.5
npm http GET https://registry.npmjs.org/xmlhttprequest/1.4.2
npm http 304 https://registry.npmjs.org/active-x-obfuscator/0.0.1
npm http 304 https://registry.npmjs.org/ws
npm http 304 https://registry.npmjs.org/uglify-js/1.2.5
npm http 304 https://registry.npmjs.org/xmlhttprequest/1.4.2
npm http GET https://registry.npmjs.org/zeparser/0.0.5
npm http GET https://registry.npmjs.org/options
npm http GET https://registry.npmjs.org/tinycolor
npm http GET https://registry.npmjs.org/commander
npm http 304 https://registry.npmjs.org/zeparser/0.0.5
npm http 304 https://registry.npmjs.org/options
npm http 304 https://registry.npmjs.org/tinycolor
npm http 304 https://registry.npmjs.org/commander

> ws@0.4.25 install E:\chat_\nodejs\node_modules\socket.io\node_modules\socket.i
o-client\node_modules\ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)

CreateProcessW: The system cannot find the file specified.
npm ERR! error rolling back Error: ENOTEMPTY, rmdir 'E:\chat_\nodejs\node_module
s\socket.io\node_modules\socket.io-client\node_modules\active-x-obfuscator\node_
modules\zeparser'
npm ERR! error rolling back  socket.io-client@0.9.11 { [Error: ENOTEMPTY, rmdir
'E:\chat_\nodejs\node_modules\socket.io\node_modules\socket.io-client\node_modul
es\active-x-obfuscator\node_modules\zeparser']
npm ERR! error rolling back   errno: 53,
npm ERR! error rolling back   code: 'ENOTEMPTY',
npm ERR! error rolling back   path: 'E:\\chat_\\nodejs\\node_modules\\socket.io\
\node_modules\\socket.io-client\\node_modules\\active-x-obfuscator\\node_modules
\\zeparser' }
npm ERR! error rolling back Error: EPERM, readdir 'E:\chat_\nodejs\node_modules\
socket.io\node_modules\socket.io-client\node_modules\active-x-obfuscator\node_mo
dules\zeparser\benchmark.html'
npm ERR! error rolling back  socket.io@0.9.13 { [Error: EPERM, readdir 'E:\chat_
\nodejs\node_modules\socket.io\node_modules\socket.io-client\node_modules\active
-x-obfuscator\node_modules\zeparser\benchmark.html']
npm ERR! error rolling back   errno: 50,
npm ERR! error rolling back   code: 'EPERM',
npm ERR! error rolling back   path: 'E:\\chat_\\nodejs\\node_modules\\socket.io\
\node_modules\\socket.io-client\\node_modules\\active-x-obfuscator\\node_modules
\\zeparser\\benchmark.html' }
npm ERR! ws@0.4.25 install: `(node-gyp rebuild 2> builderror.log) || (exit 0)`
npm ERR! `cmd "/c" "(node-gyp rebuild 2> builderror.log) || (exit 0)"` failed wi
th 127
npm ERR!
npm ERR! Failed at the ws@0.4.25 install script.
npm ERR! This is most likely a problem with the ws package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     (node-gyp rebuild 2> builderror.log) || (exit 0)
npm ERR! You can get their info via:
npm ERR!     npm owner ls ws
npm ERR! There is likely additional logging output above.

npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "socket.io"
npm ERR! cwd E:\chat_\nodejs
npm ERR! node -v v0.8.18
npm ERR! npm -v 1.2.2
npm ERR! code ELIFECYCLE
npm ERR! Error: ENOENT, lstat 'E:\chat_\nodejs\node_modules\socket.io\node_modul
es\socket.io-client\node_modules\active-x-obfuscator\node_modules\zeparser\bench
mark.html'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod  ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "socket.io"
npm ERR! cwd E:\chat_\nodejs
npm ERR! node -v v0.8.18
npm ERR! npm -v 1.2.2
npm ERR! path E:\chat_\nodejs\node_modules\socket.io\node_modules\socket.io-client\node_modules\active-x-obfuscator\node_modules\zeparser\benchmark.html

npm ERR! fstream_path E:\chat_\nodejs\node_modules\socket.io\node_modules\socket
.io-client\node_modules\active-x-obfuscator\node_modules\zeparser\benchmark.html
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR! fstream_stack C:\Program Files\nodejs\node_modules\npm\node_modules\fstream\lib\writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:297:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     E:\chat_\nodejs\npm-debug.log
npm ERR! not ok code 0

I am new in node.js please help.Thanks in advance.

A: The problem lays in the ws package. It just can't find cmd.exe. Add to your PATH environment the path to %SYSTEMROOT%\System32 or C:\Windows\System32

A: Make sure you have all the required software to run node-gyp:

*

*https://github.com/TooTallNate/node-gyp
You can also configure version of Visual Studio used by node-gyp via an environment variable so you can avoid having to set the --msvs_version=2012 property every time you do an npm install.
Examples:

*

*set GYP_MSVS_VERSION=2012 for Visual Studio 2012

*set GYP_MSVS_VERSION=2013e (the 'e' stands for 'express edition')

For the full list see
 - https://github.com/joyent/node/blob/v0.10.29/tools/gyp/pylib/gyp/MSVSVersion.py#L209-294
This is still painful for Windows users of NodeJS as it assumes you have a copy of Visual Studio installed and many end users will never have this. So I'm lobbying Joyent to the encourage them to include web sockets as part of CORE node and also to possible ship a GNU gcc compiler as part of NodeJS install so we can permanently fix this problem.
Feel free to add your vote at:

*

*https://github.com/joyent/node/issues/8005#issuecomment-50545326


text:
Q: What is $P(A' \cap B')$ and $P(A \cup B \cup C)$? We are given that $P(A)=.43, P(B)=.44,$ and $P(C)=.19$. Also, $B$ and $C$ are mutually exclusive but $P(A\cap B)=.07$ and $P(A\cap C)= .13$
(a) What is $P(A' \cap B')$?
Note: I know that since $A,B$ are not mutually exclusive, that $P(A \cap B)=P(A) \times P(B)$. Does this same rule apply for the complement? If so, then I can use the rule $P(A)+P(A')=1$.
(b) What is $P(A \cup B \cup C)$?
I know the formula: $P(A\cup B\cup C) = P(A) +P(B)+P(C)-P(A\cap B)-P(A\cap C)- P(B\cap C)+P(A\cap B\cap C)$.
Note: The part I am having trouble on with this formula is finding $P(A\cap B\cap C)$.

A: Guide:
$$P(A) \times P(B)  \approx 0.1892 \ne P(A \cap B)$$
$A$ and $B$ are not independent.

*

*Note that $$P(A' \cap B') = 1-P(A \cup B)$$

*$ (A \cap B \cap C) \subset (B \cap C)$, Hence $P(A \cap B \cap C)=0$.

*Also, check your inclusion-exclusion formula.

A: You know that $B$ and $C$ are mutually exclusive i.e. $A\cap B$ and $C$ are mutually exclusive,
$$P(A\cap B \cap C)=0$$
Also $$P(A\cap B)\neq P(A)\cdot P(B)$$
As $A$ and $B$ are not independent events.

For Part (II),
Using De-Morgans Law,
$$P(A'\cap B')=P((A\cup B)')=1-P(((A\cup B)')')$$
$$P(A'\cap B')=1-P(A\cup B)$$
Also you know that,
$$P(A\cup B)=P(A)+P(B)-P(A\cap B)$$


text:
Q: How to use UTF-8 for non-English characters in POST method in PHP I need to send text from Android to database on server and I'm faced with some question marks for non-English characters.
PHP code:
<?php

header('Content-Type: text/html; charset=utf-8');
$con=mysql_connect("xxxxx","xxxxx","123456");
mysql_select_db("xxxxx",$con);
mysql_query("SET CHARACTER SET 'utf8'", $con);
$user=$_POST['username','utf8'];
$matn=$_POST['matn','utf8'];
$status=$_POST['status','utf8'];
if($user!=""){
    $sqlQ="insert into content(username,matn,status) VALUES('$user','$matn','$status')";
    $result=mysql_Query($sqlQ);
    if($result){
        print "ok";
    }
    else
    {
        print "no";
    }
}else{
    print "-";
}
mysql_close($con);

?>

A: Do not use the deprecated mysql_* interface, use mysqli_* or PDO.
What is that second dimension in the array $_POST?
The question marks imply that the data was not stored correctly; see http://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored


text:
Q: How do I use a strategy that I've backtested to actually trade with? Example code is provided I've found some public strategies and am using them as a guide to develop my understanding of pine script. I will paste the script I am trying to alter.
I'm very new to pine script and coding in general, but I understand the general ideas of coding and seem to be picking up pine script's syntax.
Code is as follows:
//@version=3
strategy("Moving Average and/or Bbands bot V1.1", shorttitle="Strategy", overlay=true, pyramiding=1000)

//Make the backtest numbers more legible depending on the market you're trading, altcoin, forex, or commodities.
qty = 1

// If you're trading an altcoin, make this true and the backtest numbers are now equivalent to 1 satoshi
isALT = input(false, "Altcoin")

if isALT
    qty:= 100000000

// If you're trading forex, make this true and the backtest numbers are now equivalent to $0.0001
isForex = input(false, "Forex")
if isForex
    qty:= 10000

//* Backtesting Period Selector | Component *//
//* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-Component *//
//* https://www.tradingview.com/u/pbergden/ *//
//* Modifications made *//
testStartYear = input(1, "Backtest Start Year")
testStartMonth = input(8, "Backtest Start Month")
testStartDay = input(25, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)

testStopYear = input(999999, "Backtest Stop Year")
testStopMonth = input(9, "Backtest Stop Month")
testStopDay = input(26, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)

testPeriod() =>
    time >= testPeriodStart and time <= testPeriodStop ? true : false
/////////////// END - Backtesting Period Selector | Component ///////////////

//* Heiken Ashi Candles *//
isHA = false

data = isHA ? heikenashi(tickerid) : tickerid

o = security(data, period, open)
h = security(data, period, high)
l = security(data, period, low)
c = security(data, period, close)

g = c > o
r = c < o

col = c > o ? green : red

plotcandle(o, h, l, c, "Heiken Ashi", col, black)

//Initial open logic, needs to be set at the beginning as this is affected by most of the following settings
long = na
short = na

//* Moving Average Logic *\\
// Enable this to only long or short if you are above or below the Moving Average
useMA = input(true, "Use Moving Average Cross")
ma1Input = input(50, "Moving Average 1")
ma2Input = input(200, "Moving Average 2")

ma1 = sma(c, ma1Input)
ma2 = sma(c, ma2Input)

maLong = c > ma1 and ma1 > ma2
maShort = c < ma1 and ma1 < ma2

ma1Plot = na
ma2Plot = na

if useMA
    ma1Plot := ma1
    ma2Plot := ma2
    long := maLong
    short := maShort

plot(ma1Plot, "ma1", blue)
plot(ma2Plot, "ma2", orange)

//* Bollinger Bands Logic *\\
// Enable this to only long or short if you are above or below the Bollinger Bands

useBbands = input(false, "Use Bollinger Bands")

bblength = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50)
basis = sma(c, bblength)
dev = mult * stdev(c, bblength)
upper = basis + dev
lower = basis - dev

basisPlot = na
p1Plot = na
p2Plot = na

if useBbands
    long := c < lower
    short := c > upper
    basisPlot := basis
    p1Plot := upper
    p2Plot := lower

if useBbands and useMA
    long := c < lower and maLong
    short := c > upper and maShort

plot(basisPlot, color=red)
p1 = plot(p1Plot, color=blue)
p2 = plot(p2Plot, color=blue)
fill(p1, p2)

//////////////////////////
//* Strategy Component *//
//////////////////////////

// Count your long short conditions for more control with Pyramiding
sectionLongs = 0
sectionLongs := nz(sectionLongs[1])
sectionShorts = 0
sectionShorts := nz(sectionShorts[1])

if long
    sectionLongs := sectionLongs + 1
    sectionShorts := 0

if short
    sectionLongs := 0
    sectionShorts := sectionShorts + 1

// Pyramiding Inputs

pyrl = input(1, "Pyramiding less than") // If your count is less than this number
pyre = input(0, "Pyramiding equal to") // If your count is equal to this number
pyrg = input(1000000, "Pyramiding greater than") // If your count is greater than this number

// These check to see your signal and cross references it against the pyramiding settings above
longCondition = long and sectionLongs <= pyrl or long and sectionLongs >= pyrg or long and sectionLongs == pyre
shortCondition = short and sectionShorts <= pyrl or short and sectionShorts >= pyrg or short and sectionShorts == pyre

// Get the price of the last opened long or short
last_open_longCondition = na
last_open_shortCondition = na
last_open_longCondition := longCondition ? close : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition ? close : nz(last_open_shortCondition[1])

// Count your actual opened positions for things like getting your average order price
sectionLongConditions = 0
sectionLongConditions := nz(sectionLongConditions[1])
sectionShortConditions = 0
sectionShortConditions := nz(sectionShortConditions[1])

if longCondition
    sectionLongConditions := sectionLongConditions + 1
    sectionShortConditions := 0

if shortCondition
    sectionLongConditions := 0
    sectionShortConditions := sectionShortConditions + 1

// Check if your last postion was a long or a short
last_longCondition = na
last_shortCondition = na
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])

in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition

// Keep track of the highest high since you last opened a position
last_high = na
last_low = na
last_high_short = na
last_low_short = na
last_high := not in_longCondition ? na : in_longCondition and (na(last_high[1]) or high > nz(last_high[1])) ? high : nz(last_high[1])
last_high_short := not in_shortCondition ? na : in_shortCondition and (na(last_high[1]) or high > nz(last_high[1])) ? high : nz(last_high[1])
last_low := not in_shortCondition ? na : in_shortCondition and (na(last_low[1]) or low < nz(last_low[1])) ? low : nz(last_low[1])
last_low_short := not in_longCondition ? na : in_longCondition and (na(last_low[1]) or low < nz(last_low[1])) ? low : nz(last_low[1])

// Trailing Stop
isTS = input(false, "Trailing Stop")
tsi = input(0, "Activate Trailing Stop Price") / qty
ts = input(0, "Trailing Stop") / qty
long_ts = isTS and not na(last_high) and crossunder(low, last_high - ts) and longCondition == 0 and high >= (last_open_longCondition + tsi)
short_ts = isTS and not na(last_low) and crossover(high, last_low + ts) and shortCondition == 0 and low <= (last_open_shortCondition - tsi)
tsColor = isTS and in_longCondition and last_high >= (last_open_longCondition + tsi) ? blue : isTS and in_shortCondition and last_low <= (last_open_shortCondition - tsi) ? blue : white
tsiColor = isTS and in_longCondition and last_high >= (last_open_longCondition + tsi) ? white : isTS and in_shortCondition and last_low <= (last_open_shortCondition - tsi) ? white : blue
plot(isTS and in_longCondition ? last_open_longCondition + tsi : na, "Long Trailing", tsiColor, style=3, linewidth=2)
plot(isTS and in_shortCondition ? last_open_shortCondition - tsi : na, "Short Trailing", tsiColor, style=3, linewidth=2)
plot(isTS and in_longCondition and last_high >= (last_open_longCondition + tsi) ? last_high - ts : na, "Long Trailing", tsColor, style=2, linewidth=2)
plot(isTS and in_shortCondition and last_low <= (last_open_shortCondition - tsi) ? last_low + ts : na, "Short Trailing", tsColor, style=2, linewidth=2)

// Take profit
isTP = input(false, "Take Profit")
tp = input(0, "Take Profit") / qty
long_tp = isTP and crossover(high, last_open_longCondition + tp) and longCondition == 0
short_tp = isTP and crossunder(low, last_open_shortCondition - tp) and shortCondition == 0
tpColor = isTP and in_longCondition ? purple : isTP and in_shortCondition ? purple : white
plot(isTP and in_longCondition and last_high < last_open_longCondition + tp ? last_open_longCondition + tp : na, "Long TP", tpColor, style=3, linewidth=2)
plot(isTP and in_shortCondition and last_low > last_open_shortCondition - tp ? last_open_shortCondition - tp : na, "Short TP", tpColor, style=3, linewidth=2)

// Stop Loss
isSL = input(false, "Stop Loss")
sl = input(0, "Stop Loss") / qty
long_sl = isSL and crossunder(low, last_open_longCondition - sl) and longCondition == 0
short_sl = isSL and crossover(high, last_open_shortCondition + sl) and shortCondition == 0
slColor = isSL and in_longCondition and last_low_short > last_open_longCondition - sl ? red : isSL and in_shortCondition and last_high_short < last_open_shortCondition + sl ? red : white
plot(isSL and in_longCondition ? last_open_longCondition - sl : na, "Long SL", slColor, style=3, linewidth=2)
plot(isSL and in_shortCondition ? last_open_shortCondition + sl : na, "Short SL", slColor, style=3, linewidth=2)

// Margin Call. Depending on your leverage, this will mimick a margin call at -80%.
isMargin = input(false, "Margin Call")
leverage = input(1, "Leverage")
long_call = last_open_longCondition - (0.8 + 0.2 * (1/leverage)) / leverage * last_open_longCondition
short_call = last_open_shortCondition + (0.78 + 0.2 * (1/leverage)) / leverage * last_open_shortCondition
long_call_signal = isMargin and crossunder(low, long_call)
short_call_signal = isMargin and crossunder(high, short_call)
marginColor = isMargin and in_longCondition and last_low_short > long_call ? black : isMargin and in_shortCondition and last_high_short < short_call ? black : white
plot(isMargin and in_longCondition ? long_call : na, "Long Margin", marginColor, style=3, linewidth=2)
plot(isMargin and in_shortCondition ? short_call : na, "Short Margin", marginColor, style=3, linewidth=2)

// Get the average price of your open positions and plot them
totalLongs = 0.0
totalLongs := nz(totalLongs[1])
totalShorts = 0.0
totalShorts := nz(totalShorts[1])
averageLongs = 0.0
averageLongs := nz(averageLongs[1])
averageShorts = 0.0
averageShorts := nz(averageShorts[1])

if longCondition
    totalLongs := totalLongs + last_open_longCondition
    totalShorts := 0.0

if shortCondition
    totalLongs := 0.0
    totalShorts := totalShorts + last_open_shortCondition

averageLongs := totalLongs / sectionLongConditions
averageShorts := totalShorts / sectionShortConditions

longProfit = averageLongs > 0 and close >= averageLongs ? green : red
shortProfit = averageShorts > 0 and close <= averageShorts ? green : red

plot1 = plot(averageLongs > 0 ? averageLongs : na, color=white)
plot2 = plot(close, color=white)
plot3 = plot(averageShorts > 0 ? averageShorts : na, color=white)

fill(plot1, plot2, color=longProfit, transp=50)
fill(plot2, plot3, color=shortProfit, transp=50)

//Enable this to double your order size every time your pyramid on top of an existing position. (Martingale strategy)
// useMartin = input(true, "Martingale")

// longMartin = 0
// longMartin := nz(longMartin[1])
// shortMartin = 0
// shortMartin := nz(shortMartin[1])

// // Check to see if this is our first order, set the order qty to 1
// if longCondition and sectionLongConditions == 1
//     longMartin := longMartin + 1
//     shortMartin := 0
// if shortCondition and sectionShortConditions == 1
//     longMartin := 0
//     shortMartin := shortMartin + 1

// confirm that this order is being added to an existing order
// if longCondition and sectionLongConditions > 1
//     longMartin := longMartin * 2
// if shortCondition and sectionShortConditions > 1
//     shortMartin := shortMartin * 2

// Close Conditions amalgamation for cleaner plots and signals
// Define the plot colors for each close condition
longCloseCol = na
shortCloseCol = na
longCloseCol := long_tp ? purple : long_sl ? maroon : long_ts ? blue : long_call_signal ? black : longCloseCol[1]
shortCloseCol := short_tp ? purple : short_sl ? maroon : short_ts ? blue : short_call_signal ? black : shortCloseCol[1]

// Create a single close for all the different closing conditions.
long_close = long_tp or long_sl or long_ts or long_call_signal ? 1 : 0
short_close = short_tp or short_sl or short_ts or short_call_signal ? 1 : 0

// Get the time of the last close
last_long_close = na
last_short_close = na
last_long_close := long_close ? time : nz(last_long_close[1])
last_short_close := short_close ? time : nz(last_short_close[1])

// Check for a close since your last open.
if long_close and last_long_close[1] > last_longCondition
    long_close := 0
if short_close and last_short_close[1] > last_shortCondition
    short_close := 0

if testPeriod()
    strategy.entry("Long", strategy.long, qty=qty, when=longCondition)
    strategy.entry("Short", strategy.short, qty=qty, when=shortCondition)

    strategy.close("Long", when=long_close)
    strategy.close("Short", when=short_close)

End of code.
I would like to use this strategy moving forward with my trading account, be it Paper Trading or Poloniex, instead of backtesting it, for which it is currently set.

A: You could just run it as it is, in strategy mode. Signals will trigger on the close of the realtime bar as you don't have calc_on_every_tick=true in your strategy() call.
If you want the script to generate alerts, then it needs to run as a study. Here's a modified version of your script that now runs as a study (a.k.a. indicator), with markers that plot on the strat's signals, as you won't be getting the backtesting's entry/exit marks when the script is running as a study, and the proper alertcondition() calls so you can create alerts from the script. If you do, configure your alerts to trigger Once Per Bar Close so you don't get false alerts.
Changes are limited to beginning and end of the script. Follow the instructions in the comments at the top to flip from study to strategy mode: https://pastebin.com/Wx5ru5zG


text:
Q: How to mock Angular $q service in Jasmine test? I am trying to test an Angular service, which has 2 dependencies, one on $q and another one on 'myService' which also has dependency on $q.
(function() {
    'use strict';

    angular.module('myModule').factory('myService', [
        '$q',
        'apiService',
        function($q, apiService) {

            var data = null;

            function getData() {
                var deferred = $q.defer();

                if (data === null) {

                    apiService.get('url').then(function(result) {
                        data = result;
                        deferred.resolve(data);
                    }, function() {
                        deferred.reject();
                    });
                } else {
                    deferred.resolve(data);
                }

                return deferred.promise;
            }

            return {
                getData: getData
            };
        }
    ]);
})();

I started writing a Jasmine test as seen below, but and having issues mocking $q. I would like to inject the real version of $q instead of the mock version to 'myService' and 'apiService', but am not sure how to accomplish that.
'use strict';

describe('My service', function() {
    var qSpy, apiServiceSpy;

    beforeEach(module('myModule'));

    beforeEach(function() {
        qSpy = jasmine.createSpyObj('qSpy', ['defer']);

        apiServiceSpy = jasmine.createSpyObj('apiServiceSpy', ['get']);
        apiServiceSpy.get.and.callFake(function() {
            var deferred = $q.defer();
            deferred.resolve('Remote call result');
            return deferred.promise;
        });

        module(function($provide) {
            $provide.value('$q', qSpy);
            $provide.value('apiService', apiServiceSpy);
        });
    });

    it('should get data.', inject(function(myService) {
        // Arrange

        // Act
        var data = myService.getData();

        // Assert
        expect(data).not.toBeNull();
    }));
});

Edit
Here is the updated test based on the responses below.  I guess my issue was I assumed I had to provide $q.
'use strict';

describe('My service', function() {
    var service, apiServiceSpy;

    beforeEach(module('myModule'));

    beforeEach(function() {
        apiServiceSpy = jasmine.createSpyObj('apiServiceSpy', ['get']);

        module(function($provide) {
            $provide.value('apiService', apiServiceSpy);
        });
    });

    beforeEach(inject(function($q, myService) {
        service = myService;

        apiServiceSpy.get.and.callFake(function() {
            var deferred = $q.defer();
            deferred.resolve('Remote call result');
            return deferred.promise;
        });
    }));

    it('should get data.', function() {
        // Arrange

        // Act
        var data = service.getData();

        // Assert
        expect(data).not.toBeNull();
    }));
});

A: You have to use the $injector service to get the real angular service.

$injector is used to retrieve object instances as defined by provider,
  instantiate types, invoke methods, and load modules.

var $q
beforeEach(inject(function($injector) {
    $q = $injector.get('$q');
}));

A: You can use the real $q. Important to note, that you should call $scope.$apply() to resolve promises.
var service;
var $scope;
beforeEach(function() {

    angular.mock.module('app', function ($provide) {
        $provide.value('apiService', apiServiceSpy);
    });

    angular.mock.inject(function (_myService_, _$rootScope_) {
        service = _myService_;
        $scope = _$rootScope_;
    });
});

it('works like a charm', function() {
    var data;
    service.getData().then(function(d) {
        data = d;
    });
    $scope.$apply();  // resolve promise
    expect(data).toBeAwesomeData();
});

A: The $scope.$apply() answer is awfully good, but I find it annoying to remember to do that in every test that uses promises. So since I'm lazy tell $q to act like native Promises.
beforeEach(function() {
  module('my.module')
  module(function($provide) {
    $provide.factory('$q', function() {
      // Make $q act like Promise, but with the $q() constructor
      function $q(resolve, reject) {
        return new Promise(resolve, reject)
      }

      Object.getOwnPropertyNames(Promise).forEach(function(name) {
        $q[name] = Promise[name]
      })

      return $q
    })
  })

  inject(function(_$controller_, _$q_ /* ... more dependencies */) {
    controller = _$controller_('NameOfYourController', {
      $q: _$q_,
      $scope: {},
    })
  })
})

A: You should use in the real $q service.
var rootScope;
var deferrred;
var fakeMyService = { getData: function() { return deferred.promise}};

beforEach(inject(function($q, $rootScope) {
     deferred = $q.defer();
     rootScope = $rootScope;
}))

it('should do something', function() {
    . . .

    deferred.resove(<something>);
    $rootScope.$digest();

    . . .
    expect(. . .)

})


text:
Q: Can I isolate only one property in a directive, with the rest mapped to the parent scope? I created an angular directive to make generating forms easier.
It looks like this:
function formGroup() {
    return {
        restrict: "E",
        replace: true,
        scope:
            {
                fields: "=fields",
            },
        templateUrl: "/WarpManufacturingProcessControl/Templates/InputForm.html",
    };
}

You pass in an array with info about the fields you want in the form and it generates it from a template that supports of number of input types.
Ex:
The leftColumn array is mapped to "fields" in the scope of the directive.
I need to somehow pass in variables from the parent scope and bind them to the inputs in the form so that I can access the data in the form easily.
Right now, I pass something like {label: "Name", type: "text"} for each field. I want to include something like model: $scope.name and it bind to the input, is this possible?
The actual input looks like this inside an ng-repeat
<input type="text" ng-model="field.model" class="form-control" ng-if="field.type == 'text'" attributes="field.attrs" />

Right now I can go through the array and get the values ($scope.leftColumn[0].model), but this seems horrible.
Thanks so much!

A: I ended up figuring out a solution that seems to work pretty well.
I added a second attribute to the directive where you pass an object that you want to store the form data in. Then you add an extra property to the form array with what you want to property to be named in the object.
Happy to share more details if anyone else runs across something like this


text:
Q: SQL Server trigger for 'Default (newsequentialid())' not working with '00000000-0000-0000-0000-000000000000'? I have an Entity with a Guid column as the primary key.
Its default is (newsequentialid()). So if I pass NULL it will generate the Guid.
Now I use this database with BDC Model Stuff. The problem is that this auto generated code doesn't pass NULL for the ID with new objects on creation, instead it uses probably just new Guid() which is 00000000-0000-0000-0000-000000000000. So my default constraint is not working and I get a primary key constraint violation error...
So is it possible to catch this problem with a trigger? Maybe check first if the Id is 0000...0 and then generate a valid one?

A: You can use triggers, although as others have pointed out, this would be an unwise solution, as introduces an unseen hack between code and data. Your real solution is to change your ORM such that it doesn't attempt to insert the GUID directly, as this is database generated.
So ignore the remainder of my answer.

 SqlServer doesn't support BEFORE triggers, but you could use an INSTEAD OF TRIGGER

     CREATE TRIGGER tSomeTable  ON SomeTable INSTEAD OF INSERT
     AS
        BEGIN
           INSERT INTO SomeTable(SomeKey, Name)
              SELECT
                 CASE WHEN i.SomeKey = '00000000-0000-0000-0000-000000000000'
                      THEN newid() ELSE i.SomeKey END,
                 i.Name
              FROM INSERTED i;
        END

SqlFiddle here

A: Pass Guid.NewGuid() which generates a valid Guid.


text:
Q: How to call method in lambda expression I have 3 ways to swap 2 variables (basically 3 different algorithms). Since you can't pass a method as a parameter in Java, I thought this would be a good time to use lambda expressions.
chooseSwapMethod(int selection) {
    if(selection == 1) {
        functionThatUsesSwap(
            (int[] arr, int x, int y) -> {
                int holder = arr[x];
                arr[x] = arr[y];
                arr[y] = holder;
        });
    }
    else if(selection == 2)
    {
        functionThatUsesSwap(
            (int[] arr, int x, int y) -> {
                arr[x] -= arr[y];
                arr[y] = arr[x]-arr[y];
                arr[x] -= arr[y];
        });
    }
    else if(selection == 3) {
                functionThatUsesSwap(
            (int[] arr, int x, int y) -> {
                arr[x] = arr[x]^arr[y];
                arr[y] = arr[y]^arr[x];
                arr[x] = arr[x]^arr[y];
        });
    }
    else {
        throw new IllegalArgumentEarr[x]ception();
    }
}

but in the method functionThatUsesSwap how do you actually use the swap? Am I not understanding lambda expressions clearly? For example
public void functionThatUsesSwap(Swaper s)
{
    int[] someArr = {1, 2};
    s.doSwap(someArr, 0, 1);//this is where I'm stuck
    System.out.println("a: "+someArr[0]+" b: "+someArr[1]);//this should print out a: 2 b: 1
}

A: Java is pass by value, that means that in the following:
int a = 5;
int b = 6;
swap(a,b);
System.out.println(a+" "+b);

There is no way for the function swap to change value of a or b and the result will always be 5 6.
What you can do is:

*

*pass and arrays of 2 numbers into the swap method, and swap numbers inside that array.

*make a class to hold 2 numbers and pass that.

Going with possibility 2:
class Pair {
    int a, b;
}

@FunctionalInterface
interface Swapper {
    void swap(Pair p);
}

void main() {
    Pair p = new Pair();
    p.a = 5;
    p.b = 6;
    Swapper swapper = (v -> {
        v.a ^= v.b;
        v.b ^= v.a;
        v.a ^= v.b;
    });
    swapper.swap(p);
    System.out.println(p.a + " " + p.b);
}

Result: 6 5. Note that your claim that you can't pass a method as a parameter in Java isn't entirely true, since you can pass interfaces instead.
EDIT:
There is yet another approach (I haven't thought of this earlier because Interger class is immutable). You can create a mutable (= changable) object vrapper for integer value, something like:
class IntVrapper {
    public int value;
}

Then your swap method could swap data between those two objects.


text:
Q: Send commands from lighttpd to mono application I'm working on a project and what I want to do, I have installed lighttpd on my raspberry pi which is running xbian and I have created asp file using to control xbmc by using some .net library.I got mono application as well to control xbmc and I want to send command or signal or message from lighttpd to the running mono application
How to do this, do i have to use any rpc, pipe etc.
thank you

A: You could either use the lua or php plugin, parse the requests there and run your stuff accordingly.
A rather difficult alternative would be to write a plugin yourself and make that do whatever it needs to do (though this will require at least decent C skills as well as security awareness) http://redmine.lighttpd.net/projects/1/wiki/HowToWriteALighttpdPlugin

A: https://www.mono-project.com/docs/web/fastcgi/
Separately, if files are downloading instead of being processed, then ensure that you have configured lighttpd.conf mimetype.assign


text: Q: Microsoft Sql Server Database data to google firebase Is it possible to send my sql server database data via stored procedures, to my google firebase database? How can I do that? I am new to use firebase, please show me a way to do that.


text:
Q: How can we get the previous formula field value in the next row formula field? I have two formula field Like Open balance and Closing balance.
In this, the Opening balance value will Previous day's Closing balance.
And the Closing Balance Calculation will be done using the Open Balance value.
For example the formula's inside the formula fields are:

For Opening Balance

            If OnFirstRecord = true Then (If {OpenBalanceCreditAmount}=0 then {OpenBalanceDebitAmount} else if {OpenBalanceDebitAmount}=0 then (-{OpenBalanceCreditAmount}))else Previous({@ClosingBalAmount})

For Closing Balance

    (If {@OpenBalanceAmount}<0 then ((-{@CreditAmount}+{@OpenBalanceAmount})+{@DebitAmount}) else if {@OpenBalanceAmount}>=0 then (({@DebitAmount}+{@OpenBalanceAmount})+(-{@CreditAmount})))

I am getting a error: "A Formula Cannot refer to itself,either directly or Indirectly".
Also I tried passing a temporary Formula field, which passes value of Closing balance to Open Balance. But,it too shown a same error. I think so referencing issue. Can we take only the value of closing balance by leaving the parameters used in Closing balance calculation.
Please help me out of this. And Thanks in advance.


text:
Q: How to know what function called another in JavaScript? Is there a way to automatically know who called a specific function in JS?
Let's say I have this code:
function1() {
function2();
}

function2() {
console.log('the function who called me is ...' + <magic code here>);
}

When function1 calls function2, is there any magic way for function2 to know that function1 called it, without passing any additional parameters?

A: You can use function2.caller. Using caller property gives you the detail of the function that invoked it. And further use name property to get the name of the calling function.

function function1(){
  function2();
}

function function2() {
  console.log('called by function' + function2.caller.name);
  console.log('the function who called me is ...');
}

function1();


text:
Q: Mariadb -> connect engine -> unixodbc -> firebird I like to use connect engine of mariadb to connect to a firebird database via ODBC on a server which is running on Centos 7.
I have already established a connection to sqlserver. The odbc-test to the firebird-database with isql works as well.
This is my create-statement:
CREATE TABLE con.test_table_apys
ENGINE=CONNECT
TABLE_TYPE=ODBC
TABNAME='wsk_lager_st'
CONNECTION='DSN=apys;UID=SYSDBA;PWD=myownpassword';

After sending the statement to the server I got this error message:
ERROR 2006 (HY000): MySQL server has gone away

This is the content of odbc.ini
[apys]
Description     = Firebird
Driver          = Firebird
Dbname          = apysdbserver/3051:vm_apys_ori205
Role            =
CharacterSet    = WIN1252
ReadOnly        = No
NoWait          = No

Any ideas? Thank you.

A: Now it works. The modifications are:
I have put username and password in odbc.ini
[apys]
Description     = Firebird
Driver          = Firebird
Dbname          = apysdbserver/3051:vm_apys_ori205
Role            =
CharacterSet    = WIN1252
ReadOnly        = No
NoWait          = No
User            = SYSDBA
Password        = myownpassword

removed user and password from create-statement
CREATE TABLE con.test_table_apys
ENGINE=CONNECT
TABLE_TYPE=ODBC
TABNAME='wsk_lager_st'
CONNECTION='DSN=apys';

and defined the columns
CREATE TABLE con.test_table_apys (
ID INT,
some_text VARCHAR(100)
)
ENGINE=CONNECT
TABLE_TYPE=ODBC
TABNAME='wsk_lager_st'
CONNECTION='DSN=apys';


text:
Q: POST a JSON body with the Sails REST Blueprint? In Sails 0.10, the default REST blueprint for a create action seems to only accept a POST with the content of the new item via query parameters.  I also need to support the POSTing of a JSON body to create the item.
So, POST http://localhost:1337/user?username=George works just fine, but the following does not:
POST http://localhost:1337/user

{
   username: 'George'
}

Is this possible with the default blueprint or must I implement this manually?

A: I was missing the header:
Content-Type: application/json
Now it works like a champ!