text:
Q: ASP.NET Core and on premise AD authentication I'd like to try and use ASP.NET Core MVC or Web API at my workplace but we have just Active Directory to authentication and authorization. Is there any solution to solve it with an on premise AD or we have to change for Java? I know this question is not  original but I'd like to get a simple answer to it, please.

A: As of today, System.DirectoryServices is not available in ASP.NET Core yet. You can read more here.
In the meantime, you can use Novell.Directory.Ldap.NETStandard. For example,
public bool ValidateUser(string domainName, string username, string password)
{
    string userDn = $"{username}@{domainName}";
    try
    {
        using (var connection = new LdapConnection {SecureSocketLayer = false})
        {
            connection.Connect(domainName, LdapConnection.DEFAULT_PORT);
            connection.Bind(userDn, password);

            if (connection.Bound)
                return true;
        }
    }
    catch (LdapException ex)
    {
        // Log exception
    }
    return false;
}

Since it has too many moving pieces, I have created a sample project at GitHub.

A: Microsoft has released pre-release version for System.DirectoryServices. You can get it from NuGet package manager using this command:
Install-Package System.DirectoryServices -Version 4.5.0-preview1-25914-04

This is working fine for me till now.


text:
Q: Classical book or jupyter notebooks? I am working on a series of chapters for a book on Machine Learning, in particular on the mathematics behind it, but with clear references to how to implement it in Python (see vectorization for example). My question to the community is (and apologies if this is the wrong place): would you prefer a classical book (pdf) or a series of Jupyter notebooks with math, text and code in the same place that you can fork, study and use? The book would be mainly focusing on theory, although I will support it with several examples (see for example overfitting, or optimisation algorithms like Adam or Momentum).
Feedback would be much welcome, before I start (the huge) work on it.
Thanks in advance, Umberto

A: For people who know how to edit text and implement code in Jupyter, what advantages would writing a Machine Learning textbook in a PDF file offer? Especially if the targeted consumer is assumed to be knowledgeable enough to have dealt with either Jupyter directly or just Python, I can't really see any benefits in PDF format other than conventionality (which is honestly quickly changing for books of this nature in this field).

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the easiest way of removing the attribute of a node of an xml file in vb? I'm familiar with using the MSXML2 library for reading xml files. But is there an easy way of editing a particular node. Say I have the following line of code that selects a dataroot element that has the attribute generated:
Dim oDoc as MSXML2.DOMDocument
Dim oNode as MSXML2.IXMLDOMNode

Set oDoc = ... //open xml file here//
Set oNode = oDoc.selectSingleNode("/root/dataroot/[@generated]")

I want to be able to remove the generated attribute from the selected node and save the change back to the original file.

A: Remove the attribute from the Attributes collection of the node in question:
oNode.Attributes.removeNamedItem "generated"

A: To remove an attribute from an node:
oNode.removeAttribute("generated");

To save the changes:
oDoc.save("changed.xml")


text:
Q: Fetching "id" from first 5 tags and separate them with comma in output using pure javascript I am working on one of script where I need to pull the value available in id on tag  I need to use pure Javascript to get this done. I have similar jQuery code available but I am not able to successfully complete Javascript one.
My jquery Code
var arr1st3 = $('article:lt(3)').map(function() {
    return this.id.replace(/[^\d]/g, '');
}).get();
console.log( arr1st3 );

Here is the test url
http://jsfiddle.net/0mvjbkhs/5/
I am trying to have Javascript function that will return the values in output like ['123456', '7896669', '1147777']
Any help will be really appreciated

A: Pure javascript version would be:
var arr2st3 = [].map.call(document.querySelectorAll('article:nth-child(-n+4)'), function(el) {
    return el.id.replace(/[^\d]/g, '');
});

Quite similar. You just use native Array.prototype.map and article:nth-child(-n+4) CSS selector to select elements.
Demo: http://jsfiddle.net/0mvjbkhs/6/


text:
Q: Is this a logic error Or something else? Here's what the teacher assigned us:

Suppose we are an online service that provides a bulletin board for its users. We would like to give our users the option of filtering out profanity.  We will consider the words cat, dog, and llama to be profane. Write a program that reads a string from the keyboard and tests whether the string contains one of our profane words. Your program should find words like cAt that differ only in case. You must also not identify words that simply contain what might otherwise be considered a profane word. For example, Dogmatic concatenation is a small category should not be considered profane. Allow the user to use the following punctuation: ( , . ? " ' ( ) ! : ;) This will mean that you would be expected to find "The "Cat" is not a doggone llamaman." or "Cat, and dog can not be llama." (Note: You will only be responsible for the first occurrence of a given profane word in a sentence.  However, more than one profane word may be contained in a sentence. So "Concatenate the cats", would not find a profane word but "The doggone cat, and dog are not a llama." would return 2 profane words cat and llama)

so, I tried this code:
import java.util.Scanner;
public class Degrees
{
    private static Scanner keyboard = new Scanner(System.in);
    public static void main(String[]args)
    {
        System.out.println("Enter a sentence");
        String sentence = keyboard.nextLine();
        sentence = sentence.toLowerCase();
        if(sentence.indexOf("cat ") != -1)
            System.out.println("the profane word cat was detected");
        else
            System.out.println("the profane word cat wasn't detected");

        if(sentence.indexOf("dog ") != -1)
            System.out.println("the profane word dog was detected");
        else
            System.out.println("the profane word dog wasn't detected");
        if(sentence.indexOf("llama ") != -1)
            System.out.println("the profane word llama was detected");
        else
            System.out.println("the profane word llama wasn't detected");

    }

}

however the code isn't working how it should be. if i wrote "dogmatic dog" it should only check the first occurrence of dog and see that it is within a word and then ignore the second dog. My code is just ughh. I don't know what I'm missing and what I should add. I've been going at this for 6 hours straight I swear. Please help. I just can't think of anything else. So please, I am open to suggestions and hints.
I also tried using a switch statement but for some reason it was only executing the default.

A: You'll have to create a "mini-parser" that'll iterate the words in the sentence and will check each one of them if it's considered profane or not.
Partially implemented solution:
public static void main(String[] args) {

    String s = "The doggone cat, and dOg are not a llama.";
    s = s.toLowerCase();
    Scanner sc = new Scanner(s);
    List<String> profaneWords = generateProfaneList();
    int counter = 0;
    while (sc.hasNext()) {
        String word = sc.next();
        for (String profane : profaneWords) {
            if (word.matches(".*\\b" + profane + "\\b.*") && // check an exact match
                    ! s.matches(".*" + profane + "[a-z].*\\b" + profane + "\\b.*") && // check that profane is not
                    ! s.matches(".*[a-z]" + profane + ".*\\b" + profane + "\\b.*")) { // included as part of another word
                counter++;
                System.out.println("The word '" + profane + "' is profane!");
            }
        }
    }
    System.out.println(counter + " profane words were found");
}

private static List<String> generateProfaneList() {
    List<String> profaneWords =  new ArrayList<>();
    profaneWords.add("dog");
    profaneWords.add("cat");
    profaneWords.add("llama");
    return profaneWords;
}

OUTPUT
The word 'cat' is profane!
The word 'llama' is profane!
2 profane words were found

A: I suggest using this algorithm:

*

*Define all the profane words in an array. Let's call it profaneWords.

*Split the sentence into several strings using whitespace. This will be stored into an array, let's call it wordsToAnalyze

*For each word (string) in profaneWords, let's call the current word profane:

*

*Create a flag to check if profane has been found. Let's call it found. Initialize it with a value of no.

*For each word (string) in wordsToAnalyze, let's call the current word analyzeMe:

*

*Trim all non-characters from analyzeMe.

*Check if analyzeMe is equal to profane. If it does, then mark found to yes and break the for loop.

*Check if analyzeMe contains profane. If it does, then break the current for loop.

*If found is yes, then report that the profane word has been identified.

I won't provide the proper Java implementation for algorithm above. Instead, just a pseudo code (after all, it's homework, so it's your job to do the code, not ours =) ):
profaneWords = { "cat", "dog", "llama" } //why llama is profane? =(
wordsToAnalyze = sentence.split(" ") //this can be improved but you should not use regex yet
for each profane in profaneWords
begin for
    found = false
    for each analyzeMe in wordsToAnalyze
    begin for
        analyzeMe = trimNonCharacters(analyzeMe)
        if (analyzeMe is equal to profane)
            found = true
            break
        if (analyzeMe contains profane)
            break
    end for
    if (found is true)
        print "The word " + profane + " was found."
end for

For trimNonCharacters you may create another method that basically reads every character from the string parameter and removes any non-character in it and create a new string. You may use a StringBuilder for this:
public static String trimNonCharacters(String string) {
    int startIndex = 0;
    int endIndex = string.length();
    for (int i = 0; i < string.length(); i++) {
        if (Character.isLetter(string.charAt(i))) {
            break;
        }
        startIndex++;
    }
    for (int i = string.length() - 1; i >= 0; i--) {
        if (Character.isLetter(string.charAt(i))) {
            break;
        }
        endIndex--;
    }
    String result = "";
    if (startIndex <= endIndex) {
        result = string.substring(startIndex, endIndex);
    }
    return result;
}

A: This is a great candidate for a regex:
System.out.println("Enter a sentence");
String sentence = keyboard.nextLine();
sentence = sentence.toLowerCase();

Pattern p = Pattern.compile("\Wcat\W|\Wdog\W|\Wllama\W");
Matcher m = p.matcher(sentence);
boolean matchFound = m.matches();

\W will match any non-digit and non-word so as an example concatenate would not trigger a match but "cat would.
For more information:
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html


text:
Q: Can I free() static and automatic variables in C? The code is as follow :
#include <stdlib.h>

int num = 3;   // Static external variable
int *ptr = #

int main(void)
{
 int num2 = 4;  // Automatic variable
 int *ptr2 = &num2;

 free(ptr);  //Free static variable
 free(ptr2); //Free automatic variable

 return 0;
}

I try to compile the above code and it works, I'm curious does the free() function able to free both the static variable and also automatic variable? Or basically it does nothing?

A: You shouldn't do that. free is only used for memory dynamically allocated from heap by malloc family of functions.
Memory for num is statically allocated in data segment and can't be released. Memory for num2 is allocated in the main's call stack frame and will be released as soon as main returns.
What actually happens depend on implementation of free. There are usually specific data structures maintained in heap to help malloc/free track the allocated and free memory areas. free expects these data structures to be somewhere around the place its argument points to. An when you pass it a pointer which doesn't point to a malloc-allocated heap area, it'll consider garbage data as some useful information and do some strange things. And you're lucky if the result is just an immediate program crash.

A: Calling free() on a pointer not returned by memory allocating functions(malloc,calloc etc) causes Undefined Behavior.
Your code has an Undefined Behavior, So the compiler does not need to give you any diagnostic of it and it can show any behavior, it might work, or crash, or literally do anything.
Just avoid writing code which causes an Undefined Behavior is the only solution.


text:
Q: Distributing limited resources with choices I'm looking for an algorithm to figure out the maximum number of "products" that can be created given limited "resource choices".
For example, let's say I want to create an ABC and are given these resource choices:

*

*A or B: 3

*A or C: 1

*B: 1

*C: 1

In this case, I can create at most 2 ABC by selecting 2 A and 1 B from the first choice, and 1 C from the second choice. Then I have a total of 2 A, 2 B, and 2 C which can create 2 ABC.
Is there an algorithm, other than brute forcing the permutations, which solves this problem?
For completeness, here are the constraints in my actual problem:

*

*Max number of different resources in product: 10

*Max number of resource choices: 20

*Max quantity of a choice: 50

A: It can be solved using Linear Programming or using the Ford-Fulkerson Algorithm to solve the so-called Maximum Network Flow problem. It would take me quiet some time to try to explain any of the 2 mentioned algorithms, so I think you should take a look at some online resources. If you need to solve some real problem I suggest you to go through the algorithm(s) just to get idea how you can model this particular problem and then use some of the existing libraries. If you want to learn algorithms, feel free to write your implementation :)


