text:
Q: g++ shared library only links in current directory I'm trying to compile a C++ program (on Linux and OS X) with a library that I built in another directory:
$ g++ -I./include -L./lib src/main.cpp -lale -o proj

"ale" is just the library I'm using (libale.so in ./lib/libale.so)
It compiles everything, but when I run it I get the following error:
./proj: error while loading shared libraries: libale.so: cannot open shared object file: No such file or directory

However, it does work if I put libale.so into the same directory as the executable (or add a symlink). I was looking up some solutions, and one suggestion was to set LD_LIBRARY_PATH. However, I would rather link the path directly during compilation. Is there a way to do that?

A: The answer I found was to add the following flag:
-Wl,-rpath=./lib

However, this does not work on OS X. I ended up just using a symlink for the OS X version, but it isn't the optimal solution.


text:
Q: making sense of a very basic inequality proof in an intro analysis textbook This is an excerpt from an Analysis textbook by Jospeh Taylor.
proof from the book
The author gets to line (2.1.1) and writes "If we interchange ...... also holds." I don't understand this step in the proof. Why is the author adding an additional $|b|$ to both sides? Can you explain this section of the proof?
Why can't the author just write something like: $|a|-|b| ≤ |a − b|$ holds for all real $a,b$ and $|a-b|=|b-a|$, therefore $|b|-|a| ≤ |a − b|$. Multiplying by $-1$ we get: $-|a − b| ≤ |a|-|b|$. Finally, $-|a − b| ≤ |a|-|b| ≤ |a − b|$ and therefore $||a|-|b|| ≤ |a − b|$. Note that the very last step is already proven in the text.
can someone help me make sense of the author's argument?

A: Since $|a-b|\geq|a|-|b$, we obtain $|b-a|\geq|b|-|a|$, which says $$|a-b|\geq|a|-|b|$$ and $$|a-b|\geq-(|a|-|b|),$$ which gives $$|a-b|\geq||a|-|b||$$
We used the following.

If $x\geq y$ and $x\geq-y$ so $x\geq|y|.$

This statement you proved in your post: Because it's $-x\leq y\leq x$.
Also, $$|a-b|+|b|\geq|b|-|a|$$ it's typo.
It should be $$|a-b|\geq|b|-|a|.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flyway 5.0.7 non-transactional migrations MS-SQL I'm using flyway 5.0.7 with MS SQL. I would like to turn on full text search on the server via flyway migrations. Problem is that all migrations are wrapped in transactions and its impossible to create fts catalog and index inside user transactions.
Question is: Is it possible to mark manually migration that it should not be executed in transaction?
I've tried to set mixed option to "true" - no results
I've tried to do some tricks with sp_executesql CREATE FULLTEXT CATALOG .. inside stored procedure and execute this stored procedure in migration. But without any affects

A: It's a bug which has been fixed but is not in a release yet. It will be in Flyway 6.0.0 whenever that is released.
In the meantime, you could try the Flyway 6.0.0-beta release

Question is: Is it possible to mark manually migration that it should not be executed in transaction?

I've had a quick look at the code but I can't see a way to override the regex without a code change.


text:
Q: Online search bar values after export from excel not clicking automatically tag identify wrong I am exporting values from two cells online on a webpage which is running correctly. However, I have to manually press enter as Click is not automatically working in ElementbyId tag selection ("locationSearchTextBox").
After wards, I manually press enter and inspect element to import the elevation result back to excel.
I need help in automating these final two steps. I am new in learning about tag classes, id name etc. Probably might be choosing wrong due to ignorance. Help is appreciated.
Sub elevation_finder()
Dim elevation As Long
Dim ieobject As InternetExplorer
Dim htmlElement As IHTMLElement
Dim i As Integer

i = 1

Set ieobject = New InternetExplorer
ieobject.Visible = True
ieobject.navigate "https://www.freemaptools.com/elevation-finder.htm"

Application.Wait Now + TimeValue("00:00:05")

With ActiveWorkbook.Sheets("Header")
    ieobject.document.getElementById("locationSearchTextBox").Value = _
    .Range("B2").Value & "," & .Range("C2").Value

    ieobject.document.getElementById("locationSearchTextBox").Click
    ieobject.document.getElementById("0EGu2eqKt6").Click

End With

End Sub

A: I solved the timing problems with loops. This should do what you want. I have tested it with nearly 2.000 coords in one go. Please read the comments carefully:
Sub ElevationFinder()

'Columns
Const colLat As Long = 2     'Latitude
Const colLon As Long = 3     'Longitude
Const colEleInM As Long = 4  'Elevation in meter
Const colEleInFt As Long = 5 'Elevation in feet

Const url As String = "https://www.freemaptools.com/elevation-finder.htm"

Dim browser As Object
Dim htmlDoc As Object
Dim nodeDropDown As Object
Dim nodeSearchTextBox As Object
Dim nodeSubmitButton As Object
Dim nodeClearMapButton As Object
Dim nodeElevationLabel As Object

Dim tableLongLat As Worksheet
Dim currentRow As Long
Dim coords As String
Dim elevation As String
Dim splitArray() As String
Dim timeout As Double
Dim start As Double

  start = Timer
  Set tableLongLat = Sheets("Header") 'Table with coords
  currentRow = 2 'Start row

  'Jump to first row for visual monitoring
  tableLongLat.Cells(currentRow, 1).Select

  'Initialize Internet Explorer, set visibility,
  'call URL and wait until page is fully loaded
  Set browser = CreateObject("internetexplorer.application")
  browser.Visible = False 'If you want to see what happens in IE, set this to True
  browser.navigate url
  Do Until browser.ReadyState = 4: DoEvents: Loop
  'Manual break to load the map (dynamic content)
  'The last three values are hours, minutes, seconds
  Application.Wait (Now + TimeSerial(0, 0, 5))

  'Shortening the call of the html document
  Set htmlDoc = browser.document

  'Get dropdown for selecting what to search for
  'The default setting is "Latitude,Logitude", but when we switch to another entry,
  'the required "Estimate Elevation" button to send the request appears. After that
  'we switch back to "Latitude,Logitude". The button remains in place
  Set nodeDropDown = htmlDoc.getElementById("locationSearchSelect")

  'Select "Free Text Search" and trigger the change event of the dropdown
  'Triggering is necessary because otherwise the change will not be recognized
  'by the page and the button will not appear
  nodeDropDown.selectedIndex = 5
  Call TriggerEvent(htmlDoc, nodeDropDown, "change")

  'Switch back to "Latitude,Logitude"
  nodeDropDown.selectedIndex = 0
  Call TriggerEvent(htmlDoc, nodeDropDown, "change")

  'Get input field for search text
  Set nodeSearchTextBox = htmlDoc.getElementById("locationSearchTextBox")

  'Get "Estimate Elevation" button
  Set nodeSubmitButton = htmlDoc.getElementById("locationSearchButton")

  'Get the button to clear the map from last set coords
  'There are 5 buttons on the page with the css class "fmtbutton"
  'The third is the button to clear the map (index of a node list begins at 0)
  Set nodeClearMapButton = htmlDoc.getElementsByClassName("fmtbutton")(2)

  'Go through all rows filled with coords
  Do While tableLongLat.Cells(currentRow, colLat).Value <> ""
    'Scroll for visual monitoring
    If currentRow > 14 Then
        ActiveWindow.SmallScroll down:=1
    End If

    'Get coords of current row
    coords = tableLongLat.Cells(currentRow, colLat).Value & "," & tableLongLat.Cells(currentRow, colLon).Value

    'Enter coords to search field
    nodeSearchTextBox.Value = coords

    'Click "Estimate Elevation" button
    nodeSubmitButton.Click

    'Get elevation from label on map
    'The elevation also appears above the search field,
    'but there it is more difficult to read the value
    '
    'Start time for timeout if coordinates are invalid
    timeout = Timer
    '
    'To retrieve multiple elevation information from the map,
    'coordinates must be set and deleted alternately. Since
    'setting coordinates takes different amounts of time and
    'it also takes different amounts of time to delete coordinates
    'from the map, loops are used. These ensure that the shortest
    'possible time periods are used. This has something to do with
    'server communication. The alternative would be to set a blanket
    'pause, which would slow down the macro a lot, because the
    'estimated maximum value would have to be used
    Do
      'At first we try to get the label
      Set nodeElevationLabel = htmlDoc.getElementsByClassName("leaflet-tooltip")(0)
      'Then we try to read out the text
      'If no label was there yet, no text
      'can be read out. Therefore, error
      'handling is temporarily switched off
      On Error Resume Next
      elevation = Trim(nodeElevationLabel.innertext)
      On Error GoTo 0
    'Let the loop run until either a elevation information
    'has been read out or the timeout takes effect
    Loop Until elevation <> "" Or Timer - timeout > 5 'Timeout in seconds

    If elevation <> "" Then
      'Elevation information come as string: 210.0 m / 689.0 feet
      'The two values will be separated
      splitArray = Split(elevation, "/")
      splitArray(0) = Trim(Replace(splitArray(0), "m", ""))
      splitArray(1) = Trim(Replace(splitArray(1), "feet", ""))

      'Write the elevation in meter to the Excel sheet
      tableLongLat.Cells(currentRow, colEleInM).NumberFormat = "#,##0.0 ""m"""
      tableLongLat.Cells(currentRow, colEleInM).Value = splitArray(0)

      'Write the elevation in feet to the Excel sheet
      tableLongLat.Cells(currentRow, colEleInFt).NumberFormat = "#,##0.0 ""ft"""
      tableLongLat.Cells(currentRow, colEleInFt).Value = splitArray(1)

      'Click the clear map button
      nodeClearMapButton.Click
      'The loop mechanism, as explained above
      'No timeout necessary, because the label
      'will be gone in any case
      Do
        Set nodeElevationLabel = htmlDoc.getElementsByClassName("leaflet-tooltip")(0)
      Loop Until nodeElevationLabel Is Nothing
    End If

    'Prepare for next coords
    elevation = ""
    Erase splitArray
    currentRow = currentRow + 1
  Loop

  'Clean up
  browser.Quit
  'MsgBox Timer - start
End Sub

This procedure to trigger the change event:
Private Sub TriggerEvent(htmlDocument As Object, htmlElementWithEvent As Object, eventType As String)

  Dim theEvent As Object

  htmlElementWithEvent.Focus
  Set theEvent = htmlDocument.createEvent("HTMLEvents")
  theEvent.initEvent eventType, True, False
  htmlElementWithEvent.dispatchEvent theEvent
End Sub


text:
Q: Installing Rosetta-dependent software on OS X Lion I've got some old programs that I still need to dip in to from time to time, but they are old Rosetta-dependent software.
Is there a 3rd party install I can do to make my Lion machine be able to run them?

A: You have a few options.

*

*If your Mac came pre-installed with Snow Leopard or earlier, you can simply downgrade your Mac using the installation media. Note that you cannot downgrade a Mac that came with Lion or newer.

*Install an older version of OS X in a virtual machine, using VMWare, VirtualBox, or Parallels. You may need a software license.

*Obvious, but added for completeness. Check if the software in question has an update. Roaring Apps may be able to help you out.

One thing you can not do is simply install Rosetta on your Lion machine. It relies on some old code and kernel extensions which simply do not exist in Lion.


