text:
Q: java cli running indicator I want some ascii characters periodically changing to indicate my CLI program is running, like -|\/-|/.... The old character is replaced by the new, which looks like an animation. Is there any library approaching that?
Kejia

A: You might want to use the carriage return(CR) character ('\r' in java) to do this. I would do it this way (assuming you are doing the animation at the beginning of the row):
My solution (Test.java):
public class Test
{
    public static void main(String[] args)
    {
        try
        {
            System.out.print("\\");
            Thread.sleep(1000);
            System.out.print("\r|");
            Thread.sleep(1000);
            System.out.print("\r/");
        }catch(Exception e)
        {
        }
    }
}

A: Simplest idea: try replace all console (rows & cols) with new view (frame) of your animation.

A: I once wrote a test program and part of it worked like curl/wget to download a file. To print the progress I just used System.err.print(n); System.err.print('\r'); which moves the cursor to the start of the line ready for the next progress update. But in your case you could probably print each one of "\\\b" "-\b" "/\b" (\b is backspace) in order repetitively to get the spinning effect.

A: In Scala:
"-|\\/-|/".toCharArray ().foreach {c =>  print ("\b" + c); Thread.sleep (250); }

Analog, but more Code in Java, but not tested:
for (c : "-|\\/-|/".toCharArray ())
{
    System.out.print ("\b" + c);
    Thread.sleep (250);
}


text:
Q: Does the windowClass property or NgbModalOptions actually do anything? I am opening an NgbModal passing a TemplateRef to create the dialog body, and passing in a custom class via the windowClass property of the NgbModalOptions object that I pass to the open() method.  I define the class in a referenced styleUrl in the component and am serving the modal via an injectable service in the component.  The modal is loading fine, and I can see the class name when I inspect the DOM, but the class appears to have no bearing on the modal.  I would like to use it to customize the size of the modal (css is defined to affect the child div where the size is set), but I have also played with properties that I can see in the Styles tab of the Chrome dev tools, but cannot see it affecting anything.  When I inspect in Firefox dev tools, I can find the CSS as an inline style sheet and it has a reference to the ngContent identifier assigned by Angular, so I am assuming that is does not affect the entire document, nor those parts added by ng-bootstrap that constitute the modal wrapper.  Has anyone been able to make this work successfully?  I am at my wit's end.  I would even be happy if I could get an ElementRef of the modal-header dive, but since I am using a template (which is not fully loaded in the DOM at init time) I have not been able to.  One of my requirements is that we do all DOM manipulation via Angular to maintain platform independence in the project ... so no jQuery.  Any thoughts?  And thanks in advance!!

A: I use windowClass and size attributes of NgbModalOptions to customize the modal. Sample code follows:
this.modalService.open(<your_template_ref_var>, {size: 'lg', windowClass: 'modal-adaptive-s1'});

Whereas
.modal-adaptive-s1 .modal-lg {width: 400px !important;  max-width: 400px;}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maximum of the product of two functions Suppose I have two bounded, non-negative, continuous functions $f,g:[a,b]\to \mathbb{R}$. Is it true that
$$\max_{x\in[a,b]}(f(x)g(x))\leq \max_{x\in[a,b]}(f(x))\max_{x\in[a,b]}(g(x)).$$
I have played around with some examples and am having a hard time finding an example for which this breaks.


text:
Q: Windows 11 black screen instead of blue Maybe a silly question, but I would just like to know this, is this an error or what. I just installed Windows 11 (upgraded from Windows 10 Home) and it works fine. Just some backgrounds colors are black as default instead of blue. Windows 11 is activated.
It looks like this:

Is this backgrounds normal for Windows 11? I can't get any other color.


text:
Q: Sorting The ArrayList in Android I Have 3 ArrayLists for example list1,list2 and list3
list1={ram,kevin,sachin,akshay,salman};
list2={111111111,22222222,3333333333,4444444444,5555555555};
list3={ram@gmail.com,kevin@gmail.com,sachin@gmail.com,akshay@gmail.com,salman@gmail.com};

i want to sort list1 in alphabetical order and i need other list to sort according to list1.

A: Sorting one list and updating others according to that sort order is quite cumbersome, since you'd have to match the new index of an element to the old index and use both to update the other lists.
In some cases that would be necessary and I'd solve that with some intermediate maps but in most cases, yours included, I'd just create an object for the data and put them into a single list, e.g.:
class User {
  String name;
  int id;
  String email;
}

List<User> list = ...;

Collections.sort( list, new Comparator<User>() {
  public int compare( User lhs, User rhs ) {
    return lhs.name.compareTo(rhs.name);
  }
});

Note that I intentionally left out stuff like constructors or null checks, to boil the code down to the essential parts.

A: It would be easier to do something like so (as per the recommendations above):
public class User implements Comparable<User>
{
    private String name;
    private String ID;
    private String email;

    public int compare(User u1)
    {
         return this.getName().compareTo(u1.getName());
    }
}

...

List<User> users = ...
Collections.sort(users);

The above code should sort the elements in Lexicographical Order by taking the name as sorting parameter.

A: Use a Comparator. There you define what to compare and how, in the compare() method you define what should be returned from two of your instances. Here's an example for a String Comparator.
new Comparator<String>() {
  public int compare(final String user1, final String user2) {
    // This would return the ASCII representation of the first character of each string
    return (int) user2.charAt(0) - (int) user1.charAt(0);
  };
};


text:
Q: How do I force $.getJSON to run before $http in Javascript? I have the following Javascript code in the controller of my web page.
 $.getJSON('resources/properties/properties.json', function(data) {
    $scope.properties = data;
    });

$http({
    method: 'GET',
    url: $scope.properties.Properties.dataLocation
        }).
        success(function (data) {
        $scope.all_types_and_configs = data;
        $scope.exec = [];
        }).
        error(function (data) {
        $scope.error = data.message;
        $scope.data = '';
        return;
        });
});

The structure of the json file to be fetched is not the problem.
It is supposed to first run the $.getJSON command and afterwards run the $http-request, since the $http request gets its url from the variable that is defined in the $.getJSON part at the top but instead when i do a console.log(properties) just below it, it spits out "undefined".
Why is the code not executing in the order that it is written?

A: The code is executing in order that it's written, just callback functions are being executed when the corresponding requests are complete. So you should put the second call in the first callback:
$.getJSON('resources/properties/properties.json', function(data) {
    $scope.properties = data;
    $http({method: 'GET', url: $scope.properties.Properties.dataLocation}).
        success(function (data) {
            $scope.all_types_and_configs = data;
            $scope.exec = [];
        }).
        error(function (data) {
           $scope.error = data.message;
           $scope.data = '';
           return;
        });
    });
});

A: It is executed asynchronous so both call will be done independantly.
$.getJSON has third parameter - success callback this is the way to sync those.
http://api.jquery.com/jquery.getjson/
Not sure why you are mixing jQuery AJAX and Angular $http ?

