text:
Q: Переход на другую строчку Подскажите, пожалуйста, как мне сделать так, чтобы я переходил на другую строчку?
os.system('cls||clear') # очищаем экран
    back = (colored ("0 = назад ---> " , 'red'))
    print (colored ("---------------SCANER---------------" , 'red')) #приветствие :)
    print (colored ("[1]=сканировать отдельный порт" , 'yellow'))
    print (colored ("[2]=сканировать список" , 'yellow'))
    print (colored ("[3]=о самом скрипте" , 'yellow'))
    x = int(input(colored("[scan] ---> " , 'white')))
    if x==1:
        f1()
    elif x==2:
        f2()
    elif x==3:
        os.system('cls||clear')
        print (colored ("О скрипте и что он делает: Данный скрипт сканирует порты у хоста и проверят их закрыты они или нет." , 'blue'))
        print (colored ("1 функция скрипта сканирует конкретный порт выбранный вами." , 'blue'))
        print (colored ("2 функция скрипта сканирует несколько портов. есть два варианта:" , 'blue'))
        print (colored ("2.1 сканирует самые известный порты. 2.2 сканирует все порты от 1 до 6535" , 'blue'))
        print (colored ("Примечание: Будьте остарожнее с функцией 2.2! у вас может зависнуть компьютер или быть проблемы с провайдером!!!" , 'blue'))
        print (colored ("by Bogdan" , 'blue'))

    else:
        print (colored("Ошибка!" , 'red'))

перед else нужно что бы программа задавала вопрос хотите ли вы вернуться назад? тогда мы вводим число и он возращает нас на первую строчку (сорри за глупый вопрос)

A: Вам необходим бесконечный цикл с выходом по условию:
while True:
  # ваш код который вы привели в вопросе
  r = int(input(colored("Repeat? 0 - No, 1 - Yes " , 'white')))
  if r==0:
    break


text:
Q: Refresh datagridview after update data in another form I have two forms. Form 1 has a datagridview in side and form 2 has a textbox and a button inside. Value is entered in textbox will be inserted in datagridview after I click the button.
I used Show() and ShowDialog() before, but a new form with new data is shown after I clicked button. I also tried Update() and Refresh() but still not working? I need the datagridview refresh itself after I click the button and no new form come out. Anyone can help me? Please....
Here is my code:
Form 1
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.dataGridView1.Rows.Add(46.13, 0, 0);
        this.dataGridView1.Rows.Add(105.22, 0, 0);
        this.dataGridView1.Rows.Add(80.67, 0, 0);
    }

    public void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 newMDIChild = new Form2();
        // Set the parent form of the child window.
        newMDIChild.MdiParent = this;
        // Display the new form.
        newMDIChild.Show();

    }

Form 2
public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        FormTest.Form1 frm = new Form1();

        frm.dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;

        frm.();

    }
}

A: Form 2 Button Click use this Code
private void button1_Click(object sender, EventArgs e)
{
   Form frm=(Form)this.MdiParent;
   DataGridView dt = (DataGridView)frm.Controls["dataGridView1"];
   dt.Rows[0].Cells[0].Value = textBox1.Text;

}

A: You can create a callback interface with one method to add and update data. Implement this in form1 then create a new constructor in form2 with a parameter type of the interface and when creating form2's object pass the reference of the form1 (this).
from the form2 when you click on the button just call the interface's method with data to update in gridview as parameter. The interface object here in form2 holds reference of form1 and it will call the function implemented in form1 update the grid.
interface ICallBack { void UpdateGrid(string data); }

public calss Class1 : ICallBack
{
        // Rest of your code

    void UpdateGrid(string data)
    {
            gridView.Rows[0].Cells[0].Value = data;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Class2 obj = new Class2(this);
        obj.Show();
    }
}

public calss Class2
{
    ICallBack callback;

    public Class2(ICallBack callback)
    {
        this.callback = callback;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        callback.UpdateGrid(textBox1.Text);
    }
}

Hope it helps!

A: If you wish to update/Refresh datagridview on another form. I see two methods:
1. DataTable (Create a datatable and make the source of your datagridview, if you make the changes you will realize the changes are immediately impacting datagridview)
Programmatically to achieve it follow as: Assuming Form-1 has datagridview and Form to has some controls from where you want to add/edit/delete data and want to change Datagridview on Form-1
On Form-2 create a constructor as:
Form myForm1-null;
    public Form-2(Form objForm1)
    {
myForm1=objForm1;
InitializeComponent();
    }

Now you can access myForm1 object like this on any event:
private void btnadd_Click(object sender, EventArgs e)
{
DataGridView dg = (DataGridView)myForm1.Controls["YourDataGridViewName"];
dg.Rows.Add();
}

Now come to Form-1 and open the event on which you are calling Form-2
private void btnShow_Click(object sender, EventArgs e)
{
Form-2 oFrm2 = new Form-2(this);
oFrm2.Show();
}

Hope it helps

A: Best approach would be using delegates.
Use the code as follows.
Assume MainForm has the data grid.
Main Form :
public MainForm()
        {
            InitializeComponent();
        }

public void form2_UpdateEventHandler(object sender, Form2.UpdateEventArgs args)
    {
        dgvItems.DataSource = GetData();
    }

private void MainForm_Load(object sender, EventArgs e)
        {
             dgvItems.DataSource =  GetData();
        }

public DataTable GetData()
        {
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = *your query*
            adp = new SqlDataAdapter(cmd);
            ds.Clear();
            adp.Fill(ds);
            dt = ds.Tables[0];
            con.Close();
            return dt;
        }
//show Form 2

private void btnSave_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2(this);
            frm.UpdateEventHandler += form2_UpdateEventHandler;
            frm.ShowDialog();

        }

Then assume insert data from Form 2
Form 2 :
//Form 2 constructor

public Form2(MainForm mainForm)
   {
    InitializeComponent();
   }

 public delegate void UpdateDelegate(object sender, UpdateEventArgs args);
 public event UpdateDelegate UpdateEventHandler;

 public class UpdateEventArgs : EventArgs
    {
      public string Data { get; set; }
    }

protected void InsertData()
    {
       UpdateEventArgs args = new UpdateEventArgs();
       UpdateEventHandler.Invoke(this, args);
    }

 private void btnInsertData_Click(object sender, EventArgs e)
     {
        SqlCommand cmd = new SqlCommand("SP_AddNewRow", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@param1", "Test1");
        cmd.Parameters.AddWithValue("@param2", "Test2");

    if (con.State == ConnectionState.Closed)
       {
         con.Open();
        }
    int n = cmd.ExecuteNonQuery();

    con.Close();

    if (n != 0)
    {
      //your codes if needed
       InsertData();
    }
}

Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass query values from a ASP.NET page to a WPF page contained in an iframe? I have an ASP.NET web page that contains an iframe. In it I want to show a WPF page. When I load the page I do this:
string strPrint = ResolveClientUrl("~/FolderXXX/PageXXX.xbap?param1=value1&param2=value2");
printIfr.Attributes["src"] = strPrint;

The page loads perfectly, and shows my (few) controls, but I cannot access param1 and param2. I tried
NameValueCollection param = HttpUtility.ParseQueryString((ApplicationDeployment.CurrentDeployment.ActivationUri));
string letters = param["param1"];

but I get an empty string...

A: It turns out that I was passing parameters properly, using the iframe src property and then from the WPF get those values using ApplicationDeployment.CurrentDeployment.ActivationUri
The problem with this seeming not to be working was that I'm using Visual Studio internal server. Switched to IIS and worked like a charm.
Hope this helps someone!


text:
Q: Unlocking 3D Analyst and Spatial Analyst Tools with ArcGIS Pro? If I buy ArcGIS Pro, do I need to buy Spatial Analyst and 3D Analyst extensions separately, or do they come free with the package?

A: If you already have ArcGIS Desktop (ArcMap) with those extensions, ArcGIS Pro is licensed to use the same extensions - you won't need to buy the extensions again.
You will need to set up your ArcGIS Pro Extension licenses in the same way as you set up your ArcGIS Pro licenses.

Can I use my licensed ArcGIS for Desktop extensions with ArcGIS Pro?
Yes. Since ArcGIS Pro is part of ArcGIS for Desktop, you are licensed
  to use the same extensions for ArcGIS Pro as you are with ArcMap (as
  available). The following extensions are available for ArcGIS Pro:
  ArcGIS 3D Analyst, ArcGIS Spatial Analyst, ArcGIS Network Analyst,
  ArcGIS Workflow Manager, and ArcGIS Data Reviewer. The extension
  licenses for ArcGIS Pro are managed using the same method you have
  chosen for your ArcGIS Pro license.

from ArcGIS Pro - Common Questions

A: To see the 3D/Spatial Analyst tools in ArcGIS Pro which require separate licensing you should consult these pages from the Help:

*

*3D Analyst toolbox licensing

*Spatial Analyst toolbox licensing

A: Just like with ArcGIS for Desktop (that you'll receive if you buy ArcGIS Pro and vice versa) extensions must be purchased . Note that with ArcGIS Pro, you'll be able to visualize layers in 3D (but you won't have access to the tools of the 3D Analyst toolbox if you don't buy it).
For both Desktop applications, you can evaluate any extension during (I think) 2 months for free.


text:
Q: How does ambipolar transport work? In my introductory semiconductor physics class, I learned that "excess holes and electrons move together in the presence of an applied electric field because of the development of an internal electric field that provides a force attracting the excess holes and electrons". I do understand that the applied electric field will lead to a charge separation and the charge separation will lead to the development of an internal electric field causing an attraction between holes and electrons. However, I do not understand how holes and electrons can move together. Unless the internal and applied electric fields have the same magnitude, shouldn't holes and electrons have opposite net forces and still move in opposite directions although their acceleration and speed may decrease due to the presence of internal electric field?
Moreover, even under the assumption that they do move together, how do they drift in an applied electric field while the packet of a hole and an electron pair would have no net charge?


text:
Q: Checking whether they are characteristic functions or not. My problem is determined whether the following functions $\phi(t)=\cos(t)$ and $\phi(t)=(1+t^4)^{-1}$ are characteristic functions for some random variable?
One thing I know that if they didn't satisfy properties of characteristic functions (such as $\phi(0)=1$, and $\phi$ is uniformly continuous), then we can say they are not characteristic functions. However, these two functions agrees these properties, and hence I may guess they will be characteristic functions for some random variables. However, I have no idea how to show the argument.
Thank you.

A: $$\cos(t) = \frac{e^{it} + e^{-it}}{2}$$
so this is the characteristic function of a random variable that is $+1$ with probability $1/2$ and $-1$ with probability $1/2$.
$(1+t^4)^{-1}$ is the Fourier transform of $2^{-3/2} e^{-|s|/\sqrt{2}} (\cos(s/\sqrt{2}) + \sin(|s|/\sqrt{2})$
but this is negative e.g. for $s/\sqrt{2} \in (3\pi/4, 7\pi/4)$, so in this case $\phi$ can't be a characteristic function.
EDIT: Another way to show $\phi(t) = (1+t^4)^{-1}$ is not a characteristic function is to show that there is an $n$-tuple of real numbers $s_1, \ldots, s_n$ such that the $n \times n$ matrix with entries $A_{jk} = \phi(s_j - s_k)$
is not positive semidefinite.  For example, this is the case with $n=3$ and
$s_1 = 1/2,s_2 = 1, s_3 = 3/2)$: you can check that
$$ \det\pmatrix{1 & 16/17 & 1/2\cr 16/17 & 1 & 16/17\cr 1/2 & 16/17 & 1} < 0$$


text:
Q: Natural homomorphism from local galois group to galois group of residue field extension Let $L/K$ be a galois extension of number field. Let $R_K$ and $R_L$ be ring of integers of $K$ and $L$.
Let $p$ be a unratified prime of $K$. Let $P$ be a unique prime above $p$.
There is map from $Gal(L_P/K_p)$ to $Gal((R_L/P)/(R_K/p))$.
I'm having trouble to prove this map is isomorphism.
I understand the proof of subjectivity, but stuck with injectivity. I should have to use the condition $p$ is uramified. Thank you for your help.


text:
Q: Any difference between "don't forget it" and "don't you forget it!"? Sometimes it gets confusing whether we should include "you" when we want to tell someone not to do something.
For insantance, normally if we want someone not to do something, we would say "Do not do it". But it is quite often that I often see sentences like "Do not you do it". That makes me confused.
For instance look at this sentence: "I'm the boss around here, and don't you forget it!"
What would change if the speaker did not include "you", such as "I'm the boss around here, and don't forget it!"
So, my question is basically, is there any difference between;
- "Don't do it!"
- "Don't you do it!"
Regards,

A: "Don't you ..." (as a command, not a question) is a frozen expression that reflects the grammar of older English. It would be ungrammatical (or barely grammatical) in Modern English, except in this phrase.
It is used as a stronger version of "Don't".

A: "Don't (you) forget it!" is standard negated imperative. Making the subject explicit adds emphasis.
This looks a bit odd since it's inverted, but that only happens when you have helper verb "do" for negation. The positive form looks more normal; in fact, the only way you know the emphasized form is imperative rather than declarative is the exclamation mark (or tone, if spoken):
"(You) forget it!"


text:
Q: Android UNEXPECTED TOP-LEVEL EXCEPTION: After adding the Espresso test files I got the error. I tried many suggestions, nothing helped so far.
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Landroid/support/test/BuildConfig;
    at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
    }
}

