text:
Q: MahApps Metro NumericUpDown problems After using MahApp Metro formy project in WPF I encountered a problem I can't solve. the framework works fine except when I am using the NumericUpDown control.
I can see this control onto my UserControl while I'am working on it. But at the compilation the code then becomes :
The tag 'NumericUpDown' does not exist in XML namespace "http://metro.mahapps.com/winfx/xaml/controls". Line 75 Position 26.
With my XAML code it could perhaps help :
<UserControl x:Class="FullTest.Tabs.DataGridStrategie" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
         xmlns:convertors="clr-namespace:FullTest.ModelView.Convertors"
         xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
         xmlns:sys="clr-namespace:System;assembly=mscorlib"
         xmlns:utils="clr-namespace:FullTest.UtilityClasses"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
    <ResourceDictionary>
        <BooleanToVisibilityConverter x:Key="BoolToVis"/>
        <ObjectDataProvider MethodName="GetType"
        ObjectType="{x:Type sys:Type}" x:Key="colorsTypeOdp">
            <ObjectDataProvider.MethodParameters>
                <sys:String>System.Windows.Media.Colors, PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</sys:String>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
        <ObjectDataProvider ObjectInstance="{StaticResource colorsTypeOdp}"  MethodName="GetProperties" x:Key="colorPropertiesOdp">
        </ObjectDataProvider>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/emerald.xaml" />
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</UserControl.Resources>
<DataGrid ItemsSource="{Binding Path=Str...}"
              Grid.Row="0"
              AutoGenerateColumns="False" Margin="0,0,-172,0" x:Name="MainGrid">

    <DataGrid.Columns>

        <DataGridTemplateColumn Header="Colors ..." Width="Auto">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox Name="superCombo" ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" SelectedItem="{Binding BrushColor, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
                        <ComboBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Width="20" Height="20" Margin="5" Background="{Binding Name}"/>
                                    <TextBlock  Text="{Binding Name}"/>
                                </StackPanel>
                            </DataTemplate>
                        </ComboBox.ItemTemplate>
                    </ComboBox>

                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>

        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Name of ..." x:Name="Str.." Width="150">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Name="itemNameTextBox" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Typ o....">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox Name="TypeStrat" ItemsSource="{Binding Path=Typ....}" SelectedIndex="{Binding Index, UpdateSourceTrigger=PropertyChanged, Mode= TwoWay}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

      <!--Here Appears the problem due to the controller-->
        <DataGridTemplateColumn Header="">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <controls:NumericUpDown Grid.Row="0"
                            Grid.Column="1"
                            Height="23"
                            Margin="5,5,5,5"
                            Interval="1"
                            StringFormat="{}{0:###0}"/>

                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

    </DataGrid.Columns>
</DataGrid>

I could provide more information if it can be useful.


text:
Q: Cloud Composer 2 unable to send SMTP emails I am struggling in sending a email from cloud-composer 2 environment(composer-2.0.11-airflow-2.2.3) via smtp.gmail.com.
Please find my configs below :
Note I tried using smtp_password_cmd and smtp_password_secret but both give the same error.
I have also setup a network connectivity test which shows smtp.gmail.com is reachable from my VPC
Error Msg:

File "/opt/python3.8/lib/python3.8/smtplib.py", line 310, in _get_socket
return socket.create_connection((host, port), timeout,
File "/opt/python3.8/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/opt/python3.8/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
OSError: [Errno 99] Cannot assign requested address

Any help/pointers would be appreciated.
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to cache phpexcel with symfony2 phpexcel bundle Is there any way to speed up my function to work with larger excel file?
There is my code:
$excelService = $this->get('xls.service_xls5');

$excelObj = $this->get('xls.load_xls5')->setReadDataOnly(true)->load('../web/bundles/static/pliki/'.$name);

$sheet = $excelObj->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();

for ($row = 1; $row <= $highestRow; $row++){

    $nazwaKlienta = $sheet->getCellByColumnAndRow(0,$row)->getValue();
    $ulica = $sheet->getCellByColumnAndRow(1,$row)->getValue();
    $miasto = $sheet->getCellByColumnAndRow(2,$row)->getValue();
    $kod = $sheet->getCellByColumnAndRow(3,$row)->getValue();
    $notatka = $sheet->getCellByColumnAndRow(4,$row)->getValue();
    $kolor = $sheet->getCellByColumnAndRow(5,$row)->getValue();

    if ($row == $highestRow) {
        $excelObj->disconnectWorksheets();
        unset($excelObj);
    }

    $em = $this->getDoctrine()->getManager();
    $klient = new Klient();
    $klient->setNazwa($nazwaKlienta);
    (...)

    $em->persist($klient);
    $em->flush();
    $klientId = $klient->getId();
    $punkt = new Punkty();
    $punkt->setIdKlienta($klient);
    $em->persist($punkt);
    $em->flush();
}

This code open an existing excel file and read all data and write it to database. It works fine with data amount about 150-200 but i need to work with data about 2000 rows. How can i cache it with phpexcelBundle or maybe there is another way?

A: A cache mechanism could help you:
Is there $name into the db? if yes don't do the job just take the value from the db.
You could also use APC setting an expiration time of the given $name.
please have a look to:
rationally-boost-your-symfony2-application-with-caching-tips-and-monitoring
slide 27.


text:
Q: Remove .php extension from my symfony project I have created two applications in my symfony project, but my second application i can only access using .php extension.
example http://192.168.1.3:9000/backend.php
I want to remove the .php extension from the backend project, is possible?
Help is highly appreciated.
Thanks,

A: You can rename your backend.php file to just backend without extension, then use following in your .htaccess config:
<Files backend>
    ForceType application/x-httpd-php
</Files>

(One could also use DefaultType to make that possible for all php scripts, but this would cause extra work with unsetting it again in subfolders for security reasons.)

A: So you want to remove the extension from the file on the server [backend file on server]? or the url [http://192.168.1.3:9000/backend]?
Both can be done via htaccesss


text:
Q: Before you develop a web app, how much of a spec do you need? If you were to accept a role as a full time web app developer responsible for creating a new application from scratch, how much of a defined specification and design would need and/or expect to start development?
What tools/software is even used for this (for web apps built with something like RoR)? I would expect a mockup/wireframe to be required, but what else is done in the design stage? What is the best method or process to convey the functionality of the application so that developers know what to translate into code.
I'm interested to hear from web app developers who have thought: "If I only had <this>, I could develop this so much quicker/easier/cleaner", or "I have no idea what this customer wants unless they document it in <thing>."
I'm not trying to start a philosophical debate, I am curious from the developers' perspective what is the "right" way to design web apps from scratch. There is probably a book somewhere that someone can tell me to RTFM, but I've only been able to find resources on learning actual coding and development, not the design phase.

A: It depends.
My favorite project I did started off with the specification of "Make the knowledge base browse-able."  Thats it.  One sentence.  I worked with the knowledge manager (who was responsible for the data and structure of the knowledge base), and a user interface guy.  And we did it.  Turned out to be a very successful project in part because the goal donor (same as gold owner in this case) didn't have any preconceptions of how the final thing worked - just that it worked and trusted us enough to let us make it.
On the other hand, there have been projects with many integration points between different teams where there were dozens of xsds floating around that specified every detail of the interface.  The business came to us with mock ups of what they wanted and all the rules for how each field behaved and what was sent to the other systems.  This worked too - and it was necessary.  If any one team went off and did their own thing, it would have fallen like a house of cards once we tried to put it together.  There were reams of paper that represented various versions of the specification.
Recently, one of the companies that subcontracts work to my current employer commented that they are very happy with us because they give us not much in the way of specifications and we do what they were thinking (our project managers must be telepathic).
There is no right answer, it depends completely on what the expectations of the client (be it another business uint in the company you work for, or an external client).  The more they expect things and the less they trust you do to the right thing and accept what you give them, the more the work will need to specified.
One set of the approaches that was taken up to try to address this are the iterative methodologies.  The idea with these is you build something in a short time period and then ask "is this what you were thinking?" Each iteration you add functionality or change it as the client asks.  The most well known of these approaches is agile (which itself encompasses a range of methodologies).
As to books?  There are dozens of them.  Seriously, dozens.  Maybe dozens of dozens if not more (there's no one book that we can tell you will solve that problem - just go into the project management section of a library or bookstore and start thumbing through them).


text:
Q: GUI to set numeric ranges in Delphi Once in a while I need a GUI to set numeric ranges, but so far I've never really found any component that does it nicely.
I've attempted the following:

*

*2 TTrackbars: 1 for min, 1 for max

*2 TTackbars: 1 for min, 1 for range

*2 TSpinEdit controls to type the numbers manually

*
1 TTrackbar control, with a little button to switch between min-mode and max-mode. In min-mode I set selStart and in max-mode I set selEnd (with ShowSelRange set to true).
Most options take more screen estate than I'd like, and they are not intuitive.
Ideally, I'd like something that works like the scrollbar in Sony ACID. You can click and drag 3 different points to the min, max, or both:

Is there any Free component available to set a range, or can something similar be done by using out-of-the-box VCL components creatively?

Update
I've modified TMkRangeSlider to suit my needs. It works like a charm now. I've sent the modified component and demo to the original author.

A: How about something like Range Slider, by Michael Kochiashvili. It is freeware with source, written for Delphi 5 and comes with a demo:

It won't move min and max simultaneously, but since you've got the source, you could probably add that functionality if you really need it.

A: Using a standard TScrollBox, it is technically possible to do some manual fiddling of its PageSize and Position properties while dragging its thumb around (ScrollCode=scTrack in its OnScroll event) to simulate the kind of UI that you showed in the ACID screenshot.  The problem is that 1) you can't owner-draw a TScrollBar to add the drag lines, and 2) there is no direct way to determine which portion of the thumb the user is holding the mouse down on (the ends versus the middle).  Unless you can come up with some fairly reliable calculations to figure out the pixel offsets of the left and right edges of the thumb based on the current Position and PageSize in relation to the overall client rectangle, then you are probably best off simply writing your own component instead, and then you can make it look and behave anyway you want.


text:
Q: android - sharedpreferences return null value I'm trying to use sharedpreferences to check whether the user logged in before they start using the app. I save the username in shredpreferences when user log in.
Login.java
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        Button btnLogin = (Button) findViewById(R.id.buttonlogin);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View adapt) {
                EditText usernameEditText = (EditText) findViewById(R.id.EditUserName);
                userName = usernameEditText.getText().toString();
                EditText passwordEditText = (EditText) findViewById(R.id.EditPassword);
                userPassword = passwordEditText.getText().toString();
                if (userName.matches("") && userPassword.matches("")) {
                    toast("Please enter Username and Password");
                    return;
                } else if (userName.matches("") || userName.equals("")) {
                    toast("Please enter Username");
                    return;
                } else if (userPassword.matches("") || userPassword.equals("")) {
                    toast("Please enter Password");
                    return;
                } else {
                    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("MEM1", userName);
                    editor.commit();
                    new DownloadFilesTask().execute();
                }
            }
        });
    }

    private void toast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
        protected void onPreExecute() {
        }

        protected void onPostExecute(Void result) {
            toast("user logged in");
            startActivity(new Intent(Login.this, MainActivity.class));
            finish();
        }

        @Override
        protected Void doInBackground(Void... params) {
            return null;
        }
    }

}

