text:
Q: Weird behavior UIView animation on gesture recognizer's sender.view in paging UIScrollView Setup:
I have a horizontal paging UIScrollView set up with help of the LXPagingViews class (to easily add a 'peeping' UIScrollView). This is set up, so you can flick between different views in the UIScrollView. I have added a UIPinchGestureRecognizer to every view, so when the user pinches on a view, it displays a 'zooming' animation, and segues into a detail view. A screenshot for more clarity:

Problem:
When I pinch one of the views, the zoom animation starts and the view segues into the detail view. This works fine, EXCEPT for the last view in the UIScrollView. In the last view (doesn't matter how many views it has, as long as it has more than 2), when the animation plays, it spawns a new view behind the view I tapped, and animates that one. This makes for a weird animation. Also, the view doesn't get blocked from input by the animation, because it spawns a new one. This means that the user can spawn multiple views quickly by pinching fast.
I hope this screenshot illustrates the problem a bit:

What I have tried:

*

*Debugging the gesture recognizer's superview subviews, to see if more views spawn

*Monitoring what view get's animated. For every pinch the user does, another view gets animated for some reason

*Tried to use another way of setting the image instead of lazy-loading. Didn't help

*Tried other images, more and less views, orientation differences and empty views.

Code:
Adding the gesture recognizer to the view:
- (UIView<ReusableView> *)pagingView:(PagingView *)thePagingView reusableViewForPageIndex:(NSUInteger)thePageIndex withFrame:(CGRect)theFrame {
    // View's Identifier
    static NSString *theIdentifier = @"voucherDetailView";
    VoucherDetailView *thePageView = (VoucherDetailView *)[thePagingView dequeueReusableViewWithIdentifier:theIdentifier];
    if (thePageView == nil) {
        thePageView = [[VoucherDetailView alloc] initWithFrame:theFrame];
    } else {
        thePageView.frame = theFrame;
    }

    Voucher *voucher = [_vouchers objectAtIndex:thePageIndex];
    NSURL *fullVoucherImageUrl = [NSURL URLWithString:voucher.fullVoucherImage];
    [thePageView.voucher setImageWithURL:fullVoucherImageUrl placeholderImage:[UIImage imageNamed:@"11283253-nederland_kaart"]];

    // Gesture recognizer
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(openZoomablePinch:)];
    [thePageView addGestureRecognizer:pinchGesture];

    return thePageView;
}

The pinch handler:
- (void)openZoomablePinch:(UIPinchGestureRecognizer*)sender {
    // Only allow one pinch to activate the animation
    if (sender.state == UIGestureRecognizerStateBegan) {
        // Bring the view to the front so it doesn't clip with the peeping views
        [sender.view.superview bringSubviewToFront:sender.view];
        CGAffineTransform trans = sender.view.transform;
        [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             sender.view.transform = CGAffineTransformScale(sender.view.transform, 1.15, 1.15);
                         }
                         completion:^(BOOL finished) {
                             if (finished && self.view.window) {
                                 sender.view.transform = trans;
                                 [self performSegueWithIdentifier:@"voucherZoomSegue" sender:self];
                             }
                         }];
    }
}

EDIT: PagingView code that gets called on the last view when pinching:
    UIView<ReusableView> *theRightMostReusableView = [self.visibleReusableViews lastObject];
    NSUInteger theRightMostPageIndex = (NSUInteger)floorf(CGRectGetMinX(theRightMostReusableView.frame) / thePageWidth);
    while ((theRightMostPageIndex != MAX(0, self.numberOfItems - 1)) && (theRightMostPageIndex < theToIndex)) {
        theRightMostPageIndex = MIN(theRightMostPageIndex + 1, MAX(0, self.numberOfItems - 1));
        CGFloat theMinX = theRightMostPageIndex * thePageWidth;
        CGRect theRect = CGRectMake(theMinX, 0.0f, thePageWidth, thePageHeight);
        UIView<ReusableView> *theReusableView = [self.dataSource pagingView:self reusableViewForPageIndex:theRightMostPageIndex withFrame:theRect];
        if (!CGRectContainsRect(theRect, theReusableView.frame)) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:[NSString stringWithFormat:
                                                   @"theReusableView's frame (%@) must be contained by the given frame (%@)",
                                                   NSStringFromCGRect(theReusableView.frame),
                                                   NSStringFromCGRect(theRect)]
                                         userInfo:nil];
        }
        [self.visibleReusableViews addObject:theReusableView];
        [self addSubview:theReusableView];
    }

EDIT 2:
I have uploaded a small demo project here. The way to use it, set the simulator (or your device) in landscape, go to Peeping Paging View, and try to pinch/tap the views (except the first one). As you can see, the views get zoomed, except for the last view, which spawns a new view behind it and zooms that one (the '9' stays the same size).
The code is in the PeepingPagingViewController.m.
Solution (thanks to Oladya Kane):
The rightmost visible index is mistakingly indexed as the leftmost visible index. The code I had to change was the line:
NSUInteger theRightMostPageIndex = (NSUInteger)floorf(CGRectGetMinX(theRightMostReusableView.frame) / thePageWidth);

to
NSUInteger theRightMostPageIndex = MIN((NSInteger)floorf((CGRectGetMaxX(theRightMostReusableView.frame) - 0.1f) / thePageWidth), MAX(0, self.numberOfItems - 1));

A: I've looked through you demo code and found following bug:
When your pinch gesture recognizer is called, you animate it's sender frame. This forces PageView to layout its subviews -> it calls your delegate method
- (UIView<ReusableView> *)pagingView:(PagingView *)thePagingView reusableViewForPageIndex:(NSUInteger)thePageIndex withFrame:(CGRect)theFrame

Here you provide view to PagingView and it adds your view beneath your last view, messing up your view hierarchy. I think you might use some kind of a flag somewhere to prevent PagingView from requesting new views. The strangest thing is that this kind of behavior happens only for last view.
Hope this will help you.
EDIT:
I found the problem.
In the method
- (void)layoutSubviewsFromIndex:(NSUInteger)theFromIndex toIndex:(NSUInteger)theToIndex

indexes of the leftmost and rightmost visible views are computed. But the rightmost visible index is mistakenly computed as the leftmost index, so, you need to replace this line:
NSUInteger theRightMostPageIndex = (NSUInteger)floorf(CGRectGetMinX(theRightMostReusableView.frame) / thePageWidth);

With this one:
NSUInteger theRightMostPageIndex = MIN((NSInteger)floorf((CGRectGetMaxX(theRightMostReusableView.frame) - 0.1f) / thePageWidth), MAX(0, self.numberOfItems - 1));

This will prevent PagingView from requesting new views for already visible last (rightmost) view.


text:
Q: How to create a Priority queue schedule in Autosys? Technologies available: Autosys, Informatica, Unix scripting, Database (available via informatica)
How our batch currently works is with filewatchers looking for a file called "control.txt" which gets deleted when a feed starts processing. It gets recreated once completed which allows all "control" autosys jobs waiting, to have one pick up the control file and begin processing data feeds one by one.
However, the system has grown large, and some feeds have become more important than others, and we're looking at ways to improve our scheduler to prioritize feeds over others.
With the current design, of one a file deciding when the next feed runs, it can't be done, and I haven't been able to come up with a simple solution to make it happen.
Example:
1. Feed A is processing
2. Feed B, Feed C, Feed X, Feed F come in while Feed A is processing
3. Need to ensure that Feed B is processed next, even though C, X, F are ready.
4. C, X, F have a lower priority than A and B, but have the same priority and can process in any order

A: A very interesting question. One thing that I can think of is to have an extra Autosys job with a shell script that copies the file in certain order. Like:

*

*Create input folder e.g. StageFolder

*Let's call your current Autosys input folder "the InputFolder"

*Have Autosys monitor it and for any file run a OrderedFileCopyScript.sh, every minute

*OrderedFileCopyScript.sh should copy one file from StageFolder to InputFolder in desired order only if InputFolder is empty

I hope I made myself clear.

A: I oppose use of Autosys for this requirement ! Wrong tool !
I don't know all the details but considering an application with the usual reference tables.
In this case you should make use of feed reference table to include relative priorities.
I would suggest to create(or reuse) a table to loaded by the successor job of the file watcher.
1) Table to contain the unprocessed file with the corresponding priority and then use this table to process the files based on the priority.
2) Remove/archive the entries once done.
3) Have another job of this and run like a daemon with start_times/run_window.
This gives the flexibility to deal with change in priorities and keeps overall design simple.
This gives

redpajama_set_name: RedPajamaStackExchange


text:
Q: What modified will be in a project that is in vb.net and used backend SQL Server 2005 to run on another computer Tell me if I want to run a project that is created in vb.net 2010 and uses a backend SQL Server 2005.........

*

*how many changes can be done in a project to run on another computer....?

*what connection string I can write for it.......?

*which software do I need to install on the other computer to run a project on it.......

A: On that other computer, you need:

*

*a compatible version of the .NET framework (whichever version you're using)

*your application

That is, if you put the SQL Server database onto a separate, central server.
In that case, your connection string looks something like:
server=YourDBServer;database=YourDatabase;Integrated Security=SSPI;

or
server=YourDBServer;database=YourDatabase;user id=YourUser;Password=Top$ecret;

There are lots of variations of connection strings, depending on your setup - check out the Connection Strings web site for details and lots of samples
Update: as you would see on the ConnectionStrings web site - if you have an ASP.NET web application, you can also locally deploy your *.MDF file to the App_Data directory of your web - in that case, you also need to locally install SQL Server 2005 Express on your client's PC, and you need to use a connection string like this:
Server=(local)\SQLExpress;AttachDbFilename=|DataDirectory|YourDBFile.mdf;
Database=YourDatabase;Trusted_Connection=Yes;


text:
Q: combo box value not returning Below is my php file , there is a combobox with multiple options, on selection new menu should appear according to selection
All the code is in single php file that is index.php
I don't want to refresh the page or submit the value it should be done on selection/click
My url look like this
http://localhost/lms/grade/report/userdef/index.php?id=13

and in computer file is located at
C:\xampp\htdocs\lms\grade\report\userdef

it's just for clarification because jQuery need paths and stuff that I am not good with
This is my code for combo boxes and selection
<?php
$change;
if( isset($_GET['combo_1']) )
{
echo $change = $_GET['combo_1'];
}

echo '<select name="combo" id="combo_1">';
echo '<option value="2">Submative</option>';
echo '<option value="1">formative</option>';
echo '<option value="3">successive</option>';
echo '</select>';
 ?>
<br>
<?php
 if ($change==='1' or $change==='2')
{
$quizzes....// query for quezzes one
echo '<select id="combo_2">';
echo '<option value=" " selected="selected">Choose....</option>';
}
foreach($quizzes as $id2 => $name) {
     echo '<option value=' . $id2 . '>' . $name . '</option>';
}
echo '</select>';
   }

if ($change==='2')
{
quizzes2//query for quizes
echo '<select id="combo_3">';
echo '<option value=" " selected="selected">Choose....</option>';

foreach($quizzes2 as $id3 => $name2) {
     echo '<option value=' . $id3 . '>' . $name2 . '</option>';
}
echo '</select>';
}

if ($change==='3')
{
// another menu
}
//////more functionality

I am trying to return value selected using following javascript but nothing happens, its not returning the value
All the code is in single file that is index.php:
<script type="text/javascript">
$(document).ready(function() {

    $('#combo_1').change(function(){
        var combo_1 = $(this).val();
        $.ajax({
                type: 'GET',
                url: 'index.php',
                data: {'combo_1':combo_1},
                success: function(data){
                    alert(data)
                }
            });
    });

});

</script>