The app build.gradle is:
apply plugin: 'com.android.application'
android {
    signingConfigs {
        config {
           keystore stuff ...
        }
    }
    compileSdkVersion 22
    buildToolsVersion "22.0.1"
    defaultConfig {
        applicationId ...
        minSdkVersion 16
        targetSdkVersion 19
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-project.txt'
        }
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'LICENSE.txt'
    }
}
dependencies {
    compile 'com.android.support:support-v4:22.1.0'
    compile 'com.google.code.gson:gson:2.4'
    compile 'joda-time:joda-time:2.0'
    compile files('libs/commons-io-2.4.jar')
    compile files('libs/commons-lang3-3.4.jar')
    compile files('libs/exp4j-0.4.4.jar')
    compile files('libs/GraphView-3.1.2.jar')
    compile files('libs/mapsforge-map-0.3.1-SNAPSHOT-jar-with-dependencies.jar')
    compile files('libs/osmbonuspack_v5.1.jar')
    compile files('libs/osmdroid-android-4.3.jar')
    compile files('libs/slf4j-android-1.5.8.jar')
    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
    compile 'com.android.support:support-annotations:22.2.0'
    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test:rules:0.3'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
}
allprojects {
    repositories {
        jcenter()
    }
}

I tried many suggestions in this area, I hope you can help.

A: Based on the answer here and your config file, could you remove the following line from your gradle and give it a shot.
com.android.support.test:testing-support-lib:0.1


text:
Q: remove input box border using CSS? I have an input text field that I have removed its borders and changed its background using CSS.
This works fine in Firefox but the problem that I have is in the Google Chrome!
Good----> This is how it should be and is in Firefox:
http://tinypic.com/view.php?pic=n2g0g0&s=5
Bad-----> This is how it is showing in Google Chrome with the white border around the input field:
http://tinypic.com/view.php?pic=uc1me&s=5
This is my CSS CODE:
#myInput{

color:#FFF;
font-family:Tahoma, Geneva, sans-serif;
text-align:center;
font-size:16px;
background-color:#1abc9c;
outline:none;
border:none;
border-style: none;
font-weight:bold;
}

although the CSS above is inline CSS.
The question is how can I remove that white border around the input field so it looks like the one in firefox?
Thanks
edit:
Here is the code for the input inside the div tags. This is exactly what I have in the HTML page:

<FORM NAME="wcForm" >
  <input style=" color:#FFF; font-family:Tahoma, Geneva, sans-serif; text-align:center; font-size:16px; background-color:#1abc9c; outline:none; border:none; border-style: none; font-weight:bold -webkit-appearance:none; -moz-appearance:none; appearance:none;"  name="mClock" class="mClock" id="mClock" size="30" />
</FORM>

A:


text:
Q: Use dconf (or comparable) to set configs for another user On Ubuntu Desktop 13.10, I have a setup script which runs as root. It essentially configures the computer as necessary, but I need to set some things with dconf. The script runs in a Terminal window under a regular user with sudo. I need to run the command dconf write /com/canonical/unity/launcher/favorites "['unity://expo-icon', <...>']". (It is run with a variety of different settings.)
I have tested the commands as the login user, and they work just fine. However, when I am logged in as root, I cannot do sudo -u bitc dconf write <...>; I get errors like error: Could not connect: Connection refused or unable to create directory '/root/.cache/conf'.
The script must be run as root because of some other tasks it performs, but it appears that dconf must be run under the specific login session, not just the user, to configure it. I would rather not have a separate script for dconf, but that is possible. Is there a way to attach to the login session (or some other way to set the dconf keys for that user)?
(The script is written in javascript with node.js.)

A: Is it sufficient to do this?
sudo -u bitc HOME=/home/bitc dconf write <...>
             ^^^^^^^^^^^^^^^

I was trying to do something similar. I have a script that connects via SSH and runs as root. I want it to change some settings for a user. This seems to work for me:
sudo -u vagrant HOME=/home/vagrant dbus-launch --exit-with-session gsettings set org.freedesktop.ibus.general use-system-keyboard-layout true

I think that's potentially bad because it's spawning a new dbus-daemon for the duration of the this session, but without the dbus-launch I got dbus errors. Perhaps these are specific to gsettings, but I want to mention it in case it helps.

A: I have a POST-Install script that sets my gsetting. Because I run the script as sudo the EUID is 0, there fore I have to find the $RUID (Real User ID).
here is my approach:
#!/usr/bin/env bash
# Get the Real Username
RUID=$(who | awk 'FNR == 1 {print $1}')

# Translate Real Username to Real User ID
RUSER_UID=$(id -u ${RUID})

# Set gsettings for the Real User
sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings set org.gnome.desktop.interface clock-show-date false

exit


text:
Q: shifting a DataFrame along another and mapping correlation I have a dataset full of meaningless information (length=M), within which a range with the data I am actually looking for is hidden. Since I know in advance how the "true data" section approximately looks like, I have a "master dataset" (length=n, whereby n is way smaller than M), which I shift along the measured dataset. The logic I use is:

*

*I start by comparing the master dataset with the first n elements of the measured data

*calculate the correlation

*Shift in the measured dataset by one element. Compare the master dataset with the measured data [1:n+1]

*calculate the correlation

*shift by another element. Correlation with  measured data [2:n+2]

*and so on...

This way, I can locate my data by finding the maximum correlation between the data and the master. Here is a simplified version of my code:
a_list = [0,1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1,0]
b_list = [6,7,8,7,6]
a_array = np.array(a_list)
b_array = np.array(b_list)

a_dataframe = pd.DataFrame(a_array)
b_dataframe = pd.DataFrame(b_array)

correlations = []
for i in range (0,len(a_dataframe)-len(b_dataframe)):
    correlations.append(a_dataframe[i:len(b_dataframe)+i].corrwith(b_dataframe)[0])

This code works just fine (although the correlations that come out in this example are nonsense), and it finds what I look for. The problem  have is that shifting each time one element with a loop and appending each calculated correlation to a list seems like a pretty inefficient approach to me. And this step is actually one of the bottlenecks of my whole software when it comes to calculation time.
I am searching for more efficient, elegant, pythonic apporaches to basically do the same. Help?
Thank you very much in advance
D.
EDIT AFTER SCOTT THOPSON'S COMMENT
I have corrected the mistake pointed out.


text:
Q: Convert a simple cnn from keras to pytorch Can anyone please help me to convert this model to PyTorch? I already tried to convert from Keras to PyTorch like this How can I convert this keras cnn model to pytorch version but training results were different. Thank you.
input_3d = (1, 64, 96, 96)
pool_3d = (2, 2, 2)
model = Sequential()
model.add(Convolution3D(8, 3, 3, 3, name='conv1', input_shape=input_3d,
                          data_format='channels_first'))
model.add(MaxPooling3D(pool_size=pool_3d, name='pool1'))
model.add(Convolution3D(8, 3, 3, 3, name='conv2',data_format='channels_first'))
model.add(MaxPooling3D(pool_size=pool_3d, name='pool2'))
model.add(Convolution3D(8, 3, 3, 3, name='conv3',data_format='channels_first'))
model.add(MaxPooling3D(pool_size=pool_3d, name='pool3'))
model.add(Flatten())
model.add(Dense(2000, activation='relu', name='dense1'))
model.add(Dropout(0.5, name='dropout1'))
model.add(Dense(500, activation='relu', name='dense2'))
model.add(Dropout(0.5, name='dropout2'))
model.add(Dense(3, activation='softmax', name='softmax'))

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv1 (Conv3D)               (None, 8, 60, 94, 94)     224
_________________________________________________________________
pool1 (MaxPooling3D)         (None, 8, 30, 47, 47)     0
_________________________________________________________________
conv2 (Conv3D)               (None, 8, 28, 45, 45)     1736
_________________________________________________________________
pool2 (MaxPooling3D)         (None, 8, 14, 22, 22)     0
_________________________________________________________________
conv3 (Conv3D)               (None, 8, 12, 20, 20)     1736
_________________________________________________________________
pool3 (MaxPooling3D)         (None, 8, 6, 10, 10)      0
_________________________________________________________________
flatten_1 (Flatten)          (None, 4800)              0
_________________________________________________________________
dense1 (Dense)               (None, 2000)              9602000
_________________________________________________________________
dropout1 (Dropout)           (None, 2000)              0
_________________________________________________________________
dense2 (Dense)               (None, 500)               1000500
_________________________________________________________________
dropout2 (Dropout)           (None, 500)               0
_________________________________________________________________
softmax (Dense)              (None, 3)                 1503
=================================================================

