text:
Q: Problem in generation of world in predicate I'm having a problem in the generation of the world for last predicate, even though there are more than 3 signatures, only 3 are shown.
What am I missing?
Do I need to specify something in pred show(){} ?
Do I need to run the predicate enforcing a specific number of objects?
open util/boolean

// Signatures

abstract sig Sensor {
    available: one Bool
}

sig HeartRateSensor extends Sensor{}
sig BloodPressureSensor extends Sensor{}
sig SleepMonitoringSensor extends Sensor{}

sig Smartwatch {
    user: one User,
    sensors: set Sensor,
    compatible: one Bool
} {
    // Must have at least 3 different sensors:
    // HeartRateSensor, BloodPressureSensor, SleepMonitoringSensor
    all disj s, s', s'': Sensor {
        ((s in sensors && s' in sensors && s'' in sensors) &&
        (s != s' && s' != s'' && s != s'') &&
    ( s.available = True && s'.available = True && s''.available = True)) <=> compatible = True
    }
}

abstract sig Customer {
    username: lone String,
    password: lone String,
    canRegister: one Bool,
    isRegistered: one Bool
} {
    isRegistered = True => canRegister = True
    canRegister = False => isRegistered = False
    #username = 0 || #password = 0 => canRegister = False
}

sig User extends Customer {
    fiscalCodeOrSSN: lone String,
    smartwatch: one Smartwatch,
    notifications: set Notification,
    acceptsDataRequestFrom: set Company
} {
    (#fiscalCodeOrSSN = 0 || smartwatch.compatible = False) => canRegister = False
}

sig Company extends Customer {
    paymentMethod: lone String,
    queries: set Query
} {
    #paymentMethod = 0 => canRegister = False
    isRegistered = False => #queries = 0
}

abstract sig Query {
    company: one Company
}

sig AnonQuery extends Query {
    people: set User,
    isValid: one Bool
} {
    isValid = True <=> #people >= 5
}

sig IndividualQuery extends Query {
    person: one User,
    userAccepts: lone Bool, // lone cause if #userAccepts = 0 it must mean that a notification had been received by the user
} {
    all u: User {
        u = person => userAccepts = True else #userAccepts = 0 && #person.notifications > 0
    }
}

sig Notification {
    user: one User,
    company: one Company
}

// Facts: Consistency

fact UsernameConsistency {
    // There are no 2 Customer(s) with the same username
    all disj c, c': Customer | c.username != c'.username
}

fact FiscalCodeOrSSNConsistency {
    // There are no 2 User(s) with the same fiscalCodeOrSSN
    all disj u, u': User | u.fiscalCodeOrSSN != u'.fiscalCodeOrSSN
}

fact SmartWatchConsistency {
    // Let's suppose, wlog, that the cardinality of the relation
    // between smartwatch and user is 1 to 1
    all s: Smartwatch, u: User | s.user = u <=> u.smartwatch = s
}

fact QueryConsistency {
    // If a query has been made by a company
    // it must be in the set of all the queries
    // made by the company
    all q: Query, c: Company | q.company = c <=> q in c.queries
}

fact NotificationConsistency {
    // If a notification has been sent to a user
    // the user must have it in the set of
    // all notifications
    all n: Notification, u: User | n.user = u <=> n in u.notifications
}

// Assertions

// Goal G2: The system should allow users to register by providing his
// Fiscal Code or his Social Security Number, an username and a password.

assert UserCanRegister {
    all u: User {
        (
            #u.username = 1 &&
            #u.password = 1 &&
            #u.fiscalCodeOrSSN = 1 &&
            u.isRegistered = False &&
            u.(smartwatch.compatible) = True
        ) => u.canRegister = True
    }
}

check UserCanRegister for 5

// Goal G3: The system should allow companies to register

assert CompaniesCanRegister {
    all c: Company {
        (
            #c.username = 1 &&
            #c.password = 1 &&
            #c.paymentMethod = 1
        ) => c.canRegister = True
    }
}

check CompaniesCanRegister for 5

// Goal G4: The system should allow registered companies to request data
// from an anonymized group of individuals, only if individuals in the
// group are more than 1000.

assert CompaniesCanMakeAnonimizedQueries {
    all c: Company, q: AnonQuery{
        (
            c.isRegistered = True &&
            #queries > 0 &&
            #q.people >= 5
        ) => q.isValid = True && q in c.queries

    }
}

check CompaniesCanMakeAnonimizedQueries for 5

// Goal G5: The system should allow registered companies to request data
// from an individual person, only if individuals accept the request.

assert CompaniesCanMakeIndividualQueries {

    // If a company requests data from a single person
    // either
    // the person accepts <=> company is in the person acceptance list
    // or
    // the person still hasn't accepted => there's a notification concerning the company and the user in the person notification list

    all q: IndividualQuery, c: Company, n: Notification {
        (q.company = c) &&
        (
            (q.userAccepts = True <=> c in q.(person.acceptsDataRequestFrom)) ||
            (#q.userAccepts = 0 => (
                n.user = q.person &&
                n.company = c &&
                n in q.(person.notifications)
            ))
        )
    }

}

check CompaniesCanMakeAnonimizedQueries for 5

pred show(){}

run show for 10

A: Nevermind, I just figured out.
Just kidding, the problem was a strange behaviour in declaring an attribute of type String. Substituting the String declaration with a "custom" signature (for instance sig Charset {}) allowed for the world to be displayed properly.

A: See answer to : How to model a consitent database in alloy?.
For the builtin signature String to work , you have to initialize a custom "pool" of String-typed atoms.
In your case, I'd do it as follows for each signature having a string-typed field:
sig Company extends Customer {
    paymentMethod: lone String,
    queries: set Query
} {
    payementMethod in "PayPal"+ "Bank Transfer"+"Credit Card"
    ...
}


text:
Q: Pull the image path from a database and display the image What I'm trying to do is to have the user search for a product and upon searching for it, bring back an image. I want this to happen by pulling the image's path from the database and have it be part of the "" path. I've seen a few tutorials and similar questions online but all of them require the user to first upload the image (which I don't want to happen).
So the query definitely works, it pulls all text data out which can be seen when I run it. I'm lead to believe it's the path then, but I'm not sure why it's not working. I have the  and it takes the "img/ImageName path (which is pulled directly from the database. I've even played around with it, having the "img/" appear as part of the PHP (as a string). However, whenever I perform the query the only thing that shows up where the image should be is the alt "could not be found" icon.
Here's my code:
HTML:

<form action="searchDB.php" method="GET" id="searchForm">

Search for the product you want!

    <input type="text" name="product" id="product" placeholder="Product...">

    <input id="submit" type="submit" value="Search">

</form>

PHP:
<?php
$conn = new mysqli($servername, $username, $password, $dbase);

if ($conn->connect_error) {
   echo "Connection failed: ". $conn->connect_error;
}

if(empty($_GET['product']) ){
   die('please input a search!');
} else {

$product = mysqli_real_escape_string($conn, $_GET['product']);

$sql = "SELECT * FROM products WHERE product = '$product'";
$result = $conn->query($sql);

?>

<?php
if ($result->num_rows > 0){
  //output each row
  while($row = $result->fetch_assoc()){#
            echo '
';
            echo ''.$row['product'].'	';
            echo ''.$row['brand'].'	';
            echo ''.$row['cost'].'	';

   /*This is the path here, it pulls the image path from the database
   ("img/Image-Name") and puts it in a "src" attribute*/
    echo '' ."" .'	';
    echo ''.$row['specification'].'	';
    echo '
';
    echo '
';
    echo '
';
  }
} else {
   echo "Sorry, we could not find any products relating to your search.";
}

}

mysqli_close($conn);
?>

A: Change:
echo '' ."" .'	';

to either this
echo '' ."" .'	';

or to this
echo '' ."" .'	';

depending on, whether you really need the forward slash in the beginning of the path or not.

A: This will yield in invalid (or semi-valid, because HTML is very forgiveable) HTML:
echo '' ."" .'	';
//                      ^ Note the open-quote is AFTER the /
// So this will look like

Instead of what you probably want

redpajama_set_name: RedPajamaStackExchange


text:
Q: Analysis of rippled Code on Github ? Need help, lack of documentations ( specially define and macros) I am working on code produced by a company called Ripple that provides cross-currency payment solutions.
I am currently analyzing the code of their daemon server available on Github.
I might not be the first to arrive to this conclusion, but it is extremely difficult to not get lost working on someone else's large project. Although a documentation is provided, the code still does not seems understandable to me if you aren't one of the creators.
One main difficulty is that the code refers to external libraries and sometimes it feels impossible to know where to look to learn what a function does or which value a variable contains.

Simple example from my question of the moment:

I'm starting with the main.cpp file (because I assume that is what is launched when the program starts) and I have these lines:
#if defined(BEAST_LINUX) || defined(BEAST_MAC) || defined(BEAST_BSD)
#include <sys/resource.h>
#endif

I searched for a week now but I can't find what BEAST_LINUX is for.
(It is a redundant problem where macros and preprocessos instructions are called very frequently which refers to #define that refers to #define and so on, and documentation can rarely be found on the net).
Additionally, is there a quick way to discover where a variable is declared in a GitHub repository, especially when it is declared in another file ?

A: #if defined(BEAST_LINUX) || defined(BEAST_MAC) || defined(BEAST_BSD)
#include <sys/resource.h>
#endif

Let me walk you through how I would reason about this code:
First, I see that it's going to sometimes include sys/resource.h and sometimes not include it. The <> tells me that it's a system header. So this is code to decide whether or not to include a particular system header.
Second, I see that the test is for macros that differ in that one says LINUX, one MAC, and one BSD. I know these are platforms. And the test is an or.
So, now I can conclude that if a define associated with one of three platforms is set, then we include a particular system header.
Punching sys/resource.h into my favorite search engine, I find that it's part of the Single UNIX Specification. And I notice that all three platforms mentioned in the macro have a UNIX heritage.
So, in conclusion, the code appears to include a SUS header on those platforms that are expected to have that particular header. In particular, not on Windows which isn't going to have it.
By the way, I'd suggest cloning the git repository onto your own machine so you can use local search tools on it. If you're going to be analyzing a lot of code, it's worth setting up an environment that can hold code and let you compile and analyze it and then learn how to use its search and navigation tools to get around the code quickly.

A: I'm one of the developers of rippled. As the other answer alludes, this is a macro that is set to a non-zero value when the code is being compiled on a Linux platform; if it is, then it causes the preprocessor to include the specific header.
This define was, originally, in a library named Beast. Large parts of that library were moved out of Beast and into the Ripple source, to help facilitate inclusion of Beast's awesome websocket and http routines into Boost.
If you are working under Windows, there is a Visual Studio project which, when loaded, makes discovering symbols and code call graphs pretty easy using the tools built-in to Visual Studio.
I also have a Doxygen build, which produces nice documentation of classes and comments, along with a cross-reference. I'll see about making it available publicly over the web.

A: This seems to be a macro
#if (defined (_WIN32) || defined (_WIN64))
  #define       BEAST_WIN32 1
  #define       BEAST_WINDOWS 1
#elif defined (BEAST_ANDROID)
  #undef        BEAST_ANDROID
  #define       BEAST_ANDROID 1
#elif defined (LINUX) || defined (__linux__)
#define BEAST_LINUX 1

defined in this source Beast: An amazing cross platform library in this file PlatformConfig.h. This is an old source however, the new library doesn't contain this define anymore. This new library is located here Beast, also submitted to Boost.
You can search specific repository for code by using Github search, however, it only works on latest file versions. To do a search for all file versions you'll need to do it from command line, as explained here GitHub: searching through older versions of files. There's no fast way to search for variable or macro definition, except if your IDE supports go to definition functionality.


text:
Q: Correct way to test if Single values equal Nothing The following line of code gives a warning with Resharper: 'Comparison of floating point numbers with equality operator. Possible loss of precision while rounding values.'
Dim samples() As Single

If samples(i) = Nothing Then
    samples(i) = _mPreviousSamples(i)
End If

What is the best way of checking if a value is present?

A:
What is the best way of checking if a value is present?

I think you have the wrong concept "Nothing" with regards to value types such as Single.  For value types, Nothing is more correctly interpreted as the default value for the type: in the case of a Single, 0.0.
If you want to know if a value is present with a value type, you need to first initialize the value type to hold a value that could never exist in this context otherwise. For primitive types such as Single, Nothing is rarely good enough.  In the case of Single, try using Single.NaN, and check the values using Single.IsNan()

A: I don't know VB.NET that well, but in C# I would do something like float? samples = null;.
Can you declare it as a nullable like Dim s As System.Nullable(Of Single) = Nothing?

A: Dim samples As System.Nullable(Of Single) = Nothing
If samples.HasValue Then
    Console.WriteLine(samples.Value)
Else
    Console.WriteLine("samples is Nothing")
End If

EDIT: Precisions:
In most cases you can use the Nullable(Of Single) just like a Single. VB automatically converts it to a Single where appropriate. Where not, just use the Value property as in the example above. Instead of Nullable(Of Single) you can also write Single? with a question mark. Instead of testing the samples.HasValue property you can also test samples IsNot Nothing.
Dim samples As Single? = Nothing
If samples Is Nothing Then
    Console.WriteLine("samples is Nothing")
Else
    Console.WriteLine(samples)
End If


text:
Q: Trying to count per month for 2000 , but get an error "ORA-00904: "MONTH": invalid identifier" SELECT COUNT(*) AS PerMonth
FROM NAS_CUSTOMER
WHERE YEAR(CUST_BIRTH) = '2000'
GROUP BY MONTH(CUST_BIRTH)

A: Oracle doesn't have a MONTH() function.  You can use EXTRACT():
SELECT EXTRACT(MONTH FROM CUST_BIRTH), COUNT(*) AS PerMonth
FROM NAS_CUSTOMER
WHERE CUST_BIRTH >= DATE '2000-01-01' AND
      CUST_BIRTH < DATE '2001-01-01'
GROUP BY EXTRACT(MONTH FROM CUST_BIRTH);

Similarly for YEAR(), but I replaced that with explicit date comparisons.

A: One way is to use the TO_CHAR() function.

SELECT TO_CHAR(CUST_BIRTH,'mm'),COUNT(*) AS PerMonth
FROM NAS_CUSTOMER
WHERE TO_CHAR(CUST_BIRTH,'yyyy') = '2000'
GROUP BY TO_CHAR(CUST_BIRTH,'mm')


text:
Q: Square Point of Sale API - Error code "amount_too_small", but card is charged? i'm making calls to the square pos ios web api with charges of $1.00 for system integration testing.
the calls are successful, in that they switch control to the square app, the card gets charged $1.00, transactions show up in the dashboard, i can refund them, etc. so obviously i'm sending the minimum amount suggested in the documentation to test the api (https://docs.connect.squareup.com/articles/web-api-ios) due to the lack of a point of sale api sandbox?
why does the response return a status of "error" with an error_code of "amount_too_small" when it was processed successfully?

A: Make sure you are using an amount of at least 100 to represent $1 (or 100 cents). You should only get this error if you try to charge an amount lower than 100.
My guess is that you are seeing transactions that you made previously, or you are getting replayed responses by reusing idempotency keys. If you are in fact getting an error in response while a transaction is being created, it seems like there is something wrong with our system. Could you record a video of what you are doing, or some detailed logs of requests & responses with headers?


text:
Q: UITableView first cell not set The first row of my UITableViews are all blank, even though my NSLog's in function tableView .. cellForRowAtIndexPath, shows that row 0, 1, 2, ... are call call and initialized.
I make four UITableViews side-by-side, each with 40 rows.  NSLog's show that the function with cellForRowAtIndexPath is called for all 40 rows, but each display row 0 is empty.  Displayed row 1 contains the cell that I expect at row 0, row 2 contains the one for row 1, etc.
Here's the code that creates the UITableView data structure, and the function cellForRowAtIndexPath which builds its cells.
Here's the array of four UITableViews at the .m file scope level (at its beginning):
UITableView* channel_tableView[ TOTAL_TX_CHANNELS ];

And here's where the UITableViews are create in the function viewDidLayoutSubviews:
    for( int channel=0; channel < TOTAL_TX_CHANNELS; ++channel )
    {
        // Create channel_tableView:

            CGRect tableFrame = CGRectMake(x, y, width, height);

            channel_tableView[ channel ] = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];

            channel_tableView[ channel ].rowHeight = channel_row_height;
            channel_tableView[ channel ].sectionFooterHeight = 0;
            channel_tableView[ channel ].sectionHeaderHeight = 0;
            channel_tableView[ channel ].scrollEnabled = YES;
            //new_channel_tableView.showsVerticalScrollIndicator = YES;
            channel_tableView[ channel ].userInteractionEnabled = YES;
            channel_tableView[ channel ].bounces = YES;

            channel_tableView[ channel ].delegate = self;
            channel_tableView[ channel ].dataSource = self;

        //  channel_tableView[ channel ].autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
            [channel_tableView[ channel ]  reloadData];             // display channel's TableView
            [[self view] addSubview:   channel_tableView[ channel ]];
    }

And here's the function that creates all the cells:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog( @"cellForRowAtIndexPath");
    NSLog( @"   %d  = row", indexPath.row  );

    UITextView*  test_textView;
    UITextView*  test_2nd_textView;
    UITextView*  test_3rd_textView;

    // Determine which channel_tableView:
        int channel;
        for( channel = 0; channel < TOTAL_TX_CHANNELS; ++channel )
        {
            if( tableView == channel_tableView[ channel ] )
                break;
        }
        // channel = tableView's channel
        NSLog( @"   %d  = channel", channel  );

    // DOCUMENTATION:  Table View Programming Guide for iOS > Adding subviews to a cellís content view
    // Give each cell a cell identifier unique to each channel tableView and unique to each row, so that each gets a unique data structure:
            NSString *CellIdentifier = [NSString stringWithFormat:@"%d_%d",channel,indexPath.row];

    //static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        // if nil: cell(chan, row) has not been created before.  <>nil: cell = data structure previously initialized
    if (cell == nil)
    {
        NSLog( @"       cell nil");
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
        /* Though it's UITableViewCellStyleDefault, the three defaults (image, label, detail label) are nil
        if not set. */
    }
        // Add UITextView for channel pipe to cell:
            int pipe_width = 20;
            int w = pipe_width;
            int x = channel_tableView_width/2 - pipe_width/2;
            int h = channel_row_height;
            int y = 0;
            test_textView = [[UITextView alloc] initWithFrame:CGRectMake    (x,y, w,h)] ;
            [test_textView setFont:[UIFont boldSystemFontOfSize:8.0]];
            [test_textView setEditable:NO];
            [test_textView setTextAlignment:NSTextAlignmentCenter];
            // Round the corners and set border color
            if(channel == power_channel )
                [test_textView setBackgroundColor:[UIColor greenColor]];
            else
                [test_textView setBackgroundColor:[UIColor whiteColor]];
            [[test_textView layer] setBorderColor:[[UIColor blackColor] CGColor]];
            [[test_textView layer] setBorderWidth:1];
            //[[test_textView layer] setCornerRadius:15];
            [test_textView setClipsToBounds: YES];

        // Add UITextView for PWR RX to cell:
        int PWR_RX_width = channel_tableView_width/2;
         y = y + h ;
         w = PWR_RX_width;
         x = channel_tableView_width/2 - PWR_RX_width/2;
         h = 20;
            test_2nd_textView = [[UITextView alloc] initWithFrame:CGRectMake    (x,y, w,h)];
            [test_2nd_textView setFont:[UIFont boldSystemFontOfSize:8.0]];
            [test_2nd_textView setEditable:NO];
            [test_2nd_textView setTextAlignment:NSTextAlignmentCenter];
            // Round the corners and set border color
            [test_2nd_textView setBackgroundColor:[UIColor whiteColor]];
            [[test_2nd_textView layer] setBorderColor:[[UIColor blackColor] CGColor]];
            [[test_2nd_textView layer] setBorderWidth: 1];
            //[[test_2nd_textView layer] setCornerRadius:15];
            [test_2nd_textView setClipsToBounds: YES];

        // Add UITextView for device to cell:
        int device_width = channel_tableView_width/2;
         y = y + h-3;
         w = device_width;
         x = channel_tableView_width/2 - device_width/2;
         h = 40;
            test_3rd_textView = [[UITextView alloc] initWithFrame:CGRectMake    (x,y, w,h)];
            [test_3rd_textView setFont:[UIFont boldSystemFontOfSize:8.0]];
            [test_3rd_textView setEditable:NO];
            [test_3rd_textView setTextAlignment:NSTextAlignmentCenter];
            // Round the corners and set border color
            [test_3rd_textView setBackgroundColor:[UIColor whiteColor]];
            [[test_3rd_textView layer] setBorderColor:[[UIColor blackColor] CGColor]];
            [[test_3rd_textView layer] setBorderWidth: 1];
            //[[test_3rd_textView layer] setCornerRadius:15];
            [test_3rd_textView setClipsToBounds: YES];

        /*
                test_textView.tag = TEST_TEXTVIEW_TAG;
                test_2nd_textView.tag = TEST_2ND_TEXTVIEW_TAG;
                test_3rd_textView.tag = TEST_3RD_TEXTVIEW_TAG;

        test_textView     = (UITextView*)[cell.contentView viewWithTag: TEST_TEXTVIEW_TAG];
        test_2nd_textView = (UITextView*)[cell.contentView viewWithTag: TEST_2ND_TEXTVIEW_TAG];
        test_3rd_textView = (UITextView*)[cell.contentView viewWithTag: TEST_3RD_TEXTVIEW_TAG];
         */
    //[test_textView setText:     [NSString stringWithFormat: @"pipe-%d", indexPath.row ]];
    [test_2nd_textView setText: [NSString stringWithFormat: @"PWR RX %d", indexPath.row + 1 ]];
    [test_3rd_textView setText: [NSString stringWithFormat: @"device %d", indexPath.row + 1 ]];
            // Add created UI objects to cell[ indexPath.row ]:
                [cell.contentView addSubview:test_textView ];
                [cell.contentView addSubview:test_2nd_textView ];
                [cell.contentView addSubview:test_3rd_textView ];
    return cell;
}