text:
Q: Cell Click Events in DataGrid using MVVM structure Friends, I am creating one small application in WPF C# with following MVVM structure.
I am stuck to one point where even I don't know how to google it, so finally thought to keep it here.
You can see from below image that I have a table structure using GridView. I have enabled a single cell selection also in the same.

Now what I need is when I click on particular cell, TextBox named as AllowEdit_Text should show value of selected text, and once I edit in this TextBox, it should reflect back to table. Now what my worry is how to get access of the individual cell which is selected?(Even my table is Dynamic). I found many articles like the link here: How do i handle cell double click event on WPF DataGrid, equivalent to windows DataGrid's Events?
But in these articles they all use back-end method with Sender argument, which can be accessible in coding part of View only, but as this one is violating MVVM structure, I am confused how to proceed.
Please show me the perfect way which can be helpful and also follows MVVM structure.
Below is my existing View code for your reference.
VehicalForm.xaml
        <Window x:Class="Seris.VehicalForm"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="500" Width="600">
<Control>
    <Control.Template>
        <ControlTemplate>
            <WrapPanel Orientation="Vertical" Margin="10 " >
                <Label Content="Vehical No" HorizontalAlignment="Left"/>
                <TextBox Name="VehicalNo_Text" Height="23" Width="80" TextWrapping="Wrap" Text="{Binding VehicalNo, UpdateSourceTrigger=PropertyChanged}"  HorizontalAlignment="Left" />
                <Label Content="Model" HorizontalAlignment="Left"/>
                <TextBox Name="Model_Text" Height="23" Width="80" TextWrapping="Wrap" Text="{Binding Model, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" />
                <Label Content="Manufacturing Date" HorizontalAlignment="Left"/>
                <DatePicker Name="ManufacturingDate_DateTime" SelectedDate="{Binding ManufacturingDate, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
                <Label Content="IU No" HorizontalAlignment="Left"/>
                <TextBox Height="23" Width="80" Name="IUNO_Text" TextWrapping="Wrap" Text="{Binding IUNo, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left"/>
                <Label Content="Personnel" HorizontalAlignment="Left"/>
                <ComboBox Name="Personnel_Combo" SelectedValue="{Binding PersonnelNameSelected, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding PersonnelName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" HorizontalAlignment="Left" Width="116"/>
                <Separator Height="20" RenderTransformOrigin="0.5,0.5" Width="16"/>
                <Button Name="Save_Button" Command="{Binding SaveButton_Command}" Content="Save" Width="66"/>
                <Label x:Name="Error_Label" Content="{Binding ErrorMessage, UpdateSourceTrigger=PropertyChanged}" Foreground="Red" HorizontalAlignment="Left" Height="41" Width="137"/>
                <ListView Name ="Grid" Height="294" Width="371" >
                    <DataGrid Name="DG" ItemsSource="{Binding ListItems, UpdateSourceTrigger=PropertyChanged}" SelectionUnit="Cell" GridLinesVisibility="None" IsReadOnly="True" AutoGenerateColumns="False" BorderThickness="0">
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="Vehical No" Binding="{Binding VehicalNo}" />
                            <DataGridTextColumn Header="Model" Binding="{Binding Model}" />
                            <DataGridTextColumn Header="ManufacturingDate" Binding="{Binding ManufacturingDate}" />
                            <DataGridTextColumn Header="IUNo" Binding="{Binding IUNo}" />
                            <DataGridTextColumn Header="Personnel" Binding="{Binding PersonnelNameSelected, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />

                        </DataGrid.Columns>

                    </DataGrid>
                </ListView>
                <TextBlock Name="Notification" Text="{Binding EditText, UpdateSourceTrigger=PropertyChanged}"/>
                <TextBlock Name="AllowEdit_Text"/>
            </WrapPanel>
            <ControlTemplate.Triggers>
                <DataTrigger Binding="{Binding IsMouseOver, ElementName=Grid}" Value="true">
                    <Setter Property="Text" TargetName="Notification" Value="abc"/>
                </DataTrigger>

            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Control.Template>
</Control>
</Window>

A: You can use the MVVMLight framework to use EventToCommand behavior.
Example:
<ListBox Name="list">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseDoubleClick">
      <Command:EventToCommand
           Command="{Binding Path=DataContext.DoSomethingCommand,ElementName=list}"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</ListBox>

A: Use SelectedIndex property in following way
<DataGrid
    Name="DG"
    ItemsSource="{Binding ListItems, UpdateSourceTrigger=PropertyChanged}"
    SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}"
    SelectionUnit="Cell"
    GridLinesVisibility="None"
    IsReadOnly="True"
    AutoGenerateColumns="False"
    BorderThickness="0">

Using this property you can get the selected index in the grid.

A: It's better to use MVVMLight.
I give you the steps to retrieve the selected row(s) of the grid.
1. First of all the datagrid binding
XAML
<DataGrid ItemsSource="{Binding friends}" AutoGenerateColumns="False">

Code Behind
private ObservableCollection<Friend> _friends;
public ObservableCollection<Friend> friends
{
    get { return _friends; }
    set { _friends = value;
    RaisePropertyChanged(); }
}

2. The DataGrid click event, you can do that in different ways depending if you want to manage single row selection or multiple rows selection.
In this case i show you how to manage multiple selection, it can be used also for single row selection or you can use the SelectedItem Property of the grid.
References to add to the view to be able to use the MVVMLight events
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:MVVVMLightCommand="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform"

Manage the event on the datagrid for the "MouseDoubleClick" event
<DataGrid ItemsSource="{Binding ItemSourceDataGrid}" x:Name="dataGridTest" AutoGenerateColumns="False" Height="258" Width="485" Grid.Column="1">
....
<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseDoubleClick" >
        <MVVVMLightCommand:EventToCommand Command="{Binding DGSelectionChangedCommand,Mode=OneWay}" CommandParameter="{Binding SelectedItems, ElementName=DataGridTest}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

...
</DataGrid>

Constructor of the viewmodel, as you can see the RelayCommand will receive a list of objects correspoding to the selected rows.
DGSelectionChangedCommand = new RelayCommand<IList>(DGSelectionChanged);

Viewmodel - The RelayCommand
public RelayCommand<IList> DGSelectionChangedCommand { get; private set;}

Viewmodel - where you retrieve the list<> of selected rows.
private void DataGridSelectionChanged(IList test)
{
    foreach (var item in test)
    {
        MessageBox.Show(((Friend)item).ID.ToString());
    }
}

Hope this helps


text:
Q: Create data relation on multiple columns I'm trying to create relation on multple columns but I get error like:

column' argument cannot be null.
  Parameter name: column

This is how I do it:
        MySqlDataAdapter table1;
        MySqlDataAdapter table2;

        DataSet myDataSet = new DataSet();

        table1 = new MySqlDataAdapter(query1, this.connection);
        table2 = new MySqlDataAdapter(query2, this.connection);

        table1.Fill(myDataSet, "mainList");
        table2.Fill(myDataSet, "subList");

        myDataSet.Relations.Add(relationName,
        new DataColumn[] { myDataSet.Tables["mainList"].Columns[fieldName1_1], myDataSet.Tables["mainList"].Columns[fieldName1_2] },
        new DataColumn[] { myDataSet.Tables["subList"].Columns[fieldName2_1], myDataSet.Tables["mainList"].Columns[fieldName2_2] }).Nested=true;

        return myDataSet;

