text:
Q: Acceder al texto de un span para separarlo en múltiples div una ves se mostro en el dom Necesito acceder a cada una de las líneas de texto que contiene un span para poder separarlos en múltiples divs, se que la etiqueta span detecta los saltos de linea una ves el contenido se muestra en la pagina web actualmente tengo un método que me hace esto pero superficial, solo crea unos contadores los cuales me indican el tamaño del contenido, lo que yo necesito es que el texto este dentro de los divs esto es posible una ves se el contenido se muestra en el dom?
Estoy usando vue en mi proyecto, lo único que que hace es que me permite crear un documento pdf del lado del cliente con la librería Html2pdf pero necesito que los saltos de linea sea más preciso, es por eso que deseo colocar cada linea en un div, si esto no es posible que alternativa tengo?
    <template>

Titulo de ejemplo para esta wea

Titulo 2 de ejemplo para esta wea

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, numquam commodi enim deserunt
        omnis facilis! Quisquam repudiandae ratione officiis illo minus aut voluptates nobis laudantium
        itaque quam, magnam provident aliquid? Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum quo perspiciatis alias
        officiis nulla sunt laudantium, ad deleniti laborum aliquam quos inventore, illo rem asperiores
        ipsa atque eveniet impedit autem? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Velit
        repellendus esse aspernatur tenetur dolore dolor suscipit id laborum, culpa quos. Aliquid ex minima
        in alias quod quidem exercitationem cumque distinctio. Lorem ipsum dolor, sit amet consectetur adipisicing
        elit. Nemo, numquam? Repudiandae numquam temporibus minima quisquam omnis, voluptatem quam dolores,
        qui cumque quo consectetur facilis eius deserunt quas molestiae eum laborum. Lorem ipsum dolor sit amet consectetur,
        adipisicing elit. Iste, laudantium alias ipsam accusantium quasi voluptatem qui rem sit blanditiis maiores aspernatur eveniet aliquid in harum?
        At eos obcaecati officiis enim. Lorem, ipsum dolor sit amet consectetur adipisicing elit. Molestiae totam
        alias temporibus earum corporis nobis obcaecati, ad assumenda quas placeat eius ducimus sint reiciendis aliquam dolorum.
        Praesentium eum sit autem!

Titulo 3 de ejemplo para esta wea

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, numquam commodi enim deserunt
        omnis facilis! Quisquam repudiandae ratione officiis illo minus aut voluptates nobis laudantium
        itaque quam, magnam provident aliquid? Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum quo perspiciatis alias
        officiis nulla sunt laudantium, ad deleniti laborum aliquam quos inventore, illo rem asperiores
        ipsa atque eveniet impedit autem? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Velit
        repellendus esse aspernatur tenetur dolore dolor suscipit id laborum, culpa quos. Aliquid ex minima
        in alias quod quidem exercitationem cumque distinctio. Lorem ipsum dolor, sit amet consectetur adipisicing
        elit. Nemo, numquam?

        Titulo 4 de ejemplo para esta wea

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, numquam commodi enim deserunt
        omnis facilis! Quisquam repudiandae ratione officiis illo minus aut voluptates nobis laudantium
        itaque quam, magnam provident aliquid? Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum quo perspiciatis alias
        officiis nulla sunt laudantium, ad deleniti laborum aliquam quos inventore, illo rem asperiores
        ipsa atque eveniet impedit autem? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Velit
        repellendus esse aspernatur tenetur dolore dolor suscipit id laborum, culpa quos. Aliquid ex minima
        in alias quod quidem exercitationem cumque distinctio. Lorem ipsum dolor, sit amet consectetur adipisicing
        elit. Nemo, numquam? Repudiandae numquam temporibus minima quisquam omnis, voluptatem quam dolores,
        qui cumque quo consectetur facilis eius deserunt quas molestiae eum laborum. Lorem ipsum dolor sit amet consectetur,
        adipisicing elit. Iste, laudantium alias ipsam accusantium quasi voluptatem qui rem sit blanditiis maiores aspernatur eveniet aliquid in harum?
        At eos obcaecati officiis enim. Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque officia, qui quo corrupti dolor fuga perferendis
        delectus repellat. Vel excepturi doloremque necessitatibus corrupti quod illo praesentium labore non ex dolor!
        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Maxime laborum ratione reprehenderit nemo temporibus quia maiores
        quibusdam eaque inventore, veritatis perferendis asperiores, dolore esse tempora qui. Nobis libero fugiat exercitationem!

 Titulo 5 de ejemplo para esta wea

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, numquam commodi enim deserunt
        omnis facilis! Quisquam repudiandae ratione officiis illo minus aut voluptates nobis laudantium
        itaque quam, magnam provident aliquid? Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum quo perspiciatis alias
        officiis nulla sunt laudantium, ad deleniti laborum aliquam quos inventore, illo rem asperiores
        ipsa atque eveniet impedit autem? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Velit
        repellendus esse aspernatur tenetur dolore dolor suscipit id laborum, culpa quos. Aliquid ex minima
        in alias quod quidem exercitationem cumque distinctio. Lorem ipsum dolor, sit amet consectetur adipisicing
        elit. Nemo, numquam? Repudiandae numquam temporibus minima quisquam omnis, voluptatem quam dolores,
        qui cumque quo consectetur facilis eius deserunt quas molestiae eum laborum. Lorem ipsum dolor sit amet consectetur,
        adipisicing elit. Iste, laudantium alias ipsam accusantium quasi voluptatem qui rem sit blanditiis maiores aspernatur eveniet aliquid in harum?
        At eos obcaecati officiis enim. Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos est odio dolorem. Tempore molestiae, accusamus quidem culpa
        ut aperiam, a consequuntur aut blanditiis necessitatibus beatae optio maxime! Repudiandae,
        totam quisquam? Lorem ipsum dolor sit amet consectetur adipisicing elit. Adipisci blanditiis possimus tenetur. Alias aspernatur ipsum,
        nobis doloribus eum aliquam maxime suscipit cumque, dolore ipsa itaque. Asperiores minus similique
        eveniet ducimus.

Titulo 6 de ejemplo para esta wea

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, numquam commodi enim deserunt
        omnis facilis! Quisquam repudiandae ratione officiis illo minus aut voluptates nobis laudantium
        itaque quam, magnam provident aliquid? Lorem ipsum dolor sit amet consectetur adipisicing elit.

Titulo 7 de ejemplo para esta wea

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, numquam commodi enim deserunt
        omnis facilis! Quisquam repudiandae ratione officiis illo minus aut voluptates nobis laudantium
        itaque quam, magnam provident aliquid? Lorem ipsum dolor sit amet consectetur adipisicing elit.

Titulo 8 de ejemplo para esta wea

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, numquam commodi enim deserunt
        omnis facilis! Quisquam repudiandae ratione officiis illo minus aut voluptates nobis laudantium
        itaque quam, magnam provident aliquid? Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum quo perspiciatis alias
        officiis nulla sunt laudantium, ad deleniti laborum aliquam quos inventore, illo rem asperiores
        ipsa atque eveniet impedit autem? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Velit
        repellendus esse aspernatur tenetur dolore dolor suscipit id laborum, culpa quos. Aliquid ex minima
        in alias quod quidem exercitationem cumque distinctio. Lorem ipsum dolor, sit amet consectetur adipisicing
        elit. Nemo, numquam?

Titulo 9 de ejemplo para esta wea

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, numquam commodi enim deserunt
        omnis facilis! Quisquam repudiandae ratione officiis illo minus aut voluptates nobis laudantium
        itaque quam, magnam provident aliquid? Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum quo perspiciatis alias
        officiis nulla sunt laudantium, ad deleniti laborum aliquam quos inventore, illo rem asperiores
        ipsa atque eveniet impedit autem? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Velit
        repellendus esse aspernatur tenetur dolore dolor suscipit id laborum, culpa quos. Aliquid ex minima
        in alias quod quidem exercitationem cumque distinctio. Lorem ipsum dolor, sit amet consectetur adipisicing
        elit. Nemo, numquam? Repudiandae numquam temporibus minima quisquam omnis, voluptatem quam dolores,
        qui cumque quo consectetur facilis eius deserunt quas molestiae eum laborum. Lorem ipsum dolor sit amet consectetur,
        adipisicing elit.

Titulo 10 de ejemplo para esta wea

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, numquam commodi enim deserunt
        omnis facilis! Quisquam repudiandae ratione officiis illo minus aut voluptates nobis laudantium
        itaque quam, magnam provident aliquid? Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum quo perspiciatis alias
        officiis nulla sunt laudantium, ad deleniti laborum aliquam quos inventore, illo rem asperiores
        ipsa atque eveniet impedit autem? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Velit
        repellendus esse aspernatur tenetur dolore dolor suscipit id laborum, culpa quos. Aliquid ex minima
        in alias quod quidem exercitationem cumque distinctio. Lorem ipsum dolor, sit amet consectetur adipisicing
        elit. Nemo, numquam? Repudiandae numquam temporibus minima quisquam omnis, voluptatem quam dolores,
        qui cumque quo consectetur facilis eius deserunt quas molestiae eum laborum. Lorem ipsum dolor sit amet consectetur,
        adipisicing elit. Iste, laudantium alias ipsam accusantium quasi voluptatem qui rem sit blanditiis maiores aspernatur eveniet aliquid in harum?
        At eos obcaecati officiis enim. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Provident commodi ab totam. Culpa corrupti natus officiis
        tempora. Dolor autem repellendus, quidem explicabo ipsum ratione nisi facilis tempore? Provident, magni facilis!
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Aut hic odit facilis, earum consectetur fugit. Earum iusto magnam saepe cumque labore.
        Unde quis accusantium libero ipsum rem suscipit praesentium doloribus! Lorem ipsum dolor sit amet consectetur adipisicing elit.
        Ex, deserunt nobis? Error, sed? Dolore illo iste repellendus ipsum maiores tenetur, numquam, alias inventore officiis illum ea architecto
        sapiente soluta velit!

    <button v-on:click="download">
        imprimir
    </button>

  </template>


text:
Q: How to add symbolic variables to Symmetric Functions algebra in Sagemath I'm defining some operators in the algebra Symqt = SymmetricFunctions(QQ['q','t'].fraction_field()), and I need a third variable.
If I add it to the base field, however, I'm unable to evaluate it; if I try to define a polynomial ring over Symqt, I'm unable to multiply coefficients and variables.
from sage.combinat.q_analogues import *
from sage.combinat.sf.sfa import *
F = QQ['q','t','u'].fraction_field()
F.inject_variables(verbose = False)
Symqt = SymmetricFunctions(F)
Symqt.inject_shorthands(verbose = False)
(u*s[2]).subs(u=1)