SCREENSHOT SHOWING BLANK ROW-0 ..............................

A: Your test_2nd_textView and test_3rd_textView are being drawn outside the first table cell (which is not clipping), because you're initializing them with a frame with the y>=cell_height. For test_textView, y=0, h=cell_height. For test_2nd_textView, y=cell_height and h=20, hence test_2nd_textView is drawn at the top of the second cell.


text:
Q: Two associations for the same table resulting in a collision I have videos and artists, video belongsTo artist and artist hasMany videos.
I did it and is working, when I find videos and set [contain => ['Artists'] I got the result videos entity with the related artist.
This first relationship is about the artist that is the "owner" of the video, but I need another relationship because a video could have N others artists "featuring" the video.
Heres a better overview:
Tables:
videos: id (pk), artist_id (fk)
artists_videos: video_Id (pk), artist_id (pk)
artists: id (pk)
-
Heres the code:
//VideosTable
$this->BelongsTo('Artists');
$this->belongsToMany('Artists');

//ArtistsTable
$this->hasMany('Videos');
$this->belongsToMany('Videos');

The issue is, when I set this second relationship the first relationship stops to work, I think is happening some kind of collision.

A: You need to call these associations with different names:
$this->belongsTo('Comments', [
            'className' => 'Comments',
            ...
        ]);

$this->hasMany('UnapprovedComments', [
            'className' => 'Comments',
            ...
        ]);

... so they're treated by the ORM as separate instances.

A: You can try this since you defined "videos" belongsToMany "artists" [As per your Tables] and artists hasMany videos
In the Videos Table:
$this->belongsTo('Artists', [
            'foreignKey' => 'artist_id'
        ]);

$this->belongsToMany('Artists', [
            'foreignKey' => 'video_id',
            'targetForeignKey' => 'artist_id',
            'joinTable' => 'artists_videos'
        ]);

In the Artists Table:
$this->hasMany('Videos', [
                'foreignKey' => 'artist_id'
            ]);
$this->belongsToMany('Videos', [
            'foreignKey' => 'artist_id',
            'targetForeignKey' => 'video_id',
            'joinTable' => 'artists_videos'
        ]);

you can check the example at CakePHP Examples
Then try from the CakeDoc
$this->hasMany('Comments', [
        'className' => 'Comments',
        'conditions' => ['approved' => true]
    ]);

    $this->hasMany('UnapprovedComments', [
        'className' => 'Comments',
        'conditions' => ['approved' => false],
        'propertyName' => 'unnaproved_comments'
    ]);


text:
Q: Noetherian module over two rings Let $f : R → S $  be a surjective ring homomorphism.
How can I show the following statement:
An $S$-module $M$ is Noetherian if and only if it is Noetherian as $R$-module.

A: We have $S \cong R/I$ where $I$ is the kernel of the homomorphism. Now, the $R$-submodules of $M$ are precisely the $R/I$-submodules of $M$, which means that $M$ satisfies the ascending chain condition as an $R$-module if and only if it satisfies the ascending chain condition as an $R/I$-module.
Note that the isomorphism $S \cong R/I$ is sufficient for the result to follow, because of the way we define the action of $S$ on $M$.


text:
Q: Как заменить стандартное всплывающее окно на google maps, когда кликаешь на маркер? Как заменить стандартную всплывашку на google maps, когда кликаешь на маркер?

A: Это infoWindow, в Google Картах можно поменять как:
1) Самый популярный способ - с помощью infoBubble.
Пример использования этого infoBubble можно увидеть на этом сайте.
2) Можно кастомизировать infoWindow, например, как вот тут - пример от Google. Требует больше кода, но зато работать должно ок.
3) для стилей вместо infoWindow можно попробовать infoBox, пример использования его можно увидеть тут.