A: Here is working code:
PHP CODE:
<?php
$comboBoxval = '';
// Check Ajax Request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // If combo_1 exist
    if (isset($_GET['DDBV'])) {
       // simple
       echo $comboBoxval = $_GET['DDBV'];
       exit;
    }
}
?>

Java Script Code:
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#combo_1').change(function(){
        var DDBV = $(this).val();
        $.ajax({
                type: 'GET',
                url: 'test.php',
                data: {'DDBV':DDBV},
                success: function(data){
                    // show ajax output to next
                    //$('#combo_1').after(data);
                    console.log(data);
                }
            });
    });

});
</script>

HTML Code:
<select name="combo" id="combo_1">
    <option value="2">Submative</option>
    <option value="1">formative</option>
    <option value="3">successive</option>
</select>

Now you will get your combo box value in ajax response


text:
Q: What is status=24/XPU in syslog? A service failed on my server with this message:
systemd[1]: my.service: Main process exited, code=killed, status=24/XCPU
What does it mean? I couldn't find anything related to this status.
Ubuntu 16.04 LTS x64. OpenVZ container.

A: The service was killed for using too much CPU time.
From man 7 signal:

SIGXCPU 24,24,30    Core    CPU time limit exceeded (4.2BSD);

This is specific to OpenVZ where the provider can impose resource limits.


text:
Q: how to create the transition with animations in the link I have to create a transition animation like in the link below.. please help if anyone knows how to do this
https://dribbble.com/shots/6488787-Music-App-UI-Pages
I tried to zoom image.. and i need this view in every view controller in the app so i tried to do it as a base view controller
I tried to add the bar in the right side of the screen. but now struggling to do the effect as the design shows
import UIKit

class BaseViewController: UIViewController {

    var location = CGPoint(x: 0, y: 0)

    var buttonImage = UIImageView()
    var strechyImage = UIImageView()
    var boxviewImage = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpView()
    }

    override func touchesMoved(_ touches: Set<UITouch>?, with event: UIEvent?) {

        let touch : UITouch! = touches?.first
        location = touch.location(in: self.view)

        strechyImage.center = location

    }

    func setUpView() {

        let viewHeight = UIScreen.main.bounds.height
        //FloatButton.setImage(UIImage(named: "Icon ionic-md-sad"), for: .normal)

        boxviewImage.image = UIImage(named: "nfc box")
        boxviewImage.frame = CGRect(x: 0, y: 0, width: 5, height: 200)
        let currentWindow: UIWindow? = UIApplication.shared.keyWindow
        currentWindow?.addSubview(boxviewImage)
        //view.addSubview(boxviewImage)

        strechyImage.image = UIImage(named: "nfc curve")
        strechyImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
        view.addSubview(strechyImage)

        buttonImage.image = UIImage(named: "nfc floating")
        buttonImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
        strechyImage.addSubview(buttonImage)
        //view.bringSubviewToFront(buttonImage)

        buttonImage.translatesAutoresizingMaskIntoConstraints = false
        strechyImage.translatesAutoresizingMaskIntoConstraints = false
        boxviewImage.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            strechyImage.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: 1),
            strechyImage.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.142),
            strechyImage.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3),

            strechyImage.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -(viewHeight / 20)),

            buttonImage.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.1),
            buttonImage.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.055),
            buttonImage.centerXAnchor.constraint(equalToSystemSpacingAfter: strechyImage.centerXAnchor, multiplier: -0.9),
            buttonImage.centerYAnchor.constraint(equalToSystemSpacingBelow: strechyImage.centerYAnchor, multiplier: 0),

            boxviewImage.trailingAnchor.constraint(equalTo: currentWindow!.safeAreaLayoutGuide.trailingAnchor, constant: 2.2),
            boxviewImage.widthAnchor.constraint(equalTo: currentWindow!.widthAnchor, multiplier: 0.0255),
            boxviewImage.heightAnchor.constraint(equalToConstant: viewHeight),

            ])

    }

}

Need to create this transition as close as possible to the design in the link


text:
Q: What exactly is an "induced operation"? Examples of places where I see this used:

Let * be a binary operation in S and let H be a subset of S... the binary operation on H given by restricting * to H is the induced operation of * on H
For a subgroup, it is not sufficient that "the set of one group be a subset of another, but also that the group operation on the subset be the induced operation that assigns the same element to each ordered pair from this subset as is assigned by the group operation on the whole set"

I just really don't understand what an induced operation is supposed to be.
Is this an accurate understanding?: If you have the binary structure $\langle S,* \rangle$, then the induced operation is if you make another binary structure with set S' and let the operation be the same * as in the first binary structure. In other words, is it accurate to say that the operation * in the binary structure $\langle S',* \rangle$ is the induced operation of $\langle S,* \rangle$, but the operation *' in $\langle S',*' \rangle$ is not?
All quotes from the book "A First Course in Abstract Algebra" by John Fraleigh, 7th edition

A: Your suggestion is correct, except that you forgot to say what $S'$ has to do with $S$. And it is this: $S'$ is a subset of $S$. For instance, sum on $\mathbb R$ does not induce an operation in $(-1,1)$ since, in general the sum of two elements of $(-1,1)$ is not an element of $(-1,1)$.
There is another case of induced operations, which appears in the context of quotients of algebraic structures, but I don't know whether or not you are familar with this.

A: I think looking at an example is quite telling: let us consider $\mathbb{Q}\subset \mathbb{R}$. Then $\mathbb{R}$ and $\mathbb{Q}$ are groups for the usual addition. But $\mathbb{Q}$ is also a group for the (quite arbitrary) operation $a\star b= a+b+1$.
Now the addition on $\mathbb{Q}$ is the operation induced by the addition on $\mathbb{R}$, meaning that if you take two elements $a,b\in \mathbb{Q}$, you can add them as real numbers or as rational numbers, and it is the same thing.
On the other hand, even though $(\mathbb{Q},\star)$ is a group and $\mathbb{Q}\subset \mathbb{R}$, the operation $\star$ is not the restriction of the addition on $\mathbb{R}$, it is not the induced operation, so this does not define a subgroup.
On the other hand, if we define $a\bullet b= a+ b+1$ on $\mathbb{R}$, then $\star$ on $\mathbb{Q}$ is the restriction of $\bullet$ on $\mathbb{R}$, so $(\mathbb{Q},\star)$ is a subgroup of $(\mathbb{R},\bullet)$.

A:
Induced operation. Definition (2.4) Let $\ast$ be a binary operation on a set $S$ and let $H$ be a subset of $S$. If for all $a,b \in H$ we also have $a\ast b \in H$, then $H$ is closed under $\ast$. In this case, the binary operation on $H$ given by restricting $\ast$ to $H$ is the induced operation of $\ast$ on $H$.