and I tried to check the username value before I start my mainactivity.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    String username =sharedPreferences.getString("MEM1", "");
    if(username.equalsIgnoreCase("")||username.length()==0)
    {
        toast("username is null");
        startActivity(new Intent(MainActivity.this, Login.class));
        finish();
    }

but the username is always null. Please help. Thanks

A: Calling getPreferences means that you have to be in the same activity. Using getSharedPreferences allows you to share the preferences between activities. You just have to define a name for the preferences when calling getSharedPreferences("Pref name here", MODE_PRIVATE);

A: Write below Code instead of your code to save username into sharedpreferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("MEM1", userName);
editor.commit();

And Use below code For Get Preferences Value.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String username = myPrefs.getString("MEM1","");

A: private final String TAXI_SPREF = "TAXI_SHARED_PREFERENCES";

//set-save data to shared preferences
SharedPreferences.Editor sPEditor = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).edit();
sPEditor.putInt("USERID", etUserID.getText().toString());
sPEditor.putString("EMAIL", etEmail.getText().toString());
sPEditor.apply();

//get data from shared preferences

SharedPreferences sharedPreferences = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE);
int userID = sharedPreferences.getInt("USERID", 0);
string email = sharedPreferences.getString("EMAIL", 0);
////////     or         /////
String email = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).getString("EMAIL","EMPTY");
    if (!email.equals("EMPTY")){
        etEmail.setText(email);
    }


text:
Q: spring security sasl: Unable to configure SSO url I am using following spring security saml repo from github:
https://github.com/spring-projects/spring-security-saml/tree/master/sample
Whenever I try to update the SSO url, for e.g. localhost:8100/saml/ddo, instead of /saml/sso, browser gets stuck in infinite loops.
(I have followed the steps mentioned in readme and updated the url on okta as well in application to test)
Sample code and config enclosed in:
Spring secuirty saml issue
EDIT:
I did what below answer suggested,but I am getting the Incoming SAML message is invalid..
On debugging, I found that attemptAuthentication in SAMLProcessingFilter, the location in endpoint that are added still contain the /api/saml/SSO instead of /api/saml/ddo

and that's why getEndpoint method in SamlUtil throws excpetion with following line:
throw new SAMLException("Endpoint with message binding " + messageBinding + " and URL " + requestURL + " wasn't found in local metadata");
because the requestUrl and endpoint location do not match.
I also checked my metadata.xml but it does not contain any info related to these urls.
In the MetaDataGenerator class method getSAMLWebSSOProcessingFilterPath, the samlWebSSOFilter is null and that's why the default filter url: /saml/SSO is returned. I am trying to figure out how to set this value at runtime?
I understand that there is a method with name: setSamlWebSSOFilter, and everything works correct if I provide the url /saml/ddo at the time of startup. But I am not able to make this work if config is changed at runtime.
Any idea how can I move forward?

A: Setting field filterProcessesUrl on bean samlWebSSOProcessingFilter to value /saml/ddo should solve the problem.


text:
Q: What would be a stable OS upgrade for my mid/late 2007 Mac Book Pro? Can anyone advise what a stable OS version would be for my mid/late 2007 Mac Book Pro? I am running Snow leopard 10.6.8 and know I can upgrade to Yosemite but have my hesitations after reading many comments on blogs. I've started to notice the effects of Snow Leopard being fazed out and want to upgrade but don't want to kill my machine while doing with a OS thats too much for it. I also don't want to lose apps in the process due to incompatibility.
My basic specs are as follows:
Processor: 2.6 GHZ Intel Core 2 Duo
Memory: 4GB 667 MHz DDR2 SDRAM
Hard Drive Capacity: 320GB (27GB available)
I need to upgrade to use apps like Teamviewer 10 for example (as it's not supported on 10.6.8) but as it is my machine has slowed down and hangs despite repairing the permissions, using maintenance in OnyX, using Preferential Treatment and DiskWarrior (I've not repaired the disk in DiskWarrior yet despite my graph showing 39% errors). I just don't want to upgrade too high and completely affect my computers performance. I am correct in assuming this? Any thoughts would be most appreciated!
Thanks
Paul

A: I actually have the very same machine. I started with Snow Leopard, since it originally had 1GB of RAM. After a bit of playing, I decided I liked the newer UI better and upgraded to Lion. Lion is a LOT better on this machine, very snappy, and has support for newer software from the Mac App Store. Unfortunately, some pre-Unibody MacBooks CANNOT be upgraded past Lion without hacks. Main reason being the graphics unable to keep up with the later 'beauty' introduced into the operating system.

A: I think 10.7-10.9 are all about the same on that machine so I don't see why not to install 10.9 Mavericks since it is latest and most polished of them with Aqua UI.
Yosemite while having some nice UI enchancement has some quirks regarding redraw speed.
And is clearly not as polished as Mavericks.
For great speedup you might consider buying an SSD though. If you don't use Superdrive then you might just replace it with 9.5mm PATA to SATA Optibay and save on SSD size. If you go this way install HDD into Optibay adapter and SSD in place of HDD.


text:
Q: Contact form name string I am trying to have it so when the user sends the form the subject line show the user's name like "Inquiry from [Name of user]". How it's setup now it gets to me with the subject "Contact form from site." How can I modify the code to make that happen?
<?php
// configure
$from = 'info@mysite.com';
$sendTo = 'info@mysite.com';
$subject = 'Contact form at site';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Your Message was successfully submitted. Thank you! We will get back to you soon.';
$errorMessage = 'There was an error while submitting the form. Please try again or call us at 970-201-9619';

// let's do the sending

try
{
    $emailText = "You have new message from your Website\n=============================\n";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

    mail($sendTo, $subject, $emailText, "From: " . $from);

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}

A: Made change in the subject as per your requirement. I have moved the subject variable right above the mail sending code and concatenate name and surname of user with subject line of mail. Please check below snippet and let me know if you have any query.
<?php
// configure
$from = 'info@mysite.com';
$sendTo = 'info@mysite.com';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Your Message was successfully submitted. Thank you! We will get back to you soon.';
$errorMessage = 'There was an error while submitting the form. Please try again or call us at 970-201-9619';

// let's do the sending

try
{
    $emailText = "You have new message from your Website\n=============================\n";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }
    $subject = 'Inquiry from '.$_POST['name']." ".$_POST['surname'];
    mail($sendTo, $subject, $emailText, "From: " . $from);

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}
?>


text:
Q: Array of arrays/array of objects/arrayList of arrayList I'm doing a project, where I'm reading accelerometer sensor data from a smartwatch. The app that is made has a start and stop button, that starts and stops the sensor readings, respectively.
I would like to start recording the data when the user presses start - I know how to access the sensor data, but I need a way to store the data until the stop button is pressed. Accelerometer data is X-, Y-, and Z-axis data, that could look something like this:
[2.034343, 8.342423, 0.012313]

So I need a way to store this type of vector within an additional array, in order to separate each vector recorded. Thus, the data structure I'm looking for should look something like this when having recorded three vectors of data:
[[2.034343, 8.342423, 0.012313], [6.031843, 2.349153, 0.012313], [1.734843, 5.342423, 1.012393]]

The data structure will be filled with these vectors in the time between the user pressing start to when stop is pressed.
Do I need an ArrayList of ArrayLists? Or do you have any other suggestions as to what the best data structural solution to this is? As of right now, the data only needs to be stored as long as the app is running.
I have no idea why I cannot figure out how to do this in Kotlin, I have only been able to make an ArrayList of ArrayList, however, instead of separating each vector with the brackets (as shown above) it just appends all the vector values to an array that holds all values (like a standard array).
Hope I can get some help. Thanks in advance.

A: If you want to do this with a 2D structure, you can instantiate an ArrayList or MutableList, and then you just add lists to it each time you have new data. If you use ArrayList specifically, you can specify the initial size. Setting a large initial size can help avoid the list having to resize itself while you're adding data, which can be an expensive operation if it has become large.
val data = ArrayList<List<Float>>(10000)

//adding data:
data.add(listOf(xData, yData, zData))

However, I would probably use a 1D collection because all the data points are Floats (or Doubles?) and it's easy to read them 3 at a time. Then you aren't having to create a new collection object to wrap each data point, which requires more memory allocation.
Normally, I wouldn't do something like this, which sacrifices code clarity and conciseness, but since you're recording a stream of data that could be very large, it makes sense to optimize it a bit up front.
val data = ArrayList<Float>(30000)

//adding data:
data.add(xData)
data.add(yData)
data.add(zData)

//iterating the data later:
for (i in 0 until data.size step 3) {
    val x = data[i]
    val y = data[i + 1]
    val z = data[i + 2]
    //...
}

// Or if you have a Point class, you could create a wrapper class
// for getting the points lazily:
class PointAccessor(val source: List<Float>) {
    operator fun get(index: Int): Point {
        val i = index * 3
        return Point(source[i], source[i + 1], source[i + 2])
    }
}

val pointData = PointAccessor(data)

val someX = pointData[4].x

A: A data class could make sense:
data class Point(val x: Double, val y: Double, val z: Double)

val list = mutableListOf<Point>()

list.add(Point(2.034343, 8.342423, 0.012313))
list.add(Point(6.031843, 2.349153, 0.012313))
list.add(Point(1.734843, 5.342423, 1.012393))

for (point in list) {
  println("Point: " + point.x + " | " + point.y + " | " + point.z)
}


text:
Q: CLNDR.js & Underscore.js templating issue I'm using the CLNDR.js plugin to create a nice mini calendar. I need to be able to access a value in an event function inside a day function. Let me try and explain below:
This is my JS code that populates the calendar. You'll see inside my JSON that I'm trying to add a class: 'bank-holiday' to the array of properties.

Below is my underscore.js template that populates my calendar:

            <% _.each(daysOfTheWeek, function(day) { %>
<%= day %>
<% }); %>

        <% _.each(days, function(day) { %><div class="<%= event.class %> <%= day.classes %>" id="<%= day.id %>"><%= day.day %>
<% }); %>

x

EVENTS

            <% _.each(eventsThisMonth, function(event) { %>

                <a target="blank" href="<%= event.url %>"><%= moment(event.date).format('MMMM Do') %>: <%= event.title %>

            <% }); %>

You can see in those code that I'm trying to utilise the event.class inside the day function. Is there a way to do this? You can see in the above code that the event function is being used to show event.url event.title etc.
<% _.each(days, function(day) { %><div class="<%= event.class %> <%= day.classes %>" id="<%= day.id %>"><%= day.day %>
<% }); %>
Thanks in advance for any help with this,
Andy

A: It looks like you need to loop through the days variable, and then there is an events key. Using this you can access the classes.
<%
    var classes = '';
    if( day.events.length ){
        for( var i = 0; i < day.events.length; i++ ){
            classes += ' ' + day.events[i].class;
        }
    }
%>