text:
Q: What is the difference between Font Awesome 4 and 5? Could you please write me : what is the difference between Font Awesome 4 and 5?
and what is the difference between :

Thank You !

A: Font Awesome 5 is a big refactoring of Font Awesome including new icons and breaking changes.
fas FontAwesome CSS class stands for font awesome solid (the Solid icon style) but fa is also kept for retro-compatibility. So, there is no difference between fas an fa that both applies the Solid icon style.
Regarding the differences between Font Awesome 4 and 5 :

*

*5 icons styles (Solid, Brands, Regular, Light and Duotone) but only the first two are free (Solid and Brands)

*some icons have new names

*now all icons have an "outlined" style but this is in the Regular icon style which is not free. As a consequence, icons previously ending by -o does not exist anymore in FontAwesome version 5 Free.

Also have a look at the page Upgrade From Version 4 of Font Awesome docs for more info.


text:
Q: C# Azure Face AI try to recognize people in image My goal is to check if the system know/don't know the person who is sitting in front of my webcam.
First I tried it in a Console App and everythink worked fine but now I what to have a "nice" operlay in WPF and I inplement all in my WPF App even a Anti UI Block System but now I get a exeption

I know thats a big exeption. I'm sorry that the exeption is written in German (I can't change it). What is says: System.Net.Http.HttpRequestException: Error while sending and the remotehost closed a connection.
Here is the methode that triggers that exeption:
private static async Task<List<DetectedFace>> DetectFaceRecognize(IFaceClient faceClient, string path, string recognition_model)
    {
        try
        {
            FileStream fs = File.OpenRead(path);

            IList<DetectedFace> detectedFaces = await faceClient.Face.DetectWithStreamAsync(fs, detectionModel: DetectionModel.Detection03);//Exeption triggert here
            Console.WriteLine($"{detectedFaces.Count} face(s) detected from image `{Path.GetFileName(path)}`");

            fs.Close();
            return detectedFaces.ToList();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
            return await DetectFaceRecognize(faceClient, path, recognition_model);

        }
    }

Can someone help me with this exeption?

A: Can you explicitly set the TLS version by adding the following line
 System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;


text:
Q: how set a specifc database schema with gorm? I'm developing an CRUD app. I'm reading an JSON from an api and I want to write this JSON in a database with "database/sql" and GORM in a spcific schema
the struct:
type Veiculo struct {
gorm.Model
Codigo                int       `json:"vei_codigo"`
Placa                 string    `json:"vei_placa"`
Nome                  string    `json:"vei_nome"`
}