text:
Q: Windows Phone 7.1: Using compression when calling an async SOAP web service I'm trying to use GZip or any other method of compression for consuming a SOAP web service on windows phone 7.1 , but I don't seem to find a way.
I found a library called SharpGIS.GZipWebClient, but the examples don't seem to work with the type of classes generated by Visual Studio 2010 when I add the service reference. I don't seem to find the WebClient class to be able to override GetWebRequest and GetWebResponse like they do on this blog
EDIT: This is the code I'm using to call the service:
private void btnService_Click(object sender, RoutedEventArgs e)
        {
            lblResponse.Text = "... Waiting for service response";
            ConvertSoapClient client = new ConvertSoapClient();

            client.TestCompressionCompleted += new EventHandler<TestCompressionCompletedEventArgs>(TestCompressionCompleted);

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 1000; i++)
                sb.Append("qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm");

            client.TestCompressionAsync(sb.ToString());
        }

        private void TestCompressionCompleted(object sender, TestCompressionCompletedEventArgs args)
        {
            lblResponse.Text = "Web service responded! Length = " + args.Result.Length;
        }


text:
Q: how put user input into a variable in an SQL statement using c/c++ I'm quite new in all this programming. But I wanted to know how to pass a variable value into an/a SQL/MYSQL statement in a C/C++ query code.
For example, I wanted to select from database: mysql_query(conn, "select * from ;");
Say that  is a variable and receives user's input. How do I actually do that? Any idea will be greatly appreciated.

A: You could use std::string as other said, but you could also use sql::PreparedStatement which are a lot more safe :
sql::Connection *con;
sql::PreparedStatement *prep_stmt
const char* tableName = "foo";

prep_stmt = con->prepareStatement("SELECT * FROM ?");
prep_stmt->setString(1, tableName);
prep_stmt->execute();

When using prepared statement, the DBMS will parse and compile the statement as is and will bind the values of the parameters only at the execution of the statement. This allow you to reuse the same statement multiple times with different parameters but also offer you a strong protection against SQL injection since you let the DBMS take care of the parameters.

A: To make milleniumbug's warning more explicit: Google "SQL injection". The solution is prepared statements.
std::string sql = "select * from ?;". This is a statement which you can prepare and then execute. When preparing, MySQL finds the ?, and when executing you just need to provide a value for ?. MySQL will then insert the table name for you.

A: You can use std::string to easily build an SQL statement.
#include <string>

std::string CreateSelectStatement(const std::string& tableName)
{
    std::string  sql;

    sql = "select * from " + tableName + ";";

    return sql;
}

You can then use the string to query the database.
std::string sql(CreateSelectStatement("sometable"));

mysql_query(conn, sql.c_str());


text:
Q: How do you add custom styling to a tab when it's active in Bootstrap 4? I have these list items. When the active tab changes to Page_1, I'd like the
 to have border-bottom: solid 1px #000; as opposed to Bootstrap's own styling/

Home

Page 1

A: Select the bootstrap item you want to override, then make sure you make your own bootstrap class in your style file that loads after the bootstrap css file loads. Click on a tab to highlight it as active, note the order of bootstrap, then custom styles:

.nav-tabs .nav-item.show .nav-link, .nav-tabs .nav-link.active {
  background: moccasin;
  border-bottom: 2px solid green;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

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

    Home
    Profile
    Contact

...

...

...


text:
Q: how to stop multiple go routines i have to invoke goroutuine /thread from a loop. Because of the loop, there are many go routines executes in parallel. If any routine/thread executed successfully, then i have to stop all other thread/routine.
Is there any way to implement this?

A: You can use quit channels in addition to context as answered by Burak.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func foo(channel, quit chan string, i int) {

    channel <- fmt.Sprintf("goroutine %d started!", i)
    for {
        rand.Seed(time.Now().UnixNano())
        time.Sleep(time.Duration(rand.Intn(500)+500) * time.Millisecond)
        quit <- fmt.Sprintf("goRoutine %d completed!", i)
    }
}
func main() {

    channel := make(chan string)
    quit := make(chan string)

    for i := 0; i < 3; i++ {
        go foo(channel, quit, i)
    }

    for {
        select {
        case update:= <-channel:
            fmt.Println(update)
        case quit:= <-quit:
            fmt.Println(quit)
            return
        }
    }
}

A: You can use a context:
ctx, cancel:= context.WithCancel(context.Background())
for ... {
   go func() {
      defer cancel() // cancel context once this goroutine ends
      doStuff(ctx)
   }()
}

You have to check context cancellation in the goroutines:
func doStuff(ctx context.Context) {
   ...
   if ctx.Err()!=nil {
       // Canceled, return
       return
   }
  ...
}

This will not guarantee that once the context is canceled other goroutines will end immediately, however it guarantees that, if you check for context cancellation correctly, all goroutines will end eventually.

A: You could use a context and an errgroup.
Something along the lines of...
package main

import (
    "context"
    "fmt"
    "math/rand"
    "os"
    "time"

    "golang.org/x/sync/errgroup"
)

func doStuff(ctx context.Context, i int) error {
    count := 0
    for ctx.Err() == nil {
        // do the stuff
        time.Sleep(time.Millisecond * time.Duration(rand.Intn(500)))
        count++
        if count > 6 { // error condition
            fmt.Fprintf(os.Stdout, "%v reached count %v\n", i, count)
            return fmt.Errorf("Error %v, count %v\n", i, count)
        }
    }
    fmt.Fprintf(os.Stdout, "Killed %v @ count %v\n", i, count)
    return ctx.Err()
}

func main() {
    rand.Seed(int64(time.Now().Nanosecond()))
    ctxWc, _ := context.WithCancel(context.Background())
    g, ctx := errgroup.WithContext(ctxWc)
    for i := 0; i < 5; i++ {
        i := i
        g.Go(func() error {
            return doStuff(ctx, i)
        })
    }
    err := g.Wait()
    fmt.Println("The End")
    if err != nil {
        fmt.Println(err)
    }
}


text:
Q: Parsing Comma Separated File in C I'm trying to parse a file in C that is a comprised of sets of numbers (one per line). Each set is separated by a comma. For some reason I'm getting an incorrect output.
Example input: 1,2,4,8,55,777
Output: A bunch of what seem to be memory addresses. And when I print off the strings it's not reading 55 or 777 (or any number over two digits).
int * parseFile(char *input, int *set, int line)
{
    char buf[BUF_SIZE];
    char *token = (char *) malloc(10 * sizeof(char));
    int i;

    FILE *f = fopen(input, "r");

    for (i = 1; i < line; i++)
        fgets(buf, BUF_SIZE, f);

    memset(buf, 0, BUF_SIZE); // Clear the buffer.
    i = 0;

    if (fgets(buf, BUF_SIZE, f) != NULL) {
        token = strtok(buf, ",");
        set[i] = atoi(token);
        i++;

       while (set[i] != 0) {
            printf("%d\n", set[i]);
            set[i] = atoi(token);
            i++;

            token = strtok(NULL, ",");
        }
    }

    fclose(f);

    return set;
}

A: you can use fscanf()
use the following fscanf() into a loop till you reach the end of the file:
int a,b,c,d,e,x;
while (fscanf(f, " %d , %d , %d , %d, %d , %d", &a, &b, &c, &d, &e, &x) != EOF) {....}

A: You are printing the value of set[i] before you assign to it the value of atoi.
Consider:
set[i] = atoi(token);
printf("%d,",set[i]);

while (set[i] != 0) {
    i++;
    set[i] = atoi(token);
    printf("%d,",set[i]);
}

A: I am very confused with this:
set[i] = atoi(token); //i = 0
i++; //i = 1

while (set[i] != 0) { //set[1] = ???
  printf(...set[i]);
  set[i] = atoi(token);
  i++;
  ...

so, depending on the previous content of the array "set", you decide, whether to read the next value. So, if you did a "memset(set, 0, sizeof(set));" you actually read one line. If you did not clear the "set", if may contain rubbish, which you "printf()" before readin the next value

A: I like this
 if (fgets(buf, BUF_SIZE, f) != NULL) {
    token = strtok(buf, ",");
    for (i=0; token != NULL; i++) {
      set[i] = atoi(token);
      // Optional: if (set[i] == 0) break; // I don't know why to stop on 0
      printf("%d\n", set[i]);
      token = strtok(NULL, ",");
    }
  }

The break is a little ugly, but it's better than
for (i=0; (token != NULL) && ((set[i] = atoi(token)) != 0); i++) {


text:
Q: how to have more than 1 container using jquery masonry I have a tabs set up on my website and I would like to use Masonry on the content of each tab, but I can only get it working on 1 tab at a time.
Initially I tried just using the generic  selector and using that in each tab. This however just worked in the first tab. I then tried adding more container variables:
<!--Masonry kit-->
<script type="text/javascript" src="http://localhost/LazyDuck/masonry-site/js/jquery.masonry.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).load(function() {

var $container = $('#container');
var $container = $('#dining');
var $container = $('#events');
var $container = $('#climbing');
var $container = $('#wildlife');
var $container = $('#shopping');
var $container = $('#kids');
var $container = $('#sport');

$container.masonry({
  itemSelector: '.item',
  gutterWidth : 10,
  isAnimated: !Modernizr.csstransitions
});
});});

But that doesn't work either. I'm sure this is a simple thing but my JavaScript coding isn't so great. I guessed the above. :(

A: I think it is more of jQUery syntax but also i think masonry wont work if there is no visible content. It has to be applied to a div that is visible.
So one way would be to do it all while its visible and then hide it.. Not great.. I know.
var $container = $('#container');
var $container = $('#dining');
var $container = $('#events');
var $container = $('#climbing');
var $container = $('#wildlife');