A: You could use the JQuery.done, which will execute your code after your request has finished.
Example:
(function() {
  var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
  $.getJSON( flickerAPI, {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  })
    .done(function( data ) {
      $.each( data.items, function( i, item ) {
        $( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
        if ( i === 3 ) {
          return false;
        }
      });
    });
})();

A: The same way that you have already got the line $scope.properties = data; to run after the JSON has been received. You put it in the callback function you pass to getJSON.

Why is the code not executing in the order that it is written?

It is.
getJSON(url, foo) means "Make an HTTP request to the url and set up an event handler to call foo when the response is received".
You seem to be expecting it to wait for the response before doing anything else. That would lock up the UI and be horrible.


text:
Q: Can I install Ubuntu touch on any tablet? I have found this procedure for installing Ubuntu touch:
http://www.pcadvisor.co.uk/how-to/linux/how-install-ubuntu-touch-image-3531970/
I don't see any reason why it wouldn't work with any device.

*

*Is it risky? Does it work? If not, why?

*Why is there no instruction on Ubuntu's website about how to install touch on a tablet?

*And more generally, is it or not possible to install Ubuntu touch on any device? If not, will it ever be?

A:
"Can I install Ubuntu touch on any tablet?"

No

"I don't see any reason why it wouldn't work with any device."

There are a myriad of reasons, like different screens, chips, RAM etc, the same reasons you must have Android built for that specific device, not just any old Android rom.

"Is it risky? Does it work? If not, why?"

Yes it is, there is the same risks as flashing anything, bootloop, brick etc... See answer above for the why.

"Why is there no instruction on Ubuntu's website about how to install
  touch on a tablet?"

There are

"And more generally, is it or not possible to install Ubuntu touch on
  any device? If not, will it ever be?"

It will never be possible to just install on any device, not all devices are created equally and compatibility is a big issue. More devices will get support in the future but never everything.
Although, if you have exceptional programming skills, you could in theory port it to any device but it would be a lot of work.
Info on porting touch to your device and currently supported devices, plus 3rd party roms on XDA.


text:
Q: "Re" resolve resources with angular ui router without reload I am using the following code to resolve a resource when the main state is loaded. Is it possible to re - resolve the resource without reloading the page? I am avoiding reload so that the user experience is not affected.
    $stateProvider
        .state('main', {
            url: '/',
            templateUrl: 'publicApp/main.html',
            controller: 'MainCtrl as mainCtrl',
            resolve: {
                userData: ["UserApi", function (UserApi) {
                    return UserApi.getUserData().$promise;
                }]
            }
        })

    .controller('MainCtrl', function (userData) {
        console.log(userData.something);
    })

Since is a public site, the user can visit any page without logging in but when the user logs in the page must customize based on the user data.
EDIT
I am using a modal for login so the state doesn't reload after logging in, I was thinking of throwing an event on $rootScope and then add listeners in controllers to load them again. But this doesn't look good, so I am looking for a better way
I currently have two options:

*

*Reload page - will effect the user experience, so its the last option

*Throw an event for the login modal and catch it in other controllers

Any better ideas?

A: Try using state reload once promise is resolved
$state.reload();


text:
Q: kile 2.1.2 in ubuntu 11.10
Possible Duplicate:
How can I fix a 404 Error using a PPA?

I read that kile was upgraded to version 2.1.2 which might have a live preview feature included. So I wanted to install it on ubuntu 11.10 but I don't seem to have much luck. I added the ppa for kile/stable but it doesn't work. This is what i get after sudo apt-get update:
W: Failed to fetch http://ppa.launchpad.net/kile/stable/ubuntu/dists/oneiric/main/source/Sources  404  Not Found

W: Failed to fetch http://ppa.launchpad.net/kile/stable/ubuntu/dists/oneiric/main/binary-amd64/Packages  404  Not Found

and a similar one for binary 386 I can't post because i am a new user and i can only have 2 hyper links.
Is there a way to install the newest version of kile in ubuntu 11.10? I would like to avoid installing ubuntu 12.04 since I had some bad experiences with this new version.
Cheers,
Lucian

A: There isn't an 11.10 PPA for Kile listed at that PPA, just 12.04, 11.04, 10.10, and 10.04. Not sure why they skipped 11.10. You could attempt adding the PPA for 11.04 or 12.04, but I'm unfamiliar with Kile so I don't know how well that work work or not.


text: Q: AASM state machine, can guards be skipped? Is it possible to skip a guard in some instances? Kind of like running some_event_without_validation! except you're not skipping object validation, but transitions guards.


text:
Q: After compiling PHP from source are the devel libraries still needed? After compiling PHP from source are the devel libraries still needed?
For example, I am building a newer version of PHP from source than is on our dev servers. I installed alot of [extension i.e. mysql, postgresql, curl, etc]-devel packages in order for the configure from the dev server setup to work. Do i still need these after php has compiled? For example could I make a distro and then distribute the PHP distro to another server without needing these devel dependencies?
I am a bit of a noob to this.

A: You don't need to ship the devel-libraries.
But my advice is to take some time and learn how the build system of your linux distribution works. And then build a new php package that can be installed by the package manager.
Take a look at how the "original" php packages were built for the distribution. Most likely you can simply copy and edit the existing rule file(s) and then make a new version of that package. This way you take advantage of the dependency mechanisms and the package manager will not remove/overwrite your version so easily when an update shows up in the "official" repositories.


text:
Q: How to Generate a LTPA token from the Application that has been deployed in Web Sphere Application Server I have a Spring Application, That authenticates the user name and password, And uses the JWT token for the SSO, I have deployed it in the Web Sphere Application Server, (**I have used the WAS 9 )I need the application to generate the LTPA token so that it can be used to authenticate the other application which is deployed in another web sphere application server, in the IBM Documentation, However the issues is. I am not aware where it needs to be added in the project. Or do I need to do anything needful. I have enabled the LTPA from the Security>> Global Security and enabled the SSO as well. I am aware that the generation is automated, But as the application needs to create the LTPA token for specific user. And it needs to be redirected to the URL of the other application, Which has the same domain name as well, The issue remains, What are the modification that I need to do in order for the application to generate the LTPA token and send it to the application that is deployed in other WAS server. And can I use the restapi for it. OR can be added in the URL, or use cookies.
Thank you in advance.


text:
Q: Would the adjectival form of "on the premises" be on-premise, on premise, or on-premises? I am familiar with the origin of the word premises as it relates to property, both land and structure (relayed here: Is "premises" always plural?). I want to know if there is an accpetable adjectival form.
So which of the following is most correct and which are acceptable?

*

*Virtual events are less effective than on-premise.

*Virtual events are less effective than on premise.

*Virtual events are less effective than on-premises.

(I know that reforming the sentence so that it doesn't use an adjective would likely be best, but what is the runner up?)

A: I wouldn't use premises at all, but the more customary onsite:

Virtual events are less effective than onsite.

But if you had to use premises, perhaps the least bad option would be:

Virtual events are less effective than on the premises.

A: "On premises" is based on a legal term meaning "on the premises" by which a party establishes ownership of real estate. Because of the longevity of real estate, different legal systems may have been in place during the time of ownership; thus "premises" may be used to argue who is the rightful owner. "On Premise" is incorrect.
"On premises" is a compound modifier - that is, multiple words acting together as an adjective. A decision to hyphenate, as in "on-premises", is a style decision. The hyphen makes it clear that "on" doesn't modify "premises", but rather that the two words are acting together to modify something else, such as "she installed the software on-premises." I'd suggest that either form is valid and that the key is to be consistent within any given body of work.

A: On-premise describes something that is on-topic or according to a statement; not "at a given location".  I agree with the others who say that onsite is the correct term, but the buzzword-happy crowd has jumped all over on-premise and run with it.  Even the dictionary says that the plural form is used to talk about land or buildings.


text:
Q: How can I CONCAT portions of three columns to one new column I am trying to create a new column in my results that is made up on the first 3 characters of "PrimaryName", all of "VendorCity", and the first 5 characters of "VendorZip"
SELECT,VendorName
      ,replace(PrimaryVendorLocationName,' ','') as PrimaryName
      ,replace(PrimaryVendorLocationCity,' ','') as VendorCity
      ,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
FROM [table]

As you can see I also need to remove spaces to ensure a cleaner return. I would like to call the new column "NewVendorCode". So a record that originates like this:

R A Slack
Chicago Heights
60654-1234

Will return this:

RASChicagoHeights60654

A: You can use the following, using LEFT (MySQL / TSQL):
SELECT CONCAT(
    LEFT(REPLACE(PrimaryVendorLocationName, ' ', ''), 3),
    REPLACE(PrimaryVendorLocationCity, ' ', ''),
    LEFT(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 5)
) FROM table_name

... or you can use SUBSTRING (MySQL / TSQL) (instead of LEFT):
SELECT CONCAT(
    SUBSTRING(REPLACE(PrimaryVendorLocationName, ' ', ''), 1, 3),
    REPLACE(PrimaryVendorLocationCity, ' ', ''),
    SUBSTRING(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 1, 5)
) FROM table_name

Note: As you can see the SELECT querys work on MySQL and TSQL without change.

demo (MySQL): https://www.db-fiddle.com/f/wTuKzosFgkEuKXtruCTCxg/0
demo (TSQL): http://sqlfiddle.com/#!18/dbc98/1/1

A: You can use the following code:
  SELECT VendorName+
  replace(PrimaryVendorLocationName,' ','') +
  replace(PrimaryVendorLocationCity,' ','') +
  replace(PrimaryVendorLocationZipCode,' ','') as NewVendorCode

A: SELECT VendorName
  ,PrimaryName
  ,VendorCity
  ,VendorZip
  ,CONCAT(LEFT(PrimaryName,3),VendorCity,LEFT(VendorZip,5)) As NewVendorCode
FROM (
     SELECT VendorName
       ,replace(PrimaryVendorLocationName,' ','') as PrimaryName
       ,replace(PrimaryVendorLocationCity,' ','') as VendorCity
       ,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
     FROM [table]
)


text:
Q: Angular CLI Generate Library with SASS I have an Angular6 app that I am trying to create a library for. I was able to generate a library project but when I generate the component for the library, Angular CLI is creating it with .css files.
How can I get it to create .scss files?
Here are the commands I'm using to create the project:
ng new example-app --style=scss
rename example-app example
cd example
ng generate library example --prefix=exam --style=scss
ng generate component test --project=example

The --style=scss option on the ng generate library command does not have an effect, I still get CSS files in my test component folder.

A: You can fix it by overriding schematics for your project in your angular.json like in the example below:
"example": {
    "root": "projects/example",
    "sourceRoot": "projects/example/src",
    "projectType": "library",
    "prefix": "exam",
    "schematics": {
      "@schematics/angular:component": {
        "styleext": "scss"
      }
    },
 ....
}

or you can set this value via angular-cli like so:
ng config schematics.@schematics/angular:component.styleext scss

After that try to generate component, it should have scss extension.
EDIT (replace styleExt with style):
As per this closed ticket https://github.com/ngrx/platform/issues/2248 with new version of Angular CLI styleExt has been replaced with style - I tested it in two libraries that are using Angular anf Angular CLI versions 8.


text:
Q: django and ajax without jquery I am trying to submit a form using ajax to django view but without jquery, and i am not able to get through few things.

*

*I am unable to send formData to django via ajax

*Also unable to check if the request is made via ajax or not (request.is_ajax())

I am using core Javascript for this functionality so any help will be appreciated.
Views.py
def register(request):
if request.method == "POST":
    form = RegisterForm(request.POST)
    if form.is_valid():
        if request.is_ajax():
            # form is submited via ajax
        else:
            # error submitting the form via ajax
    else:
        return JsonResponse({'error':'There was an error'})
else:
    form = RegisterForm()
context = {
    'form' : form
}
return render(request, 'users/register.html', context)

AJAX
function _(e){
    return document.getElementById(e);
};

function getCookie(name){
    var cookieValue = null;

    if(document.cookie){
        var cookies = document.cookie.split(';');
        for(var i = 0; i < cookies.length; i++){
            cookie = cookies[i].trim();
            if(cookie.substring(0, name.length + 1) == (name + '=')){
                cookieValue = decodeURIComponent(cookie.substring(name.length+1));
                break;
            };
        };
    };
    return cookieValue;
};

var btn = _('formBtn');

btn.addEventListener('click', function(e){
     e.preventDefault();

    var ajax = new XMLHttpRequest();
    var fname = _('id_first_name').value;
    var lname = _('id_last_name').value;
    var email = _('id_email').value;
    var password = _('id_password').value;
    var csrfCookie = getCookie('csrftoken');

    // formData not working

    ajax.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200){
            console.log(this.responseText);
        }
    };

    ajax.open('POST', '/users/registerAjax/', true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("X-CSRFToken", csrfCookie);
    ajax.send(encodeURI('first_name='+fname+'&last_name='+lname+'&email='+email+'&password='+password));

})


text:
Q: Binding to ChoiceList Display Name in Lightswitch with Telerik Grid I have swapped the core Lightswitch 2011 data grid control with the latest Telerik Silverlight RadGridView control.
As per their tutorials, I bind the grid columns as per normal.
However, in the core Lightswitch datagrid, if you bind to a string field that is a ChoiceList (e.g. Project Status - Value = 1, DisplayName = "In Progress") then it automatically shows the Display NAme (e.g. "IN Progress").
But in the Telerik RadGridView it shows the VALUE, not the DisplayName (e.g. 1 in the example above).
Here is the DataMemberBinding expression I use in the XAML customer control:
I assume the core Lightswitch DataGrid is getting it from the query somehow - I assumed it would be something like
Binding ProjectStatus.DisplayName but this does not work... (See screenshot)

        <telerik:GridViewDataColumn  ShowColumnWhenGrouped="False"
                                     Width="SizeToHeader"
                                     CellStyle="{StaticResource FormLabelValueTextStyle}"
                                     DataMemberBinding="{Binding ProjectStatus}">
            <telerik:GridViewDataColumn.Header>
                <TextBlock Style="{StaticResource HeaderCellTextBlockStyle}"
                           Text="Project Status" />
            </telerik:GridViewDataColumn.Header>
        </telerik:GridViewDataColumn>

    </telerik:RadGridView.Columns>
</Controls:RadGridView>

A: Choice Lists are a LightSwitch concept, they're stored in the lsml file (one of the reasons I don't use them), so I'm not surprised that it's not available if you're using a non-LS datagrid.
The way around this would be to use an actual lookup table instead of the choice list. Then you'd be able to bind to the entity's properties.