A: Your PyTorch equivalent of the Keras model would look like this:
class CNN(nn.Module):

    def __init__(self, ):
        super(CNN, self).__init__()

        self.maxpool = nn.MaxPool3d((2, 2, 2))

        self.conv1 = nn.Conv3d(in_channels=1, out_channels=8, kernel_size=3)
        self.conv2 = nn.Conv3d(in_channels=8, out_channels=8, kernel_size=3)
        self.conv3 = nn.Conv3d(in_channels=8, out_channels=8, kernel_size=3)

        self.linear1 = nn.Linear(4800, 2000)
        self.dropout1 = nn.Dropout3d(0.5)

        self.linear2 = nn.Linear(2000, 500)
        self.dropout2 = nn.Dropout3d(0.5)

        self.linear3 = nn.Linear(500, 3)

    def forward(self, x):

        out = self.maxpool(self.conv1(x))
        out = self.maxpool(self.conv2(out))
        out = self.maxpool(self.conv3(out))

        # Flattening process
        b, c, d, h, w = out.size() # batch_size, channels, depth, height, width
        out = out.view(-1, c * d * h * w)

        out = self.dropout1(self.linear1(out))
        out = self.dropout2(self.linear2(out))
        out = self.linear3(out)

        out = torch.softmax(out, 1)

        return out

A driver program to test the model:
inputs = torch.randn(8, 1, 64, 96, 96)
model = CNN()
outputs = model(inputs)
print(outputs.shape) # torch.Size([8, 3])

A: You can save keras weight and reload then in pytorch.
the steps are
Step 0: Train a Model in Keras. ...
Step 1: Recreate & Initialize Your Model Architecture in PyTorch. ...
Step 2: Import Your Keras Model and Copy the Weights. ...
Step 3: Load Those Weights onto Your PyTorch Model. ...
Step 4: Test and Save Your Pytorch Model.
You Can follow example here https://gereshes.com/2019/06/24/how-to-transfer-a-simple-keras-model-to-pytorch-the-hard-way/


text:
Q: When i apply it it showing Script could not be translated from: |B|var rsiLength = 14|E| // Inputs
var rsiLength = 14
var macdFastLength = 12
var macdSlowLength = 26
var macdSignalLength = 9
var atrLength = 14
var volumeFactor = 0.1
// Calculate indicators
var rsi = rsi(close, rsiLength)
var macd = macd(close, macdFastLength, macdSlowLength, macdSignalLength)
var atr = atr(atrLength)
var volume = volume * volumeFactor
// Define signals
var buySignal = rsi < 30 and macd.histogram > 0 and volume > atr
var sellSignal = rsi > 70 and macd.histogram < 0 and volume > atr
// Plot signals
plot(buySignal ? 50 : na, color=color.green, linewidth=3, style=plot.style_circles, title='Buy Signal')
plot(sellSignal ? 50 : na, color=color.red, linewidth=3, style=plot.style_circles, title='Sell Signal')
// Capital
strategy.risk = 0.01
strategy.entry("Long", strategy.long, when=buySignal, comment="Buy")
strategy.close("Long", when=sellSignal, comment="Sell")
Script could not be translated from: |B|var rsiLength = 14|E|
It tried to make a strategy which generates buy and sell signal but it showing this


text:
Q: Getting groovy syntax issue in my Jenkins pipeline I have a simple script that i need for my pipeline :-

sh '''podname=$(kubectl get pods -n my-namespace --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep my-pod)
          echo "my name is $podname"'''

All i need to invoke through my jenkins declarative pipeline is the value of that kubectl command that i can use later in my script. If i run the same directly on the linux server it works just fine, but somehow through groovy shell invocation always results in syntax errors with respect to unterminated quotes, illegal dollar literal, etc.
How do i fix this?

A: The syntax looks fine to me, except for this, in the middle of the command:
"\n"

This will be interpreted as an actual new-line, which may not be what you want? Perhaps try this instead, to let the \n sequence be passed to the command:
"\\n"

If that still doesn't help...
 according to the docs:
Runs a Bourne shell script, typically on a Unix node. Multiple lines are accepted.

An interpreter selector may be used, for example: #!/usr/bin/perl

So another suggestion is to try adding the appropriate shebang to your script... as there's no reason the result should be different from when you run this on the shell.


text:
Q: Splitting a bilingual text into two parts using Python input text: "gut, wird gemacht right, will do (inf)"
output text: gut, wird gemacht
right , will do (inf)
input text: gut, mache ich right, will do (inf) or I'll do that
output text: gut , mache ich
right, will will do (inf) or I'll do that
input text: "wie mans macht, ists verkehrt whatever you do is wrong"
output text: wie mans macht, ists verkehrt
whatever you do is wrong

A: First off, please try to solve the problem yourself first. As @Julien points out, no one will write code for you.
To answer your question, you need to find an alghoritm that can detect which language a text is written in, and specify how certain it is (eg, counting letter frequencies has a surprisingly good hit rate, or you might want to use a database and compare words to that).
The next step is to choose an algorithm to find the most likely split. You could for instance evaluate each word individually, or try splitting the text in a couple locations to find what position is best.
Once you have that set up it's just a matter of trying different things until you get the accuracy you need.


text:
Q: Shared albums FB Graph API As you know FB has a feature - shared albums. It is pretty good feature which allow many users to use one album.
Issue: I try to develop an iOS application which just show all photos from this SHARED album, but I get only MY photos (which I uploaded), not all. Is there way to get all photos, not only my?
Example: I created a shared album, uploaded 7 photos. My friend uploaded 2 photos. I tried to check this photos with FB Graph API Explorer (https://developers.facebook.com/tools/explorer) and I see only 7 photos in this album and my friend see only 2 photos.
PS: album permissions - for everyone


text:
Q: Rails: Batch Subscribe users to MailChimp API on Heroku running into timeout issues Here is my code
  users = User.all

  # Latency issues with connecting with Heroku and MC
  Gibbon::API.timeout = 120

  gb = Gibbon::API.new
  batch = []
  users.each do |user|
    batch << user.mail_chimp_information
  end

  puts gb.lists.batchSubscribe(id: "MC_ID_HERE", batch: batch, double_optin: false, update_existing: true)

The code above is set to run on a nightly cron that batch subscribes (or updates existing) users to my MailChimp account. My app is running on Heroku which causes issues with retrieving users and then looping through them before sending them to MailChimp. If I remove the Gibbon::API.timeout = 120 line, then the default is 15 seconds and times out.
What is the best practice on batch uploading of user information to an external API? Manually setting the Timeout is a quick fix for now, but as my user base grows, the greater the threat for time outs to occur again.

A: Best practice is to use a delayed job to do the work for you.
The idea is that you setup each job as a one off (instead of many) delayed job and then have a background queue that handles the subscribing.
The common gems are:

*

*DelayedJob

*Resque

*Sidekiq


text:
Q: Troubles with apache and virtual hosts I have a BIG problem.
I have VPS with Debian OS, and LAMP installed. Fresh install.
For control panel i using Webmin.
Now i trying to setup multiple sub-domains on my server using webmin for example:
downloads.my-domain.com
cpanel.my-domains.com
forum.my-domains.com

But problem what is happening is next, while i using no virtual hosts, everything works perfectly when i accessing it using my-domain.com, but when i add Virtual host, i cann access it but my-domain.com becomes unavilable because it redirects to virtual hosts i added. When i add more than 2 virtual hosts, problem is still here.
Also, when i try to access to virtual server for example downloads.my-domain.com, it redirects again to cpanel.my-domains.com
When i delete virtual hosts, access to my-domain.com is succesfull...
What i known:
 - That is not problem with my domain provider. I correctly added subdomains and added host record to my VPS IP.
 - I added unique name to every single virtual host.
 - There are no two same virtual hosts
 - Every virtaul hosts have own directory: for example: downloads.my-domain.com have own WWW dir: /var/downloads
Can somebody help me? Thanks.

A: I fixed it by deleting all exist virtual hosts and manualy adding these code to my httpd.conf for each virtual host:
<VirtualHost *:80>
        ServerAdmin admin@my-domain.com
        DocumentRoot "/var/www/download.my-domain.com"
        ErrorLog /var/www/error_download.log
        CustomLog /var/www/access_download.log common
        ServerName download.my-domain.com
        ServerAlias download
        <Directory "/var/www/download.my-domain.com">
                AllowOverride All
        </Directory>
</VirtualHost>

So if you have(or you haved) same problem, just edit these lines to match your own criteria and use it.
You can use this editor/generator which i just created, to customize this code.
http://server2.elite7hackers.us/apps/vhosts/


text:
Q: When registering on a site through disqus also register this user own my own database So to be honest the title says what I'm after. I've searched and tried (nothing worth posting)
Has anybody ever tried to do this themselves?
Thanks in advance if anybody has thought about this.

A: I found that to get this you will either need to grab out the details via JS with when the post is activated... but this is almost impossible.
So the best answer is to pay discus for their ultimate package and then they offer it to you via their api.


text:
Q: Get month from CalendarView Android I am using the Android CalendarView to create a simple Calendar app. I need to get the Month when the user presses the previous or next buttons in the calendar view. The CalendarView doesn't have any methods to get the month when the user clicks those buttons, so I tried using the following code to extract the Month.
ViewGroup vg = (ViewGroup) calendarView.getChildAt(0);
 View subView = vg.getChildAt(0);

but for some reason the ViewGroup holds a DayPickerViewPager widget, and 2 AppcompatImageButtons (the previous and next buttons), but no TextView or anything like that which holds the actual Month name.
The subView holds the DayPickerViewPager. Does anyone know how I can get the month on previous/next button clicks?
Thank you in advance

A:
The CalendarView doesn't have any methods to get the month when the user clicks those buttons

I think it does; at least when you select a given date.

long getDate ()
Gets the selected date in milliseconds

You can process that into a Calendar object, which you can get the month from.
Refer: Java - Milliseconds to Month/Year (not just the current time)

I need to get the Month when the user presses the previous or next buttons in the calendar view

You need to use setOnDateChangeListener to capture the date that is finally selected.
It's not clear why you need an action event for the "next / previous" buttons when the user has not made a selection yet.
But, it you did, then you will need to setOnClickListener on both of those AppCompatImageButtons. However, once you do that yourself, you'll be overwriting the existing click listeners for them.

A: Unfortunately, you cannot implement the month change event using Android's default CalenderView. However, an alternative customized MaterialCalendarView is available here that provides both the date and month change listeners.
The sample code to use the view is as follows:
MaterialCalendarView calendarView = new MaterialCalendarView(getActivity());
calendarView.setOnMonthChangedListener(new OnMonthChangedListener() {
@Override
public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
      // Do something here
      Date selectedDate = date.getDate();
}
});

The date change listener can also be implemented in the similar manner using MaterialCalendarView.


text:
Q: Transaction on the Client Side i have a big problem to use or understand the use of transaction with wsdualhttpbinding WCF.
i have something like this :
IService :
[ServiceContract]
public interface IService
{
  //...
  [OperationContract]
  [ApplyDataContractResolver]
  [TransactionFlow(TransactionFlowOption.Mandatory)]
  bool SaveDevice(Device device);
  //...
}

Service.svc.cs :
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
  public class Service : IService
  {
   [OperationBehavior(TransactionScopeRequired = true)]
   public bool SaveDevice(Device device)
   {
            bool temp = false;
            Transaction transaction = Transaction.Current;

            using (EntityConn context = new EntityConn())
            {
                try
                {
                  //....
                }
             }
    }
   }