<div class="<%= day.classes %><%= classes %>" id="<%= day.id %>"><%= day.day %>

A: You can change underscore.js delimiters, as it says it their site:

If ERB-style delimiters aren't your cup of tea, you can change
  Underscore's template settings to use different symbols to set off
  interpolated code. Define an interpolate regex to match expressions
  that should be interpolated verbatim, an escape regex to match
  expressions that should be inserted after being HTML-escaped, and an
  evaluate regex to match expressions that should be evaluated without
  insertion into the resulting string. You may define or omit any
  combination of the three. For example, to perform Mustache.js-style
  templating:
_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

var template = _.template("Hello {{ name }}!");
template({name: "Mustache"});
=> "Hello Mustache!"

Source: http://underscorejs.org/


text:
Q: Show Due dates for linked issues in Jira I want to make a Confluence page which tracks my jira tickets and the issues that are linked to those tickets.
Till now I have done this:
project= ABC AND "Epic Link"= 'Epic1' AND status != 'closed'

I want to create a table that has Jira- key, summary, tasks, due date, status and linked issues.
I want to make sure that I show linked issues that are only linked to the current epic (that is Epic1) and also show the due dates of these issues.
I have tired doing this:-
project= ABC AND "Epic Link"= 'Epic1' AND status != 'closed' AND issuefunction in linkedIssuesOf(" "Epic Link" = Epic1 ")

but it doesn't seem to understand this issueFunction in or issue in
Can someone please help me out

A: Try using the following-
project = ABC  AND "Epic Link" = Epic1 and issue in childIssuesOf("Epic1")


text:
Q: Assign unique width to each row of a facet_grid / facet_wrap plot I'm looking to assign a custom width to each row of a one column, facet-wrapped plot in R. (I know this is entirely non-standard.)
With grid.arrange I can assign a unique height to each row of a facet-wrapped like plot with the following snippet:
group1 <- seq(1, 10, 2)
group2 <-  seq(1, 20, 3)
x = c(group1, group2)
mydf <- data.frame (X =x , Y = rnorm (length (x),5,1),
                    groups = c(rep(1, length (group1)), rep(2, length(group2))))

plot1 <- ggplot(mydf, aes(X, Y)) + geom_point()
plot2 <- ggplot(mydf, aes(X, Y)) + geom_point()

grid.arrange(plot1, plot2, heights=c(1,2))

The code above gives each row of the plot a unique height:

I'm wondering if it's possible to assign a unique width to each row of the plot, rather than assign a unique height to each row. Is that even possible with any ggplot2 extension?

A: Yes this is possible if you use the plot.margin functionality in the ggplot theme(). You can set each plot width as a percent of the total length of the page by doing:
plot1 <- ggplot(mydf, aes(X, Y)) + geom_point()+theme( plot.margin = unit(c(0.01,0.5,0.01,0.01), "npc"))
plot2 <- ggplot(mydf, aes(X, Y)) + geom_point()+theme( plot.margin = unit(c(0.01,0.2,0.01,0.01), "npc"))

When we use npcs as our unit of interest in the plot.margin call, we are setting relative to the page width. The 0.5 and 0.2 correspond to the right margin. As npc increases, the smaller your plot will get.
grid.arrange(plot1, plot2, heights=c(1,2))

A: As another option, you can use nullGrob (a blank grob that just takes up space) to allocate horizontal space in a given row. For example:
library(gridExtra)
library(grid)

plot1 <- ggplot(mydf, aes(X, Y)) + geom_point()
plot2 <- ggplot(mydf, aes(X, Y)) + geom_point()

grid.arrange(arrangeGrob(plot1, nullGrob(), widths=c(1,1)),
             plot2, heights=c(1,2))


text:
Q: If $\ell=6m-1$ is prime then $\ell\ne3\frac{j^2+3k^2}{j+3k}$ Let $\ell=6m-1$ for some integer $m\ge1$ be a prime and for any integer $1\le j\le (\ell-1)/2$, $$\dfrac{(j-m)(3j-3m+1)}{2}\neq\dfrac{\ell^2-1}{24}.$$ Then, I need a proof for the inequality that for integers $1\le j,k\le (\ell-1)/2$, $$\dfrac{(j-m)(3j-3m+1)}{2}+\dfrac{3(k-m)(3k-3m+1)}{2}\neq\dfrac{\ell^2-1}{6}.$$
Assuming $$\dfrac{(j-m)(3j-3m+1)}{2}+\dfrac{3(k-m)(3k-3m+1)}{2}=\dfrac{\ell^2-1}{6}$$ and simplification by $\ell=6m-1$ gives that $$\ell=3\dfrac{j^2+3k^2}{j+3k}.$$ If $3\nmid (j+3k)$, $\ell$ is not a prime, which is a contradiction. Now, I have not been able to conclude with a contradiction when $3\mid (j+3k)$. Other proofs are welcome. Thanks in advance.

A: For $3|j+3k$, we must have $3|j$. Then, let $j=3t$ for some integer $t$. Then
$$\ell=\frac{3(j^2+3k^2)}{j+3k}=\frac{3(9t^2+3k^2)}{3(t+k)}=\frac{3(k^2+3t^2)}{t+k}.$$
So, $3|t+k$. Let $k=3u-t$; then
$$\ell=\frac{(3u-t)^2+3t^2}u=\frac{4t^2-6tu+9u^2}u.$$
So, $u|4t^2$. Consider any prime $p|u$. Also, since
$$u=\frac j9+\frac k3<\ell-1,$$
$p\neq \ell$. Letting
$$t=p^\alpha r,\ u=p^\beta s$$
with $p\nmid r,s$, we have
$$0=\nu_p(\ell)=\nu_p\left(\frac{4p^{2\alpha}r^2-6p^{\alpha+\beta}rs+9p^{2\beta}s^2}{p^\beta s}\right)\geq 2\min(\alpha,\beta)-\beta,$$
so $2\min(\alpha,\beta)\leq \beta$. Since $\beta>1$, $\min(\alpha,\beta)<\beta$, and so it must be $\alpha$, giving $2\alpha\leq \beta$. However, for $p$ odd, $u|4t^2$ gives $2\alpha\geq\beta$, so $2\alpha=\beta$. For $p=2$, $u|4t^2$ gives $\beta\leq 2\alpha+2$. This means that $u$ is one of $\{t^2,2t^2,4t^2\}$.
If $u=2t^2$, then
$$\ell=2-6t+9u=18t^2-6t+2,$$
which is even. Otherwise,
$$\ell=[1\text{ or }4]-6t+9u\equiv 1\pmod 3,$$
a contradiction since $\ell=6m-1$. So, we are done.


text:
Q: ProgressDialog circle stops to spin when intensive calculations are in background I need advice about ProgressDialog , I show dialog like
            pd = ProgressDialog.show(
                    Dashboard.this,
                    "LOADING...",
                    "PLEASE WAIT", true, false);

and it shows, but it when in background is intensive calculation that circle stops to spin ( like it is blocked). I am running this code above inside onClick button. What to change to avoid this blocking or that is impossible ?

A: You have to move your intensive calculation to another Thread, to not block UI thread
see another SO question for example how to use AsyncTask and ProgressDialog together
progressDialog in AsyncTask

A: When you say your progress dialog does not spin, it actually means that your intensive calculation is blocking the main /UI thread
you should make use of an Asynctask
Also get a hang of painless threading in android
It will run in the background without causing hiccups in the UI thread...
Since android apps run on a single main (UI ) thread, you should avoid doing heavy tasks on the UI thread
An asynctask is basically an intelligent worker thread provided by the android system.. It contains helper methods wherein you can easily decide what you want to do
A progress dialog should be created in onPreExecute() and dismissed in onPostExecute()
Do intensive task in doInBackgound()
Here are some tutorials:
easy to understand asynctask


text:
Q: Don´t reciving notification in Orion ,atribute reference in Orion instance /ngsi10/subscribeContext not send information to my server I need something help about Orion instance /ngsi10/subscribeContext.
I made a ngsi10/updateContext and I recived this response
{
  "contextResponses" : [
    {
      "contextElement" : {
        "type" : "Room",
        "isPattern" : "false",
        "id" : "Room1",
        "attributes" : [
          {
            "name" : "temperature",
            "type" : "float",
            "value" : ""
          },
          {
            "name" : "pressure",
            "type" : "integer",
            "value" : ""
          }
        ]
      },
      "statusCode" : {
        "code" : "200",
        "reasonPhrase" : "OK"
      }
    }
  ]
}

in atribute "reference" in subscribeContext  send : "http://195.81.125.89/webservices/scriptupdatefile.php"
this script only save the information in txt.
  I sent /ngsi10/subscribeContext
{
    "entities": [
        {
            "type": "Room",
            "isPattern": "false",
            "id": " Room1"
        }
    ],
    "attributes": [
        "temperature"
    ],
    "reference": "http://195.81.125.89/webservices/scriptupdatefile.php",
    "duration": "P1M",
    "notifyConditions": [
        {
            "type": "ONTIMEINTERVAL",
            "condValues": [
                "PT10S"
            ]
        }
    ]
}

I probed too with
"type": ""type": "ONCHANGE"
condValues": ["temperature"]

and  I recibed the correct subscription...(ngsi10/unsubscribeContext work fine...)
{
  "subscribeResponse" : {
    "subscriptionId" : "556f23bd1407221d5bc569ce",
    "duration" : "P1M"
  }
}