text:
Q: I'm looking for a way to measure single events on energy use time series I'm a noob to the group and am after statistical advice.  Any interest would be really great.  I expect to use R for analysis and have already read the below page which demonstrates correlations for energy use against NOAA temperatures.  I suspect my problem is going to be harder to analyse.
I will run an experiment later this year.  After that:
I should have six months of half hourly readings of home energy use for 30 homes (6 controls).  These are kWh smart meter floating point values.  At specific times during the sample (such as every few days), the treatment home occupants will get an informational stimulus which may affect their electricity consumption.  Perhaps this effect happens soon after the event (such as minutes) but it may be days.  The effect should be a drop in energy consumption, maybe sustained, perhaps not.
The below R example is for NOAA weather data as it correlates to energy use.  The writer finds strong correlations and I suppose this is a much easier correlation to hunt for.  I need to say that certain quasi regular interventions had some sort of signature in the energy use time series.  I suspect I already need weather series (and control series) to help in pre-processing the data.
https://www.r-bloggers.com/modeling-residential-electricity-usage-with-r/
Any advice about directions or things to try would be very gratefully received.
Cheers
Craig


text:
Q: Lie algebra of the automorphism group of an arbitrary Lie Algebra? I'm trying to prove the Lie algebra of $Aut(\mathfrak{g})$ is $Der(\mathfrak{g})$, the set of all derivations over $\mathfrak{g}$. Where $\mathfrak{g}$ is an arbitrary finite lie algebra.
Due to $\mathfrak{g}$ is finite Lie algebra, I am using that $Lie(Aut(\mathfrak{g}))=\{X \in M(n, \mathbb{C}) / e^{tX}\in Aut(\mathfrak{g})\}$.
How can I prove if $\delta \in Der(\mathfrak{g})$ then $e^{t\delta}([X,Y])=[e^{t\delta}(X),e^{t\delta}(Y)]$?
And if $\delta \in Lie(Aut(\mathfrak{g}))$ then $\delta \in Der(\mathfrak{g})$?

A: Let $\varphi(t)$ be a smooth path of automorphisms with $\varphi(0)=\mathrm{id}$. Then for $X,Y\in\mathfrak g$ you've got:
$$0=\frac d{dt}[X,Y]\lvert_{t=0}= \frac d{dt}[\varphi(t) X,\varphi(t)Y]\lvert_{t=0}=[\varphi'(0)X, Y]+[X,\varphi'(0)Y]$$
and $\varphi'(0)$ is a derivation. Hence the elements of Lie algebra of the automorphism group are derivations.
And the other direction? Let $\delta$ be a derivation, then:
$$[\delta^n X,\delta^m Y]= (-1)^m[\delta^{n+m}X,Y]$$
and
$$[\sum_n\frac{(t\delta)^n}{n!}X, \sum_m \frac{(t\delta)^m}{m!}Y]=\sum_{n,m}\frac{(-1)^mt^{n+m}}{n!\,m!}[\delta^{n+m}X,Y]$$
do a substitution of the sums, let $k=n+m$ and multiply by $\frac{k!}{k!}$ and $1^{k-m}$. Then the sum becomes:
$$\sum_k\frac{t^k}{k!}\sum_{m≤k}\frac{(-1)^m 1^{k-m}k!}{m!\,(k-m)!} [\delta^{k}X,Y] = \sum_k \frac{t^k}{k!}\sum_{m≤k}(1+(-1))^k[\delta^kX,Y]$$
Now only the $k=0$ term survives, so you are left with $[X,Y]$.


text:
Q: How to import the Mysql database using Java I need to import my database using Java. I am using Wamp and SQL version 5.7.19. I am trying to get the backup of my database when a user clicks on the export button and save the .sql file to the path selected by the user. Can Somebody Tell me what is the issue
   JFileChooser fc = new JFileChooser();
   fc.showOpenDialog(this);
   String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

    try {
        File f = fc.getSelectedFile();
        path = f.getAbsolutePath();
        path = path.replace('\\', '/');
        path = path+"_"+date+ ".sql";
        jTextField2.setText(path);

    } catch (Exception e) {
        e.printStackTrace();
    }
    Process p = null;
    try {

        Runtime runtime = Runtime.getRuntime();
        p = runtime.exec("c:/wamp64/bin/mysql/mysql5.7.19/bin/mysqldump -u root - proot --add-drop-database -B dbName -r "
                    + jTextField2.getText() + path + ".sql");

        int processComplete = p.waitFor();

        if (processComplete == 0) {
            JOptionPane.showMessageDialog(this, "Backup created successfully");
        } else {
            JOptionPane.showMessageDialog(this, "Could not create the backup   !!!");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

A: I haven't tested, but I think your problem is here:
                + jTextField2.getText() + path + ".sql");

As I read the code, the text field contains the path, and and the path variable too, so you get it twice in the command string. You also got ".sql" three times in total since you've already appended it to path before filling it into the text field. I suggest just:
                + path);


text:
Q: How to get sum from joined table B with multiple results againts one row in table A? I'm developing a software that show's users spareparts searched with various different criteria.
Spareparts are in one table (actually a flat BOM-structure) and stock quantities in another. Stock quantities are a bit problematic since there can be 0 to 5 different locations (rows) for 1 sparepart and different amount in every location (row). This means that the total stock quantity must be SUMmed from all different locations (rows).
Let it be that spareparts are in table spareparts and stock quantities in stockQ. Join is made by ITEMID that is the sparepart key in both tables.
How do I achieve this? Usually one query results in 50 to 500 spareparts. I would not want to make a stock quantity check for each part one at a time.
EDIT: Fixed false tagging, replaced mysql with oracle.

A: If i correctly understood, you want the total quantity and not the different locations'quantity. You could achieve this joining with the summed quantity in stockq.
I'm not sure about mysql sintax but this query should do the job
select *
from spareparts S
join (select ITEMID, sum(quantity) as quantity from stockQ group by ITEMID) as Q
on S.ITEMID = Q.ITEMID


text:
Q: Why isn't this reflecting in the front-end? <a href="?page=gmgt_workouttype&tab=workouttypelist" class="nav-tab <?php echo $active_tab == 'workouttypelist' ? 'nav-tab-active' : ''; ?>">
                        <?php echo ' '.__('Workout Log', 'gym_mgt'); ?>

Now, I want to change the Workout Log to Logs.
However, this isn't reflecting in front-end.

A: Please clear the browser cache and refresh.


text:
Q: how to make the result from result_lbl from window 1 to window 2? How would I access the output from result_lbl of window 1 to window 2? I had being reading and seems that I need to use "controller" somewhere to link the 2 classes together, but it seems like with "controller" there needs to be a lambda function somewhere, which I thought was a no no. Would someone please help me out.  Thanks.
import tkinter as t

def main():
    root = t.Tk()
    root.geometry("250x370")
    root.config(background="LightBlue4")
    root.title("print to screen")
    app = Application(root)
    root.mainloop()

class Application:
    def __init__(self,parent):
        self.parent=parent

        self.frame_top = t.Frame(self.parent, bg="tan", bd=2,      relief=t.RIDGE)
        self.frame_top.pack(anchor=t.N, fill=t.BOTH, expand=1)

        self.frame_btm = t.Frame(self.parent, bg="plum1", bd=2, relief=t.RIDGE)
        self.frame_btm.pack(anchor=t.S, fill=t.X, expand=0)

----------------------------------------------------------------
        self.labelVariable=t.StringVar()
        self.result_lbl=t.Label(self.frame_top,   font="Helvetica 50 bold italic", textvariable=self.labelVariable)
        self.result_lbl.pack()

        self.entryVariable = t.StringVar()
        self.entry=t.Entry(self.frame_btm, textvariable=self.entryVariable)
        self.entry.bind("<Return>", self.on_button)
        self.entry.pack()

        self.button = t.Button(self.frame_btm, text="print to screen", command=self.on_button)
        self.button.pack()

        self.button_window=t.Button(self.frame_btm, text="2nd", fg="brown",command=self.second_window)
        self.button_window.pack()

---------------------------------------------
    def on_button(self):
        self.labelVariable.set(self.entryVariable.get())
        self.entry.delete(0,"end")

    def second_window(self):
        self.second_window = t.Toplevel(self.parent)
        self.second_window.geometry("250x370")
        self.second_window.title("2nd window")
        self.app = Window_2(self.second_window)

class Window_2:
    def __init__(self, parent):
        self.parent = parent

        self.frame= t.Frame(self.parent, bg="tan", bd=2, relief=t.RIDGE)
        self.frame.pack(anchor=t.N, fill=t.BOTH, expand=1)

if __name__ == '__main__':
    main()