To solve the chainablilty of starting the plugin just do this
$('#wildlife, #climbing , ... ,#container).masonry({ ..

But in this case it would be easier to toggle it by a uniqe class name such as
class="MasoniseThis otherClasses"
...
$('.MasoniseThis').masonry({ ..

And on each pageload it should apply the plugin to any visible divs with that Class on it.
Without some markupor example in JSFiddle we cannot really help you any more.


text:
Q: Earth Engine: issues with NAIP image collection I am trying to visualize the NAIP data available by direct import in Earth Engine. I am unable to use the simple print method: Collection query aborted after accumulating over 5000 elements.
I suppose the problem comes from the fact that the NAIP is an image collection containing images with different bands over time, but not sure how to solve this, and how to visualize the details/information on the discussion?
var NAIP = ee.ImageCollection('USDA/NAIP/DOQQ')

// problem 1:
print(NAIP, "NAIP")

A: The NAIP image collection contains over 1.4 million images, and printing the image collection requests metadata for each of the images. This is probably not what a user actually wants to do, so the query limit of 5000 elements (images in this case) seems to be a reasonable limit.
If you do want to see the metadata for the NAIP images, do it on a subset of the collection. For example, limit it to 10 images:
var NAIP = ee.ImageCollection('USDA/NAIP/DOQQ');
print("NAIP sample", NAIP.limit(10));

Backing up to your original goal, a map-based visualization of Earth Engine data can be done using the Map.addLayer() command. For example, the NAIP images for 2015 can be visualized with the following code:
var NAIP2015 = NAIP.filterDate('2015', '2016');
Map.addLayer(NAIP2015, {bands: 'R,G,B'}, 'NAIP 2016');

Note-1: NAIP only covers selected US states each year, so there may be no data where you are looking.
Note-2: The spectral bands of NAIP images has changed over the years and may not even be consistent within a single year, so you may need to filter the collection to make it homogeneous before displaying it. For example, this code filters out the 2006 images that do not contain the blue 'B' band:
var NAIP2006 = NAIP.filterDate('2006', '2007')
  .filter(ee.Filter.listContains('system:band_names', 'B'));
Map.addLayer(NAIP2006, {bands: 'R,G,B'}, 'NAIP 2006');


text:
Q: If a particular record is not available then I need to display as zero in MYSQL query SELECT DATE(login) AS loginDate, COALESCE(COUNT(login),0) AS loginCount
  FROM LMS_LoginTracking
 WHERE prism_mem_id = 55308
   AND DATE(login) BETWEEN '2017-01-04T18:30:00.000Z' AND '2017-01-09T18:30:00.000Z'
 GROUP BY DATE(login)

Output is :
LoginDate     LoginCount
2017-01-05     406
2017-01-06     558
2017-01-08      11
2017-01-09     406

Here, what I am expecting is 2017-01-07 should be 0 as this date is not available in the data, even though I need the result for that particular date as zero result.
Required output:
LoginDate     LoginCount
2017-01-05     406
2017-01-06     558
2017-01-07       0
2017-01-08      11
2017-01-09     406

Please help me on this.

A: There are lot's of different ways in which this can be achieved. The easiest I know is to create a table that stores the dates of interest. Then fill it up with the relevent data. Let's call it work_days
CREATE TABLE work_days(
    work_day date NOT NULL PRIMARY KEY
);

And then you can use a left join on it as follows
SELECT date(login) as loginDate, COALESCE(count(login),0) as loginCount
FROM work_dates LEFT JOIN LMS_LoginTracking
ON work_dates.work_day = date(LMS_LoginTracking.login) /* edit as appropriate */
WHERE prism_mem_id=55308 AND DATE(login) BETWEEN '2017-01-04T18:30:00.000Z' AND '2017-01-09T18:30:00.000Z' group by date(login)

You haven't posted your tables so cannot be tested here. Therefor this query may not work in it's exact form. Please edit as appropriate


text:
Q: Why does my md5sum hash not match other md5s? So for a school assignment we are working with hashes.  However I've encountered a problem where my file.txt containing:
test hashes
test hashes

without quotes doesn't match the hash from HashCalc (for windows) and http://www.md5hashgenerator.com/ both come up with cd7e8e88f33efb42e0a1148e92c5005b while md5sum on my kali linux comes up with f3c5fdf4320346eb9bd2a6b64235248e using
head -c -1 file.txt | md5sum

It works fine with just one line of test hashes, but with the second line I can't make it match.

A: $ echo -ne "test hashes\ntest hashes" | md5sum
f3c5fdf4320346eb9bd2a6b64235248e  -
$ echo -ne "test hashes\r\ntest hashes" | md5sum
cd7e8e88f33efb42e0a1148e92c5005b  -

It's about Unix (\n) vs. DOS line ending (\r\n).
You can convert Unix line endings to DOS ones with unix2dos:
$ echo -ne "test hashes\ntest hashes" | unix2dos | md5sum
cd7e8e88f33efb42e0a1148e92c5005b  -

The reverse command is dos2unix.


text:
Q: Set of linear functionals span the dual space iff intersection of their kernels is $\{0\}$. I was wondering if anyone could offer some insight into the following problem:
Let$\mathit{V}$ be a vector space over a field $\mathbb{F}$. Assume that dim$\mathit{V}$ is finite. Let $f_1, \ldots, f_k$ $\in$ $\mathit{V}$ '
Show that $\{f_1, \ldots, f_k\}$ span $\mathit{V}$ ' iff  $\bigcap_{i=1}^n \ker(f_i)$ = $\{0\}$

A: First suppose $f_1,...,f_n$ is a basis for $V^*$ and $b_1,...,b_n$ is a basis for $V$. Then
the matrix $C$ defined by $[C]_{ij} = f_i(b_i)$ is invertible, and if we let $A=C^{-1}$ then the points $\beta_i = \sum_k [A]_{ik} b_k$ satisfy $f_j ( \beta_i) = \delta_{ij}$.
That is, $f_k$ is the dual basis for $\beta_k$.
Suppose $f_k$ span $V^*$, and $x \in V$. Without loss of generality we can assume
that $f_k$ is a basis for $V^*$. Write $x=\sum_k \alpha_k \beta_k$. Since $\alpha_k = f_k(x)$, we see that if $f_k(x) = 0$ for all $k$ then $x=0$. Hence $\cap_k \ker f_k = \{0\}$.
Now suppose the $f_k$ do not span $V^*$. Without loss of generality we can assume that the $f_k$ are linearly independent. Add functionals $g_j$
such that $f_k,g_j$ form a basis. Construct the basis $\beta_k$ of $V$ as above.
Suppose $g_j(\beta_j) = 1$, then we have $f_k(\beta_j) = 0$ for all $k$ and so
$\beta_j \in \cap_k \ker f_k$.


text:
Q: Updating foreign key within transaction fails I have a table A referencing table B via a compound foreign key (we use Quartz which has compound keys).
When I want to update the compound key I have to update it for both tables, but:

*

*when I start with table A, it fails because there is no valid foreign key in table B.

*when I start with table B, it doesn't allow me to update it as table A still references the records.

I always though that I should be able to do this within transaction as data is consistent before and after transaction, but I couldn't get it working on Postgres and H2.
What's wrong with my understanding of transactional consistency?

A: First insert valid key in B. Then update A. Finally delete the invalid key in B.

A: You actually need to use a deferred constraint for the foreign key.
The problem you are having is because Postgres will check foreign key constraints after each statement, not after the transaction is complete. Deferred constraints allow you to defer checks for constraints until the end of the transaction.
This article helped me when I ran into the same problem and it also has examples similar to your situation. Give it a read and you should know how to solve this:
https://begriffs.com/posts/2017-08-27-deferrable-sql-constraints.html


text:
Q: Upload file using JS and REST. Specify content type I can upload file to SharePoint library using JS and REST.
The content type of added file is as library default content type.
How can i specify file content type when uploading file? Thanks!

A: You cannot specify metadata when uploading a file via REST.  You have to upload the file, then update it afterwards.  To specify content type, simply specify the ContentTypeId when updating the metadata.


text:
Q: windows batch file quits after this line On windows 10, my batch file always quit after this line without any infomation:
cd ..\DOC\API && make html & cd ..\..\BUILDALL

I stared at this line for long and cannot figure out why lines after this one cannot execute. I also tried the following line and its shows the correct directory.
cd ..\DOC\API && make html & cd ..\..\BUILDALL & dir

A: as Stephen pointed out, 'make' is a batch file, and a windows batch file terminate when execute another batch file, unless we call that batch file.  So this is correct:
cd ..\DOC\API && call make html & cd ..\..\BUILDALL

Like others did, I checked the directories again and again, and even used the following line to check it:
cd ..\DOC\API && make html & cd ..\..\BUILDALL & dir

Even the last dir outputs correctly, the batch file still terminate for the reason explained above. dir could show correctly since the line is parsed altogether.
soembadhat explained from a different perspective.


text:
Q: How to have multiple relationships between two entities with two way navigation properties (Code-First)? As you can see in the code below I have two tables having one One-to-Many and one Many-to-Many relationships with each other. This code seems wrong since I won't be able to navigate to Meeting entities from Person entities. I don't know the jargon but I'll tell you in english.
You know each person have attended many meetings
You know each person have created many meetings
You know each meeting has many attendees
You know each meeting has one creator
When we talk about a meeting, you can tell the creator using the foreign key "Creator_ID"
When we talk about a meeting, you can tell who were the attendees using the intermediate mapping table
When we talk about a person you can tell the meetings that this person attended using the intermediate mapping table
But
When we talk about a person to tell the meetings that this person have created you should go through all the meetings and check their foreign key "Creator_ID"
I know this is how DBMS works. But since I am working with Entity Framework, I want to be able to use
meetings = thisPerson.meetingsCreated;

public class Person
    {

        public int ID {get; set;}
        public string UserName { get; set; }

        public ObservableCollection<Meeting> meetingsAttended { get; set; }
        public ObservableCollection<Meeting> meetingsCreated { get; set; }
    }

public class Meeting
    {
        public int ID { get; set; }
        string Title { get; set; }

        [ForeignKey("Creatator_ID")]
        public virtual Person createdBy { get; set; }
        public virtual ObservableCollection<Person> Attendees { get; set; }
    }

Should I implement a method in Person class which goes through all the meetings and returns the meetings created by this Person? How should I do it?

A: you should have some configuration instructions like
protected override void OnModelCreating(DbModelBuilder modelBuilder) {

    modelBuilder.Entity<Meeting>().HasResquired(m => m.CreatedBy).WithMany(p => p.meetingCreated);
    modelBuilder.Entity<Meeting>().HasMany(m => m.Attendees).WithMany(p => p.meetingAttended);

}


text:
Q: ios - (Push Notification) When I call getNotificationSettings alertSetting is returning NotSupported When I call
UNUserNotificationCenter.current().getNotificationSettings

the alertSetting is returning "Not Supported". Here is the callback.
Notification settings: <UNNotificationSettings: 0x17408be50; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, **alertSetting: NotSupported**, carPlaySetting: Enabled, alertStyle: Banner>

What does that means?
I'm testing on an iPhone with iOS 10.3.2.

A: Is means that the setting is not available to your app. You can find more information here: https://developer.apple.com/documentation/usernotifications/unnotificationsetting


text:
Q: Alternative formula of Gaussian Curvature I encountered the below quote defining the gaussian curvature not mentioning normals in the context of unfamiliar differential forms formalism. How does one reconcile this with the definition of the gaussian curvature that I am familiar with which mentions normals which is
$$K = \det dN = \det\begin{pmatrix} a_{11} & a_{12} \\ a_{21} & a_{22} \end{pmatrix}$$
where $$N_u=a_{11}\mathbf{x}_u + a_{21}\mathbf{x}_v$$
$$N_v=a_{12}\mathbf{x}_u + a_{22}\mathbf{x}_v$$

Let $S$ be a surface in $R^3$. A frame field on $S$ is a choice of vector fields $\{\mathbf{E_1,E_2}\}$ such that at each point $p$ of $S$, $\mathbf{E_1}(p)$ and $\mathbf{E_2}(p)$ form an orthonormal basis for $T_p S$.
...
We define $\Omega(V)=(\nabla_V \mathbf{E_1})\cdot \mathbf{E_2}$. Since
  $(\nabla_V \mathbf{E_1})\cdot \mathbf{E_2}=d\mathbf{E_1}(V)\cdot\mathbf{E_2} = d\mathbf{E_1}\cdot \mathbf{E_2}(V)$, it is sometimes
  more convenient to write $$\Omega=d\mathbf{E_1}\cdot \mathbf{E_2}$$ We
  now define a numerical measure of the curvature of $S$ at each point,
  which does not depend on a choice of tangent vector at that point.
Definition 4. The gaussian curvature at each point of $S$ is defined
  to be the number $$K=-d\Omega(\mathbf{E_1},\mathbf{E_2})$$

A: The answer to your question is the Mainardi-Codazzi equation. Letting $\mathbf E_3$ be the unit normal, write
$$\omega_{ij} = d\mathbf E_i\cdot \mathbf E_j \quad\text{for } i,j=1,2,3.$$
Note that your $\Omega = \omega_{12}$. Note also that $\omega_{ij}=-\omega_{ji}$ because $\mathbf E_i\cdot\mathbf E_j$ is a constant function.
Note that $d\mathbf E_i = \sum \omega_{ij}\mathbf E_j$, so, differentiating again, we have
$$0 = \sum d\omega_{ij}\mathbf E_j - \sum\omega_{ij}\wedge d\mathbf E_j = \sum d\omega_{ik}\mathbf E_k - \sum\omega_{ij}\wedge\omega_{jk}\mathbf E_k.$$
Since $\{\mathbf E_k\}$ is linearly independent, we deduce that
$$d\omega_{ik} = \sum\omega_{ij}\wedge\omega_{jk}.$$
In particular,
\begin{equation}d\omega_{12} = \omega_{13}\wedge\omega_{32} = -\omega_{13}\wedge\omega_{23}. \tag{$\star$}
\end{equation}
(Equation ($\star$) is one formulation of the Mainardi-Codazzi equation.)
Writing
\begin{align*}
\omega_{13} &= h_{11}\omega_1 + h_{12}\omega_2 \\
\omega_{23} &= h_{21}\omega_1 + h_{22}\omega_2,
\end{align*}
we see that $\omega_{13}\wedge\omega_{23} = (h_{11}h_{22}-h_{12}h_{21})\omega_1\wedge\omega_2$. The matrix $\big[h_{ij}\big]$ is the matrix of $-dN$ with respect to the basis $\{\mathbf E_1,\mathbf E_2\}$. Since the determinant of a linear map is independent of the basis one uses to express its matrix, we deduce that
$$d\omega_{12} = -\det(dN)\omega_1\wedge\omega_2.$$
Evaluating on $\mathbf E_1,\mathbf E_2$, we see that, in fact, $K = \det(dN)$.


text:
Q: Huge CPU usage when calling 'UIImagePickerController didFinishPickingMediaWithInfo' iOS7 XCode I noticed a huge CPU usage when I press 'Use Photo' on UIImagePickerController calling the proper method:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

}

even if the method is empy! Here an image logging CPU usage while above method is called.

Top that I recorded was 169%. So wtf?!?

A: This is because size of the image that you are using is very large normally more than 2mb. So so a image resize before using it.
here is the code snippet:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];

    if (!originalImage)
        return;

    // Optionally set a placeholder image here while resizing happens in background

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Set desired maximum height and calculate width
        CGFloat height = 640.0f;  // or whatever you need
        CGFloat width = (height / self.view.frame.size.height) * self.view.frame.size.width;

        // Resize the image
        UIImage * image = [originalImage resizedImage:CGSizeMake(width, height) interpolationQuality:kCGInterpolationDefault];

        //save/use the image here
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, NULL);//for saving to camera roll
    });
}
}