The above is quoted from Section 2 – Binary Operations
Instructor: Yifan Yang
Fall 2006 the first result on google search for induced binary operation.
My understanding would be it induces a new magma ( a set with an operation it's closed under) which if it has certain elements would be a subgroup, subring, etc.


text:
Q: Query in Access 2010 With this query
SELECT Year, Month,  Customer, Cod_user, Int(Sum(hours)) AS hours
FROM T_Att
GROUP BY Year, Mounth, Customer, Cod_user
HAVING (((Year)="2016") AND ((Month)="03") AND ((Customer)="CA"));

I get the following result

If you want to add the global sum (sum) and a key, what needs to change?

A: Although I haven't tested you should be able to just add another field:
This will add all hours for all years, months and customers.
SELECT      Year,
            Month,
            Customer,
            Cod_user,
            Int(Sum(hours)) AS lhours,
            (
             SELECT SUM(hours)
             FROM T_Att
            ) AS GlobalTotal
FROM        T_Att
GROUP BY    Year, Month, Customer, Cod_user
HAVING      (((Year)="2016") AND ((Month)="03") AND ((Customer)="CA"));

To keep the GlobalTotal to March 2016 use:
SELECT      Year,
            Month,
            Customer,
            Cod_user,
            Int(Sum(hours)) AS lhours,
            (
             SELECT SUM(hours)
             FROM T_Att
             WHERE Year = T1.Year AND Month = T1.Month
            ) AS GlobalTotal
FROM        T_Att T1
GROUP BY    Year, Month, Customer, Cod_user
HAVING      (((Year)="2016") AND ((Month)="03") AND ((Customer)="CA"));

Note - I've renamed hours to lhours to avoid a circular reference.  You should also consider renaming year and month as these are key words and may cause problems.
Also, year and month would be better as numbers rather than text.


text:
Q: Is it possible to avoid the entries in an Assembler to behave as a quee? I am trying to implement the real behavior of a warehouse in Anylogic.In the transportation section I used the assembler to transport  three different products in one package.The quees before the hold box  work as a storage with a limit capacity. The case is that there is a moment where the storage is full and the hold become unblocked in that moment all the components go to the entry of the assembler and the storage its empty. This behavior is not realistic and I would like to avoid the components to get stuck at the entry of the assembler and go 1 by 1. Is this possible?

A: Sure, change your "Hold" block to release only 1 agent at a time:

You will need to ensure that more than 1 agent is freed by calling hold.unblock() regularly until the queue is empty, though.
Alternatively, replace the Queue-Hold combination with a "Wait" block and free() only individual agents when you think it is the right time.


text:
Q: Linking to another page with a jQuery element The title might sound a little bit confusing because I don't know how to word it but here's my situation.
Lets say I have two pages. One is my home page and the other is a showcase page.
What I would like to accomplish is this. When I click on the Showcase 1 link on the index page I want the browser to go to the showcase page and open up the first showcase automatically.
Is this possible?
The home page has a snippet as follows:

Showcase 1
All Showcases

The showcase page has a snippet as follows:

$(document).ready(function() {

  $('.showcases').css('display', 'none');

  $('#showcase-link-one').click(function() {
    $('#showcase-two').stop(true, true).hide('fast');
    $('#showcase-three').stop(true, true).hide('fast');
    $('#showcase-one').stop(true, true).show('fast');
  });

  $('#showcase-link-two').click(function() {
    $('#showcase-one').stop(true, true).hide('fast');
    $('#showcase-three').stop(true, true).hide('fast');
    $('#showcase-two').stop(true, true).show('fast');
  });

  $('#showcase-link-three').click(function() {
    $('#showcase-one').stop(true, true).hide('fast');
    $('#showcase-two').stop(true, true).hide('fast');
    $('#showcase-three').stop(true, true).show('fast');
  });

});
ul {
    list-style-type: none;
}

.showcase-link {
    text-decoration: none;
}

.showcase-link:hover {
    color: #000;
}

Showcase One

Showcase Two

Showcase Three

You Clicked on Showcase One

You Clicked on Showcase Two

You Clicked on Showcase Three

A: One way to do it is to set the hash in the URL when clicking that link.
Showcase 1

Then with JS you can check the hash with window.location.hash and open the right showcase.
Lets say you save all the clickable showcases in an array
var showcase = ['#link-one', '#link-two', '#link-three'];

$(document).ready(function() {

  $('.showcases').css('display', 'none');

  $('#showcase-link-one').click(function() {
    $('#showcase-two').stop(true, true).hide('fast');
    $('#showcase-three').stop(true, true).hide('fast');
    $('#showcase-one').stop(true, true).show('fast');
  });

  $('#showcase-link-two').click(function() {
    $('#showcase-one').stop(true, true).hide('fast');
    $('#showcase-three').stop(true, true).hide('fast');
    $('#showcase-two').stop(true, true).show('fast');
  });

  $('#showcase-link-three').click(function() {
    $('#showcase-one').stop(true, true).hide('fast');
    $('#showcase-two').stop(true, true).hide('fast');
    $('#showcase-three').stop(true, true).show('fast');
  });

  if($.inArray(window.location.hash, showcase)) // check to see if it's a showcase
     $( '#showcase-' + window.location.hash.replace('#') ).trigger('click')

});

Like this you can send the information in you link and use it on the next page.

A: If you change the code to the following showcase one will run when the page loads.
$(document).ready(function() {

  $('.showcases').css('display', 'none');

  $('#showcase-link-one').click(function() {
    $('#showcase-two').stop(true, true).hide('fast');
    $('#showcase-three').stop(true, true).hide('fast');
    $('#showcase-one').stop(true, true).show('fast');
  });

  $('#showcase-link-two').click(function() {
    $('#showcase-one').stop(true, true).hide('fast');
    $('#showcase-three').stop(true, true).hide('fast');
    $('#showcase-two').stop(true, true).show('fast');
  });

  $('#showcase-link-three').click(function() {
    $('#showcase-one').stop(true, true).hide('fast');
    $('#showcase-two').stop(true, true).hide('fast');
    $('#showcase-three').stop(true, true).show('fast');
  });

  $('#showcase-link-one').trigger('click');
});


text:
Q: Rails prints the query result along with the object data in the view I want to create a notebook app in rails. I need to print all the notes in the index view, so below is code in haml.
 = @notes.each do |note|
   %h1= link_to note.title, note
   %p= time_ago_in_words(note.created_at)

The problem is after the Note title and created time are displayed, the query result is printed at the end(Screenshot below).

The issue persists only while printing all the notes at once using loop. Can't figure out what's the issue. Thanks in advance.

A: Change = with -
- @notes.each do |note|

If you just want to loop over @notes use - if you want to print some output use =
- @notes.each do |note|
   %h1= link_to note.title, note
   %p= time_ago_in_words(note.created_at)


text:
Q: OSGi bundle has name unknown_0.0.0 I have created OSGi bundle by Apache Felix Maven Bundle Plugin. Output jar file seems good, and MANIFEST.MF is following:
Manifest-Version: 1.0
Export-Package: cz.bach.entities.ui.extensions;uses:="org.osgi.framewo
rk,cz.bach.entities.ui.extensions.output,org.slf4j,cz.bach.dataframe2
.domain,com.vaadin.ui,cz.bach.entities.ui.commons,cz.bach.entities.ui
.actions,com.vaadin.server,org.springframework.beans.factory.annotati
on,cz.bach.entities.ui.lang,cz.bach.entities.ui.output,org.aspectj.la
ng,org.springframework.transaction.aspectj,org.aspectj.lang.reflect,o
rg.springframework.transaction.annotation,org.aspectj.runtime.reflect
,org.springframework.beans.factory.aspectj,org.springframework.beans,
org.springframework.context,org.springframework.beans.factory.config,
com.vaadin.event,org.apache.log4j,org.osgi.framework.launch"
Ignore-Package: cz.bach.entities.ui.extensions
Bundle-ActivationPolicy: lazy
Built-By: firzen
Tool: Bnd-0.0.357
Bundle-Name: extensions
Created-By: Apache Maven Bundle Plugin
Build-Jdk: 1.6.0_45
Bundle-Version: 0.0.1.SNAPSHOT
Bnd-LastModified: 1446557486350
Bundle-Activator: cz.bach.entities.ui.extensions.Activator
Bundle-ManifestVersion: 2
Bundle-SymbolicName: isai-extensions
Import-Package: com.vaadin.event;resolution:=optional;version="7.5",co
m.vaadin.server;resolution:=optional;version="7.5",com.vaadin.ui;reso
lution:=optional;version="7.5",cz.bach.dataframe2.domain;resolution:=
optional,cz.bach.entities.ui.actions;resolution:=optional,cz.bach.ent
ities.ui.commons;resolution:=optional,cz.bach.entities.ui.extensions.
output;resolution:=optional,cz.bach.entities.ui.lang;resolution:=opti
onal,cz.bach.entities.ui.output;resolution:=optional,org.apache.log4j
;resolution:=optional,org.aspectj.lang;resolution:=optional,org.aspec
tj.lang.reflect;resolution:=optional,org.aspectj.runtime.reflect;reso
lution:=optional,org.osgi.framework;resolution:=optional;version="1.3
",org.osgi.framework.launch;resolution:=optional;version="1.1",org.sl
f4j;resolution:=optional;version="1.7",org.springframework.beans;reso
lution:=optional;version="3.1",org.springframework.beans.factory.anno
tation;resolution:=optional;version="3.1",org.springframework.beans.f
actory.aspectj;resolution:=optional;version="3.1",org.springframework
.beans.factory.config;resolution:=optional;version="3.1",org.springfr
amework.context;resolution:=optional;version="3.1",org.springframewor
k.transaction.annotation;resolution:=optional;version="3.1",org.sprin
gframework.transaction.aspectj;resolution:=optional;version="3.1"

But when I load this jar file by this code in my project ..
public void installPackage(File f) throws BundleException  {
    Bundle b = ctx.installBundle("file:" + f.getPath());
    System.out.println("starting bundle: " + b + ", location: " + f.getPath());
    b.start();
}

.. the output is:
starting bundle: unknown_0.0.0 [3], location: /tmp/isai-extensions.jar

It means that symbolic name of bundle is null despite the fact that it was specified in MANIFEST.MF by line: Bundle-SymbolicName: isai-extensions. Also when I call b.start(), no exception is thrown. It is quite strange behaviour.. How can I set symbolic name properly?
Thanks in advance!

A: You can call Bundle.getSymbolicName.
In your example code you are calling Bundle.toString. The OSGi spec doesn't define exactly what this method should return, but I am a bit surprised that it's returning "unknown".

A: I have solved this problem by removing /tmp/org.eclipse.osgi folder (on GNU/Linux machine). After that step my bundle started to work.


text:
Q: How to echo something from javascript to div class html Javascript
    function validateForm() {
        var result;
        var keywords = document.querySelectorAll('#keywords');
        [].slice.call(websites).forEach(function(website) {
            if (website.value == '') {
                website.focus();
                HERE I SAY SOMEHOW THE ERROR
                result = false;
                return true;
            }
        });
        return result;
    }

HTML

HERE THE ERROR IS GETTING ECHOED

How do i echo website in that div above and how do i add the error in that if condition.

A: Try:
document.querySelectorAll('.error-website')[0].innerHTML = 'Website';

As NULL and VisioN has pointed , this:
document.querySelector('.error-website').innerHTML = 'Website';

is even faster , because of "querySelector is faster unless the match is the last DomNode in the DOM".

A: First of all, it would be more appropriate to use an ID not a class; the reason is that classes are meant for, well, classes (i.e. categories) of elements; however, in your case, you are dealing with one single unique element (you'll only have one), so assuming you take my advice and change to the following markup:

HERE THE ERROR IS GETTING ECHOED

... it will be as simple as:
document.getElementById('error-website').innerHTML = "whatever you like";

A: $(".error-website").text("Website")

A: document.getElementById('error-website').innerHTML = ....
if you use an id...

A: Use DOM document.getElementsByClassName
Eg.
function validateForm() {
      var result;
      var keywords = document.querySelectorAll('#keywords');
      [].slice.call(websites).forEach(function(website) {
    if (website.value == '') {
    website.focus();
        HERE I SAY SOMEHOW THE ERROR
        result = false;
        return true;
    }
});
return result;

var a=validateForm();
if(a){
 document.getElementsByClassName("error-website")[0].innerHTML=a;
}

NOTE: getElementsByClassName() does not work in Internet Explorer 5,6,7, and 8


text:
Q: как убрать гланицы на изображении используя matplotlib.pyplot У меня есть изображение которое я перевожу в чб используя cv2.
потом мне необходимо сохранить измененное изображение на диск, для этого я использую matplotlib.pyplot.
всё оукей, но изображение сохраняется с белыми рамками по периметру.

A: Короче проблема заключается в том, что я использовал matplotlib. А он тут совсем не нужен.
Matplotlib я использовал для перевода фото в негатив, вот этой строчкой plt.imshow(img, cmap=plt.cm.binary). И казалось бы, ну вот, фото в негативе!
Но тут у нас появляются рамки и шкалы измерения(от шкал я избавился), а от рамок нет :(
Для избежания этой дрочки надо использовать cv2 и для перевода фото в негатив вам надо от 225 отнять ваше изображение(код висит ниже).
#метод переводит в негатив переданное изображение
def load_img(imgpath):
    img = cv2.imread(imgpath, 0) #загружаем фото
    negative_img = 225 - img #переводим в негатив
    cv2.imwrite("negative image.bmp", negative_img) #сохраняем


text:
Q: (Mongoose) When isModified is false? I have something like that
UserSchema.pre('save', function(next) {
  console.log(this.isModified());

  next();
});

The output is always true, reading the documentation it says:

Returns true if this document was modified, else false.

I can't find a case when the function returns false.
UPDATE
This is the way I call the save function
let user = new User;

  user.email =  req.body.email;
  user.displayName =  req.body.displayName;
  user.avatar =  req.body.avatar;
  user.password =  req.body.password;

  user.save((err, userStored) => {
    if (err)
      return res.status(500).send({Message: `Error. ${err}`});

    res.status(200).send({product: userStored});
  })

A: This is possible because you are always modifying that data. If you want to check that (isModified === false) then try to update document with previous value(same value as before). You will get a false in nModified.
Like,
let updatedata = {
        'nOtp': nOtp
    };
    Model.update({_id: 'your_id'}, { $set: updatedata }, (error, doc) => {
        if (error) return res.status(500).json(error);
        // **Here below line you can check. If values is same as before**
        if (doc.nModified === 0) return res.status(417).jsonp({message: 'document is not modified'});
        return res.status(200).json({message: 'success'});
    });

You can do it same in your method


text:
Q: Change instance return value without using Instance variables Can someone give me the best possible solution for this,
I have a class
Class A

  def a
    return "a" if @logic
    return "b"
  end

  def change_logic
    @logic = true
  end

end

In my solution, I should be able to do
object = A.new
object.change_logic
object.a #print "a"

or
object = A.new
object.a #print "b"

To implement this I created the method change_logic & it will change @logic instance variable.
But I need to implement this without having a instance variable like @logic
What will be the best way to do it??

A: If you need to change what's returned conditionally but you don't want the condition at instance level then the method needs to be informed of what that condition is. For example,
Class A
  def a(logic = false)
    logic ? 'a' : 'b'
  end
end

then it would be invoked instead as:
object = A.new
object.a(true) #print "a"

or
object = A.new
object.a #print "b"


text:
Q: Running binary in Google Cloud Function I have a cloud function that generates a pdf. The cloud functions is in Python3.7 and it uses the module pdfkit==0.6.1. This pdfkit has a dependency of wkhtmltopdf. The OS env where the instance is running does not provide this dependency. So what i did was put the wkhtmltopdf binary in the code directory and use it from there. The problem is that it gives an error "[Errno 13] Permission denied: '/user_code/wkhtmltopdf.deb'". Is there a way to allow permissions to a file in cloud functions? or maybe install the dependency another way like so "sudo apt-get install xvfb libfontconfig wkhtmltopdf

A: Cloud Functions is a Event-driven serverless; this means that a function will run when an event occurs and you don't care about the infrastructure behind. pdfkit depends on wkhtmltopdf which is a binary that should be installed on your server that does not apply for Cloud Functions scope.
Nevertheless, I tried to upload the binaries to Cloud Functions zipped with the code and after doing some tricky commands using python changing the permission of the binaries to be executable you need to  face another problem, wkhtmltopdf depends on QT5 libraries. You need to upload your zip file with the binaries, libraries and your code which is more than 150 MB and even when you thought you're done, more libraries are required, more memory is needed and when you execute your function it takes a long time to run because of all the preprocessing.
At the end, this is a bad idea and you may want to use an alternative like this.


text:
Q: compile and join coffeescript files I have the following structure:
/lib
  / myfile.js.cofee
  / secondfile.js
/src

and i would like to compile them into
/lib
  / myfile.js.cofee
  / secondfile.js
/src
  / awesomefile.min.js

I have read about Cakefiles, but i'm not sure how to exactly do this.
Thanks,
Mike

A: If you happen to be using something based on connect (e.g. express), I'd recommend using connect-assets. If not, then grunt may be a good bet, as was previously suggested. If you'd like to do this yourself using a Cakefile, here is one approach you could use:
Note that the convention is to build from src to lib (which is the reverse of what you stated in the question). I'll use that convention below, but you can easily switch it back if needed.
$ npm install snockets
place the following in src/awesomefile.coffee:
#= require secondfile.js
#= require myfile.js.coffee

create a Cakefile with the following:
fs = require 'fs'
Snockets = require 'snockets'

NAME = 'awesomefile'
INPUT_FILE = "src/#{NAME}.coffee"
OUTPUT_FILE = "lib/#{NAME}.min.js"

task 'build', 'Build lib/ from src/', ->
  snockets = new Snockets()
  js = snockets.getConcatenation INPUT_FILE, async: false, minify: true
  fs.writeFileSync OUTPUT_FILE, js

task 'clean', "remove #{OUTPUT_FILE}", ->
  fs.unlinkSync OUTPUT_FILE

Now you can just do:
$ cake build
and that will create a lib/awesomefile.min.js.
You can have the files in src track their own dependencies, or you can list the order to be included in a single file like I've done above. For more, you can check out the snockets repository. Also note that the compiling chapter chapter of The Little Book on CoffeeScript is a good resource for learning about cake files.

A: Might not be the exact answer you expected.
Grunt.js at www.gruntjs.com is a very helpful buildtool and certainly includes a lot of stuff that you need to do on a daily basis with a webproject.


text:
Q: css responsive grid - horizontal line between rows I have a responsive layout with a grid of content blocks.
on desktop each row is 4 blocks
on tablet each row is 3 blocks
on phone each row is 2 blocks
I want a horizontal line to run between each row of blocks on all sizes. At the moment I have a border bottom on each block but the line doesn't extend the full width of the page if you have an empty space (eg 3 blocks on a 4 column grid)
The only way I can think of doing it is to wrap each row in a container using JS and reload that function on each screen resize.
Anyone know of a CSS solution?
This image should demonstrate what I'm trying to achieve:

A: You can use some CSS media queries instead of javascript:
@media (max-width:768px) { /*Extra small devices - Phones (<768px)*/
    /*css here to show only the horizontal line for this size*/
}

@media (min-width:768px) { /*Small devices - Tablets (≥768px)*/
    /*css here to show only the horizontal line for this size*/
}

@media (min-width:992px) { /*Medium devices - Desktops (≥992px)*/
    /*css here to show only the horizontal line for this size*/
}

@media (min-width:1200px) { /*Large devices - Desktops (≥1200px)*/
    /*css here to show only the horizontal line for this size*/
}

A: If old browser support is not an issue, you could put some :before or :after code insertion to insert stuff before the start of each row
e.g. something like
<!DOCTYPE html>

<title>Quick and dirty border demo</title>

a

a

a

a

a

a

a

a

a

With different patterns (3n+1 etc) for each media query.
If you don't want a border above the first row, use (2n+3), (3n+4) ... (xn+(x+1))


text:
Q: iOS 4.0.1 "fast app switching" behavior in simulator vs device (iPhone 4) I'm testing an iPhone app in both the simulator (XCode 3.2.3, iPhone SDK 4.0.1) and on the device (iPhone 4 and iOS 4.0.1).  The simulator exhibits the expected "fast app switching" behavior while the device does not.
Simulator:

*

*click home button while app is running => go back to home screen

*click the app icon => app resumes where it left-off (app does not restart)

Device

*

*click home button while app is running => go back to home screen

*click the app icon => app restarts (does not resume from the user quit)

Why is this happening?

A: Maybe your phone is low on memory.


text:
Q: Parse + PubNub : private chat I want to make a private chat with Parse and Pubnub.
When a user receives an image from another friend, he can click on "reply by message", that opens a new view, and here is the private chat between the 2 friends.
I use "BubbleView" in framework for giving an iOS messaging aspect.
How can I make a private channel in Pubnub ?
I've added
PFUser *user = [PFUser currentUser];

channel = [PNChannel channelWithName:user.objectId];

but that affects only the channel to the user who are using the app, not channel for the 2 persons ... ?
With my code I can receive my own message, the console says :
PubNub (xxxxxxxxxx) SUBSCRIBED ON CHANNELS: (
    "PNChannel(xxxxxxxxx) objectID(user from parse who are using the app)"
Message received: the message i've sent
Here is my code :
ChatViewController.h :
#import "MessagesViewController.h"
#import "PNImports.h"

@interface ChatViewController : MessagesViewController

@property (strong, nonatomic) NSMutableArray *messages;

@end

ChatViewController.m :
#import "ChatViewController.h"
#import <Parse/Parse.h>

@interface ChatViewController ()

@end
PNChannel *channel;
id message;
NSDate *receiveDate;
NSString *text;
@implementation ChatViewController

#pragma mark - View lifecycle
- (void)viewDidLoad
{

    [super viewDidLoad];
    self.title = @"Messages";
    self.messages = [[NSMutableArray alloc] initWithObjects:
                     @"Testing some messages here.", @"lol",
                     nil];
    UIButton *exitButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [exitButton addTarget:self action:@selector(backToInboxView) forControlEvents:UIControlEventTouchUpInside];
    [exitButton setTitle:@"Inbox" forState:UIControlStateNormal];
    exitButton.frame = CGRectMake(0.0, 0.0, 60, 60);
    [self.view addSubview:exitButton];

    // #1 Define client configuration
    PNConfiguration *myConfig = [PNConfiguration configurationForOrigin:@"pubsub.pubnub.com"
                                                             publishKey:@"demo"
                                                           subscribeKey:@"demo"
                                                              secretKey:nil];
    // #2 make the configuration active
    [PubNub setConfiguration:myConfig];
    // #3 Connect to the PubNub
    [PubNub connect];

   }

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messages.count;
}

#pragma mark - Messages view controller
- (BubbleMessageStyle)messageStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (indexPath.row % 2) ? BubbleMessageStyleIncoming : BubbleMessageStyleOutgoing;
}

- (NSString *)textForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.messages objectAtIndex:indexPath.row];
}

- (void)sendPressed:(UIButton *)sender withText:text
{
    [self.messages addObject:text];
    if((self.messages.count - 1) % 2)
        [MessageSoundEffect playMessageSentSound];
    else
        [MessageSoundEffect playMessageReceivedSound];
    PFUser *user       = [PFUser currentUser];
    channel = [PNChannel channelWithName:user.objectId];
    // Receive Messages Sent to Me!
    [PubNub subscribeOnChannel:channel];
    // Send a Message to Sally
    [PubNub sendMessage:text toChannel:channel];
    [self finishSend];
}

- (void)backToInboxView{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end

and in Appdelegate.m :
- (void)pubnubClient:(PubNub *)client didSubscribeOnChannels:(NSArray *)channels {
    NSLog(@"DELEGATE: Subscribed to channel:%@", channels);
}
- (void)pubnubClient:(PubNub *)client didReceiveMessage:(PNMessage *)message {
    NSLog(@"Message received: %@", message.message);
}

A: Although in JavaScript, this is an extremely detailed tutorial on how to implement chat functionality (with private + public channels) with PubNub:
http://www.pubnub.com/blog/javascript-private-chat-api-with-access-control/
The same features exist for the PubNub ObjectiveC client.
PubNub channels alone are just channels -- there is no attribute on a channel that says a channel is private or public. To simulate "private", you can create hard-to-guess names for private channels (and don't give those names out), but over time, thats not the most secure solution.
To really make a PubNub channel private, use the PAM feature (as detailed in the tutorial). This will allow you to grant and revoke authorization tokens to specific channels, so even if someone does guess a private channel name, they cannot access it without knowing the auth token.
To lock it down even more, you can use built-in encryption, and with that running over a secure (SSL) PubNub connection, you've got a pretty secure and scaleable solution.


text:
Q: Tcp accept fails after first connection after 1 hour I have written C++ client server application and the server is crashing.
The scenario

*

*Start server

*1 hour later (not before) Client connect

Then the Server which is waiting in accept returns -1 with errno "Too many open files".
Nothing else special is running on the machine which led me to believe that accept is opening many file descriptors while waiting.
Is that true?
How can I fix this so the client could connect anytime?
the relevant server code:
int sockClient;
while (true) {

    sockaddr_in* clientSockAddr = new sockaddr_in();
    socklen_t clientSockAddrLen = sizeof(sockaddr_in);

    sockClient = accept(sockServer, (sockaddr *) clientSockAddr,
                        &clientSockAddrLen);

    if(sockClient == -1 ){
        std::ostringstream s;
        s << "TCP Server: accept connection error." << std::strerror(errno);
        throw runtime_error(s.str());
    }

    connection->communicate(sockClient, clientSockAddr, clientSockAddrLen);
}

A: You have a file descriptor leak somewhere. Possibly you aren't closing accepted sockets when you've finished with them, or else it's on a file somewhere.


text:
Q: Java: how to split a string when you want a delimiter of nothing Say I have string A = "AAaabb";
How do I split this string when there are no spaces, so I can't use space as a delimiter.
Is there a like null delimiter, where it just splits all characters?
basically I want an array with each individual character
[A, A, a, a, b, b]

A: Try this!
Use A.split(""); //A is your array
String A = "AAaabb";
String Array[] = A.split("");
System.out.println(Array[0]); // print A

A: just do this :
    String input =  "AAaabb";
    char[] output;
    output = input.toCharArray();

A: public static void main(String[] args) {
    String s = "AAaabb";
    String[] array = s.split("");

    for (String string : array) {
        System.out.println(string);
    }
}

result:
A
A
a
a
b
b


text:
Q: Save a file as a BLOB with Doctrine I use Symfony2 with Doctrine 2.2.2 and a Oracle Database. I want to save a file as a BLOB in the Oracle DB. I wrote a costum Type for Doctrine to have a BLOB Type. It look's like this:
class Blob extends Type
{
const BLOB = 'blob';

public function convertToPHPValue($value, AbstractPlatform $platform)
{
    return (is_resource($value)) ? stream_get_contents($value) : $value;
}

public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
    return 'BLOB';
}

public function getBindingType() {
    return \PDO::PARAM_LOB;
}

public function getName()
{
    return self::BLOB;
}
}

The entity which holds the file is the following:
<?php

class Document
{
/**
 * @var integer $id
 */
private $id;

/**
 * @var file $file
 */
private $file;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set file
 *
 * @param blob $file
 */
public function setFile($file)
{
    $this->file = $file;
}

/**
 * Get file
 *
 * @return blob
 */
public function getFile()
{
    return $this->file;
}
}

When I want to save the file with my Controller Doctrine only saves the Path to the temp-File which will be created when uploading the file.

A: It seems the $file variable is not a resource.
You could try this:
public function convertToPHPValue($value, AbstractPlatform $platform)
{
    return is_file($value) ? file_get_contents($value) : $value;
}

A: Seems to be a blob type in doctrine 2.2 here Doctrine\DBAL\Types\BlobType


text:
Q: RestSharp latest version breaks my API's post method (add Guid before and after the body) Since latest version of RestSharp, all my post API's are failing because something has been added to the bodies I send.
Looks like a Guid id is generated and is added before and after the body for each call; the issue is it's not accepted by all my API's providers.
FYI, I created 2 identical console apps, one with version "106.12.0", and one with latest version "107.3.0". please see below the result:
Thanks in advance to help me with this
BR
-Vince
Examples:
Working with Version="106.12.0" :
before:
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="application/xml"
  <SMSBoxXMLRequest>
  <username>cnoxxxx</username>
  <!-- password hidden -->
  <command>WEBSEND</command>
  <parameters>
    <service>VALAIS</service>
    <text>Test de Message Sms 1</text>
    <test></test>
    <receiver>+4177222333444</receiver>
  </parameters>
</SMSBoxXMLRequest>

after:
Not Working with Version="107.3.0" :
**--497993c6-3ef7-47fb-b527-403c1eefedf8**
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="application/xml"
  <SMSBoxXMLRequest>
  <username>cnoxxxx</username>
  <!-- password hidden -->
  <command>WEBSEND</command>
  <parameters>
    <service>VALAIS</service>
    <text>Test de Message Sms 1</text>
    <test></test>
    <receiver>+4177222333444</receiver>
  </parameters>
</SMSBoxXMLRequest>
**--497993c6-3ef7-47fb-b527-403c1eefedf8--**

**--3277a8db-bd83-4f3c-af2e-d34efe76fe98**
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="application/xml"
  <SMSBoxXMLRequest>
  <username>cnoxxxx</username>
  <!-- password hidden -->
  <command>WEBSEND</command>
  <parameters>
    <service>VALAIS</service>
    <text>Test de Message Sms 2</text>
    <test></test>
    <receiver>+4177222333444</receiver>
  </parameters>
</SMSBoxXMLRequest>
**--3277a8db-bd83-4f3c-af2e-d34efe76fe98--**

**--5b81fa95-a0b9-4f5c-9242-742734b0241e**
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="application/xml"
  <SMSBoxXMLRequest>
  <username>cnoxxxx</username>
  <!-- password hidden -->
  <command>WEBSEND</command>
  <parameters>
    <service>VALAIS</service>
    <text>Test de Message Sms 3</text>
    <test></test>
    <receiver>+4177222333444</receiver>
  </parameters>
</SMSBoxXMLRequest>
**--5b81fa95-a0b9-4f5c-9242-742734b0241e-**-


text:
Q: GC.collect is not releasing memory I am having an issue where the service application starts out at 16k and over 4 days gets to 3mg in memory.
The application cycles over and over again and waits x secs before it cycles again and the memory should release on every cycle. It looks like the memory just increases after x amount of cycles but never falls back down as I thought it would.
I am positive I am not doing something correctly but I am not sure what.
Any help would be appreciated.
Here is the code I used
Imports log4net
Imports log4net.Config
Imports System.Configuration
Imports System.IO
Imports System.Reflection
Imports System.Security.AccessControl
Imports System.Security.Principal
Imports System.Threading
Imports System.Data.SqlClient

Public Class EDIService
    Implements IDisposable

    Private Shared ReadOnly _log As ILog = LogManager.GetLogger(GetType(EDIService))

    Dim strStorageFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
    Dim strWorkFolder As String = strStorageFolder & "\EDIService"
    Dim strLogFolder As String = strWorkFolder & "\Log"

    Public MsSQLConn As SqlConnection
    Dim Comm As New Onling.clsSQLExecutes

    Dim objDSMS As DataSet
    Dim objDTMS As DataTable
    Dim objDSMT As DataSet
    Dim objDTMT As DataTable
    Dim objDSP As DataSet
    Dim objDTP As DataTable

    Private stopping As Boolean
    Private stoppedEvent As ManualResetEvent

    Public Sub New()
        InitializeComponent()
        'Init the log for net settings (must have in 4.0 Framework)
        log4net.Config.XmlConfigurator.Configure()
        Me.stopping = False
        Me.stoppedEvent = New ManualResetEvent(False)

        StartUp()

    End Sub

The onStart
Protected Overrides Sub OnStart(ByVal args() As String)
        ' Log a service start message to the Application log.
        _log.Info("EDI Service in OnStart.")

        ' Queue the main service function for execution in a worker thread.
        ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf ServiceWorkerThread))
    End Sub