A: There are few things I would like to comment about your program, however, I am going to mention only the things directly related to your actual problem.
Redesign your program and code less
Better design means less code. On the name of this development verse, your second class:
class Window_2:
    def __init__(self, parent):
        self.parent = parent

        self.frame= t.Frame(self.parent, bg="tan", bd=2, relief=t.RIDGE)
        self.frame.pack(anchor=t.N, fill=t.BOTH, expand=1)

is completely useless regarding the goal you want to achieve. All what you would implement in this class, you could do it in self.second_window frame which you created using  Toplevel().
So just take the configuration of Window_2 class and inject it into self.second_window toplevel frame. This way you move and keep the design of the first into the later.
self.second_window = t.Toplevel(self.parent, bg = 'tan', bd=2,  relief=t.RIDGE)

Also, for the sake of code maintenance and scalability,  I would like to suggest you to rename the variable self.second_window in self.second_window() method to something else, let's say to self.second_win. As your code goes longer, this may be a source of confusion or eventually bugs not only for your peers who would work on your code but also for yourself.
Program re-design benefits
You may guess that the re-design we did above has a direct positive impact to resolve your problem. This is because your second frame (or window as you call it) self.second_window() looks now just like a simple method that can now access simply any member of Application() class, namely self.result_lbl. This way, your problem is already almost solved.
The trick
The trick to complete the solution of your problem is now to create an other label within what you call the second window, let's call it self.result_lbl_copy that we need to show in self.second_wind then we must set its text to the same text as in self.result_lbl using cget() method.
Which thing is reflected in our code by:
self.result_lbl_copy=t.Label(self.second_win,   font="Helvetica 50 bold italic", textvariable=self.labelVariable, text = self.result_lbl.cget('text'))
self.result_lbl_copy.pack()

Full program
Here is the program you can test:
'''
Created on Apr 21, 2016

@author: billal begueradj
'''
import tkinter as t

def main():
    root = t.Tk()
    root.geometry("250x370")
    root.config(background="LightBlue4")
    root.title("print to screen")
    app = Application(root)
    root.mainloop()

class Application:
    def __init__(self,parent):
        self.parent=parent

        self.frame_top = t.Frame(self.parent, bg="tan", bd=2,      relief=t.RIDGE)
        self.frame_top.pack(anchor=t.N, fill=t.BOTH, expand=1)

        self.frame_btm = t.Frame(self.parent, bg="plum1", bd=2, relief=t.RIDGE)
        self.frame_btm.pack(anchor=t.S, fill=t.X, expand=0)
        self.labelVariable=t.StringVar()
        self.result_lbl=t.Label(self.frame_top,   font="Helvetica 50 bold italic", textvariable=self.labelVariable)
        self.result_lbl.pack()

        self.entryVariable = t.StringVar()
        self.entry=t.Entry(self.frame_btm, textvariable=self.entryVariable)
        self.entry.bind("<Return>", self.on_button)
        self.entry.pack()

        self.button = t.Button(self.frame_btm, text="print to screen", command=self.on_button)
        self.button.pack()

        self.button_window=t.Button(self.frame_btm, text="2nd", fg="brown",command=self.second_window)
        self.button_window.pack()

    def on_button(self):
            self.labelVariable.set(self.entryVariable.get())
            self.entry.delete(0,"end")

    def second_window(self):
            self.second_win = t.Toplevel(self.parent, bg = 'tan', bd=2,  relief=t.RIDGE)
            self.second_win.geometry("250x370")
            self.second_win.title("2nd window")
            self.result_lbl_copy=t.Label(self.second_win,   font="Helvetica 50 bold italic", textvariable=self.labelVariable, text = self.result_lbl.cget('text'))
            self.result_lbl_copy.pack()

if __name__ == '__main__':
    main()

Demo
Here is a screenshot of the running program:

EDIT:
Solution while keeping the bad design
If you want to keep the previous bad design by using Window_2() class anyway then the solution does not change that much.
Just before this line:
self.app = Window_2(self.second_window)

Insert the same two lines I mentioned above for the trick:
self.result_lbl_copy=t.Label(self.second_window,   font="Helvetica 50 bold italic", textvariable=self.labelVariable, text = self.result_lbl.cget('text'))
self.result_lbl_copy.pack()

Full program
Here is the full program with your own design:
'''
Created on Apr 22, 2016

@author: billal begueradj
'''

import tkinter as t

def main():
    root = t.Tk()
    root.geometry("250x370")
    root.config(background="LightBlue4")
    root.title("print to screen")
    app = Application(root)
    root.mainloop()

class Application:
    def __init__(self,parent):
        self.parent=parent

        self.frame_top = t.Frame(self.parent, bg="tan", bd=2,      relief=t.RIDGE)
        self.frame_top.pack(anchor=t.N, fill=t.BOTH, expand=1)

        self.frame_btm = t.Frame(self.parent, bg="plum1", bd=2, relief=t.RIDGE)
        self.frame_btm.pack(anchor=t.S, fill=t.X, expand=0)
        self.labelVariable=t.StringVar()
        self.result_lbl=t.Label(self.frame_top,   font="Helvetica 50 bold italic", textvariable=self.labelVariable)
        self.result_lbl.pack()

        self.entryVariable = t.StringVar()
        self.entry=t.Entry(self.frame_btm, textvariable=self.entryVariable)
        self.entry.bind("<Return>", self.on_button)
        self.entry.pack()

        self.button = t.Button(self.frame_btm, text="print to screen", command=self.on_button)
        self.button.pack()

        self.button_window=t.Button(self.frame_btm, text="2nd", fg="brown",command=self.second_window)
        self.button_window.pack()
    def on_button(self):
           self.labelVariable.set(self.entryVariable.get())
           self.entry.delete(0,"end")

    def second_window(self):
           self.second_window = t.Toplevel(self.parent)
           self.second_window.geometry("250x370")
           self.second_window.title("2nd window")
           self.result_lbl_copy=t.Label(self.second_window,   font="Helvetica 50 bold italic", textvariable=self.labelVariable, text = self.result_lbl.cget('text'))
           self.result_lbl_copy.pack()
           self.app = Window_2(self.second_window)

class Window_2:
    def __init__(self, parent):
        self.parent = parent

        self.frame= t.Frame(self.parent, bg="tan", bd=2, relief=t.RIDGE)
        self.frame.pack(anchor=t.N, fill=t.BOTH, expand=1)

if __name__ == '__main__':
    main()

I tested this program and it leads to the same interface. You can choose between the two solutions, however I recommend you the first one for reasons I mentioned.
About  on_button() method
I want to prevent you from an error that you did not ask but which I discovered in your program: There is a problem with this function:
def on_button(self):
       self.labelVariable.set(self.entryVariable.get())
       self.entry.delete(0,"end")

Change its definition to:
 def on_button(self,something):

something is just an argument which you can call with any name such as begueradj. If you don't understand why, let me know. But first execute your program by running Enter


text:
Q: Centering Image Container between two sections I have been trying to center an image container between a div and a section. However, when I manipulate the box's margins or the figure, the size of the box changes along with the position of the image container. I want the image container to lie between the section and the box.

<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@6.5.95/css/materialdesignicons.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@6.5.95/css/materialdesignicons.min.css" />
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500;600;700&display=swap" rel="stylesheet">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

            <button class="button is-primary is-small navbar-end" style="font-family: Montserrat; font-size: bold; color: #FFFFFF; background-color: #53C0B3; border-radius: 5%;">
                            Language
                        </button>
            <button class="button is-primary is-small navbar-end" style="font-family: Montserrat; font-size: bold; color: #FFFFFF; background-color: #53C0B3; border-radius: 5%;">
                            Profile
                        </button>

A: Try this approach.
Place absolute positioned circle image inside your relative positioned navbar. Now give bottom: 0 to circle to make sure it remains at the bottom of the nav irrespective of what is its dimensions.
Now give translateY(50%) to move the circle 50% below its height while respecting the bottom: 0. This will make sure that the circle remains at its position.
Implementation:

*{box-sizing: border-box;margin:0;padding:0}

nav{
  position: relative;
  padding-block: 3rem;
  background-color: lightgrey;
}

.circle{
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, 50%);

  width: 8rem;
  aspect-ratio: 1;
  border-radius: 50%;

  background-color: seagreen;
}

A: You should give the image an absolute position while giving the main dive relative position and a certain height where your image is located. In addition, you can add the features you want by giving the left, right and bottom properties to center. I created it as you requested below. I hope it works for you.

<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@6.5.95/css/materialdesignicons.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@6.5.95/css/materialdesignicons.min.css" />
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500;600;700&display=swap" rel="stylesheet">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

            <button class="button is-primary is-small navbar-end" style="font-family: Montserrat; font-size: bold; color: #FFFFFF; background-color: #53C0B3; border-radius: 5%;">
                            Language
                        </button>
            <button class="button is-primary is-small navbar-end" style="font-family: Montserrat; font-size: bold; color: #FFFFFF; background-color: #53C0B3; border-radius: 5%;">
                            Profile
                        </button>

    Hi everyone


text:
Q: Django how to display ratings as stars? I'm building a rating system for my website that is currently working with numbers. What I want is really simple :
1) In a template, displaying a mean rating as stars instead of as a number (I need to have partials stars, for example 4.3/5 would be rendered as 4 stars and a 1/3 star).
2) In a form, being able to click on stars to record a rating instead of entering a number.
For that purpose, I have installed django star-ratings. The problem is that there are no documentation available about how to actually use these app. I only want to be able to modify my templates to display numbers as stars and to record stars as numbers but I can't figure out how to do that. That seems so simple but I found nothing on the official documentation nor on internet.
Can someone familiar with this app help me ? Or is there a better way to proceed than using star-ratings ?
Thanks in advance !