I saw in my virtual box CENTOS that my subcription is correct, and update every x time.... , but in my logs server(http://195.81.125.89...) and my txt did not see any operation or any call....enter code here
thanks!!

A: I am a little confused by "reference": "http://195.81.125.89/webservices/scriptupdatefile.php"  ... As reference you need to put the information of a server (IP:PORT/PATH) that will accept a connection and read what the broker sends to it via socket. It seems like you want a PHP script to be launched for every notification ... This is not how it works (I might have misunderstood the whole thing, but the php suffix of your reference makes me wonder ...). In short, you need a running process that accepts incoming connections on IP:PORT.


text:
Q: How to change colour of status bar? How can I change the colour of the status bar on my iPhone 4s? It is blue now and I want it set to default?

A: A blue bar is usually an indication something is using Location Services. It ought to say which app in the bar itself.
Check Settings > Privacy > Location Services to see which apps are allowed to do that & which have been checking recently.


text:
Q: UITableView with SpriteKit How can I implement a UITableView with spriteKit? I know that I have create the tableView as an outlet in the ViewController file, but how can I access this tableView from my gameScene so I can change the position, size, cell content etc.
I have so far not been able to find any useful instructions or documentation regarding this situation.

A: If you want to use your UITableView (that was created in a storyboard, you said outlet so I am guessing that is where you created it) within your scene you will need to do a few things.
First create a variable for your table view in your scene. My swift is rusty, but if it was Objective-C it would be a matter of creating a property in the YourScene.h file.
Now when you instantiate your scene you can set the table view you have an outlet for in your scene. Something like this...
scene.tableView = tableView
skView.presentScene(scene)

Next thing in your scene you would want to implement UITableViewDelegate, UITableViewDataSource That way in your didMoveToView in your scene you can do this...
tableView?.delegate = self;
tableView?.dataSource = self;

Now in your scene you would have
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
func cellForRowAtIndexPath(indexPath: NSIndexPath) -> UITableViewCell?

This should allow you to do anything you would do with a tableView within your scene code.
Just remember a UITableView is part of UIKit and will likely be sitting on top of your SKView (added as a child). Positioning and size will be in the UIKit coordinate system.
Hopefully that makes sense and is helpful.

A: You can use the view in the didMoveToView
-(void)didMoveToView:(SKView *)view {
    // your table code
    [view addSubview:myTable];
}

Using view of SKView being the key here.
If you are in another method which does not have the SKView view, you can do this:
-(void)myMethod {
    SKView* view = self.view;
    // your table code
    [view addSubview:myTable];
}


text:
Q: ASIC verification of a multiport switch

simulate this circuit – Schematic created using CircuitLab
I have a DUT that can take packets from all 4 identical interfaces (A, B, C, D) Packets from one port can go to either one of the output ports (1,2,3,4). Example: Packets from A can go onto 1, 2, 3 or 4. Packets from port B can go to 1, 2, 3 or 4 and so on. Packets coming on the same port are in order but packets can be serviced in any order between A, B, C, D (no order is maintained since all 4 interfaces can be active at the same time sending packets).
How do I verify such a DUT? What scoreboard data structure to use?

A: I think I would approach this by maintaining 16 separate queues (FIFO buffers), one for each of the possible paths through the DUT, since from your description, that is the only sense in which order is preserved. When a packet is transmitted into one of the input ports, it is also placed in the appropriate queue.
When a packet comes out of an output port, check each of the four queues associated with that port and make sure that it is the first packet in one of them. If so, remove it from the queue and keep going.
If not, the level of diagnostics to include in the testbench is up to you. For example, you might search all of the queues to their full depth to determine whether a packet was dropped or misrouted. Or you could simply halt the simulation and debug it interactively from there.

A: you can have  a multidimensional associative array of queue with first index being the output port, second index being the input port for a referral data structure. A particular packet is queued depending on its input & output ports.
when transactions are observed on output ports, you can pop the expected packet from the referral data structure & compare.
This way you will only verify the order of packets for each input port.


text:
Q: Extending an automorphism to the integral closure I need some help to solve the second part of this problem. Also I will appreciate corrections about my solution to the first part. The problem is the following.

Let $\sigma$ be an automorphism of the integral domain $R$. Show that $\sigma$ extends in an unique way to the integral closure of $R$ in it's field of fractions.

My solution: denote $\overline{R}$ for the normalization of $R$ and $\overline{\sigma}$ for the extension of $\sigma$. Given some $r/s\in \overline{R}$, we can define $\overline{\sigma}(r/s) = \sigma(r)/\sigma(s)$. From this I can show that $\overline{\sigma}(r/s)\in\overline{R}$. So this looks like a decent extension. I guess the extension is supposed to be a homomorphism (or even an automorphism), althought this is not said explicity.
The problem comes when I try to show it is unique. I don't know what to do, all my approaches failed.

A: The uniqueness is fairly trivial. Since suppose $\bar{\sigma}$ is an extension then it must be defined as you said. Indeed $\bar{\sigma}(r/s)=\bar{\sigma}(r\cdot s^{-1})=\bar{\sigma}(r)\cdot\bar{\sigma}(s)^{-1}=\sigma(r)\cdot\sigma(s)^{-1}=\sigma(r)/\sigma(s)$. And indeed $\bar{\sigma}$ is an automorphism if $\sigma$ is since the inverse is given by the unique extension of $\sigma^{–1}$.

A:
Let $\sigma$ be an automorphism of an integral domain $R$. Then this extends uniquely to an automorphism $\overline{\sigma}$ of $K$, where $K$ is the field of fractions of $R$.

This follows easily from the Universal Property of the Ring of Fractions noticing that $\sigma(a)=0\iff a=0$. Moreover, the construction of $\overline{\sigma}$ tells us that $\overline{\sigma}(a/b)=\sigma(a)/\sigma(b)$.
Now let's observe that $x\in\overline{R}\Longrightarrow\overline{\sigma}(x)\in\overline R$: if $x^n+a_1x^{n-1}+\cdots+a_n=0$ with $a_i\in R$ then $\overline{\sigma}(x)^n+\sigma(a_1)\overline{\sigma}(x)^{n-1}+\cdots+\sigma(a_n)=0$ with $\sigma(a_i)\in R$. Thus $\overline{\sigma}_{|\overline R}$, the restriction of $\overline{\sigma}$ to $\overline R$, is an automorphism of $\overline R$.
Let $\tau$ be an automorphism of $\overline R$ which extends $\sigma$. We want to show $\tau=\overline{\sigma}_{|\overline R}$. But $K$ is also the field of fractions of $\overline R$, so it follows that $\tau$ extends (uniquely) to an automorphism $\overline{\tau}$ of $K$. Since $\overline{\tau}$ extends $\sigma$ to $K$ we must have $\overline{\tau}=\overline{\sigma}$, and therefore $\tau=\overline{\sigma}_{|\overline R}$.


text:
Q: Trying to make a Zxing winforms sample decode more formats including code_39 I'm trying to work with winforms c# samples, as eventually this is going in an existing winforms app.
I found a nice small example for taking input from a video camera and getting a barcode and then decoding it. Works great...
but it doesn't decode the type of barcode we are printing in-house, (i think it's code 39, but i'm not sure so i need a more general answer if possible.)
Here is the code i'm using, as my sample winform, there are several controls used but not declared here.
using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using ZXing;
namespace zxingTest
{
    public partial class Form1 : Form
    {
        FilterInfoCollection filterInfoCollection;
        VideoCaptureDevice videoCaptureDevice;
        public Form1()
        {
            InitializeComponent();
        }
    private void button1_Click( object sender, EventArgs e )
    {
        videoCaptureDevice = new VideoCaptureDevice( filterInfoCollection[cboCamera.SelectedIndex].MonikerString );
        videoCaptureDevice.NewFrame += FinalFrame_NewFrame;
        videoCaptureDevice.Start();
    }

    private void Form1_Load( object sender, EventArgs e )
    {
        filterInfoCollection = new FilterInfoCollection( FilterCategory.VideoInputDevice );
        foreach ( FilterInfo Device in filterInfoCollection )
            cboCamera.Items.Add( Device.Name );
        cboCamera.SelectedIndex = 0;
        videoCaptureDevice = new VideoCaptureDevice();
        timer1.Start();
    }

    private void FinalFrame_NewFrame( object sender, NewFrameEventArgs eventArgs )
    {
        pictureBox1.Image = ( Bitmap ) eventArgs.Frame.Clone();
    }

    private void timer1_Tick( object sender, EventArgs e )
    {
        BarcodeReader Reader = new BarcodeReader();
        //BarDecoder

        if (null != pictureBox1.Image)
        {
            Result result = Reader.Decode((Bitmap) pictureBox1.Image);
            if (result != null)
            {
                txtResult.Text = result.ToString();
            }
            //Result result = Reader.((Bitmap) pictureBox1.Image);
            //if ()
        }
    }

    private void btnDecode_Click( object sender, EventArgs e )
    {
        //timer1.Start();
    }

    private void Form1_FormClosing( object sender, FormClosingEventArgs e )
    {
        if ( videoCaptureDevice.IsRunning == true )
            videoCaptureDevice.Stop();
    }
}

}
In the timer1_tick method, it decodes a UPC barcode just fine... but ours are ignored.
There are lots of examples for android, etc, but I can't find any for straight windows and  I haven't found decoratively that its identical across implementations.
How do i convert the sample above to process more types, specifically code_93
I found info about using BarDecoder instead of BarReader, but it does not seem to be a declared type
Here is the barcode I'm trying to read


text:
Q: Deletar item da lista se diretório não existir Eu tenho uma lista contendo o caminho de alguns diretórios, quero verificar se cada diretório existe, para isso utilizo o os.path.exists(), se um diretório não existe, uso o método remove() para remove-lo da lista, porém no looping for ele ignora o próximo item da lista, por exemplo, se o a:/ não existe ele o paga porém pula o b:/ e apaga o c:/ e assim por diante.
Segue o código que estou usando:
def conf_dir_exist_b(lines):
    for lna in lines:
        for lnb in lna:
            if(os.path.exists(lnb) == False):
                lna.remove(lnb)
            else:
                pass
    return lines

if __name__ == '__main__':
conf_dir_exist_b(['a:/', 'b:/', 'w:/', 'g:/', 'f:/', 'd:/Downloads/Torrent/End', 'x:/files.2t', 'y:/files.1t'], ['d:/Dropbox/project/rato_bat', 'x:/bb'])

A: De acordo com a documentação isso acontece porque:

(Em tradução livre)
Há uma sutileza quando a sequência está sendo modificado pelo loop
  (isso só pode ocorrer por sequências mutáveis, isto é, listas). Um
  contador interno é usado para manter o controle de qual item é usado
  seguinte, e este é incrementado a cada iteração. Quando este contador
  tiver atingido o comprimento da sequência o loop termina.
Isto significa que se o conjunto exclui o item atual (ou um anterior)
  da sequência, o próximo item será ignorado (uma vez que obtém o
  índice do item atual que já foi tratado).
Da mesma forma, se o conjunto insere um item na seqüência antes do item
  atual, o item atual será tratado novamente na próxima vez através do
  loop. Isso pode levar a bugs que podem ser evitados fazendo uma cópia
  temporária usando uma fatia de toda a sequência, [...]

Uma forma de você fazer isto é percorrer toda a lista e verificar se o item atual é um diretório existente, se for, você o insere em uma nova lista, ao término da iteração você devolve como resultado essa lista, veja um exemplo:
def checkDirExist(lista):
    # Variável que vai armazenar os diretórios existentes
    resultado = []

    # Percorre cada uma das listas
    for diretorios in lista:
        # Percorre os itens das listas
        for diretorio in diretorios:
            # Verifica se o item atual é um diretório existente
            if os.path.exists(diretorio):
                # Se for, armazena o item na nova lista
                resultado.append(diretorio)
            # Caso não exista o diretório
            #else:
            #   print("O diretório {0} não existe!".format(diretorio))

    return resultado

# Lista de listas
diretorios = [
               ['a:/', 'b:/', 'w:/', 'g:/', 'f:/',
                'd:/Downloads/Torrent/End', 'x:/files.2t', 'y:/files.1t'],
               ['d:/Dropbox/project/rato_bat', 'x:/bb'],
             ]

diretoriosExistentes = checkDirExist(diretorios)

# ... continuação do teu código ...

Uma outra forma é usar List Comprehensions, que consiste em criar uma nova lista com os itens que você quer:
diretorios[:] = [listas for listas in diretorios for dir in listas if os.path.exists(dir)]
print (diretorios)


text:
Q: How add comment if the cell is not previously empty? I am trying to add auto comment log code to the cells that are changed.
I want to add a comment only if the cell was not empty, I mean if the cell already has a content.
My code is adding a comment to every cell even if it is the first time that I am writing something to the new cell.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim singlecell As Range

If Target.Cells.CountLarge > 100000 Then Exit Sub

For Each singlecell In Target

    If singlecell.Comment Is Nothing And Target.Value <> "" Then
        singlecell.AddComment Now & " - " _
          & "new value: " _
          & singlecell.Value & " - " _
          & Environ("username") & " -" _
          & "changed the value from a NULL value."

    ElseIf Not singlecell.Comment Is Nothing And Target.Value <> "" Then
        Target.Comment.Text _
          vbNewLine & Now & " - " _
          & "value changed to: " _
          & Target.Value & " - by: " _
          & Environ("username") & " -" _
          , Len(Target.Comment.Text) + 1 _
          , False

    ElseIf singlecell.Comment Is Nothing And Target.Value = 0 Then
        Exit Sub

    End If

    singlecell.Comment.Shape.TextFrame.AutoSize = True

Next singlecell
End Sub

A: i think i found my own answer
the below code works and only adding comments if the cell is not empty. so its making this easy to track changes made to any cell.
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.DisplayAlerts = False
If ActiveCell.Value = vbNullString Then
Exit Sub
Else
If Target.Comment Is Nothing And Target.CountLarge < 2 Then

Target.AddComment Now & " - " _
& "prev value = " _
& ActiveCell.Value & " - " _
& "new value: " _
& Target.Value & " - " _
& Environ("username") & " -" _
& "changed the value from a NULL value."

ElseIf Not Target.Comment Is Nothing Then
Target.Comment.Text _
vbNewLine & Now & " - " _
& "value changed to: " _
& Target.Value & " - by: " _
& Environ("username") & " -" _
, Len(Target.Comment.Text) + 1 _
, False

Exit Sub

End If

End If
If Target.CountLarge < 2 Then
 Target.Comment.Shape.TextFrame.AutoSize = True
 End If
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub

A:     On Error Resume Next
    S_Cell.AddComment
    If Err.Number <> 0 Then
        S_Cell.Comment.Delete
        S_Cell.AddComment
    End If


text:
Q: Basic mapped tuple type example? How can you map one tuple type to another in typescript?
This question has been asked countless times in many contexts but they all seem to be for specific use-cases or else have subtle bugs.
Can someone provide a simple, correct, general example?
Related Questions

*

*How to 'map' a Tuple to another Tuple type in Typescript 3.0

*Why are Typescript Mapped Tuple Types behaving differently when supplying Generic type vs direct type?

*Is Typescript 4.0+ capable of functions using mapped variatic tuple types?

*Mapping tuple-typed value to different tuple-typed value without casts

*Can a mapped tuple preserve the length and ordering of typed entries in typescript

*Issue around Mapped Tuple Types with type inference

*How to map a typescript tuple into a new tuple using Array.map

*TypeScript generic map variadic tuple values to nested mapped type

*Why Typescript Mapped tuple types shows all options in AutoCompletion/Intellisense?

*Extending (mapped) tuple types

*How to map & index into tuple types that is generically spread in TypeScript?

*How to use array.map with tuples in typescript?

*Extracting types and returning a mapped tuple type

*Can a function return a mapped tuple without noUncheckedIndexedAccess errors?

*typescript mapped tuple lookup types?

*How can you generate a mapped type that is a tuple type?

A: The trick is to convert over a generic type parameter not a specific type!
type Original = [number, string, Date]
type Converter<T> = T | undefined

type ConvertArray<T> = { [K in keyof T]: Converter<T[K]> }
type Final = ConvertArray<Original>

const fine: Final = [1, 'a', undefined]
const causesError: Final = ['a', 'a', 'a']
const alsoFine = fine.map(val => val)
const doubleLength = fine.length * 2
function fineFunc([num, str, date]: Final) {}
fineFunc(fine)
fineFunc(['a', 'a', 'a']) // error (correctly)

// If you don't use the generic intermediate step:
type WrongFinal = { [K in keyof Original]: Converter<Original[K]>}
const seemsOkRight: WrongFinal = [1, 'a', new Date()]
const actuallyWontWork = seemsOkRight.length * 2 // <- Error!!

Playground


text:
Q: .NET XSD validation confusion I am attempting to use an XmlReader and associated XmlReaderSettings object to perform XSD validation on some documents. I am declaring a ValidationEventHandler which I was expecting would get called whenever the reader encounters a validation problem. However I am getting an XSDValidationException when I attempt to create the reader.
Any idea what would cause the exception? The message is:

System.Xml.Schema.XmlSchemaValidationException: The 'http://www.w3.org/XML/1998/namespace:base' attribute is not declared.

Could there be an issue with one of the underlying schemas?

A: Verify that your actual XML document does not have a root element in no namespace.
This error can appear when your schema validation has a target namespace but the XML document being validated contains any root elements without a namespace.
Unfortunately schema validation in this case will only generate a warning that it does not find a matching schema for the root element and that warning is only displayed when a certain flag to report warnings is set, which is not set when using the Validate method of XmlDocument.

A: Search your schemas and your document for an xml:base attribute. If present, then the schema defining that attribute will need to be in your schema set.

A: A code sample would have been nice to be sure of what you're doing, but I can make some assumptions because I'm in the same spot. I came across Using XSDs with includes and adapted the accepted answer to work for me.
The problem is that the XmlReader doesn't seem to know what the base path is for the included schema if you don't specify it while Create()ing the XmlReader. Assuming that you have a file path to your XML file, use XmlReader.Create(Stream input, XmlReaderSettings settings, String baseUri) and supply the path to the XML file as baseUri.
Example:
using System.IO;
using System.Xml;
using System.Xml.Schema;

public void LoadXml(string path) {
    XmlDocument doc = new XmlDocument();
    XmlReader docReader;

    XmlReaderSettings rdrOpts = new XmlReaderSettings();
    rdrOpts.ValidationType = ValidationType.Schema;
    rdrOpts.ValidationFlags = XmlSchemaValidationFlags.ProcessSchemaLocation;

    try {
        // This line is what you're looking for:
        docReader = XmlReader.Create(new FileStream(path, FileMode.Open, FileAccess.Read), rdrOpts, Path.GetDirectoryName(path));
        doc.Load(docReader);
    } catch (System.Xml.Schema.XmlSchemaValidationException ex) {
        //...
    } //and catch any other relevant exceptions here, like System.IO.FileNotFoundException
}


text:
Q: Bounds on expectation of Gaussian random vectors Let $X\in\mathbb{R}^n$ and $Y\in\mathbb{R}^m$, $n\geq m$, be independent standard Gaussian random vectors and define $D\in \mathbb{R}^{m\times m}$, a positive-definite (symmetric) matrix.
I want to prove that
$$
-E\|X\|_2+E\|Y\|_2\leq -\sqrt{n}+\sqrt{m}\quad\quad (\text{1})
$$
and
$$
\dfrac{E\|\sqrt{D}Y\|_2}{\sqrt{tr(D)}}\leq \dfrac{E\|Y\|_2}{\sqrt{m}}\quad\quad (\text{2})
$$
(Here $\|x\|_2=\sqrt{x^{T}x}$, $tr(D)$ is the trace of $D$ and $\sqrt{D}$ is such that $(\sqrt{D})^2=D$.)
For (1) I know by Jensen's inequality that $E\|X\|_2\leq \sqrt{n}$ and $E\|Y\|_2\leq \sqrt{m}$. But how this implies (1)?
For (2) I know (again by Jensen) that $E\|\sqrt{D}Y\|_2\leq \sqrt{tr(D)}$ but that doesn't help me to obtain the bound since $E\|Y\|_2/\sqrt{m}\leq 1$.
Any help will be appreciated.

A: Very nice questions, can you share where you got them from?
For the second one:
We can show this claim by showing that the right side is maximized for $D = I$.
$$\frac{E ||\sqrt D Y||_2}{\sqrt{tr(D)}}=E||\sqrt{\frac{D}{tr(D)}}Y||_2$$
The expectation of the norm and the expectation of the norm squared are both maximized by the same $D$ since squaring is monotonic for positive values. So we can instead maximize:
$$E||\sqrt{\frac{D}{tr(D)}}Y||_2^2$$
It's not too hard to show that this expression is convex is $D$ by showing the hessian is positive semidefinite. We can then show that the maximum is attained for $D = I$ by showing that the gradient is $0$ at that point:
$$\nabla_D E||\sqrt{\frac{D}{tr(D)}}Y||_2^2=E[\frac{YY^T}{tr(D)} - \frac{Y^TDY}{tr(D)^2}I]$$
Applying $E[YY^T] = I$ and $E[Y^TDY] = tr(D)$ shows that this is $0$ for $D = I$, and thus the claim holds.
I also tried another way by expressing the ratio in terms of the SVD of $D$. Then you end up with something like this for the ratio on the left:
$$E ||\sum_i \alpha_i \sqrt{\frac{\lambda_i}{\sum_j \lambda_j}}v_i||$$
where $\alpha_i$ is the length of the projection of $Y$ onto the eigenvector $v_i$ of $D$. And on the right you get:
$$E ||\sum_i \alpha_i \frac{1}{\sqrt m}v_i||$$
You can then show that the first expression is maximized when all $\lambda_i$ are equal. wlog, since $V$ (the matrix of eigenvectors) is orthonormal, this shows that this expression is maximized for $D=I$.

A: This was done with the help of a friend.
For the first one. It is sufficient to prove it for $n=m+1$. Let $X_1,X_2,...$ be a sequence of iid $N(0,1)$ and let $Z=\sum_{j=1}^mX_j^2$.
It's easy to see that the functions
$$
x\mapsto \sqrt{c+x^2},\;c\geq 0,\quad x\mapsto\sqrt{x+1}-\sqrt{x}
$$
are convex in $[0,\infty)$ (by double derivative if you will). Therefore, by Jensen inequality,
\begin{align*}
E\sqrt{Z+X^2_{m+1}}-E\sqrt{Z}&=E\left[E\left[\sqrt{Z+X^2_{m+1}}\,\Big|\,Z\right]\right]-E\sqrt{Z}\\
&\geq E\left[\sqrt{Z+E[X^2_{m+1}|Z]}\right]-E\sqrt{Z}\\
&=E\left[\sqrt{Z+1}\right]-E\sqrt{Z}\\
&=E[\sqrt{Z+1}-\sqrt{Z}]\\
&\geq \sqrt{EZ+1}-\sqrt{EZ}\\
&=\sqrt{m+1}-\sqrt{m}.
\end{align*}

A: I leave a link to my solution to the first question for those who stumbled upon the same problem.


text:
Q: Flex newbie on using HGroup and VGroup to control layout I'm trying to learn Flex layout using VGroup and HGroup. As a simple exercise, I want to control the pixel-placement of button pairs. The code below attempts to place 3 pairs of buttons each in two rows. For example, the first row has a button pair 20 pixels from the top and left; another button pair 20 pixels from the top and centered; and another button pair 20 pixels from the top and right. The 2nd row has just all the buttons aligned 20 pixels to left.
It should look something like:
button button                     button button                   button button
button button button button button button

But the code produces no difference between the two rows. Can anyone help me understand how to control the layout like I'm intending?
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx"
           minWidth="955"
           minHeight="600">

<s:VGroup top="20" left="20" right="20">

    <s:HGroup top="20" left="20" right="20">

        <s:Button label="row1 left1"/>
        <s:Button label="row1 left2"/>

        <s:HGroup  horizontalAlign="center">
            <s:Button label="row1 middle1"/>
            <s:Button label="row1 middle2"/>
        </s:HGroup>

        <s:HGroup right="20">
            <s:Button label="row1 right1"/>
            <s:Button label="row1 right2"/>
        </s:HGroup>

    </s:HGroup>

    <s:HGroup top="50" left="20">
        <s:Button label="row2 left1"/>
        <s:Button label="row2 left2"/>
        <s:Button label="row2 middle1"/>
        <s:Button label="row2 middle2"/>
        <s:Button label="row2 right1"/>
        <s:Button label="row2 right2"/>
    </s:HGroup>

</s:VGroup>

</s:Application>

UPDATE: Based on Dom's answer below, here's the correct code for what I was intending:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx"
           minWidth="955"
           minHeight="600">

<s:HGroup left="20" right="20" top="20">
    <s:HGroup>
        <s:Button click=""/>
        <s:Button click=""/>
    </s:HGroup>
    <s:Spacer width="100%"/>
    <s:HGroup>
        <s:Button click=""/>
        <s:Button click=""/>
    </s:HGroup>
    <s:Spacer width="100%"/>
    <s:HGroup>
        <s:Button click=""/>
        <s:Button click=""/>
    </s:HGroup>
</s:HGroup>
<s:VGroup left="20" right="20" top="50">
    <s:HGroup width="100%">
        <s:Button click=""/>
        <s:Button click=""/>
        <s:Button click=""/>
        <s:Button click=""/>
        <s:Button click=""/>
        <s:Button click=""/>
    </s:HGroup>
</s:VGroup>

</s:Application>

A: I see two options:
1: dont use HGroup's
2: use HGroup's and space the items with
<s:Spacer width="x"/>

where x can be a % or exact pixels.
edit: properly formatted my answer so that s:spacer showed
edit 2: added code below:
<s:VGroup width="100%" height="100%">
    <s:HGroup width="100%">
        <s:HGroup>
            <s:Button click=""/>
            <s:Button click=""/>
        </s:HGroup>
        <s:Spacer width="100%"/>
        <s:HGroup>
            <s:Button click=""/>
            <s:Button click=""/>
        </s:HGroup>
        <s:Spacer width="100%"/>
        <s:HGroup>
            <s:Button click=""/>
            <s:Button click=""/>
        </s:HGroup>
    </s:HGroup>
    <s:HGroup width="100%">
        <s:Button click=""/>
        <s:Button click=""/>
        <s:Button click=""/>
        <s:Button click=""/>
        <s:Button click=""/>
        <s:Button click=""/>
    </s:HGroup>
</s:VGroup>

That will look exactly like your example above.

A: I really try to avoid spacers.  I think I've used one once to hack something into place... but it felt dirty.
The first row shouldn't be an HGroup, but a Group comprised of three HGroups.  Like this, but without any spacers:
<s:VGroup top="20" left="20" right="20">

    <s:Group width="100%">

        <s:HGroup left="0">
            <s:Button label="row1 left1"/>
            <s:Button label="row1 left2"/>
        </s:HGroup>

        <s:HGroup horizontalCenter="0">
            <s:Button label="row1 middle1"/>
            <s:Button label="row1 middle2"/>
        </s:HGroup>

        <s:HGroup right="0">
            <s:Button label="row1 right1"/>
            <s:Button label="row1 right2"/>
        </s:HGroup>

    </s:Group>

    <s:HGroup top="50" left="20">
        <s:Button label="row2 left1"/>
        <s:Button label="row2 left2"/>
        <s:Button label="row2 middle1"/>
        <s:Button label="row2 middle2"/>
        <s:Button label="row2 right1"/>
        <s:Button label="row2 right2"/>
    </s:HGroup>

</s:VGroup>


text:
Q: Is the Tango project dead? Is the Tango Desktop Project dead? It looks totally abandoned to me...

A: Last time the site was updated was 2009, but that doesn't mean it's dead. Infrequent updates don't men a project is dead just that it doesn't have a recent update.
Tango Desktop is quite far reaching, and has in fact influenced many things on today's DEs.
Remember Tango Desktop is more of an initiative then it is a piece of software. So you kind of asking if html 4 is dead. It might not have been updated in a long time, but it's far from dead.
Many, many (matter of fact most) modern projects follow the goals of the Tango Desktop Project. As do "most" DEs and modern UI guidelines.
The project is still important, still relevant, but just doesn't need a bunch of updates to keep it so.

A: Looks alive to me. Go into Bugzilla and search for tickets/issues related to the Tango project and you'll see that people are still working issues. That and code check-ins are usually the best 2 indicators if a project is alive or dead.

*

*bugs related to Tango Project
The mailing lists and IRC are probably the other best 2 indicators. I looked through the mailing lists and they're ghost towns but this isn't something that requires a lot of chatter either, so as others have said in comments and the other answer, lack of updates and low frequency don't mean a lot on a project that's providing foundation layers for GNOME.


text:
Q: Application deployed in Azure VM I have a react application deployed using an Azure virtual machine. To access the app I need to use configured DNS, for example, "http://XYZ.eastasia.cloudapp.azure.com:3000".  However, I don't want to include the port num in the URL. How can I port forward in azure so that only by typing 'http://XYZ.eastasia.cloudapp.azure.com' should be enough to access the application?

A: If you want to users access your app by URL: http://XYZ.eastasia.cloudapp.azure.com, you should run your react app on 80 port. Refer to this post to specify a port to run react app.


text:
Q: Removing header text in NSIS installer I would like to replace the entire header area in an NSIS installer with a bitmap. I have set MUI-HEADERIMAGE-BITMAP and set all the subcaptions to " ", however on the install files page I see empty white boxes over top my bitmap where the text would normally be. Is there a way around this?
Cheers,
Chris

A: Why don't you post the relevant code from your installer?
Here's what I use:
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_BITMAP "Banner.bmp"
!define MUI_HEADERIMAGE_BITMAP_NOSTRETCH
!define MUI_HEADER_TRANSPARENT_TEXT


text:
Q: Proteger a string de conexão em uma aplicação .NET Winforms? Tenho uma aplicação .NET Windows Forms que se conecta a um servidor SQL Server diretamente, sem o uso de uma camada intermediária como um WebService ou WebAPI, através de SqlConnection. Essa aplicação é instalada no computador dos clientes enquanto o servidor fica disponível através da internet.
Qual a melhor maneira, sem alterar toda a aplicação, de evitar que a string de conexão (connection string) seja capturada através de um sniffer tipo o WireShark rodando na mesma rede?

A: Segundo este artigo em inglês, o componente de conexão do SQL Server já vai criptografar as partes importantes da string de conexão durante a conexão, como a senha e nome de usuário... a não ser que use ODBC.
Seguindo alguns links desse artigo, encontrei esse artigo da MSDN: Criptografando conexões com o SQL Server que mostra como forçar o uso de SSL para criptografar TODO o tráfego de dados entre o cliente e o servidor SQL Server.

A: O correto mesmo seria você não ter essa conexão do cliente -> banco e sim cliente -> webService (com autenticação) -> banco. Por mais que você tente fazer algum tipo de encode/encriptação na string, todo o tráfego feito entre o cliente e o banco poderá ser capturado pelo sniffer. Qualquer select poderá ser capturado mesmo que sua aplicação não mostre esses dados eles virão no tráfego e podem ser capturados sem dificuldade.
Veja:

Mesmo que tente implementar uma conexão segura, isso poderá ser burlado com o sslstrip. É mais fácil criar um WebService e com isso deixar a comunicação com o banco isolada do cliente.

A: Verifiquei que a versões do SQL antigas, anteriores a 2005 (especificamente a 2000) não funcionam com o parâmetro encrypt=yes na string de conexão (connection string). Tentei em outro server mais recente e recebi o erro:

provider: Provedor SSL, error: 0 - A cadeia de certificação foi
  emitida por uma autoridade que não é de confiança.

Então encontrei outro parâmetro trustservercertificate=true que adicionei à minha string de conexão e funcionou. Esse parâmetro permite que meu client aceite um certificado emitido pelo server.
Em testes que fiz com WireShark não consegui interceptar nem a string de conexão, nem as instruções SQL, nem os dados de retorno. Os dados agora trafegam criptografados.
Então, a solução que encontrei foi incluir esse trecho ao final da string de conexão:
encrypt=yes;trustservercertificate=true;


text:
Q: SQL Server 2012 - error in MERGE statement on semicolon I have this SQL statement with MERGE. It works fine when I run it in SQL Server Management Studio, however when I am trying my application to call the exact same query via a scheduled task and execute it, I see the below error.
Can someone please help me understand whats happening.
MERGE TEST2 AS TARGET
USING TEST1 AS SOURCE
ON TARGET.ID = SOURCE.ID
AND SOURCE.ID IS NOT NULL
WHEN MATCHED THEN
    UPDATE SET ID=SOURCE.ID,
               Name= SOURCE.Name,
               City= SOURCE.City,
               State = SOURCE.State

WHEN NOT MATCHED THEN
INSERT (ID, Name, City, State)
VALUES(SOURCE.ID, SOURCE.Name, SOURCE.City, SOURCE.State);

Message: java.sql.SQLException: A MERGE statement must be terminated
  by a semi-colon (;).

A: If it runs in SSMS and not trough the application with that particular error means that SQL does not get a semicolon. Why that is happening? Run a profiler to see what your application sends to SQL. My wild guess would be that your application cuts the tail of your query. For instance following query will generate the same error:
MERGE TEST2 AS TARGET
USING TEST1 AS SOURCE
ON TARGET.ID = SOURCE.ID
AND SOURCE.ID IS NOT NULL
WHEN MATCHED THEN
    UPDATE SET ID=SOURC

A: When using DataConnect mode (i.e. outside of SQL Server Management Studio) to execute a SQL statement, the semi-colon characters may be automatically removed as the engine interprets them as the end of the statement. This is generally not an issue, but if a MERGE statement is used, it can lead to the error message "SQL Error (10713): MERGE statement must be terminated by a semi-colon (;)."
To avoid this, the semi-colon must be escaped with a back-slash. For example:
MERGE TEST2 AS TARGET
USING TEST1 AS SOURCE
ON TARGET.ID = SOURCE.ID
AND SOURCE.ID IS NOT NULL
WHEN MATCHED THEN
    UPDATE SET ID=SOURCE.ID,
               Name= SOURCE.Name,
               City= SOURCE.City,
               State = SOURCE.State

WHEN NOT MATCHED THEN
INSERT (ID, Name, City, State)
VALUES(SOURCE.ID, SOURCE.Name, SOURCE.City, SOURCE.State)\;


text:
Q: choose values of variable in effect function - R sub <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20)
f1 <- c("f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","f","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m","m")
f2 <- c("c1","c1","c1","c1","c1","c1","c1","c1","c1","c1","c2","c2","c2","c2","c2","c2","c2","c2","c2","c2","c1","c1","c1","c1","c1","c1","c1","c1","c1","c1","c2","c2","c2","c2","c2","c2","c2","c2","c2","c2")
f3 <- c(0.03,0.03,0.49,0.49,0.33,0.33,0.20,0.20,0.13,0.13,0.05,0.05,0.47,0.47,0.30,0.30,0.22,0.22,0.15,0.15, 0.03,0.03,0.49,0.49,0.33,0.33,0.20,0.20,0.13,0.13,0.05,0.05,0.47,0.47,0.30,0.30,0.22,0.22,0.15,0.15)
y <- c(0.9,1,98,96,52,49,44,41,12,19,5,5,89,92,65,56,39,38,35,33, 87,83,5,7,55,58,67,61,70,80,88,90,0.8,0.9,55,52,55,58,70,69)