text:
Q: Using both CROSS APPLY and INNER JOIN in the same query I'm attempting to use both Left Join and Cross Apply in the same query and running into difficulties.
SELECT vAH.TagName, vAH.EventSTamp, -123 Value, vAH.Description,
--  Ack.DateTime, Ack.UserFullName as AckUser, Ack.Description as AckComment,
LEFT(vAH.TagName,9) + CONVERT(nvarchar(30),LLC.StartDateTime,113)  as ObjName
FROM WWALMDBArchived.dbo.v_AlarmHistory vAH
--CROSS APPLY (
--  SELECT TOP 1 EventStamp as DateTime, UserFullName, Description
--  FROM WWALMDBArchived.dbo.v_AlarmHistory vAH
--  WHERE TagName = vAH.TagName
--  AND EventStamp > vAH.EventStamp
--  AND AlarmState IN ('ACK_RTN','ACK_ALM')
--  ORDER BY DateTime, UserFullName, Description DESC
--  ) Ack
INNER JOIN CPMS.dbo.LotListConfig LLC
ON vAH.EventStamp >= LLC.StartDateTime
AND vAH.EventStamp <= LLC.EndDateTime
WHERE vAH.TagName LIKE @LineNumber + '%.Action_Alarm_ALM'
AND LLC.LineNumber = @LineNumber
AND LLC.LotNumber = @LotNumber
AND vAH.AlarmState = 'UNACK_ALM'

Essentially what I am doing is getting the boundary information from the LotListConfig table, getting the initial alarm information from v_AlarmHistory, and using the Cross Apply to get some subsequent alarm information from the v_AlarmHistory table.
The query above returns the records I would expect, but uncommenting the Cross Apply causes no records to return.  There's an interaction of some kind happening between the Inner Join and the Cross Apply that I'm missing.
Anyone?

A: Nevermind.
My query above is using the same table shortcut (vAH) in both the main query and the CROSS APPLY query.  Deleting the vAH inside the Cross Apply resolves the issue.


text:
Q: tkinter bad screen distance "10 0" My goal is to pady this section marked with a red circle slighty down.

Snippet of my code supposed to pady the last label down:
self.likviditetsgL = Label(self.left_child, bg=grey, text='Likviditetsgrad,%', pady=(10,0))

which results in: _tkinter.TclError: bad screen distance "10 0"
There is definitely more than enough place to expand to, so what could the cause of the error be?
Stuff I have tried:

*

*padding the other way around doesn't change anything "pady=(0,10)".

*I could even pad with 0 and it would still cause the same error "pady=(0,0)".

*I even tried rewriting the tuple to a string and it made no different pady="10 0".
I can post the source code (around 150 lines) if needed.

A: The pady option of a label only accepts a single value (eg: pady=10), not a tuple. The "bad screen distance" error refers to the fact that the value must be a "screen distance". Normally that means an integer representing pixels, but it can also be something like "1c" (one centimeter), "1i" (one inch), "1m" (one millimeter), or "1p" (one printers point).
You may be confusing the pady option of a Label with the pady option of the grid or pack methods. The option for grid and pack methods accept a tuple, but the option for the label itself only accepts a single number.


text:
Q: Why are votes anonymous? Let's make with the transparency and have them publicly attributed Why isn't there any possibility to make upvotes onymously? Seeing positive votes from credible other members would highly increase transparency and trust in answers.
Has anything like that been tried out so far?
What strong opinions are against such an option? Why not even make such behavior default?

A: One of the biggest problems with onymous votes would be a sort of clique-like, Facebook experience where people upvote each other's posts as "thanks" for the upvote and become friends in that regard.
The danger is even greater that people would revenge-downvote each other.
I think you'd have more people voting for the person rather than the content, which would certainly be terrible for the site.

A: You should judge a post by the content and any available relevant facts, NOT by who supports it.
The former is science.  The latter becomes politics and then religion.
We want better technical answers, so posts should stand on their own merits, as much as possible.

A: "Seeing positive votes from credible SO members" might lead people to the opposite conclusion — that the absence of those votes was a sign of disapproval.
The potential abuses of non-anonymous voting are too great to imagine.
We don't want to go there.

A:
Why are votes anonymous?

Because Stack Exchange is not a social forum, plain and simple. This is a network of professional communities, focused on content, not on who posted it.
Social communities like Facebook allow showing who liked a post because it has no real impact: there is no reputation, no penalty for "downvoting", and the whole point of the social media is "pile voting" anyway. The exact opposite of Stack Exchange.


text:
Q: ¿Por qué el servicio system/connect de drupal 7 devuelve una página en blanco? Necesito crear un servicio web en drupal 7 que contenga el recurso system/connect (para mostrar los usuarios logueados) pero a la hora de consumirlo devuelve una página en blanco. ¿A qué se puede deber esto?
He probado con el recurso usuario y funciona bien (devuelve todos los usuarios del sistema)
la url que estoy utilizando para consumir es la siguiente
https://localhost/drupal/x_login/system/connect

Donde x_login es el endpoint. Además existen usuarios conectados en el momento de consumir el servicio.

A: Lo que pasa es que el system/connect es utilizado solo para saber el usuario actual que está conectado. Por ejemplo, si tu estás logueado y envías al servidor rest de Drupal en el metodo POST, el system/connect debe darte el CSFR-Token de tu usuario, no el de todos los usuarios que están conectados.
En youtube, tengo unos videos relacionados con este tema el cual te puede interesar.
Modulo Services Drupal 7 1/2


text:
Q: File lock kept opened even after closing the file, co-editing gone for toss in my Enterprise The latest macOS 10.14.x and macOS 10.15.x have degraded their behavior with Word applications on network drives mapped via SMB. These network drives are shared drives on the Windows 2019 file server or it can be on any Linux file server.
Issues:
A) When we map an n/w drive on macOS 10.14.x and above versions with SMB and open a .docx file and close it, the file lock is not released by the client even after closing/force-existing the application on the client. This takes a toll on our n/w users who are working on co-editing the file for various needs of my enterprise. Thorough testing has revealed that this issue is not seen on  macOS 10.12/10.13.
We can reconfirm this issue by listing the files opened on n/w drive on Windows 2019 file server's PowerShell command "Get-SmbOpenFile", we will continue to see the file lock from client even after closing/force-exiting the file/application from client.
Anyone heard/observed this issue?
Are there any posts/fixes about this behavior that Apple introduced from  macOS 10.14? This is really degrading Mac usability and corrupting n/w users data  and making lives of shared drive administrators difficult!


text:
Q: last position null ListView Custom Adapter In my class of adapter I'm having problems getView method (). When I print the positions of the elements that I want to list, always missing the last but repeated the first. For example, I have an array of my class of RowItem (custom) class with 7 elements. The positions I get is:
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
    System.out.println("Position : "+position);
    return null
}

Position : 0
Position : 1
Position : 2
Position : 3
Position : 4
Position : 5
.....

However, if the method getCount print receipt
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
    System.out.println("Count "+getCount());
    return null;
}

Count : 7
Count : 7
Count : 7
Count : 7
Count : 7
Count : 7