Model.cs
So here im in my Client an try to execute an Operation with Transaction requirements :
if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                try
                {
                   //do some stuff
                }
            }
          }

Well im getting an Error : Transaction.Current is empty

*

*Do i on the right way?

*When not how can i solve it?

Thank u for helping
EDIT : I just needed to place the if after the using
    using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
    {
     if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
     {
            try
            {
               //do some stuff
            }
     }
    }

A: Outside of a TransactionScope, I think Transaction.Current will always be null.  You need to enter the transaction scope first, then start accessing properties of Transaction.Current.  It looks like you are trying to execute some non-transactional operation at the client?  If so, try this:
using (TransactionScope tran = new TransactionScope())
{
    if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
    {
        // ambient transaction is not escalated; exclude this operation from the ambient transaction
        using (TransactionScope tran2 = new TransactionScope(TransactionScopeOption.Suppress))
        {
            // do some stuff
        }
    }
    else
    {
        // ambient transaction is escalated
        // do some other stuff
    }
}

Note: I've copied the condition as you have it in your example code, but you should verify that this is the right test.  According to MSDN, TransactionInformation.DistributedIdentifier is null, not Guid.Empty, outside of a distributed transaction.

A: I think you want to add AutoEnlistTransaction=true on your OperationBehavior attribute.  Likewise, you may want to add AutoCompleteTransaction=true.


text:
Q: Want to filter horizontal normals in xyz vector file (matlab) Code working but not correct I have a vector dataset (Nx3) with xyz positions. I calculated the normals for all the points in my dataset.
What I want to do is filter out all horizontal normals (that is, when the y points represent a vertical feature in my data).
I have this thus far but it's only filtering out points in the x-space. I'm confused if I should be in xz space or yz space to filter out horizontal normals? Suggestions?
%dimension Nx3 (N variable by scene used)
normals = 'normals.csv';
P1 = csvread(normals);

%dimension Nx3 (N variable by scene used)
pts = 'pts.csv';
P0 = csvread(pts);

threshold = .5

%calculate angle between normal vectors and rotated data
ang = atan2( P0(:,2) - P1(:,2), P0(:,1) - P1(:,1) )

%filter data
filter = abs(ang) < threshold;
newNormals = P1(~filter, :);
newPts = P0(~filter,:);

dlmwrite('newpts.txt', finalPts, 'delimiter',' ')