the endpoint function:
func CreateVeiculo(c *gin.Context) {

var veiculo model.Veiculo
//id := c.Params.ByName("id")

c.BindJSON(&veiculo)
c.JSON(200, veiculo)

psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+" password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
dbVeiculosGorm, err := gorm.Open("postgres", psqlInfo)
if err != nil {
    panic(err)
}
defer dbVeiculosGorm.Close()

dbVeiculosGorm.AutoMigrate(&model.Veiculo{})

//t := time.Now()
//ts := t.Format("2006-01-02 15:04:05")

dbVeiculosGorm.Create(&model.Veiculo{Placa: veiculo.Placa, Nome: veiculo.Nome}

but the database is untouchable. There is multiple schemas. Do i have to set the specific schema?? What am i doing wrong?

A: Using GORM 2.0 This will work. Note the . has to be added for the TablePrefix.
func ConnectDB() (db *gorm.DB, err error) {
    db, err = gorm.Open(postgres.New(postgres.Config{
        DSN:                  `user=test password=test dbname=DB-NAME port=5432 sslmode=disable`,
        PreferSimpleProtocol: true,
    }), &gorm.Config{
        NamingStrategy: schema.NamingStrategy{
            TablePrefix:   "YOUR_SCHEMA_NAME.", // schema name
            SingularTable: false,
        }})
    return
}

A: before automigrate do
gorm.DefaultTableNameHandler = func(dbVeiculosGorm *gorm.DB, defaultTableName string) string {
    return "your schema name." + defaultTableName
}

dbVeiculosGorm.AutoMigrate(&model.Veiculo{})

A: To specify specific schema in your create statement modify your code like so:
dbVeiculosGorm.Table("schema.tablename").Create(&model.Veiculo{Placa: veiculo.Placa, Nome: veiculo.Nome}

To specify schema for your migrate action, add this method:
type Veiculo struct {
    gorm.Model
    Codigo int    `json:"vei_codigo"`
    Placa  string `json:"vei_placa"`
    Nome   string `json:"vei_nome"`
}

func (u *Veiculo) TableName() string {
    // custom table name, this is default
    return "schema.veiculo"
}

A: The Answer of @hbswift also worked for me but I tried something before which is a little bit different inspired by latest gorm Close idea.
func ConnectDB() (db *gorm.DB, err error) {
    db, err = gorm.Open(postgres.New(postgres.Config{
        DSN:                  `user=postgres password=a12345 dbname=YOUR-DB-NAME port=5432 sslmode=disable`,
        PreferSimpleProtocol: true, // disables implicit prepared statement usage. By default pgx automatically uses the extended protocol
    }), &gorm.Config{})
    return
}

func main() {
    var sqlDB *sql.DB
    var db *gorm.DB
    {
        var err error
        db, err = ConnectDB()
        if err != nil {
            os.Exit(-1)
        }
        sqlDB, _ = db.DB()
        sqlDB.Exec(`set search_path='Schema-Name'`)
    }
    defer sqlDB.Close()

}

A: In Addition to Alan.WCR to Capitalize Table name,
gorm.DefaultTableNameHandler = func(db *gorm.DB, table string) string {
    var tableName string
    names := strings.Split(table, "_")
    for _, name := range names {
        tableName = tableName + strings.Title(name)
    }
    return "Users." + tableName
}

A: I use this configuration with my database with singular names with postgresql.
gorm.DefaultTableNameHandler = func(db *gorm.DB, table string) string {
    fmt.Printf(table)
    return "schema_name." + table[:len(table)-1]
}

A: I don't have the reputation to comment yet or I would comment on Yurifull's post. It is worth mentioning that singularizing is a big more complex than chopping off the last character. Fortunately, jinzhu has split the singularization logic out into its own package so we can update Yurifull's code to look like:
import (
    "github.com/jinzhu/inflection"
)

...

gorm.DefaultTableNameHandler = func(db *gorm.DB, table string) string {
    fmt.Printf(table)
    return "schema_name." + inflection.Singular(table)
}

A: Here's a basic example of pretty much all you need to insert some simple data into a PostgreSQL database via gorm.

main.go

package main

import (
    "log"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres" // Don't forget the dialect
)

// Simple Example model
type FuelType struct {
    gorm.Model // Gorm default columns (id, created_at, updated_at, deleted_at)
    Name string
}

func main() {
    // Database initialization
    db, err := gorm.Open(
        "postgres",
        "host=localhost port=5432 user=postgres dbname=foo password=bar sslmode=disable",
    )
    if err != nil {
        log.Fatalln("Can't connect to the db: ", err)
    }
    defer func() {
        if err := db.Close(); err != nil {
            log.Fatalln("Can't close the db connection: ", err)
        }
    }()

    // Migration
    db.AutoMigrate(&FuelType{})

    // Insertion
    fuelType := FuelType{Name: "100 GFuel"}
    db.Create(&fuelType)
}

A: If you are using the latest version of gorm this WILL not work:
gorm.DefaultTableNameHandler = func(dbVeiculosGorm *gorm.DB, defaultTableName string) string {
    return "your schema name." + defaultTableName
}

dbVeiculosGorm.AutoMigrate(&model.Veiculo{})

Instead define your naming convention in the gorm config. Example:
    dsn := "host=localhost user=myuser dbname=golang_tutorial port=5432"
    db,err := gorm.Open(postgres.Open(dsn), &gorm.Config{
            NamingStrategy: schema.NamingStrategy{
                TablePrefix: "golang_crud.", // schema name
                SingularTable: true,
            },
    })

A:
Please check with this code my testing is on

package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
type User struct {
ID       int
Username string
}
func main() {
db, err := gorm.Open("postgres", "host=localhost port=5432 sslmode=disable dbname=aman")
if err != nil {
panic(err)
}
defer db.Close()
db.LogMode(true)
// set schema here.
gorm.DefaultTableNameHandler = func(db *gorm.DB, tableName string) string {
    return "s1." + tableName
}

db.CreateTable(&User{})

}


text:
Q: Dual Booting with GRUB I currently have Ubuntu and XP as dual boot using GRUB. The Ubuntu version is old and I want to blow it away and do a fresh install of a modern version.
I want to keep XP and GRUB. It seems every article assumes you want to remove both! Does anyone know how to remove the current version of Ubuntu and then install another without removing GRUB and breaking things?

A: Most modern Desktop Linux installs are smart enough to keep Windows partitions and automatically add them to the Grub boot script.  I haven't used newer Ubuntu versions, but I know openSUSE does this.
That said, I would attempt to run through a newer Ubuntu install and see what it says when the auto-partitioning comes up.  See if it sets up a mount point for the current Windows installation.

A: If you overwrite the old version of Ubuntu using the partitioner available in the setup, it should detect Windows XP with os-prober and install GRUB fresh into your MBR.


text:
Q: Java - Garbage arraylist field of objects in static arraylist please look at this :
class MyUtility{

public static MyStock stock;

}

class MyStock{

public ArrayList<SomeThing> myListOfThings;

}

class SomeThing{

public ArrayList<WhatEver> myWhatever;
public double [] myArray;

}

so i can everywhere access MyUtility.stock (thread safe is not the question)
I know the GC wont clean "myListOfThings", and i dont care : this list is global and static for good reason.
But Will the GC clean "myWhatever" ? And if not, how to force/let it elligible to ?
i mean : if in the life of one "SomeThing" , "myWhatever" arraylist size goes to 123 then 0, or myArray goes from new double[123] to null;

A: You cannot force GC to run.

Automatic garbage collection is the process of looking at heap memory,
  identifying which objects are in use and which are not, and deleting
  the unused objects. An in use object, or a referenced object, means
  that some part of your program still maintains a pointer to that
  object. An unused object, or unreferenced object, is no longer
  referenced by any part of your program. So the memory used by an
  unreferenced object can be reclaimed.
In a programming language like C, allocating and deallocating
  memory is a manual process. In Java, process of deallocating memory is
  handled automatically by the garbage collector.
     https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

If you want GC to be able to clear memory used "myWhatever"
then you need OR to clear the list: so any objects hold by the list(but not referenced in other part) will be cleared or make the list null it will have the same effect.
myWhatever.clear();

OR
myWhatever = null;

In first case you will still have the reference to an empty list, so you will not have to recreate it, in second case you will mark also the reference to the list that is eligible for GC.

A: System.gc() lets JVM know that you want to garbage collect, it does not guarantee that it will happen though.
Your object can be garbage collected when there are no more references pointing to it.


text:
Q: jqgrid not passing search filter data type on refresh of grid When loadig the grid for the first time the json data that gets sent to my search method on the server for the filter property has a value of:
{"groupOp":"AND","rules":[{"field":"ModifiedBy","op":"cn","data":"SomeData","type":"text"}]}

But when I click the refresh button on the jqgrid the json data for the filter property is:
{"groupOp":"AND","rules":[{"field":"ModifiedBy","op":"eq","data":"Somedata"}]}

Notice it is missing the type attribute. Does anyone have any ideas on why this might be happening?

A: If you click on "Refresh" button the value of the filters parameter which should be send to the server should be
{"groupOp":"AND","rules":[]}

If you has another values you should post the code of the grid and describe the use case. If one could reproduce your problem one can either find a bug in jqGrid or in your program.
Which version of jqGrid you use?


text:
Q: Need Advice on designing ATL inproc Server (dll) that serves as both a soure and a sink of events I need to design an ATL inproc server that besides exposing methods and properties, also can fire events (source) and serve as a sink for a third party COM control that fires events.  I would assume that this is a fairly common requirement.  I can also foresee several "gotchas" that I would like to read up on before commencing the design.  My questions/concerns are:

*

*Can someone point me to an example?

*Which threading model to use?

*Should I have a seperate COM object for the sink?

*Should I, and how do I, protect certain memory.  For example, my server will receive data from the third party control.  It will save this, and in some cases, fire an event to interested clients.  The interested clients will request the data through a standard method or property.  I did try to research this myself. I can find many  examples of COM servers that are soures, and some that are sinks, but never both.  The only post I did find was this:
http://www.generation-nt.com/us/atl-control-an-event-source-sink-help-9098542.html
Which strongly advocates putting the sink on a seperate COM object.

Any leads, tutorials or ideas would be much appreciated.
Thanks,
Andrew

A: Check out ATL connection points, which will take care of the boiler plate code.  This link provides an over view and sample code: http://msdn.microsoft.com/en-us/library/h7kad5hw(v=vs.90).aspx


text:
Q: Dropping a process into the background If I have started a process, and it spends more time than I anticipated, and I regret not having said rm foo & rather than rm foo, can I do something to drop it into the background?

A: In pretty much any shell you're likely to be using, you should be able to press control-Z to suspend the process and then use the bg command to resume it in the background.
e.g.
$ sleep 1000
^Z[1] + Stopped                  sleep 1000

$ bg
[1] sleep 1000&

$ jobs
[1] +  Running                 sleep 1000

$

Note that some jobs (e.g. those that ask for user input) will not run in the background and will stop, waiting to be brought back to the foreground (fg).
(There are shells and situations where this doesn't work, but they tend to be highly specialised - eg embedded systems - or very very old versions of unix).

A: Another option could be the use of screen or tmux. You can detach your current session and continue your work later, even from another system. The biggest gain is that the session is automatically detached when the line hangs up. With tmux you can even split the screen into panes, switching between them and rearrange the portions with the mouse.


text:
Q: Bootstrap 3 .container-fluid with a 50-50 split Here's my challenge. The design calls for a full width row with a 50-50 split. Each half is a different colour. Ok, easy enough. Other rows will be the fixed .container width with 12 columns
In each half, on desktop, the content would conform to a fixed container width, each width 6 columns, on large, then 12 on mobile.
I've attached a slice from the PSD.

Here's my initial code as i work through this.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Copy example

Copy example

I'm unsure how to have the content sit within the 1170 container width, without a lot of custom CSS and html.

A:

Header 1

Copy example

Header 2

Copy example

A: Another way to do that without so much code. Is dealing more with structure. Mantaining responsivity and using bootstrap 4 classes:
HTML

left split

right split

left content

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eget mauris ut enim scelerisque sollicitudin in nec nisl. Quisque arcu arcu, bibendum id nunc sit amet, auctor bibendum tellus. Sed non scelerisque nulla. Sed pharetra lacus sapien, et condimentum
        ante condimentum non. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce magna lorem, lacinia congue varius blandit, facilisis quis nulla. Maecenas eu finibus tortor, sed volutpat justo. Fusce pulvinar

right content

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eget mauris ut enim scelerisque sollicitudin in nec nisl. Quisque arcu arcu, bibendum id nunc sit amet, auctor bibendum tellus. diam at placerat consectetur. Aliquam nec nisl luctus, imperdiet
        dolor non, feugiat ligula.

CSS
.background-holder {
  overflow: hidden;
  margin: 0 auto;
  position: absolute;
  height: 100%;
  pointer-events: none;
  z-index: -1;
}

.container {
  border-left: 2px solid red;
  border-right: 2px solid red;
}

jsfiddle DEMO


text:
Q: Whats the best way to work with formview and .findcontrol I have formview and add logic to it when updating,inserting etc... However on each subroutine, I had to a a variable and a findcontrol in order to work with that control. Now, my code is bigger and harder to read.
My other approach was to put the 'fincontrols' outside the routines but I would get errors that it could not be found.
Is there a cleaner , better approach when working with controls on a formview?

A: This is how I use the find control function:
TextBox txt_test = (TextBox)FormView1.FindControl("txt_test");

as far as I know this is the easiest and cleanest way I could find.


text:
Q: How do I use an HTML inline tag inside a string? I have an svg icon (which is the symbol of the Enter key):

    <svg width="15" height="15" aria-label="Enter key" role="img">
        <g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2">
            <path d="M12 3.53088v3c0 1-1 2-2 2H4M7 11.53088l-3-3 3-3"></path>
       </g>
   </svg>

I have an input text field like this:
<input type="text" placeholder="Press the ENTER key">

I want to append the svg icon inside the placeholder of the input field, such that the placeholder is like

Press the <-| key

How do I achieve this?
EDIT: The button icons should be like this:
enter image description here

A: You can't do it with placeholder property since it only supports text.
If your icon can be a font icon, you could do it as Use Font Awesome Icon in Placeholder.
There's a workaround that you could fake a placeholder using :placeholder-shown pseudo class, so the "placeholder" can be anything.
For example:

.input-wrapper {
  position: relative;
}

.input-wrapper .placeholder {
  display: none;
  height: 100%;
  top: 0;
  left: 8px;
  align-items: center;
  position: absolute;
  pointer-events: none;
  opacity: 0.5;
  font-size: 0.8em;
}

.input-wrapper input:placeholder-shown + .placeholder {
  display: flex;
}

/* customization */
input {
  padding: 6px;
}

.DocSearch-Commands-Key {
  border: solid 1px #ccc;
  border-radius: 4px;
  height: 16px;
  display: flex;
  align-items: center;
  margin: 0 4px;
  margin-top: -1px;
  padding: 0 4px;
  box-shadow: 0px 2px 0px rgba(0, 0, 0, 0.4);
  background-color: #eee;
}

  <input type="text" placeholder=" ">

    Press the

      <svg width="15" height="15" aria-label="Enter key" role="img">
        <g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2">
            <path d="M12 3.53088v3c0 1-1 2-2 2H4M7 11.53088l-3-3 3-3"></path>
        </g>
      </svg>

     key

A: First, you need to convert your SVG to URI to use as a background.
I used the following site to convert the SVG to URI
SVG to CSS background-image converter
Then you need to adjust the width of your input field to show it in the centre of the text.
You can also adjust the width of the SVG to adjust it between words.

function myFunction()
{
  let input = document.getElementById('input')
  if(input.value.length>0)
    {
    input.style.background = 'none'
    }
  else{
    input.style.background = `url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='15' height='15' aria-label='Enter key' role='img'%3E%3Cg fill='none' stroke='currentColor' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.2'%3E%3Cpath d='M12 3.53088v3c0 1-1 2-2 2H4M7 11.53088l-3-3 3-3'%3E%3C/path%3E%3C/g%3E%3C/svg%3E")center / contain no-repeat`;
  }
}
label {
  position: relative;
}

input {
  padding: 10px 10px;
  width: 150px;
  border: none;
  border-left: 2px solid black;
  outline: none;
    background: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='15' height='15' aria-label='Enter key' role='img'%3E%3Cg fill='none' stroke='currentColor' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.2'%3E%3Cpath d='M12 3.53088v3c0 1-1 2-2 2H4M7 11.53088l-3-3 3-3'%3E%3C/path%3E%3C/g%3E%3C/svg%3E")center / contain no-repeat;
background-origin:border-box;
}

  <input type="text" placeholder="Press the           Key" id='input' oninput="myFunction();"/>


text:
Q: What is the best evaluation of training the sequential modeling? It's concerned with the probabilistic modeling of the sequential dataset.
As far as my understanding, well-known RNN methodologies consist of two steps:

*

*firstly, train the model representing $p(y_{i}|y_{i-1})$
with respect to the loss calculated from the pair of consecutive samples $(y_{i-1}, y_{i})$,

*and then, consequently obtain $p(y_{N}, \cdots y_{1}|y_{0}) = p(y_{N}|y_{N-1})\cdots p(y_{1}|y_{0})$
given a sequence $(y_{0}, y_{1}, \cdots, y_{N})$.

However, there can be another option for training:

*

*sample any sequence from the dataset: $(y_{0}, y_{1}, \cdots, y_{N})$

*and then train $p(y_{i}|y_{i-1})$ with respect to the loss evaluating $p(y_{N}, \cdots y_{1}|y_{0}) = p(y_{N}|y_{N-1})\cdots p(y_{1}|y_{0})$
(e.g. logarithm likelihood, Wasserstein distance, etc.).

Those two methods train a recurrent unit $p(y_{i}|y_{i-1})$ and the loss function is theoretically the same thing.

*

*Is there any difference between them in the practical sense?

*For example, the latter can reduce the over-fitting?,

*the latter can be better at long-term prediction, but not at short-term one?etc.

A: I think this question is a bit confused, because an RNN does not model $p(y_i | y_{i-1})$ -- indeed, in most cases, such a simple conditional probability could be modeled just by constructing a large frequency-count table.
In general, an RNN defines a distribution $p(y) = \prod_j p(y_i | y_{j<i})$. In most cases, you train by directly maximizing log-likelihood of entire sequences from the dataset.


text:
Q: Obtaining inconsistent results in Spark Have any Spark experts had strange experience: obtaining inconsistent map-reduce results using pypark?
Suppose in the midway, I have a RDD
....
add = sc.parallelize([(('Alex', item1), 3), (('Joe', item2), 1),...])

My goal is to aggregate how many different users, so I do
print (set(rdd.map(lambda x: (x[0][0],1)).reduceByKey(add).collect()))
print (rdd.map(lambda x: (x[0][0],1)).reduceByKey(add).collect())
print (set(rdd.map(lambda x: (x[0][0],1)).reduceByKey(add).map(lambda x: x[0]).collect()))

These three prints should have the same content (though in different formats). For example, the first one is a set of set({('Alex', 1), ('John', 10), ('Joe', 2)...}); second a list of [('Alex', 1), ('John', 10), ('Joe', 2)...]. The number of the items should be equal to the number of different users. Third is a set({'Alex', 'John', 'Joe'...})
But instead I got set({('Alex', 1), ('John', 2), ('Joe', 3)...}); second a list of [('John', 5), ('Joe', 2)...]('Alex' is even missing here). The lengths of the set and list are different.
Unfortunately, I even cannot reproduce the error if I only write a short test code; still get right results. Did any meet this problem before?

A: I think I figured out.
The reason is that if I used the same RDD frequently, I need to .cache().
If the RDD becomes
add = sc.parallelize([(('Alex', item1), 3), (('Joe', item2), 1),...]).cache()

then the inconsistent problem solved.
Or, if I further prepare the aggregated rdd as
aggregated_rdd = rdd.map(lambda x: (x[0][0],1)).reduceByKey(add)
print (set(aggregated_rdd.collect()))
print (aggregated_rdd.collect())
print (set(aggregated_rdd.map(lambda x: x[0]).collect()))

then there are no inconsistent problems neither.


text:
Q: HTML5 DIV flashes on tap When receving an onclick event from a DIV as a result of a tap on the iPad, The DIV automatically flashes to a dark color to give the user feedback for the tap. Is there any way to prevent this flash from occurring?

A: It's because there are events on the element. Just set:
div {
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}

A: Maybe try adding a class for div.stylename:active ? give the background the same colour as the div.


text:
Q: µ in the Middle of a Capacitor Rating I'm looking at an electrolytic capacitor (and old blue, Philips one used in electronics classes) and am wondering why it is printed with 4µ7-M.
I tried Googling, figuring that it was a common enough occurrence, but found nothing.
Is that supposed to be a 47µF cap? Why is the µ in the middle of the number? What is the -M for?
Thanks.

A: Like Jim said, the µ indicates the place of the decimal point. This isn't restricted to capacitors, but also used for resistors and inductors:

resistor 31k6 = 31.6 kiloOhm
  resistor 5M6 = 5.6 megaOhm
  capacitor 2n2 = 2.2 nanoFarad
  inductor 4µ7 = 4.7 microHenry

A: It caused less confusion than sometimes arose with a decimal point, which was missed sometimes when documents were copied or faxed. That's not such a problem these days, but it is in common use, especially here in Europe. I always use that notation.

A: The "µ" symbol is put in place of the decimal point, 4µ7 translates to 4.7 µ farads.
Not too sure about the "-M" part tho - sorry


text:
Q: How i can convert a txt to int in powershell i have a txt file with this :

1230;
  012;
  45;
  125

and i want to convert this in an int
but is doesn't work... he juste return the last number
here is my code :
$numbertxt = get-content -Path C:\mysticpath\number.txt -Raw
$numbertxt.GetType()
write-host $numbertxt
foreach ($flags in $numbertxt)
{
    $integer = [int]$flags
}
echo $integer

somebody can help me ?
Sorry for my english

A: $numbertxt = (get-content -Path C:\mysticpath\number.txt -Raw) -split ';'
$numbertxt.GetType()
write-host $numbertxt
foreach ($flags in $numbertxt)
{
    $integer = [int]$flags
    echo $integer
}

First a integer can only be made of numbers so you will need to split the contents by ';'. This will make a array of strings that are numbers.
Also put the echo on the inside of the for loop will allow for it to display each number as its processed

A: try this method (control if it's convertible to integer before print)
$res=0;

#verbose version
(Get-Content "c:\temp\test.txt") -split ';' | where {[int]::TryParse($_, [ref] $res)} | foreach {$res}

#short version
(gc "c:\temp\test.txt") -split ';' | ?{[int]::TryParse($_, [ref] $res)} | %{$res}


text:
Q: Is it possible two combine two linear gradient in css over single div I want to make the following using css
See Resultant Image
Thus far I have made the horizontal lines using repeating-linear-gradient

.pattern1{
  width: 100%;
  height: 250px;
  background:repeating-linear-gradient(to bottom, white, white 40px, black 3px, black 43px)
}

But i need to add left vertical line of 30px within same div using css.
Here is the fiddle link

A: Yes

.pattern1{
  height: 252px;
  background:
    linear-gradient(red,red) left/30px 100% no-repeat,
    repeating-linear-gradient(to bottom, white 0 40px, black 0 42px)
}

OR like below:

.pattern1{
  height: 252px;
  background:
    linear-gradient(to right, red 30px, transparent 0),
    repeating-linear-gradient(to bottom, white 0 40px, black 0 42px)
}


text:
Q: Processing List Data in Pandas Columns I have a Pandas DataFrame which looks like following
27    [A,B,C]
27    [D,E,F]
27    [G,H,I]
27    [J,K,L]
34    [M,N,O]
34    [P,Q,R]
34    [S,T,U]

I would like to aggregate all the lists with the same id. But what function would help me aggregate lists together.
Thanks

A: I'm assuming your data consists of a list of characters, you can perform a groupby and call sum:
In [406]:

df.groupby('a').sum()
Out[406]:
                                       b
a
27  [A, B, C, D, E, F, G, H, I, J, K, L]
34           [M, N, O, P, Q, R, S, T, U]


text:
Q: xcodebuild - set certificate through commandline I have an Xcode project for an iOS application.
I plan building it through commandline using xcodebuild.
I will be adding minor customizations from build to build, producing slightly different versions of the application (for branding purpose).
What I need is a way to automatically set a specific certificate for each build. Is it possible to somehow set a certificate for the build through command line?
To clarify - every time I build the project, I want to use a new certificate.

A: before the build, set environment variable CODE_SIGNING_IDENTITY="name of certificate"


text: Q: QGIS 3.2 Raster Histogram frequency axis always locked at 1 Question is pretty much in the title: Whenever I go to layer properties and generate a histogram for a raster the frequency axis of the histogram is capped at 1. So for say a multi-band image I see the pixel values for the multiple bands on the x-axis of the histogram and the frequency of those values on the y-axis. My problem is that the range of the y-axis displayed is from 0-1 which is useless. How do I fix this?


text:
Q: Have an error while writing monodb app for the first time So, this is the code can any one explain why this code is giving this error.
...
const  { MongoClient } = require('mongodb').Mongoclient;
const assert = require('assert');
const url = "mongodb://localhost:27017";

const dbName = 'fruitsdb';

const client = new MongoClient(url, {
useUnifiedTopology: true,
useNewUrlParser: true
});
client.connect(function(err) {
assert.equal(null,err);
console.log("Connected successfully to server");

const db = client.db(dbName);

client.close();

});
...
const  { MongoClient } = require('mongodb').Mongoclient;
^
TypeError: Cannot destructure property MongoClient of 'undefined' or 'null'.
but this code is not giving error.
...
const { MongoClient } = require('mongodb');

const assert = require('assert');

const url = "mongodb://localhost:27017";

const dbName = 'fruitsdb';

const client = new MongoClient(url, {
useUnifiedTopology: true,
useNewUrlParser: true
});
client.connect(function(err)
{
assert.equal(null,err);
console.log("Connected successfully to server");

const db = client.db(dbName);

client.close();

});
Pls, do explain the code too, I am new to this, and starting out, could you pls explain how the code is working.

A: Look at this example when you use { "property" } = Object  you select one property that exist in the Object.
const data = {
    firstName: "ravi",
    lastName: "kumar",
    friend: {
       firstName: "erfan",
       lastName: "hp",
    }
}

const { firstName } = data; // show ravi

const { firstName } = data.friend; // show erfan

we have MongoClient property in require('mongodb')
but we don't have MongoClient property in require('mongodb').MongoClient


text:
Q: Adaptive UI UWP I am trying to learn about adaptive UI. I use bootstrap alot, but am in the process of designing a Windows 10 app with xaml. I am wanting the textboxes and textbloxks to adjust based on if the user shrinks the window or not. This is what I have, but it is not adapting nor is it responsive.
<Grid Grid.Row="1">
        <TextBlock HorizontalAlignment="Left" FontSize="24" Margin="10,22,0,0" Grid.Row="1" TextWrapping="Wrap" Text="Title" VerticalAlignment="Top"/>
        <TextBox x:Name="txtBoxTitle" Margin="79,24,0,0" Grid.Row="1" Width="800" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Left"/>
        <TextBlock HorizontalAlignment="Left" FontSize="24" Margin="10,131,0,0" Grid.Row="1" TextWrapping="Wrap" Text="Body" VerticalAlignment="Top"/>
        <TextBox x:Name="txtBoxBody" Margin="79,133,-225,0" Grid.Row="1" Width="800" Height="500" TextWrapping="Wrap" AcceptsReturn="True" HorizontalAlignment="Left" VerticalAlignment="Top"/>
        <Button x:Name="btnSubmitArticle" Content="Submit" HorizontalAlignment="Left" VerticalAlignment="Bottom"  Margin="80,20,20,20" d:LayoutOverrides="Width"/>
    </Grid>

Additional Question
How can I pull the text in the textbox all the way to the right of the window and have it respond correctly when the screen size changes.
<RelativePanel Margin="12,12">
           <TextBlock x:Name="txtBoxDate"
           RelativePanel.AlignLeftWithPanel="True"
           RelativePanel.AlignRightWithPanel="True"
           FontSize="14"
           TextAlignment="Right"
           TextWrapping="Wrap"
           Text="Title" />
</RelativePanel>

Can anyone point me in the right direction to making these elements repsonsive depending on screen size?

A: Assuming that the whole row stretches, the problem is that you're setting Width of those elements (and some weird Margins, probably because you dragged and dropped the controls from the toolbox). You can use a RelativePanel to nicely stack the items and keep them stretched from left to right inside the panel:
<RelativePanel Margin="12,0">
    <TextBlock x:Name="FirstTextBlock"
               RelativePanel.AlignLeftWithPanel="True"
               RelativePanel.AlignRightWithPanel="True"
               FontSize="24"
               TextWrapping="Wrap"
               Text="Title" />
    <TextBox x:Name="txtBoxTitle"
             RelativePanel.Below="FirstTextBlock"
             RelativePanel.AlignLeftWithPanel="True"
             RelativePanel.AlignRightWithPanel="True"
             Margin="0,8,0,0"
             TextWrapping="Wrap" />
    <TextBlock x:Name="SecondTextBlock"
               RelativePanel.Below="txtBoxTitle"
               RelativePanel.AlignLeftWithPanel="True"
               RelativePanel.AlignRightWithPanel="True"
               FontSize="24"
               Margin="0,8,0,0"
               TextWrapping="Wrap"
               Text="Body" />
    <TextBox x:Name="txtBoxBody"
             RelativePanel.Below="SecondTextBlock"
             RelativePanel.AlignLeftWithPanel="True"
             RelativePanel.AlignRightWithPanel="True"
             Margin="0,8,0,0"
             Height="500"
             TextWrapping="Wrap"
             AcceptsReturn="True" />
    <Button x:Name="btnSubmitArticle"
            RelativePanel.Below="txtBoxBody"
            Content="Submit"
            Margin="0,8,0,0"
            d:LayoutOverrides="Width"/>
</RelativePanel>


text:
Q: Questions about programming a cnn with PyTorch I'm pretty new at programming cnn so I'm a little bit lost. I'm trying to do this part of the code, where they ask me to implement a fully-connected network to classify the digits. It should contain 1 hidden layer with 20 units. I should use ReLU activation function on the hidden layer.
class Network(nn.Module):
    def __init__(self):
        super(Network, self).__init__()
        self.fc1 = ...

        self.fc2 = nn.Sequential(
            nn.Linear(500,10),
            nn.Softmax(dim = 1)
            )

    def forward(self, x):
        x = x.view(x.size(0),-1)
        x = self.fc1(x)
        x = self.fc2(x)
        return x

The dots are the part to fill, I think about this line:
self.fc1 = nn.Linear(20, 500)

But I don't know if it's correct. Could someone help me please? And I don't understand at all what the function Softmax do... so if someone knows it please.
Thank you so much!!
Pd. This is the code to load the data:
batch_size = 64
trainset = datasets.MNIST('./data', train=True, download=True, transform=transforms.ToTensor())
train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=1)
testset = datasets.MNIST('./data', train=False, download=True, transform=transforms.ToTensor())
test_loader = DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=1)

A: From the code given for the model, it can be seen that the hidden layer has 500 units. So I am assuming you meant 20 units for input. With this assumption, the code must be:
self.fc1 = nn.Sequential(
    nn.Linear(20, 500),
    nn.ReLU()
    )

Coming to the next part of your question, given that you are working with MNIST dataset and you have the softmax function, I am assuming you are trying to predict the number present in the images.
Your neural network performs various multiplication and addition operations in each layer and finally, you end up with 10 numbers in the output layer. Now, you have to make sense of these 10 numbers to decide which of the 10 digits is given in the image.
One way to do this would be to select the unit which has the maximum value. For example if the 10th unit has the maximum value among all units, then we conclude that the digit is '9'. If the 2nd unit has the maximum value, then we conclude that the digit is '1'.
This is fine but a better way would be to convert the values of each of the units to probability that the corresponding digit is contained in the image and then we choose the digit having highest probability. This has certain mathematical advantages which helps us in defining a better loss function.
Softmax is what helps us to convert the values to probabilities. On applying softmax, all the values lie in the range (0, 1) and they sum up to 1.
If you are interested in deeplearning and the math behind it, I would suggest you to checkout Andrew NG's course on deeplearning.

A: You did not mention the shape of your data so I'll be assuming the expected shape returned by datasets.MNIST.
Data shape: torch.Size([64, 1, 28, 28])
class Network(nn.Module):
    def __init__(self):
        super(Network, self).__init__()
        self.fc1 = nn.Sequential(
            nn.Linear(1*28*28, 20),
            nn.ReLU())

        self.fc2 = nn.Sequential(
            nn.Linear(500,10),
            nn.Softmax(dim = 1))

    def forward(self, x):
        x = x.view(x.size(0), -1)
        x = self.fc1(x)
        x = self.fc2(x)
        return x

The first argument of nn.Linear is the size of input feature while the second is the number of units.
For self.fc1, the size of the input feature is the multiplication of your data shape except the batch size, which is 1 * 28 * 28. And as per your post the second argument should be 20 (20 units).
The shape of the output from self.fc1 (which is also the input to self.fc2) will then be (batch size, 20).
For self.fc2, the size of the input  feature will be 20 while the number of units (which is also the number of digits) will be 10.


text:
Q: can I plot 2 sets of data in the same density histogram (mathematica)? can I plot 2 different sets of data ({x1,y1} and also {x2,y2}) in the same density histogram (mathematica)?
I don't know if that is possible due to superposition of colors.

A: How about something like this?
a = SmoothDensityHistogram[
   RandomVariate[BinormalDistribution[0.3], 10], Mesh -> 3,
   MeshStyle -> Red, ColorFunction -> None];
b = SmoothDensityHistogram[
   RandomVariate[BinormalDistribution[0.6], 10], Mesh -> 3,
   MeshStyle -> Blue, ColorFunction -> None];
Show[
 a /. GrayLevel[_] -> Opacity[0],
 b /. GrayLevel[_] -> Opacity[0],
 ImageSize -> 300]


text:
Q: Using RxSwift, How To Enable UIButton Based on Valid Text? In RxSwift/RxCocoa 2.0.0- beta 3, I have a ViewModel with:
let someString = Variable("")

func isValidSomeString() -> Observable<Bool>  {

    if someString.value.characters.count == 0 {
        return just(false)
    }
    return just(true)
}

I have the someString bound already to a text field in the ViewController.
Whenever the someString (or perhaps the text field if that's a better way) changes, I want a button enabled based on if someString is valid.
I tried using the "Observable< Bool >", but started going down another path. I could do this in the ViewController:
    someViewModel.someString.subscribeNext { text -> Void in

        // could just someUIButton.enabled = someViewModel.isValidSomeString(text)

    }.addDisposableTo(disposeBag)

Isn't there another way that is less verbose than the isValidSomeString(text) approach? We already have had nice success with a isValidLogin that returns Observable< Bool > which used combineLatest.

A: Sounds like Action is the perfect tool to use in this case. You'll want to create an Action in your ViewModel, let its enabledIf observable be the result of changes to the string, and connect this action to your UIButton. This way the button will be auto-enabled.
In your ViewModel, you'll need to add this:
var buttonAction: CocoaAction {
    let hasString = self.someString.map { !$0.isEmpty }
    return CocoaAction(enabledIf: hasString) {
        // do something when button tapped
        return empty()
    }
}

And when binding your ViewController to your ViewModel, you'll do:
myButton.rx_action = viewModel.buttonAction

A: Looks like you just need to map your someString to Obserable<Bool> and then bind it to rx_enabled of UIButton
Something like this:
someViewModel.someString
             .asObservable()
             .map { (str) -> Bool in
                 return someViewModel.isValidSomeString(text)
             }
            .bindTo(someUIButton.rx_enabled)
            .addDisposableTo(disposeBag)

but I think it whould be simpler if you would  have Variable<Bool> in your viewmodel kind of
struct ViewModel {
....
    canLogIn = Variable(false)
}

In this case you will be able bind it to rx_enabled like this:
  let userNameValidation = loginTextField
     .rx_text
     .map({!$0.isEmpty})
     .shareReplay(1)

  let passwordValidation = passwordTextField
     .rx_text
     .map({!$0.isEmpty})
     .shareReplay(1)

  let loginEnabled = combineLatest(userNameValidation, passWordValidation) { (username, password) in
     return username && password
  }

  loginEnabled
     .bindTo(loginViewModel.canlogIn)
     .addDisposableTo(disposeBag)

  loginViewModel.canlogIn
         .bindTo(loginButton.rx_enabled)
         .addDisposableTo(disposeBag)


text:
Q: Loop over numbered files and append on every line of file the content of another file with the same number I have a lot of numbered *.csv files with different numbers of lines and just as many *.txt files. I want to append on every line of file 1.csv the content of file 1.txt, on every line of file 2.csv the content of file 2.txt and so on. Each *.txt file contains only one line.
What I have tried:
for i in {1..2}; do for j in {1..2}; do perl -i -p -e "s/^(.+?)$/\1<content of $j.txt>/g" ./$i.csv; done; done

But obviously this doesn't work.
example (initial situation):
1.csv
  line 1
  line 2
  line 3

2.csv
  line 1
  line 2

1.txt
  yyy

2.txt
  zzz

result (should be):
1.csv
  line 1yyy
  line 2yyy
  line 3yyy

2.csv
  line 1zzz
  line 2zzz

1.txt
  yyy

2.txt
  zzz

Any help would be appreciated.

A: To expand on your perl attempt, perhaps
for f in ./*.csv; do
  perl -i -lpe 'BEGIN{$x = shift @ARGV} s/$/$x/' "$(<"${f%.csv}.txt")" "$f"
done

(assuming ksh/zsh/bash for the $(<file) operator; replace with $(cat<file) if your shell doesn't support it).
giving
$ head ./*.csv
==> ./1.csv <==
  line 1yyy
  line 2yyy
  line 3yyy

==> ./2.csv <==
  line 1zzz
  line 2zzz

However you don't really need a regex substitution for this - you could consider replacing s/$/$x/ by a simple string concatenation $_ .= $x

A: Use awk:
for f in *.csv; do
    awk '
        FNR==NR{txt=$0}
        FNR!=NR{printf "%s%s\n",$0,txt}
    ' "${f%.*}.txt" "$f" > "$f.csv.tmp" && mv "$f.csv.tmp" "$f"
done

Output:
$ cat a.csv
line 1yyy
line 2yyy
line 3yyy

Some modern implementations of awk have -i inplace option, so you won't need the "tmp and mv part". See here.

A: A sed-oneliner:
for i in 1 2 ; do sed -i "s/$/$(cat $i.txt)/" $i.csv ; done

s/$/ I'm replacing the end of each line, thus appending to the line
$(cat $i.txt) append the text-file named after the current number.
Note that this will will lead to problems if the filen.txt contains special characters like slash, backslash, quotes, ...
If this is a concern, use an ascii record separator instead of the / in the sed-statement.  You can type those in vim by pressing Ctrl+V, then enter their decimal value --- 030 in this case


text:
Q: Unable to find height of BST Using recursion I am trying to find height of tree but the output seems wrong. Any errors?
#include <iostream>

struct node{
    int data;
    node* left, *right;
};

node* getNode(int item){
    node* new_node = new node;
    new_node->data = item;
    new_node->left = new_node->right = nullptr;
    return new_node;
}

node* insert(node* root, int item){
    if(root == nullptr){
        root = getNode(item);
    }
    else if(item < root->data){
        root->left = insert(root->left, item);
    }
    else if(item > root->data){
        root->right = insert(root->right, item);
    }
    return root;
}

int height(node* root){
    if(root == nullptr){
        return 0;
    }
    else{
        return 1+std::max(height(root->left), height(root->right));
    }
}

int main()
{
    node* root;
    root = insert(root, 40);
    root = insert(root, 10);
    root = insert(root, 20);
    root = insert(root, 80);
    root = insert(root, 30);
    root = insert(root, 1);
    std::cout << "\nheight of Tree: " << height(root);

    return 0;
}

Tree should have height 3 (if i am not wrong) but its showing 4.
I am using GNU GCC compiler with Code::Blocks IDE it works there,
But when I am running same code on Programiz c++ online compiler it shows Segmentation fault so maybe the I am doing something wrong.
Regards

A: Right away, this code:
int main()
{
    node* root;  // <-- uninitialized
    root = insert(root, 40); // <-- Using an uninitialized pointer
    //...
}

is faulty.
The root is an uninitialized pointer, and passing that uninitialized pointer to insert will invoke undefined behavior.
The probable fix is to simply do:
node* root = nullptr;

A: Your code is returning 4 because you're counting the number of nodes on the longest path down from the root, rather than the number of edges. Notice, for example, that you're considering a one-node tree to have height 1, whereas it's conventionally considered to have height 0.
There's an easy fix to this, and that's to change your base case. As weird as it seems, the convention is to treat an empty tree as having height -1. Change your base case appropriately and watch what happens. Can you account for why this works?
(Also, as pointed out by the other answer, your code works with an uninitialized pointer, which can literally destroy the fabric of spacetime and teleport us all to a Dimension of Infinite Peril. Initializing that pointer to nullptr should fix that. Pro tip: run your code under valgrind to see these sorts of errors in real-time!)


text:
Q: Showing the existence of an element $g \in G$, a finite abelian group, where $g$ has order $LCM\{|x|: x \in G\}$ So I, more or less, need help understanding this problem.
The first thing I have tried is to pick a specific group: $\mathbf{Z}_5$, under multiplication.
To demonstrate, say we pick element $2$ and $|2| = 4$, and then the only other possible orders are $\{1,4\}$.
Indeed, $4 = LCM(1,4)$.
Not really quite sure, how to generalize this, yet. Any hints? What shall I think about? Definitely prime factorization of each element, hmm... I think!


text:
Q: How add an image to a nested object in React Js? I am trying to add a file type image to my nested object, below i have added my handle change where i am trying to get the image into the nested object.
const handleImage = (e, docketIndex, i) => {
const list = { ...inputList }
list.product_information[i].docket_numbers[docketIndex]['imageURL'] = e.target.files[0]
console.log(list)
setInputList(list)

}
Below is the result of the above code which shows an empty object in JSON stringify
product_information": [
{
  "docket_numbers": [
    {
      "imageURL": {}
    }
  ],

But when i console log the handle change results is below which is a working as expected

But when i try to send the image to the backend its shows and empty object. i have tried adding an image using Formdata before but i am trying achieve this without using Formdata.


text:
Q: Error while importing sql in phpmyadmin While I'm trying to import a .sql backup in phpmyadmin , I get this error :
****Error**
SQL query:
--
-- Dumping data for table `wp_commentmeta`
--
INSERT INTO `wp_commentmeta` ( `meta_id` , `comment_id` , `meta_key` , `meta_value` )

VALUES ( 2, 2, '_wp_trash_meta_status', '0' ) , ( 3, 2, '_wp_trash_meta_time', '1398086942' ) ;

MySQL said:

1062 - Duplicate entry '2' for key 'PRIMARY'**

What should I do?

A: *

*You cant duplicate the data with the same primary key

*Truncate your current table and try it again (TRUNCATE your_table;)
OR DELETE FROM your_table WHERE your_ID_field LIKE 2

*IF your ID field is AUTO_INCREMENT field you can slove it like this
INSERT INTO `wp_commentmeta` ( `meta_key` , `meta_value` )

VALUES ('_wp_trash_meta_status', '0' ),
       ('_wp_trash_meta_time', '1398086942' ) ;


text:
Q: Como executar um procedimento somente uma vez? Montei um gerador de pagamentos que pega vários dados e salva em uma tabela do banco, o problema é que usei o evento OnActivate do Form, então cada vez que volta para o form inicial, o procedimento é executado novamente, sendo que esses dados só devem ser inseridos uma vez ao dia(pagamento referente ao dia atual). Alguma dica de como executar isso somente quando o programa for inicializado pela primeira vez ao dia(levando em conta que o usuário pode fechar e abrir novamente)?
procedure TForm3.FormActivate(Sender: TObject);
var
dataa,dataontem,datatrunc : TdateTime;
year,month,day :word;
mm,dd ,a,btext,datatext:string;
b,c,i:integer;
valorMens:real;
Soma:Double;

begin

    datatrunc:=Trunc(dataa);

//-------------------------------------------------------------------
// Gerar Pagamento Mensalidade
// ------------------------------------------------------------------

  i:=0;

  a:=stringgrid2.RowCount.ToString();
  c:=strtoint(a);
  edit5.Text:=inttostr(c);
  datatext:=datetimetostr(datatrunc);

  Form1.ADOQueryMens.Close;
  Form1.ADOQueryMens.Filter:=('Data='+ QuotedStr(datatext));
  Form1.ADOQueryMens.Filtered:=true;
  Form1.ADOQueryMens.open;

  if Form1.ADOQueryMens.FieldByName('Data').IsNull then
    begin

      if c>0 then
        begin
          while i<c do
            begin
              b:=strtoint(stringgrid2.Cells[0,i]);
              btext:=inttostr(b);

              adoQueryAluno.Close;
              adoQueryAluno.Filter:=('Código='+ QuotedStr(btext));
              adoQueryAluno.Filtered:=true;
              adoQueryAluno.open;

              Soma:= 0;
              ADOQueryAluno.First;

              while not ADOQueryAluno.Eof do
                begin
                  Soma:= Soma + AdoqueryAlunoValor.Value;
                  ADOQueryAluno.Next;
                end;
                valorMens:=Soma;
              Form1.AdoTableMensalidade.Open;
              Form1.AdoTableMensalidade.Insert;

              Form1.AdoTableMensalidade.FieldValues['CodAluno']:=b;
              Form1.AdoTableMensalidade.FieldValues['Valor']:=valorMens;
              Form1.AdoTableMensalidade.FieldValues['Data']:=Trunc(dataa);
              Form1.AdoTableMensalidade.FieldValues['Pago']:=false;

              Form1.ADOTableMensalidade.Post;
              Form1.ADOTableMensalidade.Close;
              Form1.ADOTableMensalidade.Open;

              i:=i+1;

            end;
        end;
       Form1.ADOQueryMens.Filtered:=false;

    end;
end;

Isso executa no OnActivate do Form, e faz a inserção dos valores na Tabela Mensalidade, quanto a isso está tudo ok e ele insere certinho... Mas ele executa toda vez que volta no form inicial, o que é o problema.

A: Segui as dicas do @ThiagoFriedman e @DenerCarvalho e funcionou, criei um filtro para a tabela Mensalidade usando a data atual e a partir dela verifiquei se tinha algum dado já inserido, e então via se deveria inserir ou não, conforme segue o código acima, foi corrigido está funcionando.


text:
Q: Can i write java code which reloads one internet page? I'm just wondering if I can write code which reloads an internet page for example in 5 seconds. I only know Java so, is it possible with this language?

A: Yes, look into the HttpURLConnection class. There are many examples of this.

A: In your JSP you can use
<meta http-equiv="refresh" content="5"> //Refresh after 5 seconds

Also you can use HttpServletResponse#setIntHeader
<% response.setIntHeader("Refresh", 5); %>//Refresh after 5 seconds

A: You can do this with httpservlet. You can refresh a page with http header
response.setHeader("Refresh", "5; url=http://your.domain.com/page");

or by hml meta refresh.
(code is not tested)


text:
Q: rmarkdown with page navigation on the side Hi I would like to a add a page navigation on the side of my Rmarkdown file. It would be nice if it could look like the sidebar on this page.
---
title: "My Title"
author: "My Name"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
  html_document:
    theme: united
    highlight: tango
    code_folding: hide
    df_print: paged
    toc: true
    toc_depth: 2

---
# Section 1
abc
## Section 1.1
abcabc
# Section 2
abcabcabc

can anyone help?

A: I've tried this and works pretty well:
---
title: "TEST"
output:
  html_document:
  toc: true
  toc_float: true
  toc_collapsed: true
toc_depth: 3
number_sections: true
theme: lumen
---

For more info please check the answer in this link: RMarkdown: Floating TOC and TOC at beginning

A: Adding one more answer which fixes the incorrect indentation on the answer given by @alika:
---
title: "TEST"
output:
  html_document:
    toc: true
    toc_float: true
    toc_collapsed: true
    toc_depth: 3
    number_sections: true
    theme: lumen
---


text:
Q: Drop data frame columns by name I have a number of columns that I would like to remove from a data frame. I know that we can delete them individually using something like:
df$x <- NULL

But I was hoping to do this with fewer commands.
Also, I know that I could drop columns using integer indexing like this:
df <- df[ -c(1, 3:6, 12) ]

But I am concerned that the relative position of my variables may change.
Given how powerful R is, I figured there might be a better way than dropping each column one by one.

A: list(NULL) also works:
dat <- mtcars
colnames(dat)
# [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
# [11] "carb"
dat[,c("mpg","cyl","wt")] <- list(NULL)
colnames(dat)
# [1] "disp" "hp"   "drat" "qsec" "vs"   "am"   "gear" "carb"

A: Provide the data frame and a string of comma separated names to remove:
remove_features <- function(df, features) {
  rem_vec <- unlist(strsplit(features, ', '))
  res <- df[,!(names(df) %in% rem_vec)]
  return(res)
}

Usage:
remove_features(iris, "Sepal.Length, Petal.Width")

A: There's also the subset command, useful if you know which columns you want:
df <- data.frame(a = 1:10, b = 2:11, c = 3:12)
df <- subset(df, select = c(a, c))

UPDATED after comment by @hadley: To drop columns a,c you could do:
df <- subset(df, select = -c(a, c))

A: There is a potentially more powerful strategy based on the fact that grep() will return a numeric vector. If you have a long list of variables as I do in one of my dataset, some variables that end in ".A" and others that end in ".B" and you only want the ones that end in ".A" (along with all the variables that don't match either pattern, do this:
dfrm2 <- dfrm[ , -grep("\\.B$", names(dfrm)) ]

For the case at hand, using Joris Meys example, it might not be as compact, but it would be:
DF <- DF[, -grep( paste("^",drops,"$", sep="", collapse="|"), names(DF) )]

A: If you want remove the columns by reference and avoid the internal copying associated with data.frames then you can use the data.table package and the function :=
You can pass a character vector names to the left hand side of the := operator, and NULL as the RHS.
library(data.table)

df <- data.frame(a=1:10, b=1:10, c=1:10, d=1:10)
DT <- data.table(df)
# or more simply  DT <- data.table(a=1:10, b=1:10, c=1:10, d=1:10) #

DT[, c('a','b') := NULL]

If you want to predefine the names as as character vector outside the call to [, wrap the name of the object in () or {} to force the LHS to be evaluated in the calling scope not as a name within the scope of DT.
del <- c('a','b')
DT <- data.table(a=1:10, b=1:10, c=1:10, d=1:10)
DT[, (del) := NULL]
DT <-  <- data.table(a=1:10, b=1:10, c=1:10, d=1:10)
DT[, {del} := NULL]
# force or `c` would also work.

You can also use set, which avoids the overhead of [.data.table, and also works for data.frames!
df <- data.frame(a=1:10, b=1:10, c=1:10, d=1:10)
DT <- data.table(df)

# drop `a` from df (no copying involved)

set(df, j = 'a', value = NULL)
# drop `b` from DT (no copying involved)
set(DT, j = 'b', value = NULL)

A: Another dplyr answer.
Use select(-column).
If your variables have some common naming structure, you might try starts_with().  For example
library(dplyr)
df <- data.frame(var1 = rnorm(5), var2 = rnorm(5), var3 = rnorm (5),
                 var4 = rnorm(5), char1 = rnorm(5), char2 = rnorm(5))
df
#        var2      char1        var4       var3       char2       var1
#1 -0.4629512 -0.3595079 -0.04763169  0.6398194  0.70996579 0.75879754
#2  0.5489027  0.1572841 -1.65313658 -1.3228020 -1.42785427 0.31168919
#3 -0.1707694 -0.9036500  0.47583030 -0.6636173  0.02116066 0.03983268

df1 <- df %>% select(-starts_with("char"))

df1
#        var2        var4       var3       var1
#1 -0.4629512 -0.04763169  0.6398194 0.75879754
#2  0.5489027 -1.65313658 -1.3228020 0.31168919
#3 -0.1707694  0.47583030 -0.6636173 0.03983268

If you want to drop a sequence of variables in the data frame, you can use :.  For example if you wanted to drop var2, var3, and all variables in between, you'd just be left with var1:
df2 <- df1 %>% select(-c(var2:var3) )
df2
#        var1
#1 0.75879754
#2 0.31168919
#3 0.03983268

A: Dplyr Solution
I doubt this will get much attention down here, but if you have a list of columns that you want to remove, and you want to do it in a dplyr chain I use one_of() in the select clause:
Here is a simple, reproducable example:
undesired <- c('mpg', 'cyl', 'hp')

mtcars <- mtcars %>%
  select(-one_of(undesired))

Documentation can be found by running ?one_of or here:
http://genomicsclass.github.io/book/pages/dplyr_tutorial.html

A: Drop and delete columns by columns name in data frame.
A <- df[ , c("Name","Name1","Name2","Name3")]

A: Another possibility:
df <- df[, setdiff(names(df), c("a", "c"))]

or
df <- df[, grep('^(a|c)$', names(df), invert=TRUE)]

A: within(df, rm(x))

is probably easiest, or for multiple variables:
within(df, rm(x, y))

Or if you're dealing with data.tables (per How do you delete a column by name in data.table?):
dt[, x := NULL]   # Deletes column x by reference instantly.

dt[, !"x"]   # Selects all but x into a new data.table.

or for multiple variables
dt[, c("x","y") := NULL]

dt[, !c("x", "y")]

A: DF <- data.frame(
  x=1:10,
  y=10:1,
  z=rep(5,10),
  a=11:20
)
DF

Output:
    x  y z  a
1   1 10 5 11
2   2  9 5 12
3   3  8 5 13
4   4  7 5 14
5   5  6 5 15
6   6  5 5 16
7   7  4 5 17
8   8  3 5 18
9   9  2 5 19
10 10  1 5 20

DF[c("a","x")] <- list(NULL)

Output:
        y z
    1  10 5
    2   9 5
    3   8 5
    4   7 5
    5   6 5
    6   5 5
    7   4 5
    8   3 5
    9   2 5
    10  1 5

A: Out of interest, this flags up one of R's weird multiple syntax inconsistencies.  For example given a two-column data frame:
df <- data.frame(x=1, y=2)

This gives a data frame
subset(df, select=-y)

but this gives a vector
df[,-2]

This is all explained in ?[ but it's not exactly expected behaviour.  Well at least not to me...

A: Here is a dplyr way to go about it:
#df[ -c(1,3:6, 12) ]  # original
df.cut <- df %>% select(-col.to.drop.1, -col.to.drop.2, ..., -col.to.drop.6)  # with dplyr::select()

I like this because it's intuitive to read & understand without annotation and robust to columns changing position within the data frame. It also follows the vectorized idiom using - to remove elements.

A: There are a lot of ways you can do...
Option-1:
df[ , -which(names(df) %in% c("name1","name2"))]

Option-2:
df[!names(df) %in% c("name1", "name2")]

Option-3:
subset(df, select=-c(name1,name2))

A: I keep thinking there must be a better idiom, but for subtraction of columns by name, I tend to do the following:
df <- data.frame(a=1:10, b=1:10, c=1:10, d=1:10)

# return everything except a and c
df <- df[,-match(c("a","c"),names(df))]
df

A: You could use %in% like this:
df[, !(colnames(df) %in% c("x","bar","foo"))]

A: There's a function called dropNamed() in Bernd Bischl's BBmisc package that does exactly this.
BBmisc::dropNamed(df, "x")

The advantage is that it avoids repeating the data frame argument and thus is suitable for piping in magrittr (just like the dplyr approaches):
df %>% BBmisc::dropNamed("x")

A: You can use a simple list of names :
DF <- data.frame(
  x=1:10,
  y=10:1,
  z=rep(5,10),
  a=11:20
)
drops <- c("x","z")
DF[ , !(names(DF) %in% drops)]

Or, alternatively, you can make a list of those to keep and refer to them by name :
keeps <- c("y", "a")
DF[keeps]

EDIT :
For those still not acquainted with the drop argument of the indexing function, if you want to keep one column as a data frame, you do:
keeps <- "y"
DF[ , keeps, drop = FALSE]

drop=TRUE (or not mentioning it) will drop unnecessary dimensions, and hence return a vector with the values of column y.

A: Another solution if you don't want to use @hadley's above: If "COLUMN_NAME" is the name of the column you want to drop:
df[,-which(names(df) == "COLUMN_NAME")]

A: Beyond select(-one_of(drop_col_names)) demonstrated in earlier answers, there are a couple other dplyr options for dropping columns using select() that do not involve defining all the specific column names (using the dplyr starwars sample data for some variety in column names):
library(dplyr)
starwars %>%
  select(-(name:mass)) %>%        # the range of columns from 'name' to 'mass'
  select(-contains('color')) %>%  # any column name that contains 'color'
  select(-starts_with('bi')) %>%  # any column name that starts with 'bi'
  select(-ends_with('er')) %>%    # any column name that ends with 'er'
  select(-matches('^f.+s$')) %>%  # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%     # not by column name but by data type
  head(2)

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>
1 Tatooine  Human
2 Tatooine  Droid

If you need to drop a column that may or may not exist in the data frame, here's a slight twist using select_if() that unlike using one_of() will not throw an Unknown columns: warning if the column name does not exist. In this example 'bad_column' is not a column in the data frame:
starwars %>%
  select_if(!names(.) %in% c('height', 'mass', 'bad_column'))

A: Find the index of the columns you want to drop using which. Give these indexes a negative sign (*-1). Then subset on those values, which will remove them from the dataframe. This is an example.
DF <- data.frame(one=c('a','b'), two=c('c', 'd'), three=c('e', 'f'), four=c('g', 'h'))
DF
#  one two three four
#1   a   d     f    i
#2   b   e     g    j

DF[which(names(DF) %in% c('two','three')) *-1]
#  one four
#1   a    g
#2   b    h

A: If you have a large data.frame and are low on memory use [ . . . . or rm and within to remove columns of a data.frame, as subset is currently (R 3.6.2) using more memory - beside the hint of the manual to use subset interactively.
getData <- function() {
  n <- 1e7
  set.seed(7)
  data.frame(a = runif(n), b = runif(n), c = runif(n), d = runif(n))
}

DF <- getData()
tt <- sum(.Internal(gc(FALSE, TRUE, TRUE))[13:14])
DF <- DF[setdiff(names(DF), c("a", "c"))] ##
#DF <- DF[!(names(DF) %in% c("a", "c"))] #Alternative
#DF <- DF[-match(c("a","c"),names(DF))]  #Alternative
sum(.Internal(gc(FALSE, FALSE, TRUE))[13:14]) - tt
#0.1 MB are used

DF <- getData()
tt <- sum(.Internal(gc(FALSE, TRUE, TRUE))[13:14])
DF <- subset(DF, select = -c(a, c)) ##
sum(.Internal(gc(FALSE, FALSE, TRUE))[13:14]) - tt
#357 MB are used

DF <- getData()
tt <- sum(.Internal(gc(FALSE, TRUE, TRUE))[13:14])
DF <- within(DF, rm(a, c)) ##
sum(.Internal(gc(FALSE, FALSE, TRUE))[13:14]) - tt
#0.1 MB are used

DF <- getData()
tt <- sum(.Internal(gc(FALSE, TRUE, TRUE))[13:14])
DF[c("a", "c")]  <- NULL ##
sum(.Internal(gc(FALSE, FALSE, TRUE))[13:14]) - tt
#0.1 MB are used

A: Another data.table option which hasn't been posted yet is using the special verb .SD, which stands for subset of data. Together with the .SDcols argument you can select/drop columns by name or index.
require(data.table)
# data
dt = data.table(
  A = LETTERS[1:5],
  B = 1:5,
  C = rep(TRUE, 5)
)
# delete B
dt[ , .SD, .SDcols =! 'B' ]
# delete all matches (i.e. all columns)
cols = grep('[A-Z]+', names(dt), value = TRUE)
dt[ , .SD, .SDcols =! cols ]

A summary of all the options for such a task in data.table can be found here

A: df <- data.frame(
+   a=1:5,
+   b=6:10,
+   c=rep(22,5),
+   d=round(runif(5)*100, 2),
+   e=round(runif(5)*100, 2),
+   f=round(runif(5)*100, 2),
+   g=round(runif(5)*100, 2),
+   h=round(runif(5)*100, 2)
+ )
> df
  a  b  c     d     e     f     g     h
1 1  6 22 76.31 39.96 66.62 72.75 73.14
2 2  7 22 53.41 94.85 96.02 97.31 85.32
3 3  8 22 98.29 38.95 12.61 29.67 88.45
4 4  9 22 20.04 53.53 83.07 77.50 94.99
5 5 10 22  5.67  0.42 15.07 59.75 31.21

> # remove cols: d g h
> newDf <- df[, c(1:3, 5), drop=TRUE]
> newDf
  a  b  c     e
1 1  6 22 39.96
2 2  7 22 94.85
3 3  8 22 38.95
4 4  9 22 53.53
5 5 10 22  0.42

A: Another option using the function fselect from the collapse package. Here is a reproducible example:
DF <- data.frame(
  x=1:10,
  y=10:1,
  z=rep(5,10),
  a=11:20
)

library(collapse)
fselect(DF, -z)
#>     x  y  a
#> 1   1 10 11
#> 2   2  9 12
#> 3   3  8 13
#> 4   4  7 14
#> 5   5  6 15
#> 6   6  5 16
#> 7   7  4 17
#> 8   8  3 18
#> 9   9  2 19
#> 10 10  1 20

Created on 2022-08-26 with reprex v2.0.2


text:
Q: Equilibria of first-price auctions with discrete valuation Assume we have a first-price auction with discrete and independent private values and identical distributions of all bidders. It is known that there exists a Bayes-Nash equilibrium where bidders bid on disjunct bid intervals. For example, we have valuations 0,1,2. Then a bidder with valuation 0 bids zero, a bidder with valuation 1 plays a mixed strategy on some interval $[0,\overline{b}_1]$ and a bidder with valuation 2 plays a mixed strategy on some interval $[\overline{b}_1,\overline{b}_2]$.
Is it true that this Bayes-Nash equilibrium is unique? If this is true, how one can show that overlapping bidding intervals are impossible? Or is it possible to show at least that this is the unique symmetric equilibrium, i.e. an equilibrium where all bidders employ the same strategy?
I tried to find the answer in the literature but I only found papers which derive the symmetric Bayes-Nash equilibrium with disjunct bidding intervals without discussing other possible equilibria. Thank you!


text:
Q: Build for archiving in Xcode 5 Just upgrade to xcode 5 and i saw "Build for archiving" missing in product menu.
I go to Preferences/Key bindings and saw in product menu "build for -> installing", i put a key and it does not work.
So i execute this to do it :
xcodebuild -project myproject.xcodeproj -target mytarget -configuration Release
and i get the same thing as before in previous xcode with "build for archiving"
(Just build with release configuration)
Any idea how to "build for archiving" (not Product/archive) with xcode 5 GUI ?
Thank you

A: You can use "Build For Profiling", it is set to Release configuration.

A: " Note that if the Archive menu is disabled this is most likely because the a simulator option is currently selected as the run target in the Xcode toolbar. Changing this menu either to a connected device, or the generic iOS Device target option should enable the Archive option in Product menu. "
More info at http://www.techotopia.com/index.php/Preparing_and_Submitting_an_iOS_7_Application_to_the_App_Store

A: It looks like they have combined the two steps "Build for Archiving" and "Archive" into one menu command: Product -> Archive in XCode 5.


text:
Q: Count click with python pyautogui Hello guys i m starting learning about pyautogui and with the code below i can locate if an image is on my screen and click on it and count it and print count.
import pyautogui
import time

    def main():
        print('BOT PROTOTIPO 1.0')
        time.sleep(5)
        tentativa = 0
        while True:
            if pyautogui.locateOnScreen('ButtonTest.png'):
                x = pyautogui.locateOnScreen('ButtonTest.png')
                print('ButtonTest clicked')
                pyautogui.click(x)
                time.sleep(3)
                tentativa += 1
                print(tentativa)
    main()

What i need now is if ButtonTest.png was clicked by the user mouse, count in a different variable.
Hope you help me.