I can't figure what I'm doing wrong?


text:
Q: Promql percent successes by category I have a gauge that with label "success_or_failure" with values "success" and "failure". I want to create a chart in graphana that shows the percentage of success broken down by another label "category". The idea is to see the "percent success" for each category over time.
The promql I want would be something like:
avg by (category)
  (event_gauge{success_or_failure="success"} /
  ignoring(success_or_failue) group_right event_gauge)

When I do this, every charted element is equal to 1. This leads me to believe think that I'm doing it wrong. What am I doing wrong here?

A: Prometheus will only use your last stored value in the PromQL query you have listed. The PromQL query always works based on the last value of your metric.
You could do a
sum_over_time(event_gauge{success_or_failure="success"}[1h]) /
count_over_time(event_gauge{success_or_failure="success"}[1h])

to sort of get what you want.
But really, the data is not modelled well for using with Prometheus. You should think of using counters for this.
Something with event_counter{category="xyz", status="success"} and event_counter{category="xyz", status="failure"}. And have your instrumentation code increment the current counter based on the events.
Let Prometheus just scrape the latest state of your counters.
Then you can do
avg by (category)
 (sum without (status) (event_counter{category="xyz", status="success"})
    /
  sum without (status) (event_counter{category="xyz"}))

P.S. I haven't fully tested it so there might be slight syntax mistakes, but most importantly do see if you can model it as a counter instead of a gauge.


text:
Q: Create Command line shortcuts in Windows 7 I'm using jsDoc to create documentations for my JavaScript files. The command I use is
> java -jar jsrun.jar app\run.js -a -t=templates\jsdoc mycode.js

What I want is to create a batch or something else (I really don't know), so that I can type
> jsdoc mycode.js

Without having to specify any folders or change my working directory in the command line.
Is this possible? How?
Thanks!

A: Make a batch file called "jsdoc.bat" and ensure that you have a path you your jsdoc folder / app folder (or code the full locations in). Ensure there is a path to wherever you put this file set path = c:\whereverthebatfileis\ The following would be the code.

java -jar jsrun.jar  c:\whateverfolder\app\run.js -a -t=c:\whateverfolder\templates\jsdoc\ %1

Usage would be:
jsdoc myfile.js


text:
Q: svn repository malformed: how to fix repair repository structure OK. The repository structure has directories "src" "aux" and "script". No "trunk", no "tags", no "branches". Is there any way I can get this code into a correctly-structure repository while preserving the revision history?

A: Yes, there is a way. You should use svn mv.
mkdir trunk
mkdir branches
mkdir tags
svn ci
svn mv src trunk/src
svn mv aux trunk/aux
svn mv script trunk/script

A: *

*create a trunk directory

*move src, aux and script into the trunk directory

*create empty tags and branches directories for future use

If you have a working copy that contains src, aux and script, you could do:
svn mkdir trunk tags branches
svn mv src aux script trunk
svn commit

A: this discussion might help.
in short: svn mv


text:
Q: Repeater Field empty in ACF I'm fairly new in using ACF so I used the code that was displayed in their site to display what is inside of my repeater field.
However, when I try to show the repeater's content it is empty??
This is my code, this is still in trial mode just to see if it's working-which it isn't. My repeater field already has 2 rows but it's not showing up any of those and just displays the else:
// check if the repeater field has rows of data
if( have_rows('map_infogrp') ):

    // loop through the rows of data
    while ( have_rows('map_infogrp') ) : the_row();

        // display a sub field value
        the_sub_field('google_map');
        the_sub_field('branch_name');
        //$street = get_sub_field('street');
        //$district = get_sub_field('district');
        //$phonenum = get_sub_field('phone_number');
        //$email = get_sub_field('email');

    endwhile;
else:

echo 'why is this empty???';

endif;

A: You need to specify the page id that you have set the ACF Repeater, otherwise it will get from the current page ID

have_rows($field_name, $post_id); //syntax

So, update your loop inserting the page ID you've entered the repeater data:
if( have_rows('map_infogrp', 'page_id') ):

    // loop through the rows of data
        while ( have_rows('map_infogrp', 'page_id') ) : the_row();

...

A: If you have the fields filled in on the specific page it should be showing up. If not, double check the field name(not label) that you used. If you have more than one row make sure you're printing it out as an array too


text:
Q: Can you make a variable from table that you make in Google Docs? I'm new to Google Script and was wondering if I can write something that takes the information I input in a table in Google Docs and make it a variable so that I can transfer it to a Google Sheet and manipulate it the way I need over there.

A: A Simple Example
It gets the upper left cell in the first table in the document and sends to cell A1 in a spreadsheet with the provided id and Sheet2
function getTableData() {
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  var tables=body.getTables();
  var A1=tables[0].getCell(0, 0).editAsText().getText();
  var ss=SpreadsheetApp.openById('ssid');
  var sh=ss.getSheetByName('Sheet2');
  sh.getRange('A1').setValue(A1);
}

This one gets all the values in the first table.
function getTableData() {
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  var tables=body.getTables();
  var A=[];
  for(var i=0;i<tables[0].getNumRows();i++) {
    var r=[];
    for(var j=0;j<tables[0].getRow(i).getNumCells();j++) {
      r.push(tables[0].getCell(i,j).editAsText().getText());
    }
    A.push(r);
  }
  var ss=SpreadsheetApp.openById('ssid');
  var sh=ss.getSheetByName('Sheet2');
  sh.getRange(1,1,A.length,A[0].length).setValues(A);
}


text:
Q: Powermockito with Java 8 I am using powermockito to mock static methods with params in Java 7. Recently started migrating to Java 8. Post migration the powermockito stopped mocking the static methods and started calling the original method.
Pom.xml
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4-rule-agent</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.18.2-GA</version>
    <scope>test</scope>
</dependency>

Test class
using spring runner with PowerMockRule
@RunWith(SpringJUnit4ClassRunner.class)

@Rule
public PowerMockRule rule = new PowerMockRule();

Below is the code used for mock/stubbing the static..

PowerMockito.stub(PowerMockito.method(ABCHelper.class, "prepareResult",Arg1.class,Arg2.class,Arg3.class,Arg4.class)).toReturn(mockedReturnedObject);

Can somebody please help me with this issue?

A: Below code works for me. Please give it a try with below dependencies and code in new project.
pom.xml
 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>PowerMockTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4-rule</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-classloading-xstream</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

Test class
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

import org.junit.Rule;
import org.junit.Test;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;

@PrepareForTest({UtilTest.class})
public class PowerMockRuleTest {

  @Rule
  public PowerMockRule powerMockRule = new PowerMockRule();

  @Test
  public void testStatic() throws Exception{
    PowerMockito.mockStatic(UtilTest.class);
    when(UtilTest.getName()).thenReturn("1234");
    System.out.println(UtilTest.getName());

    Main mainMock = mock(Main.class);

    PowerMockito.whenNew(Main.class).withAnyArguments().thenReturn(mainMock);
    when(mainMock.getMyTest()).thenReturn("12345");
    System.out.println(mainMock.getMyTest());
  }

}

Classess:
public class UtilTest {

  public static String getName() {

    return "test";
  }

}

public class Main {

  public static void main(String[] args) {
    System.out.println("Hello World!");
  }

  public String getMyTest() {
    return "main test";
  }
}


text:
Q: Eclipse wrong formatter spacing Since I did Right Mouse > Source > Format on one of my projects, all my files in Eclipse are formatted wrong. They use spaces and only two of them:
public class XYZ {
  public XYZ( ) {
    ;
  }
}

But in my formatter, settings I set it to "only use tabs" and a tab size of 4! But it doesn't work? What can I do now?
It should look like this:
public class XYZ {
    public XYZ( ) {
        ;
    }
}

Here is how my formatter settings looks like.

And here how the code really gets formatted. Without tabs and an indention of only 2 spaces!

A: Make sure you've selected the correct "Active Profile" to use on Window > Preferences > Java > Code Style > Formatter.
EDIT: Another possibility would be to use a "Clean Up Profile" instead. Try creating one and set those ticks.
Then do Right Mouse > Source > Clean Up..., select your created profile and run the Clean Up.


text:
Q: A countable product of separable spaces is separable This exercise is given in Munkres, but it is not stated in which topology that it holds. Do I take the product topology or box topology?
Additionally, I have a question on how to solve this problem. Let $A = A_1 \times A_2 \dots$ be the space, and let $B_n$ be the countable dense subset of $A_n$. Can I take $B = B_1 \times B_2 \times \cdots$ to be the countable dense subset, or do I have to be more clever than that?

A: It's the product topology, and you have to be a bit cleverer than that, because $\prod_nB_n$ is in general not countable.
HINT: For each $n$ fix a point $x_n\in B_n$, and consider the set of points of your $B$ that are equal to $x_n$ for all but at most finitely many indices.
In fact a stronger result is true: the product of $2^\omega=\mathfrak{c}=|\Bbb R|$ separable spaces is separable, but this is significantly harder to prove. See this question for more information.


text:
Q: jarsigner error: java.lang.RuntimeException: keystore load: Invalid keystore format While I was executing my certsign.sh script in my workarea ,I got  the below  error
jarsigner error: java.lang.RuntimeException: keystore load: Invalid keystore format
The contents of the certsign.sh is this one :-
echo "Signing Client.jar"
jarsigner -keystore GeminiDD_KS -storepass GeminiDD Client.jar GeminiDD
echo "Client.jar Signed... Verificiation in progress"
jarsigner -verify Client.jar

But when I am executing the same script in some other location it is not showing error.

A: If the behaviour is different on different systems it may depend on the Java version opr vendor. Which version of java are you using on your workstation (official Oracle JDK, OpenJDK...)?
You can also force the use of Java Keystore format in your signing script:

jarsigner -keystore GeminiDD_KS -storetype JKS -storepass GeminiDD Client.jar GeminiDD


text:
Q: insert date with time in access database c# In the access I'm only getting the date  5/12/2015 but no the time, I need something like this
5/12/2015 4:56 PM saved in the access database
  DateTime dtclickdate = DateTime.Now;
  OleDbParameter clickdate = new OleDbParameter("@clickdate ", OleDbType.DBDate);
  clickdate.Value = dtclickdate;
  cmd.Parameters.Add(clickdate);

A: Have a look at the MSDN description of OleDbType:

DBDate:     Date data in the format yyyymmdd (DBTYPE_DBDATE). This maps to DateTime.

As you can see, DBDate does not contain a time component. I would suggest to use Date instead:

Date:   Date data, stored as a double (DBTYPE_DATE). The whole portion is the number of days since December 30, 1899, and the fractional portion is a fraction of a day. This maps to DateTime.

According to the following Microsoft Knowledge Base article, this is the correct type to use for Access Date/Time fields.
Quoted from INFO: OleDbType Enumeration vs. Microsoft Access Data Types:
Access Type Name  Database Data Type  OLE DB Type  .NET Framework Type  Member Name
    ...
Date/Time         DateTime            DBTYPE_DATE  System.DateTime    OleDbType.Date
    ...

StackOverflow should really add support for tables...
PS: Note that OLEDB does not like Milliseconds in Date/Time fields. If you get a Data type mismatch in criteria expression error, remove the milliseconds:
dtm = New DateTime(dtm.Year, dtm.Month, dtm.Day, dtm.Hour, dtm.Minute, dtm.Second)

A: You should use the OleDbType.DBTimeStamp enumeration, which maps to DateTime:
DateTime dtclickdate = DateTime.Now;
OleDbParameter clickdate = new OleDbParameter("@clickdate ", OleDbType.DBTimeStamp);
clickdate.Value = dtclickdate; cmd.Parameters.Add(clickdate);

See this documentation for more information.

A: Try OleDbType.DBTimeStamp:
DateTime dtclickdate = DateTime.Now;
OleDbParameter clickdate = new OleDbParameter("@clickdate ", OleDbType.DBTimeStamp);
clickdate.Value = dtclickdate;
cmd.Parameters.Add(clickdate);

Reason: this also stores time fraction as explained here.


text:
Q: PYOMO Constraints - setting constraints over indexed variables I have been trying to get into python optimization, and I have found that pyomo is probably the way to go; I had some experience with GUROBI as a student, but of course that is no longer possible, so I have to look into the open source options.
I basically want to perform an non-linear mixed integer problem in which I will minimized a certain ratio. The problem itself is setting up a power purchase agreement (PPA) in a renewable energy scenario. Depending on the electricity generated, you will have to either buy or sell electricity acording to the PPA.
The only starting data is the generation; the PPA is the main decision variable, but I will need others. "buy", "sell", "b1" and "b2" are unknown without the PPA value. These are the equations:
Equations that rule the problem (by hand).
Using pyomo, I was trying to set up the problem as:
# Dataframe with my Generation information:

January = Data['Full_Data'][(Data['Full_Data']['Month'] == 1) & (Data['Full_Data']['Year'] == 2011)]

Gen = January['Producible (MWh)']
Time = len(Generacion)
M=100
# Model variables and definition:

m = ConcreteModel()
m.IDX = range(time)
m.PPA = Var(initialize = 2.0, bounds =(1,7))
m.compra = Var(m.IDX, bounds = (0, None))
m.venta = Var(m.IDX, bounds = (0, None))
m.b1 = Var(m.IDX, within = Binary)
m.b2 = Var(m.IDX, within = Binary)

And then, the constraint; only the first one, as I was already getting errors:
m.b1_rule = Constraint(
    expr = (((Gen[i] - PPA)/M for i in m.IDX)  <= m.b1[i])
 )

which gives me the error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-5d5f5584ebca> in <module>
      1 m.b1_rule = Constraint(
----> 2     expr = (((Generacion[i] - PPA)/M for i in m.IDX)  <= m.b1[i])
      3  )

pyomo\core\expr\numvalue.pyx in pyomo.core.expr.numvalue.NumericValue.__ge__()

pyomo\core\expr\logical_expr.pyx in pyomo.core.expr.logical_expr._generate_relational_expression()

AttributeError: 'generator' object has no attribute 'is_expression_type'

I honestly have no idea what this means. I feel like this should be a simple problem,  but I am strugling with the syntax. I basically have to apply a constraint to each individual data from "Generation", there is no sum involved; all constraints are 1-to-1 contraints set so that the physical energy requirements make sense.
How do I set up the constraints like this?
Thank you very much

A: You have a couple things to fix.  First, the error you are getting is because you have "extra parenthesis" around an expression that python is trying to convert to a generator.  So, step 1 is to remove the outer parenthesis, but that will not solve your issue.
You said you want to generate this constraint "for each" value of your index.  Any time you want to generate copies of a constraint "for each" you will need to either do that by making a constraint list and adding to it with some kind of loop, or use a function-rule combination.  There are examples of each in the pyomo documentation and plenty on this site (I have posted a ton if you look at some of my posts.)  I would suggest the function-rule combo and you should end up with something like:
def my_constr(m, i):
    return m.Gen[i] - m.PPA <= m.b1[i] * M
m.C1 = Constraint(m.IDX, rule=my_constr)


text:
Q: Stopping overscroll / bounce in Phonegap IOS I am using the latest version of Phonegap on IOS (ipad) and I can't seem to disable the vertical overscroll/bounce on the whole app. I don't mind it on inner elements but it looks rather strange when you swipe up or down and the whole app bounces up and down.
I've tried setting UIWebViewBounce to no in the .plist however that doesn't seem to have done anything.
Appreciate the help :)