The ServiceWorkerThread
Private Sub ServiceWorkerThread(ByVal state As Object)
    ' Periodically check if the service is stopping.
    Do While Not Me.stopping
        CheckForFiles()
        _log.Info("Sent to garbage collector")
        'GC.WaitForPendingFinalizers()
        'GC.Collect()
        'GC.WaitForPendingFinalizers()
        'GC.Collect()
        'Dispose(True)
        'GC.SuppressFinalize(Me)
        GC.Collect()
        GC.WaitForPendingFinalizers()
        ' Perform main service function here...
        _log.Info("Sleeping for " & My.Settings.TimerMilliseconds / 1000 & " seconds")
        Thread.Sleep(My.Settings.TimerMilliseconds)  ' Simulate some lengthy operations.
    Loop

    ' Signal the stopped event.
    Me.stoppedEvent.Set()
    GC.Collect()
    GC.WaitForPendingFinalizers()

End Sub


text:
Q: Python 3 urllib Discord vs Slack Bot I have this simple python script which is supposed to send me a message on Slack, and it works fine.
#!/usr/bin/python

from urllib.request import Request, urlopen
import json

# Provide the webhook URL that slack generated
slack_webhook_url = 'https://hooks.slack.com/services/josadfs/nfonwnfoawf/abcdsads'