dat <- data.frame(sub=sub, f1=f1, f2=f2, f3=f3, y=y)

m <- lmer(y ~ f1*f2*f3 + (1|sub), data=dat)

library(effects)
fit <- effect('f1:f3', m)
fit_df <- as.data.frame(fit)

   f1   f3       fit       se     lower     upper
1   f 0.03  1.908931 4.440515 -7.136102  10.95396
2   m 0.03 93.323001 4.440515 84.277968 102.36803
3   f 0.10 15.972474 3.530700  8.780673  23.16428
4   m 0.10 80.567822 3.530700 73.376022  87.75962
5   f 0.30 56.154027 2.827934 50.393713  61.91434
6   m 0.30 44.124456 2.827934 38.364143  49.88477
7   f 0.40 76.244803 3.846031 68.410694  84.07891
8   m 0.40 25.902774 3.846031 18.068664  33.73688
9   f 0.50 96.335579 5.254148 85.633229 107.03793
10  m 0.50  7.681091 5.254148 -3.021259  18.38344

This will create a data frame with arbitrary f3 values (in the example 0.03, 0.10, 0.30, 0.40, 0.50). But what if I want to choose the values myself (say 0.04, 0.20, 0.50)?

A: You can specify xlevels
library(effects)

fit <- effect('f1:f3', m, xlevels=list(f3 = c(0.04, .2, .5)))
fit_df <- as.data.frame(fit)