A: If you're adding <preference name="DisallowOverscroll" value="true"/> to config.xml without any luck, you may be changing the wrong file. Instead, search the entire phonegap directory for "DisallowOverscroll." You should find several instances. Change those to true.
Cheers.

A: In config.xml of your project, under preferences for iOS set DisallowOverscroll to true. By default it is false which makes whole view to scroll along with inner elements of the view.
<preference name="DisallowOverscroll" value="true" />

A: If nothing else works, try to remove -webkit-overflow-scrolling: touch from your css...if you had it!

A: Use this way:-
function disallowOverscroll(){
  $(document).on('touchmove',function(e){
    e.preventDefault();
  });
  $('body').on('touchstart','.scrollable',function(e) {
    if (e.currentTarget.scrollTop === 0) {
      e.currentTarget.scrollTop = 1;
    } else if (e.currentTarget.scrollHeight
              === e.currentTarget.scrollTop
                  + e.currentTarget.offsetHeight) {
      e.currentTarget.scrollTop -= 1;
    }
  });
  $('body').on('touchmove','.scrollable',function(e) {
    e.stopPropagation();
  });
}
disallowOverscroll();

For more details or Tips & Tricks, please read this article click

A: In config.xml of your project, under preferences for iOS set DisallowOverscroll to true.
<preference name="DisallowOverscroll" value="true" />

A: There is a way I used to achieve this. but it's not conventional because it's dealing with native coding. In the MainViewController there is a method named webViewDidFinishLoad. Include this
theWebView.scrollView.bounces= NO;
inside that method.
- (void)webViewDidFinishLoad:(UIWebView*)theWebView
{
    // Black base color for background matches the native apps
    theWebView.backgroundColor = [UIColor blackColor];
    theWebView.scrollView.bounces= NO;
    return [super webViewDidFinishLoad:theWebView];
}

As this is ios native code this'll work in any phonegap/cordova distribution.

A: Thanks For All answer. But If you have issue in windows Phone here is the solution.
Just go to MainPage.xaml.cs file and replace below function..
public MainPage()
    {
        InitializeComponent();
        this.CordovaView.DisableBouncyScrolling = true;
        this.CordovaView.Loaded += CordovaView_Loaded;
    }

Its works for me :)

A: The accepted answer did not work for me, I had to set UIWebViewBounce to false:
<preference name="UIWebViewBounce" value="false" />

A: You have to modify a property in your config.xml file.
Just set the following preference to true
<preference name="DisallowOverscroll" value="true" />

A: I had a similar issue, but couldn't fix it with all solutions I found so far (like editing config.xml).
But finally, simply editing the body's CSS property then it fixed:
html,body
{
  overflow: auto;
  height:100%;
}

A: Try This One If you are ionic framework user Abc.html file inside content.
<ion-content has-bouncing="false">

A: now for phonegap 3.0 above version use below syntex in config.xml file and it will works 100%
<preference name="DisallowOverscroll" value="true"/>

A: Use this:
<preference name="UIWebViewBounce" value="false" />

A: this is what worked for my app running phonegap 3.0:
add the following line to config.xml
<preference name="webviewbounce" value="false"/>

A: This worked for me. Try adding this code in config.xml file of your phonegap app:
<preference name="DisallowOverscroll" value="true">

A: It is better to modify two elements in config.xml as follows:
<preference name="DisallowOverscroll" value="true"/>
<preference name="UIWebViewBounce" value="false" />

A: For Cordova 7 and an iPhone 7 + iOS 11.0.3, modifying the root-directory config.xml and adding this worked beautifully:
<platform name="ios">
    <preference name="DisallowOverscroll" value="true" />
    <preference name="UIWebViewBounce" value="false" />
    ... (other stuff) ...
</platform>