# Post the message to the slack webhook
message = {
    "text": "Hello world"
}

req = Request(slack_webhook_url, json.dumps(message).encode('utf-8'))

response = urlopen(req)
response.read()

I have another script the does the same thing, but for discord.
#!/usr/bin/python

from urllib.request import Request, urlopen
import json

# Provide the webhook URL that slack generated
slack_webhook_url = 'https://discordapp.com/api/webhooks/252534154132/knskdnvoangoe0940507230'

# Post the message to the slack webhook
message = {
    "content": "Hello world"
}

req = Request(slack_webhook_url, json.dumps(message).encode('utf-8'))

response = urlopen(req)
response.read()

For some reason, this gives me a HTTP Error 403: Forbidden error.
The curl commands both work, so it's not an API key issue. The discord script works when using the requests module, though.
#!/usr/bin/python

import json
import requests

# Provide the webhook URL that Discord generated
discord_webhook_url = 'https://discordapp.com/api/webhooks/252534154132/knskdnvoangoe0940507230'

# Post the message to the Discord webhook
data = {
    "content": "Hello world"
}
requests.post(discord_webhook_url, data=data)

Is there something wrong with my urllib implementation? Can the discord request be sent using urllib?

A: It appears that Discord blocks the requests from the default user-agent of Python's urllib. I was able to successfully execute the code by specifying User-Agent and Content-Type using Request.add_header(). I tested the below code and it worked for me.
#!/usr/bin/python

from urllib.request import Request, urlopen
import json

# Provide the webhook URL that slack generated
slack_webhook_url = '<redacted>'

# Post the message to the slack webhook
message = {
    "content": "Hello world"
}

req = Request(slack_webhook_url, json.dumps(message).encode('utf-8'))