This causes, that my last element is always like the first. On my list I have a button that when you click, modify a value in the cell to which the button belongs. But this error, it modified only visually the first element and the last. My class :
@SuppressLint("InflateParams")
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {

Context context;
private ArrayList<RowItem> items;

public CustomListViewAdapter(Context context, int resourceId,
    List<RowItem> items) {
    super(context, resourceId, items);
    this.context = context;
    this.items = new ArrayList<RowItem>();
    this.items.addAll(items);
}

/*private view holder class*/
static class ViewHolder {
    TextView txtNombre;
    TextView txtTicket;
    TextView txtAsiento;
    TextView txtOrden;
    TextView txtNumero;
    TextView txtMensaje;
    TextView txtAdicionales;
    TextView txtOtros;
    TextView txtCategoria;
    Button btn;
 }

@Override
public int getCount() {
    return items.size();
}

@Override
public RowItem getItem(int position) {
    return items.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

As I call this class from my activity
CustomListViewAdapter adapter;
public List<RowItem> rowItems = new ArrayList<RowItem>();
rowItems = nueva.getInscripcionsByRut(ValidacionMultiple.this, rut_inscripcion);
adapter = new CustomListViewAdapter(ValidacionMultiple.this,R.layout.lista_validacion_multiple, rowItems );
listView.setAdapter(adapter);

Method getInscripcionsByRut
public List<RowItem> getInscripcionsByRut(Context context, String rut){
    inscripcionValida = new Inscripcions();
    List<RowItem> rowItems = new ArrayList<RowItem>();
    RowItem item;
    bdTickets = new TicketsBaseDatos(context, Config.NAME_DATABASE, null, 1);
    SQLiteDatabase db = bdTickets.getWritableDatabase();
    SessionManager manager = new SessionManager();
    String codigoEvento = manager.getValue(context, "codigoEvento");
    String[] args = new String[] {rut,codigoEvento};
    String codigo_checkin = manager.getValue(context, "checkin");
    Cursor c = db.rawQuery("SELECT * FROM Inscripcion WHERE rut=? AND codigo_evento=?",args);
    for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
         item = new RowItem();
         inscripcionValida.setId(c.getInt(0));
         inscripcionValida.setHash(c.getString(1));
         inscripcionValida.setCodigo_evento(c.getString(2));
         inscripcionValida.setTicket(c.getString(3));
         inscripcionValida.setNombre(c.getString(4));
         inscripcionValida.setInscripcion_id(c.getString(5));
         inscripcionValida.setValidado(c.getInt(6));
         inscripcionValida.setSincronizado(c.getInt(7));
         inscripcionValida.setNumero(c.getString(8));
         inscripcionValida.setAsiento(c.getString(9));
         inscripcionValida.setAdicionales(c.getString(10));
         inscripcionValida.setOtros(c.getString(11));
         inscripcionValida.setCategoria(c.getString(12));
         inscripcionValida.setRut(c.getString(14));
         inscripcionValida.setTalla(c.getString(15));
         inscripcionValida.setNombreResponsable(c.getString(17));
         inscripcionValida.setFechaValidacion(c.getString(16));
         item.setAsiento(inscripcionValida.getAsiento());
         item.setNumero(inscripcionValida.getNumero());
         item.setHash(inscripcionValida.getHash());
         item.setNombre(inscripcionValida.getNombre());
         item.setTicket(inscripcionValida.getTicket());
         item.setOtros(inscripcionValida.getOtros());
         item.setAdicionales(inscripcionValida.getAdicionales());
         if(manager.getValue(context,"checkin") != null){
             item.setValidado(checkinValidado(context,inscripcionValida.getInscripcion_id(),codigo_checkin));
         }else{
             item.setValidado(inscripcionValida.getValidado());
         }
         item.setId_inscripcion(Integer.parseInt(inscripcionValida.getInscripcion_id()));
         rowItems.add(item);
    }
    c.close();
    db.close();
    return rowItems;
}

It is also sending data from my DB to my List to display in the listview.
I got my method getView like this:
 @Override
public View getView(final int position, View convertView, final ViewGroup parent) {
    System.out.println(getCount());
    ViewHolder holder;
    RowItem rowItem = getItem(position);
    if (convertView == null) {
        LayoutInflater mInflater = LayoutInflater.from(getContext());
        convertView = mInflater.inflate(R.layout.lista_validacion_multiple,null);
        holder = new ViewHolder();
        holder.txtNombre = (TextView)convertView.findViewById(R.id.txtNombre);
        holder.btn = (Button)convertView.findViewById(R.id.button1);
        holder.txtMensaje = (TextView)convertView.findViewById(R.id.txtMensaje);
        convertView.setTag(holder);
    } else{
        holder = (ViewHolder) convertView.getTag();
    }
    holder.txtNombre.setText(Html.fromHtml("Nombre: <b>"+rowItem.getNombre()+"</b>"));
    if(rowItem.getValidado()==1){
        holder.btn.setBackgroundResource(R.drawable.icon_big_alert);
        holder.btn.setText("");
        holder.txtMensaje.setText("E-ticket ya validado");
    }else{
        holder.btn.setTag(position);
        holder.btn.setOnClickListener(new View.OnClickListener() {
           //More code...
        });
    }
    convertView.setTag(holder);
    return convertView;
}

What happens here is that if I click on the button of the first item or the last item, you get the same data and do not correspond.

A: Just add holder.btn.setOnClickListener(null); in the if condition.
if(rowItem.getValidado()==1){
     holder.btn.setOnClickListener(null);
}else{
     holder.btn.setOnClickListener(new View.OnClickListener() {
          int position=(Integer)v.getTag();
          RowItem item_click = getItem(position);
          Button b = (Button)v.findViewById(R.id.button1);
          b.setTag(position);
          //More elements.
     });
}

The inconsistent behaviour you see is because of view recycling in listview. Your views for list items are recycled and reused. Say you list has got 100 items so 100 different views will not be created. It will only create unique views approximately equal to the number of items visible in the list. So if a item disappears from the list, its view is not destroyed, it is given to the other items.
public View getView(int position, View convertView, ViewGroup parent);

here convertView is the view that gets recycled
Now in your code you assigned a onClickListener to one view. For the 7th item, the earlier would have been recycled for which onClickListener has already been set. So just remove that onClickListener on whichever row you don't want the listener to be present


text:
Q: How to convert java array type string to string array? I use apache kafka to publish the string message. Before publishing, message type is string array like below,
String[] msgArray = ["aaa", "bbb", "ccc"];

My kafka publishing message type is java string, so I convert this array to string with Arrays.toString(msgArray) method. Apache Kafka publishing and consuming work well. The received message is Java String,["aaa", "bbb", "ccc"]. But the problem is I have no idea how to convert this array type string message back to string array. Below is the part of my codes.
//record.value is array type string -> ["aaa", "bbb", "ccc"]
String[] parameters = new String[record.value().split(",").length];
int i=0;
for(String str : record.value().split(",")) {
    if(i < parameters.length) {
        parameters[i] = str.replace("]", "").replace("[", "");
    }
    i++;
}

But the result is not appropriate. Are there any arrays api which converts array type string to string array?

A: How about deserializing the String with JSONArray:
import org.json.JSONArray;

String[] msgArray = {"aaa", "bbb", "ccc"};

// serializing
String msg = Arrays.toString(msgArray);

// deserializing
JSONArray jsonArray = new JSONArray(msg);
System.out.println(jsonArray.toList());

A: You can follow Psidom's answer or try this option:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
List<String> msgArray = new ObjectMapper().readValue(msg, new TypeReference<List<String>>(){});

A: You can also use Object Mapper for serializing and deserializing your input and output. As it provide support of all of the data types as well as custom.
String[] msgArray = {"aaa", "bbb", "ccc"};

ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(msgArray);
String[] strings = objectMapper.readValue(value, String[].class);


text:
Q: How to make this piece of code look better This is one of my redux reducers and I feel it looks very ugly. Is it possible to improve it?
The goal that I want to achieve is very simple:
If I already have this item in my current state, increase the quantity by 1,
otherwise add this item to state.
function globalReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TO_CART: {
      let { item } = action;
      if (state.getIn(['sideCart', 'orderItems', item.id])) {
        item.quantity = state.getIn(['sideCart', 'orderItems', item.id]).get('quantity') + 1;
      } else {
        item.quantity = 1;
      }
      item = fromJS(item);
      const newState = state.setIn(['sideCart', 'orderItems', item.get('id')], item);
      return newState;
    }
    default:
      return state;
  }
}

The state should look like this:
sideCart: {
    orderItems: {
      1: {
        id: 'orderItems-1',
        name: 'AI Brown\'s BBQ Fillet of Beef with Brown Mushroom Brandy Sauce',
        quantity: 10,
        price: 12,
        subitems: ['0', '1', '2'],
        instruction: 'No rosemary for beef',
      },
      2: {
        id: 'orderItems-2',
        name: 'AI Brown\'s BBQ Fillet',
        quantity: 10,
        price: 14,
        subitems: ['0', '1', '2'],
        instruction: 'No rosemary for beef',
      },
    },
}

A: This is how I would enhance it syntactically:
const reduceCart = (state, action) => {
  let { item } = action;
  const stateIn = state.getIn(['sideCart', 'orderItems', item.id]);
  item.quantity = stateIn
      ? stateIn + 1
      : 1;
  item = fromJS(item);
  return state.setIn(['sideCart', 'orderItems', item.get('id')], item);
};

const globalReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TO_CART: return reduceCart(state, action);
    default: return state;
  }
};

A: I found the same complexity when using immutable.js to handle deeply nested objects. I have made a lightweight immutable helper: ImmutableAssign that allows you to continue working with plain JS objects, which will simplify your operations.
In the following example, it expects state and action to be plain JS objects, and it will return you a new state as plain JS object:
function globalReducer(state = initialState, action) {
    switch (action.type) {
        case ADD_TO_CART: return addCart(state, action);
        default: return state;
    }
}

function addCart(state, action) {
    let { item } = action;

    return iassign(state,
        function(state, context) {
            return state.sideCart.orderItems[context.item.id]
        },
        function(selectedItem) {
            item.quantity = selectedItem.quantity ? selectedItem.quantity + 1 : 1;
            return item;
        },
        { item: item });
}

// The first parameter is a function that return the
// property you need to modify in your state.
// This function must be **pure function**, therefore "item"
// need to be passed in via the context parameter.
//
// The second parameter is a function that modify selected
// part of your state, it doesn't need to be pure, therefore
// you can access "item" directly
//
// The third parameter is the context used in the first
// function (pure function)


text: Q: forecast package from R - Can a time series model saved to predict later Can we use forecast package to create a time series model and save  it for later prediction. i am using the forecast method with 'ets' or 'arima' as one of the parameters.But it predicts the point estimate,but we can not save the model which can generate future prediction with the same model.


text:
Q: Scala: How to group every nth element of sub lists? Consider having this:
List(List("a1", "b1"), List("a2", "b2"))
and I want this
List(List("a1", "a2"), List("b1", "b2"))
I am pretty sure there is a functional way to do this.
But I have no idea how to solve.

A: Function like following should help with it.
  def transponent[T](l: List[List[T]]): List[List[T]] =
    if (l.head.isEmpty) Nil else l.map(_.head) :: transponent(l.map{_.tail})

Should probably be rewritten with @tailrecurtion.


text:
Q: How to create Grouped Bar Chart in Vegalite? Name | Value 1 | Value 2
BTC  | 1       | 2
ETH  | 1       | 2

to this:

Tried to used this as an example: https://vega.github.io/vega-lite/examples/bar_grouped.html,
but I can't make it work.
Can someone please point me to the right direction? Thank you in advance.

A: Instead of using column provided in your question, You can simply use layers and keep the x axis as common and provide value1 and value2 in y axis of each layer respectively and simply provide some offset to show it as a grouped bar chart. Below is the basic spec configuration and editor:
{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A simple bar chart with embedded data.",
  "title": "My chart",
  "width": 200,
  "data": {
    "values": [
      {"name": "BTH", "value1": 28, "value2": 24, "legendTitle": "value1"},
      {"name": "ETH", "value1": 55, "value2": 25, "legendTitle": "value2"}
    ]
  },
  "encoding": {
    "x": {"field": "name", "type": "nominal", "axis": {"labelAngle": 0}}
  },
  "layer": [
    {
      "mark": {"type": "bar", "xOffset": -20, "size": 30, "color": "skyblue"},
      "encoding": {
        "y": {
          "field": "value1",
          "type": "quantitative",
          "axis": {"title": null, "ticks": false}
        }
      }
    },
    {
      "mark": {"type": "bar", "size": 30, "xOffset": 18, "color": "orange"},
      "encoding": {
        "y": {
          "field": "value2",
          "type": "quantitative",
          "axis": {"title": null, "ticks": false}
        }
      }
    },
    {
      "mark": {"type": "text"},
      "encoding": {
        "fill": {
          "field": "legendTitle",
          "scale": {"range": ["skyBlue", "orange"]},
          "legend": {"title": null, "symbolType": "square", "orient": "bottom"}
        }
      }
    }
  ]
}


text:
Q: Prove that $\langle f(x) \rangle $ is prime ideal in $\Bbb Z[x]$ if $f(x)$ is irreducible over $\Bbb Z$ I know $(x^2+1)$ is prime ideal of $\Bbb Z[x]$ without being maximal ideal.  It can be easily proved  as quotient ring isomorphic to integral domain $\Bbb Z[i]$. My question is the generalization of this i. e.  if $(x^2+1)$ is replaced by arbitrary irreducible polynomial $f(x)$  over $\Bbb Z$.  Can anyone suggest me an outline of this proof ? Thank you.