A: Assuming that the y-axis points upward, it seems like you are only checking the projection of your vector on the xy-plane. If you are trying to filter all vertical vectors, then you should do the exact same check on the yz-plane as well.
% xy-projection
x_filter = abs(atan2(P0(:,2)-P1(:,2),P0(:,1)-P1(:,1))<threshold;
% yz-projection
z_filter = abs(atan2(P0(:,2)-P1(:,2),P0(:,3)-P1(:,3))<threshold;
% xy-projection and yz-projections are both vertical
filter = x_filter & z_filter;

But another check would be that diff(x) and diff(z) are both zero.
threshold = 1e-3;
% what is relative difference between vector's length and diff(y)?
filter = abs(1-norm(P0-P1)./(P0(:,2)-P1(:,2)))<threshold;

then use your filter as previously.
newNormals = P1(~filter, :);
newPts = P0(~filter,:);


text:
Q: Why the array need to be sorted first in "Meeting Rooms 2" of Leetcode? The following is the problem "Meeting Rooms 2" in Leetcode:

Given an array of meeting time intervals consisting of start and end
  times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of
  conference rooms required.
For example, Given [[0, 30],[5, 10],[15, 20]], return 2.

As we all know a possible solution is to sort the interval array before compare the start and the end time of the adjacent meeting.
    public int minMeetingRooms(Interval[] intervals) {
        Arrays.sort(intervals, new Comparator<Interval>() {
            public int compare(Interval a, Interval b) {
                return a.start - b.start;
            }
        });
        List<Interval> list = new ArrayList<>(Arrays.asList(intervals));
        int count = 0;
        while (!list.isEmpty()) {
            int end = list.remove(0).end; count++; // create new timeline
            Iterator<Interval> ite = list.iterator();
            while (ite.hasNext()) {
                Interval next = ite.next();
                if (next.start >= end) { // add to current timeline
                    end = next.end;
                    ite.remove();
                }
            }
        }
        return count;
    }

But let's say we have the following code to detect the time conflict between two meetings,
    private boolean isConflict(Interval a, Interval b) {
        boolean abfb = (a.start < b.start && a.end <= b.start);
        boolean aaftb = (b.start < a.start && b.end <= a.start);
        return !(abfb || aaftb);
    }

For example, we have the intervals: [[15,20],[12,14],[1,17],[0,30],[7,10],[5,10]]. Begin with [15,20],
The schedule of Room#1 should be: [[7,10],[12,14],[15,20]]
Now it remains [[1,17],[0,30],[5,10]], they all need a new room,
Room#2 : [[1,17]],
Room#3 : [[0,30]],
Room#4 : [[5,10]],
So we need 4 rooms in all.
And here is the code,
    public int minMeetingRooms(Interval[] intervals) {
        List<Interval> list = new LinkedList<>(Arrays.asList(intervals));
        int count = 0;
        while (!list.isEmpty()) {
            List<Interval> group = new ArrayList<>();
            group.add(list.remove(0)); count++;
            Iterator<Interval> ite = list.iterator();
            while (ite.hasNext()) {
                Interval noGroup = ite.next();
                boolean conflict = false;
                for (Interval inGroup : group) {
                    if (isConflict(inGroup,noGroup)) { conflict = true; break; }
                }
                if (!conflict) {
                    group.add(noGroup);
                    ite.remove();
                }
            }
        }
        return count;
    }

The above code passed 71/77 tests, but failed on the 72th. Any one can tell the reason why it doesn't work if we do not sort first the intervals?

A: You need not to sort the array. It can be solved in O(n) time complexity. The idea is to create a count array and update it with +1 at index start[i] and with -1 at index end[i]. start and end are the arrays of corresponding start and end timings of the meetings.
After that, you just need to add all +1 and -1 and form the exact count array and then return the maximum value present in that array. Below is the pseudo code:
int[] count = new int[100];
for(int i=0;i<start.length;i++){
    count[start[i]] += 1;
    count[end[i]] -= 1;
}
//form the count array with exact values in this loop
count[0] = 0;
for(int i =0;i<count.length;i++){
    count[i] = count[i] + count[i-1];
}
return max(count);

A: Your "greedy" algorithm will not make optimal use of rooms for some input sets.  It accepts the first fit it finds in the list of intervals.  Rather, it needs to take the closest fit for every available opening.  One way to achieve this is to sort the intervals by starting time; that way, it will always find the earliest available meeting once the most recent one is completed.
For instance, generate several sets of meetings with 1-unit gaps: say, 3, 4, 5, and 6 units long.
[[1, 3], [4, 6], [7, 9], ...]
[[1, 4], [5, 8], [9, 12], ...]
[[1, 5], [6, 10], [11, 15], ...]
[[1, 6], [7, 12], [13, 18], ...]

Feed them to your algorithm in order, and you'll get the optimal 4 rooms.  Shuffle them randomly, and you'll require 5 or 6 rooms.


text:
Q: Where does Elaticsearch take the elasticsearch-keystore password from? I've been reading the little documentation Elastic provides, but it is just about how to operate it. And I don't really understand the fundamentals of it.

*

*You initialise the keystore with a password: bin/elasticsearch-keystore passwd

*You add a key-value to it bin/elasticsearch-keystore add mySecret (prompts for secret)

*You refer to the key inside elasticsearch.yml i.e. ${mySecret}

*Start Elasticsearch, and the value is magically extracted and replaced from the keystore.

My doubt is: how does Elasticsearch get the password to decrypt the keystore and use the values in the configuration file? Or is the keystore password stored somewhere?
If yes, where? In this case I don't see the benefit of using keystore at all?

A: @sscarduzio
place your password in ansible yml file, protect the yml file with ansible-vault, this way you only have to remember and type only the vault password for all the keystores and sensitive passwords
with some further tricks depensing on your setup you can automate further and supply vault password with automation

A: Currently I am using elasticsearch v7.10. Its systemd service runs /usr/share/elasticsearch/bin/systemd-entrypoint as its ExecStart. By looking at it, you can see that it is trying to read keystore password from a file specified by environment variable ES_KEYSTORE_PASSPHRASE_FILE.
You can create a file, containing your passphrase, add an Environment directive in your service file and assign ES_KEYSTORE_PASSPHRASE_FILE to path of your file.
touch /var/elasticpassword
echo MY_STRONG_PASSWORD > /var/elasticpassword
vim /usr/lib/systemd/system/elasticsearch.service

in [service] section add the following line:
Environment=/var/elasticpassword

Reload systemctl and restart the service
systemctl daemon-reload
service elasticsearch restart


text:
Q: Google Adsense are not visible i have placed the Google ad sense code on website.. it shows the block but Google ad is not visible.
Looking forward for your valuable advise and experience.

A: Same issue here I have found what is causing this issue. When I insert the ad code inside the wordpress widgets, the wordpress is automatically removing the comments line of adsense > for eg:    this is name of the ad unit given by adsense in the form of comment. But when I checked the webpage source code, it is automatically removing this line and so ads are not appearing and empty blocks appear. Haven't found a solution yet, will post it if I find it. I came here searching for one and saw your post.


text:
Q: How Were These Coefficients in a Polynomial Approximation for Sine Determined? Background: I'm writing some geometry software in Java. I need the precision offered by Java's BigDecimal class. Since BigDecimal doesn't have support for trig functions, I thought I'd take a look at how Java implements the standard Math library methods and write my own version with BigDecimal support.
Reading this JavaDoc, I learned that Java uses algorithms "from the well-known network library netlib as the package "Freely Distributable Math Library," fdlibm. These algorithms, which are written in the C programming language, are then to be understood as executed with all floating-point operations following the rules of Java floating-point arithmetic."
My Question: I looked up fblibm's sin function, k_sin.c, and it looks like they use a Taylor series of order 13 to approximate sine (edit - njuffa commented that fdlibm uses a minimax polynomial approximation). The code defines the coefficients of the polynomial as S1 through S6. I decided to check the values of these coefficients, and found that S6 is only correct to one significant digit! I would expect it to be 1/(13!), which Windows Calculator and Google Calc tell me is 1.6059044...e-10, not 1.58969099521155010221e-10 (which is the value for S6 in the code). Even S5 differs in the fifth digit from 1/(11!). Can someone explain this discrepancy? Specifically, how are those coefficients (S1 through S6) determined?
/* @(#)k_sin.c 1.3 95/01/18 */
/*
 * ====================================================
 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
 *
 * Developed at SunSoft, a Sun Microsystems, Inc. business.
 * Permission to use, copy, modify, and distribute this
 * software is freely granted, provided that this notice
 * is preserved.
 * ====================================================
 */

/* __kernel_sin( x, y, iy)
 * kernel sin function on [-pi/4, pi/4], pi/4 ~ 0.7854
 * Input x is assumed to be bounded by ~pi/4 in magnitude.
 * Input y is the tail of x.
 * Input iy indicates whether y is 0. (if iy=0, y assume to be 0).
 *
 * Algorithm
 *  1. Since sin(-x) = -sin(x), we need only to consider positive x.
 *  2. if x < 2^-27 (hx<0x3e400000 0), return x with inexact if x!=0.
 *  3. sin(x) is approximated by a polynomial of degree 13 on
 *     [0,pi/4]
 *                   3            13
 *      sin(x) ~ x + S1*x + ... + S6*x
 *     where
 *
 *  |sin(x)         2     4     6     8     10     12  |     -58
 *  |----- - (1+S1*x +S2*x +S3*x +S4*x +S5*x  +S6*x   )| <= 2
 *  |  x                               |
 *
 *  4. sin(x+y) = sin(x) + sin'(x')*y
 *          ~ sin(x) + (1-x*x/2)*y
 *     For better accuracy, let
 *           3      2      2      2      2
 *      r = x *(S2+x *(S3+x *(S4+x *(S5+x *S6))))
 *     then                   3    2
 *      sin(x) = x + (S1*x + (x *(r-y/2)+y))
 */

#include "fdlibm.h"

#ifdef __STDC__
static const double
#else
static double
#endif
half =  5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */
S1  = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */
S2  =  8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */
S3  = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */
S4  =  2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */
S5  = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */
S6  =  1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */

#ifdef __STDC__
    double __kernel_sin(double x, double y, int iy)
#else
    double __kernel_sin(x, y, iy)
    double x,y; int iy;     /* iy=0 if y is zero */
#endif
{
    double z,r,v;
    int ix;
    ix = __HI(x)&0x7fffffff;    /* high word of x */
    if(ix<0x3e400000)           /* |x| < 2**-27 */
       {if((int)x==0) return x;}        /* generate inexact */
    z   =  x*x;
    v   =  z*x;
    r   =  S2+z*(S3+z*(S4+z*(S5+z*S6)));
    if(iy==0) return x+v*(S1+z*r);
    else      return x-((z*(half*y-v*r)-y)-v*S1);
}

A: We can use trig identities to get everything down to 0≤x≤π/4, and then need a way to approximate sin x on that interval.  On 0≤x≤2-27, we can just stick with sin x≈x (which the Taylor polynomial would also give, within the tolerance of a double).
The reason for not using a Taylor polynomial is in step 3 of the algorithm's comment.  The Taylor polynomial gives (provable) accuracy near zero at the expense of less accuracy as you get away from zero.  By the time you get to π/4, the 13th order Taylor polynomial (divided by x) differs from (sin x)/x by 3e-14.  This is far worse than fblibm's error of 2-58.  In order to get that accurate with a Taylor polynomial, you'd need to go until (π/4)n-1/n! < 2-58, which takes another 2 or 3 terms.
So why does fblibm settle for an accuracy of 2-58?  Because that's past the tolerance of a double (which only has 52 bits in its mantissa).
In your case though, you're wanting arbitrarily many bits of sin x.  To use fblibm's approach, you'd need to recalculate the coefficients whenever your desired accuracy changes.  Your best approach seems to be to stick with the Taylor polynomial at 0, since it's very easily computable, and take terms until (π/4)n-1/n! meets your desired accuracy.
njuffa had a useful idea of using identities to further restrict your domain.  For example, sin(x) = 3*sin(x/3) - 4*sin^3(x/3).  Using this would let you restrict your domain to 0≤x≤π/12.  And you could use it twice to restrict your domain to 0≤x≤π/36.  This would make it so that your Taylor expansion would have your desired accuracy much more quickly.  And instead of trying to get an arbitrarily accurate value of π for (π/4)n-1/n!, I'd recommend rounding π up to 4 and going until 1/n! meets your desired accuracy (or 3-n/n! or 9-n/n! if you've used the trig identity once or twice).


text:
Q: Junit test для метода, который возвращает объект Path может быть, кто-то направит в нужное русло.. есть такой класс, задача которого возвращать объект Path (java.nio) для дальнейшего чтения файлов
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileLoader {

    public Path loadFile(String name) throws URISyntaxException, FileNotFoundException {
        if (name == null) {
            throw new IllegalArgumentException("input can't be null");
        }
        URL url = getClass().getClassLoader().getResource(name);
        if (url == null) {
            throw new FileNotFoundException(
                    String.format("file %s was not found or access to the resource is denied", name));
        }
        return Paths.get(url.toURI());
    }
}

как мне протестировать метод loadFile в junit
я написал такой тест:
 @Test
void loadFileTest_ShouldNotThrowAnyExceptions_WhenFileExist() throws FileNotFoundException, URISyntaxException {
    FileLoader loader = new FileLoader();
    assertDoesNotThrow(() -> loader.loadFile("startTest1.log"));
}

но нужно тестировать именно результат (то есть то что возвращает метод, то есть сравнить с чем-то объект Path


text:
Q: Uso Concorrente em Aplicações Asp.net Estou começando a estudar programação em asp.net mvc (e tentando seguir o DDD) e, com isso, me surgiu uma dúvida em relação ao uso concorrente: O Asp.net já realiza esse controle para mim ou eu é quem devo controlar isso com Threads em tudo quanto é método do meu sistema (Controllers, acesso a dados, camada de application, etc)?

A: Sua pergunta nao eh muito especifica, vou tentar responder levando em conta o que voce mais citou (DDD e DAL).
Existe o controle de concorrencia a nivel de request, isto é, requests simultaneos tem sua própria memória como um sandbox, eles não dividem a maioria dos estados. Um exemplo de objeto que é dividido é sessão.
Como voce falou mais com foco em DDD e acesso a dados (imagino que seja o banco), você que tem que fazer o controle.
Suponha que voce ta usando o EntityFramework, voce pode ter requests simultaneos mexendo no mesmo dado, e isso pode dar problema.
Exemplo: um sistema de reserva, onde o usuario A pode estar com a janela de assentos aberta, pensando onde vai sentar. Enquanto isso, o usuario B tambem chega nessa tela e escolhe o assento 1. Coincidentemente, o usuario A tambem escolhe o assento 1 e dispara o request junto com usuario B, de modo que os 2 requests chegam no servidor juntos. Nesse momento, se seu codigo nao tratar concorrencia e simplesmente executar User.MakeReservation(1) para ambos usuarios, voce vai ter perda de dados.
Existem varias maneiras de lidar com isso, como a concorrencia pessimista e a otimista.
A nivel de threads e tudo mais, cada request, na maioria das vezes, vai ter o seu espaco, e dentro desse espaco voce tem que tratar concorrencias desse tipo.


text:
Q: Javascript and webshop tracking/affiliate across websites, how to do? I have a small front end to a webshop. All customers that go through my website and buy an item from the webshop I get back 5% of the amount. I need to find a way af tracking the customers i forward from my webshop to the other webshop. And then get the webshop to reply to me when the purchase has been made. In my webshop i have made a small page: collect.aspx that requests and saves the values passed in the querystring, something like this pseudo code:
string orderid = Request["orderid"];
string amount = Request["amount"];
..save to database

On the webshop i forward customers to i get to insert a javascript on the last page in the purchase flow. I have tried a lot of things but it seems that the only thing that works is to fool the browser into thinking im referring a javascript, like this:
<script type="text/javascript" src="http://domain.com/mypage.aspx?orderid=4&amount=45/>

I saw how other trackers did their bit, and this seems to be the general way of doing it. With this script however, i get all the orders, i only want to log those that belong tome, those who entered through my website.
Here is my big problem, how to do this? I added a cookie when the user opens my page, and i want to check for this cookie again when the purchase page make the callback. It weems that i cant get the cookie from the browser when it makes the "" call. This is really buggin me now.
Could anyone please tell me how this is generally done, this tracking. And what am i missing in regards to this cookie thing?
All ideas on how to do this is very welcome.

A: The cookie approach is not very good, since most browsers block 3rd party cookies. Instead i solved it by logging IP when they visit my page, and the log it again when the script calls be back. Works fine.


text:
Q: Element type is invalid: expected string (for built-in components) or a class/function (for composite components) but got: undefined I'm trying to render react-bootstrap component, but it is throwing
react-dom.development.js:28439 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
The error is thrown when this part of code is insert
                    <Form.Group controlId='image'>
                        <Form.Label>Image</Form.Label>
                        <Form.Control
                            type='text'
                            placeholder='Enter image url'
                            value={image}
                            onChange={(e) => setImage(e.target.value)}
                        ></Form.Control>
                        <Form.File
                            id="image-file"
                            label="Choose File"
                            custom
                            onChange={uploadFileHandler}>
                        </Form.File>
                        {uploading && <Loader />}
                    </Form.Group>

The error is thrown when Form.File is inserted.

A: There is no such component "Form.File":
https://github.com/react-bootstrap/react-bootstrap/blob/master/src/Form.tsx#L65
Use FormControl with type="file" for it:
<Form.Group controlId="formFile" className="mb-3">
    <Form.Label>Default file input example</Form.Label>
    <Form.Control type="file" />
</Form.Group>

https://react-bootstrap.github.io/forms/form-control/#file-input


text:
Q: Unable to create a spring starter project in STS I am trying to create a spring starter project in STS. I am selecting the gradle distribution and the Spring web dependency. When I click on finish I am getting the following error message. Error message

A: Looks like a connection issue from your end caused due probably due to unstable network. In any case you can always add dependencies and download the project from https://start.spring.io

A: Don't forget to configure your proxy in your IDE.
Please look at this tutorial


text:
Q: Make \phantomsection get me where links to chapter usually do I have such code:
\documentclass{report}

\usepackage{hyperref}

\newcommand{\specnodala}[1]{\newpage\phantomsection\addcontentsline{toc}{chapter}{#1}\section*{#1}}

\begin{document}
\tableofcontents

\specnodala{Izmantotie}
\specnodala{Ievads}

\end{document}

The links (from bookmarks or table of contents) lead me to the heading, but I want it to get me a bit higher like it does with a chapter. I tried adding \clearpage or \cleardoublepage before \phantomsection. It made linking to the second chapter nicer, but changed nothing about the first.

A: Unless you are using an ancient version of hyperref, it is usually enough to put \addcontentsline after your starred \section. hyperref then uses the anchor of the previous \section for the table of contents and the bookmarks:
\documentclass{report}

\usepackage{hyperref}
\usepackage{bookmark}% bookmarks get faster updated

\newcommand{\specnodala}[1]{%
  \newpage % or \clearpage, if previous float objects should not float into the next section
  \section*{#1}%
  \addcontentsline{toc}{chapter}{#1}%
}

\begin{document}
\tableofcontents

\specnodala{Izmantotie}
\specnodala{Ievads}

\end{document}

The destination names for the two \specnodala are section*.2 and section*.3 with the following positions (x × y) after compiling with pdflatex:
section*.2: 133.768 × 675.168
section*.3: 133.768 × 675.168

Thus the positions are the same exactly.

A: Modify your \specnodala to jump vertically to the location you want before setting \phantomsection, and then jump back. Here's an example:
\documentclass{report}
\usepackage{hyperref}% http://ctan.org/pkg/hyperref
\newcommand{\specnodala}[1]{%
  \clearpage%
  \vspace*{-1in}\phantomsection\vspace*{1in}% Hyperlink reference is set 1in above heading
  \addcontentsline{toc}{chapter}{#1}\section*{#1}}
\begin{document}
\tableofcontents

\specnodala{Izmantotie}
\specnodala{Ievads}

\end{document}


text:
Q: Change image width by screen size I have some images that I want to add to my web(the image width should be as the screen width). the problem is that there are a lot of screen which means that there is a different between each one to another screen size/resolution. I tried to set the image width to 100% but in some cases it works great and in some case it distort it. Someone can please tell me the solution to this problem?

A: Set the img CSS to width: 100%; height: auto;
img {
    width: 100%;
    hegiht: auto;
}

DEMO


text:
Q: Kali installation is without any applications I have installed kali Linux, ran in few errors upon installing. Started kali and I did not had gui, so I ran apt-get update and upgrade and I recieved gui. But now I have no applications, not even terminal, what can I do?
P.S.I have installed Kali Linux 64-bit(installer) image, version 2020.1b.

A: According to the Kali forum, no one really managed to install 2020.x propoerly. (Me neither). The majority of users there seems to revert to 2019.4.
See
https://forums.kali.org/showthread.php?47126-Kali-2020-1-anyone-actually-have-it-installing-properly

A: The problem was that I was ticking too many options on the step select applications and I accidentally selected 2 GUIs: GNOME and XFCE and it could not resolve it maybe. So for any one else out there getting error on this step just do not tick GNOME, leave it with the default kali GUI XFCE and the installation will be okay.


text:
Q: Pumping Cocoa message loop from background thread I have a Cocoa-based command line application that programmatically creates an NSWindow + NSView. It uses a nextEventMatchingMask loop to manually pump the event loop and dispatch events. This loop is called by some upper level code periodically to poll for input.
If I run everything on the main thread then this works fine in that the view receives input events correctly.
If instead I move the window creation and message loop to a separate thread then nextEventMatchingMask no longer returns any events and the view doesn't receive input.
I'm aware that only the "main" thread in a Cocoa app is supposed to handle events. This secondary thread however is the only thread that needs to talk to Cocoa, so I would like to use it as the "main" thread as far as Cocoa is concerned. Is this possible? I call NSApplicationLoad from this thread, and as far as I know this is the first Cocoa function called in the process.
If I can't specify which is the main Cocoa thread then, is there any other way to be able to create an NSWindow on a background thread and receive events for it? I can't do something like call NSApplication Run because I am not in control of the application's main loop. I just need to pull input events from the Window when the upper level code requests that I do so.

A: Maybe you need to start the runloop on the secondary thread. In your main thread, when you spawn off your secondary thread, call something like this:
[NSThread detachNewThreadSelector:@selector(launchThread)
                         toTarget:[ThreadHandler class]
                       withObject:nil];

In the ThreadHandler class, have something like:
+ (void)launchThread
{
    NSRunLoop *threadRunLoop = [NSRunLoop currentRunLoop];
    while (someThreadExitCondition && [threadRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]]);
}

This should start your thread runloop processing events. I'm not sure without testing whether this would allow you to process events for a window created in a secondary thread, but it might get you started on how to run the thread's runloop. You could even set up something like a Distributed Objects situation where you pump events from the main event loop through a NSConnection to the secondary thread (example). Hopefully this might at least give you another avenue to pursue.

A: That's not behavior I would rely on.
If you need to run your backend on a thread which is not restricted by a run loop, then run it on a secondary thread in order to run the UI from the main thread.
Alternatively, you could create another process...


text:
Q: Mysql server. Why does it speed up after a restart? I'm running a drupal 7 site locally using mamp.
Sometimes the site runs really slowly (and feels like it hits a bottle next, 5 pages will load really slowly then all of a sudden they instantly load). However, when I restart mysql it speeds right up.
Why is this?


text:
Q: Strange convergence behavior of non-linear least-squares using Lie algebra for SE(3) I am having trouble understanding an issue that I observe when running a rather simple bundle adjustment problem using non-linear least-squares with an analytical Jacobian as opposed to a finite-difference approximation of that. For a reason that I do not understand, running a toy problem (see below) that performs bundle adjustment with 3 cameras and a few beacons/points demonstrates expected convergence behavior when running without an analytical Jacobian. However, once I plug in the Jacobian into the same optimizer, the convergence deteriorates significantly, to a point where the optimum is not even reached anymore.
I checked the obvious problem of just having a faulty Jacobian, but I double-checked the implementation (and the literature) and it seems to be correct.
My question is - assuming that I don't have an implementation error - if there is an explanation for the behaviour that I am seeing. I am expecting the FD approximation to be different from the analytical Jacobian, at least at all combinations of $X$ and $Y$ on the Lie manifold where $[X,Y]=0$ does not hold and I would expect the FD approximation to be performing worse for this reason, but the opposite seems to be the case.
I tried to squeeze the problem setup into a single MatLab toy-problem that shows the issue, sorry if this got a little lengthy and quite condensed in the style. Any input is appreciated as I am scratching my head over that for quite some time now.
% Setup example with 3 cameras and a few beacons to reconstruct
% cameras as 3x6 matrix (3 cameras, 6-parameter axis-angle / translation)
cameras = [0.1    0  0.2  0  0   2  ;
           0.1  0.3  0.1  0  0   1  ;
             0  0.2  0.4  0  0 1.5];
% beacons as 8x3 matrix, 3d points with row-wise stacking
beacons = [   0.4,  -0.2,   0.1  ;
             -0.1,   0.1,  0.15  ;
             -0.3,   0.2,  -0.1  ;
              0.3,   0.4,   0.1  ;
             0.25,   0.1,  -0.2  ;
              0.4,   0.3,   0.2  ;
             0.24, -0.13,   0.2  ;
              0.1,  -0.3, -0.12 ];
% compute ideal measurements (perspective projection)
measurements = zeros(size(cameras,1)*size(beacons,1),2);
mnum=1;
for c=1:size(cameras, 1)
    M = se3exp(cameras(c,:));
    for b=1:size(beacons, 1)
        x = M*[beacons(b,:),1]';
        measurements(mnum, :) = [x(1)/x(3), x(2)/x(3)];
        mnum = mnum + 1;
    end
end
%% Use finite-difference approximation to the Jacobian for minimization
% initialize reconstructed cameras and beacons
rcameras = [0.05    0 0.15 0 0 1 ;
            0.05 0.05  0.2 0 0 1 ;
               0    0  0.3 0 0 1 ];
rbeacons = zeros(size(beacons));
% run unconstrained non-linear least squares and read back results
options=optimoptions('lsqnonlin','Display','iter','Algorithm','levenberg-marquardt');
func = @(x) residual(reshape(x(1:size(rcameras,1)*6),[6,size(rcameras,1)])', reshape(x(size(rcameras,1)*6+1:end),[3,size(rbeacons,1)])', measurements);
xinit = [reshape(rcameras',[size(rcameras,1)*6,1]) ; reshape(rbeacons',[size(rbeacons,1)*3,1])];
xfinal = lsqnonlin(func,xinit,[],[],options);
% read back results and align with 1st reference camera
rcameras = reshape(xfinal(1:size(rcameras,1)*6),[6,size(rcameras,1)])';
rbeacons = reshape(xfinal(size(rcameras,1)*6+1:end),[3,size(rbeacons,1)])';
[rcameras, rbeacons] = align(rcameras, rbeacons, cameras, beacons);
cameras
rcameras
%% Use analytical Jacobian for minimization
% initialize reconstructed cameras and beacons
rcameras = [0.05    0 0.15 0 0 1 ;
            0.05 0.05  0.2 0 0 1 ;
               0    0  0.3 0 0 1 ];
rbeacons = zeros(size(beacons));
% run unconstrained non-linear least squares and read back results
joptions=optimoptions('lsqnonlin','Display','iter','Algorithm','levenberg-marquardt','SpecifyObjectiveGradient',true);
jfunc = @(x) adapter(reshape(x(1:size(rcameras,1)*6),[6,size(rcameras,1)])', reshape(x(size(rcameras,1)*6+1:end),[3,size(rbeacons,1)])', measurements);
xinit = [reshape(rcameras',[size(rcameras,1)*6,1]) ; reshape(rbeacons',[size(rbeacons,1)*3,1])];
xfinal = lsqnonlin(jfunc,xinit,[],[],joptions);
% read back results and align with 1st reference camera
rcameras = reshape(xfinal(1:size(rcameras,1)*6),[6,size(rcameras,1)])';
rbeacons = reshape(xfinal(size(rcameras,1)*6+1:end),[3,size(rbeacons,1)])';
[rcameras,rbeacons] = align(rcameras, rbeacons, cameras, beacons);
cameras
rcameras
%% Function to align cameras/beacons to the reference for comparison
function [cams, beacs] = align(cameras, beacons, refcameras, refbeacons)
    refdist = norm(refbeacons(1,:)-refbeacons(2,:));
    recdist = norm(beacons(1,:)-beacons(2,:));
    scale = refdist/recdist;
    beacs = beacons*scale;
    cams = cameras;
    for c=1:size(cameras,1)
        cams(c,4:6) = cams(c,4:6)*scale;
    end
    Tref = se3exp(refcameras(1,:));
    A = inv(se3exp(cams(1,:)))*Tref;
    for c=1:size(cams,1)
        cams(c,:) = se3log(se3exp(cams(c,:))*A);
    end
    Ai = inv(A);
    for b=1:size(beacs,1)
        t = Ai*[beacs(b,:),1]';
        beacs(b,:) = t(1:3)';
    end
end
%% Compute residual of bundle adjustment problem
function f = residual(cameras, beacons, measurements)
    mnum=1;
    f = zeros(size(measurements, 1)*2,1);
    for c=1:size(cameras,1)
        M = se3exp(cameras(c,:));
        for b=1:size(beacons,1)
            x = M * [beacons(b,:),1]';
            d = (measurements(mnum,:) - [x(1)/x(3), x(2)/x(3)])';
            i = (mnum-1)*2+1;
            f(i:i+1) = d;
            mnum = mnum + 1;
        end
    end
end
%% Compute Jacobian via finite-differencing (not used)
function J = fdJacobian(cameras, beacons, measurements)
    epsilon = 1e-8;
    r = residual(cameras, beacons, measurements);
    J = [];
    for c=1:size(cameras, 1)
        for i=1:6
            x = cameras;
            x(c,i) = x(c,i) + epsilon;
            fwd = residual(x, beacons, measurements);
            J = [J (fwd-r)./epsilon];
        end
    end
    for b=1:size(beacons,1)
        for i=1:3
            x = beacons;
            x(b,i) = x(b,i) + epsilon;
            fwd = residual(cameras, x, measurements);
            J = [J (fwd-r)./epsilon];
        end
    end
end
%% Compute Jacobian
function J = lieJacobian(cameras, beacons, measurements)
    J = zeros(size(measurements,1)*2, size(cameras,1)*6+size(beacons,1)*3);
    mnum = 1;
    for c = 1:size(cameras, 1)
        M = se3exp(cameras(c,:));
        columnc = (c-1)*6+1;
        for b = 1:size(beacons, 1)
            columnb = (b-1)*3+size(cameras,1)*6+1;
            r = (mnum-1)*2+1;
            x = M * [beacons(b,:),1]';
            xo = beacons(b,:);
            sx = [   0, -xo(3),  xo(2) ;
                  xo(3),     0, -xo(1) ;
                 -xo(2), xo(1),     0 ];
            dpi = [ 1/x(3)      0  -x(1)/(x(3)^2)  ;
                         0  1/x(3) -x(2)/(x(3)^2)  ];
            % Derivatives of rigid motion action chained with projection
            J(r:r+1,columnc:columnc+5) = dpi*[M(1:3,1:3)*sx, -M(1:3,1:3)];
            J(r:r+1,columnb:columnb+2) = -dpi*M(1:3,1:3);
            mnum = mnum+1;
        end
    end
end
%% Adapter function for lsqnonlin that returns residual and Jacobian
function [f, J] = adapter(cameras, beacons, measurements)
    f = residual(cameras, beacons, measurements);
    J = lieJacobian(cameras, beacons, measurements);
end
%% Exponential map from se(3) to SE(3)
function M = se3exp(posevec)
    angle = norm(posevec(1:3));
    skew = [          0 , -posevec(3),  posevec(2) ;
             posevec(3) ,           0, -posevec(1) ;
            -posevec(2) ,  posevec(1),          0 ];
    if abs(angle) < 1e-10
        R = eye(3);
        Jl = eye(3);
    else
        R =  eye(3)+(sin(angle)/angle)*skew + ((1-cos(angle))/(angle^2)) * skew*skew;
        Jl = eye(3)+((1-cos(angle))/(angle^2))*skew + ((angle-sin(angle))/(angle^3)) * skew*skew;
    end
    M = [ R , Jl*posevec(4:6)' ;
          0, 0, 0, 1    ];
end
%% Logarithm map from SE(3) to se(3)
function lie = se3log(M)
   trM = trace(M(1:3,1:3));
   if abs(trM - 3) < 1e-7
       angle = 0;
       rs = zeros(3,3);
       Jr = eye(3);
       theta = [0, 0, 0];
   elseif abs(trM + 1) < 1e-7
       angle = pi;
       [me, mi] = max(diag(M(1:3,1:3)));
       I = eye(3,3);
       col = M(1:3,mi) + I(:,mi);
       theta = angle * (col / sqrt(2*(1+me)))';
       rs = skew(theta);
       Jr = eye(3)-0.5*rs+(1/angle^2)*(1-(sin(angle)/angle)/(2*((1-cos(angle))/angle^2)))*rs*rs;
   else
       angle = acos((trace(M(1:3,1:3))-1)/2);
       rs = angle/(2*sin(angle)) * (M(1:3,1:3)-M(1:3,1:3)');
       Jr = eye(3)-0.5*rs+(1/angle^2)*(1-(sin(angle)/angle)/(2*((1-cos(angle))/angle^2)))*rs*rs;
       theta=[rs(3,2),rs(1,3),rs(2,1)];
   end
   t = Jr*M(1:3,4);
   lie=[theta,t(1),t(2),t(3)]';
end

Edit: there was an actual bug in the Jacobian that I fixed, the convergence behaviour is still sub-par to the FD approximation, but reaches the correct minimum.

A: The way the optimization problem is set up, requires the use of the left Jacobian of the Lie group. AFAIK using the derivative of the group action is not the same and the gradient directions are not the same (cf this document on page 248).
What is required here, is in the aforementioned text on page 251 (eq. 7.187). I took the liberty of adjusting the MatLab example, which is pasted below and exposes the same convergence behaviour for the finite-differencing and the analytical Jacobian.
The document linked above also has a closed form representation of the left Jacobian, which I was too lazy too implement (see page 235).
%% Setup example with 3 cameras and a few beacons to reconstruct
% cameras as 3x6 matrix (3 cameras, 6-parameter axis-angle / translation)
cameras = [0.1    0  0.2  0  0   2  ;
           0.1  0.3  0.1  0  0   1  ;
             0  0.2  0.4  0  0 1.5];
% beacons as 8x3 matrix, 3d points with row-wise stacking
beacons = [   0.4,  -0.2,   0.1  ;
             -0.1,   0.1,  0.15  ;
             -0.3,   0.2,  -0.1  ;
              0.3,   0.4,   0.1  ;
             0.25,   0.1,  -0.2  ;
              0.4,   0.3,   0.2  ;
             0.24, -0.13,   0.2  ;
              0.1,  -0.3, -0.12 ];
% compute ideal measurements (perspective projection)
measurements = zeros(size(cameras,1)*size(beacons,1),2);
mnum=1;
for c=1:size(cameras, 1)
    M = se3exp(cameras(c,:));
    for b=1:size(beacons, 1)
        x = M*[beacons(b,:),1]';
        measurements(mnum, :) = [x(1)/x(3), x(2)/x(3)];
        mnum = mnum + 1;
    end
end
%% Use finite-difference approximation to the Jacobian for minimization
% initialize reconstructed cameras and beacons
rcameras = [0.05    0 0.15 0 0 1 ;
            0.05 0.05  0.2 0 0 1 ;
               0    0  0.3 0 0 1 ];
rbeacons = zeros(size(beacons));
% run unconstrained non-linear least squares and read back results
options=optimoptions('lsqnonlin','Display','iter','Algorithm','levenberg-marquardt');
func = @(x) residual(reshape(x(1:size(rcameras,1)*6),[6,size(rcameras,1)])', reshape(x(size(rcameras,1)*6+1:end),[3,size(rbeacons,1)])', measurements);
xinit = [reshape(rcameras',[size(rcameras,1)*6,1]) ; reshape(rbeacons',[size(rbeacons,1)*3,1])];
xfinal = lsqnonlin(func,xinit,[],[],options);
% read back results and align with 1st reference camera
rcameras = reshape(xfinal(1:size(rcameras,1)*6),[6,size(rcameras,1)])';
rbeacons = reshape(xfinal(size(rcameras,1)*6+1:end),[3,size(rbeacons,1)])';
[rcameras, rbeacons] = align(rcameras, rbeacons, cameras, beacons);
cameras
rcameras
%% Use analytical Jacobian for minimization
% initialize reconstructed cameras and beacons
rcameras = [0.05    0 0.15 0 0 1 ;
            0.05 0.05  0.2 0 0 1 ;
               0    0  0.3 0 0 1 ];
rbeacons = zeros(size(beacons));
% run unconstrained non-linear least squares and read back results
joptions=optimoptions('lsqnonlin','Display','iter','Algorithm','levenberg-marquardt','SpecifyObjectiveGradient',true);
jfunc = @(x) adapter(reshape(x(1:size(rcameras,1)*6),[6,size(rcameras,1)])', reshape(x(size(rcameras,1)*6+1:end),[3,size(rbeacons,1)])', measurements);
xinit = [reshape(rcameras',[size(rcameras,1)*6,1]) ; reshape(rbeacons',[size(rbeacons,1)*3,1])];
xfinal = lsqnonlin(jfunc,xinit,[],[],joptions);
% read back results and align with 1st reference camera
rcameras = reshape(xfinal(1:size(rcameras,1)*6),[6,size(rcameras,1)])';
rbeacons = reshape(xfinal(size(rcameras,1)*6+1:end),[3,size(rbeacons,1)])';
[rcameras,rbeacons] = align(rcameras, rbeacons, cameras, beacons);
cameras
rcameras
%% Function to align cameras/beacons to the reference for comparison
function [cams, beacs] = align(cameras, beacons, refcameras, refbeacons)
    refdist = norm(refbeacons(1,:)-refbeacons(2,:));
    recdist = norm(beacons(1,:)-beacons(2,:));
    scale = refdist/recdist;
    beacs = beacons*scale;
    cams = cameras;
    for c=1:size(cameras,1)
        cams(c,4:6) = cams(c,4:6)*scale;
    end
    Tref = se3exp(refcameras(1,:));
    A = inv(se3exp(cams(1,:)))*Tref;
    for c=1:size(cams,1)
        cams(c,:) = se3log(se3exp(cams(c,:))*A);
    end
    Ai = inv(A);
    for b=1:size(beacs,1)
        t = Ai*[beacs(b,:),1]';
        beacs(b,:) = t(1:3)';
    end
end
%% Compute residual of bundle adjustment problem
function f = residual(cameras, beacons, measurements)
    mnum=1;
    f = zeros(size(measurements, 1)*2,1);
    for c=1:size(cameras,1)
        M = se3exp(cameras(c,:));
        for b=1:size(beacons,1)
            x = M * [beacons(b,:),1]';
            d = (measurements(mnum,:) - [x(1)/x(3), x(2)/x(3)])';
            i = (mnum-1)*2+1;
            f(i:i+1) = d;
            mnum = mnum + 1;
        end
    end
end
%% Compute Jacobian
function J = lieJacobian(cameras, beacons, measurements)
    J = zeros(size(measurements,1)*2, size(cameras,1)*6+size(beacons,1)*3);
    mnum = 1;
    for c = 1:size(cameras, 1)
        M = se3exp(cameras(c,:));
        Jl = leftJacobian(cameras(c,:));
        columnc = (c-1)*6+1;
        for b = 1:size(beacons, 1)
            columnb = (b-1)*3+size(cameras,1)*6+1;
            r = (mnum-1)*2+1;
            x = M * [beacons(b,:),1]';
            sx = skew(x);
            dpi = [ 1/x(3)      0  -x(1)/(x(3)^2)  ;
                         0  1/x(3) -x(2)/(x(3)^2)  ];
            J(r:r+1,columnc:columnc+5) = -dpi*[-sx eye(3)]*Jl;
            J(r:r+1,columnb:columnb+2) = -dpi*M(1:3,1:3);
            mnum = mnum+1;
        end
    end
end
%% Adapter function for lsqnonlin that returns residual and Jacobian
function [f, J] = adapter(cameras, beacons, measurements)
    f = residual(cameras, beacons, measurements);
    J = lieJacobian(cameras, beacons, measurements);
end
%% Exponential map from se(3) to SE(3)
function M = se3exp(posevec)
    angle = norm(posevec(1:3));
    s = skew(posevec);
    if abs(angle) < 1e-10
        R = eye(3);
        Jl = eye(3);
    else
        R =  eye(3)+(sin(angle)/angle)*s + ((1-cos(angle))/(angle^2)) * s*s;
        Jl = eye(3)+((1-cos(angle))/(angle^2))*s + ((angle-sin(angle))/(angle^3)) * s*s;
    end
    M = [ R , Jl*posevec(4:6)' ;
          0, 0, 0, 1    ];
end
%% Logarithm map from SE(3) to se(3)
function lie = se3log(M)
   trM = trace(M(1:3,1:3));
   if abs(trM - 3) < 1e-7
       Jr = eye(3);
       theta = [0, 0, 0];
   elseif abs(trM + 1) < 1e-7
       angle = pi;
       [me, mi] = max(diag(M(1:3,1:3)));
       I = eye(3,3);
       col = M(1:3,mi) + I(:,mi);
       theta = angle * (col / sqrt(2*(1+me)))';
       rs = skew(theta);
       Jr = eye(3)-0.5*rs+(1/angle^2)*(1-(sin(angle)/angle)/(2*((1-cos(angle))/angle^2)))*rs*rs;
   else
       angle = acos((trace(M(1:3,1:3))-1)/2);
       rs = angle/(2*sin(angle)) * (M(1:3,1:3)-M(1:3,1:3)');
       Jr = eye(3)-0.5*rs+(1/angle^2)*(1-(sin(angle)/angle)/(2*((1-cos(angle))/angle^2)))*rs*rs;
       theta=[rs(3,2),rs(1,3),rs(2,1)];
   end
   t = Jr*M(1:3,4);
   lie=[theta,t(1),t(2),t(3)]';
end
%% Approximate left Jacobian matrix at provided pose with power series expansion
function Jl = leftJacobian(pose)
    se3elem = [skew(pose(1:3)), zeros(3,3) ;
               skew(pose(4:6)), skew(pose(1:3))];
    M = se3elem;
    Jl = eye(6);
    fac = 1;
    for i=1:10
        fac = fac*(i+1);
        Jl = Jl + (1/fac)*M;
        M = M * se3elem;
    end
end
%% Calculate skew-symmetric 3x3 matrix from 3-vector
function s = skew(vec)
    s = [ 0 -vec(3) vec(2) ; vec(3) 0 -vec(1) ; -vec(2) vec(1) 0];
end


text:
Q: How to use react-app-rewired with TypeScript? The following StackOverflow answer told me how to use react-app-rewired to import JavaScript files from outside the src folder, without ejecting the app:
https://stackoverflow.com/a/55298684/377011
However, when using this with a Typescript file outside of the src folder (i.e. import * from '../../myfile.ts'), I get the following error:
Module not found: Can't resolve 'ts-loader' in '...\myapp'

So I installed ts-loader (yarn add ts-loader), but now I'm getting
Error: TypeScript emitted no output for ...\myapp\src\index.tsx

noEmit is set to true in my tsconfig.json.
Any idea?
Edit: This is my tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}


text:
Q: In C++, how do I write a 3-dimensional array? Thanks for looking!
Background
I am building a quadcopter and am placing on each of it's four arms a strip of RGB LEDs which are individually addressable.  There are 6 LEDs per strip.
Further, there are six steps in a sequence to how I wish to toggle the lights so all six lights on the strip don't necessarily toggle at once.
In pseudo code, here is what I am trying to create:
someArray = A group of 4 LED strips {Strip 1: [
    Step 1: [ LED 1: [R, G, B], . . ., LED 6: [R, G, B] ],
    . . .,
    Step 6: [ LED 1: [R, G, B], . . ., LED 6: [R, G, B] ],
],
. . .,
Strip 4: [
    Step 1: [ LED 1: [R, G, B], . . ., LED 6: [R, G, B] ],
    . . .,
    Step 6: [ LED 1: [R, G, B], . . ., LED 6: [R, G, B] ],
]};

I am using an Arduino to drive the lights, and the code is in C++ with which I am not very familiar.
What I have tried so far:
Here is the code I have tried so far, but when I compile in the Arduino IDE, I get an error that says "Braces around scalar initializer for type 'int'".
int gpsHoldArr[4][6][6] = {
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
};

What am I missing here?
Intended Usage
Intended use would be something like this:
//iterate each of the 6 sets of RGB values and assign them to the correct (sequential) LED
void toggleLights(int lights[]){
  for(int i = 0; i <= 6; ++i)
  {
    set_color_led(i, lights[i][0], lights[i][1], lights[i][2]);
  }
}

toggleLights(gpsHoldArr[1][0]);//Get the first step of the second arm.

Thanks in advance.

A: You wrote the initialization for a 4d array as RGB has 3 components. You probably want to do something like this:
struct rgb {
  int r, g, b;
};

rgb gpsHoldArr[4][6][6] = {
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
  {
    {{255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {0,0,0}},
    {{255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}, {255,0,0}}
},
};

Or, change your declaration to this:
int gpsHoldArr[4][6][6][3]

A: Use a byte and cut the memory usage in half
typedef struct rgb_t {
  byte r;
  byte g;
  byte b;
};

rgb_t gpsHoldArr[4][6][6] = {


text:
Q: Angular 5 Form validation for optional fields Ok, so I am very new to Angular(I am using Angular 5).  I am trying implement form validation
such that I have two input fields where:
    -   A user must use one or both fields before submitting the form.
    -   Both fields must adhere to the pattern \w{10}
    -   until validation criteria has been met, the submit button must remain disabled
    -   There needs to be a message underneath each field describing malformed input as
        happens.
I have managed to get something working with regard to the pattern matching and submit button disabled....but I am having a hard time figuring out to provide functionality such that
a user opting to only fill out one field and having the submit button enabled...I can only seem to get it to work when both fields are being used.

Angular  Template Form validation

  <form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" novalidate >

Is "userlogin" valid? {{userlogin.valid}}

    <input type = "text" name = "emailId" placeholder = "emailId" ngModel required   pattern = "\w+\@\w+\.\w+" />

    <input type = "password" name = "passwd" placeholder = "passwd" ngModel   pattern ="\w{10}"/>

    <input type = "submit"  [disabled] = "!userlogin.valid"  value = "submit">
 </form>

import { Component, OnInit ,ANALYZE_FOR_ENTRY_COMPONENTS } from '@angular/core';
import { FormGroup, FormControl,FormArray,NgForm, Validators} from '@angular/forms';
import {Report} from './report.model';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

      constructor() {}

      ngOnInit() {
        this.report = new Report() ;
        this.isDisabled = false ;
      }

     onClickSubmit(data) {
        let email = data.emailId ;
        let passwd = data.passwd ;
        email = email.trim() ;
        passwd = passwd.trim() ;
        console.log(email);
        this.emailFlag = this.regexpEmail.test(email);
        // alert('Entered Email id : ' + this.emailFlag);
        alert('Email -> ' + email + ': ' + 'passwd :' + passwd );

      }

}

Any help would be greatly appreciated !!!  Thanks!!!!

A: Try below given code:
Template:

Angular  Template Form validation

  <form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" novalidate >

Is "userlogin" valid? {{userlogin.valid}}

    <input type = "text" name = "emailId" placeholder = "emailId" [(ngModel)]="emailid"  pattern = "\w+\@\w+\.\w+" />

    <input type = "password" name = "passwd" placeholder = "passwd" [(ngModel)]="pwd"  pattern ="\w{10}"/>

    <input type = "submit"  [disabled] = "(!emailid && !pwd) || !userlogin.valid"  value = "submit">
 </form>

Component-
import { Component, OnInit ,ANALYZE_FOR_ENTRY_COMPONENTS } from '@angular/core';
import { FormGroup, FormControl,FormArray,NgForm, Validators} from '@angular/forms';
import {Report} from './report.model';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  emailid;
  pwd;
      constructor() {}

      ngOnInit() {
        this.report = new Report() ;
        this.isDisabled = false ;
      }

     onClickSubmit(data) {
        let email = data.emailId ;
        let passwd = data.passwd ;
        email = email.trim() ;
        passwd = passwd.trim() ;
        console.log(email);
        this.emailFlag = this.regexpEmail.test(email);
        // alert('Entered Email id : ' + this.emailFlag);
        alert('Email -> ' + email + ': ' + 'passwd :' + passwd );

      }

}


text:
Q: Meteor.js event handler: DB & CSS issue I have the following event handler in a Meteor app:
Template.messageItem.events({
'click .message-block #faveMsg': function (e) {
    console.log($(e.target));
    if (_.contains(this.favoritedBy, Meteor.userId())) {
        Messages.update({_id: this._id}, {$pull: {favoritedBy: Meteor.userId()} });
        $(e.target).removeClass('selected');
    } else{
        Messages.update({_id: this._id}, {$addToSet: {favoritedBy: Meteor.userId() } });
        $(e.target).addClass('selected');
    };
    console.log(this.favoritedBy);
    // $(e.target).toggleClass('selected');
}
});

The CSS update works independently. As soon as I bring in db logic the CSS change stops working.
I previously had a single toggleClass method (commented out above) which did the job but that no longer works if I reinstate it while commenting out the add/remove methods currently being used... ie something broke after I added the DB logic.
I'm guessing this is a dumb JS syntax issue as I'm a js newb... any ideas?

A: I'm nearly certain this is happening:

*

*You update a document.

*You change the css on the rendered version of that document.

*The server receives the update (1), and sends a new version of the document to the client.

*The document (or possibly more things) is rendered again on your page.

The trouble is that (4) invalidates any changes that were made in (2) because the DOM element is removed from the page and a new version is added back. The best way to deal with this in the current version of meteor is to use a session variable which stores the id of the message. You can then use that session variable to render the right version of the css. So instead of your $(e.target)... you could do:
Session.set('selectedMessage', this._id);

Then you can add a template helper like this:
Template.messageItem.helpers({
  selected: function() {
    return Session.equals('selectedMessage', this._id);
  }
});

Finally, your template code could use that helper to display the right class:

{{message.text}}

A: Building on David's observation above the DB update was causing my template to re-render (I should have realized as that is standard behavior in Meteor...). So the cleanest solution I could find was to wrap the relevant HTML element in a constant block:

  {{#constant}}

  {{/constant}}
    Received from {{sentBy}} {{timeago sentTime}}.

  {{#if msgTypeText}}

{{msgText}}

  ...

Subsequently when my JS function updates the DB & adds the 'selected' class to the icon element Meteor doesn't re-render it and it preserves my selected-element CSS

A: Another way to do it is take out the CSS class insert from the event handler and put conditional logic in the html/handlebars code:

    {{#if favoritedByMe}}

    {{else}}

    {{/if}}
    Received from {{sentBy}} {{timeago sentTime}}.

This reactively updates the element and also works well. The downside of this approach is that it simply re-renders the html icon element when it is favorited rather than just adding a class, so you lose CSS transitions. However you avoid the constant block which could cause issues in some use cases


text:
Q: Doctrine - Remove of Entity with unidirection many-to-many relation fails I have two entities. Configuration and Role with a unidirection many-to-many relation in Configuration:
/**
 * @var Role[]
 *
 * @ORM\ManyToMany(targetEntity="App\Entity\Role")
 */
private $roles;

Creation and update works as expected, but a
$this->entityManager->remove($configuration);
$this->entityManager->flush();

wont work (foreign key violation), because Doctrine will not delete the relation-dataset
It only works with a manual removal of the relation AND an additional flush before the removal of the entity.
foreach ($issueTypeConfiguration->getRoles() as $role) {
    $issueTypeConfiguration->removeRole($role);
}
// It only works with this additional flush
$this->entityManager->flush();
$this->entityManager->remove($issueTypeConfiguration);
$this->entityManager->flush();

I expect Doctrine to delete the related datasets

A: Due to the manual creation of the many-to-many-table (Migration is not possible), I forgot to set the foreign key to DELETE CASCADE
I expected Doctrine to handle the deletion