A: Open xCode -> find and click on config.xml from left menu-> and change  DisallowOverscroll value false to true
Or use this code by replacing previous.
 <preference name="DisallowOverscroll" value="true" />

A: After update the the config.xml I had not luck, if that is your case try this.
For iOS works on iPhone + iOS 11, on CDVThemeableBrowser.m file, set property as YES:
self.disallowoverscroll = YES;

A: DisallowOverscroll does not work for me.
Solution is to ensure that there is nowhere to scroll.
For example, in my case it was div wider (it can be higher) than the body like below:

something

Now, above div is 5% bigger than body that cause scrolling. Set width to 90% fixes the issue.


text:
Q: LaunchOniOSDevice Task failing I have an app that I am working on with the Gluon Framework and everytime I try to run the launchiOSDevice task, it fails with an IndexOutOfBounds = -1 Exception. The stack trace is as follows. I am attempting to incorporate the library RichTextFx:
https://github.com/TomasMikula/RichTextFX
Into a Gluon mobile app
Gradle File :
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.2.0'
    }
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'eon.tachyon.core.Eon'

dependencies {
    compile 'com.gluonhq:charm:4.3.1'
    compile files('libs/richtextfx-fat-0.6.10.jar')
}

jfxmobile {
    downConfig {
        version = '3.2.4'
        // Do not edit the line below. Use Gluon Mobile Settings in your project context menu instead
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }
    android {
        manifest = 'src/android/AndroidManifest.xml'
    }
    ios {
        arch = "arm64"
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

Code :
import com.gluonhq.charm.down.Platform;
import eon.tachyon.core.Eon;
import eon.tachyon.core.Script;
import javafx.geometry.Pos;
import javafx.scene.layout.BorderPane;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.LineNumberFactory;

/**
 *
 * @author aniket
 */
public class CodeTab extends ScriptTab {

    private final BorderPane center;
    private final CodeArea area;

    public CodeTab(Script scr) {
        super(scr);
        setContent(center = new BorderPane());
        center.setCenter(area = new CodeArea());
        area.setMinHeight(Eon.application.getHeight()/2);
        area.setStyle("-fx-text-fill:white;");
        area.setParagraphGraphicFactory(LineNumberFactory.get(area));
        BorderPane.setAlignment(center, Pos.TOP_CENTER);
        if (!Platform.isDesktop()) {
            area.focusedProperty().addListener((ob, older, newer) -> {
                if (newer) {
                    center.setCenter(null);
                    center.setTop(area);
                } else {
                    center.setTop(null);
                    center.setCenter(area);
                }
            });
        }
    }

}

Issue 1
Requested project: /Users/aniket/NetBeansProjects/Eon
Stack trace:
org.gradle.tooling.BuildException: Could not execute build using Gradle distribution 'https://services.gradle.org/distributions/gradle-2.14.1-all.zip'.
    at org.gradle.tooling.internal.consumer.ExceptionTransformer.transform(ExceptionTransformer.java:51)
    at org.gradle.tooling.internal.consumer.ExceptionTransformer.transform(ExceptionTransformer.java:29)
    at org.gradle.tooling.internal.consumer.ResultHandlerAdapter.onFailure(ResultHandlerAdapter.java:41)
    at org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:57)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
    at org.gradle.tooling.internal.consumer.DefaultBuildLauncher.run(DefaultBuildLauncher.java:77)
    at org.netbeans.gradle.project.tasks.AsyncGradleTask.runBuild(AsyncGradleTask.java:371)
    at org.netbeans.gradle.project.tasks.AsyncGradleTask.doGradleTasksWithProgressIgnoreTaskDefCancel(AsyncGradleTask.java:494)
    at org.netbeans.gradle.project.tasks.AsyncGradleTask.doGradleTasksWithProgressIgnoreTaskDefCancel(AsyncGradleTask.java:404)
    at org.netbeans.gradle.project.tasks.AsyncGradleTask.doGradleTasksWithProgress(AsyncGradleTask.java:395)
    at org.netbeans.gradle.project.tasks.AsyncGradleTask.access$400(AsyncGradleTask.java:86)
    at org.netbeans.gradle.project.tasks.AsyncGradleTask$BuildExecutionItem$1.run(AsyncGradleTask.java:776)
    at org.netbeans.gradle.project.tasks.GradleDaemonManager.runBlockingGradleTask(GradleDaemonManager.java:51)
    at org.netbeans.gradle.project.tasks.GradleDaemonManager.access$200(GradleDaemonManager.java:22)
    at org.netbeans.gradle.project.tasks.GradleDaemonManager$2.execute(GradleDaemonManager.java:128)
    at org.jtrim.concurrent.AbstractTaskExecutorService$FunctionWrapper.execute(AbstractTaskExecutorService.java:270)
    at org.jtrim.concurrent.AbstractTaskExecutorService$TaskOfAbstractExecutor.execute(AbstractTaskExecutorService.java:340)
    at org.jtrim.concurrent.Tasks$RunOnceCancelableTask.execute(Tasks.java:342)
    at org.jtrim.concurrent.ThreadPoolTaskExecutor$ThreadPoolTaskExecutorImpl$QueuedItem.runTask(ThreadPoolTaskExecutor.java:1213)
    at org.jtrim.concurrent.ThreadPoolTaskExecutor$ThreadPoolTaskExecutorImpl$Worker.executeTask(ThreadPoolTaskExecutor.java:1049)
    at org.jtrim.concurrent.ThreadPoolTaskExecutor$ThreadPoolTaskExecutorImpl$Worker.run(ThreadPoolTaskExecutor.java:1179)
    at org.jtrim.concurrent.ThreadPoolTaskExecutor$ThreadPoolTaskExecutorImpl$Worker$1.run(ThreadPoolTaskExecutor.java:998)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.internal.exceptions.LocationAwareException: Execution failed for task ':launchIOSDevice'.
    at org.gradle.initialization.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:74)
    at org.gradle.initialization.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:47)
    at org.gradle.initialization.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:100)
    at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:92)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:92)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:83)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:99)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:46)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:58)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:48)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
    at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:81)
    at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:46)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:52)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:237)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':launchIOSDevice'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:153)
    at org.gradle.internal.Factories$1.create(Factories.java:22)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:53)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:150)
    at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
    at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:98)
    ... 42 more
Caused by: org.robovm.compiler.CompilerException: java.lang.ArrayIndexOutOfBoundsException: -1
    at org.robovm.compiler.plugin.lambda.LambdaPlugin.transformMethod(LambdaPlugin.java:242)
    at org.robovm.compiler.plugin.lambda.LambdaPlugin.beforeClass(LambdaPlugin.java:89)
    at org.robovm.compiler.ClassCompiler.compile(ClassCompiler.java:681)
    at org.robovm.compiler.ClassCompiler.compile(ClassCompiler.java:292)
    at org.robovm.compiler.AppCompiler.compile(AppCompiler.java:310)
    at org.robovm.compiler.AppCompiler.compile(AppCompiler.java:393)
    at org.robovm.compiler.AppCompiler.compile(AppCompiler.java:453)
    at org.robovm.compiler.AppCompiler.build(AppCompiler.java:776)
    at org.robovm.compiler.AppCompiler$build.call(Unknown Source)
    at org.javafxports.jfxmobile.plugin.ios.task.BaseIosTask.compile(BaseIosTask.groovy:185)
    at org.javafxports.jfxmobile.plugin.ios.task.IosDevice.iosDevice(IosDevice.groovy:38)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:228)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:221)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:210)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:621)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:604)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 70 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: -1
    at org.robovm.compiler.plugin.lambda.LambdaClassGenerator.pushArguments(LambdaClassGenerator.java:203)
    at org.robovm.compiler.plugin.lambda.LambdaClassGenerator.createForwardingMethod(LambdaClassGenerator.java:134)
    at org.robovm.compiler.plugin.lambda.LambdaClassGenerator.generate(LambdaClassGenerator.java:79)
    at org.robovm.compiler.plugin.lambda.LambdaPlugin.transformMethod(LambdaPlugin.java:180)
    ... 88 more


text:
Q: Why is my hover only working on some of the polygon/path edges? I have a svg that I want to highlight a path/polygon on hover.  Here is my html:

svg {
  border: 1px solid #c00;
}
svg polygon:hover {
  fill:  rgba(73,143,226,0.80);
}
 <svg version="1.1" x="0px" y="0px" viewBox="0 0 2986 886" enable-background="new 0 0 2986 886">
      <polygon fill="none" stroke="#000000" strokeWidth="0.25" stroke-miterlimit="10" points="2289.1,543.6 2632.4,599 2546.8,421.2
        2183.8,302.3 " id="15"></polygon>
      <polygon fill="none" stroke="#000000" strokeWidth="0.25" stroke-miterlimit="10" points="2182.9,300.3 2545.8,419.2 2426,170.2
        2148.2,0 2035.7,-1 " id="22"></polygon>
        ...
        ...
    </svg>

On the first polygon, the hover fill gets added on hover.  On the second polygon I have to run the mouse along the edge of the polygon to get the hover to work.  What can I do to make the hover always work?


text:
Q: Fact to Fact Relationship I have two fact tables:
1. FactPOLine: it has all the PO lines.
2. FactInvoiceLines: it has all the invoice lines.
There is a one-to-many relationship between invoice and po.  i.e. each invoice line can have only one po line, but a po line can have multiple invoice lines.
How do I model this relationship? I think connecting two facts is not recommended.
Thank you.

A: Fact tables are joined for analysis by the dimensions that they have in common.  For example, FactPOLine and FactInvoiceLines might both have keys to the following dimensions:

*

*Item / Product

*Customer

*Supplier

*Carrier

*Date