text:
Q: Purrr functional programming error when hitting blank values Im sorry if this is a brainf*rt question - its probably a simple error handling. This code breaks when one of the variables hits a blank (in this case in the 'num_views' variable) - Is there a way to return an 'NA' for any blank values? I would be so grateful for any advice
The error response is:
Error: All columns in a tibble must be vectors.
Column num_views is a function.
# Custom functions
parse_listing <- function(listing){

  # Review content
  address <- listings %>% html_nodes(xpath = '//p[@data-testid="listing-description"]') %>% html_text2()
  link <- listings %>% html_nodes(xpath = '//div[@data-testid="search-result"]/div/div/a[2]') %>% html_attr('href') %>% paste("https://www.zoopla.co.uk", ., sep="")
  prop_type <- listings %>% html_nodes(xpath = '//h2[@data-testid="listing-title"]') %>% html_text2()
  price <- listings %>% html_nodes(xpath = '//div[@data-testid="listing-price"]/p[@size="6"]') %>% html_text2() %>% str_remove_all("[£,]")
  est_agent <- listings %>% html_nodes(xpath = '//div[@data-testid="search-result"]//a/img') %>% html_attr('alt') %>% str_remove('Marketed by ')
  date_listed <- listings %>% html_nodes(xpath = '//span[@data-testid="date-published"]') %>% html_text2() %>% str_remove('Listed on ')  %>% dmy()
  num_views <- possibly(listings %>% html_nodes(xpath = '//span[@data-testid="number-of-views"]') %>% html_text2() %>% str_remove(' views'), otherwise = NULL)

  tibble(address, link, prop_type, price, est_agent, date_listed, num_views)
}

# Script
link <- 'https://www.zoopla.co.uk/for-sale/property/wd3/?page_size=25&q=wd3&radius=0&results_sort=most_popular&search_source=refine&pn=7'
page <- read_html(link)
listings <- page %>% html_nodes(xpath = '//div[@data-testid="search-result"]')

wd3p7 <- map_dfr(listings, parse_listing)

A: Wrap with a tryCatch or possibly/safely (from purrr) to return the desired value when there is an error
library(purrr)
library(rvest)
library(dplyr)
library(lubridate)
 parse_listing <- function(listing){

    # Review content
    address <- possibly(function(x)  {
                   x %>%
                    html_nodes(xpath = '//p[@data-testid="listing-description"]') %>%
                      html_text2()
              }, otherwise = NA_character_)(listing)

   link <- possibly(function(x) {
        x %>%
          html_nodes(xpath = '//div[@data-testid="search-result"]/div/div/a[2]') %>%
           html_attr('href') %>%
           paste("https://www.zoopla.co.uk", ., sep="")
           }, otherwise = NA_character_)(listing)

   prop_type <- possibly(function(x) {
        x %>%
         html_nodes(xpath = '//h2[@data-testid="listing-title"]') %>%
         html_text2()
         }, otherwise = NA_character_)(listing)

   price <- possibly(function(x) {
     x %>%
      html_nodes(xpath = '//div[@data-testid="listing-price"]/p[@size="6"]') %>%
       html_text2() %>%
       str_remove_all("[£,]")
        }, otherwise = NA_character_)(listing)
   est_agent <- possibly(function(x) {
    x %>%
     html_nodes(xpath = '//div[@data-testid="search-result"]//a/img') %>%
      html_attr('alt') %>%
      str_remove('Marketed by ')
      }, otherwise = NA_character_)(listing)
   date_listed <- possibly(function(x) {
      x %>%
       html_nodes(xpath = '//span[@data-testid="date-published"]') %>%
       html_text2() %>%
       str_remove('Listed on ')  %>%
       dmy()
         }, otherwise = NA_character_)(listing)
   num_views <- possibly(function(x) {
      x %>%
       html_nodes(xpath = '//span[@data-testid="number-of-views"]') %>%
       html_text2() %>%
       str_remove(' views')
       }, otherwise = NA_character_)(listing)
   type.convert(as_tibble(do.call(qpcR:::cbind.na, dplyr::lst(address, link, prop_type, price, est_agent, date_listed, num_views))), as.is = TRUE)

    }

-testing
link <- 'https://www.zoopla.co.uk/for-sale/property/wd3/?page_size=25&q=wd3&radius=0&results_sort=most_popular&search_source=refine&pn=7'
page <- read_html(link)
listings <- page %>% html_nodes(xpath = '//div[@data-testid="search-result"]')
 wd3p7 <- map_dfr(setNames(listings, listings), parse_listing, .id = "listing")

-output
> wd3p7
# A tibble: 625 × 8
   listing                                         address               link                prop_type     price est_agent        date_listed num_views
   <chr>                                           <chr>                 <chr>               <chr>         <int> <chr>                  <int>     <int>
 1 "<div data-testid=\"search-result\" class=\"ea… High Street, Rickman… https://www.zoopla… 2 bed flat … 400000 Gibbs Gillespie…       19039        40
 2 "<div data-testid=\"search-result\" class=\"ea… High Street, Rickman… https://www.zoopla… 1 bed prope… 315000 Trend & Thomas,…       19033        34
 3 "<div data-testid=\"search-result\" class=\"ea… Springwell Lane, Ric… https://www.zoopla… 2 bed flat … 375000 Purplebricks, H…       19044        32
 4 "<div data-testid=\"search-result\" class=\"ea… Rectory Road, Rickma… https://www.zoopla… 1 bed flat … 315000 Trend & Thomas,…       18897        30
 5 "<div data-testid=\"search-result\" class=\"ea… Penn House, 30 High … https://www.zoopla… Studio for … 270000 Gibbs Gillespie…       18982        25
 6 "<div data-testid=\"search-result\" class=\"ea… The Forge, Bury Lane… https://www.zoopla… 2 bed flat … 425000 Robsons, WD3           19005        25
 7 "<div data-testid=\"search-result\" class=\"ea… High Street, Rickman… https://www.zoopla… 1 bed prope… 299950 Trend & Thomas,…       18792        26
 8 "<div data-testid=\"search-result\" class=\"ea… The Forge, Bury Lane… https://www.zoopla… 2 bed flat … 450000 Savills - Rickm…       18960        19
 9 "<div data-testid=\"search-result\" class=\"ea… Homestead Road, Rick… https://www.zoopla… 1 bed flat … 279000 Trend & Thomas,…       18654        18
10 "<div data-testid=\"search-result\" class=\"ea… High Street, Rickman… https://www.zoopla… 1 bed flat … 270000 Trend & Thomas,…       18463        18
# … with 615 more rows


text:
Q: control volumes of multiple independent sound sources In linux, how would one have multiple sound sources, which volumes can be controlled independently. For instance you'd have two youtube videos running, and each one would be controlled by something like alsamixer:
amixer set X 20%
amixer set Y 60%;

The sound of both should then just be merged. Is there a low level solution to this?


text:
Q: How to run a Windows batch process in background, but kill it if the command prompt is closed? On Linux, I could do this just doing:
myprogram &

However on Windows... If I start a command like:
start /B myprogram.exe

It runs in the background, but if I close my command prompt, the myprogram.exe is not killed. How to make it be killed automatically when the command prompt is closed?
Related question:

*

*Windows - Run process on background after closing cmd


text:
Q: What does offending class tell me on server startup? I'm having the jee7 web api as dependency. I can start my app on tomcat application successfully, but what does the following "offending class" statements tell me? Do I have to take any actions?
Jan 13, 2014 5:47:47 PM org.apache.catalina.loader.WebappClassLoader validateJarFile
Information: validateJarFile(C:\Users\me\Servers\apache-tomcat-7.0.50\wtpwebapps\app\WEB-INF\lib\el-api-2.2.jar) - jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/el/Expression.class
Jan 13, 2014 5:47:47 PM org.apache.catalina.loader.WebappClassLoader validateJarFile
Information: validateJarFile(C:\Users\me\Servers\apache-tomcat-7.0.50\wtpwebapps\app\WEB-INF\lib\javaee-web-api-7.0.jar) - jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/servlet/Servlet.class

pom.xml
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
    </dependency>

A: I have faced the same issue during a project using Eclipse.
Doing below things resolved the issue

*

*Added javax.*.jar to the build path

*Removed the project - gave clean build and add the project and finally published....!!

Bingo...!!
This resolved my issue. Hope this helps.
Thanks,
mskr.

A: It seems like you (your Servlet container) are trying to load some classes that have already been loaded. The servlet-api and el-api should be provided by the Servlet container.
Change your pom.xml to account for that
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>

A: This is a very common problem for developers who are using Maven as a build tool. when , we include the servlet-api as a project dependency i.e pom.xml like this :
<dependency>
<groupId>  javax.servlet</groupId>

<artifactId>servlet-api</artifactId>
<version>2.5</version>

add scope as provided in the above dependency as following .
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>

A: I fixed this by using the correct Servlet API version: Tomcat 7.x expects version 3.0.x, not the 3.1.x I'd tried using.


text:
Q: EDIT (judge harshly): My display() method won't display and I'm not sure why I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.
The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.
I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.
My constructor looks like this:
==================================================
 public class Salesperson
   {
   private String salesName;
   private int salesID;
   private double annualSales;

   public Salesperson(String salesName, int salesIDNum, double yearlySales)
   {
       this.salesName = salesName;
       salesID = salesIDNum;
       annualSales = yearlySales;
   }

   public String getSalesName()
   {
       return salesName;
   }
   public void setSalesName(String salesName)
   {
       this.salesName = salesName;
   }
   public double getSalesID()
   {
       return salesID;
   }
   public void setSalesID(int salesIDNum)
   {
       salesID = salesIDNum;
   }
   public double getAnnualSales()
   {
       return annualSales;
   }
   public void setAnnualSales(double yearlySales)
   {
       annualSales = yearlySales;
   }
   @Override
   public String toString()
   {
       return String.format("%s-%-10s%-10.2f", salesName,
                salesID, annualSales);
    }

       }