#  f1   f3       fit       se     lower     upper
#1  f 0.04  3.918009 4.301342 -4.843539  12.67956
#2  m 0.04 91.500832 4.301342 82.739285 100.26238
#3  f 0.20 36.063251 2.687348 30.589301  41.53720
#4  m 0.20 62.346139 2.687348 56.872190  67.82009
#5  f 0.50 96.335579 5.254148 85.633229 107.03793
#6  m 0.50  7.681091 5.254148 -3.021259  18.3834


text:
Q: CriticalExceptionCount in SharePoint 2010 Can anyone please describe me what is the role of CriticalExceptionCount measure in SharePoint 2010?
Couldn't understand the below line:
ResourcesPerPoint - Represents a normalization factor for this resource measure. 0 will disable.

A: When using Sandboxed solutions in SharePoint 2010 the code runs in a separate process to isolate the "normal" environment from the sandboxed code.
Each site collection is allocated a number of points it can use for sandboxed code each day. The moment the site collection has consumed more that that number of point during a day all sandboxed code execution for that site collection is disabled until next day.
So what is a point?
A point is taxed for use of certain resources. One of these resources is Critical Exceptions others are CPU, IO,... see Resource Usage Limits on Sandboxed Solutions in SharePoint 2010 for full list. As you can't just add CPU time, IO operations, Exception count..., SharePoint has introduced a way to convert each of these into points.
For CriticalExceptionCount there is set to numbers:

*

*Resources Per Point = 10 (by default) means that each exception costs 1/10 point.

*Absolute Limit = 3 (by default) means that if a worker process encounters 3 of these exceptions then it'll be restarted (as it could be a local problem) the restart costing 1 point.

The exceptions that count as Critical in this context are:

*

*ThreadAbortException

*OutOfMemoryException

*AccessViolationException

*AppDomainUnloadedException

*BadImageFormatException

*TypeInitializationException

*MissingMethodException

*ExecutionEngineException

A: CriticalExceptionCount is one of the resource usage limits defined for sandbox solution on SharePoint 2010 - it works by monitoring the following list of exception a solution may trigger:

*

*ThreadAbortException

*OutOfMemoryException

*AccessViolationException

*AppDomainUnloadedException

*BadImageFormatException

*TypeInitializationException

*MissingMethodException

*ExecutionEngineException

The resource per point property is related to the Per Day/Per Site Collection usage limit.
Basically, you can define an usage limit (expressed in resource point - default 300) for a specific site collection: when the usage exceeds its maximum allowed points all sandboxed solutions in the site collection are terminated, and no more can run for the remainder of the day.
In this contest "The Resources Per Point (column) specifies how much of the resource, by default, causes an additional point to be added toward the Per Day/Per Site Collection total." (taken from MSDN). In your example the critical exception count usage limit is defined with a default Resource Per Point setting of 3. This means that after 3 critical exception the daily usage will be increased.
There is also a second parameter called "Absolute Limit". This defines how many resource usage should trigger an immediate termination of the process, no matter what the daily limit may by.
For further detail, see this links: msdn, John blog article.


text:
Q: Wi-Fi Monitor mode listening to traffic Can we broadcast Music using wifi broadcast and listen to thhe same on devices supporting monitor mode.
I would like to listen on monitor mode because I expect the number of devices getting connected is too high for wifi to work properly using IP-protocol.
I want the wifi device to act as a FM broadcast where every device recieves every packets and stream the music.