Date is a special case in which their might be multiple dates associated with each line.  However, it makes analysis much easier if you can cut by one primary date for each table so that you can analyze both by year, quarter, month.
Lastly, it may be useful to add a junk dimension to hold the po number and line and link both tables to it.  In that case, a user could analyze by PO.  This is helpful for more operational type reports.
EDIT:
In your comments you note that business wants to analyze by PO.  This probably makes sense if the company only has a handful of POs per year.  However, it is more likely the case that they have thousands, ten of thousands or more and this makes it very unwieldy to for detailed analysis.
I suggest asking the 5 whys and trying to discover their goals.  i.e. Why do you want to analyze by PO?  Why do you want to see all the data?  Why do you want to see those unfilled POs? ...
Eventually, you'll arrive at some hard measures that you can add to your reports and data models.  Things like a flag for open PO lines, or a semi-additive measure for % complete.  Whatever it is that their after, you can probably get them exactly what they need rather than 1000 page report by PO line.

A: I believe that would be referred to as a degenerate dimension.  The perfect example is purchase order or invoice numbers.  All of the po attributes are associated with other dimension, except the PO #.  These numbers feel like a dimension attribute, but they don't exist until the fact event occurs.  They belong in the fact table, but will be used to create a new dimension containing a single attribute.  All of the other attributes will still exist in the other analytical dimensions.
http://www.kimballgroup.com/2003/01/fact-tables-and-dimension-tables/
http://www.kimballgroup.com/2003/06/design-tip-46-another-look-at-degenerate-dimensions/
http://www.kimballgroup.com/2007/10/design-tip-95-patterns-to-avoid-when-modeling-headerline-item-transactions/

A: These IDs can both be modelled as 'degenerate dimensions' in the fact table itself as per the answer from Wes.
You can just plonk the POLine # alongside the InvoiceLine # in the InvoiceLine table for those situations where you have to join on those IDs.
You might even get away with having a fact table surrogate key in POLIne which you can use in InvoiceLine as a foreign key. It isn't perfect, but its practical.
Mark is correct that you normally link via dimensions rather than via such IDs, but the kind of linkages you describe are acceptable in dimensional modelling when needed.


text:
Q: "Function evaluation disabled because a previous function evaluation timed out." - in vs2012 Recently I started working on VS2012.
When I debug my code (this is a SharePoint 2013 application) and trying to get the value of variables - I get again and again the message:
Function evaluation disabled because a previous function evaluation timed out.
You must continue execution to reenable function evaluation.

I previously worked in visual studio 2010 (for SharePoint 2010 applications) and almost never got this message while trying to get the value of variables in the Quick Watch.
I Googled the error message, and I saw that the problem occurs when trying to get a value of functions whose action takes a long time,
But I'm not trying to get a value of functions, only variables, and yet I get this error.
I do not always get the error on the same variables, but random - each time different variables.
Is anyone else having this problem specifically in VS2012?
And how can I get rid of it?

A:
Why this is happening ?