A: Fix $s$ irreducible. Now consider $p,q$ polynomials such that $pq = rs$ for some other polynomial $r$. Now, since $\mathbb{Z}[X]$ is a unique factorization domain, the polynomials $p,q$ and $r$ have a decomposition in irreducibles,
$$
p = f_1^{\alpha_1} \cdots f_n^{\alpha_n}, \quad q = g_1^{\beta_1} \cdots g_m^{\beta_m}, \quad r = h_1^{\gamma_1} \cdots h_k^{\gamma_k}.
$$
So the former equality says that
$$
f_1^{\alpha_1} \cdots f_n^{\alpha_n} \cdot g_1^{\beta_1} \cdots g_m^{\beta_m} = h_1^{\gamma_1} \cdots h_k^{\gamma_k} \cdot s.
$$
Once again, by the uniqueness of factorization, one of the irreducibles of the left must coincide with $s$ up to a unit. Without loss of generality, suppose that $f_i = \pm s$ for some $1 \leq n \leq n$. Then,
$$
f = \pm s(f_1^{\alpha_1} \cdots \widehat{f_i^{\alpha_i}} \cdots f_n^{\alpha_n})
$$
and so $s$ divides $p$.
This proves that if $s$ divides $pq$ then it divides either $p$ or $q$, which is to say that $(s)$ is prime. In general $R[X]$ is a UFD if $R$ is one, and that's all we have used. So $(s)$ will be prime if $s$ is irreducible in any UFD.
In general, an irreducible element $s$ of an UDF is always prime (by the argument above), which is to say that $(s)$ is prime.

A: A simple argument could be:

*