And my code for application looks like this:

    import java.util.Arrays;
    import java.util.Scanner;
     public class CreateSalesperson
     {
       private static final Scanner USER_INPUT = new Scanner(System.in);
       private static final int UPPER_SIZE_LIMIT = 20;
       private static final int LOWER_SIZE_LIMIT = 0;
       private static Salesperson[] salesStaffInDatabase = new
      Salesperson[20];
       private static int numOfSalesPpl = 0;
       private static boolean loop = true;
       public static void main(String[] args)
      {
       String selection;
       selection = programMenu();
       String response;

            while(loop)
              switch(selection)
              {
                  case "A":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                  case "a":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                    case "C":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "c":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "E":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                    case "e":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                }
                }

      public static void changeRecord()
        {
            String idNum;
            String salesName;
            double salesAmount;
            String response;

            System.out.print("Enter Sales ID: ");
            idNum = USER_INPUT.nextLine();
            if(isValidID(idNum))

            {
            int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
            System.out.println(salesStaffInDatabase[searchResult]);
            }
            else
            {
                System.out.println("Invalid Sales ID");
            }
        }
     public static boolean isValidID(String idNum)
     {
     boolean isValid= false;
     for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
     {
         if(salesStaffInDatabase[val].equals(idNum))
                 {
                   isValid = true;
                 }
     }
     return isValid;
     }
     public static void addRecord()
     {
        int idNum;
        String salesName;
        double salesAmount;
        String idNo;
        String response;

       do
       {
        System.out.print("Please enter sales ID: ");
        idNum = USER_INPUT.nextInt();
        idNo = Integer.toString(idNum);
        if(idNo.length() != 8)

           System.out.println("Sales ID must be 8 digits long: ");

       }
       while(idNo.length() < 8 || idNo.length() > 8);

        System.out.print("Name: ");
        salesName = USER_INPUT.nextLine();
        USER_INPUT.nextLine();
        System.out.print("Sales Amount: ");
        salesAmount = Double.parseDouble(USER_INPUT.nextLine());
        salesStaffInDatabase[numOfSalesPpl] = new
     Salesperson(salesName,idNum,salesAmount);

        salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
        salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
        salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);

        System.out.print("Do you want to display database Y/N?: ");
        response = USER_INPUT.nextLine();
        while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
        {
          displayDatabase();
        }
    }

    public static void displayDatabase()
    {

        for(int val=0;val < numOfSalesPpl; val++)
        {
              System.out.println(salesStaffInDatabase[val]);
        }

    }
    public static String programMenu()
    {
    String selection;
     do
        {

         System.out.println("(A)dd a Record");
         System.out.println("(C)hange a Record");
         System.out.println("(E)xit Database");
         System.out.print("Enter selection: ");
         selection = USER_INPUT.nextLine();
        }
        while(!selection.equalsIgnoreCase("a") &&
    !selection.equalsIgnoreCase("c")
        && !selection.equalsIgnoreCase("e"));
        return selection;
    }
    }

=================================================================

A: edit the toString()method in Salesperson class :
      @Override
public String toString() {
    return "Salesperson{" +
            "salesFirstName='" + salesFirstName + '\'' +
            ", salesLastName='" + salesLastName + '\'' +
            ", salesID='" + salesID + '\'' +
            ", annualSales=" + String.format("%-10.2f",  annualSales)+
            '}';
}

A: In Java, whenever you want to display an object as string, you must override the toString() method.
The code that you posted, the Salesperson's toString() method returns only the salesID and anualSales. If you want to display another attribute, you must place it in the toString() method.
If you want to display the first name on the beginning of the output, you can do:
@Override public String toString() {
    return String.format("%s - %-10s%-10.2f", salesFirstName, salesID, annualSales);
}


text:
Q: Nested observable arrays in knockout.js Edit:
I need to make a table that prints rows of observable array object attributes.
So, each job can have an array of tasks. I have input boxes to add jobs and tasks to dropdown menus and a submit button to add the selected task to the selected job. This all works fine. I've checked and the tasks are being pushed into their respective job object task arrays.
Edit: I check viewModel.jobs()[0].tasks() in the console and it shows the tasks being added correctly.
Then I want to show the results in a table using nested templates (above)
Edit: I began by using this method of simply nesting foreaches in the table and assuming the parent child hierarchy would work. Clearly the mistake is in my JavaScript, but the tasks still won't show up and I'm all jammed up... Thank you guys so much for the help!

var job = function(name) {
  this.jobName = name;
  this.tasks = ko.observableArray();
}

var task = function(name) {
  this.taskName = name;
}

var viewModel = {
  selectedJob: ko.observable(),
  selectedTask: ko.observable(),
  jobName: "",
  jobs: ko.observableArray([new job("job1")]),
  taskName: "",
  taskList: ko.observableArray([new task("task1")]),

  addJob: function() {
    var objectToAdd = new job(this.jobName);

    if (objectToAdd.jobName === "") return;

    for (var i = 0; i < this.jobs().length; i++) {
      if (objectToAdd.jobName === this.jobs()[i].jobName) {

        return;
      }
    }
    this.jobs.push(objectToAdd);
  },

  addTask: function() {
    var taskToAdd = new task(this.taskName);

    if (taskToAdd.taskName === "") return;

    for (var i = 0; i < this.taskList().length; i++) {
      if (taskToAdd.taskName === this.taskList()[i].taskName) {

        return;
      }
    }

    this.taskList.push(taskToAdd);
  },

  removeJob: function(job) {
    viewModel.jobs.remove(job);
  },

  submitTask: function() {

    this.selectedJob().tasks().push(this.selectedTask());

  },

}

ko.applyBindings(viewModel);

<form data-bind="submit: submitTask">

      <select data-bind="options: jobs, optionsText: 'jobName', value: selectedJob, optionsCaption: 'Select Job'"></select>
      <input class="text-box" data-bind="value: jobName" /><button data-bind="click: addJob">Add Job</button>

      <select data-bind="options: taskList, optionsText: 'taskName',
                         value: selectedTask, optionsCaption: 'Select Task'"></select>
      <input class="text-box" data-bind="value: taskName" /><button data-bind="click: addTask">Add Task</button>

    <button class="submit-button" data-bind="click: submitTask">Add to Timesheet</button>

</form>

Timesheet:

        Hours

A: You cannot put div directly inside a table element. That's why it is ignored.
Change this

 to a
 and modify the template to be a td.
Also this part might be a typo: 	.

var job = function(name) {
    this.jobName = name;
    this.tasks = ko.observableArray([
      new task("job1"),
      new task("job2")
    ]);
}

var task = function(name) {
    this.taskName = name;
}

var VM = function(){
    this.jobs = [
      new job("Dev"),
      new job("Tester")
    ]
}

ko.applyBindings(new VM());

Also, you might want to use the snippet feature of SO, so that your code will be runnable.

A: What @Adrian suggested should work. It can also be achieved in much simpler code

var job = function(name) {
    this.jobName = name;
    this.tasks =[
      new task("job1"),
      new task("job2")
    ]
}

var task = function(name) {
    this.taskName = name;
}

var VM = function(){
    this.jobs = [
      new job("Dev"),
      new job("Tester")
    ]
}

ko.applyBindings(new VM());

          Hours


text:
Q: Having trouble with copying struct to another memory location with memcpy() Okay so basically I am not sure what is happening here
I am basically trying to copy a struct variable that I defined to another memory location which I malloc'd using memcopy
the compiler does not give any errors and warnings
however when I try to access the malloc'd memory location to see if the data was copied,I find some weird numbers coming up when I dereference the pointer and not the values that I copied
here is my code , what is it exactly that I am missing here,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <stdint.h>

typedef uint32_t u_int32_t;

typedef unsigned char byte;
typedef u_int32_t link;
typedef u_int32_t size;
typedef u_int32_t addr;

typedef struct header {
   u_int32_t unkno;
   size sze;
   link next;
   link prev;
} head;

int main(){

   head x;

   printf("%d %d %d %d\n", &x, &x.unkno,sizeof(head),0x12345);

   x.unkno = 0x12345;
   x.sze = 10;
   x.next = 2;
   x.prev = 6;

   void * s = malloc(sizeof(u_int32_t)*100);

   memcpy(s, (const void *)&x, sizeof(head));

   head * k = (head *)s;

   printf("%d",*(k+1));

   return 0;
}

so if somebody can point me to what I am doing wrong, or if this is even possible?

A: You only copy one structure to the 400 bytes you allocated, and malloc does not initialize the memory in any way.
The contents of newly allocated memory from malloc is indeterminate, and reading from the uninitialized memory leads to undefined behavior.
Also, when you do *(k + 1) you treat k as an array, and accessing the second element (*(k + 1) is equivalent to k[1]). You then do something even weirder and print the value as a decimal number, which it really isn't.
Lastly, when printing a pointer using printf you should use the "%p" format specifier.

To actually answer your question, then yes the data you copy is there, at the beginning of the allocated memory. You just don't print any of it.

A: Okay i solved this
basically it was the problem with the pointer that was accessing the malloc'd memory
it was this line that was causing me problems
head * k = (head *)s;

it should have been
 u_int32_t * k = (u_int32_t *)s;


text:
Q: Angular 5 Excel Office App Communication not happening from Dialog to Task Pane We are facing an issue while sending a message from Dialog to the Task pane in our Angular 5 Excel Single Page Application
We are able to open Dialog Window, but the callback event is not firing when we send a message from Dialog to the Task Pane.  Please find below is our code.
The code in the Task Pane:
openMainWindow() {
  this.message = "opening dialog";
  Office.context.ui.displayDialogAsync(
    "https://localhost:3000/#/mainwindow",
    { height: 100, width: 100 },
    this.callBack
  );
}

callBack(result) {
  this.message = "opened dialog";
  this.dialog = result.value;
  this.dialog.addEventHandler(Office.EventType.DialogMessageReceived, this.processMessage);
  this.message = this.dialog.toString();
}

The above callback event is not firing.
processMessage(arg) {
    this.message = "received a message from dialog";
    this.dialog.close();
    this.message = arg.message;
}

Code in the Dialog Window:
sendMessage() {
    this.message = "sending message to parent";
    Office.context.ui.messageParent("this is the message from child");
}

We have tested the same functionality using JQuery (multiple pages) and it is working fine, we are able to send and receive messages from Dialog.
If possible please help us or point us to someone on your team to solve this issue with Angular Excel App.

A: There is a very valuable page that covers some unique issues presented by Angular when building Office Web Add-ins: Develop Office Add-ins with Angular.
There is also an important note in the Dialog API docs when it comes to SPA web apps:

The dialog box is in a new window with its own execution context. If you pass a route, your base page and all its initialization and bootstrapping code run again in this new context, and any variables are set to their initial values in the dialog window. So this technique launches a second instance of your application in the dialog window. Code that changes variables in the dialog window does not change the task pane version of the same variables. Similarly, the dialog window has its own session storage, which is not accessible from code in the task pane.

I believe your trouble here has to do with this not pointing to the object you expect it too. You should be binding the callback to the proper this object:
openMainWindow() {
  this.message = "opening dialog";
  Office.context.ui.displayDialogAsync(
    "https://localhost:3000/#/mainwindow",
    { height: 100, width: 100 },
    this.callBack.bind(this));
}


text:
Q: How to make a Case/Switch in python with no all breaks, and code between 2 cases I know Java and C and I used to use Switch statements, but there aren't in python.
I see many ways of use if-elif-else to remplace, but any that remplace completly.
Example of code that I want remplace.
switch(expression) {
   case a:
       doA();
   case b:
       doB();
   case c:
       doC();
       break;
   case d:
   case e:
       doDE()
       break;
   case f:
   case g:
       doFG():
   case h:
       doH();
       break;
   case i:
       doI();
   default:
       foo();
       break;
}

As you can see not all case are follow by break, and there is code between some cases that only executed with one case, but there is also common code that is executed in both case.
I see a many ways, but any that allow this at same time. And I think this is the real diference between if-elif-else, and switch-case.
So there is any way of do this will be great, or it's only posible with repeted functions calls and complex if with all posibilities?.
Thank you.

A: The switch statement is considered harmful. That's probably why Python doesn't have it. The fallthrough behavior is a major source of bugs in C code. It's easy to forget a break; That's why C# disallows it--you'd have to use an explicit goto instead. It's the same in Python's dict of functions approach. You put in a call to the next function. "Explicit is better than implicit".
The easiest way to make a dict of functions (with identifier keys) is with a class declaration.
class switch:
    def a():
        print('a')
        switch.b()
    def b():
        print('b')
        switch.c()
    def c():
        print('c')
    def d():
        switch.e()
    def e():
        print('de')
    def f():
        switch.g()
    def g():
        print('fg')
    def h():
        print('h')
    def i():
        print('i')
        switch.default()
    def default():
        print('foo')

Use it like so.
>>> expression = 'a'
>>> getattr(switch, expression, 'default')()
a
b
c

You can also extract the __dict__ attr if you want an actual dict.
>>> switch.__dict__.get('e', 'default')()
de

You can be similarly explicit with if statements.
def switch(case)
    if case == a:
        doA()
        case = b
    if case == b:
        doB()
        case = c
    if case == c:
        doC()
        return
    if case == d:
        case = e
    if case == e:
        doDE()
        return
    if case == f:
        case = g
    if case == g:
        doFG()
        case = h
    if case == h:
        doH()
        return
    if case == i:
        doI()
    foo()

If you're worried about side effects changing the condition or if the conditions are more complex than simple equality and you don't want to repeat them, you can use a helper variable instead of reassigning case.
def switch(case):
    fall = False
    if case == a:
        doA()
        fall = True
    if fall or case == b:
        doB()
        fall = True
    if fall or case == c:
        doC()
        return
    if case == d:
        fall = True
    if fall or case == e:
        doDE()
        return
    if case == f:
        fall = True
    if fall or case == g:
        doFG()
        fall = True
    if fall or case == h:
        doH()
        return
    if case == i:
        doI()
    foo()

A: The if statement can do any condition at all. You just have to be a little more explicit.
def switch(case):
    if case in 'a':
        doA()
    if case in 'ab':
        doB()
    if case in 'abc':
        doC()
        return
    if case in 'de':
        doDE()
        return
    if case in 'fg':
        doFG()
    if case in 'fgh':
        doH()
        return
    if case in 'i':
        doI()
    foo()


text:
Q: C# - writing bit by bit into binary file This is a piece of code that aim to make use of Shannon coding on .txt file. What I hope to accomplish here is to create binary file that stores encoded message.
An array codes stores strings with only 0s and 1s. (codes)
An array symbolsSet contains characters in the form of integer values.
indexFirstProbability is just the value that indicates where we need to start reading symbolSet.
sampleText is a string we want to encode (Shannon codes were made based on it)
My code produces wrong output. Instead of writing one bit at time into a file, it writes two bits where first one is always 0.
For example if code for letter a is 00 and for b is 110, the output file  for message aab is: 00 00 00 00 01 01 00 instead of  0 0 0 0 1 1 0 (spaced added for readability).
I would appreciate if someone explain to me why my code works that way and how to fix it.
static void saveMessageIntoBinaryFile (string[] codes, int[] symbolSet,
            int indexFirstProbability, string sampleText, string fileName, string path)
{
    BinaryWriter binaryWriter = new BinaryWriter(File.Open( path + fileName + ".bin", FileMode.Create));

    string temp;
    bool oneOrZero;

    foreach (char s in sampleText)
    {
        temp = codes[Array.IndexOf(symbolSet, s) - indexFirstProbability];

        foreach (char b in temp)
        {
            if (b == '0')
                oneOrZero = false;
            else
                oneOrZero = true;

            binaryWriter.Write(oneOrZero);
        }

    }
    binaryWriter.Close();
}

A: I would do sth like this:
public static void Main()
{
    Console.WriteLine("Hello World");
    SaveMessageIntoBinaryFile(new []{"00", "110"}, new char[]{'a', 'b'}, "aab", "output.txt", "");
}

static void SaveMessageIntoBinaryFile (string[] codes, char[] symbolSet, string sampleText, string fileName, string path)
{
    using(var writer = new StreamWriter(File.Open(Path.Combine(path, fileName), FileMode.Create)))
    {
        foreach(var symbol in sampleText)
        {
            var codeIndex = Array.IndexOf<char>(symbolSet, symbol);
            writer.Write(codes[codeIndex]);
            Console.Write(codes[codeIndex] + "\t");
        }
    }
}

You can try to launch it here: https://dotnetfiddle.net/Jj27Fu
Do you really need binary output?


text:
Q: Optimising "i = b ? (i | mask) : (i & ~mask)" I want to be able to set or clear (multiple) bits of a uintX_t t.
i is a runtime variable (uintX_t).
b is a runtime variable (uintX_t) which is constrained to be 0 or 1.
mask is a compile-time constant.
Is there a better way than:
i = b ? (i | mask) : (i & ~mask)

I'm looking to avoid branching, if that's possible.  Target is ARM, if it matters.

A: Exploiting the fact that -1u is the value with all bits set:
i = (i & ~mask) | (mask & -b);

or
i ^= (i ^ -b) & mask;

The second approach reduces the number of operations and code size. The first approach may still be faster on a superscalar architecture because some operations can be executed in parallel.

A: The idea here is to replace the branch by a multiplication, where we can zero each side depending on the value of b:
i = (i | (mask * b)) & (~mask | (mask * b));

A: Another alternative: Always set bits to 0 (left part) and optionally set bits to 1 (right part).
i = (i & ~mask) | (mask * b);

A: The most readable way is to do this in several steps - doing so won't affect performance but improve readability.
As is always the case with bit-wise operators, you must be careful with implicit type promotions. For example, careless use of ~ tends to create implicit promotion bugs. (The ?: operator also silently promotes the result by balancing the 2nd and 3rd operands with each other.)
Readable, portable, safe code:
uintx_t i = ... ;
uintx_t b = ... ;  // 1 or 0

i &= (uintx_t)~mask;   // always clear the bit
i |= mask * b;         // if b is 1, set the bit, otherwise OR with 0


text:
Q: Help converting Json into a Dynamic Map I need to convert this json
{
    "jsonrpc": "2.0",
    "method": "hostgroup.get",
    "params": {
        "output": "extend",
        "filter": {
            "name": [
                "4:CLIENTES.Balearia"
            ]
        }
    },
    "auth": "xxxxxxxxxxxxxxxxxx",
    "id": 1
}

into a Map like this:
   String payload = JSON.serialize(
        new Map<String, Object> {
            'jsonrpc' => '2.0',
                'method' => 'hostgroup.get',
                'params' =>
                new Map<String, Object> {
                    'output' => 'extend',
                    'filter' => new Map<String[], String>{'name' => '4:CLIENTES.Balearia'}
                },
                    'auth' => result,
                    'id' => 1
                    }
    );

So I can play with the values and make them dynamic before sending them to the webservice.
I've been trying but always an error .... Is there any tool for making this ??
Thanks a lot

A: You could use json2apex to create a serializable class, but it can only create static classes. To be dynamic, you need to write it by hand. There's only so much that a tool can help you with. You need to understand the basics of data models. In your code, you wrote Map<String[], String>, which would be a List<String> for the key, but you should have written Map<String, String>. You should read more about Lists, Maps, and Sets for more information.

A: I did it like this:
String payload = JSON.serialize(
    new Map<String, Object> {
        'jsonrpc' => '2.0',
            'method' => 'hostgroup.get',
            'params' =>
            new Map<String, Object> {
                'output' => 'extend',
                'filter' => new Map<String, String[]>{'name' => new String[] { '4:CLIENTES.Balearia' } }
            },
                'auth' => result,
                'id' => 1
                }
);


text:
Q: Itext7 ColumnDocumentRenderer change Margin per Page I'm using Itext7, I've been trying to change left margin of the document with no luck. I have two columns, I want left margin for odd page 30, and for even to be 50.
 PageHeaderHandler pageHeaderHandler = new PageHeaderHandler(SummaryDoc, pdfdoc, sumTable);
 pdfdoc.AddEventHandler(PdfDocumentEvent.END_PAGE, pageHeaderHandler);
 columnWidth = ((PageSize.A4.GetWidth() - offSet * 2) / 2 - gutter) + 30;
 columnHeight = PageSize.A4.GetHeight() - offSet * 2;
 Rectangle[] columns = {
                    new Rectangle(offSet, topMargin, columnWidth, columnHeight),
                    new Rectangle(offSet + columnWidth + gutter, topMargin, columnWidth, columnHeight)};
 SummaryDoc.Doc.SetRenderer(new ColumnDocumentRenderer(SummaryDoc.Doc, columns));