A: Are you talking about this Wifibroadcast , here?
If so: well yes, monitor mode is the underlying technology, as can be seen here.
Now, if this is about doing a commercial product, sadly, you cannot expect any kind of interoperability from this.
Streaming audio/video over Wi-Fi is a business, and the the power in charge (Wi-Fi Alliance aka WFA) as some view on it, including certification programs. Have a look at Miracast, using Wi-Fi Direct.
As for multicast / broadcast, it is even more of a business and the realm of proprietary technologies for now (example here - and no, this is not limited to automobile). This is quite complicated, to start with because of the synchronization problem across receivers: you don't want 2 radio receivers in the same room to play with a 1 seconds delay, this would be cacophony.
EDIT:
Meaning, be it with the Wifibroadcast OSS project or with the proprietary industry about it, since there is not yet an open protocol for this (as "publicly available standard specification", I don't even go about implementation, FLOSS or not), you will have to provide a specific application for every receiver to match your broadcaster protocol, and vice versa. And that is the state of the industry today. That is what the company I mentioned above, or this other one more well know, or these are doing. And so, they do not interoperate. This will be your problem: provide a receiver app for Windows, Mac OS, Android and iOS (where you may not even have access to sub-layer 3 API) that will match your radio broadcaster protocol. And Linux too, please.
Though, this is the direction of history because this is what the user wants: stream A/V to/from device/application X from brand A to device/application Y from brand B.
And so people have been working on this, on layer 2, because layer 3 and above have unsolvable challenges with it, at IEEE since 2004 with Ethernet AVB, which is a set of protocols. You can download some of its standards for free, others for a moderate fee depending on how old they are. There is a SIG taking care of certification(http://avnu.org/certified-products/) to guarantee interoperability.
It is for 802.3 (aka wired Ethernet), but there is some work done to bring this to 802.11 Wi-Fi. Because again, that's what the user wants, the market is here, no question about that. It will take a long time. Even more to get consumer electronic grade devices or applications of the shelves. But they will interoperate out of the box, that's the goal.
There's even been work done on moving this to layer 3/IP as well BTW, with some performance sacrifice.
So come back in a few years, and all should be setup. Or, if you have lots of time and money and no urge to deliver, implement a solution based on these standards?
PS:
Link to AVnu (Ethernet AVB SIG) page about use cases for consumer electronics audio streaming, wired or wireless:
http://avnu.org/consumer/
...and its 10 pages white paper at the bottom of the page.


text:
Q: Performing a New Code Review on a Brand New Git Repository I want to perform a code review on a brand new repository.  This means I want all code to be reviewed not just a portion of it.  However, when I enter:
 ccollab addgitdiffs 1234 0000..HEAD

I get:
fatal: ambiguous argument '0000..HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
No files to review!

How do you review a brand new git repository?  I tried to upload a tar of the code but it doesn't display correctly.

A: The code for this new repository came from another location.  I did a review from the first changeset to the last.  That seemed to work.

A: I use code collaborator and you can use the "empty" git commit for this:
ccollab addgitdiffs new 4b825dc642cb6eb9a060e54bf8d69288fbee4904..HEAD


text:
Q: String for field name in javascript object literals I have a question regarding field names in js object literals. I have a function test that looks like this:
function test()
{
    var o1 = {f1:"Hello"};
    var o2 = {"f1":"Hello"};
    alert(o1.f1 + " " + o2.f1);
}

and the result is that a box appears with "Hello Hello" written in it (the test was inspired by seeing code that used strings for all of the field names). My question is, what is the difference between the two objects? Is there a difference between quoting the field name and not? Are there any specific style guidelines if the two are functionally the same?

A:
My question is, what is the difference between the two objects?

They are identical.

Is there a difference between quoting the field name and not?

Quoted property names can be things which are not valid identifiers.
e.g. { "foo-bar": 1 } is fine but { foo-bar: 1 } is a syntax error.


text:
Q: Inequalities between areas of triangles in an Euclidean 4-simplex? The 10 edge lengths of a 4-simplex with vertices $0,1,2,3,4$ satisfy the inequality that the eigenvalues of the matrix $M$ with elements $$M = [m_{ij}] = l_{0i}^2+l_{0j}^2-l_{ij}^2$$ is positive definite. $l_{ij}$ is the length of an edge connecting vertices $i$ and $j$. This actually holds in general for an $n$-simplex. A 4-simplex also has 10 areas of triangles.
My question is that given rather 10 areas of triangles of the 4-simplex, is there an inequality between only the areas to ensure that they form the simplex?


text:
Q: Wrong SQL statement in Oracle 11g I want to get the value SESSIONID from this table:
CREATE TABLE SESSIONSLOG(
  SESSIONID VARCHAR2(30 ) NOT NULL,
  USERNAME VARCHAR2(30 ),
  IPADDRESS VARCHAR2(30 ),
  LOGINTIME TIMESTAMP(6),
  LOGOUTTIME TIMESTAMP(6)
)
/

I tried this SQL query:
SELECT SESSIONID FROM ACTIVESESSIONSLOG

But I get this error message:
ORA-00904: "SESSIONID": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:
Error at Line: 1 Column: 7

How I can fix this?

A: You're querying the wrong table:
CREATE TABLE SESSIONSLOG

...
SELECT SESSIONID FROM ACTIVESESSIONSLOG

ACTIVESESSIONSLOG is not the same as SESSIONSLOG.

A: You are querying wrong table ... table should be SESSIONSLOG
SELECT SESSIONID FROM SESSIONSLOG

A: @user1285928 you are not supposed to use " ACTIVESESSIONSLOG " .
Instead Use SESSIONSLOG. Also use the delimiter symbol ;
SELECT SESSIONID FROM SESSIONSLOG;


text:
Q: Add username as watermark when downloading an already existing pdf file in codeigniter What I want to achieve is that whenever a user downloads a pdf file from the system, a watermark with his/her Username is added to the file. I have had a look at this link but I haven't got around it (it uses native PHP).

A: You can use for the watermark downloaded file the below code.
 public function doWaterMark()
    {
        $currentFile = $this->file;
        //$currentFile = put here your file;
        $Username = "UserName";
        $this->pdf = new FPDI();

        $pagecount = $this->pdf->setSourceFile($currentFile);

        for ($i = 1; $i <= $pagecount; $i++) {
            $this->pdf->addPage(); //<- moved from outside loop
            $tplidx = $this->pdf->importPage($i);
            $this->pdf->useTemplate($tplidx, 10, 10, 100);
            // now write some text above the imported page
            $this->pdf->SetFont('Arial', 'I', 40);
            $this->pdf->SetTextColor(255, 0, 0);
            $this->pdf->SetXY(25, 135);
            $this->_rotate(55);
            $this->pdf->Write(0, $Username);
            $this->_rotate(0); //<-added
        }

        $this->pdf->Output('New File Name', 'F');
    }


text:
Q: How to specify comparator for following map of map How to specify comparator for following map of map
ConcurrentSkipListMap<byte[], ConcurrentSkipListMap<byte[], ConcurrentSkipListMap<byte[], Object>>> myIndex;

Will the following declaration correct
myIndex = new ConcurrentSkipListMap<byte[], ConcurrentSkipListMap<byte[], ConcurrentSkipListMap<byte[], Object>>>(new MyCustomComparator)

Will this comparator be applicable to inner ConcurrentSkipListMap

A: No it wont be applicable to inner ConcurrentSkipListMap. You have to pass it to the constructor of the inner ConcurrentSkipListMap(), when you create a instance of the inner map.


text:
Q: What to compute on school project "Distributed calculation"? (Useful) Before you read my question: This topic fits to more than one StackExchange site (Mathematics, Software Recommendations, Software Engineering, Stackoverflow) so I putted it into most popular one. Move it please if you think it fits somewhere else better.
TL;DR: I need something useful what I can compute in simple distributed calculation app and what is not one of the most common things (DNA, fractals, ...)
End of semester is coming and I have an semestral work to do for subject "Distributed systems". The task is to make distributed system (across few physical devices connected by LAN). I have some options like distributed chat, shared variable, or what I prefer, distributed calculation.
My question is what can I compute on this. If I choose this topic I want it to be useful for something.
I do not  have knowlege of biomedicine (to compute DNA), advanced mathematics (eg. fractals) or similar stuff for what are distributed systems used mostly.
Do you guys have some ideas?
PS: It is not important but I will code it most likely in Node.JS or Java

A: You can go with prime numbers calculation using brute force, i assume the value of your project is not in the efficiency of the algorithm, more on how you are distributing the calculation.

A: Something that would be really interesting could be to execute queries using distributed calculation. Depending on your familiarity with databases and on the time you can devote, you can support as many types of queries as you find challenging and interesting (e.g distributed join).
To elaborate, you will have a number of nodes and some data that will be partitioned across those nodes and you will have a client performing queries on all those data. Your system will be able to answer those queries by doing some local computation on each node and then combining the results in a meaningful way to return the final answer.
To sum up, your project would be a simplified distributed query engine.


text:
Q: .htaccess for /index.html = / I would like Google, Twitter and Google+ to treat
http://example.com
http://example.com/ and
http://example.com/index.html as one and the same URL.
Redirect 301 http://example.com http://example.com/ works
Redirect 301 http://example.com/index.html http://example.com/ does nothing (two different urls are still seen)
Redirect 301 /index.html / results in a redirect loop

I'd be most grateful to anyone who might be able to give me the definitive way to write that has redirect.

A: You can use this code in your DOCUMENT_ROOT/.htaccess file:
DirectoryIndex index.html
RewriteEngine On

RewriteCond %{THE_REQUEST} /index\.html [NC]
RewriteRule ^(.*?)index\.html$ /$1 [L,R=302,NC,NE]

Also note that http://example.com/ and http://example.com are same URL for a web server and browser. Browsers usually strip trailing slash even before sending request to web server thus making http://example.com/ to http://example.com


text:
Q: Best way to hand-solder this TQFP (SMD) component So I'm working on a small project right now that requires a ATmega32U4RC. I'm trying to test/prototype with it, but it's a surface-mount component, so I can't just place it in my breadboard. So I found this, which is perfect for what I want.
The problem is that I haven't soldered in quite some time. I've also never soldered a component with such tiny leads.
Needless to say, I ended up with this:

Yea, I know it's bad :(
The solder-wick didn't really seem to want to do it's job (anyone know why this is?), so I couldn't really clean it up.
Are there any tips for doing this (tools that might help me, etc.)? Is there an easier way to do this than hand-soldering?

A: Learn to use "drag soldering" technique. Basically, instead of trying to solder each pin individually, you just get a bead of solder on the tip and roll it across the pins. As you hit each one, it'll leave just enough solder on the pin to attach it.
A video will do a lot to help explain here:
https://www.youtube.com/watch?v=wUyetZ5RtPs
There's a few things that help make this work:

*

*Apply flux - lots of it - before you start soldering. Yes, I know the solder you're using probably has a flux core, but that's not enough here. (If you use paste flux, the paste can also help keep the part in place.)

*Using the right kind of tip helps a lot. A small tip is not what you want here! I use a Hakko "hoof" tip (T18-C2); there's probably equivalents for most other good irons.

A: Get better (fresher?) solder wick. Digikey carries it, you can have it next-day.
It will clean that up very nicely, in seconds.
You may have to add more solder then suck it away. Looks like you are already using 63/37 but it behaves a bit more nicely than lead-free solders.
Before soldering, make sure the board is clean (your ENIG board should be fine). For a prototype I like to use a flux pen (like a Magic Marker/Sharpie but it contains liquid flux) on the contacts- some use liquid flux from a bottle.

A: The QFP-44 with 0.8mm lead spacing is far from the worst case. There is no way to escape micro-miniturization of electronics, 0603/0402/0201 components, and 0.4mm - 0.5mm QFN packages. Even BGA is in line next for DIY folks.

*

*First, get a good iron. It is always worth to have a good tool even if you have this for hobby, to avoid frustration from bad solder joints and non-working projects. JBC is probably the best, next is/was Weller, but they looks like having business issues. I use mid-end Weller WX1011 with WXMP-MS iron (40W), with 0.1mm cone tip (RT1-NW) and several other interchangeable cartridges (knife shape). Tip temperature - 380C.

*Next, get a spool of regular 63/37 solder wire with rosin core, I use 0.010", smallest available. And 0.032" for bigger jobs.

*Get a rosin-based mildly-activated flux, Kester flux-pen 186.

*Get a cheap stereo microscope, 10X-30X from eBay, they can be in $120/$170 range, to check for bad joints and solder bridges and parts alignment.

*Get a cheap ($30) Chinese hot air pen from eBay, it helps a lot in finishing solder joints on SMT components.
Soldering rule #1 - Use More Flux.
Soldering rule #2 - Use More Flux.
Don't use "no-clean" stuff or ROHS solders. "Drag soldering" does not work well for pin spacing under 1mm. Solder wick is your friend too.


text:
Q: Pandas - Usecols when columns exist in csv Since the columns and list of usecols are different, it spits the error
"ValueError" Usecols do not match names.
How can I 'usecol' if columns exist in csv?
csv sample:
df.csv

AB,CD,EF,GH
foo,20160101,a,1
foo,20160102,a,3
foo,20160103,a,5

reading csv:
import pandas as pd

df = pd.read_csv('df.csv',
    header=0,usecols=["AB", "CD", "IJ"])

This is what I'd like to get:
df

date       AB   CD
2016-01-01  a    1
2016-01-02  a    3
2016-01-03  a    5

Ignored "IJ".

A: Use lambda in usecols to skip columns that not in csv:
import pandas as pd
from io import StringIO

txt = """AB,CD,EF,GH
foo,20160101,a,1
foo,20160102,a,3
foo,20160103,a,5"""

usecols = ['AB', 'CD', 'IJ']

df = pd.read_csv(StringIO(txt), usecols=lambda c: c in set(usecols))

print(df)

    AB        CD
0  foo  20160101
1  foo  20160102
2  foo  20160103

A: import csv normally
import pandas as pd
from io import StringIO

txt = """AB,CD,EF,GH
foo,20160101,a,1
foo,20160102,a,3
foo,20160103,a,5"""

df = pd.read_csv(StringIO(txt))

print(df)

    AB        CD EF  GH
0  foo  20160101  a   1
1  foo  20160102  a   3
2  foo  20160103  a   5

reindex with intersection
usecols = ['AB', 'CD', 'IJ']
df.reindex_axis(df.columns.intersection(usecols), 1)

    AB        CD
0  foo  20160101
1  foo  20160102
2  foo  20160103


text:
Q: How can I use queue on custom class in laravel? In laravel 5.5 I was making an SMS service
SMS::to("xxxx")->send(new WelcomeSms());

or
WelcomeSms::message("xxx")->sendTo("xxx");

in here I want to use queue. When I call sendTo it must be work with queue. How can I do that?

A: All about Queues in Laravel you can read in the documentation. You need to  generate Queue Job and dispatch SmsMessage from a controller:
SmsMessage Class:
class SmsMessage {

    private $number;
    private $message;

    public function getNumber(): ?string {
        return $this->number;
    }

    public function setNumber(string $number) {
        $this->number = $number
    }

    public function getMessage(): ?string {
        return $this->message;
    }

    public function setMessage(string $message) {
        $this->message = $message
    }

}

Controller:
Then from a controller method dispatch some data and put it on the queue:
class SmsController extends Controller
{
    /**
     * Send new sms
     *
     * @param  Request  $request
     * @return Response
     */
    public function send(Request $request)
    {
        // Some code here

        $smsMessage = new SmsMessage();
        $smsMessage->setNumber('xxx');
        $smsMessage->setMessage('Lorem ipsum ...');

        SendSms::dispatch($smsMessage);
    }
}

SmsQueueJob Class:
php artisan make:job SmsQueueJob

It will generate a simple skeleton class:
class SmsQueueJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $smsMessage;

    /**
     * Create a new job instance.
     *
     * @param  SmsMessage $smsMessage
     * @return void
     */
    public function __construct(SmsMessage $smsMessage)
    {
        $this->smsMessage= $smsMessage;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Here send the SMS message
        SMS::to($sms->getNumber())->send(new WelcomeSms());
    }
}

You can generate new queue, new connection for this queue

To run queue worker run command below:
php artisan queue:work

In production environment you should run this command as a Cron Job or use Supervisor