*If $f(x)$ is irreducible in $\Bbb{Z}[x]$, including that it has no non-unit constant factor, then it is also irreducible in $\Bbb{Q}[x]$ (the usual argument invokes Gauss's lemma at a key step).

*Therefore $f(x)$ generates a maximal ideal in $\Bbb{Q}[x]$.

*Therefore $\Bbb{Q}[x]/\langle f(x)\rangle$ is a field.

*But $\Bbb{Z}[x]/\langle f(x)\rangle$ is a subring of $\Bbb{Q}[x]/\langle f(x)\rangle$, so it is an integral domain.

*Therefore $\langle f(x)\rangle$ is a prime ideal of $\Bbb{Z}[x]$.

A: S'pose $g(x)h(x)\in\langle f(x)\rangle $ and that $f(x)$ is irreducible in $\Bbb Z[x]$.
Then $\exists k(x)\in\Bbb Z[x]$ such that $g(x)h(x)=k(x)f(x)$.  So, $f(x)\mid g(x)h(x)$.  But since $f$ is irreducible,  $f(x)\mid g(x)\lor f(x)\mid h(x)$.  Then $g(x)\in\langle f(x)\rangle \lor h(x)\in \langle f(x)\rangle $.
(The key is that primes and irreducibles are the same in the UFD $\Bbb Z[x]$.)


text:
Q: prevent user from deleting all table rows with jQuery courtesy of a few tutorials and the SO community, I have the below syntax which dynamically adds or removes rows from table.
I want to prevent the user from being able to delete all rows in the table. I have put in an if statement to prevent deleting the first row on load, how do I get a count of all table rows to use in the if statement so I can delete all rows as long as there is at least one remaining row after deletion?
my syntax is:

author's first name	author's last name

<input type="text" name="first_name" />	<input type="text" name="last_name" />	 x

Thanks as always,

A: You could use
if ($(this).closest('table').find('tr').length<2) {
   alert ('form must have at least one row')
} else {
   $(this).closest('tr').remove();
}

A: we meet again.....anyways
try this
jQuery("table.authors-list").on('click','.deleteRow',function(event){
 if ($(this).parents('table').find('tr').length >  2) {
    $(this).closest('tr').remove();
 }else{
  alert ('form must have at least one row')
 }

});

fiddle here

A: Assuming you didn't include all the markup for brevity's sake, I would be tempted to try something along these lines:

            author's first name
            author's last name

                <input type="text" name="first_name" />

                <input type="text" name="last_name" />

             x

You can then move on to the javascript:
(It's completely unnecessary to include the table tag in the selector... your classname should work just fine for these purposes, and saves you a few characters, btw...)
jQuery(".authors-list tbody").on('change', 'input[name^="first_name"]', function (event) {
    event.preventDefault();
    // get the number of rows, here
    var counter = $(".authors-list tbody tr").length;
    // also, you don't need to wrap newRow in a jQuery() call... append() does that for you
    var newRow = '
<input type="text" name="first_name' + counter + '" />	<input type="text" name="last_name' + counter + '" />	 x
';
    jQuery('.authors-list tbody').append(newRow);
});

jQuery(".authors-list tbody").on('click', '.deleteRow', function (event) {
    // get the counter at the point in time when you're trying to test deletion
    var counter = $(".authors-list tbody tr").length;
    if (counter == 1) {
        alert('form must have at least one row')
    } else {
        $(this).closest('tr').remove();
    }
});

http://jsfiddle.net/mori57/BsaZY/2/


text:
Q: How to avoid require(..\..\src\test) using NODE_PATH in nodejs How can I replace long relative file paths like require(..\..\src\test) with the more convenient notation require(src\test)?
I try the solution of NODE_PATH in package.json following this article: https://www.coreycleary.me/escaping-relative-path-hell/
but when run npm start, I get a 'MODULE_NOT_FOUND' error.
My package.json look like this:
"scripts": {
    "start": "NODE_PATH=/src/zip && node index.js"
  },

I work in a windows environment and get the error 'NODE_PATH' is not recognized as an internal or external command, operable program or batch file.

A: You can manually replace the path before \src\test with /*$__dirname$*/ and then read the JSON file from your node application, and replace /*$__dirname$*/ with the value of the __dirname JavaScript variable.
So do this before creating the server or listening to it.
const fs = require('fs');
const jsonFilePath = '<path>';

// Read the json file
let json = fs.readFileSync(jsonFilePath, 'utf-8');

if(json.includes('/*$__dirname$*/')) {
    // Replace /*$__dirname$*/ with the variable __dirname's value
    json = json.replace('/*$__dirname$*/', __dirname);

    // Change the JSON file text
    fs.writeFile('jsonFilePath', json, (err) => {
        if(err) { console.log(err); }
    });
};

A: There is a solution to this without changing any process.env variables.
You can use the package.json exports field. More information about this is on the node.js docs. The exports field can be used to define exported files and directories. For example, if your package name is my-package and you want to make the /deep/deeper/src/ folder available as just my-package/src, you can use the exports field.
Example:
Files:
deep/
    deeper/
        src/
            test.js
            more.js
package.json
index.js

package.json content:
{
    "name": "my-module"
    "exports": {
        ".": "./index.js"
        "./src/": "./deep/deeper/src"
    }
}

Note: The / after ./src tells node that it's for everything in /src/, not just a file named /src.
index.js content:
//Self referencing the module is allowed if you use --experimental-modules flag.
require("my-package/src/test");

//This is the 'hell' that you would be avoiding.
require("./deep/deeper/src/test");

I like this solution because you can specify many different paths and files just by changing package.json. The files in the module can refer their own package which this section of the docs explains.
Note: Depending on the version of node you are using, you might need to use the --exerimental-modules flag. For example:
node --experimental-modules index.js


text:
Q: FlyoutNavigation won't work with UIViewController So I have a major problem. When I use FlyoutNavigation to be my navigation drawer, I can't get it to animate unless I'm using a UITableView. As soon as I put a UITableView it animates

A: Okay, so my problem was that the background wasn't loaded. As soon as I loaded a background... the problems went away.


text:
Q: How can i query the contacts content provider outside an activity? I'm trying to query the Contacts content provider outside an Activity. But managedQuery is a method of Activity. Is there any other class/method that I can use instead of managedQuery?
Here's my code:
class MyActivity extends Activity {

  private Cursor getContacts() {
 Uri uri = ContactsContract.Contacts.CONTENT_URI;
 String[] projection = new String[] { ContactsContract.Contacts._ID,
   ContactsContract.Contacts.DISPLAY_NAME,
   ContactsContract.Contacts.HAS_PHONE_NUMBER };
 String where = null;
 String[] whereArgs = null;
 String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
   + " COLLATE LOCALIZED ASC";

 return context.managedQuery(uri, projection, where, whereArgs, sortOrder);
  }
}

A: Use ContentResolver.query() instead.
(call Context.getContentResolver() to get an instance of ContentResolver. You will need a Context anyway, but it does not have to be an Acitivity)
Activity.managedQuery() takes care of dealing with the Activity lifecycle with respect to the Cursor. ContentResolver.query() does not do that, so you will have to make sure to close and requery etc. the cursor yourself.


text:
Q: Cant get memcache to work using xampp/php Im on Windows 7, 64/bit running xampp v3.1. The php version is 5.4, Im trying to install memcache locally on the box so I can use memcache with php. I have searched google and followed directions about installing memcached.exe as a service, then downloading the memcache dll extension file for php and putting it into the ext folder under the php folder. I then add it to the php.ini folder, restart apache and memcache does not show up when running phpinfo() and when I try to run memcache via php it tells me this function does not exist. Can anyone help me figure this out? I verified the service is up and running, I tried different versions of the dll php extension file but still same issue. Any suggestions? Here is one site I used for instructions on installing memcache:
http://shikii.net/blog/installing-memcached-for-php-5-3-on-windows-7/

A: There must be some error logged into your apache logs. What is the error?

A: Looks like I grabbed the incorrect version of memcache for php. You must grab the correct memcache dll file for the php version you are using. I found the correct download here:
http://windows.php.net/downloads/pecl/snaps/memcache/3.0.6/php_memcache-3.0.6-5.4-ts-vc9-x86.zip
It has the correct php version, 5.4 and its thread safe. Once I downloaded it, extracted the dll and put into php extension folder and restarted xampp/apache, it now works.


text:
Q: Android custom interpolator I have to animate my view like that it decelerate upto 30% after that accelerate till 70% and at last again decelerate till finish.
Please find below image for the function of time.

Which interpolater i have to used or need to go with custom one.
If custom one required then please let me know the function which i have to use in getInterpolation()
Thanks in advance.

A: You do not have to write your own custom interpolator, you can use this library https://github.com/daimajia/AnimationEasingFunctions, use ExpoEaseOut
AnimatorSet set = new AnimatorSet();
set.playTogether(
         Glider.glide(Skill.ExpoEaseOut, 300, ObjectAnimator.ofFloat(mTarget, "translationY", 0, 100)
 );
set.setDuration(300);
set.start();


text:
Q: Using logical operator in knockout conditional if binding
  <button class="btn dropdown-toggle" data-toggle="dropdown">/span>/button>

I am trying to show a button with a dropdown only when the name property contains the value "Setup" or "Appeals" but it does not work. Can we use logical operator in above knockout if binding ?

A: When you are using a conditional statement inside of your binding remember that you need to 'get' the value -

  <button class="btn dropdown-toggle" data-toggle="dropdown">/span>/button>


text:
Q: after deleting and uploading new index html the browser still serves older version Mixed Content: The page at 'https://d1wktfnq0mcp3y.cloudfront.net/' was loaded

over HTTPS, but requested an insecure script 'http://code.jquery.com/jquery-latest.min.js'.
This request has been blocked; the content must be served over HTTPS.
d1wktfnq0mcp3y.cloudfront.net/:1
Unchecked runtime.lastError: The message port closed before a response was received.
d1wktfnq0mcp3y.cloudfront.net/:1
Mixed Content: The page at 'https://d1wktfnq0mcp3y.cloudfront.net/' was loaded
over HTTPS, but requested an insecure favicon 'http://example.com/myicon.png'. This request has been blocked; the content must be served over HTTPS.

the problem is that i use CDN over s3 static; but cloudfront redirects http to https; whenver it finds any "http://" in index file it throws error above.
a similar question on SO recommended to delete index.html and reupload new file index.html - doing this did not help, as the browser still shows in the "source" tab "http://". what could be the reason?


text:
Q: Why does grep seem to die after 30 minutes? I'm trying to grep my entire iMac using this command:
grep -rnwl / -e "Birthdaysx" 1>birthdaysx.txt 2>birthdaysxerrors.txt

I can see it is very busy in Activity Manager for a while, then after 30 minutes CPU usage drops to zero, although it still appears in the list, and never returns to the prompt.  (birthdaysxerrors.txt lists some Permission denied, recursive directory loop etc errors as expected.)
What can I do to keep it running?


text:
Q: Why are mapped drives available only with admin rights? I am using Windows 10 pro, version 1607, build 14393.321 the latest available at this date. Some network drives are mapped with domain group policy and logon scripts.
Opening an elevated command prompt NET USE correctly displays the mapped drive.
On the contrary opening a command prompt with user rights NET USE doesn't show the mapped drive.
The user I made the test with is in the local administrator group.
I know about EnableLinkedConnections registry key, I tried it but it doesn't work. Also, because it solves exactly the opposite problem, mapped drives which are not available with elevated rights.
How can I resolve this?


text: Q: Computing significance of a hypothesis test I am constructing a hypothesis test on a distribution $Bin(10,p)$, $H_0:p=0.5$ vs $H_1:p=0.55$.  I used R programming and I found the significance level when critical value is 8 to be 0.0546875. Why can't I get exactly 0.05?


text:
Q: Follow up question inter arrival bus problem, uniformly distributed buses Follow up on this question
Average bus waiting time
I am interested in the case where we assume that the busses are initialized uniformly and we arrive at a uniform random time. How much time do we have to wait if the bus arrival times are themselves also uniform?
The existing answers all investigate when we assume that the arrival times are discrete time intervals but the initialization is uniformly distributed. This is not the same as this question because
P(W>t) = Probability that we wait at least t minutes $!= \prod (1-t/m_k)$
I think that in this scenario we have to condition on when we saw the last bus, and evaluate from there. Does anyone have any insight into this question?


text:
Q: Initialize backbone model using its child model I have following backbone models
var Parent = Backbone.Model.extend({
    defaults: {
        id: '',
        name: ''
    }
});

var Child = Parent.extend({
    defaults: {
        color: '',
        shape: '',
        isValid: false
});

Now I have the following object of "Child" model
var child = new Child({
    id: '101',
    name: 'Abc',
    color: 'White',
    shape: 'Square',
    isValid: true
});

I need to create a "Parent" model object using this "Child" model object for which I did the following:
var json = convertToJSON(child);
var parent = new Parent(json);

But here the attributes of "Child" model are also filled into parent object of "Parent" model. Is there any way to fill only those attributes applicable to the "Parent" model in this new object? I don't want to use "delete" to remove inapplicable attributes.

A: You can use a pick method on a child model to get only required attributes
var json = child.pick('color', 'shape');
var parent = new Parent(json);

It will return an object that you can pass to a parent model.
You can read more about it here
Alternatively you can use es2015 destructive assignment but you would need Babel transpiler for it.
const {color, shape} = child;
const parent = new Parent({color, shape});

A: *

*You can use _.pick, proxied onto your child object as child.pick to pick specific attributes,

*You can extract the keys of Parent.defaults to determine what you need

This translates into :
var parent = new Parent(
    child.pick(_.keys(Parent.prototype.defaults))
);

And a demo https://jsfiddle.net/nikoshr/u5rfpa6v/


text:
Q: Angular 2 RC Final - Dynamically loading route data from service I'm trying to load route data from a service and automatically generate routes in Angular 2 RC Final. I see that you can assign route data via the Router.Module.forRoot() function but don't see a way of assigning fetched data to the function. I tried the code below but get a "Property 'forRoot' does not exist on type 'RouterModule' error".
I may be completely off the mark, but the code should show roughly what I'm trying to achieve. The app paths are: mysite.com/london/ mysite.com/new-york/, etc. Is there a way of doing this?
The router version I am using is: "@angular/router": "~3.0.1"
app.module.ts:
import { NgModule, OnInit  } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';
import { PathService } from './path.service';
import { Path } from './path';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule
    ],
    declarations: [
        AppComponent
      ],
    providers: [
        PathService
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule implements OnInit {
    private ROUTES: Array<Object>;
    private paths: Path[];

    constructor(
        @Inject(RouterModule) private _routerModule: RouterModule,
        @Inject(PathService) private _pathService: PathService) {}

    ngOnInit() {
        this.getPathData();
    }

    getPathData() {
        this._pathService.getPaths().subscribe((paths: Path[]) => this.paths = paths, (err: any) => { }, () => this.generateRoutes());
    }

    generateRoutes() {
        this.ROUTES = 'do something to this.paths and assign route date here';

        this._routerModule.forRoot(this.ROUTES);
    }
}

JSON:
[
    {
        id: "1",
        name: "London",
        path: "london"
    },
    {
        id: "2",
        name: "New York",
        path: "new-york"
    },
    {
        id: "3",
        name: "Paris",
        path: "paris"
    },
    {
        id: "4",
        name: "Tokyo",
        path: "tokyo"
    }
]

A: not sure as this seems very cutting edge. The closest to what you want is lazy loading routes. Heres a very simple demo. The routes are loaded when they are first visited on demand.
I doubt it helps but worth a shot :)
https://github.com/danday74/angular2-router-modular/blob/master/app/app-routing.module.ts


text:
Q: Sails js , How to send events in background to mobile Hi we are developing mobile app and want to sent some event triggers to mobile form sails js to mobile . We have rest services exposed over sails which mobile is consuming. Is it possible to send some events to mobile from sails and android application do some processing on getting those events..

A: Yes..!! You can use Push Notifications Or Cron Job Or Node-Schedular
There is a  npm package called "sails-service-pusher" for push notifications and
"node-schedule" for cron job.
For Background jobs You can use Cron Job.
That's the best way to trigger a events in background.


text:
Q: can't view string fields in an hdf5 file A python program (https://github.com/MannLabs/alphapeptdeep) created the following hdf5 file--> https://drive.google.com/file/d/1Ct2B7IU2WsqJfT3eGoR1xn3GSOffFqtN/view?usp=sharing
I can successfully open it up in HDFView, view metadata, and even view the data for floating point value fields.
However, for string fields, it simply gives an error (which I suspect is misleading).
For example, if one tries to view the data for this field:
/library/mod_seq_df/sequence
It gives the following (misleading?) error:
failed to read scalar dataset: Filter not available exception: Read Failed
I installed HDFView 3.1.4 on a clean debian 11 docker container. And I installed the HDF5 filter plugins as well from HDF5-1.14.0 installation scripts.
Thoughts?

A: After a little more investigation, I have some good news. I also found lots of challenges in the different HDF5 APIs.
First the good news. I can access the data in your file using h5py (a Python package). So, your HDF5 file appears to be fine. While the problems with HDFView are a headache, your errors are not caused by data corruption (or problems with compression filters).
This is what I have determined:

*

*Although the groups are named something_df and have some
attributes that look like they "could be" Pandas attributes, this
file was not created by Pandas. On closer inspection, several Pandas
attributes you would expect to find are missing.

*I opened with PyTables (the underlying HDF5 technology for Pandas), and got an error accessing Groups due to an attribute named is_pd_dataframe that is saved as an 8-bit Enum (Boolean). Apparently PyTables doesn't support that datatype.

*When I used PyTables to read a dataset of string values, I get this error: variable length strings are not supported yet. This is consistent with the Pandas error message in my earlier comment, and further confirmation the file probably wasn't created by Pandas.

*I don't know if items 2 or 3 are related to your HDFView and Java problems. I can open and view these attributes on each group's Object Attribute Info tab. (As I understand, HDFView is built with Java - so those 2 problems are consistent.)

I included my Python code (below) that extracts some data. (I know you want to work in Java, but this confirms the data is accessible.) At this point I suggest 2 paths: 1) adding HDF5/Java tags to your SO question to see if the Java community has an answer, and/or 2) contact The HDF Group about HDFView problems (you can post a question on their forum at: https://forum.hdfgroup.org/).
Python/h5py solution:
import h5py
with h5py.File('predict.speclib.hdf','r') as h5f:
    # read group attributes:
    grp = h5f['/library/mod_seq_df']
    print(f"is_pd_dataframe attribute value: {grp.attrs['is_pd_dataframe']}")
    print(f"last_updated attribute value: {grp.attrs['last_updated']}")
    print()
    # read varlength string dataset:
    ds = h5f['/library/mod_seq_df/sequence']
    print(ds.shape, ds.dtype)
    for i in range(0,5):
        print(f'{i}: {ds[i]}')
    for i in range(ds.shape[0]-5,ds.shape[0]):
        print(f'{i}: {ds[i]}')
    print()
    # read float32 dataset:
    ds = h5f['/library/fragment_intensity_df/y_z1']
    print(ds.shape, ds.dtype)
    for i in range(0,5):
        print(f'{i}: {ds[i]}')
    for i in range(ds.shape[0]-5,ds.shape[0]):
        print(f'{i}: {ds[i]}')

Output looks like this:
is_pd_dataframe attribute value: True
last_updated attribute value: Sat Dec 31 16:26:42 2022

(21785,) object
0: b'YLQEREQR'
1: b'SMLRWMER'
2: b'FIQERFER'
3: b'ENFRECLR'
4: b'FLRLCHFK'
21780: b'SGSGNETPLALKSGGGGGGSQTPR'
21781: b'AAPLLAALTALLAAAAAGGDAPPGK'
21782: b'STAVPPVPGPGPGPGPGPGPGSTSR'
21783: b'GDPGDVGGPGPPGASGEPGAPGPPGK'
21784: b'GSIFGSGGGGMSGGGGGAGGGGGGSSHR'

(277994,) float32
0: 0.0
1: 0.0649685338139534
2: 0.012746012769639492
3: 0.036795008927583694
4: 0.12544597685337067
277989: 0.10976477712392807
277990: 0.06583086401224136
277991: 0.0935806930065155
277992: 0.08901204913854599
277993: 0.2575165033340454

A: Some information may help, we used python code, https://github.com/MannLabs/alphabase/blob/main/alphabase/io/hdf.py#L242 and https://github.com/MannLabs/alphabase/blob/main/alphabase/io/hdf.py#L213, to create datasets in the hdf file. Although we call it df in this hdf file, it is still a HDF group object containing pd.Series as HDF datasets and a is_pd_dataframe attribute.
A string dataset is a numpy.ndarray with dtype('O'), and no encoding (e.g. .encode('ascii')) is involved. I guess a string value in the string dataset is still 32-bit (unicode) array?


text:
Q: Getting the value of a variable from another function I am unable to get the answer variable from the question function to check if the answer is indeed correct.
Following is what I have done so far:
import random
import operator
a = 0
ops = {
    '+':operator.add,
    '-':operator.sub
}
def generateQuestion():
    x = random.randint(1, 10)
    y = random.randint(1, 10)
    op = random.choice(list(ops.keys()))
    a = ops.get(op)(x,y)
    print("What is {} {} {}?\n".format(x, op, y))
    return a

def askQuestion():
    guess = input("")
    if guess == a:
        print("Correct")
    else:
        print("Wrong, the answer is ", a)

generateQuestion()
askQuestion()

I cut out the in between stuff which is all working fine.
I'm aware I've set a = 0 at the top as well otherwise I got a was not defined error. However, I can't get the math from outside of the generateQuestion().

A: import random
import operator

ops = {
    '+':operator.add,
    '-':operator.sub
}

def generateQuestion():
    x = random.randint(1, 10)
    y = random.randint(1, 10)
    op = random.choice(list(ops.keys()))
    a = ops.get(op)(x,y)
    print("What is {} {} {}?\n".format(x, op, y))
    return a

def askQuestion(a):
    guess = input("")
    if guess == a:
        print("Correct")
    else:
        print("Wrong, the answer is ", a)

variable = generateQuestion()
askQuestion(variable)

A: You can alleviate the need for the global by passing the answer value straight into askQuestion.
Don't forget to convert the return from input to an int, if you are running python 3. If using python 2 then you would not require the int conversion.
import random
import operator

ops = {
    '+':operator.add,
    '-':operator.sub
}

def generateQuestion():
    x = random.randint(1, 10)
    y = random.randint(1, 10)
    op = random.choice(list(ops.keys()))
    a = ops.get(op)(x,y)
    print("What is {} {} {}?\n".format(x, op, y))
    return a

def askQuestion(a):
    guess = input("")

    try:
        if int(guess) == a:
            print("Correct")
        else:
            print("Wrong, the answer is ", a)
    except:
        print('Did not input integer')

askQuestion(generateQuestion())

A: You have a scoping issue. Your variable a inside generateQuestion is not the same variable as a outside.
In order to fix this, you need to declare a as global inside generateQuestion.
import random
import operator
a = 0
ops = {
    '+':operator.add,
    '-':operator.sub
}
def generateQuestion():
    x = random.randint(1, 10)
    y = random.randint(1, 10)
    op = random.choice(list(ops.keys()))
    global a
    a = ops.get(op)(x,y)
    print("What is {} {} {}?\n".format(x, op, y))
    return a

def askQuestion():
    guess = input("")
    if guess == a:
        print("Correct")
    else:
        print("Wrong, the answer is ", a)

generateQuestion()
askQuestion()

Hav a look at this:
http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/scope_resolution_legb_rule.ipynb


text:
Q: Stubbing a module, its methods, and inner classes with RSpec I have a module like this that I'm trying to write unit tests for
module MyThing
  module Helpers
    def self.generate_archive
      # ...
      ::Configuration.export(arg)
    rescue ::Configuration::Error => error
      raise error
    end
  end
end

The ::Configuration module can't exist in my unit testing environment for reasons that are beyond my control, so I need to stub it out.  Here's what I've come up with so far.
RSpec.describe 'MyThing' do
  it 'generates an archive' do
    configuration_stub = stub_const("::Configuration", Module.new)
    configuration_error_stub = stub_const("::Configuration::Error", Class.new)

    expect_any_instance_of(configuration_stub).to receive(:export).with("arg")
    MyThing::Helpers.generate_archive
  end
end

This gets me an error.
NoMethodError:
  Undefined method `export' for Configuration:Module

If I put the configuration_stub definition inline with the expect_any_instance_of like this
RSpec.describe 'MyThing' do
  it 'generates an archive' do
    configuration_error_stub = stub_const("::Configuration::Error", Class.new)

    expect_any_instance_of(stub_const("::Configuration", Module.new)).to receive(:export).with("arg")
    MyThing::Helpers.generate_archive
  end
end

I also get an error.
NameError:
  Uninitialized constant Configuration::Error
...
# --- Caused by: ---
# NoMethodError:
#   Undefined method `export' for Configuration:Module

A: expect_any_instance_of works on instance methods. export is being called as a class method.
Instead, use a normal expect on the class.
expect(Configuration).to receive(:export).with("arg")

Note: it is not necessary to write ::Configuration in the tests. The :: is to clarify between MyThing::Helpers::Configuration and Configuration.
Note: if you're calling methods directly on Configuration it should probably be a Class not a Module.
Note: instead of calling methods on a class, consider using a Configuration object. App.config.export where App.config returns the default Configuration object. This is more flexible.
The problem with that is RSpec will verify that Configuration.export exists. It doesn't. You could turn off verification, or you could make a real class to test with.
  before {
    stub_const(
      "Configuration",
      Class.new do
        def self.export(*args)
        end
      end
    )
  }

  it 'exports' do
    expect(Configuration).to receive(:export).with("arg")
    Configuration.export("arg")
  end

You could write a stub Configuration module for testing only and put it into spec/support, but your tests are increasingly divorced from reality.
The real problem is your project should have a real Configuration class!
I'm going to guess the real Configuration contains production information which cannot be checked into the repository. This is a common anti-pattern. The Configuration module should hide the details of where the configuration values are coming from. There should be independent development, test, and production configurations. There are many ways of doing this, the most common are to use environment specific config files, or to store environment specific config values in environment variables.

While you could mock the Configuration::Error exception, there should be no reason Configuration::Error cannot exist in your test environment. Add it and simulate an error like so:
  context 'when Configuration.export raises an error'
    before {
      allow(Configuration).to receive(:export).and_raise(Configuration::Error)
    }

    it 'does whatever its supposed to do' do
    end
  end


text:
Q: Unitization of Banach algebras Is every theorem about unital Banach algebra also true for non-unital Banach algebras because of unitization?

A: Of course not. For example the Gelfand spectrum of Banach algebra is locally compact, and it is compact iff $A$ is unital. There a lot of examples in Banach homology where existence of unit plays significant role.
Another example which is more related to Banach space geometry than to Banach algebras: the Banach algebra $c_0$ have no extreme points while its unitization $c$ have $\mathfrak{c}$ extreme points.


text:
Q: How to write each JSON objects in a newline of JSON file? (Python) I am stuck with a problem, indeed I have a JSON file in which each objects is in a line. So, if there are 100 objects, there will be 100 lines.
[{ "attribute1" : "no1", "attribute1": "no2"}
{ "attribute1" : "no12", "attribute1": "no22"}]

I open this JSON file, and delete some atttributes of every elements.
Then, I want to write the objects back into the file in the same way (1 object = 1 line).
I have tried to do so with "indent" and "separators" but it does not work.
I would like to have :
[{ "attribute1": "no2"}
{"attribute1": "no22"}]

Thanks for reading.
    with open('verbes_lowercase.json','r+',encoding='utf-8-sig') as json_data:
        data=json.load(json_data)
        for k in range(len(data)):
            del data[k]["attribute1"]
        json.dump(data,json_data,ensure_ascii=False , indent='1', separators=(',',':'))
        json_data.seek(0)
        json_data.truncate()

A: I use a trick to do what I want, to rewrite all the objects into a new line. I write what I want to keep into a newfile.
with open('verbes_lowercase.json','r',encoding='utf-8-sig') as json_data:
    data=json.load(json_data)
    with open("verbes.json",'w',encoding="utf-8-sig") as file:
        file.write("[")
        length=len(data)
        for k in range(0,length):
            del data[k]["attribute1"]
            if (k!=length-1):
                 file.write(json.dumps(data[k], ensure_ascii=False)+",\n")
            else:
                file.write(json.dumps(data[length-1], ensure_ascii=False)+"]")


text:
Q: Is there any way to change the text size (font size) of specific blocks when you using asciidoc? I need your help.
Now I am using AsciiDoc and AsciiDoctor to create some manuals.
I want texts smaller on some specific blocks, for example wide table, wide list, and so on, but not want main texts smaller.
Especially I need to make texts of wide tables smaller as my customer requests so.
Is there any way?

A: You mention lists and tables...
About lists, it can't be done as stated in AsciiDoctor Documentation:

Unsupported
Complex AsciiDoc markup is not permitted in attribute values, such as:

*

*lists

*multiple paragraphs

*other whitespace-dependent markup types

As you can see, there it mentions multiple paragraphs, so while @EhmKah answer is a correct way to set a custom styling block, it won't be rendered as expected in a table/list as it's multi-paragraph.
The Built-in CSS class syntax is the way to go [small]#any phrases#
But in order to make this work in a table, you must set the cell type with a specifier in this case, the AsciiDoc specifier denoted by a
This means the cell (or column) will render supported AsciiDoc statements, attributes, etc.
Here's a working example:
[frame="none",grid="none"]
|====
a| image::images\logo.png[] a|[.small]#Autor: {author}#
|====

If you have tons of rows/columns, you don't have to manually apply the a to all of them. You can set the columns you need this behavior this way:
[cols="1a,2a",frame="none",grid="none"]
|====
| image::images\logo.png[] |[.small]#Autor: {author}#
|====

You can check its documentation for more about Column Formatting and you can check the Rendered table with variable widths and alignments sub section for more about AsciiDoc (a) and other specifiers.

A: docinfo.html + --attribute docinfo=shared
You can drop your CSS modifications into a file called docinfo.html:
<style>
/* Your custom CSS. */
</style>

and then build with:
asciidoctor --attribute docinfo=shared README.adoc

and that makes Asciidoctor 2.0.10 place docinfo.html at the bottom of the <head> element.
So you can override most of the default Asciidoctor style from there.
Then it's just a matter of understanding the generated HTML and previous style definitions to override them.
For image specifically, see also: How to set a custom image height for an image in Asciidoctor?

A: When you use a theme file, you can add a role to it like this:
role:
  mycustomfont:
    font-color: #333
    font-size:  10

Now you can reference your newly created role right from your table cell:
a|[.mycustomfont]# some text #

A: I read something about

*

*[small] and [%autofit] option https://github.com/asciidoctor/asciidoctor-pdf/issues/185 I never needed it so maybe you give it a try.

example-code
[small]
----
should be rendered in smaller font.
----

[%autofit]
----
really long text that doesn't want to fit on a single line with the default font size, so we'll make it shrink to fit.
----


text:
Q: how do you create a data frame from an existing data frame with summary I am trying to create to separate data frames what will include Avg, Max and 95th percentile fo the data by Hostname.

*

*for the Cpubusy and 2. for the UsedPercentMemory

The data frame would look something like this:
Hostname   Avg   Max 95th Percentile
Web01      10     90    92
Web02      5      80    75

dput(d)

structure(list(Hostname = structure(c(8L, 8L, 9L, 5L, 6L, 7L,
1L, 2L, 3L, 4L), .Label = c("db01", "db02", "farm01", "farm02",
"tom01", "tom02", "tom03", "web01", "web03"), class = "factor"),
    Date = structure(c(6L, 10L, 5L, 3L, 2L, 1L, 8L, 9L, 7L, 4L
    ), .Label = c("10/5/2015 1:15", "10/5/2015 1:30", "10/5/2015 2:15",
    "10/5/2015 4:30", "10/5/2015 8:30", "10/5/2015 8:45", "10/6/2015 8:15",
    "10/6/2015 8:30", "9/11/2015 5:00", "9/11/2015 6:00"), class = "factor"),
    Cpubusy = c(31L, 20L, 30L, 20L, 18L, 20L, 41L, 21L, 29L,
    24L), UsedPercentMemory = c(99L, 98L, 95L, 99L, 99L, 99L,
    99L, 98L, 63L, 99L)), .Names = c("Hostname", "Date", "Cpubusy",
"UsedPercentMemory"), class = "data.frame", row.names = c(NA,
-10L))

Is there an easy way to do this in r, I am trying to avoid loops.
I tried this:
dd %>% group_by(Hostname) %>% summarise_each(funs(mean, max))

I cannot figure out 95th percentile.

A: Not sure if this is the efficient way
library(dplyr)
library(lazyeval)
dd %>%
   group_by(Hostname) %>%
   summarise_(Mean = interp(~mean(var, na.rm=TRUE), var=as.name(m)),
              Max=interp(~max(var, na.rm=TRUE), var=as.name(m)),
              Quantile= interp(~quantile(var, prob=0.95), var=as.name(m)))