It seems this kind of bug can happen simply when you are trying to watch at some variables who have to be thread safe but sometimes this framework implementation is not perfect....
To avoid this problem : when stepping through code where variables are bound to windows or other controls, you don't show local variables or "auto" variables.  Look at such things only when you are sure your variables are all safe to look at.  And note that the error doesn't necessarily appear on the unsafe variables. Use the "immediate" window on safe (i.e. non-control) variables when operating in dangerous code.
Data accessors should always be thread safe. But sometimes between two implementations (let's say between Sharepoint 2010 and Sharepoint 2012 or two version of the .NET framework), this rules is sometimes not true... There is some examples between VS2003 and 2005...

How can I increase the timeout ?

You can increase the timeout by changing the values of the registry Key HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Debugger using RegEdit.
Don't forget to restart Visual Studio after changing the registry key.


text:
Q: Error in sum(x[i:(i + 50)], na.rm = TRUE) : invalid 'type' (character) of argument I am new in R , and I am trying to do a script to calculate the sliding mean of some data.
This is how my data looks like:
Timestamp        Accelerometer X Accelerometer Y Accelerometer Z

1 121219.757080078 -5.66180946541818 8.85684119781125  1.65407075345669
2 121239.288330078 -7.38255951126451 9.4117333531527   1.44410517346543
it has around 6000 rows, and I need to calculate the mean of Accelerometer x, Accelerometer Y, and Accelerometer Z each fifty rows. So from the data of row 1 to 50 I must get the mean of the 3 variables, then from rows 51 to 100, and so on until row 6000.
I tried with (for the first variable):
library(reshape2)
library(reshape)
x <- deadlift$`Accelerometer X`
win.size <- 50
slide <- 50
results <- data.frame(index=numeric(),win.mean=numeric())
i<-1
j<-1
while (i<length(x)) {
  win.mean<-sum(x[i:(i+50)],na.rm = TRUE)/win.size
  results[j,]<-c(i,win.mean)
  i<-i+slide
  j<-j+1
}

but I get this message:
Error in sum(x[i:(i + 50)], na.rm = TRUE) :
  invalid 'type' (character) of argument
any help?
Thank you.

A: Problem solved.
the problem was that the object x was created as character. I converted it to numeric with as.numeric.
It worked.
Regards,


text:
Q: Could not Execute the Chromdriver from the Docker ( /usr/local/bin/chromedriver ) I am trying to execute the chrome driver from the docker container but did not succeed with the process, so far I did the following.

*

*Implement the Microsoft Azure Functions

*Implement the Dockerfile

*Running a docker container successfully

Python File
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request. 11:38')

    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    path_to_chrome=os.path.join(os.getcwd(),'/usr/local/bin/chromedriver')

    driver = webdriver.Chrome(executable_path=path_to_chrome, chrome_options=chrome_options)

Dockerfile
FROM mcr.microsoft.com/azure-functions/python:3.0-python3.8

# 0. Install essential packages
RUN apt-get update \
    && apt-get install -y \
        build-essential \
        cmake \
        git \
        wget \
        unzip \
    && rm -rf /var/lib/apt/lists/*

# 1. Install Chrome (root image is debian)
# See https://stackoverflow.com/questions/49132615/installing-chrome-in-docker-file
ARG CHROME_VERSION="google-chrome-stable"
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
  && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list \
  && apt-get update -qqy \
  && apt-get -qqy install \
    ${CHROME_VERSION:-google-chrome-stable} \
  && rm /etc/apt/sources.list.d/google-chrome.list \
  && rm -rf /var/lib/apt/lists/* /var/cache/apt/*

# 2. Install Chrome driver used by Selenium
RUN LATEST=$(wget -q -O - http://chromedriver.storage.googleapis.com/LATEST_RELEASE) && \
    wget http://chromedriver.storage.googleapis.com/$LATEST/chromedriver_linux64.zip && \
    unzip chromedriver_linux64.zip && ln -s $PWD/chromedriver /usr/local/bin/chromedriver

ENV PATH="/usr/local/bin/chromedriver:${PATH}"

# 3. Install selenium in Python
RUN pip install -U selenium

# 4. Finally, copy python code to image
COPY . /home/site/wwwroot

# 5. Install other packages in requirements.txt
RUN cd /home/site/wwwroot && \
    pip install -r requirements.txt

A: Check whether chromedriver is in that path or not
To check open CMD and type chromedriver (assuming your chromedriver executable is still named like this) and hit enter  if Starting ChromeDriver 2.15.322448 is appearing, the PATH is set appropriately
Alternatively you can use a direct path to the chromedriver like this:
driver = webdriver.Chrome('/path/to/chromedriver')

So in your specific case:
driver = webdriver.Chrome("C:/Users/Username/Downloads/chromedriver_win32/chromedriver.exe")

Also, you need to install selenium packages
try installing the Alpine compatible version of chromedriver, available in Alpine repositories, using apk add chromium-chromedriver:
https://pkgs.alpinelinux.org/package/v3.9/community/x86_64/chromium-chromedriver


text:
Q: 302 Redirect from CGI script stopped working in Apache 2.4 I inherited maintenance of a self-written CGI application without
documentation and have never met the original author. The application
stopped working in Debian 8, but worked in Debian 7 and CentOS 5. The
main changes were the upgrade from Apache 2.2 (used by Debian 7 &
CentOS 5) to Apache 2.4 (used by Debian 8) and the upgrade from perl
5.8 (in CentOS 5) respectively perl 5.14 (in Debian 7) to perl 5.20.
The problematic part boils down to the following script (a
302-redirect):
#!/usr/bin/perl
$|=1; # activate auto-flushing of stdout
use strict;
use warnings;
my $CRLF = "\015\012";
print STDOUT "Status: 302 Moved Temporarily$CRLF" .
             "Location: /does_not_matter$CRLF" .
             "URI: /does_not_matter$CRLF" .
             "Connection: close$CRLF" .
             "Content-type: text/html; charset=UTF-8$CRLF$CRLF";
close STDOUT;
while(1) {
        sleep 1;
}

The observed behavior is that the redirect never reaches the client
as long as the script is still running when used with Apache 2.4, but
there is no error message in Apache's error.log. I changed the client
(Firefox, Chromium, wget), the Apache module (mod_cgid & mod_cgi),
sent additional headers, removed the close STDOUT, removed the
$|=1, replaced the $CRLF with \n and made the script
fork and exit the parent process (so that Apache is no longer the
parent process), all to no avail. The only things that worked: use
Apache 2.2, turn the script into an NPH-CGI-script (which has to send
complete HTTP headers that Apache will not modify in any way, even if
they contain errors), make the script exit instead of entering an
endless loop. I confirmed via tcpdump that the packages with the
redirect indeed never leave the server before the script is killed.
And from the Date-line in the response and the time of the eventual
arrival I gather that Apache receives my output immediately (&
immediately adds the Date-line to the headers), but does not send the
response to the client.
Don't bother answering, I already figured the solution out by myself
and will write an answer. I just want to make the solution available
to others who might encounter the same problem.

A: The problem was the missing message body. A 302 redirect may contain
a message body (see RFC 2616, section 4.3 (Message Body): "All other
responses do include a message-body, although it MAY be of zero
length"), but a Content-Length-line is optional (section 4.4 of RFC
2616 says the message body length can be determined by closing the
connection if the Content-Length-line is missing). Since Apache can
not know whether I want to send a message body or not, it has to wait
until I close the connection or actually send the message body
(Apache 2.2 apparently behaved erroneously here by not waiting for
the message body - or maybe close STDOUT; does not do in perl
5.20 what it did in older perl versions). The correct script should
therefore look like this (verified to work both in Apache 2.2 and in
Apache 2.4) - the only difference is an additional $CRLF which
terminates a zero-length message body:
#!/usr/bin/perl
$|=1; # activate auto-flushing of stdout
use strict;
use warnings;
my $CRLF = "\015\012";
print STDOUT "Status: 302 Moved Temporarily$CRLF" .
             "Location: /doesNotMatter$CRLF" .
             "URI: /doesNotMatter$CRLF" .
             "Connection: close$CRLF" .
             "Content-type: text/html; charset=UTF-8$CRLF$CRLF$CRLF";
close STDOUT;
while(1) {
        sleep 1;
}

It was https://stackoverflow.com/a/8062277/2845840 that pointed me in the right direction.


text:
Q: Configure a joystick in ubunntu 20.04 I have a 0079-0006-DragonRaise Inc Generic USB Joystick. It is being recognised by my ubuntu 20.40. On testing with jstest-gtk I found a very odd problem

*

*BUTTON_TRIGGER is not recognised

*Axis 2 is also invoking Buttons 0 and 2 in addition to their original actions

*Axis 3 is just invoking Buttons 1 and 3

*BASE buttons are invoking Axises 0 and 1

Is this a problem with my drivers?

A: This is a problem with my Gamepad. My drivers are fine.

A: Hardware with vendor ID 0x0079 and product ID 0x0006 is usually a generic USB HID gamepad (sometimes called "PC TWIN SHOCK Gamepad"), often with DualShock 2 styling but sometimes with a completely different form factor like this arcade joystick thing. Since the product can't be uniquely identified from the device IDs, it would be helpful if you could edit your question to include a link to a product page showing an image of the device you're trying to use.
HID gamepads technically don't need a driver, but the inputs may not be correctly mapped in games if they don't use the same keycodes described in the Linux Gamepad Specification. Devices with IDs 0076:0006 are handled in the dragonrise module, which seems to do some weird remapping that might cause the behavior you're seeing.
You might have some luck disabling the dragonrise module so the gamepad is handled by the default HID gamepad driver. Force feedback probably won't work but the mapping might be more correct.


text:
Q: Switching to local update server has slowed down my update process I have Ubuntu 14.04. I have just changed the server settings to the server in my country. Since then, my Ubuntu updates have become very slow. Why is this? And how can I speed it up?

A: I highly recommend that you use the source server marked as "Main Server". The connection speed to the local server would vary from country to country.
Another possible solution is to choose the "Other" option, then select "Select Best Server". This will make Ubuntu test the connection speed of all the servers and choose the best one.
Lastly, you can select a "First World" server given that they usually have better Internet connection speeds.

A: you probably changed the location where APT is taking the sources from.
you can change your sources.list located here :  /etc/apt/sources.list
an easier way is probably to change the software sources directly in UI of Software Center.

*

*open software center

*click Edit on top and select software sources

*select server where to take sources from


text:
Q: ¿Es el SHH mas seguro que HTTPS para enviar commits en github? En el curso de git/github el profesor dijo que SSH es más seguro que HTTPS y no lo dudo porqué lo investigue, pero veo que al configurar la SHH github ya no me pide contraseña para hacer push ¿esto no es peligroso?

A: Dos cosas:

*

*Yo no diría que es más seguro SSH que HTTPS. Ambos son protocolos de transporte cifrados. Durante la comunicación entre cliente y servidor, tanto tus credenciales como los datos del repositorio están a salvo de miradas indiscretas. Usar SSH tiene alguna ventaja, pero también inconvenientes (más adelante me explico)

*No temas porque no te pida la contraseña. Cuando usas SSH tu contraseña de github no juega ya ningún papel, ya que te estás identificando por otro mecanismo, basado en tu pareja de claves privada/pública. No obstante, el hecho de que no te pida ningún tipo de frase de paso, indica que tu clave privada no está protegida, lo que sí puede ser un riesgo (más adelante me explico).

Sobre SSH frente a HTTPS
Los principales inconvenientes de SSH sobre HTTPS son:

*

*Es más complejo de configurar (tienes que crear una pareja de claves con ssh-keygen, subir la parte pública al servidor, etc)

*En algunas organizaciones el tráfico ssh está bloqueado, y no podrías en ese caso hacer push/pull/clone desde ese sitio. HTTPS en cambio suele estar siempre permitido.

La principal ventaja es:

*

*No te pide contraseñas, sin que por ello haya riesgo de seguridad si todo está correctamente configurado
Sobre las contraseñas y frases de paso
Cuando te autenticas por HTTPS, git te pide tu nombre de usuario y tu contraseña, y envía ambas a Github. Los servidores de Github verifican que ese usuario existe, y que la contraseña enviada es correcta, y entonces dan acceso al repositorio en cuestión.
Esto implica que los servidores de Github tienen que tener guardada de algún modo tu contraseña, para poder compararla con la git envía. Esto plantea un pequeño riesgo de seguridad, y es que los archivos donde se guardan las contraseñas de los usuarios puedan ser "robados" por terceros. Usualmente estos archivos no contienen las contraseñas en "texto claro", sino que contienen hashes criptográficos de las contraseñas a partir de las cuales es imposible recuperar las originales, pero un atacante podría dar con las contraseñas de un usuario por fuerza bruta, generando contraseñas habituales, calculando sus hashes y comparando éstos con los almacenados por Github.
En cualquier caso, antes de eso el atacante debería haber conseguido acceso a los ficheros de contraseñas de Github, lo que ya en principio debería ser complejo. El problema aquí básicamente es que estás confiando en otros (en Github) para que protejan bien tus contraseñas.
Usando SSH, no necesitas confiar en nadie, porque lo que se guarda en Github en este caso es la parte pública de una pareja de claves, mientras que la parte secreta queda en tu ordenador (y tú eres entonces el responsable de la seguridad de ella). Un atacante que consiga tu clave pública de Github no puede hacer nada con ella sin tener la correspondiente parte privada, que está en tu computador.
No obstante, si el atacante consiguiera entrar en tu ordenador y robara tu parte privada, entonces podría usarla para modificar tus repositorios, leerlos, cambiarlos o borrarlos. Para protegerte de esta eventualidad, cuando creas la pareja de claves con ssh-keygen debes suministrar una frase de paso. Esta frase de paso se usa para proteger la parte privada de la clave. Gracias a ella, aún si un atacante te roba el archivo con la parte privada de la clave, no podrá usarlo sin conocer la frase de paso, y esta no está almacenada en ningún lugar, salvo en tu cabeza.
Naturalmente, usar una frase de paso para proteger la parte privada es lo recomendable. Pero al hacerlo perdemos una de las ventajas de usar ssh, y es la de que no nos pida la contraseña. Fíjate que te pediría una, si bien no sería tu contraseña de github, sino la frase de paso que protege tu clave privada. Si te resulta molesto tener que teclear esa frase de paso cada vez que haces push/pull, puedes usar un agente (ssh-agent) que es un proceso que mantiene en RAM tu clave privada, y que te pide la frase de paso una sola vez y luego la recuerda.
Nota final Aún usando SSH para tus comunicaciones con Github a través del comando git, no evitas tener una contraseña en Github, ya que esta la necesitas de todas formas para acceder a través de su interfaz Web. La única forma de evitarlo es registrarse en Github usando algún proveedor OAuth, como Google. En ese caso Github no necesita mantener ninguna contraseña tuya (pero la mantendrá Google, al final en alguien tienes que confiar).


text:
Q: any nginx API to write my log to access_log? I install a http module so that my postinitialize function will be called once configuration is loaded. I want to write something in the function to access_log file so that the data can be processed with access log data together.
Does nginx provide API to write something to the access log file ?

A: Do you mean something like this?
http://nginx.org/en/docs/dev/development_guide.html#logging


text:
Q: How to disable submit button after click Im currently working on an extension where I currently have a submit button and input. When a user is clicking on the submit button, the user should not be able to click on the submit button anymore and should be disabled and if the user has already entered a user ID then it should also not be able to click on submit again.
How can I be able to disable the submit button when a user has clicked it or has already clicked it before using my code below?
popup.js
function get_discord_id(callback) {
    chrome.storage.sync.get(["discord_id"], (result) => {
        callback(result.discord_id);
    });
}

function set_discord_id(discord_id) {
    chrome.storage.sync.set({ discord_id: discord_id }, () => {});
}

window.addEventListener("DOMContentLoaded", () => {
    // console.log(`Testing: ${input.placeholder}`)
    // check if discord ID is already stored
    get_discord_id((discord_id) => {
        console.log(`Console test:`);
        if (discord_id != null) {
            let input = document.getElementById("discord-id-input");
            input.value = "";
            input.placeholder = discord_id;
        }
    });

    document.getElementById("discord-id-button").addEventListener("click", () => {
        let input = document.getElementById("discord-id-input");
        let value = input.value;
        input.value = "";
        input.placeholder = value;

        chrome.runtime.sendMessage({ discord_id: value }, function(response) {
            // console.log(response.discord_id);
        });

        set_discord_id(value);
        e.target.disabled = "true";
    });
});

HTML
<!DOCTYPE html>

    <link rel="stylesheet" href="../css/style.css">

            <input type="text" id="discord-id-input" name="discord-id-input" placeholder="Discord ID">
            <button id="discord-id-button" type="submit" class="submit"></button>
            ENTER DISCORD USER ID AND SUBMIT

CSS
#discord-id-button {
    box-shadow: 0 0 10px 0 #251431;
    border-radius: 8px;
    transition: 0.3s;
}

#discord-id-button:hover {
    box-shadow: 0 0 10px 6px #251431;
}

#discord-id-input {
    box-shadow: 0 2px 1px 0 #251431;
    border-radius: 8px;
}

body {
    background-image: url('../images/bg2.jpg');
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    height: 250px;
    padding: 5px 15px 30px 15px;
    width: 500px;
}

.text-center {
    text-align: center;
}

*:focus {
    outline: none;
}

.form-control {
    align-items: center;
    display: flex;
    justify-content: center;
}

label {
    display: block;
}

select,
input {
    background: #582e79;
    border-radius: 8px;
    border: 1px #582e79;
    color: #999;
    margin-left: 60px;
    margin-top: 135px;
    padding: 5px 10px;
    text-align: center;
    width: 150px;
}

.mt10 {
    margin-top: 20px;
}

.submit {
    background-color: transparent;
    background-image: url("../images/arrow.png");
    background-position: center center;
    background-repeat: no-repeat;
    border: none;
    height: 15px;
    width: 50px;
    margin-left: 15px;
    margin-top: 135px;
    outline: none;
    padding-bottom: 25px;
}

.help-text {
    position: fixed;
    color: #FFFF;
    font-size: 9px;
    color: #999;
    margin-top: 190px;
}

A: You can use
document.getElementById('button').disabled="true";

A: If you want some extra styling for your disabled button you could do this:

*

*add two classes to your html button: enabled and disabled. Then, on click, replace the "disabled" class with the class "enabled" and remove event listener.

If you just want to disable it, ignore the part with the classes and just disable it on click.
Simple fiddle:

const button = document.querySelector("button");
const classes = button.classList;

button.addEventListener('click', handleClick)

function handleClick() {
  //classes.replace('enabled', 'disabled');
  button.disabled = true;
  button.removeEventListener('click', handleClick)
}
.disabled {
  background: #ccc;
}
<button class="enabled"> submit</button>


text:
Q: Parsing the pointers in JSON using python I have the following data in Json which has nested loops. Here the author has a pointer to the className _User.
{ "results": [
{
    "accepted": "YES",
    "author": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": "HZ1c6AmfuE"
    },
    "createdAt": "2014-02-19T22:39:47.899Z",
    "objectId": "t6G5lLaxoR",
    "recipient": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": "avIzy6RtKQ"
    },
    "updatedAt": "2014-02-19T22:40:08.906Z"
},
{
    "accepted": "YES",
    "author": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": "HZ1c6AmfuE"
    },
    "createdAt": "2014-02-20T00:18:40.640Z",
    "objectId": "ZmagKJJVKd",
    "recipient": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": "zw48k1oAw3"
    },
    "updatedAt": "2014-02-20T00:19:17.602Z"
}] }

I use the following code to read the file
json_data = pd.read_json('RelationshipRequest.json')
df = pd.concat([pd.DataFrame.from_dict(item, orient='index').T for item in json_data.results])
print df.author

This prints :
0    {u'className': u'_User', u'__type': u'Pointer'...
0    {u'className': u'_User', u'__type': u'Pointer'...

Is there a way where I can extract objectId from the nested field in author to get the author.objectId = HZ1c6AmfuE
?

A: This is how Python and JSON works:
Either you save that exact content in a file and use:
with open('RelationshipRequest.json', 'r') as fh:
    json_data = json.load(fh)

or you pass it as a string directly yourself:
json_data = json.loads('{ ... }')

Either way, the net result would be (and this is how you access JSON data):
for result in json_data['results']:
    print(result['author']['objectId'])

Python doesn't treat JSON data as objects, like you're used to in JavaScript, it's a dictionary and nothing short of it so treat for what it is is my suggestion.
There's probably some neat trick to convert this into class objects but this is generally how you actually use JSON data in Python.

A: I don't fully understand what you want to accomplish, but if all you want is to extract the objectId fields, then the following code snippet will do that.
import json

with open('RelationshipRequest.json') as f:
    json_data = json.load(f)
    id_list =  [rec['author']['objectId'] for rec in json_data['results']]
    print id_list


text:
Q: Delay displaying a fixed bar, but hide it instantly I currently have the following code which delays showing a fixed bar after a certain point.
The code hides the fixed bar if you scroll up to the top, but automatically shows the bar after 2 seconds, even though the scroll point is below 70, so it should be hidden all together.
    $(window).scroll(function() {
        if($(window).scrollTop() > 70) {
            $('#mini-header').delay(2000).show(0);
        } else if($(window).scrollTop() < 70) {
            $('#mini-header').hide();
        }
    });

A jsFiddle shows the behaivor.

A: You can change your else if to a simple else and hide the div by display: none -
FIDDLE DEMO
$(document).ready(function() {
    $(window).scroll(function() {
            if($(window).scrollTop() > 70) {
                $('#mini-header').delay(2000).show();
            } else {
                $('#mini-header').css("display", "none");
            }
    });
});

UPDATED DEMO
$(document).ready(function() {
    $(window).scroll(function() {
            if ( $(window).scrollTop() > 70 ) {
                $('#mini-header').stop().animate({ opacity:1 }, 2000, function() {
                    $(this).css("display", "block");
                });
            } else {
                $('#mini-header').stop().animate({ opacity:0 }).css("display", "none");
            }
    });
});

The animate() acts like a delay() but the difference - you can stop() it.

A: removing the 0 from show() seems to do the trick. http://jsfiddle.net/the_archer/Ds4Ls/


text:
Q: spring boot execution: org.apache.tomcat.util.scan.StandardJarScanner.setJarScanFilter(Lorg/apache/tomcat/JarScanFilter;V I am new to spring boot and trying to start with a simple project in spring boot, But unable to start the project as Java application and receiving the error message mentioned below,
Project Structure
SpringBootWebApplication.java
package main.java.com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringBootWebApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }

}

WelcomeController.java
package main.java.com.test;

import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WelcomeController {

    // inject via application.properties
    @Value("${welcome.message:test}")
    private String message = "Hello World";

    @RequestMapping("/")
    public String welcome(Map<String, Object> model) {
        model.put("message", this.message);
        return "welcome";
    }

}

welcome.jsp
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

    <link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />

    <c:url value="/css/main.css" var="jstlCss" />
    <link href="${jstlCss}" rel="stylesheet" />

                Spring Boot

Home

About

Spring Boot Web JSP Example

Message: ${message}

Below are the list of Jar's i have added under /WEB-INF/lib
Jar's Added
Receiving the error message when running the project as java application
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.2.RELEASE)

Jun 18, 2018 2:52:41 PM main.java.com.mykong.SpringBootWebApplication logStarting
INFO: Starting SpringBootWebApplication on BR-LL58000 with PID 9864 (C:\Users\tpucchin\workspace\SpringHelloWorld\build\classes started by TPUCChin in C:\Users\tpucchin\workspace\SpringHelloWorld)
Jun 18, 2018 2:52:41 PM main.java.com.mykong.SpringBootWebApplication logStartupProfileInfo
INFO: No active profile set, falling back to default profiles: default
Jun 18, 2018 2:52:41 PM org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext prepareRefresh
INFO: Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@81db25: startup date [Mon Jun 18 14:52:41 BST 2018]; root of context hierarchy
Jun 18, 2018 2:52:42 PM org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is java.lang.NoSuchMethodError: org.apache.tomcat.util.scan.StandardJarScanner.setJarScanFilter(Lorg/apache/tomcat/JarScanFilter;)V
Jun 18, 2018 2:52:42 PM org.springframework.boot.SpringApplication reportFailure
SEVERE: Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is java.lang.NoSuchMethodError: org.apache.tomcat.util.scan.StandardJarScanner.setJarScanFilter(Lorg/apache/tomcat/JarScanFilter;)V
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:536)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175)
    at main.java.com.mykong.SpringBootWebApplication.main(SpringBootWebApplication.java:20)
Caused by: java.lang.NoSuchMethodError: org.apache.tomcat.util.scan.StandardJarScanner.setJarScanFilter(Lorg/apache/tomcat/JarScanFilter;)V
    at org.springframework.boot.context.embedded.tomcat.SkipPatternJarScanner$Tomcat8TldSkipSetter.setSkipPattern(SkipPatternJarScanner.java:107)
    at org.springframework.boot.context.embedded.tomcat.SkipPatternJarScanner.setPatternToTomcat8SkipFilter(SkipPatternJarScanner.java:62)
    at org.springframework.boot.context.embedded.tomcat.SkipPatternJarScanner.<init>(SkipPatternJarScanner.java:57)
    at org.springframework.boot.context.embedded.tomcat.SkipPatternJarScanner.apply(SkipPatternJarScanner.java:88)
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.prepareContext(TomcatEmbeddedServletContainerFactory.java:207)
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:176)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:164)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134)
    ... 8 more

What i am doing wrong here and how to resolve this error?. I have tried the answers avaiable in the previous queries but unable to resolve this.

A: Go to project properties -> project facet --> uncheck tomcat from runtime.

A: I figured out the issue was caused by the tomcat server which i configured for this project, I removed the server from the project and now able to run the project as java application without any issues.