#specifying headers for the request, discord appears to block the  default urllib user-agent
req.add_header('Content-Type', 'application/json')
req.add_header('User-Agent', 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11')

response = urlopen(req)
response.read()


text:
Q: For mysql or mariaDB, Boolean search really does not return in relevance order? I already checked both documentations(for mysql and mariaDB latest versions):

For boolean mode, searches are not returned in order of relevance!
  https://dev.mysql.com/doc/refman/5.7/en/fulltext-boolean.html
https://mariadb.com/kb/en/mariadb/fulltext-index-overview/

But when i test it, it IS sorting by relevance! I ran some tests and it is sorting by the return of MATCH(which i believe is the relevance,right!?)! Is the documentation out of date? Or am i missing something?
Tests on 10.1.25-MariaDB
DROP TABLE IF EXISTS t1;
CREATE TABLE t1(id INT PRIMARY KEY,c1 varchar(30),FULLTEXT(c1));
INSERT INTO t1(id,c1) VALUES
(1,'aaa'),
(2,'aaa bbb ccc'),
(3,'aaa bbb');

SET @a='aaa bbb ccc';

SELECT id
FROM t1 WHERE
MATCH(c1) AGAINST(@a IN BOOLEAN MODE); # 2,3,1

SELECT id, MATCH(c1) AGAINST(@a IN BOOLEAN MODE) as rev
FROM t1 WHERE
MATCH(c1) AGAINST(@a IN BOOLEAN MODE) ORDER BY rev DESC; # 2,3,1


text:
Q: PrimeNG - DataTable sorting I try to implement a datatable with dynamic column sortable and paginator.
My problem is that sorting doesn't work:
My code:
 <p-dataTable [value]="enregistrements" [row]="10" [paginator]="true"
 [pageLinks]="3" [rowPerPageOptions]="5,10(20]" scrollable="true" scrollWidth="1200px">
<ng-container *ngFor="let champ of champs; let i = index">
    <p-column header="{{champ}}" [sortable]="true" field="{{champ}}">
        <ng-template let-enregistrement="rowData" pTemplate type="body">{{enregistrement.champs[i].value}}</ng-template>
    <p-column>
</ng-container>
</p-dataTable>

Ideas on what the problem might be?
My code compile and the display is right but when i click on header column to sort it, nothing happens.


text:
Q: How can I display a translation of a database column name as a table heading in a view, Rails 3 I have a model called User with an attribute called current_sign_in_at. In my en.yml file I have the display name as such…
en-GB:
  activerecord:
    attributes:
      user:
        current_sign_in_at: "Last sign-in"

…which allows me to display the desired form label ("Last sign-in") using = f.label :current_sign_in_at.
But how can I use this same translation for a table header, i.e. not in a form?
%th= :current_sign_in_at

A: You can use the static method "human_attribute_name", See the doc here on API dock
In your case:
%th= User.human_attribute_name :current_sign_in_at

(use User.human_name to display the model name translated with I18n in en.activerecord.models.user)
Hope this helps!

A: Another option for internationalized table headings is the table_for gem.
This will let you write erb code like:
<%= table_for @user do |table| %>
  <% table.column :current_sign_in_at %>
<% end %>


text:
Q: Computer keeps restarting in games I just bought a new PSU and video card so this problem might be related to that, but every time I fire up my favorite games (WoW and TF2), my computer will reboot without warning after playing for some time.
Here are my specs:

*

*Windows 7 64-bit

*Core i7 950 stock

*ASUS P6TD Deluxe

*6 GB Corsair Dominator @ 1600mhz

*Radeon 5870 (slightly overclocked)

*Corsair 850W modular PSU (brand new)

As I mentioned, it started happening more frequently after upgrading to the new power supply. What would happen once a week before is now happening 3-4 times a day. I upgraded from a 650W Corsair.
EDIT: Clocking my video card a little bit lower fixed this.

A: Issues like this are often caused or related to overheating components. Try making a log whilst the game runs with a program like SpeedFan (you can find logging in Configure > Log) of your CPU and GPU temperatures, especially. If these figures seem high, they may well be the cause of your problem. If the CPU is overheating at stock frequency/voltage, it may mean that the heatsink is not properly secured, or the TIM has not properly interfaced the CPU heatspreader and the heatsink. In this case, resecure the heatsink and refresh the TIM. If the GPU seems to be overheating, try downclocking (yes, frequency has an effect on temperature), and if you want to you can also try undervolting, but I wouldn't recommend it unless you know what you're doing.
However, I think the most likely thing is that you have an unstable GPU overclock. What have you done to test the stability of the clocks you are running with?


text:
Q: Tensorflow eval() without session or move variable to an other session I'm using tensorflow-models like it is described in the iris predict examples. Because of that I do not have a session object. Now I want to convert the labels to a numpy-array with .eval(). Without a session there comes an error.
Traceback (most recent call last):
 File "myfile.py", line 273, in <module>
   tf.app.run()
 File "/usr/local/lib/python3.4/site-packages/tensorflow/python/platform/app.py", line 30, in run
   sys.exit(main(sys.argv))
 File "myfile.py", line 270, in main
   train_and_eval()
 File "myfile.py", line 258, in train_and_eval
   label.eval()
 File "/usr/local/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 559, in eval
   return _eval_using_default_session(self, feed_dict, self.graph, session)
 File "/usr/local/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 3642, in _eval_using_default_session
   raise ValueError("Cannot evaluate tensor using `eval()`: No default "
ValueError: Cannot evaluate tensor using `eval()`: No default session is registered. Use `with sess.as_default()` or pass an explicit session to `eval(session=sess)`

Is there a possibility to access / get the session the model used in background? Or is there an other possibility to convert the tensor to a numpy-array?
If I create a new session, then it seems that tensorflow moves to this session but has no access to the variable. A python print() is displayed, but then it runs inifite. How can I parse a variable to this new session?
The other part of the net works well - it's only this special thing convert the tensor to a numpy-array
    COLUMNS = ["col1", "col2", "col3", "target"]
    LABEL_COLUMN = "target"
    CATEGORICAL_COLUMNS = ["col1", "col2", "col3"]

    def build_estimator(model_dir):
        col1 = tf.contrib.layers.sparse_column_with_hash_bucket(
            "col1", hash_bucket_size=10000)
        col2........

        wide_columns = [col1, col2, col3]
        deep_columns = [
            tf.contrib.layers.embedding_column(col1, dimension=7),
            tf.contrib.layers.embedding_column(col2, dimension=7),
            tf.contrib.layers.embedding_column(col3, dimension=7)
        ]

        m = tf.contrib.learn.DNNLinearCombinedClassifier(...)
        return m

    def input_fn(file_names, batch_size):
        ...
        label = tf.string_to_number(examples_dict[LABEL_COLUMN], out_type=tf.int32)
        return feature_cols, label

    def train_and_eval():
        model_dir = "./model/"
        print(model_dir)

        m = build_estimator(model_dir)
        m.fit(input_fn=lambda: input_fn(train_file_name, batch_size), steps=steps)
        results = m.evaluate(input_fn=lambda: input_fn(test_file_name, batch_size),
            steps=1)
        pred_m = m.predict(input_fn=lambda: input_fn(test_file_name, batch_size))

        sess = tf.InteractiveSession()
        with sess.as_default():
            print("Is a session there?")
            _, label = input_fn(test_file_name, batch_size)
            label.eval()
            print(label)

    def main(_):
        train_and_eval()

    if __name__ == "__main__":
        tf.app.run()

The new session starts at the end of the code-snippet:
        sess = tf.InteractiveSession()
        with sess.as_default():
            print("Is a session there?")
            _, label = input_fn(test_file_name, batch_size)
            label.eval()
            print(label)

A: You need a Session and you need to initialize your variables before being able to access them:
with Session() as sess:
    sess.run(tf.global_variables_initializer())
    ...
    label_numpy = label.eval()

A: I changed the order so as to solved my problem.
     import tensorflow as tf
     v= tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
     result = tf.clip_by_value(v, 2.5, 4.5).eval()
     with tf.Session() as sess:
          print(sess.run(result))

Then my IDE warned"ValueError: Cannot evaluate tensor using eval(): No default session is registered. Use with sess.as_default() or pass an explicit session to eval(session=sess)"
Afterwards, I changed it into:
    import tensorflow as tf
    v= tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
    with tf.Session() as sess:
        result = tf.clip_by_value(v, 2.5, 4.5).eval()
        print(sess.run(result))

Then the problem is solved.

A: Since you use an estimator you can evaluate this way :
 evaluate_result = estimator.evaluate(input_fn=lambda: my_input_fn(INPUT_FILE_PATH, BATCH_SIZE))

It will return a dict containing the evaluation metrics specified in model_fn keyed by name, as well as an entry global_step which contains the value of the global step for which this evaluation was performed.
Otherwise you can use a session in which you must initialize your global variables:
with Session() as sess:
    sess.run(tf.global_variables_initializer())

You will be able to evaluate the normal way and your session will have access to your model.

A: I had this same issue when I was trying to create some custom metrics/loss functions. What I ended up doing was to use tf.py_func or better tf.py_function to make a call to a python function. (Tensorflow Doc).
The tensors you pass into the function are expected to be turned into numpy data/arrays.
The only difference between py_func and py_function is that with py_func the Tensor is automatically turned into a numpy array, whereas with py_function it's still a Tensor and you have to manually call .numpy() on it.
Tensorflow will add this call to the graph execution for you.
def train_and_eval():
    ...
    with Session() as sess:
        sess.run(tf.global_variables_initializer())
        ...
        labels = #some tensor
        other = #some tensor
        result = tf.py_function(some_function, [labels, other], [tf.float64]) # where the last argument
        # is an array representing the return type(s) of `some_function()`.
        # If `some_function` returns nothing, then you can do
        # tf.py_function(some_function, [labels, other], [])

# your normal python function
def some_function(labels, other):
    '''
    If you called this through py_func, the inputs are already numpy arrays,
    if you called through py_function, they're Tensors and you have to call
    labels.numpy() and other.numpy() to turn them to numpy.
    '''
    labels, other = labels.numpy(), other.numpy()
    print(labels)


text:
Q: How to Pass a sqlplus parameter from shell script to sql file I am having a Shell script that has a variable storing the date value using sqlplus connection as below. I want to pass the shell variable 'var_Date' value to the sql file.
cat extract.sh
#!/bin/ksh
var_Date=`sqlplus -s $DB_USER/$DB_PASS@$DB_HOST:$DB_PORT/$DB_SID << EOF
SELECT MAX(SAMPLE_DATE)-1 FROM SAMPLE_CASES WHERE KEY IN ('ab','bc');
EXIT;
EOF`
export var_Date
echo $var_Date

sqlplus -s $DB_USER/$DB_PASS@$DB_HOST:$DB_PORT/$DB_SID @data_extract.sql $var_Date

cat extract.sql
set echo off
set trimspool on
set pagesize 0
set colsep ~

spool extract.csv
SELECT CASE_ID FROM SAMPLE_CASE1 WHERE TIME_START>='&1'
spool off

I have tried to execute this script but it is failing with invalid identifier. Please help to understand what is the mistake I am doing here.

A: After searching in the internet for almost a week, could arrive at a working code. Below is the working code.
cat extract.sh
#!/bin/ksh
   var_Date=`sqlplus -s $DB_USER/$DB_PASS@$DB_HOST:$DB_PORT/$DB_SID << EOF
   SET HEADING OFF
   SELECT ''''||TRIM(MAX(SAMPLE_DATE)-1)||'''' FROM SAMPLE_CASES WHERE KEY IN ('ab','bc');
   EXIT;
   EOF`
   export var_Date
   echo $var_Date

   sqlplus -s $DB_USER/$DB_PASS@$DB_HOST:$DB_PORT/$DB_SID @data_extract.sql $var_Date

cat extract.sql
set echo off
set trimspool on
set pagesize 0
set colsep ~

spool extract.csv
SELECT CASE_ID FROM SAMPLE_CASE1 WHERE to_char(TIME_START,'DD-MON-YYYY') >='&1'
spool off

Firstly, we to need to pass the argument $var_Date to sqlplus within single quotes which is done within the variable declaration itself by concatenating ''''. We also need to use SET HEADING OFF to make the variable var_Date hold only the date value and not the header value.
Secondly, there was a ora error: "ORA-01858: a non-numeric character was found where a numeric was expected". To mitigate this, I had type-casted the field time_start to to_char post which the filter is applied and stored in the csv file.
Hope this helps others who had trouble like me.


text:
Q: How do I get rid of part of an object / Dictionary? I'm web scraping a site for data using beautifulsoup4, and I'm not sure how to be specific to the data I want, without calling an unwanted object. I've failed to get rid of it.
import requests
from bs4 import BeautifulSoup

headers = {'User-agent': 'Mozilla/5.0 (Windows 10; Win64; x64; rv:101.0.1) Gecko/20100101 Firefox/101.0.1'}
url = "https://elitejobstoday.com/job-category/education-jobs-in-uganda/"

r = requests.get(url, headers = headers)
c = r.content
soup = BeautifulSoup(c, "html.parser")

table = soup.find("div", attrs={"article": "loadmore-item"})

def jobScan(link):

    the_job = {}

    job = requests.get(url, headers = headers)
    jobC = job.content
    jobSoup = BeautifulSoup(jobC, "html.parser")

    name = jobSoup.find("h3", attrs={"class": "loop-item-title"})
    title = name.a.text

    the_job['title'] = title
    print('The job is: {}'.format(title))

    print(the_job)

    return the_job

jobScan(table)

this is the result it fetches
PS C:\Users\MUHUMUZA IVAN\Desktop\JobPortal> py absa.py
The job is: 25 Credit Officers (Group lending) at ENCOT Microfinance Ltd
{'urlLink': 'https://elitejobstoday.com/job-category/education-jobs-in-uganda/', 'title': '25 Credit Officers (Group lending) at ENCOT Microfinance Ltd'}

I want to be able to retain "The job is: 25 Credit Officers (Group lending) at ENCOT Microfinance Ltd" and drop "{'urlLink': 'https://elitejobstoday.com/job-category/education-jobs-in-uganda/', 'title': '25 Credit Officers (Group lending) at ENCOT Microfinance Ltd'}"

A: if you just want the desired output to be printed, you don't need the dicitonary or any return. just print the title and remove the second print.
import requests
from bs4 import BeautifulSoup

headers = {'User-agent': 'Mozilla/5.0 (Windows 10; Win64; x64; rv:101.0.1) Gecko/20100101 Firefox/101.0.1'}
url = "https://elitejobstoday.com/job-category/education-jobs-in-uganda/"

r = requests.get(url, headers=headers)
c = r.content
soup = BeautifulSoup(c, "html.parser")
table = soup.find("div", attrs={"article": "loadmore-item"})

def jobScan(link):
    job = requests.get(url, headers=headers)
    jobC = job.content
    jobSoup = BeautifulSoup(jobC, "html.parser")
    name = jobSoup.find("h3", attrs={"class": "loop-item-title"})
    title = name.a.text

    print('The job is: {}'.format(title))

jobScan(table)


text:
Q: Electrostatic Pressure Concept There was a Question bothering me.

I tried solving it But couldn't So I finally went up to my teacher asked him for help . He told me that there was a formula for Electrostatic pressure $\rightarrow$
$$\mbox{Pressure}= \frac{\sigma^2}{2\epsilon_0}$$
And we had just to multiply it to the projected area = $\pi r^2$
When i asked him about the pressure thing he never replied.
So what is it actually.Can someone Derive it/Explain  it please.

A: If you charge up a body, you get either an excess or deficiency of electrons on the body. It must be obvious to you that if we keep a bunch of similar charges close each charge will experience a repulsion. This repulsion per unit area of the body can be termed electrostatic pressure. To solve this problem I can give you three hints to solve this problem for which you won't be needing any calculus.
1) A charge cannot interact with its own electrostatic field.
2) Whenever you move across the surface of a conductor there is a discontinuity in the field around it.
3) Force divided by the surface normal to the force will give you the pressure on the surface.

A: I haven't seen the term electrostatic pressure used explicitly before, but I can explain how to think about the problem.
You need to consider the total force on each hemisphere, which is of course the integral over the sphere of the (vector) force per unit area. Take, then, a surface element $dA$, with charge $\sigma dA$. As is nicely explained by Purcell, the force on such a surface element is given by the average of the electric field inside and outside. Since the field inside vanishes, the total force on the surface element is then $$d\mathbf{F}=\frac{1}{2}\sigma dA\times\frac{4\pi R^2\sigma}{4\pi\epsilon_0}\frac{\hat{\mathbf{r}}}{R^2}=\frac{\sigma^2}{2\epsilon_0}\hat{\mathbf{r}}\,dA.$$
By symmetry, the total force on each hemisphere will be along the axis of the problem, which I take in the $z$ direction. This total force will then be
$$\mathbf{F}=\int d\mathbf{F}=\hat{\mathbf{z}}\int\frac{\sigma^2}{2\epsilon_0}\hat{\mathbf{z}}\cdot\hat{\mathbf{r}}dA=\hat{\mathbf{z}}\frac{\sigma^2}{2\epsilon_0}R^2\int\cos(\theta)d\Omega=\frac{\sigma^2\pi R^2}{2\epsilon_0}\hat{\mathbf{z}}.$$
The effect is indeed like having a gas inside exerting an outward pressure $p=\frac{dF}{dA}=\frac{\sigma^2}{2\epsilon_0}$, but this is hardly general - it depends on the precise, global arrangement of charges of this particular problem, while giving the impression of being a purely local  thing (since it depends only on the "local" charge density, which is of course also a global parameter). If you do accept this "pressure" then yes, the total force is this constant pressure times the area vector of the surface, which is $\pi R^2\hat{\mathbf{z}}$.

A: I think you can do this by dimensional analysis. I'll do the calculation because your professor almost certainly won't accept it, so it's not cheating :-)
We have the three quantities 1/$\epsilon_0$, $\sigma^2$ and $R^n$, where we don't know $n$, and the product has to have the dimensions of force. The dimensions are:
$1/\epsilon_0 = L^3MT^{-4}A^{-2} = L^3MT^{-4}Q^{-2}T^2 = L^3MT^{-2}Q^{-2}$
$\sigma^2 = Q^2L^{-4}$
$R^n = L^n$
and of course force has dimensions $MLT^{-2}$. Multiply together $1/\epsilon_0$, $\sigma^2$ and $R^n$ and set the dimensions equal to $MLT^{-2}$ and you get:
$L^3MT^{-2}Q^{-2}Q^2L^{-4}L^n = MLT^{-2}$
which simplifies to:
$ML^{-1}L^nT^{-2} = MLT^{-2}$
and therefore $n = 2$ and the answer is A.

A: Electrostatic pressure is the tension developed inside the sphere due to mutual repulsion among the charges of the same sphere. Its same like a rubber band is stretched from all the points outwards so a stress is developed in it

A:
Take the case of 3-D conductor and derive pressure exerted on a plate slightly separated from that conductor.
First try to derive it on your own if not comfortable take help from uploaded picture.

A: When charge is given to a conductor body then due to mutual repulsion between two charges on the two parts of the given conductor, a net force at a point on the surface of a charge conductor whose direction is normally outward. This mechanical force developed per unit area on the surface of charge conductor is also called electrostatic pressure/electrostatic stress.


text:
Q: Sharepoint & Azure: msoidcliL.dll missing I'm trying to deploy an application to Azure Websites that uses the Sharepoint Client Object Model (Sharepoint SDK 2013) to read data from a Sharepoint instance.
Everything works fine when I run it locally (with the Sharepoint SDK installed), but when I deploy it to Azure Websites and try to run it, I get System.IO.FileNotFoundException: msoidcliL.dll.
Obviously, it's because there's no Sharepoint SDK installed on the Azure server.
Is there any way to get this running on Azure Websites?
I already tried to copy the DLLs into the ~/bin directory (I tried with both 32 and 64 bit versions), which didn't change to error at all. I googled a few posts from people that had a similar problems, but I wasn't able to find any hint or solution so far :(

A: Just use Microsoft.Sharepoint.Client & Runtime Dlls of V 16. You won't get error.

A: i'm think this is not possible.
As workaround you may try to change variable in class ClientUtility.s_setupDirectory using reflection, something like that:
var path = Server.MapPath("/") + "bin\\";
logger.Info("Server Path:" + path);
var field = typeof(Microsoft.SharePoint.Client.ClientUtility)
              .GetField("s_setupDirectory",
                        BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue(null, path);

But you may run into other problems
UPDATE: Please use SharePoint Client Components V16, it will work.


text:
Q: Css before/after selector content can't contain the same attribute more than once It seems that the content of a before / after selector can't contain the same attribute more than once.
Example:
Let's say we have a div with the name "24".
When writing this:
content: attr(name) ' of ' attr(name);

the result is not "24 of 24", but "24 of". The second 24 is ignored.
If I change the second attribute into a different attribute then both attributes work, for example;
content: attr(name) ' of ' attr(data-size);

Both attributes with the value "24" result in "24 of 24".
Any idea why the same attribute can not be used multiple times or any idea how to make that work for a text line like this?

A: Sorry my mistake, a CSS mystery. Now I try it again and it just works! This does not explain anything, but I assume the cause of failing was something else.... Also thanks web-tiki for your jsfiddle to clarify! My question is solved.


text:
Q: How to enable MySQL remote access? I have a MySQL server and I want to enable remote access for a certain IP and localhost only. For some reason I couldn't manage to do it as it doesn't work every time I try. I typed the following command (of course user, password and db where different):
mysql> GRANT ALL ON foo.* TO bar@'192.168.0.1' IDENTIFIED BY 'PASSWORD';
I also disabled skip-networking.
What am I doing wrong then?

A: You need to change the bind-address parameter to the IP you wish to allow remote access to.  However, most people just comment out the bind-address parameter in the my.cnf file to allow access from anywhere and deal with who can access the DB server with user access control.  I would suggest the latter and not the former. Don't forget to restart mysql server after making changes to my.cnf for the changes to take effect.
Please refer Here for more information.
Additionally, The grant statement should have single quotes around the name as well as the host:
mysql> GRANT ALL ON foo.* TO 'bar'@'192.168.0.1' IDENTIFIED BY 'PASSWORD';

Also, don't forget to
Flush privileges;


text:
Q: Use of a Compiler from Java to Machine Code Why is java code not compiled to machine code by many people even if it will run faster than the JVM and without the JVM?
I am a computer science student at the TUM germany.
I know the benefits and disadvantages of java and the pros/cons of e.g. C/C++.
The java syntax is very similar to C++ (cannot speak about C, have not looked at it ever).
In java you dont use the stack explicitly. Compiling java code (after fixing the minor syntax differences) with a C compiler will only use the heap then.
Also created objects on the heap will not be freed automatically.
I recently had to code a "compiler" for java syntax so I do have a basic understanding of parsing code and tranforming it into usable assembler code.
If a company created an efficient parser that finds the lifetime of objects in java code to change these objects to use the stack in C++ instead, a compiler could compile this code the same way as regular C++ which could result in a better performance than using the JVM. Also heap objects will get freed after not being used anymore. (Even if you had to manually add the lines where objects should be freed, I dont think this might be hard)
I know I broke this huge topic down to this small explanation. Is there anything I am missing or is there something wrong with my thoughts?
(I am "in danger of being blocked from asking any more". Please help me to change my topic to better suit this forum!)
EDIT:
I am using both, java at university, C++ for doing projects at home. For me the differences are minor and can be changed easily. That is my experience at least.

A: efficient parser that finds the lifetime of objects : this is impossible to do, the lifetime cannot be determined statistically except on special/simple cases.
Even if you had to manually add the lines where objects should be freed, I dont think this might be hard : this is what we do in C or C++, the mark being a call to free/delete :-)
This is not for nothing garbage collectors exists, and you cannot replace easily a garbage collector by magic.
When there is no garbage collector there are some ways to help to free the allocated memory automatically, for instance to use std::shared_ptr, std::string also use an internal counter to know when the internal char * can be freed. The use of a counter of references is simple, but the count of references have to not overflow the counter, and that way does not work when you have a circle because the counters cannot go down to 0, again there is no magic


text:
Q: Jenkins SVNKit error while connecting to SVN in Linux server post kernel patch upgrade to FP3 I upgraded the kernel to patch 3 and now when I run Jenkins I am getting the error below during SVN Update  :
I think the issue may be with Subversion plugin (currently 1.45),SVNKit.
Linux version is SUSE Linux enterprise Server 11(x86_64)
PATCH LEVEl -3
VERSION 11
Subversion Plugin -1.45
Jenkins version -1.534
Error is below:
svn: E175002: SSLv3 SSLContext not available
    at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:64)
    at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:51)
    at org.tmatesoft.svn.core.internal.io.dav.http.HTTPConnection._request(HTTPConnection.java:754)
    at org.tmatesoft.svn.core.internal.io.dav.http.HTTPConnection.request(HTTPConnection.java:373)
    ... 37 more

Please help as its blocking my work!


text:
Q: iOS autolayout changes leading and trailing space I have some issues with auto layout, hopefully some of you can help me =).
I add a UIView to an empty view controller, like this:

Then I add constraints for leading and trailing space, like this:

Which results in this:

I can't understand why it sets them as equal to -16.0. If I change those values to 0, then Xcode complains about the width of the gray UIView.
When I run the app on iPhone 5 simulator, it looks fine:

However, when I run the app on iPhone 6 Plus simulator it adds white space on the left and on the right:

I don't want the gray UIView to have any space from the left of from the right no matter how big the screen is. How can I fix it? Thanks!

A: Double click the constraint and open it. There select first or second item and deselect "Relative to margin". Then set your constant as 0.
Xcode is showing -16 because it is calculating space with respect to a margin and not the edges.
Check following link for more info on margins. Editing Auto Layout Constraints

A: You can clear all existing constraints on the view,and in Any*Any mode, add constraints for all 4 space to superview, which are Leading, Trailing, Top, Bottom. Then it will have the equal width with the screen no matter how big the screen is.


text:
Q: Understanding the difference between $\partial f, \mathcal{D}_{f^{*}}, f^{*}, \partial f^{*}$ for a specific set of functions I am trying to calculate the following quantities: $\partial f, \mathcal{D}_{f^{*}}, f^{*}, \partial f^{*}$ for the following functions:

*

*$f(x) = x^2, \mathcal{D}_{f} = \mathbb{R}$.

*$f(x) = |x|, \mathcal{D}_{f} = \mathbb{R}$.

*$f(x) = e^x, \mathcal{D}_{f} = \mathbb{R}$.

*$f(x) = \dfrac{|x|^{p}}{p}, \mathcal{D}_{f} = \mathbb{R}, p>1$.

*$f(x) = x \log x-x+1, f(0) = 1, \mathcal{D}_{f} = [0, + \infty]$.

I am completely lost, seeing that as far as my study goes I have not been taught how to "calculate" them, other than the relatively well known definition.
Any pointers would be more than welcome.

A: Any book with Convex Analysis in the title will help you. The function in 2 is sublinear so its conjugate must be an indicator function. I find the following formula very useful for computing the subdifferential:
$$\partial f(x) = \mathbb{R} \cap [f'_-(x),f'_+(x)],$$
where $f'_{\pm}$ are the one-sided derivatives from Calculus I.


text:
Q: Sequence: Show that $\limsup(s_n.t_n) ≤ \limsup(s_n) · \limsup(t_n)$ Suppose $\{s_n\}$ and $\{t_n\}$ are bounded sequences of nonnegative numbers. Show that as $n\rightarrow \infty$ $$\limsup(s_n.t_n) ≤ \limsup(s_n) · \limsup(t_n)$$
My attempt:
Let $\limsup(s_n)=l$ and $\limsup(t_n)=m$ then $s_n<l+\epsilon$ for $n>N_1$ and $t_n<m+\epsilon$ for $n>N_2$. Also  $\{s_n\}$ and $\{t_n\}$ are bounded sequences, sequence $\{s_n.t_n\}$ is also bounded.
But $$s_nt_n<lm+l\epsilon +m\epsilon +\epsilon^2$$
How to prove that. I have no idea how to prove. Please help.

A: $$
\begin{align}
\limsup_{n\to\infty}s_nt_n
&=\lim_{n\to\infty}\sup_{k\ge n}s_kt_k\tag{1}\\
&=\lim_{n\to\infty}\sup_{\substack{j\ge n\\k\ge n\\j=k}}s_jt_k\tag{2}\\
&\le\lim_{n\to\infty}\sup_{\substack{j\ge n\\k\ge n}}s_jt_k\tag{3}\\
&=\lim_{n\to\infty}\sup_{j\ge n}s_j\sup_{k\ge n}t_k\tag{4}\\
&=\lim_{n\to\infty}\sup_{j\ge n}s_j\lim_{n\to\infty}\sup_{k\ge n}t_k\tag{5}\\
&=\limsup_{n\to\infty}s_n\limsup_{n\to\infty}t_n\tag{6}
\end{align}
$$
Explanation:
$(1)$: definition
$(2)$: rewrite in terms of two variables
$(3)$: the sup over a smaller set is less than the sup over a larger set
$(4)$: separate the sups
$(5)$: limit of a product is the product of the limits
$(6)$: definition

Clarification
$$
\begin{align}
\sup_{\substack{j\ge n\\k\ge n}}s_jt_k
&=\lim_{m_1,m_2\to\infty}\max_{\substack{m_1\ge j\ge n\\m_2\ge k\ge n}}s_jt_k\tag{7}\\
&=\lim_{m\to\infty}\max_{\substack{m\ge j\ge n\\m\ge k\ge n}}s_jt_k\tag{8}\\
&=\lim_{m\to\infty}\max_{m\ge j\ge n}s_j\max_{m\ge k\ge n}t_k\tag{9}\\
&=\lim_{m\to\infty}\max_{m\ge j\ge n}s_j\lim_{m\to\infty}\max_{m\ge k\ge n}t_k\tag{10}\\
&=\sup_{j\ge n}s_j\sup_{k\ge n}t_k\tag{11}
\end{align}
$$
Explanation:
$\phantom{1}(7)$: write sup as a limit of max
$\phantom{1}(8)$: limit of any subsequence is the limit of the sequence
$\phantom{1}(9)$: the greatest product is the product of the greatest elements
$(10)$: limit of a product is the product of the limits
$(11)$: definition

A: You've shown that for any $\epsilon > 0$: there exists a sufficiently large $N$ such that $n>N$ implies that
$$
s_nt_n < lm + (l+m)\epsilon + \epsilon^2
$$
Thus, for any such $n$, we have $\sup_{k \geq n} s_k t_k < lm + (l+m)\epsilon + \epsilon^2$.  Thus,
$$
\limsup_{n \to \infty} s_nt_n = \lim_{n \to \infty} \sup_{k \geq n} s_k t_k \leq lm + (l+m)\epsilon + \epsilon^2
$$
Howevever, since $\epsilon>0$ is arbitrary, we may conclude that
$$
\limsup_{n \to \infty} s_nt_n \leq lm + (l+m)(0) + (0)^2 = lm
$$
as desired.

A: Let $s_{k_n}t_{k_n}$ be the subsequence of $s_nt_n$ which converges to $\limsup s_nt_n$.
As $s_{k_n}$ is bounded, it possesses a converging subsequence $s_{k'_n}\to s$, and as $t_{k'_n}$ is bounded, it possesses a converging subsequence $t_{k''_n}\to s$.
Clearly,
$$
st=\lim_{n\to\infty}s_{k''_n}t_{k''_n}
= \lim_{n\to\infty}s_nt_n=  \limsup_{n\to\infty}s_nt_n .
$$
At the same time
$$
s=\lim_{n\to\infty}s_{k''_n}\le\limsup_{n\to\infty}s_n  \quad\text{and}\quad
t=\lim_{n\to\infty}t_{k''_n}\le\limsup_{n\to\infty}t_n.
$$
Hence
$$
\lim_{n\to\infty}s_nt_n=st\le
\big(\limsup_{n\to\infty}s_n\big)\big( \limsup_{n\to\infty}t_n\big).
$$


text:
Q: Como adicionar campos dinamicamente e vinculá-los à viewmodel no Asp.Net Tenho um relacionamento de 1:N entre Pessoa e Contato. Na minha view, consigo listar todos os contatos de um cliente, quando o mesmo é aberto.

Preciso implementar o botão "Novo Contato" de forma que, quando clicado, adicione dinamicamente os campos (Tipo de Contato, Contato, Contato Principal, Detalhes e o Botão Excluir)...  Eu tentei fazer com Java Script e consegui, mas tive problemas com as "validations" que não funcionavam e o "combobox ContatoTipo" que não popula... Isso ocorre pq não consegui usar as tags do asp.net core asp-"validation-for" e "asp-items" no bloco de JavaScript...
Fiz um FOR para receber os dados do banco e as validations e combobox funcionam corretamente. O Problema está no bloco JS que não funcionam. Como faço isso funcionar no JavaScript?
@model Retaguarda.Application.ViewModels.Pessoa.PessoaViewModel
@{
    ViewData["Title"] = "_PessoaContato";
}

                @if (Model.PessoasContatosViewModel != null)
                {
                    @for (int i = 0; i < Model.PessoasContatosViewModel.Count; i++)
                    {

                                @Html.HiddenFor(model => model.PessoasContatosViewModel[i].Id, new { @class = "hid-id" })
                                Tipo de Contato
                                <select asp-for="PessoasContatosViewModel[i].ContatoTipoId" asp-items="Model.ContatosTipos" data-plugin="selectpicker" title="Selecione uma opção" class="form-control show-tick show-menu-arrow sel-contatoTipo"></select>

                                Contato
                                <input type="text" asp-for="PessoasContatosViewModel[i].Contato" class="form-control txt-contato" />

                                    <input type="checkbox" asp-for="PessoasContatosViewModel[i].ContatoPrincipal" class="ckb-contatoPrincipal" checked autocomplete="off" />
                                    Contato Principal

                                Detalhes
                                <textarea asp-for="PessoasContatosViewModel[i].Detalhes" class="form-control txt-detalhes"></textarea>

                                <button type="button" class="btn btn-icon btn-default btn-outline btn-remover-contato" data-id="@Model.PessoasContatosViewModel[i].Id." style="margin-top: 30px;"></button>

                    }

                }

                <button id="btn-add-contato" type="button" class="btn btn-icon btn-default btn-outline"> Novo Contato</button>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Controller:
[HttpGet]
[Authorize(Policy = "CanWritePessoaData")]
[Route("pessoa-gerenciar/editar-pessoa/{id:int}")]
public IActionResult Edit(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var pessoaViewModel = _pessoaAppService.GetJoinById(id.Value);

    if (pessoaViewModel == null)
    {
        return NotFound();
    }

    pessoaViewModel.PessoaGenericoViewModel.Filiais = PreencherFiliais();
    pessoaViewModel.ContatosTipos = PreencherContatodosTipos();
    return View(pessoaViewModel);

}

ViewModels:
public class PessoaViewModel
{
    [Key]
    public int Id { get; set; }

    [DisplayName("Natureza")]
    [Required(ErrorMessage = "Escolha uma Natureza")]
    public PessoaNatureza PessoaNatureza { get; set; }
    [DisplayName("Natureza")]
    public string PessoaNaturezaDescricao { get; set; }
    [DisplayName("Naturezas")]
    public IEnumerable<SelectListItem> PessoasNaturezas { get; set; }

    public PessoaGenericoViewModel PessoaGenericoViewModel { get; set; }
    public IEnumerable<PessoaGenericoViewModel> PessoasGenericosViewModel { get; set; }

    public IEnumerable<SelectListItem> ContatosTipos { get; set; }
    public List<PessoaContatoViewModel> PessoasContatosViewModel { get; set; }

    public PessoaFisicaViewModel PessoaFisicaViewModel { get; set; }
    public PessoaJuridicaViewModel PessoaJuridicaViewModel { get; set; }

    public PessoaViewModel()
    {
        PessoasNaturezas = ExtensaoDeEnumerador.EnumParaSelectListGenerico<PessoaNatureza>("U", PessoaNatureza.ToString()).OrderBy(x => x.Text);
        PessoaFisicaViewModel = null;
        PessoaJuridicaViewModel = null;
    }
}

public class PessoaContatoViewModel
{
    [Key]
    public int Id { get; set; }

    public int PessoaId { get; set; }

    [DisplayName("Tipo de Contato")]
    [Required(ErrorMessage = "Escolha um Tipo de Contato")]
    public int ContatoTipoId { get; set; }
    [DisplayName("Tipo de Contato")]
    public string ContatoTipoDescricao { get; set; }
    [DisplayName("Tipos de Contato")]
    public IEnumerable<SelectListItem> ContatosTipos { get; set; }

    [DisplayName("Contato")]
    [Required(ErrorMessage = "O campo Contato é obrigatório")]
    [MaxLength(100, ErrorMessage = "O campo {0} deve ter no máximo {1} caracteres")]
    public string Contato { get; set; }

    [DisplayName("Detalhes")]
    [MaxLength(150, ErrorMessage = "O campo {0} deve ter no máximo {1} caracteres")]
    public string Detalhes { get; set; }

    [DisplayName("Contato Principal")]
    public bool ContatoPrincipal { get; set; }
}

A: Se adicionar puro html assim como está fazendo, não vai ter coisas importantes da sua model, como DataAnnotations por exemplo. Uma solução "mista" seria criar uma Action que devolva uma linha nova da sua model e através de uma chamada Ajax à essa action, pegar o conteúdo devidamente renderizado, e adicionar.
Para isso, transforme o bloco que deseja adicionar dinamicamente numa PartialView:
ContatoPartial:

        @Html.HiddenFor(model => model.PessoasContatosViewModel[@ViewBag.indice].Id, new { @class = "hid-id" })
        Tipo de Contato
        <select asp-for="PessoasContatosViewModel[@ViewBag.indice].ContatoTipoId" asp-items="Model.ContatosTipos" data-plugin="selectpicker" title="Selecione uma opção" class="form-control show-tick show-menu-arrow sel-contatoTipo"></select>

        Contato
        <input type="text" asp-for="PessoasContatosViewModel[@ViewBag.indice].Contato" class="form-control txt-contato" />

            <input type="checkbox" asp-for="PessoasContatosViewModel[@ViewBag.indice].ContatoPrincipal" class="ckb-contatoPrincipal" checked autocomplete="off" />
            Contato Principal

        Detalhes
        <textarea asp-for="PessoasContatosViewModel[@ViewBag.indice].Detalhes" class="form-control txt-detalhes"></textarea>

        <button type="button" class="btn btn-icon btn-default btn-outline btn-remover-contato" data-id="@Model.PessoasContatosViewModel[@ViewBag.indice].Id." style="margin-top: 30px;"></button>

Crie uma Action que retorne essa Partial:
public PartialViewResult NovoContato(int indice)
{
     ViewBag.indice= indice;
     return PartialView("ContatoPartial", new PessoasContatosViewModel());
}

Altere o javascript para fazer uma chamada Ajax para acionar a Action, e adicionar o conteúdo na página:
var itemIndex = $("#container input.iHidden").length;
        var novoIndice = qtdContatos +1;      //suponho q já tenha calculado
        e.preventDefault();
        $.get("@Url.Action("NovoContato", "NomeDaController")/"+novoIndice ,function(data){
            $("#div-contatos").append(data);
        });

Com isso, a nova linha será renderizada pelo ASP.Net, e a chamada ajax permite que não seja necessário um Post da página.