gives u*s[2] (doesn't evaluate), while
from sage.combinat.q_analogues import *
from sage.combinat.sf.sfa import *
F = QQ['q','t'].fraction_field()
F.inject_variables(verbose = False)
Symqt = SymmetricFunctions(F)
Symqt.inject_shorthands(verbose = False)
R = PolynomialRing(Symqt,'u')
u*s[2]

raises an error (can't multiply stuff in R with stuff in Symqt).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can Kamailio Proxy Server actually make SIP Calls? I am using a PBX (Asterisk) and all Inbound calls come through my Proxy (Kamailio).  I would like for all outbound calls that go through my PBX to be controlled by the Proxy also.  Currently outbound calls go through the PBX and communicate with endpoints.  I would like my Proxy to be the endpoint for all communication.  In my mind for this to happen, Kamailio would have to make the SIP call.  Is this correct?
Thank you!

A: The question is rather vague, however, if you want to send the call from Asterisk PBX to Kamailio and Kamailio to send it further to a carrier or SIP device, then, yes, it is possible.
One of the common use cases is Asterisk sending the calls to Kamailio, which does least cost routing or load balancing to a group of carriers (see dispatcher, lcr or carrierroute modules).

A: You can use kamailio as an outbound proxy for calls that come from your B2BUA (in that case Asterisk).
An example in the pjsip.conf
[myitsp]
type = endpoint
; other stuff
outbound_proxy = sip:192.168.0.1\;lr

That will tell Asterisk to route all outbound calls through this outbound proxy. You  just need to make sure that Kamailio is configured correctly to also receive traffic from your Asterisk server.
More information in the Asterisk docs


text:
Q: Get Distinct data from SharePoint List and push in in table I have a code that take value from SharePoint List and display it on table. Below is the code:
$(document).ready(function() {
getItems();
});

function getItems() {

$.ajax({

    async: true,
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Global')/items?$filter=Title eq Domain",
    method: "GET",

    headers: {
        "accept": "application/json;odata=verbose",
        "content-type": "application/json;odata=verbose"

    },
    success: function(data) {
        data = data.d.results;
        console.log(data);
        $.each(data, function(index, value) {

            if (value.Title == null) {
                value.Title = "";}
            else{
                value.Title = value.Title ;}

            if (value.Grouped_x0020_OPUs == null) {
                value.Grouped_x0020_OPUs = "";}
            else{
                value.Grouped_x0020_OPUs = value.Grouped_x0020_OPUs;}

            if (value.Phase == null) {
                value.Phase = "";}
            else{
                value.Phase = value.Phase ;}

            if (value.Stage == null) {
                value.Stage = "";}
            else{
                value.Stage = value.Stage ;}

            var html = "
" + value.Title + "	" + value.Grouped_x0020_OPUs + "	" + value.Phase + "	" + value.Stage + "
";
            $('.table tbody').append(html);

        });

        table = $('#table_id').DataTable();

    },
    error: function(error) {
        console.log(JSON.stringify(error));

    }

})

}

The code above will take all the value in the list. My question is how do I get a value from the list such as value.Grouped_x0020_OPUs and remove the duplicate one then display it on table?
Please help me on this. Thank you very much.

A: This is not supported. Please refer here. You can try using caml with group by clause or you can implement your own client side logic like this;
var groupedOPUs= []; //should be declared at the beginning of the success function.
if (groupedOPUs.indexOf(value.Grouped_x0020_OPUs) < 0){
        var html = "
" + value.Title + "	" + value.Grouped_x0020_OPUs + "	" + value.Phase + "	" + value.Stage + "
";
        $('.table tbody').append(html);
        groupedOPUs.push(value.Grouped_x0020_OPUs);
}


text:
Q: sum over bin range in python I have a numpy array with shape:
In: imar.shape
Out: (21, 77, 10000)

I want a binned sum on the last axis, with every bin containing 20 items.
The way I'm doing this now is:
np.sum(  imar.reshape([-1,500,20]), axis=2 ).reshape(imar.shape[:2])

It's fast, but seems error-prone if I get the arguments to reshape wrong. Is there a better way to do this?
I've looked at np.digitize,histogram,bincount, and some others, but those are value based; I want sum over a set of ranges.

A: You have the right approach.  I asked a similar question a while back:
How can I efficiently process a numpy array in blocks similar to Matlab's blkproc (blockproc) function
There are several approaches to handling the reshape.  If you are careful and write a function to do it, you'll be alright.  Of course, you need to be certain that you trim your input matrix if it isn't an integer multiple of your block size.


text:
Q: How to access camera view as an image without taking screenshot in Unreal Engine? I know I can take screenshots using following:
GetWorld()->GetGameViewport()->Viewport->TakeHighResScreenShot();

It saves a screenshot in <Project>\Saved\Screenshots\Windows. But I want more control over the image. Is it possible, say, to access individual pixels?
Is it possible to get what's on the screen as an image object (and maybe also save it in a custom location)?

A: Answered here: https://forums.unrealengine.com/t/how-to-access-camera-view-as-an-image-without-taking-screenshot-in-unreal-engine/431744
Seems like people over at Answers@UnrealEngine are more active.


text:
Q: Upload to SoftLayer Object Storage from FineUploader Has anyone tried to integrate FineUploader with SoftLayer's Object Storage?
http://www.softlayer.com/cloudlayer/storage
It is built on OpenStack's Swift and is similar to S3 in concept.  I think that FineUploader would need to be able to work with their REST API calls for it to work, but maybe there is a DIY way to do it.
I do not want to put my own server in between as for my needs, I would then not need the Object Storage service.  Goal would be to not run a server for this.

A: Currently, the short answer is no. We are going to add support for Rackspace's Cloud Files (based on OpenStack's Swift, as well) within the next 2 releases. I'd appreciate if you could chime in on the issue tracker and add your support: https://github.com/Widen/fine-uploader/issues/1025 -- note that issue is regarding Rackspace, but since they are both using Swift it may be easy to support both Rackspace and Softlayer as well as any other cloud services using Swift.

A: Softlayer is now bluemix and is its object storage is S3 capable.
Instruction for fineUploader are here ( depending on what you want to do) :
http://docs.fineuploader.com/quickstart/03-setting_up_server-s3.html
You will need to replace access_id and secret_access_key by your softlayer/bluemix one.
Endpoints are available once you create your object storage account, it will be something like this :
https://s3-api.dal-us-geo.objectstorage.softlayer.net/
Details are here of the API are here :
https://ibm-public-cos.github.io/crs-docs/crs-operations.html


text:
Q: Update Url String what ways can I update this url string without having to open or upgrade the .apk file? can I update it from a twitter post or something? I just don't want to have to keep updating the app everytime I want to change the channel, but I do need to change the channel some 5 times a day. Here is some code:
video_url = "my url link - this being the link i need to update";
     try {
                final VideoView videoView =(VideoView)findViewById(R.id.videoView1);
                mediaController = new MediaController(ServerActivity.this);
                mediaController.setAnchorView(videoView);
                // Set video link (mp4 format )
                Uri video = Uri.parse(video_url);
                videoView.setMediaController(mediaController);
                videoView.setVideoURI(video);

A: Keep URLs in persistant storage, such as SharedPreferences and load the appropriate URL from it according tho the channel you want to change to.

A: I would retrieve the url via a RSS feed.
http://www.ibm.com/developerworks/opensource/library/x-android/index.html


text:
Q: Getting weka to cross-validate a classifier from Ruby Taking a hint from here! I'm utilising weka's library of classifiers from Ruby via RJB.
I want to be able to create a classifier from an .arff file and run 10 fold cross-validation with it to produce a confusion matrix as explained in the Weka wiki.
Below is the essential code involved.
# creating the classifier
Rjb::load("./weka.jar", jvmargs=["-Xmx2000M"])
classifier = Rjb::import("weka.classifiers.bayes.NaiveBayes").new

# importing the data
data_src = Rjb::import("java.io.FileReader").new("./the_data.arff")
data = Rjb::import("weka.core.Instances").new(data_src)

evaluation = Rjb::import("weka.classifiers.Evaluation").new(data)

folds = Rjb::import('java.lang.Integer').new(10)
rand = Rjb::import("java.util.Random").new(1)

evaluation.crossValidateModel(classifier,
                              data,
                              folds,
                              rand )

print evaluation.toMatrixString()

From what I can tell from the weka wiki link above: this should work.
But...
Fail: unknown method name `crossValidateModel' (RuntimeError)

Which from what I understand usually means that the method in question hasn't been supplied with the correct arguments, but I can't see how this would be the case.
The output of evaluation.java_methods includes crossValidateModel([Ljava.lang.String;Lweka.core.Instances;I[Ljava.lang.String;Ljava.util.Random;, Lweka.classifiers.Classifier;Lweka.core.Instances;ILjava.util.Random;[Ljava.lang.Object;])
which I'm not sure how to interpret.
Does anyone out there know what I need to do?

EDIT: although I wasn't able to solve the problem as posed here, it turns out that I was able to achieve what I wanted by starting over with JRuby as described here. Thanks to michaeltwofish for the tip :)

A: Instead of using Rjb::import('java.lang.Integer').new(10)
try to use plain 10.
You are calling a method crossValidateModel from Evaluation class. Which has a overload. see below. Notice that third parameter is int. You are using java.lang.Integer. In java int and Integer are not the same thing. Look for primitive types and Wrapper types in java if you are interested. Normally java is able to change between int and Integer since java 5. But you are calling from Rjb , I think java Integer is wrapped in some object for ruby purposes and that is confusing things.
From weka javadocs.
 crossValidateModel(Classifier, Instances, int)

Performs a (stratified if class is nominal) cross-validation for a classifier on a set of instances.
crossValidateModel(String, Instances, int, String[])

Performs a (stratified if class is nominal) cross-validation for a classifier on a set of instances.


text:
Q: Is there any way to get Google People API resource ID from Google Contacts contact Id? We store the user's contactId in our database and use it to fetch/edit/delete contacts when the user requests from our app. Now that Google Contacts API is to be sunset, we need to call Google People API for these actions using resource id.
Is there any way to get Google People API resource ID from Google Contacts contact Id?
I found the following answer in Stackoverflow:

The Contacts API and People API are separate API's not meant to
interop with each other.
That said, the reverse engineered way to do this is to take the
Contacts API contact ID, parse that hexadecimal value, convert it to
decimal, and add a 'c' prefix to it, and that becomes the People API
person resource ID.
e.g. if the Contacts API contact ID was 100, then the People API
person ID would be c256. When you fetch contacts from the People API
in this fashion, it'll have the joined profile information, if
present.

I tried the solution and it is working, but need to know whether we can use this conversion error free (i.e without any exceptions) to populate the respective resource id to the contact id.

A: Answer:
While the workaround provided in this answer seems to work, I think there's a more  documented way to find the People API's resourceName based on the contactId.
This contactId is part of the Person resource, as long as the connection is coming from CONTACTS.
More specifically, this information can be found as part of the resource at:
{
  "resourceName": "people/c...",
  "metadata": {
    "sources": [
      {
        "type": "CONTACT",
        "id": "CONTACT_ID" // Converting to decimal and adding "people/c" results in resource name
      }
    ]
  }
}

Therefore, if you have an array of valid contactId, you could find the corresponding resourceNames by listing your connections (see people.connections.list) and checking whether the contactId matches the id in the nested field and retrieving the resourceName for that connection if that's the case.
Code sample:
For example, using Apps Script, you could retrieve a mapping of contactId and resourceName, like this:
function getResourceNamesFromContactIds(contactIds) { // contactIds: array with valid contactIds
  const resourceName = "people/me";
  const optionalArgs = {
    personFields: "metadata",
    sources: "READ_SOURCE_TYPE_CONTACT"
  }
  const connections = People.People.Connections.list(resourceName, optionalArgs)["connections"];
  const mapping = contactIds.map(contactId => {
    const foundConnection = connections.find(connection => {
      return contactId == connection["metadata"]["sources"][0]["id"];
    });
    if (foundConnection) {
      return {
        contactId: contactId,
        resourceName: foundConnection["resourceName"]
      }
    }
  }).filter(el => el);
  return mapping;
}

A: The accepted answer doesn't work for contacts that don't have email addresses.
There's no need to get the metadata object from person.emailAddresses, we can get it directly from the person object which doesn't require any other field to be present in the person's info.
Also, the accepted answer assumes the first source is always of type "CONTACT" which may not be the case, in which case you might get the wrong contact-id
Here's the improved version (in Java):
List<Person> people = getPeople();// fetch all pages of the user contacts, with "personFields" set to "metadata" only.

Map<String, String> mapping = new HashMap<>();

people.forEach(person -> {
    PersonMetadata metadata = person.getMetadata();
    if (metadata != null) {
        List<Source> sources = metadata.getSources();
        if (sources != null) {
            sources.stream()
                .filter(srcObj -> "CONTACT".equalsIgnoreCase(srcObj.getType()))
                .findFirst()
                .ifPresent(source ->
                    mapping.put(source.getId(), person.getResourceName()));
        }
    }
});


text:
Q: Opacity toggle three (or more) DIV

Some Text 1

Some Text 2

Some Text 3

They are presented in a row. All I want is automatically cycle the three text by toggling opacity, ie. at first text 1 is opacity 1, and test 2 and 3 are opacity .5. Then after 5 seconds or so, text 2 is opacity 1, and text 1 and three are opacity .5... so on in a cycle.
Can someone give me a hint/direction on how to do this in jquery please. Thank you in advance.


text:
Q: CSS (hover): How to change all elements (in one 'box') in some way but one element in another way? I'm working with XML and CSS. I need to add different shadowing for one of the parent's elements by mousing over this parent (box). But I can only use CSS. Is it possible to do that?
I was trying by adding hover selector for this specific element (as parent's (box's) child) but still shadowing only showed when I moused over this text.
I tried also some :not(:hover) things but this is also not the effect I want.
<registration>
    <worker ID_worker="115">
        <name>Name</name>
        <surname>Surname</surname>
        <date_of_birth>14-05-1980</date_of_birth>
    </worker>
    <activity_type type="4">
        <activity>Some activity</activity>
        <details>Some details</details>
    </activity_type>
    <date>05-29-2019</date>
    <duration>8:12:18</duration>
</registration>

registration:hover {
    background-color: RGB(13, 21, 25);
    text-shadow: 0 0 2px #FFFFFF;
    border-color: #FFFFFF;
}

This code provides changing background, border and adding shadow for whole text in XML's 'registration' when I mouse over registration box. But now I need text in 'activity_type' to have different color of shadow. Again - I can only use CSS.
Would be grateful if someone just tell me is it reachable in CSS?


text:
Q: Angular 2 - Form element value set by JQuery code is not being submitted with other manually entered form data I have designed an angular 2 app that allows a user to create a new recipe by filling in a html form. If the user manually enters values into the form, then when clicking the submit button all these values are passed to my service code. The problem is that I have a form element that is updated by a JQuery script before the submit button is pressed, but when clicking the submit button and then viewing the content of the submitted form data this form element has no value. I really do not understand why because I can physically see the value in the form on my screen. If I manually enter a value into this form element then the data is correctly submitted in the form data.
Below is my HTML (The element that has its value set by JQuery is the  element id="image_id""):-

    <form [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">

            Name

            <input name="name" formControlName="name" type="text" class="form-control" required />

Name is required

            Image

            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input name="image_id" formControlName="image_id" type="text" class="form-control" id="image_id" />

            <button class="btn btn-primary" type="submit" [disabled]="!create_recipe_form.valid">
                 Create
            </button>

    </form>

My Angular 2 component file looks like this:-
import { Component, Input, Output, EventEmitter, OnInit, ElementRef } from

'@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs/Observable';

import { CategoryService } from '../category.service';
import { RecipeService } from '../recipe.service';
import { DifficultyService } from '../difficulty.service';
import { IngredientService } from '../ingredient.service';
import { ImageService } from '../image.service';

import { Recipe } from '../recipe';
import { Category } from '../category';
import { Difficulty } from '../difficulty';
import { Ingredient } from '../ingredient';

import $ from "jquery";

@Component({
  selector: 'app-create-recipe',
  templateUrl: './create-recipe.component.html',
  styleUrls: ['./create-recipe.component.css'],
  providers: [RecipeService, ImageService]
})

export class CreateRecipeComponent implements OnInit {

  create_recipe_form: FormGroup;

  @Output() show_read_recipes_event = new EventEmitter();

  imageId: number;

  constructor(
    private _recipeService: RecipeService,
    private _imageService: ImageService,
    formBuilder: FormBuilder,
    private elem: ElementRef
  ) {
    this.create_recipe_form = formBuilder.group({
      name: ["", Validators.required],
      description: ["", Validators.required],
      image_id: ''

    });
  }

  ngOnInit() {

  }

  createRecipe(): void {
    this._recipeService.createRecipe(this.create_recipe_form.value)
      .subscribe(
        recipe => {
          console.log(recipe);
          this.readRecipes();
        },
        error => console.log(error)
      );
  }

  readRecipes(): void {
    this.show_read_recipes_event.emit({ title: "Read Recipes" });
  }

  uploadImage(e) {
    let files = this.elem.nativeElement.querySelector('#selectFile').files;
    let formData = new FormData();
    let file = files[0];

    formData.append('selectFile', file, file.name);

    this._imageService.uploadImage(formData)
      .subscribe(
        image => {
          console.log(image);
          this.addImageIdToHtml(image)

          e.preventDefault();
          e.stopPropagation();
        },
        error => console.log(error)
      );
  }

  addImageIdToHtml(image){
    this.imageId = image[0];
    $("#image_id").val(this.imageId);
    $("#image_id").text(this.imageId);
  }

}

A: jQuery manipulates the DOM directly, but in the case of an Angular form, you create and destroy form instances, and modifying the DOM does not necessarily mean changing the form instance values. I suggest you use Angular's own function to manage form value changes. Try change your addImageIdToHtml to the following:
addImageIdToHtml(image){
    this.imageId = image[0];
    this.create_recipe_form.patchValue( {
        "image_id" : this.imageId
    } );
}


text:
Q: Bounds for die roll Given a $n$-sided fair die, show that the probability $P$ that all faces from $1$ to $11$ show when doing $3n$-rolls is bounded by
$1 - 11 \cdot \frac{(n-1)^{3n}}{n^{3n}} \leq P \leq 1 -  11 \cdot \frac{11(n-1)^{3n}}{n^{3n}} + 5 \cdot 11 \cdot \frac{(n-2)^{3n}}{n^{3n}}$
I am really stuck on this one. I figured that the exact probability is very hard to find and stirling numbers are involved. So the only chance I have is to figure out what events where used for that bounds. My guess is that the left one comes from the assumtion that (Edit: Warning this is not quite correct, check the comments)
$\mathbb{P}($Faces 1-11 don't occur at all$)=\frac{|E|}{|Q|}=\frac{11 \cdot (n-1)^{3n}}{n^{3n}}$
And if you look at the complement it is that all faces 1-11 at least occur once. Surely this is a lower bound but how could I get the upper bound, I hope that I did not overlook something very easy.

A: The answer can be arrived at via a pretty standard application of the Bonferroni inequalities. We generalize this problem ever so slightly. Fix $1 \leq m \leq n$ and $M \geq m$. We want to find the probability of seeing each element of the set $\{1,\ldots,m\}$ within $M$ rolls of our $n$-sided die.
Let $A_i$ be the event that the $i$th outcome was not rolled in the first $M$ throws of the die. Let $A = \cup_{i=1}^m A_i$ be the event that not all of $\{1,\ldots,m\}$ are seen in the first $M$ throws. We are interested in the complement, $\bar{A}$, of this event.
A straightforward application of the Bonferroni inequalities shows that
$$
\renewcommand{\Pr}{\mathbb{P}}
\sum_{i=1}^m \;\Pr(A_i) - \sum_{1 \leq i < j \leq m} \Pr(A_i \cap A_j) \leq \Pr(A) \leq \sum_{i=1}^m \;\Pr(A_i) \> .
$$
But, $\Pr(A_i) = (1-1/n)^M$ for each $i$ and $\Pr(A_i \cap A_j) = (1-2/n)^M$ for each pair $i \neq j$. This yields
$$
m\Big(1-\frac{1}{n}\Big)^M - \frac{m(m-1)}{2}\Big(1-\frac{2}{n}\Big)^M \leq \Pr(A) \leq m \Big(1-\frac{1}{n}\Big)^M
$$
Using the fact that $\Pr(\bar{A}) = 1 - \Pr(A)$ and plugging in $m = 11$ and $M = 3 n$ gives the result.

Note that if $M$ is relatively large with respect to $n$ and $m$, then we can get an exponential bound. In particular, if, for $c > 0$, $M = n \log m + c n$, then
$$
m(1-1/n)^M = m (1 - 1/n)^{n \log m + c n} \leq e^{-c}
$$
and so the probability of seeing all elements of $\{1,\ldots,m\}$ within $M = n \log m + c n$ throws is
$$
\Pr(\bar{A}) \geq 1 - e^{-c} \> .
$$


text:
Q: Events: Check for other event with same start date and category I am using The Events Calendar and (correct me if I'm wrong) there is no checking to see if an event has a time conflict with another event that's already been entered. For example, if there is already an event with a certain start time in a category, there cannot be another event posted with the same start time and in the same category. That would be a conflict.
Is there any way I can check values in the database for start time and category when the event post is submitted, and if both those values already exist for a post, kick the user back to the Add Event page?
EDIT: Here is what I am attempting to use in the functions.php file as the original save_post hook:
add_action('save_post', 'nu_time_conflict');

function nu_time_conflict($post_id) {
    $prevent_publish = NULL;
    if (isset($_REQUEST['EventStartDate']) && isset($_REQUEST['EventStartHour']) && isset($_REQUEST['EventStartMinute'])) {
            $start_date = date( TribeDateUtils::DBDATETIMEFORMAT, strtotime($_REQUEST['EventStartDate'] . " " . $_REQUEST['EventStartHour'] . ":" . $_REQUEST['EventStartMinute'] . ":00") );
    } else {
        die('Ingen datum valde.');
    }
    if (isset($_REQUEST['EventEndDate']) && isset($_REQUEST['EventEndHour']) && isset($_REQUEST['EventEndMinute'])) {
            $end_date = date( TribeDateUtils::DBDATETIMEFORMAT, strtotime($_REQUEST['EventEndDate'] . " " . $_REQUEST['EventEndHour'] . ":" . $_REQUEST['EventEndMinute'] . ":59") );
    } else {
        die('Ingen datum valde.');;
    }
    //Query post type 'tribe_events' to check for posts whose meta values match the POSTed ones
    $args = array(
      'post__not_in'=> array($post_id),
      'post_type' => 'tribe_events',
      'post_status' => array('publish','pending','future','private'),
      'meta_query' => array(
          'relation' => 'OR',
          array(
            'key' => 'EventStartDate',
            'value' => array(strtotime($start_date),strtotime($end_date)),
            'compare' => 'BETWEEN'
          ),
          array(
            'key' => 'EventEndDate',
            'value' => array(strtotime($start_date),strtotime($end_date)),
            'compare' => 'BETWEEN'
          )
      )
    );
    $existingMeta = get_posts( $args );

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
     return;

    if(empty($existingMeta)){
        remove_action('save_post', 'nu_time_conflict');
        wp_update_post(array('ID' => $post_id, 'post_status' => 'pending'));

        $current_user = wp_get_current_user();

        $user_mail = $current_user->user_email;
        $admin_email = get_option('admin_email');
        $type = get_post_type( $post_id );

        if (( !wp_is_post_revision( $post_id )) && ($type = 'tribe_events' )) {

                    $to = array($user_mail, $admin_email);
                    $subject = 'Ny bokning';
                    $message = $current_user->user_firstname.' '.$current_user->user_lastname.' har skapat en ny bokning.
';
                    $message .= 'För att redigera gå in på ' .get_permalink($post_id).'

';
                    $message .= 'OBS! Bokningen är inte giltig utan att bli bekräftad av administratören.';
                    wp_mail($to, $subject, $message );
            }

        add_action('save_post', 'nu_time_conflict');
        $prevent_publish = FALSE;
    } else {
       $prevent_publish = TRUE;
    }

    if ($prevent_publish) {
            remove_action('save_post', 'nu_time_conflict');
            wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
            add_action('save_post', 'nu_time_conflict');
        }

    }

And here would be my redirect and custom message:
add_filter('redirect_post_location','nu_redirect_location',10,2);

    function nu_redirect_location($location,$post_id){
        if (isset($_POST['publish'])) {
            $status = get_post_status( $post_id );

            if($status=='draft'){
                $location = add_query_arg('message', 10, $location);
        }
        }
        return $location;
    }

        add_filter('post_updated_messages', 'nu_custom_messages');

        function nu_custom_messages($messages){

            $messages['tribe_events'][10] = 'Den valda tiden är inte tillgänglig. Välj ny tid';

          return $messages;
        }

It either isn't doing the comparison to check if those dates exist, or there is something wrong with my IF statement. It thinks all entries are valid and sends emails, and I am purposefully putting wrong ones in. So the posts aren't being marked as drafts, and the message is the one for a successful post. (The emails are also sent when the page is loaded, before any data is sent. What is with that? Should I not be using save_post?)
Any help is greatly appreciated. Since The Events Calendar has no availability function as far as I can tell, getting this to work would be perfect.


text:
Q: Difference between two features of vector What would be the difference between:
std::vector::erase

and
std::vector::clear

What I want to do is to get rid of all elements, positions, including memory addresses and having no exception thrown.
vector<array<double,1000>> S1(1000);

I would like at the end to get rid of the 1000*2 created memory addresses.

A: erase gets rid of elements selectively by position. clear gets rid of all elements unconditionally, and can be considered syntactic sugar for a call to v.erase(v.begin(),v.end());

A: The only sure way to release the memory that I can think of is to swap with a temporary vector:
vector<array<double,1000>> S1(1000);
...
vector<array<double,1000>>().swap(S1);

Although this might look strange at first, it is a known, widely used idiom.
In C++11, moving from the original vector might be an option, although it is not guaranteed to clear the memory or even clear the vector (I cannot think of a reason why an implementation wouldn't do that though):
{
  vector<array<double,1000>> tmp(std::move(S1));
} // tmp dies on exiting scope, memory is cleared

Altenratively, a call to std::vector::shrink_to_fit could result in memory de-allocation, but there are no guarantees:
S1.clear();
S1.shrink_to_fit();

A: Erase lets you specify begin and end positions whereas clear clears the whole Vector.
http://www.cplusplus.com/reference/vector/vector/erase/
http://www.cplusplus.com/reference/vector/vector/clear/

A: The function clear() empties the vector. The function erase() removes selective elements (there are several overloads). erase(v.begin(), v.end()); is equivalent to calling clear();. The created memory will still be reserved for possible future use. If you want to be sure to free all this memory, then call v.clear(); and then v.shrink_to_fit(), if you have a C++11 compiler. (There's no actual guarantee that the memory will be freed, it's just a request, but I don't know of any compiler which doesn't free the memory.) If you don't have C++11 compliance then use the alternative std::vector<std::array<double,1000>>().swap(v);. That's called the shrink to fit idiom.

A: v.erase(v.begin(),v.end()) is equivalent to v.clear() where v is an object of any vector. Here clear will be used for delete all the vector elements but erase can we used to delete any specific element or range of element.


text:
Q: Access Outlets from a different class So heres my issue. I assume its a simple one but i just cannot figure out why this is not working.
I need to access Outlets (UITextField, UITableView, UIActivityIndicatorView, etc.) in one class (RootViewController) from a different class (ServiceController).
I have this currently (only showing whats need) :
RootViewController.h
@interface RootViewController : UIViewController{
    UITextField *textField;
}

@property (nonatomic, retain) IBOutlet UITextField *textField;

- (void)startService;

@end

RootViewController.m
@implementation RootViewController

@synthesize textField;

- (void)startService{
    ServiceController *service = [[ServiceController alloc] init];
    [service start];
    [service release];
}

@end

ServiceController.h
@class RootViewController;

@interface ServiceController : NSObject{
}

@property (nonatomic, retain) IBOutlet RootViewController *rootViewController;

- (void)start;

@end

ServiceController.m
#import "RootViewController.h"

@implementation ServiceController

@synthesize rootViewController;

- (void)start{
    [((RootViewController*)rootViewController).textField setText:@"HELLO !"];
    NSLog(@"CALLED !");
}

@end

I do not see why this is not working, i use the same method to do the same thing from the RootViewController to the DetailViewController and it works fine. I checked to see if there were any other declaration in the detail/root controllers to allow that to work but i did not notice any.
PS: everything is being called successfully and "CALLED !" is being logged, just whatever i do to the outlet(s) has no effect.

A: It looks like you didn't set the rootViewController.
Try adding :
ServiceController *service = [[ServiceController alloc] init];

// set the property here
[service setRootViewController:self];

[service start];
[service release];

A: Your ServiceController needs to have its rootViewController property set. You can either do this in an XIB file or explicitly in code:
myServiceController.rootViewController = myRootViewController;


text:
Q: How to define static Map for whole spring mvc application I'm a newbie with java spring mvc framework. Please tell me how to define static map variable for whole spring mvc application.
In my case, I have some catalog as :

*

*user status catalog: enable, disable;

*project status catalog as  started, working, done...

I want to set there catalogs as global constant in my application. But i don't know how.
Thank for any help!

A: You can declare two lists (under the util namespace) and a map.
<!-- a list that holds the user status values -->
<util:list id="userStatus">
    <value>enable</value>
    <value>disable</value>
</util:list>

<!-- a list that holds the project status values -->
<util:list id="projectStatus">
    <value>started</value>
    <value>working</value>
    <value>done</value>
</util:list>

<util:map id="myMap" map-class="java.util.HashMap">
    <entry key="userStatuses"><ref bean="userStatus"/></entry>
    <entry key="projectStatuses"><ref bean="projectStatus"/></entry>
</util:map>

Note that the three of them are valid Spring beans with a (default) scope of singleton, which means a single instance of theirs will be shared across the application.


text:
Q: heroku staging or new app in heroku for staging? What are thoughts around creating a staging environment for my app or should i create a second app on heroku for staging? Which one is better, or preferred?
Thanks.

A: Second app - add the git remote of the new app to your repo so you can deploy to it from a single code base.
Read more at https://devcenter.heroku.com/articles/multiple-environments


text:
Q: Botman yii2. Properties of the conversation lost BotMan Version: 2.1
PHP Version:7.3
Messaging Service(s):
Cache Driver: SymfonyCache
Description:
I trying to have conversation. In every next method I lost data from conversation properties, that was saved in properties before!
class GetAlertDataConversation extends AppConversation
{
   public $bot;

   public $alertTitle;

   public $alertDescription;

   public $alertLatitude;

   public $alertLongitude;

   public $alertAuthorId;

   public $alertAuthorName;

   public function __construct($bot)
   {
      $this->bot = $bot;
   }

   private function askTitle()
   {

      $this->ask('Что случилось? (кратко)', function (Answer $answer) {
         $this->alertTitle = $this->askSomethingWithLettersCounting($answer->getText(), 'Слишком коротко!', 'askDescription');
         \Yii::warning($this->alertTitle);
      });
   }

   public function askDescription()
   {

      $this->ask('Расскажи подробней!', function (Answer $answer) {
         $this->alertDescription = $this->askSomethingWithLettersCounting($answer->getText(), 'Слишком коротко!', 'askLocation');
         \Yii::warning($this->alertTitle);
      });
   }

   private function askLocation()
   {
      \Yii::warning($this->alertTitle);
      $this->askForLocation('Локация?', function (Location $location) {
         // $location is a Location object with the latitude / longitude.
         $this->alertLatitude = $location->getLatitude();
         $this->alertLongitude = $location->getLongitude();
         $this->endConversation();
         return true;
      });
   }

   private function endConversation()
   {
      \Yii::warning($this->alertTitle);
      $alertId = $this->saveAlertData();
      if ($alertId)
         $this->say("Событие номер {$alertId} зарегистрировано!");
      else
         $this->say("Ошибка при сохранении события, обратитесь к администратору!");
   }

   private function saveAlertData()
   {

      $user = $this->bot->getUser();
      $this->alertAuthorId = $user->getId();
      $this->alertAuthorName = $user->getFirstName() . ' ' . $user->getLastName();

      $alert = new Alert();
      \Yii::warning($this->alertTitle);
      $alert->name = $this->alertTitle;
      $alert->description = $this->alertDescription;
      $alert->latitude = $this->alertLatitude;
      $alert->longitude = $this->alertLongitude;
      $alert->author_id = $this->alertAuthorId;
      $alert->author_name = $this->alertAuthorName;
      $alert->chat_link = '';
      $alert->additional = '';
      if ($alert->validate()) {
         $alert->save();
         return $alert->id;
      } else {
         \Yii::warning($alert->errors);
         \Yii::warning($alert);
         return false;
      }
   }
}

There is user's text answer in the first \Yii::warning($this->alertTitle); in the askTitle() function.
But all other \Yii::warning($this->alertTitle); returns NULL!!!!
As the result, saving of Alert object not working!
Please, help me. Some ideas?
I think, that it can be by some caching + serialise problem.
I was trying to change cache method to Redis. Same result.

A: Problem was in this function call and caching:
$this->askSomethingWithLettersCounting($answer->getText(), 'Слишком коротко!', 'askDescription');

If you will read other conversation botman issues in github, you wil see, that most of issues in conversation cache and serialise.
Not any PHP code of conversation can be cached right.
In this case, not direct call of functions askDescription() and askLocation() broken conversation caching.
I fixed that by removing askSomethingWithLettersCounting() function.


text:
Q: How to move cursor into text node and make it editable if there is no preexisting content using Range and Selection Objects? I am trying to make text changes based on when the user clicks the "bold" button using the Range and Selection Objects. When the text node is empty, the range that I have set using setStart() and setEnd() seems to not be working because the cursor does not move into the text node, but rather stays at its initial text node that is already given within my contenteditable div. However, If I add some preexisting content to the text Node, the range is correct,the cursor moves into the newly-created text node, and the content is bold as well as my additional input. So how do I get the cursor to go into the text Node without any content? Thanks.
Here is a code snippet:
function setBold() {
    let parent = document.querySelector('.current'); /*contenteditable parent element*/
    let sel = window.getSelection();
    let selRange = s.getRangeAt(0);
    let bold = document.createElement('b');
    let range = document.createRange();
    /*if the node has content this solution works, but in this example it does not currently*/
    let node = document.createTextNode("");
    parent.appendChild(node);
    range.setStart(node,0);
    range.setEnd(node,node.length);
    range.surroundContents(bold);
    sel.removeAllRanges();
    sel.addRange(range);
}


text:
Q: ASP HttpWebRequest and Redirect OK, I have a client doing a POST to a server with some data. The server receives the post, and answers with a redirect. The problem is that the client does not redirects. Also, I've tried to check the StatusCode of the response the client gets, and it is always the same "OK". Instead of the redirect code. What am I missing?
In the client side I have something like this:
  StringBuilder sb;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/serv/Default.aspx");
            request.Method = "POST";

        byte[] data = Encoding.ASCII.GetBytes(GetDATA());

        request.ContentType = "text/xml";
        request.ContentLength = data.Length;
        Stream stream = request.GetRequestStream();
        stream.Write(data, 0, data.Length);

        request.AllowAutoRedirect = true;
        request.MaximumAutomaticRedirections = 10;

        HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            response.Close(); } catch(Exception ex) {}

In the server side I have just this line:
HttpContext.Current.Response.Redirect("http://www.google.com", true);

In this case, the client receives an answer and does not do nothing.
Thanks.

A: When you have "AllowAutoRedirect" set to true, it means that your HttpWebRequest object will make a 2nd webrequest once it sees a redirect.  When you see the "200 OK" from the response object, it is because you are seeing the response for "www.google.com".  You can check the Response.ResponseURI to verify this.
You'll need to turn off the "AllowAutoRedirect", then check the response code like Oded said.


text:
Q: How to disable modal closing when clicking outside? [Materialize] I have a materialize modal and I would like to know how to disable the closing of it when you click away. Follow my code:

Histórico de Calibração

          <button
            class="btn waves-effect waves-light col-sm-1 col-md-2 col-lg-2 close-modal"
            type="reset"
            id="fx"
            name="action"
            href="#"
            v-on:click="exitModal"
          >Fechar
            clear
          </button>

A: You can set this and many other modifications during initialisation:
// with jQuery

$('.modal').modal({
   dismissible: false
});

// Vanilla JS

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems, {
       dismissible: false
    });
});


text:
Q: Percentage change in velocity So, if i have a building that takes 2 days and 4 hours to construct e.g., and i'm going 40% faster than the iniciall time that would have take to build this building, how much time is inicial one, plus, if I'm going 45% faster, how much time would reduce ?

A: So assuming you work constantly without stopping, it takes 52 hours to build  going 40% faster you can simply use a inverse proportion, where 140*52=x*100 where x is the time it takes to build at normal speed, which in this case x=72.8 hours. To check for other speed just replace the 140 with the new percentage, just remember to add 100 as you are going x% faster plus the initial speed.


text:
Q: Where is getResourceAsStream("file") searching when running from a test? I'm struggling to create a test to verify a ServletListener that loads a properties file. I've tested when running the application that it works fine and it finds the file in the classpath. But I don't know how to create a test for it. My idea is to create a temp file with a test property and then verify the property is put into the System properties. But I always fail to create the file in the right place.
I've tried creating the file in /target/test-classes or directly in the root of the application but it never finds it. Any idea?
This is the code I'm trying to test:
public class PropertyReadingListener implements ServletContextListener {

    public static final String PROFILES_PROPERTIES = "profiles.properties";

    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        Properties propsFromFile = new Properties();
        try {
            propsFromFile.load(getClass().getResourceAsStream(PROFILES_PROPERTIES));
        } catch (final Exception e) {
            log.warn("Unable to find {}, using default profile", PROFILES_PROPERTIES);
        }
        propsFromFile.stringPropertyNames().stream()
            .filter(prop -> System.getProperty(prop) == null)
            .forEach(prop -> System.setProperty(prop, propsFromFile.getProperty(prop)));
    }
}

Thanks.

A:
Where is getResourceAsStream("file") searching when running from a test?

Assuming that you are talking about JUnit ....
Unless you have done something funky, your unit tests will be loaded by the default classloader, and that means that the normal JVM classpath with be searched.
(Junit 4 allows you to use a different classloader: see https://stackoverflow.com/a/9192126/139985)

But I always fail to create the file in the right place.

It seems that your real problem is understanding how the Java classpath and classpath searching works.  If you understand that (and you know what JUnit runner's actual classpath is) then it should be obvious where to put the properties file so that the classloader can find it.

A: Assuming that you are using maven, put your properties file here:
src/test/resources/foo.properties

The maven resources plugin will place the (possibly filtered) copy of the file in
target/test-classes/foo.properties

The test-classes directory is on the classpath, so you reference the file like this (note the slash in front of the file name):
... getResourceAsStream("/foo.properties");

A: See Different ways of loading a file as an InputStream
Basically when you do a getClass().getResourceAsStream it looks in the package of that class for the file.. so if your PropertyReadingListener is in com.company.listeners.PropertyReadingListener then it will look in com/company/listeners for the property file.
For testability, I would pass in an InputStream into the listener that way the test can create the input stream in a convienent way and the actual user of the class in code can pass in the InputStream returned from getResourceAsStream


text:
Q: Android-Things: Migrate gpiocallback functions to suspendcoroutine functions Following the example in the photo below, I want to migrate a function with callback to a SuspendCoroutine function:

1) Is it possible to transpose the code below to SuspendCoroutine? (I ask why there may be reserved codes from the library, type: onGpioEdge and registerGpioCallback.
2) How can I do this?
class ButtonActivity : Activity() {
  // GPIO port wired to the button
  private lateinit var buttonGpio: Gpio
  // Step 4. Register an event callback.
  private val callback = object : GpioCallback() {
    fun onGpioEdge(gpio: Gpio): Boolean {
      Log.i(TAG, "GPIO changed, button pressed")
      // Step 5. Return true to keep callback active.
      return true
    }
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val manager = PeripheralManager.getInstance()
    try {
      // Step 1. Create GPIO connection.
      buttonGpio = manager.openGpio(BUTTON_PIN_NAME)
      // Step 2. Configure as an input.
      buttonGpio.setDirection(Gpio.DIRECTION_IN)
      // Step 3. Enable edge trigger events.
      buttonGpio.setEdgeTriggerType(Gpio.EDGE_FALLING)
      // Step 4. Register an event callback.
      buttonGpio.registerGpioCallback(mCallback)
    } catch (e: IOException) {
      Log.e(TAG, "Error on PeripheralIO API", e)
    }
  }

  override fun onDestroy() {
    super.onDestroy()
    // Step 6. Close the resource
    if (buttonGpio != null)
    {
      buttonGpio.unregisterGpioCallback(mCallback)
      try {
        buttonGpio.close()
      } catch (e: IOException) {
        Log.e(TAG, "Error on PeripheralIO API", e)
      }
    }
  }

A: That's an interesting idea, but I'm not sure coroutines are the best fit for GPIO.
Coroutines work great for asynchronous operations that return a value, such as API calls. GPIO is more of al listener that can happen at any time, it's a different type of callback. I would compare it to onClickListeners, and I don't think those are a good fit for coroutines either.


text:
Q: How can a web page run a program on client's computer? I developed a web software with Visual Studio. Within this web software when I click on a button, the user's computer should run an application given as an .exe file. This application is a console application and it needs to receive commandline parameters.
I've tried to run it with Javascript, but it was removed due to security issues.
     Dim startInfo As New ProcessStartInfo("C:\ProgramAdres\Program.exe")
     startInfo.WindowStyle = ProcessWindowStyle.Normal
     startInfo.Arguments = "arguments"
     Process.Start(startInfo)

This code successfuly runs the application, but on the server side. I need your help because I do not know ActiveXand don't know how to start.


text:
Q: How to find the HTML element id of text field pop up window? I am trying to automate browser using Selenium in Java. However I am unable to find the element ID of a text field in pop up window to call it in Selenium Java.
The text field whos HTML element ID that I am trying to find is Project (as seen in attached photo)
Selenium script:
driver.findElement(By.id("project-name")).sendKeys("TEST: Automatation by Selenium");

Any suggestions?

A: This works for me:
driver.findElement(By.id("project-field")).sendKeys("TEST: Automatation by Selenium");

Are you sure that the id is project-name and not project-field? In my Jira template project-field is used as id.


text:
Q: What is this usage of "have [Object] [Complement]?" I hate Bush but I would rather have him president than Obama !
It is normal to expect it to be followed by a verb or past participle or present participle, but here it is not. is this archaic?

A: I'm not sure what you mean by 'it' in your question. I assume you mean 'the word "have"'. Yes, 'have' is used as an auxiliary verb followed by V-pp to form perfect tenses, but here it is the main verb (we know that because it's the last verb in the verb group 'would rather have').
One possible but lesser used (and certainly not archaic) clause type in English is subject (here, 'I' - verb ('would rather have') - object ('him') - object complement ('president'). A simpler sentence is: 'They elected him president'. (In both sentences, is it also possible to say 'as president', and even possible to leave out 'president' - 'I would rather have him than Obama (as president, as next-door-neighbour etc)' and 'They elected him' (true, but my first question is going to be 'as what?')
If you said 'I would rather have elected him president', 'have' becomes an auxiliary verb and 'elected' is the main verb.


text:
Q: Client SMTP Submission on IIS I've got 2 IIS servers: "Local" IIS" that runs on my network and "Remote IIS" located on other network. Both IIS servers have exactly the same application installed used to send e-mails. An email used to send messages is from Exchange Online, Microsoft 365. Following the guide Configure Send Submission:  I have configured "SMTP submission" for this email address, however, it only works from "Local IIS" and not from "Remote IIS", not sure why.
Remote IIS: Windows 2012R2, IIS 8
Local IIS, windows 10 Pro; IIS 10
There is nothing that blocks outgoing port 587 on "Remote IIS". For testing purposes my colleague created a simple app, that runs independently from IIS , that also sends email and it works fine using the same Exchange Online user. The problem seems to be on IIS server on that server. Any ideas why "Remote IIS" does't send email?
The error is:
ERROR: Code: GeneralFailure Trace: en System.Net.Mail.SmtpClient.Send(MailMessage message)   en Forms_Login.btopepe_Click(Object sender, EventArgs e) Message: Error al enviar correo.


text:
Q: myql: sum up each day's sell total for each store the table is:
mysql> DESC sell_data;
+------------+--------------+------+-----+---------------------+----------------+
| Field      | Type         | Null | Key | Default             | Extra          |
+------------+--------------+------+-----+---------------------+----------------+
| id         | int(64)      | NO   | PRI | NULL                | auto_increment |
| name       | varchar(128) | NO   |     |                     |                |
| sell_date  | datetime     | NO   |     | 0000-00-00 00:00:00 |                |
| sell_price | double       | YES  |     | NULL                |                |
| cost       | double       | NO   |     | 0                   |                |
| store_id   | int(11)      | NO   |     | 0                   |                |
+------------+--------------+------+-----+---------------------+----------------+

I attached the table struct as a picture, looks like the editor does support the format well.
There are 100 records in this table, and request to sum up each day's sell total in a given week for each store, which means for each given store id, need 7 subtotals, the result would be like:

store 1: 122  123  124  125  126  127  128
store 2: 131  122  133  134  135  136  137

....
this is very diffcult for me, request help, much apperaciated.
:)
I tried to group the data by "GROUP BY", like:
SELECT store_id
     , SUM(cost) AS all_cost
     , SUM(sell_price) AS all_price
FROM sell_data
WHERE sell_date BETWEEN '2017-10-12' AND '2017-10-15'
GROUP BY store_id;

but it only gives the sum data for each store, not data for each day, totally stuck here.

A: Looks to me you going to need a pivot query.
This is done by using GROUP BY in combination with SUM and CASE
SELECT
   SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Monday'
      THEN sell_price
      ELSE 0
    END
   )
    AS
     Monday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Tuesday'
      THEN sell_price
      ELSE 0
    END
 )
  AS
   Tuesday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Wednesday'
      THEN sell_price
      ELSE 0
    END
 )
  AS
   Wednesday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Thursday'
      THEN sell_price
      ELSE 0
    END
 )
  AS
   Thursday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Friday'
      THEN sell_price
      ELSE 0
    END
 )
  AS
   Friday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Saturday'
      THEN sell_price
      ELSE 0
    END
 )
  AS
   Saturday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Sunday'
      THEN sell_price
      ELSE 0
    END
 )
  AS
   Sunday
FROM
 [table]
WHERE
 WEEK(sell_date) = [week_number]
GROUP BY
 store_id
ORDER BY
 store_id ASC

A: You need to
 group by store_id, date(sell_date)

You probably want to add that to your select too

A: Use sum(sell_price) with group by store_id


text:
Q: How to read and print PropertiesServices from client-side HTML with Google Apps Script? The foo variable is sent from the client side HTML to Code.js as demonstrated by the logs.  When this occurs, the bar key from PropertiesService is set and logged.
How is PropertiesServices accessed from the client side HTML and output as text?
logs:
Cloud logs
Oct 15, 2022, 5:27:14 PM
Info
logProperties..
Oct 15, 2022, 5:27:14 PM
Info
bar
Oct 15, 2022, 5:27:14 PM
Info
foo
Oct 15, 2022, 5:27:14 PM
Info
sending foo

html:
<!DOCTYPE html>

    <base target="_top">

    foo is:<input type="text" id="foo" />
    <input type="button" value="sendFoo" onclick="sendFoo()" />

    bar is:

I believe this can be accomplished with span tag.
code:
function setBar(foo) {
  PropertiesService.getScriptProperties().setProperty("foo",foo);
  PropertiesService.getScriptProperties().setProperty("bar","foo received");
  logProperties();
}

function initProperties() {
  PropertiesService.getScriptProperties().deleteAllProperties();
}

function logProperties() {
  Logger.log("logProperties..");
  var keys = PropertiesService.getScriptProperties().getKeys();
  keys.forEach(key => {
    Logger.log(key);
    Logger.log(PropertiesService.getScriptProperties().getProperty(key));
  });
}

function getUrl() {
  var url = ScriptApp.getService().getUrl();
  return url;
}

function doGet(e) {
  initProperties();
  var htmlOutput = HtmlService.createTemplateFromFile('WebApp');
  htmlOutput.url = getUrl();
  return htmlOutput.evaluate();
}

This is just within Google Apps Script and has been kept as simple as possible, but no simpler.
see also:
https://codewithcurt.com/how-to-call-google-apps-script-function-from-web-app/

A: Less than perfect, but accomplishes the main goal of getting data from server and displaying client side when requested by the client.
code:
var sheetId = "1L3Sd-J780mQtb7JYsmJzInI1kMdrQA8GbLspQJ5eVW4";
var sheetName = "data";

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('WebApp');
}

function getOneCellData() {
  Logger.log("getOneCellData..");
  var ss = SpreadsheetApp.openById(sheetId);
  var sheet = ss.getSheetByName(sheetName);
  var data = sheet.getRange(1,1,1,1).getValue();
  return data;
}

function getMultiCellData() {
  var ss = SpreadsheetApp.openById(sheetId);
  var sheet = ss.getSheetByName(sheetName);
  var data = sheet.getRange('A1:C1').getValues();
  return data;
}

function getInOutData(inData) {
  Logger.log("getInOutData");
  var outData = "IN DATA: " + inData;
  return outData;
}

html:
<!DOCTYPE html>

  <base target="_top">

  One Cell Data
<textarea id="oneCellData" ></textarea>

  Multi Data
<textarea id="multiData" ></textarea>

  In Data
<input type="text" id="inData" />

  Out Data
<textarea id="outData" ></textarea>

  <input type="button" onclick="callData()" value="Get Data" />

I had thought this was best done with Properties but that may not be so.
Ideally, would display the above textarea as just "plain" text.


text:
Q: Getting full folder path from name I am trying to find the full path of a folder from just the name of the folder.
The folder in question is advdupe2 folder that is usually situated in \SteamLibrary\steamapps\common\GarrysMod\garrysmod\data\advdupe2 but people might have the SteamLibrary folder in different locations for example i have it on D:\steam\SteamLibrary\steamapps\common\GarrysMod\garrysmod\data\advdupe2 and it is by default on C:\Program Files\Steam\steamapps\.
I have tried searching for this everywhere but i can find no references to this.
I looking for something like string folderPath = findFolder(folderName);


text:
Q: Why javascript uncaught reference error for beautify library I'm testing https://www.npmjs.com/package/js-beautify
with
https://jsfiddle.net/pLwcv97x/
  window.addEventListener('load', (e) => {
    console.log("test");
    beautify("", { indent_size: 2, space_in_empty_paren: true })
  });

I added library in html

A: you should use js_beautify instead of beautify:
js_beautify("", { indent_size: 2, space_in_empty_paren: true })

A: There could be a number of reasons why you are getting an Uncaught Reference Error when using the Beautify library. It is possible that the library is not loaded correctly, or that there is a conflict with another library. It is also possible that the code you are using is not compatible with the Beautify library.


text:
Q: Intra company web hosting solutions with mac mini any suggestions? We have mac mini in our company and I want to host intra website.
Any suggestion for best way to host ?
I tried configuring Apache with OS X Yosemite and didn't work at all.
Setting up Apache web server on Mac OS X 10.10.5 Yosemite
After spending a day on this, I had to look for alternatives.
Thank in advance.

A: I've decided to user SimpleHTTPServer for this purpose.
http://www.andyjamesdavies.com/blog/javascript/simple-http-server-on-mac-os-x-in-seconds


text:
Q: undefined method `mechanism=' for ActiveSupport::Dependencies:Module (NoMethodError) I have a problem while generating a controller in rails 7.0.0
When I run the command
rails g controller Home index

It gives me the following error.
/home/dev/.rvm/gems/ruby-3.0.2/gems/spring-2.1.1/lib/spring/application.rb:103:in `block in preload': undefined method `mechanism=' for ActiveSupport::Dependencies:Module (NoMethodError)
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/railties-7.0.1/lib/rails/initializable.rb:32:in `instance_exec'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/railties-7.0.1/lib/rails/initializable.rb:32:in `run'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/railties-7.0.1/lib/rails/initializable.rb:61:in `block in run_initializers'
    from /home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/tsort.rb:228:in `block in tsort_each'
    from /home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
    from /home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/tsort.rb:431:in `each_strongly_connected_component_from'
    from /home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/tsort.rb:349:in `block in each_strongly_connected_component'
    from /home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/tsort.rb:347:in `each'
    from /home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/tsort.rb:347:in `call'
    from /home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/tsort.rb:347:in `each_strongly_connected_component'
    from /home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/tsort.rb:226:in `tsort_each'
    from /home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/tsort.rb:205:in `tsort_each'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/railties-7.0.1/lib/rails/initializable.rb:60:in `run_initializers'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/railties-7.0.1/lib/rails/application.rb:372:in `initialize!'
    from /home/dev/project/spousal/config/environment.rb:5:in `<main>'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/bootsnap-1.10.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/bootsnap-1.10.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/zeitwerk-2.5.3/lib/zeitwerk/kernel.rb:35:in `require'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/spring-2.1.1/lib/spring/application.rb:106:in `preload'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/spring-2.1.1/lib/spring/application.rb:157:in `serve'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/spring-2.1.1/lib/spring/application.rb:145:in `block in run'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/spring-2.1.1/lib/spring/application.rb:139:in `loop'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/spring-2.1.1/lib/spring/application.rb:139:in `run'
    from /home/dev/.rvm/gems/ruby-3.0.2/gems/spring-2.1.1/lib/spring/application/boot.rb:19:in `<top (required)>'
    from <internal:/home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
    from <internal:/home/dev/.rvm/rubies/ruby-3.0.2/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
    from -e:1:in `<main>

I have googled but found no solution. So what's the reason for this error?

A: I recently upgraded an to Rails 7.0.1 and I ran into this same issue. I saw this same error when trying to run rails console.
I got past it when I removed spring-watcher-listen from the Gemfile (because it was preventing spring from updating past 2.x) and then bumped spring to 3.0.0 in the Gemfile. Then I ran bundle and rails console worked again.
This seems like a bump we have to overcome in upgrading Rails as noted in this article under "6. Notable Changes".

A: same here, on rails g migration ... after updating to rails-7.0.4. allthough i had in my gemfile gem "spring" and ran bundle update, spring ran on 2.x.. changed it in Gemfile to gem 'spring', '~> 4.1' ran bundle and it works.

A: Faced this issue after updating a rails 6 application to rails 7.
I tried to execute the rails g model User command.
I solved it by recreating the project with rails 7 directly.
If you have an existing project that you upgraded to rails 7 you cant apply this solution. Better refer the official conversion rails guide


text:
Q: Reroute/canoncialize website domains to single domain with redirect For some reason I can't get this simple thing to work: https://www.nginx.com/blog/creating-nginx-rewrite-rules/
I have this:
`# cat sites-available/custom_default
server {
  listen 80;
  listen [::]:80;
  server_name _;
  include hardening;

  location /.well-known/acme-challenge/ {
    root /var/www/acme-challenge/;
    default_type "text/plain";
  }

  location / {
    return 301 https://$host$request_uri;
  }
}`

Which provides the ACME well-known dir over port 80 and then redirects everything else to port 443.
Then I have a bunch of vhosts:
`# ll sites-enabled/
total 0
lrwxrwxrwx 1 root root 35 sep  5 15:15 chapters -> /etc/nginx/sites-available/chapters
lrwxrwxrwx 1 root root 41 jul 15 09:21 custom_default -> /etc/nginx/sites-available/custom_default
lrwxrwxrwx 1 root root 36 jul 15 12:24 discourse -> /etc/nginx/sites-available/discourse
lrwxrwxrwx 1 root root 30 sep  5 15:15 map -> /etc/nginx/sites-available/map`

I first want to change the domain of chapters:
`# cat sites-enabled/chapters
server {
  server_name chapters.example.community;
  return 302 https://chapters.example.one$request_uri;
}

server {
  server_name chapters.example.one;

  ssl_certificate /etc/letsencrypt/live/chapters.example.community/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/chapters.example.community/privkey.pem;

  include tls_params;
  include hardening;

  location ~ /(emoji.css|index.html|list.js|main.js|resources|robots.txt|script.js|style.min.css|errorpages/example-logo.png|errorpages/sob.png|errorpages/generic_offline.html) {
    limit_except GET HEAD { deny all; }
    root /var/www/chapters;
    error_page 403 404 502 =404 /errorpages/generic_offline.html;
  }

  location /errorpages/ {
    alias /var/www/errorpages/;
  }

  location ~* \.(css|gif|jpg|js|png|ico|otf|sng|xls|doc|exe|jpeg|tgx)$ {
    access_log off;
    expires 1d;
  }
}`

For some reason this doesn't work, maybe I'm too used to Apache. I'm expecting the first server block to listen to the old domain, then redirect to the new domain. The next server block then listens to the new domain and serves the website. But now both domains work just fine, and the old domain does not redirect traffic to the new domain.
For full context, here are the included configs:
`# cat tls_params
listen 443 ssl http2;
listen [::]:443 ssl http2;

ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m;
ssl_session_tickets off;

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;

add_header Strict-Transport-Security "max-age=63072000" always;

ssl_stapling on;
ssl_stapling_verify on;

ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;`

`# cat hardening
server_tokens off;`

If I put both server names in one server block and the redirect to the new domain, I get an infinite redirect loop. My guess is that it may have to do with my custom_default block. Any thoughts?


text:
Q: Select an element with jQuery selector regardless of ID I have the following code:

Blah

Blah

and I am trying to select  in jQuery (for the accordion in jQuery UI). However, the following does not work unless I remove the ID from the div.
$('> div > h1')

Is there some way to tell the selector to ignore the ID, or am I going about this the wrong way?
Edit: The actual use I'm going for is in the sortable accordion in jQuery UI, with IDs on the div elements. An example of what I'm doing, with source, can be found here:
http://jqueryui.com/demos/accordion/#sortable

Edit: As I have a feeling this may be related to jQueryUI, rather than the selectors themselves, below is the code I'm actually trying to run.
http://jsfiddle.net/Zgkj4/1/
Working example without ID in div:
http://jsfiddle.net/Zgkj4/2/

A: You could try selecting the
 with a parent
 that has an id attribute
$("div > div[id] > h1")

working example: http://jsfiddle.net/YjSvU/

ignores div w/o id: http://jsfiddle.net/YjSvU/1/

A: Yes, your selector should be a string, like this:
$('div > h1')

A: Your selector needs to be a string, so wrap it in single (') or double quotes (").
Also > div does not make sense, as > is direct descendant / child selector, and you have no parent on the left hand side (or otherwise context). Remove the leading >.
See it not working on jsFiddle.

A: http://codylindley.com/jqueryselectors/. A list of all jquery selectors. it should help you allot.

A: Use quotes, and im not sure about the first >
This should work:
$("div > h1")


text:
Q: The induced representations of $SL(2, F)$. Let $G=SL(2,F)$ and $I=J_{0}\cap J_{1}$ be the Iwahori subgroup of $SL(2, F)$, where $J_{0}=\left(
             \begin{array}{cc}
               \mathcal{O}_{\mathbb{F}} & \mathcal{O}_{\mathbb{F}} \\
               \mathcal{O}_{\mathbb{F}} & \mathcal{O}_{\mathbb{F}} \\
             \end{array}
           \right)\cap SL(2)$ and $J_{1}=\left(
             \begin{array}{cc}
               \mathcal{O}_{\mathbb{F}}& \varpi_{\mathbb{F}}^{-1}\mathcal{O}_{\mathbb{F}} \\
                \varpi_{\mathbb{F}} \mathcal{O}_{\mathbb{F}}& \mathcal{O}_{\mathbb{F}} \\
              \end{array}
             \right)\cap SL(2)$ are the maximal compact subgroups of $SL(2, F)$. Here $F$ is a local non-Archimedean $p$-adic field, $\mathcal{O}_{F}$ is the valuation ring and $\varpi$ is the uniformizer.
Now, we know that if $\lambda^{2}= 1$, then $Ind_{I}^{G}\lambda=\lambda^{-}\oplus\lambda^{+}$. Also , we can write  $Ind_{I}^{G}\lambda=Ind_{J_{0}}^{G}(Ind_{I}^{J_{0}}\lambda)$.
Does the following equality hold?
$Ind_{I}^{G}\lambda=Ind_{J_{0}}^{G}\lambda\oplus Ind_{J_{1}}^{G}\lambda$.
I do apologize for my bad English and my bad temper to create a question.

A: I assume that $\lambda$ is a character!? How is your $\lambda$ a representation of $J_0$ or $J_1$, do you mean the induction $Ind_I^{J_k} \lambda$ instead, but the induction is never irreducible.
On some related matters on $GL(2)$:
The question whether
$ Ind_{I}^{J_i} \lambda $
splits has been answered by Silberger for $PGL(2)$ for $J_0$ and $J_1$ in odd residue characteristic, and by Casselman for $PGL(2)$ for $J_0$ in all residue characteristics.
Silberger, Allan J. Irreducible representations of a maximal compact subgroup of ${\rm pgl}_{2}$pgl2 over the $p$p-adics. Math. Ann. 229 (1977), no. 1, 1–12.
Silberger, Allan J. ${\rm PGL}_{2}$PGL2 over the $p$p-adics: its representations, spherical functions, and Fourier analysis. Lecture Notes in Mathematics, Vol. 166
Casselman, William The restriction of a representation of ${\rm GL}_{2}(k)$GL2(k) to ${\rm GL}_{2}({\germ o})$GL2(o). Math. Ann. 206 (1973), 311–318.
In these cases, the restriction induction formula $Res_{SL(2,F)} Ind^{GL(2,F)}_{J_i} \lambda =Ind_{J_i}^{SL(2,F)} \lambda$! Induction by steps imply the results, if it $ Ind_{I}^{J_i} \lambda $ splits.
I am not sure, if that is necessary, but you can look at the induction restriction formula for $Res_{J_i} Ind^{SL(2,F)}_{J_i} \lambda$ and see what happens.


text:
Q: Library resources in Android projects built with Ant In my workspace I have 3 Android projects. One core library and two projects to build two versions of my app: free and paid. Now I have several strings, which should be different in the projects. In every project I have values/strings.xml file where e.g. "@string/version" is defined as follows: "library" in library project, "free" in free project and "paid" in paid project.
If I build free and paid projects with Eclipse I get "free" and "paid" for "@string/version". Everything is OK. But if I build my projects with Ant I get ALWAYS "library" for "@string/version".
What I'm doing wrong? Any advice would be greatly appreciated.

A: When you build with Ant, use ant clean install or ant clean debug, and see if that helps.


text:
Q: Best way to translate month names I am using Codeigniter! What will be the best way to translate month names. I have a date in mysql timestamp like this:
        2012-09-22 11:21:53
I can  convert it to 'September 22, 2012' with php date() function. I want to rename 'September' to 'Sentýabr'. Can set_locale() function can do this. By the way it is Turkmen Language.
 thank you.

OK , i created some php file to check it indivudally like this:
cool.php
<?php setlocale(LC_ALL,'ru_RU');
echo strftime('%B',time());
?>

Returns September. What might be the problem.

I have
  /* Set locale to Turkmen */
  setlocale(LC_ALL, 'tk');

And
  echo strftime( '%B',time());

Result: returns September
I need it return September in my language

A: best way to translate month names to put them in language file and call it like read here how to use language files in codeigniter Language library you can use in you project over and over if you have dual language site.
$this->lang->line('September');

your english language file
$lang['january'] = 'january';
$lang['february'] = 'february';
...
$lang['September'] = 'September';

your turkish language file

$lang['january'] = 'ocak';
$lang['february'] = 'subat';
...
$lang['September'] = 'Eylül';

A: You can use str_ireplace() with arrays for names in english, and equivalent for names in turkmen, in same order.
Something like this:
$nmeng = array('january', 'february', ..);
$nmtur = array('ocak', 'subat', ...);
$dt = 'September 22, 2012';
$dt = str_ireplace($nmeng, $nmtur, $dt);

A: Use setlocale() and strftime ...
On linux run $ locale -a to find out if the needed locale is installed and to grab its name value string.
setlocale(LC_TIME, 'ru_RU');
echo strftime('%B %e, %Y', strtotime('2012-09-22 11:21:53'));

Edit:
If you use a windows server, then change %e to %d (%e does not work in windows).
echo strftime('%B %d, %Y', strtotime('2012-09-22 11:21:53'));

For windows, check here to see supported format.

A: Add this to the index.php file near the top:
/* Set locale to Turkmen */
setlocale(LC_ALL, 'tk');

Documentation for this is here: http://php.net/manual/en/function.setlocale.php
Also, @xdazz is correct that you should combine it with strftime instead of the date() function.
You may need to confirm that "tk" is used for Turkmen.


text:
Q: Subdomain not resolving to IP I created a subdomain http://themes.ibrogram.com and it doesn't seem to work, however http://ibrogram.com/themes does work.
I've had this issue for ages using an A record and can't seem to figure out how to fix it.
Any ideas?
Edit
; Domain: ibrogram.com
; Exported (y-m-d hh:mm:ss): 2011-11-26 10:57:43
;
; This file is intended for use for informational and archival
; purposes ONLY and MUST be edited before use on a production
; DNS server.
;
; In particular, you must update the SOA record with the correct
; authoritative name server and contact e-mail address information,
; and add the correct NS records for the name servers which will
; be authoritative for this domain.
;
; For further information, please consult the BIND documentation
; located on the following website:
;
; http://www.isc.org/
;
; And RFC 1035:
;
; http://www.ietf.org/rfc/rfc1035.txt
;
; Please note that we do NOT offer technical support for any use
; of this zone data, the BIND name server, or any other third-
; party DNS software.
;
; Use at your own risk.

; SOA Record
IBROGRAM.COM.   3600    IN  SOA ns49.domaincontrol.com. dns.jomax.net (
                2011112600
                28800
                7200
                604800
                86400
                )

; A Records
@   3600    IN  A   199.38.116.24

; CNAME Records
www 3600    IN  CNAME   @
mobilemail  3600    IN  CNAME   mobilemail-v01.prod.mesa1.secureserver.net
pda 3600    IN  CNAME   mobilemail-v01.prod.mesa1.secureserver.net
email   3600    IN  CNAME   email.secureserver.net
imap    3600    IN  CNAME   imap.secureserver.net
mail    3600    IN  CNAME   pop.secureserver.net
pop 3600    IN  CNAME   pop.secureserver.net
smtp    3600    IN  CNAME   smtp.secureserver.net
ftp 3600    IN  CNAME   @
webmail 3600    IN  CNAME   webmail.secureserver.net
e   3600    IN  CNAME   email.secureserver.net

; MX Records
@   3600    IN  MX  0   smtp.secureserver.net
@   3600    IN  MX  10  mailstore1.secureserver.net

; NS Records
@   3600    IN  NS  ns49.domaincontrol.com
@   3600    IN  NS  ns50.domaincontrol.com

A: You'll need to add a zone file entry with the following A record:
themes    3600    IN  A   199.38.116.24

You can verify that it resolves by typing
dig themes.ibrogram.com

Note that you still need to ensure that your web server is setup for named-based hosting. Assuming that it is Apache, it will be something like:
NameVirtualHost *:80

<VirtualHost *:80>
ServerName themes.ibrogram.com
DocumentRoot /path/to/themes
</VirtualHost>


text:
Q: Using data in classes when button pressed objective C/iOS New to iOS and I can't figure out this simple thing. (Been googling for ages)
So I've got a class which I've initiated in the ViewController.m viewDidLoad,
Student *person = [[Student alloc] init];

person.firstName = @"test";

I've created a button, and on the button pressed method I've tried to NSLog whatever's in the firstname variable but I keep getting a null result. I add the initialisation into the method and it works fine.
is there anyway I can just call the data that's been added from the viewDidLoad?
Thanks
edit:
@implementation ViewController

- (void) viewDidLoad
{
[super viewDidLoad];

    Student *person = [[Student alloc] init];

    person.firstName = @"test";

}

- (IBAction)buttonPressed:(id)sender {

NSLog(@"%@", person.firstName);
}
@end

A: You need ivar or property. For example add ivar to your .m file:
@implementation YOURCLASSNAME
{
    Student *person;
}

//... other code

-(void)viewDidLoad {
    person = [[Student alloc] init];

    person.firstName = @"test";
}
//... Later in the same file when the button event is called
-(IBAction)buttonTapped {
    NSLog(@"%@", person.firstName);
}

A: You have declared person locally to viewDidLoad so the buttonPressed: method will know nothing of it. Change to below and read comments for explanation.
MyViewController.h
@interface MyViewController : UIViewController

// No need to create ivar as this is done for you automatically
// Declaring this property here will make it public if you don't want it public
// so code above @implementation
@property (nonatomic, strong) Student *person;

- (IBAction)buttonPressed:(id)sender;

@end

MyViewController.m
@interface MyViewController()
// Doing it here will make it private to this class only.
// @property (nonatomic, strong) Student *person;
@end

@implementaiton MyViewController

// No need for @synthesize as this is now done automatically as well
// Because @synthesize is called automatically you can just use _person or self.person

- (void)viewDidLoad
{
    // Initialization of the person instance
    _person = [[Student alloc] init];
    // Setting the firstName of the person instance
    _person.firstName = @"Test";
}

- (IBAction)buttonPressed:(id)sender
{
    // NSLog the firstName
    NSLog(@"Student's first name : %@", _person.firstName);
}

@end

A: What about you make the person a property.
In your controller header file
@interface Controller: UIViewController
@property (nonatomic, retain) Student *person;
@end

And in your controller implementation file
@implementation
@synthesize person;
@end

This way the person property should be visible to your button IBAction.
And of course you'll need to change the following in your viewDidLoad from
Student *person = [[Student alloc] init];

to
person = [[Student alloc] init];


text:
Q: Root relative or relative url for .css and .js in asp.net masterpage I wonder what kind of url I should choose for local javascript and stylesheet files.
In Asp.net masterpage:
works:
<link href="../Content/Style/site.css" rel="stylesheet" />

works:
<link href="/Content/Style/site.css" rel="stylesheet" />

works:
<script src="/Scripts/javascript.js"></script>

this doesn't work correctly
 <script src="../Scripts/javascript.js"></script>

Whats the difference between:
<link href="../Content/Style/site.css" rel="stylesheet" />

and:
<script src="../Scripts/javascript.js"></script>


text:
Q: How to integrate CAS authentication with spring security? I have integrated spring security into my project and I was previously authenticating user details using hibernate. Now I have to do it using CAS.
This is my current Spring security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.1.xsd
        ">

    <global-method-security pre-post-annotations="enabled" />

    <http pattern="/css/**" security="none"/>
    <http pattern="/images/**" security="none"/>
    <http pattern="/js/**" security="none"/>
    <http pattern="/index.jsp" security="none"/>
    <http pattern="/app/addNewUser.json" security="none"/>
    <http pattern="/dbcomplogin.jsp" security="none"/>
    <http pattern="/loggedout.jsp" security="none"/>

    <http use-expressions="true">
        <!--
             Allow all other requests. In a real application you should
             adopt a whitelisting approach where access is not allowed by default
          -->
        <intercept-url pattern="/**" access="isAuthenticated()" />
        <form-login login-page='/dbcomplogin.jsp'
          authentication-failure-url="/dbcomplogin.jsp?login_error=1"
          default-target-url="/index.jsp" />
        <logout logout-success-url="/loggedout.jsp" delete-cookies="JSESSIONID"/>
        <remember-me />

    </http>

    <beans:bean id="myUserService" class="com.tcs.ceg.services.impl.UserServiceImpl" />
    <authentication-manager>
    <authentication-provider user-service-ref="myUserService" />
    </authentication-manager>

</beans:beans>

in UserServiceImpl class "loadUserByUsername" method I am using Hibernate call to get user details from DB and I was returning the username,password if they exist in DB.
But now I have to do it using CAS server . Please tell me what all I need to change in my spring-security.xml so that, if the user is not authenticated the login page of CAS server will be opened and on click of logout the single logout will take place and logout page of CAS server will open.
I am new to CAS and spring security so kindly help me.

A: Look at the alias you are using for importing beans namespace. If your xml has configuration as xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" use it with the alias name as beans:bean


text:
Q: Closed form for $\sum\limits_{d|n}\sigma(d)$? Is there any closed form for $$\sum\limits_{d|n}\sigma(d)$$? I knew that $\sum\limits_{d|n}1=\sigma(n)$ therefore we must have $\sum\limits_{d|n}\sigma(d)=\sum\limits_{d|n}\sum\limits_{r|d}1$ but how do I manupulate the last sum?

A: It is well known that for a natural number $n$ whose factorization into primes is
$$n= p_1^{e_1} \cdots p_r^{e_r}$$
we have
$$\sigma(n) = \sum_{d|n}1 = (e_1+1) \cdots (e_r+1) = \prod_{i=1}^r \binom{e_i+1}{1}$$
Similarly, I can show you that
$$\sum_{d|n} \sigma(d) = \prod_{i=1}^r \binom{e_i+2}{2}$$
Firstly, we can write
$$\sum_{d|n} \sigma(d) = \sum_{s|d|n}1$$
so that $\sum_{d|n} \sigma(d)$ counts the number of couples $(s,d)$ with $s,d \in \{ 1, \dots, n\}$ such that $s|d$ and $d|n$. At every such couple you can associate the couple $(s, d/s)$: so that $\sum_{d|n} \sigma(d)$ counts the number of couples $(s,k)$ with $s,k \in \{ 1, \dots, n\}$ such that $sk|n$ (with $d=sk$).
In order to produce such a couple $s,k$ you have to choose for every prime $p_i$ dividing $n$ what is the power of $p_i$ which occurs in the factorization of $s$ and $k$ respectively, say $f_i$ and $g_i$ respectively, and you need the condition
$$0 \le f_i+g_i \le e_i$$
Using the standard "stars and bars" method, you can see that such couples $(f_i,g_i)$ are exactly $\binom{e_i+2}{2}$, and this concludes the proof of the formula.

A: Let me write my comment as an answer. We shall use the fact that $\sum\limits_{d\mid n}f(d)$ is multiplicative whenever $f$ is multiplicative (this is very simple to prove so I don't find it necessary to write its proof). Assuming we know the prime factorization of $n$ we can do something. The function $\sigma$ is multiplicative so the function $f(n):=\sum\limits_{d\mid n}\sigma(d)$ is multiplicative, which implies that $f(n)=\prod\limits_{p\mid n,\;\text{$p$ prime}}\left(\sum\limits_{k=0}^{\alpha(p)}\sigma\left(p^k\right)\right),$ where $\alpha(p):=\lfloor\log n/\log p\rfloor,$ but for each $k,$ we have $\sigma\left(p^k\right)=k+1$ so $$\begin{aligned}f(n)&=\prod_{p\mid n,\;\text{$p$ prime}}\left(\sum_{k=0}^{\alpha(p)}(k+1)\right)\\\\&=\prod_{p\mid n,\;\text{$p$ prime}}\left(\dfrac{(\alpha(p)+1)(\alpha(p)+2)}{2}\right)\end{aligned}.$$