And my Handler :
public void HandleEvent(Event @event)
{
    if (doc.CurrentPage() % 2 == 1)
    {
        doc.Doc.SetLeftMargin(30);
    }
    else
    {
        doc.Doc.SetLeftMargin(50);
    }
}

This doesn't work, it works for a normal DocumentRenderer but not here. Is there a way to set leftMargin for ColumnDocumentRenderer ?

A: If you look at the implementation of ColumnDocumentRenderer, first of all you would see that it does not take margins into account (margins concept might be controversial for several columns and mean different things for different people) and columns are defined in absolute units.
But most importantly, you can see that the implementation of ColumnDocumentRenderer is pretty straightforward and does not contain a lot of code. You can get inspiration from there to implement your own renderer that would use different column positions depending on whether the page is odd or even.
Here is a very basic implementation of such custom renderer class:
private static class VariableColumnDocumentRenderer extends DocumentRenderer {
    protected Rectangle[][] columns;
    protected int nextAreaNumber;
    protected int curColumnLayoutId;

    public VariableColumnDocumentRenderer(Document document, Rectangle[][] columns) {
        super(document);
        this.columns = columns;
    }

    @Override
    protected LayoutArea updateCurrentArea(LayoutResult overflowResult) {
        if (overflowResult != null && overflowResult.getAreaBreak() != null && overflowResult.getAreaBreak().getType() != AreaBreakType.NEXT_AREA) {
            curColumnLayoutId++;
            curColumnLayoutId %= columns.length;
            nextAreaNumber = 0;
        }
        if (nextAreaNumber % columns[curColumnLayoutId].length == 0) {
            curColumnLayoutId++;
            curColumnLayoutId %= columns.length;
            super.updateCurrentArea(overflowResult);
        }
        return (currentArea = new RootLayoutArea(currentPageNumber, columns[curColumnLayoutId][nextAreaNumber++ % columns.length].clone()));
    }
}

So it accepts an array of arrays of columns and in fact serves a more flexible purpose than you need. It will rotate over inner array in scope of one page and when the areas are exhausted will go to the next outer array item and so on. So in your case you can pass the columns for odd and even pages and the implementation will just rotate over those columns infinitely.
Example of how such code can be used:
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFile));
Document doc = new Document(pdfDoc);

Rectangle[] columnsOdd = {new Rectangle(100, 100, 100, 500), new Rectangle(400, 100, 100, 500)};
Rectangle[] columnsEven = {new Rectangle(200, 100, 100, 500), new Rectangle(500, 100, 100, 500)};
doc.setRenderer(new VariableColumnDocumentRenderer(doc, new Rectangle[][] {columnsOdd, columnsEven}));


text:
Q: json_object_put is not working on loop i worked with json-c library in C language.  I have the following code
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <json/json.h>

int main()
{
    while(1)
    {
          testJson();
          Sleep(2000); //sleep 2 seconds
    }
    return 0;
}

void testJson()
{
      json_object *new_obj;
      char buf[] = "{ \"foo\": \"bar\", \"foo2\": \"bar2\", \"foo3\": \"bar3\" }"
      new_obj = json_tokener_parse(buf);
      json_object_object_add(new_obj, "d1", json_object_new_string(data1));
      json_object_object_add(new_obj, "d2", json_object_new_string(data2));
      .
      .
      .
      .

      printf("obj=%s",json_object_get_string(new_obj));
      json_object_put(new_obj);
}

It print json obj only once. After it produce Segmentation fault (core dumped) message. But it working perfectly when i modifying sleep time to 10 second instead of 2 second.
I need to create and delete json object within 2 second. is it possible with json-c library?


text:
Q: How can I redirect HTTPS to HTTP in .htaccess for specific domains? We host a number of websites on our server. Our main site, let's call www.domain.com.
Anyway, we noticed that the other sites we host, etc, all point back to our main site (domain.com) when https:// is put in front of their domain. Part of the problem is that these are indexing in Google as well.
I've wondering how I can redirect all these in the htaccess - please help!

A: Add these rules to the htaccess file in your www.domain.com document root, preferably above any other routing rules that may be there:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R]


text:
Q: Jfrog Build a Docker image with a private base image from Artifactory
I am following the Jfrog Pipeline Example: Docker Build and Push from https://www.jfrog.com/confluence/display/JFROG/Pipeline+Example%3A+Docker+Build+and+Push
I would like to build a docker image based on an existing docker image(caching) from Artifactory.
I have checked the following configuration in the documentation:
https://www.jfrog.com/confluence/display/JFROG/DockerBuild
To build a Docker image that relies on a private base image:
Define the base image as an Image resource, with autoPull set to true.
Specify the Image resource as one of the inputResources of the DockerBuild step.
Build a Docker image with a private base image
This example builds a Docker image that relies on a private base image stored in an
Artifactory Docker repository.

resources:
# Application source repository
- name: gosvc_app
  type: GitRepo
  configuration:
    gitProvider: myGithub
    path: myuser/myrepo                   # replace with your repository name
    branches:
      include: master

 # Docker image in an Artifactory repository
 - name: base_image
  type: Image
  configuration:
    registry: myArtifactory
    sourceRepository: docker-local        # replace with your repository name
    imageName: docker.artprod.mycompany.com/baseimage
    imageTag: latest
    autoPull: true
pipelines:
  - name: demo_pipeline
  steps:
    - name: bld_image
      type: DockerBuild
      configuration:
        dockerFileLocation: .
        dockerFileName: Dockerfile
        dockerImageName: docker.artprod.mycompany.com/gosvc
        dockerImageTag: ${run_number}
        inputResources:
          - name: gosvc_app
          - name: base_image
        integrations:
          - name: MyArtifactory

Running this pipeline throws the following error:
"pipeline demo_pipeline has cyclic connection involving step bld_image.
A pipeline can not have cyclic connections.
If I configure DockerBuild with only the Image resource i am getting the following error.

Running this pipeline throws the following error:
"DockerBuild step bld_image must have exactly one input resource of type GitRepo"
So in one part of the documentation you can use 2 resources under 'inputResources' and while using this configuration throws the above error.
And in other part of the documentation it uses only the Image resource which throws the error of "...exactly one input resource of type GitRepo".
So how can i achieve building a docker image base on a docker image(caching) stored in Artifactory?

A: The has cyclic connection error message usually means that you're using a resource as an input as well as an output somewhere in the same pipeline (not necessarily the same step).
For example if your pipeline had base_image -> bld_image -> push_image -> base_image, then that would be considered cyclic.
Since the error log is specifically mentioning the bld_image, can you make sure that this image resource is not used as an output later in your workflow?
If you want an image to reference what was pushed in a later step, I'd recommend creating a second image type resource. One resource represents the base image, and the other can represent the new image that you've built and pushed
JFrog Pipelines doesn't allow cyclic connections like this to help users avoid accidentally creating an infinitely looping pipeline.

A: Solution for using a remote cache docker image with buildx in the Artifactory:
      steps:
        - name: {{ .Values.DockerBuild.name | default "DockerBuild" }}
          type: DockerBuild
          execution:
            onStart:
              - docker buildx create --name jfrog-builder --use
              - docker buildx install
              - jf c add example --url="$int_{{ .Values.artifactoryIntegration }}_url" --user="$int_{{ .Values.artifactoryIntegration }}_user" --password="$int_{{ .Values.artifactoryIntegration }}_password"
              - echo $int_{{ .Values.artifactoryIntegration }}_apikey | docker login --username $int_{{ .Values.artifactoryIntegration }}_user --password-stdin {{ .Values.artifactoryUrl }}
          configuration:
            dockerFileLocation: {{ .Values.DockerBuild.dockerFileLocation | quote }}
            dockerFileName: {{ .Values.DockerBuild.dockerFileName }}
            dockerImageName: {{ .Values.DockerBuild.dockerImageName }}
            dockerImageTag: {{ .Values.DockerBuild.dockerImageTag }}
            dockerOptions: "--cache-from type=registry,ref={{ .Values.DockerBuild.dockerImageName }}:{{ .Values.DockerBuild.dockerImageCacheTag }} --cache-to type=registry,ref={{ .Values.DockerBuild.dockerImageName }}:{{ .Values.DockerBuild.dockerImageCacheTag }},mode=max --load"
          inputResources:
            - name: {{ .Values.GitRepo.name | default "GitRepoRes"  }}


text:
Q: How can I get Speech Recognition to stop listening after one word? I am making a spoken PygLatin translator.
A very basic one at least that tells one translated word.
If I speak more than one word, it get's all jumbled up and takes the first character in the first word and puts it onto the last spoken word with "ay" at the end.
So I have been having a few issues because of that. Is there a way to get it to stop listening after only one spoken word? Would there possibly be a way to also get the first letter of each word put to the end of each spoken word followed by "ay"?
here is a sample of my code so far:
import time
import speech_recognition as sr
from gtts import gTTS
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from pygame import mixer
mixer.init()
pyg = "ay"
count = 3
while count > 0:
    while (True == True):
  # get audio input
        original = sr.Recognizer()
        with sr.Microphone() as source:
      # listen for 1 second and create the ambient noise energy level
            original.adjust_for_ambient_noise(source, duration = 1)
            print("Say ONE word. If you do not wish to use the translator, say 'stop' ")
        audio = original.listen(source,phrase_time_limit = 1)

  # speech recognition with Google
        try:
            response = original.recognize_google(audio)
            if response == "stop":
                print("Thanks for using the PygLatin Translator, Goodbye!")
                break
                pyg_word = response + pyg
                w = response + pyg
                pyg_word = w[1 : len(pyg_word)]
                print(pyg_word)
                tts = gTTS(text = str(pyg_word), lang='en')
                tts.save("response.mp3")
                mixer.music.load('response.mp3')
                mixer.music.play()

        except sr.UnknownValueError:
            print("Translator could not understand audio")
        except sr.RequestError as e:
            print("Sphinx error; {0}".format(e))