text:
Q: when dynamically creating an element, when clicking does not see attributes I have an array of data from which I am creating elements. And when I hang the event handler, then the dataset.container is undefined. How do I get to the attributes, or how do I create elements differently to get the data-category?

const cards = [
  [],
  [],
  []
]

function renderCategory(card) {
  let str = '';
  for (let i = 0; i < card.length; i++) {
    str += `

${card[i].name}

`;
  }
  return str;
}
let categoryCard = cards[0];

function createCard(cards) {
  const main = document.getElementById('category');
  main.innerHTML += renderCategory(cards);
}
createCard(categoryCard)

document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('#category').addEventListener('click', ({
    target: {
      dataset
    }
  }) => {
    console.log(dataset.category) // undefined
  })
})

A: event.target refers to the lowest Element of the DOM tree on which the event was triggered. In other words, depending on where you click the target can be the card-category DIV, the card-image DIV, the card-desc DIV, the card-text DIV or the IMG element. That's why you're not able to access the data-attribute which is only set on the parent.
If you want to always get the Element to which you bound the event, use event.currentTarget instead. But in your case, you bound the event to the main #category wrapper. If you want to bind the event to the element that has the data-category attribute, you'll have to reorganize your code to use document.createElement instead of producing HTML strings.
Keep in mind you should append elements to the page before binding events to them.

A: So several things
For one, I could not recognise your addEventListener('click', ({ target: { dataset } construction as valid JavaScript.
I have tried to not change a lot but I

*

*return complete set of cards

*delegate from container correctly - clicking anywhere in the card will return the category

let categoryCard;
const cards = [
{ image : "https://via.placeholder.com/128x90.png?text=Card1", name:"Card 1"},
{ image : "https://via.placeholder.com/128x90.png?text=Card2", name:"Card 2"},
{ image : "https://via.placeholder.com/128x90.png?text=Card3", name:"Card 3"}
]

function renderCategory(cards) {
  return cards.map((card,i) => (
    `

${card.name}

`)).join("");
}

function createCard(cards) {
  const main = document.getElementById('category');
  main.innerHTML += renderCategory(cards);
  categoryCard = main.querySelector(".card-category"); // first card
}

window.addEventListener('load', () => {
  document.querySelector('#category').addEventListener('click', e => {
    const tgt = e.target;
    const parent = tgt.classList.contains("card-category") ? tgt : tgt.closest(".card-category")
    console.log(parent && parent.dataset.category ? parent.dataset.category : "clicked somewhere else")
  })
  createCard(cards)
})


text:
Q: how does sort comparison get it's arguments from the array I'm reading JavaScript For Web Developer 3rd Edition and I am stuck how this works.  I understand how the compare function works.  But values.sort(compare); confuses me.  compare looks at 2 arguments and compares them.  But I do not pass 2 arguments.  Even if I did pass 2 arguments to the function, how does it compare itself to the rest of the items in the Array?  Does the sort function do something in the background that I don't know about?  If so, how does it work?
Thank you in advance :)

function compare(value1, value2)
{
 if (value1 < value2) {
 return 1;
 } else if (value1 > value2) {
 return -1;
 } else {
 return 0;
 }
}

var values = [0, 1, 5, 10, 15];
values.sort(compare);
alert(values); //15,10,5,1,0

A: The compare function is a call back function that you supply to the sort function. The sort function will use some algorithm to sort the list. When the sort function's algorithm needs to compare two items from the list, the sort method will call the compare function with the two items.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Performance issue in ThreeJS while using InterLeavedBuffer I used InterleaveleavedBuffer to manage the data and render the mesh in the browsers. I have a instances of 16000 objects from one object and when I check the draw call its 1, but while I try to Pan, rotate , zoom in/out the browser gets crashes and the response of the functionalities are very slow. I have no idea about it but as I know it has a minimal number of draw calls although why it should crash the browser.
Is there any idea to over come it and improve the performance of the viewer.
My brwoser: Version 80.0.3987.149 (Official Build) (64-bit)


text:
Q: sql regex_replace on specified columns from multiple tables How do I apply regex_replace to multiple columns from multiple tables?
I have 2 tables, "email" & "languageEmail", which each hold columns "bodyText" & "bodyHtml"
I want to replace all found links in these 4 columns with the same link + a new param.
So far I have made a regex (POSIX) that seem to match all my url links.
((http(s)?:\/\/)|(www\.))[a-zA-Z0-9@:%._\+~#=&\/?]{2,256}(\b|\s)

I have made a sql query that finds the desired columns.
SELECT
  "email"."bodyText",
  "email"."bodyHtml",
  "languageEmail"."bodyText",
  "languageEmail"."bodyHtml"
FROM
  "db"."email",
  "db"."languageEmail";

I have read postgres own documentation but there is no examples of using the regex_replace in a sql query, I have looked in oracles documentation and they have a few examples of something sort of similar to what I want to achieve, but I cannot seem to connect the dots myself and get it right.
Example of what i want to achieve:
languageEmail.bodyHtml at id 75 has value:

hello world
 click here

languageEmail.bodyText at id 75 has value:
hello worldcplease visit www.awsome.com/yes

I want to add the param &page=1 to all links/urls
so after running the query with regex_replace, languageEmail.bodyHtml at id 75 should look like:

hello wordl
 click here

languageEmail.bodyText at id 75 should look like:
hello worldcplease visit www.awsome.com/yes&page=1

A: Could you replace the second quotation mark and HTML close sign '">' with '&page=1">'?
You can use it in a CASE WHEN statement
For example:
CASE
  WHEN URL ~ '%((http(s)?:\/\/)|(www\.))[a-zA-Z0-9@:%._\+~#=&\/?]{2,256}(\b|\s)%'
   THEN
     REGEXP_REPLACE(URL, '(\">)', '&page=1">') END) AS URL_appended

For your plain text example I would try something like concatenating the URL (is it always at the end?) with the string you need at the end
So:
   SELECT
    CASE
    WHEN URL ~ '%((http(s)?:\/\/)|(www\.))[a-zA-Z0-9@:%._\+~#=&\/?]{2,256}
      (\b|\s)%'
       THEN URL || '&page=1' END AS URL_appended
    FROM your_url_table)

I think that should be it :D


text:
Q: Showing Graph/Chat and its table in PowerPoint I have to show a graph related with table showing in PPT. But I am not able to show both table and its linked graph in  same ppt file. I make change in table values.. I have update its graphs also.
I want to show both table and graph in PPT. Is it possible?


text:
Q: Derivative of a vector that is dot producted with another vector? If I have the following function: $a\textbf{x}$ , where $a$ and $\textbf{x}$ are both vectors that I am taking the dot product between, how can I differentiate this function with respect to $\textbf{x}$? What about the 2nd derivative?
For a concrete example, let's assume a = [1, 2, 3] and $\textbf{x} \in \mathbb{R}^3$ (I think this is the correct terminology to say that $\textbf{x}$ can be any vector of length 3 that is made up of real numbers?).
I'm asking because on Math Stack Exchange I see many complicated examples, and I just need some intuition about the very basics.

A: The derivative of $a\cdot \textbf{x}$ with respect to $\textbf{x}$ is
$$
\left({\partial\over dx},{\partial\over dy}\right)a\cdot \textbf{x}=(a_x,a_y).
$$
It is not so very different than the derivative of $f(x)=cx$, ${d\over dx}f(x)=c$.


text:
Q: OpenGL Depth buffer not applying I am quite new at openGL rendering, and no matter what I do the depth depth won't work.
i obviously already enabled depth test (glEnable(GL_DEPTH_TEST);), and i clear the buffer each frame.
But openGL keeps showing last objects rendered in front of others...
You can see my code on my github. These are the two files concerned : Main loop. My main loop is at src/tk/azertyfun/fps/Fps.java and the render at src/tk/azertyfun/fps/objects/Mesh.java.
I am using java and lwjgl.

A: As you say, you correctly enable depth testing before your rendering loop starts with:
glEnable(GL_DEPTH_TEST);

...and correctly clear the buffer at the beginning of each frame:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

The first thing you then draw in each frame via your render() method is with:
skybox.draw();

If you look at the implementation of the draw() method in Skybox, you'll see that you have:
glDisable(GL_DEPTH_TEST);

So it is disabled before you actually draw anything and never enabled again.


text:
Q: Output 'DataFrame' object has no attribute 'column' (Python in Jupyter notebook)
def compute_statistics(age_and_salary_data):
    histograms(age_and_salary_data)
    age = age_and_salary_data.column("Age")
    salary = age_and_salary_data.column("Salary")
    return make_array(np.mean(age), np.mean(salary))

full_stats = compute_statistics(full_data)
full_stats

This code is to:
Create a function called compute_statistics that takes a Table containing ages and salaries and:
Draws a histogram of ages
Draws a histogram of salaries
Return a two-element list containing the average age and average salary

A: In Python, if you want to access a column, you can use brackets like age_and_salary_data["Age"] and age_and_salary_data["Salary"], this column function does not exist.

A: alternatively to age_and_salary_data["Age"] you may use age_and_salary_data.Age


text:
Q: Jenkins Parameterized Build with Jenkinsfile from SCM We have some jenkins pipeline jobs defined with Jenkinsfile's located in bitbucket server, as described here. These builds are parameterized, and we'd like to be able to manually run them with non-default parameters.
The problem is, since the Jenkinsfile isn't checked out until we run it, the first time we run the build the build button is just "Build Now" instead of "Build with Parameters". Currently we are running it once with the default values so that it fails, and then running it again with the "Build with Parameters" button so we can pass in what we want.
Obviously not ideal. What is the right way to do this so we can run it with custom parameters the first time?

A: This is not possible currently, as they are post-processed they need to be executed in the 1st run before being known to jenkins and being available as 'Build with parameters'. Issue tracked here: https://issues.jenkins-ci.org/browse/JENKINS-41929
There are various ways to handle this,
The first is as you have alluded to, run it automatically/manually and let it fail, though maybe if you could set working defaults so it at least succeeds?
Another option, is to evaluate if this is the first run or not, and if so, execute the Jenkins job skipping all steps and purely processing the parameters.


text:
Q: Show size of tables and other database objects in Postgres I need to clear disk space, so I want to see which tables and other objects are using the most disk space in my Postgres databases.
Ideally, I'd like to see: database name, schema name, object type, object name and size in GB/MB.  I'm imagining something like the du -h command or the ncdu utility but for Postgres.
Is there a command to do this in psql? I know about \l+ {database name} but this just gives me the size of the database, not the objects within it.

A: This is the hit list of the largest objects in your database:
SELECT oid::regclass,
       pg_relation_size(oid),
       relkind
FROM pg_class
ORDER BY 2 DESC;


text:
Q: Long time in load_csv One of my cypher query to create relations takes very long time. Running for hours and did not complete.
I have loaded the nodes through load_csv which are roughly around 22M.
id is the unique index of all nodes.
Pin label is around 16M.
CREATE INDEX ON :Pin(id);
CREATE INDEX ON :Instance(id);

//CREATE CONSTRAINT ON (inst:Instance) ASSERT inst.Id IS UNIQUE;

USING PERIODIC COMMIT 10000
LOAD CSV WITH HEADERS FROM 'file:///home/sranga/work/Neo4j/work/signals.csv' AS line
MATCH (inst1:Pin { id: toInteger(line.Start_port)})
MATCH (inst2:Pin { id: toInteger(line.End_port)})
CREATE (inst1)-[:NET { id: toInteger(line.Signal_id),  Name: line.Name, Signed: toInteger(line.Signed), lbit: toInteger(line.Lbit), rbit: toInteger(line.Rbit)}]->(inst2);

Any idea as what is wrong?

A: Use EXPLAIN and PROFILE to get a picture of how the query is run.
Then add it to your question. (ok I saw you copy/pasted, and it does not talk much)
Is your constraint applied or not ? Are the indexes created ?
Try to reduce 10 000 to 1000.
When this number is too high, you get outofmemoryerrors. That should commit every 1000 lines read.
Follow the progress by connecting a cypher-shell to your instance and run a query to count the NET relationships.
Something like MATCH ()-[net:NET]->() return count(net);   in order to verify that it is increasing (else you stop it, breathe, and send another message )
check the number of lines in your csv with
 cat file.csv |wc -l

to be able to calculate the end of your import


text:
Q: How can I add a Dexterity content type as the default view? I'm trying to set a folder default view as a Dexterity content type that I created. But I see that Dexterity content types aren't in the list of possible default content views for folders. Why? Is there an option that I must set in the content type?

A: Content items are listed as candidate default pages if:

*

*the object is not a container type

or

*

*the object portal type is listed in the default_page_types of your site_properties property sheet. Find that in the ZMI (site settings -> Zope Management Interface -> portal_properties).
The default_page_types property is a list of portal_type ids; for Dexterity types that is usually a dotted name (the Dexterity manual uses example.conference.presenter for example).

A: Update for Plone 5.x

*

*Go to Site Setup > Content Settings control panel

*Select your (dexteity-)contenttype in the Workflow, visibility and versioning settings for your content types dropdown.

*check Can be used as a default page
(default_page_types property has been removed from ZMI)


text: Q: Averaging Models in Excel I am working in Excel and have two sets of data points that come up with a percentage for the likelihood of a recession. I am wondering what the best strategy would be to combine these data points? Should I just average them, use the geometric mean, harmonic mean, or is there another method someone would suggest? Any help on this matter is greatly appreciated!


text:
Q: multiple pictures with UIImagePickerController i've been searching around the web but couldn't find an answer.
basically i wanna take two photos one right after the other.
i'm using UIImagePickerController to show a picker and implementing didFinishPickingMediaWithInfo.
when it gets called i'm checking my count so that if its one, i implement a block and pass it to dismissViewControllerAnimated like this:
if(1 == count) {
    void (^simpleBlock)(void);
    simpleBlock = ^{
        [self useCamera];
    };

    [self dismissViewControllerAnimated:NO completion:simpleBlock];
}

it all seems to work fine, and even the useCamera method is called.
the problem is that the second time the picker shows i see all of its controls but i don't see on the screen the image from the camera.
any help would be appriciated.

A: i managed to work it out with replacing the call to useCamera with:
[self performSelector:@selector(useCamera) withObject:nil afterDelay:0.3];

i think my question has some relation to: iOS 7 UIImagePickerController has black preview
since the delay fixed the problem.

A: For you to save time. You can use available library out there. These are my good choices. CTAssetsPickerController ELCImagePickerController

A: UIImagePickerController helps to access the default camera app in iOS.
It will allow only limited functionalities like take picture/video, photo album.


text:
Q: Differences between objdump and xxd I am trying to find a call function in a binary file, so I tried this:

*

*Compile my code (in C),

*Use the command: mips-mti-linux-gnu-objdump -d myapp.elf> objdump.txt

*My function in objdump.txt file: 9d003350: 42000828 myfunction 0x1
Now, I want to identify this function in myapp.bin when reading this from memory. But, I get this: 28080042.
I tried to use the command: xxd -ps myapp.bin> xxd.txt
Just can find: 28080042.
Is it possible to do that?

A: That's an endianness conflict. objdump and xxd are giving you the same bytes, they're just using different endianness.
Actual bytes in order:
    28 08 00 42
Big endian value:
    28 08 00 42
Little endian value:
    42 00 08 28

xxd -p will print out the individual bytes in the file in the order in which they exist.
objdump is disassembling it, it knows that the bytes belong in groups of 4, and it's interpreting them as little-endian.
xxd can print in little-endian order, using the -e flag (with a default grouping of 4 bytes, use the -g flag to change the number of bytes per group). However, this is incompatible with the -p flag, because the -p flag ignores any grouping.
objdump can be made to print in big-endian order, using the -EB flag, however, this will affect what instructions it reports.


text:
Q: Access specific value from HTTP-Request I send a test HTTP-request to a SharePoint list to get the values of a list item. In return I got (shortened):

{
    "statusCode": 200,
    "headers": {
        "Transfer-Encoding": "chunked",
        "Vary": "Origin,Accept-Encoding",
        "X-SharePointHealthScore": "1",

    },
    "body": {
        "d": {

            "PraxisFoto": "{\"type\":\"thumbnail\",\"fileName\":\"Campus_Luftbild.jpg\",\"nativeFile\":{},\"fieldName\":\"PraxisFoto\",\"serverUrl\":\"https://sharepoint123.sharepoint.com\",\"fieldId\":\"c5c89367-f483-4433-a124-e307b51859ef\",\"serverRelativeUrl\":\"/sites/[SiteName]/SiteAssets/Lists/[ListID]/Campus_Luftbild.jpg\",\"id\":\"26eccafb-c4ea-4a6f-8675-xxxxxxx\"}",

        }
    }
}

Now I want to retrieve the value from serverRelativeUrl (/sites/[SiteName]/SiteAssets/Lists/[ListID]/Campus_Luftbild.jpg) located in the column PraxisFoto to get the filename for the image in an image column.
I fail to construct a HTTP-request or a compose action to get the value.

A: The value of the PraxisFoto property is a string. So you need to convert that string into an object to easily access the value of the serverRelativeUrl property. You can do this using the Initialize variable action to create an object variable and initializing it's value to the expression: json(variables('FullObject')['body']['d']['PraxisFoto'])
Note: I stored the value of the JSON object you posted in your question in a variable named FullObject. You need to replace the reference to that variable in the expression in your flow.

Then you can use this expression to get the value of the serverRelativeUrl property in a Compose action: variables('BodyObject')['serverRelativeUrl']


text:
Q: Visual Studio Team Services - Deny view of Tasks I have been looking for a way to deny a certain group the ability to see TASKS. I still want them to be able to see TICKETS. Is there a way to do this? I have been reading about permissions in VSTS, but I have not yet found anything specific to this particular question.

A: There is no way to deny specified users view tasks of work items for now.
But there has an user voice Hide Work Item Types (WITs) based on permission/security group which suggest enable to set permissions for work items types for different groups. You can vote and follow up for the user voice.
When this feature is available, then you will deny users in a group to view tasks.


text:
Q: Validar sello digital SAT México Intento validar el sello digital de un Comprobante fiscal Digital por Internet (CFDi) México.
La documentación SAT dice:

"Desencriptar el contenido del atributo sello usando el certificado incluido en el atributo "Certificado". Generar la cadena original del comprobante. Aplicar el algoritmo de digestión SHA-256. El resultado de la digestión debe ser igual al resultado de la desencripción del sello."

Tengo los siguientes datos y el siguiente código, pero cert.PublicKey hace referencia a que es obsoleto y no he podido actualizar esa línea de código:
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

string version = "3.3"; // Obtenido del XML
string certificado = "MIIGDjCCA/agAwIBAgIUMDAwMDEwMDAwMDA1MDkyNDM5ODAwDQYJKoZIhvcNAQELBQAwggGEMSAwHgYDVQQDDBdBVVRPUklEQUQgQ0VSVElGSUNBRE9SQTEuMCwGA1UECgwlU0VSVklDSU8gREUgQURNSU5JU1RSQUNJT04gVFJJQlVUQVJJQTEaMBgGA1UECwwRU0FULUlFUyBBdXRob3JpdHkxKjAoBgkqhkiG9w0BCQEWG2NvbnRhY3RvLnRlY25pY29Ac2F0LmdvYi5teDEmMCQGA1UECQwdQVYuIEhJREFMR08gNzcsIENPTC4gR1VFUlJFUk8xDjAMBgNVBBEMBTA2MzAwMQswCQYDVQQGEwJNWDEZMBcGA1UECAwQQ0lVREFEIERFIE1FWElDTzETMBEGA1UEBwwKQ1VBVUhURU1PQzEVMBMGA1UELRMMU0FUOTcwNzAxTk4zMVwwWgYJKoZIhvcNAQkCE01yZXNwb25zYWJsZTogQURNSU5JU1RSQUNJT04gQ0VOVFJBTCBERSBTRVJWSUNJT1MgVFJJQlVUQVJJT1MgQUwgQ09OVFJJQlVZRU5URTAeFw0yMTEwMDQxNDExMjBaFw0yNTEwMDQxNDExMjBaMIHcMSowKAYDVQQDEyFST0RBTUlFTlRPUyBZIEFDQ0VTT1JJT1MgU0EgREUgQ1YxKjAoBgNVBCkTIVJPREFNSUVOVE9TIFkgQUNDRVNPUklPUyBTQSBERSBDVjEqMCgGA1UEChMhUk9EQU1JRU5UT1MgWSBBQ0NFU09SSU9TIFNBIERFIENWMSUwIwYDVQQtExxSQUM4NzA0MDZQNDAgLyBBVUdNNjUxMTAzU1BBMR4wHAYDVQQFExUgLyBBVUdNNjUxMTAzSE5MR1pYMDkxDzANBgNVBAsTBm1hdHJpejCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAIQ5k2l+0VgwV+IOxKXEWJAIZYlLAaVD6FD+pQ6oBgzOhOMYPyfD8sDRuCzcqQidVSLx98kdMHykuqhHSCO+cKUGQ/uhUCGliA83cTivt6lO7GN25symhom1lat3O9flPe3J2345xNjYO7yEb0ZrINOL1763YcYXNHNomK64OBQKD616fko1bc8zxp3DK9g21WzqGKRgsH3l+MdhcE+B7hW56s354QR93+QuH2wJ1G8ygAz1Sq3t+4uh3IA0Pi2z1KcGWHpSN/PNewgIKpmV454w7TjEmQMhb/dUVlYQiAefsKVs1xco0wVWtYkHVHkj+h/F2faEw2oYv/fRE85KvhUCAwEAAaMdMBswDAYDVR0TAQH/BAIwADALBgNVHQ8EBAMCBsAwDQYJKoZIhvcNAQELBQADggIBAH10cqqZO9B2JX+E/G0VEReWaO0I3PGR1IoNo6s/m24d8UR4B82+hzxdrtQAhVr8KGP/D/G3QZKe9CqeIE3Zen0K+nbuPf97zqaoCuq32Shx4hODIjj1wXbPX2nROTFuKvD3htb/qDTgmaNCUsmajfctWgfqdOIZvWQQG+xEYRWmqJm+sILI9FdaoQANvvtfVchuQCudrA8G4bUNZmSqEBrgEMH6AscgIpx72CedcslJZLu3fNXRrSaBTT1eGR0gLRgH6Y800CpRqRn8w5yp5zXOK2PUJ/GxfTqUJ0KS4FSIb9xCUqbwYjFFKS1eKoWnlrV/3hZ9hyhXa/WTyabyGi8qzWOm7WCLZjhHHkb2SjTTZscP0h06aewEOsWJVFe92hm3hViLvDcU8Pt3c5tAzeXxn/TAZ5YUOqqOiue9VekmucKNyPnSB8Ir4DwwWJJuPP6vQDUd5JKpXTPIoN5+5wLHkIQMos+iaC1OTqxa155N3MEdp8N299F8DMM9UvmVjNEMIsapGXQInzQzeSyV2UqWlmqoiKnhNVfOw9aZm8S4Iy+nueuPU2K3VCefS2uu85EYaaB/FaCBTimfw9GxasYb2A7TOgQOjiNiQr1Uj8fCkM8tq864eAgdwVs4LiFcJojNGy8lfO/Y4lD6bBpDqq8v2fNm1VgVgh3W4S/tu3EE"; // Obtenido del XML
string selloBase64 = "JyjYN34FpmYU6COMxA689FEB7kZBlu3xx6BzSBx7MuwvqsgH33hxj6dt0KXjKlwP7frAiHqZeFhk7IK6DDqCFLljA3D/Aq+FtcxCSi5+N3EHTTBBUmcWggmyAEyTgWHRN5m/ARusbXOZWlXf2CV8hRQycTZ9lJ/9WMgmDiVbaXHXg/q2B4eiByrQ/eeOThQjNuiyc1H96GydiHfZiVIsrPBfgD4uirZSuXbBzg9CewGP0uFpp170HUof2kCzpjkaL6VNJrX5LK22Jqsxs/ch04itn6dJkyNWpZQgign0OxyUA8/62pf1rSjZd8Dot/WYOCgH4N2PTiqLbInlq/1KhQ=="; // Obtenido del XML
string cadenaOriginal = "||3.3|064F|11842|2022-07-14T16:55:18|99|00001000000509243980|120 DIAS NETO|12536.25|MXN|14542.05|I|PPD|86000|RAC870406P40|RODAMIENTOS Y ACCESORIOS S.A. DE C.V.|601|IPB7405157E6|INGENIO PRESIDENTE BENITO JUAREZ, S.A. DE C.V.|G03|31181700|S/M00184735|1|H87|Pza|SM-CTL-7 S/M0 CORDON ATEFLONADO CAJA CON 5KILOS|8156.25|8156.25|8156.25|002|Tasa|0.160000|1305|31181700|SUMA0196046|2|H87|Pza|SM-LAIC-5 SUMA EMPAQUE D/ASBESTO1/8X60X60 C/INSERCION D/MALLA|2190|4380|4380.00|002|Tasa|0.160000|700.80|002|Tasa|0.160000|2005.80|2005.80||"; // Obtenido del XML y el XSLT

byte[] sello = Convert.FromBase64String(selloBase64);

X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(certificado));
RSACryptoServiceProvider verificador = (RSACryptoServiceProvider)cert.PublicKey.Key;
HashAlgorithm algoritmoHash = null;
byte[] hashCadenaOriginal = null;
bool selloValido = false;
switch (version)
{
    case "3.2":
        algoritmoHash = SHA1.Create();
        hashCadenaOriginal = algoritmoHash.ComputeHash(Encoding.UTF8.GetBytes(cadenaOriginal));
        selloValido = verificador.VerifyHash(hashCadenaOriginal, "SHA1", sello);
        break;
    case "3.3":
        algoritmoHash = SHA256.Create();
        hashCadenaOriginal = algoritmoHash.ComputeHash(Encoding.UTF8.GetBytes(cadenaOriginal));
        selloValido = verificador.VerifyHash(hashCadenaOriginal, "SHA256", sello);
        break;
}

if (selloValido)
{
    // Factura válida
}

Soy de profesión Contador Público, pero aficionado a la programación; aprendiendo C#, me parece bueno.


text:
Q: Android Dev: Parsing a XML file Here is a snippet from the XML file I am trying to parse:
<Item xsi:type="TextureItem" Name="Texture_0044" Visible="true">
    <Position>
        <X>240</X>
        <Y>432</Y>
    </Position>
    <CustomProperties>
        <Property Name="type" Type="string" Description="slot_rectangle">
            <string />
        </Property>
    </CustomProperties>
    <Rotation>0</Rotation>
    <Scale>
        <X>1</X>
        <Y>1</Y>
    </Scale>
    <TintColor>
        <R>255</R>
        <G>255</G>
        255
        255
        <PackedValue>4294967295</PackedValue>
    </TintColor>
</Item>

I'm using an XmlResourceParser object to parse the XML file and here is my code so far:
XmlResourceParser xrp = context.getResources().getXml(R.xml.level_1);

int eventType = xrp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
    if(eventType == XmlPullParser.START_DOCUMENT) {
        //System.out.println("Start document");
    } else if(eventType == XmlPullParser.START_TAG) {
        //System.out.println("Start tag "+xrp.getName());
        if (xrp.getName().equals("Item")) {
            //...
        }
    } else if(eventType == XmlPullParser.END_TAG) {
        //System.out.println("End tag "+xrp.getName());
    } else if(eventType == XmlPullParser.TEXT) {
        //System.out.println("Text "+xrp.getText());
    }
    eventType = xrp.next();
}
System.out.println("End document");
xrp.close();

What I'm trying to do is have it so that every time a Item tag is found it will get the "Description" value of the Property tag, the text values of the X and Y tags inside the Position tag, and the text value of the Rotation tag and nothing more.
Right now I'm considering where it says if (xrp.getName().equals("Item")) just copying and pasting the outside parsing code to the inside of that if condition and then going up and down in levels getting the values I want until the END_TAG for the Item tag event occurs, but that seems very inefficient and confusing.
What I want sort of is like a xrp.Item.Position.X.getText() sort of deal if you know what I mean, does something like that exist?
Thanks!

A: You're on the right track. Just create an object model that maps to what you expect and fill it in as you parse the XML. You'll be better off having a light-weight representation of the data instead of trying to use xpath as you need values.


text:
Q: MS Access Form Not Showing Results This is truly baffling.
I have a subform that is set up as a continuous form and receives data from a query.  Here is the SQL
SELECT Top 12 Tbl_Parent_ITN.ID, Tbl_Parent_ITN.ITN_Number, Tbl_Child_ITN.ITN,
Tbl_Child_ITN.Parent_ITN_fk, Tbl_Scope_Rqmts.Completed, Tbl_Scope_Rqmts.Child_ITN_fk,
Tbl_Lkup_Requirements.Requirement, Tbl_Lkup_Basis.Basis
   FROM Tbl_Parent_ITN INNER JOIN (Tbl_Lkup_Requirements
     INNER JOIN (Tbl_Lkup_Basis INNER JOIN (Tbl_Child_ITN INNER JOIN Tbl_Scope_Rqmts
       ON Tbl_Child_ITN.Id = Tbl_Scope_Rqmts.Child_ITN_fk) ON Tbl_Lkup_Basis.ID = Tbl_Scope_Rqmts.Basis_fk)
        ON Tbl_Lkup_Requirements.ID = Tbl_Scope_Rqmts.Requirements_fk)
         ON Tbl_Parent_ITN.ID = Tbl_Child_ITN.Parent_ITN_fk
           WHERE (((Tbl_Parent_ITN.ID)=[Forms]![Frm_Parent_ITN_Main]![parent_id]));

The criteria in the where clause of the SQL is passed based on the control in the form that precedes this form.  The value is the primary key of the parent table that joins with several child tables to get all of the data for the subform.
When I open the with one record that has children it works perfectly fine and the form populates with 12 records.  However, when I go run the same operation on the next parent record I don't get any results in view even though that parent has 4 child records.
What is really perplexing is that when I run the query independently from opening the form it gives me the exact results that I want based on that 2nd parent record.  Furthermore, if I change the subform to a datasheet I still don't get any records; however, I can see the results in the filters of the datasheet form if I select those column headers (but no records show in the form itself).  The properties of the subform are the exact same in both cases, so I can't understand what would cause the records to show in the 1st case but not the 2nd??

A: A few suggestions:
1. Try to do a Me.Refresh to see what happens.
2. Put a break point in the form's OnError event to see is there is something wrong.
3. Check if there is any other data source that may be locking any data that should be refreshed.
4. Verify that the no properties that define the parent-child relationship of the data is being changed during runtime.
5. Check if the parent record id gets refreshed on the OnCurrent event of the form.
Hope this helps,
FunkSoulBrother


text:
Q: Jquery selecting elements inside element I have the follow code:
var table1 = $('[id="table1"]');
var table2 = $('[id="table2"]');

I need to get inside each table the text content from specified id as this:
var words1 = $('[id^="table-row-"]');
var words2 = $('[id^="table-row-"]');

Please note that id^="table-row-" because it is variable as for example "table-row-1", "table-row-2", etc.
I tried something like this but it does not works:
var words1 = $('[id^="table-row-"]').table1;

What I need to do?

A: First, you can use the # to find IDs:
var $table1 = $('#table-1');

You can space separate child selectors like so:
var $table1row1 = $('#table-1 #table-row-1');

Or, if you have your initial jQuery object cached, you can perform a $.find():
var $table1 = $('#table-1'),
    $tableRow1 = $table.find('#table-row-1');

However, IDs should always be unique to the entire document. Never use the same ID on more than one element. If you have an ID called table-row-1, that should be the only time that ID appears in the document, and you can simply do:
var $tableRow1 = $('#table-row-1');

I believe your HTML should probably look more like this:

So you have classes that are reusable across multiple tables, and then you can do finds for the table rows in each table.
$table1row1 = $('#table-1 .table-row-1');

Also note that if you're just incrementing the rows, you can also find elements by their index within the parent element. So, given the above HTML:
$('#table-one tr').eq(1); // returns the first tr element in #table-one

Note: it's customary when storing jQuery objects to preface the variable name with a $ to connote that it's a referencing a jQuery object.

A: you can access by there index
 $('[id^="table-row-"]')[0]
 $('[id^="table-row-"]')[1]

A: For all rows:
var words1 = $('[id="table1"] [id^="table-row-"]');
var words2 = $('[id="table2"] [id^="table-row-"]');

For one row:
var words1 = $('[id="table1"] [id="table-row-' + id + '"]');
var words2 = $('[id="table2"] [id="table-row-' + id + '"]');

A: Why not use the native (non-jQuery) querySelector?
var table = document.querySelector("table");
var row = table.querySelector("tr");
var cell = row.querySelector("td");
alert(cell.innerHTML);

...or, if you insist on using jQuery:
var $tables = $("table");
var $rows = $($tables[0]).find("tr");
var $cells = $($rows[0]).find("td");
alert($($cells[0]).html());

That's slightly different because jQuery returns all elements (in the above example, using $(xxx[0]) to get the first instance).  If you want to find all instances the native way, use querySelectorAll.


text:
Q: Android debug build failing with "Stackoverflow Error" post gradle upgrade to 2.3.0 I had recently upgraded to gradle plugin 2.3.0 and the gradle version to 4.3.1. Post that upgrade the debug build is failing with the following stack trace. Have no clue what is going wrong and where. For sure there is something related to data-bindings as per the logs but what is it I could not get the pointers. Need help.
cannot generate view binders java.lang.StackOverflowError
00:16:40,443 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at android.databinding.tool.reflection.annotation.AnnotationTypeUtil.toJava(AnnotationTypeUtil.java:176)
00:16:40,443 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at android.databinding.tool.reflection.annotation.AnnotationTypeUtil.toJava(AnnotationTypeUtil.java:149)
00:16:40,443 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at android.databinding.tool.reflection.annotation.AnnotationTypeUtil.toJava(AnnotationTypeUtil.java:249)
00:16:40,443 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at android.databinding.tool.reflection.annotation.AnnotationTypeUtil.toJava(AnnotationTypeUtil.java:151)
00:16:40,443 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at android.databinding.tool.reflection.annotation.AnnotationTypeUtil.lambda$toJava$1(AnnotationTypeUtil.java:188)
00:16:40,443 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
00:16:40,443 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at java.util.Iterator.forEachRemaining(Iterator.java:116)
00:16:40,444 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
00:16:40,444 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
00:16:40,444 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
00:16:40,444 ERROR - 00:16:40.422 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
00:16:40,444 ERROR - 00:16:40.423 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
00:16:40,444 ERROR - 00:16:40.423 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)

Post this the stack trace just repeats with this same issue endlessly.

A: After some investigation I figured out this was due to the log level set to INFO for my build and the machine was running out of memory. On changing the log level to "DEBUG" it was resolved.


text:
Q: Create and insert table I made a table for database and the table created but the insert vales are not working.
This is the table
Create table patient (
Patient_ID Number(9) primary key,
First_name varchar2(15),
Last_name varchar2(10),
Contact number(10),
City varchar2(20),
Doctor_ID Number(9) references Doctor(Doctor_ID));

This is the insert statement
insert into patient values ('21345', 'John', 'Smith', '111-111-1111', 'NJ');
insert into patient values ('21346', 'Emily', 'Rose', '222-222-2222', 'LA');
insert into patient values ('21347', 'Mark', 'Cruise', '333-333-3333', 'NY');
insert into patient values ('21348', 'Bran', 'Stark', '444-444-4444', 'TX');
insert into patient values ('21349', 'Hailey', 'Wraith', '555-555-5555', 'AZ');

I am getting an error saying not enough values.

A: You are only inserting 5 values when your table is expecting 6 (ParentID, First Name, Last Name, Contact, City and Doctor ID)
You need to pass in a value for Doctor_ID

A: You forgot to add the table column names during the insert so it tries to add all the data your passing to each column in the table. This is a better way of entering your data when it doesn't require you to insert into all table columns.
Insert into `patient` (`table1`, `table2`, `table3`, `table4`, `table5`) values ('21345', 'John', 'Smith', '111-111-1111', 'NJ');

To break down your issue more, you have 6 columns in your table, but the data your passing is 5, it will give you this error because 5 is less than 6. If you don't want to receive this error you need to state each column you are entering into as seen above -- BUT that field will need to be a nullable field.
In this case Doctor_ID is missing
Insert into `patient` (`table1`, `table2`, `table3`, `table4`, `table5`, `table6` ) values ('21345', 'John', 'Smith', '111-111-1111', 'NJ', 'DOCTOR_ID_DATA_HERE');

ANSWER:
Insert into `patient` (`Patient_ID`, `First_name`, `Last_name`, `Contact`, `City`, `Doctor_ID`) values ('2125', 'John', 'Doe', '111-111-1111', 'LA', '30114');

DOCTOR 30114 needs to already exist because you are referencing from another table, please take note!


text:
Q: Could not start printer When I am trying to print PDF document in Libra office I get this error message:

Could not start printer. Please check your printer configuration.

My printer is brother DCP-350C, i downloaded drive from site, installed it, error continue, i started to follow random tutorials about adding generic drives changing ports and such, nothing, error persists, Document print status shows cancelled despite me not cancelling it, it doesn't give me any error details why this happens.
I use mint 19.3


text:
Q: Knockout JS data-bind doesn't work When I set the debugger at the applyBidnigns line, I can see the followings:

All properties retain an actual value but I can't map any of them to my rendering. The form is completely empty.
Binding the Model:
$(document)
            .ready(function() {
                ko.applyBindings(wqsvm, jQuery('#div_wQualitySearch')[0]);
            });

        function ViewModel() {
            var self = this;
            self.search = ko.observable(new Search());
            self.submit = function() {
                if (validator != null && validator.validate('waterqualitysearch')) {
                    self.search.geolocation = getGeocodeByZip(self.search.geolocation.zip);
                    window.location.href = '#' + self.search.buildUrl() + self.buildUrl();
                }
            };
            self.buildUrl = function() {
                var locHash = encodeQueryData(self);
                return locHash;
            };
        }
        function Search() {
            var self = this;
            self.zip = ko.observable('');
            self.distance = ko.observable(25);
            self.currentPage = ko.observable(1);
            self.pageSize = ko.observable(10);
            self.availableRadiuses = ko.observableArray([25, 50, 100, 200, 250]);
            self.geolocation = ko.observable(new geoLocation());
            self.buildUrl = function () {
                var locHash = encodeQueryData(self);
                return locHash;
            }
            self.initFromUrl = function() {
                    var locHash = window.location.hash.substring(1);
                    var location = JSON.parse('{"' +
                        decodeURI(locHash).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
                    self.geolocation(new geoLocation(0, 0, '', location));
                    if (location.zip !== 'undefined')
                        self.zip(location.zip);
                    if (location.distance !== 'undefined')
                        self.distance(location.distance);
                    if (location.currentpage !== 'undefined')
                        self.currentPage(location.currentpage);
                },
                self.initialize = function() {
                    if (window.location.hash) {
                        self.initFromUrl();
                    }
                }
            self.initialize();
        }
    var wqsvm = new ViewModel();

Rendering:

    <input type="text" id="txt_QWaterZip" placeholder="ZIP Code" data-bind="value: search.zip">
    <select id="ddl_Radius" placeholder="Radius" data-bind="options: search.availableRadiuses, value: search.distance"></select>
    Search

A: I'm posting the answer to help others in the future.
Thanks to @haiim770, I was able to resolve this issue.
There is no need for search to be an observable. You can still try value: search().zip etc, though (that's because Knockout won't automatically unwrap observables that are part of an expression, it will only automatically unwrap direct references to observables [like value: SomeObservable]). Bottom line is, try: self.search = new Search(); instead.

function ViewModel() {
            var self = this;
            self.search = new Search();
            self.submit = function() {
                if (validator != null && validator.validate('waterqualitysearch')) {
                    self.search.geolocation = getGeocodeByZip(self.search.geolocation.zip);
                    window.location.href = '#' + self.search.buildUrl() + self.buildUrl();
                }
            };
            self.buildUrl = function() {
                var locHash = encodeQueryData(self);
                return locHash;
            };
        }


text:
Q: Table fixed header and first column css/html I have a table that has a large number of line and columns. But I would like to have the header fixed and the first column fixed. Here is a picture of what I need.

Only the pink part must scroll horizontally and vertically but the others must stay visible during the scrolling. My table is in a div.
First, should I use one table or four (the blue one, the red one, the green one and the pink one) ?
I have written this fiddle:
http://jsfiddle.net/5XWqj/1/
I tried to fix the header first but I wasn't a success
#container thead {
    position: fixed;
    top: 0;
}

and something like this to select and fix the first column
#container tbody tr td:first-child {
    position: fixed;
    left: 0;
}

but it's not fixing about the div that wrap my table.
Maybe I will need some jQuery or JavaScript?
If anyone could help.

A: May be you are looking for something like this:
http://zurb.com/playground/playground/responsive-tables/index.html
All you need is include the JS and CSS files and simply add class='responsive' to your table element.
I tried to implement that with your code, but there was some issue with rowspan, so tweaked it a bit.
http://jsfiddle.net/UqYgq/3/
I think you also wanted vertical scrolling in similar fashion. Let me know if I should help with that?

A: I solved same problem with only one table and DataTables plugin with FixedColumn extension.
You can see demo of the extesion: http://datatables.net/release-datatables/extras/FixedColumns/
In my solution I have one table, in its thead section are rows I want to have frozen (you can you rowspan for the first cell). And the FixedColumn extension froze first two columns for me.
DataTables plug-in init I used:
duplicatesTable = $('.js-merge-duplicates-table').dataTable({
            //I want standard table look - no DataTables features but frozen header
            "bPaginate": false,
            "bLengthChange": false,
            "bFilter": false,
            "bSort": false,
            "bInfo": false,
            "bAutoWidth": false,
            "sScrollX": "100%",
            "sScrollY": "500",
            "bScrollCollapse": true
        });
        new FixedColumns(duplicatesTable, {
            "iLeftColumns": 2, //maybe you would need only one column
            "iLeftWidth": 350
        });


text:
Q: jquery .getJSON does not GET any data from CodeIgniter REST interface I'm using Phil Sturgeon's RESTful interface for CodeIgniter https://github.com/philsturgeon/codeigniter-restserver and it appears to be working flawlessly.
On another server, I'm attempting to use jQuery to retrieve json data.
First I checked whether my js is messed up by using the flickr example in the jQuery documentation. That worked properly.
But when I substitute my url I don't appear to be getting any response.
         $.getJSON("http://myurl/apps/api/micronews/community/db/mydb/city/mycity/format/json/?jsoncallback=?",
          function(data) {
            console.log ('show me the data');
          });

I've also tried the equivalent ajax request:
$.ajax({
  url: "http://myurl/apps/api/micronews/community/db/mydb/city/mycity/format/json/",
  dataType: 'jsonp',
  success: function(results){
  console.log(results);
  }
});

The access log on the external server shows the GET request to /apps/api/micronews/community/db/mydb/city/mycity/format/json/?callback=jQuery151029825189273083685_1310236439746&_=1310236439748 and a 200 response.
Hitting that page directly from the browser returns json encoded data.
Since the GET parameters are in the URL string, it shouldn't be an issue with CodeIgniter not configured properly. And the access log seems to suggest the GET request is fine.

A: The solution work for me :
In the application/config/config.php make these changes :
$config['uri_protocol'] = "PATH_INFO";
$config['enable_query_strings'] = TRUE

Save my night !

A: I guess that is why security filtering function worked.

The security filtering function is called automatically when a new controller is invoked. It does the following:

If $config['allow_get_array'] is FALSE(default is TRUE), destroys the global GET array.

http://codeigniter.com/user_guide/libraries/input.html
So, try $config['allow_get_array'] = TRUE or use Post method.

A: Try using this:
 $.getJSON("http://myurl/apps/api/micronews/community/db/mydb/city/mycity/format/json/?callback=?",
  function(data) {
    console.log ('ready to handle data');
  });

A: Why not just use $.ajax() and then you can pass in crossDomain:true instead of worrying about jsonp callback wrappers?


text:
Q: SimpleMembershipProvider: webpages_Membership table which is the best method to access to webpages_Membership table informations using a SimpleMembershipProvider in MVC 4? I'm trying to implement the account block if he / she input a wrong password for three times ..
Many thanks

A: Using SimpleMembership you would access this information with the following method:
WebSecurity.IsAccountLockedOut(userName, allowedPasswordAttempts, intervalInSeconds)

IsAccountLockedOut returns whether the account is locked or not based on the number of attempts you want to allow and the time since the last failed logon attempt. This is used to stop brute force attempts to crack the password by other machines. You would add this check where you authenticate the user, such as the Account controllers Login method. You could do something like this:
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid &&
           !WebSecurity.IsAccountLockedOut(model.UserName, 3, 180) &&
           WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

You do not want to completely disable the user in this case and allow a valid user to get back in after the interval has passed. This to stop brute force attacks and not people that forgot their password.
The IsConfirmed field is used during registration you want the user to confirm they gave you a valid email address. You would generate and store a ConfirmationToken in the database that you would email to the user and instruct them to click on a link that would take them to a controller/action in your MVC app that would verify the token and set the IsConfirmed field to true.

A: davide, to completely disable a user, you could create a new role "Disabled" and modify the Login code:
public ActionResult Login(LoginModel model, string returnUrl)
{
    string errorMsg = "The user name or password provided is incorrect.";
    if (Roles.IsUserInRole(model.UserName, "Disabled"))
    {
        errorMsg = "Your account has been disabled. Contact webmaster for more info.";
    }
    else if (ModelState.IsValid &&
        !WebSecurity.IsAccountLockedOut(model.UserName, 3, 180) &&
        WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
    {
            return RedirectToLocal(returnUrl);
    }

    if (!WebSecurity.IsConfirmed(model.UserName))
    {
        errorMsg = "You have not completed the registration process. "
            + "To complete this process look for the email that provides instructions.";
    }

    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", errorMsg);
    return View(model);
}


text:
Q: Error left-hand-side-of-an-assignment-must-be-a-variable I am currently converting from Vb6 to C# where the below Vb6 code is allowed :
Private Property Let gUnit(Optional bResolve As Boolean, aNoseHi)
    gNoseLo(Optional parameter) = 0
End Property

Not Allowed:
void Test()
{
    gNoseLo(false) = 0   //error occurs here
}

The gNoseLo has been defined in VB6 as Private Property Get gNoseLo(Optional bResolve As Boolean). I cannot use a public property approach in C# since there are parameters so I used a method. What would be the correct way to recode the gNoseLo to accept value assignment and prevent the error?

A: A "property with a parameter" in C# is an indexer. You can't give it a name like you can in VB though1. You declare it like this:
public int this[bool parameter]
{
    get { ... }
    set { ...}
}

Now that may or may not be appropriate for your use case. Alternatives are:

*

*Have a regular property that returns something with an indexer:
public class IndexedByBoolean
{
    public int this[bool parameter]
    {
        get { ... }
        set { ...}
    }
}

public class ContainsPropertyIndexedByBool
{
    private readonly IndexedByBoolean index;

    public IndexedByBoolean NoseLo { get { return index; } }
}

Then you could use foo.NoseLo[true] = 0

*Use Get and Set methods:
SetNoseLo(true, 0);

1 Well, you specify a name, but not use it by that name.


text:
Q: C# Error: Microsoft Excel cannot access the file '...'. There are several possible reasons I've developed an ASP.Net MVC application, that is running on a IIS sever. I've wrote a code that reads a CSV and insert the rows of it in a database.
[HttpPost]
    public ActionResult InsertPosition(int id, HttpPostedFileBase position)
    {
        var posicoesExistentes = db.tbPositions.Where(s => s.id_unique == id).AsEnumerable();

        foreach (tbPosition posicao in posicoesExistentes)
        {
            db.tbPositions.Remove(posicao);
        }

        if (!Directory.Exists(Server.MapPath("~/App_Data/")))
        {
            System.IO.Directory.CreateDirectory(Server.MapPath("~/App_Data/"));
        }

        string excelPath = Server.MapPath("~/App_Data/" + position.FileName);
        if (System.IO.File.Exists(excelPath))
        {
            System.IO.File.Delete(excelPath);
        }

        position.SaveAs(excelPath);

        string tempPath = Server.MapPath("~/App_Data/" + "tmp_" + position.FileName);
        System.IO.File.Copy(excelPath, tempPath, true);

        Excel.Application application = new Excel.Application();
        Excel.Workbook workbook = application.Workbooks.Open(tempPath, ReadOnly: true,Editable:false);
        Excel.Worksheet worksheet = workbook.ActiveSheet;
        Excel.Range range = worksheet.UsedRange;
        application.Visible = true;

        for (int row = 1; row < range.Rows.Count - 1; row++)
        {
            tbPosition p = new tbPosition();

            p.position = (((Excel.Range)range.Cells[row, 1]).Text == "") ? null : Convert.ToInt32(((Excel.Range)range.Cells[row, 1]).Text);
            p.left = ((Excel.Range)range.Cells[row, 2]).Text;
            p.right = ((Excel.Range)range.Cells[row, 3]).Text;
            p.paper = ((Excel.Range)range.Cells[row, 4]).Text;
            p.denomination = ((Excel.Range)range.Cells[row, 5]).Text;
            p.material = ((Excel.Range)range.Cells[row, 6]).Text;
            p.norme = ((Excel.Range)range.Cells[row, 7]).Text;
            p.finalized_measures = ((Excel.Range)range.Cells[row, 8]).Text;
            p.observation = ((Excel.Range)range.Cells[row, 9]).Text;
            p.id_unique = id;

            db.tbPositions.Add(p);
            db.SaveChanges();
        }
        workbook.Close(true, Type.Missing, Type.Missing);
        application.Quit();
        System.IO.File.Delete(tempPath);

        return Json("Success", JsonRequestBehavior.AllowGet);
    }

but in return I got the error ' Microsoft Excel cannot access the file '...'. There are several possible reasons' when I try to open the requested excel file.
I've already tried to open the file as readonly, I've already tried to give permissions to the specifieds folders, multiples ways of close the excel file, and create an copy file of the original and read him. But unsuccessful in each one of these solutions. What have I missed here?

A: Unsupported
The short answer is that trying to programatically manipulate an Excel document using the Automation API is not supported outside of a UI context. You will come across all sorts of frustrations (for example, the API is permitted to show dialogs - how are you going to click on "OK" if it's running on a web-server?).
Microsoft explicitly state this here

Microsoft does not recommend or support server-side Automation of Office.

So what do I use?
I would recommend using the OpenXML SDK - this is free, fully supported and much faster than the Automation API.
Aspose also has a set of products, but they are not free, and I've not used them.
But I HAVE to do it this way
However, if you absolutely have to use the COM API then the following might help you:
HERE BE DRAGONS
The big problem with automation in Excel is that you need to ensure you close every single reference whenever you use them (by calling ReleaseComObject on it).
For example, the following code will cause Excel to stay open:
var range;
range = excelApplication.Range("A1");
range = excelApplication.Range("A2");
System.Runtime.InteropServices.Marshal.ReleaseComObject(range)
range = Nothing

This is because there is still a reference left over from the call to get range "A1".
Therefore, I would recommend writing a wrapper around the Excel class so that any access to, e.g., a range frees any previous ranges accessed before accessing the new range.
For reference, here is the code I used to release COM objects in the class I wrote:
Private Sub ReleaseComObject(ByVal o As Object)
    Try
        If Not IsNothing(o) Then
            While System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0
                'Wait for COM object to be released.'
            End While
        End If
        o = Nothing
    Catch exc As System.Runtime.InteropServices.COMException
        LogError(exc) ' Suppress errors thrown here '
    End Try
End Sub

A: Try this
  protected void ImportCSV(object sender, EventArgs e)
        {
            importbtn();

        }
        public class Item
        {
            public Item(string line)
            {
                var split = line.Split(',');
                string FIELD1 = split[0];
                string FIELD2 = split[1];
                string FIELD3 = split[2];

                string mainconn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

                using (SqlConnection con = new SqlConnection(mainconn))
                {
                    using (SqlCommand cmd = new SqlCommand("storedProcedureName", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.AddWithValue("@FIELD1", SqlDbType.VarChar).Value = FIELD1;
                        cmd.Parameters.AddWithValue("@FIELD2", SqlDbType.VarChar).Value = FIELD2;
                        cmd.Parameters.AddWithValue("@FIELD3", SqlDbType.VarChar).Value = FIELD3;

                        con.Open();
                        cmd.ExecuteNonQuery();
                    }

                }

            }
        }
        private void importbtn()
        {
            try
            {

                string csvPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
                FileUpload1.SaveAs(csvPath);

                var listOfObjects = File.ReadLines(csvPath).Select(line => new Item(line)).ToList();

                DataTable dt = new DataTable();

                dt.Columns.AddRange(new DataColumn[3] { new DataColumn("FIELD1", typeof(string)),
                new DataColumn("FIELD2", typeof(string)),
                new DataColumn("FIELD3",typeof(string)) });

                string csvData = File.ReadAllText(csvPath);

                foreach (string row in csvData.Split('\n'))
                {

                    if (!string.IsNullOrEmpty(row))
                    {

                        dt.Rows.Add();

                        int i = 0;

                        //Execute a loop over the columns.
                        foreach (string cell in row.Split(','))
                        {

                            dt.Rows[dt.Rows.Count - 1][i] = cell;

                            i++;

                        }

                    }
                }

                GridView1.DataSource = dt;
                GridView1.DataBind();

                Label1.Text = "File Attached Successfully";

            }
            catch (Exception ex)
            {
                Message.Text = "Please Attach any File" /*+ ex.Message*/;

            }
        }


text:
Q: cloud endpoints return error 401 unauthorized request So i have made a few cloud endpoints to be used in an application and am going through the process of securing them in an android client. Everytime i try and consume data in the android client code, i get error 401 "Unautorized Access". I can tell why the exception is being thrown as i am nullchecking the 'User' parameter on every api method. But my question is why i am always getting a null User for my api methods. I have successfully given my endpoint builder the correct credentials and setSelectedAccountName with the account on the phone. here is my example:
One api method:
 public CollectionResponse<Student> getAllStudents(User user) throws OAuthRequestException {
        if (user == null)
               throw new OAuthRequestException("BAD_USER");
        else {
               List<Student> stud = ofy().load().type(Student.class).list();
               return CollectionResponse.<Student>builder().setItems(stud).build();
           }
    }

this is placed at the top of the api as well:
@Api(name = "studentEndpoint", version = "v1", namespace = @ApiNamespace(ownerDomain = "appbackend.mymodule.example.com", ownerName = "appbackend.mymodule.example.com", packagePath=""),
            scopes = {Constants.EMAIL},
            clientIds = {Constants.WEB_CLIENT_ID, Constants.ANDROID_CLIENT_ID},
            audiences = {Constants.ANDROID_AUDIENCE})

I am grabbing the account email using account manager in my android client, setting up credentials and getting an access token.
GoogleAccountCredential cred = GoogleAccountCredential.usingAudience(AddUser.this, AppConstants.AUDIENCE);
                cred.setSelectedAccountName(emailAccount);

this is how i am using it in my client code:
StudentEndpoint service = AppConstants.getApiHandle(cred);
                stud = service.getAllStudents().execute();

The above code is being called asynchronously.
I have triple checked my client ids to make sure they are correct and they are. I am also installing this from android studio directly onto my phone via adb. I have my debug SHA1 in the the google cloud console, but do i need my release SHA1 there as well. I didnt think i would because i have not created release keys for this app yet and have only used an unsigned copy. As well if i use the web-client I can authenticate but everytime i make a request i get error 401, and i see my exception 'BAD_USER' thrown. I do have a 'Bearer' key tho showing that i have access.
If i cancel the nullcheck on the User parameter in my module the methods work fine and i can get the data from my datastore. So any reason why i am getting a null user everytime i make api requests? Any help is much appreciated. Thanks in advance.

A: I would suggest to revisit the following 3 points:

*

*Make sure that your package name is correct i.e. same in both the Android app and the package name that was specified when creating the credentials in the Cloud Console.

*Can you check the value of the AppConstants.AUDIENCE in your code. Ideally it needs to be in the following format "server:client_id:WEB_CLIENT_ID'

*Ensure that your Constants.WEB_CLIENT_ID is the same as Constants.ANDROID_AUDIENCE


text:
Q: Python : Split list based on negative integers I have a list say l = [1,5,8,-3,6,8,-3,2,-4,6,8]. Im trying to split it into sublists of positive integers i.e. the above list would give me [[1,5,8],[6,8],[2],[6,8]]. I've tried the following:
l = [1,5,8,-3,6,8,-3,2,-4,6,8]
index = 0
def sublist(somelist):
    a = []
    for i in somelist:
        if i > 0:
            a.append(i)
        else:
            global index
            index += somelist.index(i)
            break
    return a

print sublist(l)

With this I can get the 1st sublist  ( [1,5,8] ) and the index number of the 1st negative integer at 3. Now if I run my function again and pass it l[index+1:], I cant get the next sublist and assume that index will be updated to show 6. However i cant, for the life of me cant figure out how to run the function in a loop or what condition to use so that I can keep running my function and giving it l[index+1:] where index is the updated, most recently encountered position of a negative integer. Any help will be greatly appreciated

A: You need to keep track of two levels of list here - the large list that holds the sublists, and the sublists themselves. Start a large list, start a sublist, and keep appending to the current sublist while i is non-negative (which includes positive numbers and 0, by the way). When i is negative, append the current sublist to the large list and start a new sublist. Also note that you should handle cases where the first element is negative or the last element isn't negative.
l = [1,5,8,-3,6,8,-3,2,-4,6,8]

def sublist(somelist):
    result = []
    a = []
    for i in somelist:
        if i > 0:
            a.append(i)
        else:
            if a: # make sure a has something in it
                result.append(a)
            a = []
    if a: # if a is still accumulating elements
        result.append(a)
    return result

The result:
>>> sublist(l)
[[1, 5, 8], [6, 8], [2], [6, 8]]

A: Since somelist never changes, rerunning index will always get index of the first instance of an element, not the one you just reached. I'd suggest looking at enumerate to get the index and element as you loop, so no calls to index are necessary.
That said, you could use the included batteries to solve this as a one-liner, using itertools.groupby:
from itertools import groupby

def sublist(somelist):
    return [list(g) for k, g in groupby(somelist, key=(0).__le__) if k]

Still worth working through your code to understand it, but the above is going to be fast and fairly simple.

A: This code makes use of concepts found at this URL:
Python list comprehension- "pop" result from original list?
Applying an interesting concept found here to your problem, the following are some alternatives to what others have posted for this question so far.  Both use list comprehensions and are commented to explain the purpose of the second option versus the first.  Did this experiment for me as part of my learning curve, but hoping it may help you and others on this thread as well:
What's nice about these is that if your input list is very very large, you won't have to double your memory expenditure to get the job done.  You build one up as you shrink the other down.
This code was tested on Python 2.7 and Python 3.6:
o1 =  [1,5,8,-3,6,9,-4,2,-5,6,7,-7, 999, -43, -1, 888]
                                # modified version of poster's list
o1b = [1,5,8,-3,6,8,-3,2,-4,6,8]    # poster's list

o2 = [x for x in (o1.pop() for i in range(len(o1))) \
if (lambda x: True if x < 0 else o1.insert(0, x))(x)]

o2b = [x for x in (o1b.pop() for i in range(len(o1b))) \
if (lambda x: True if x < 0 else o1b.insert(0, x))(x)]

print(o1)
print(o2)
print("")

print(o1b)
print(o2b)

It produces result sets like this (on iPython Jupyter Notebooks):
[1, 5, 8, 6, 9, 2, 6, 7, 999, 888]
[-1, -43, -7, -5, -4, -3]
[1, 5, 8, 6, 8, 2, 6, 8]
[-4, -3, -3]
Here is another version that also uses list comprehensions as the work horse, but functionalizes the code in way that is more read-able (I think) and easier to test with different numeric lists.  Some will probably prefer the original code since it is shorter:
p1 =  [1,5,8,-3,6,9,-4,2,-5,6,7,-7, 999, -43, -1, 888]
                                # modified version of poster's list
p1b = [1,5,8,-3,6,8,-3,2,-4,6,8]    # poster's list

def lst_mut_byNeg_mod(x, pLst):     # list mutation by neg nums module
    # this function only make sense in context of usage in
    # split_pos_negs_in_list()

    if x < 0: return True
    else:
        pLst.insert(0,x)
        return False

def split_pos_negs_in_list(pLst):
    pLngth = len(pLst)              # reduces nesting of ((()))
    return [x for x in (pLst.pop() for i in range(pLngth)) \
            if lst_mut_byNeg_mod(x, pLst)]

p2 = split_pos_negs_in_list(p1)
print(p1)
print(p2)
print("")
p2b = split_pos_negs_in_list(p1b)
print(p1b)
print(p2b)

Final Thoughts:
Link provided earlier had a number of ideas in the comment thread:

*

*It recommends a Google search for the "python bloom filter library" - this sounds promising from a performance standpoint but I have not yet looked into it

*There is a post on that thread with 554 up-voted, and yet it has at least 4 comments explaining what might be faulty with it.  When exploring options, it may be advisable to scan the comment trail and not just review what gets the most votes.  There are many options proposed for situations like this.

A: Just for fun you can use re too for a one liner.
l = [1,5,8,-3,6,8,-3,2,-4,6,8]
print map(lambda x: map(int,x.split(",")), re.findall(r"(?<=[,\[])\s*\d+(?:,\s*\d+)*(?=,\s*-\d+|\])", str(l)))

Output:[[1, 5, 8], [6, 8], [2], [6, 8]]


text:
Q: measure CPU usage per second of a dynamically linked library I have a sample application which uses a  dynamically linked library library.so. I was measuring CPU usage of the sample application with the top command. But it shows CPU usage of both sample app and library.so per second. But I want to see the CPU usage of only the library.so. Is there anyway to do this? I heard its achievable with htop but could not find out how. I used the tree view but it shows several processes as the sample app process. I could not understand which one is library.so. I am using centos 5.11. Kernel version 3.2.63-1.el5.elrepo.

A: Given the library is considered part of your program, one way would be to implement the measurement within your code. The following minimal example is implemented on C++11 running only one function from a hypothetical library:
#include <chrono>
#include <iostream>
#include <hypothetical>
int main() {
  using namespace std::chrono;
  system_clock systemClock;
  system_clock::time_point startingTime{systemClock.now()};
  hypothetical::function();
  system_clock::duration libraryTime{systemClock.now() - startingTime};
  std::cout << "Hypothetical library took " << duration_cast<seconds>(libraryTime).count() << " seconds to run.\n";
  return 0;
}

You will need to extend this to all of the functions that your program invokes from your library.


text:
Q: Kerberos password-less ticket authentication I'm trying to implement "password-less" Kerberos authentication (except when the ticket is expired) for a particular simple service within an organisation. (Full disclosure: It's not a web service, but "remote procedure execution" over SSH.) I'd prefer to just use Bash or perhaps Python for this.
Let's say a user passes their Kerberos credentials cache file, which by default is created at /tmp/krb5cc_$(id -u) at login to the client computer, through a client script to my service which sits on a different computer/server.
Is there some way I can determine whether this user is in fact who they claim to be, i.e. authenticate them against our Kerberos/AD? I can run this:
klist -s ${cache_file}

... and capture the return code in $? (0 means the cache file is readable and not expired), but is klist really a sufficient test for authenticity? E.g. if a malicious user sets up their own Kerberos server, could they successfully use a Kerberos ticket from this server instead?


text:
Q: How to sort the elements of a list based off associated index python I am looking to sort MyArray[] of size n elements so that MyArray[n] = n. If the element is missing it should be replaced with a -1. Here is an example:
Input : MyArray = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]
MyArray = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
MyArrayNew = []
for n in MyArray:
    if n <= len(MyArray):
         MyArrayNew[n] = n
    else:
         MyArrayNew[n] = -1
print(MyArrayNew)

Here is my code thus far, any pointers on how to properly code this would be greatly appreciated!

A: Two ways to sort an array that I know in python

*

*for an inplace sorting: apply the sort() method to your array as
MyArray.sort()

*The second way is to use nested FOR ... LOOP and compare values in the array from Index 0 to the final item. I normally use a temp value to keep the previous value, compare it with the current, and swap the values according to the size. The example code below

     for i in range(len(MyArray)):
            #outer loop
            for j in range(i+1, len(MyArray)):
                #start from i+1,  why because you always want to compare the
                     previous element with the current element in the outer loop
                if(MyArray[i] > MyArray[j]):
                    temp = MyArray[i]
                    MyArray[i] = MyArray[j]
                    MyArray[j] = temp
         print(MyArray)

A: You're making two mistakes.

*

*You use n as an index as well as the value. From the for loop it can be seen that n is the value of each element in the list MyArray. But later on you use this as an index when you call MyArrayNew[n]. When n is -1 there is propably some things that happen that you do not want.

*lists indices can only be changed if they already exist. MyArrayNew starts of empty, so you can't say: change the third index to three, because the third index doesn't exist yet.

There are many approaches to solve this problem. I'll give one:
To solve the second problem I suggest appending instead of assigning indices. To solve the first problem, you could use for i in range len(arr):, but I prefer enumerate.
I'll also approach it the other way around: cycle through the indices and check if it should be its index value, or -1.
This results in the following code:
MyArray = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
MyArrayNew = []
for index, value in enumerate(MyArray):
    if index in MyArray:
        MyArrayNew.append(index)
    else:
        MyArrayNew.append(-1)

print(MyArrayNew)


text:
Q: RDLC C# Winform/WPF Print two copies on same page for File/Audit reasons This is a very specific issue I am having. I have a need to print two (or three, or four) copies of the exact same report on the same page.
The reason, is that Invoice are pre formatted, and for audit reasons creates multiples copies on the same page. So every time I print a new Invoice, I need to print on the same page multiple copies that is defined by the customer.
here is what I have tried:
1) Try to make two copies, but the printer mistakes it for two pages, so spits out the page before it prints out.
2) Try to push everything into the body. At first this idea is very promising. But the body grows when the Tablix grows. If I can solve this issue, then the problem resolves itself.
Can anybody help??

A: After much searching and now benefit, I took a shortcut solution:
Here is what we did:
1) Moved all items into the body. This allowed us to copy the elements over again as many time as necessary inside the page/body height and width.
2) In the codebehind, added a parameter that asked for MaxRow for the detail. Based on that, how ever many rows I had in the actual invoice, the code would just add blank rows to complete the MaxRow number.
So if my Max Row is 15. And my invoice has 2 rows, the system would just create 13 blank rows. If in another invoice, I had 10 rows, the system would just create 2 blank rows.
With that little short cut, I would always have the same tablix size, and therefore always maintain the same body size.


text:
Q: Generating examples of smooth manifold with boundary I'm having difficulties proving lemma  3 of Milnor, Topology from the differentiable point of view. The lemma intends to give us a way to generate examples of mainfold with boundary. The lemma states the following:
Let $M$ be a smooth manifold without boundary and let $g:M \to \mathbb{R}$ have $0$ as regular value. The set of $x$ in $M$ with $g(x) \geq 0$ is a smooth manifold, with a boundary equal to $g^{-1}(0)$.
What I have so far:
I supposed $g$ is a smooth function because of the existence of regular value for $g$ and the general context  of the book.
Because $g$ is smooth, $g^{-1}((0,+\infty))$ is open in $M$. Therefore, $g^{-1}((0,+\infty))$ is a smooth manifold of dimension $m$, as is $M$. By a preceding lemma, we know $g^{-1}(0)$ is a smooth manifold of dimension $m-1$. In that case, for every point $x \in g^{-1}(0)$ there exists an open neighborhood of $x$ diffeomorphic to an open set in $\mathbb{R}^{m-1}$.
To conclude:
To conclude the proof that $g^{-1}([0,+\infty))$ is a smooth manifold, I need to show that we can map with a diffeomorphism every small enought neighborhood in $g^{-1}([0,+\infty))$ to $V \cap H^{m}$, with the points of the boundary $g^{-1}(0)$ mapped to $\partial H^m$. Here, $H^m$ is the half-space $\{(x_1,...,x_m) \in \mathbb{R}^m\vert x_m \geq 0 \}$ and $V$ is an open set of $\mathbb{R}^m$.
I do not know how to proceed from here. Any help is greatly appreciated.

A: There are several ways of showing this; here's a sketch of one path:
Fix $p\in g^{-1}(\{0\})$. Since you have already showed that $g^{-1}(\{0\})$ is an embedded codimension $1$ submanifold, you can choose local coordinates $(x^1,\cdots,x^{n-1})$ with domain $U$, where $p\in U\subseteq g^{-1}(\{0\})$. Shrinking $U$ as necessary, we can arbitrarily extend the $x^i$ to smooth functions $M\to\mathbb{R}$. One can then use inverse function theorem to show that $(x^1,\cdots,x^{n-1},g)$ forms a coordinate chart on $M$ when restricted to a sufficiently small neighborhood of $p$, and restricting this map to $g^{-1}([0,\infty))$will give the desired boundary chart.


text:
Q: what does the "event.type " in the book mean? I read the  javascript for  web developer and I find  that words

<input type="button" value="click me" onclick="alert(event.type)">

I don't understand why the books say it output "click" ;why the event.type point to that

A: This alerts the "event.type". The event type is "click" as in this alert only works when you "click" the button. See more examples here: https://javascript.info/introduction-browser-events

A: The type property of an event object tells you the type of event it is.
It is a click event because it the event listener is a click event listener (assigned with the onclick attribute).
It might be more useful if you were using an event handler function that was shared among different types of events and you needed subtle differences between how they were handled.


text:
Q: Change Icon from FontAwesomeIcon on Function (onChange Text Input) I'm thinking about changing the icon which is set using the fontawesome-react package depending on a previous user interaction.
On screen the user has a input field and button (which contains an icon). If the Input is empty a different icon is presented
No User Input:
+-----------------------+-----------+
| Search Placeholder... | (Shuffle) |
+-----------------------+-----------+

User Input:
+-----------------------+-----------+
| Value                 | (Search)  |
+-----------------------+-----------+

when setting the icon manually inside the <FontAwesomeIcon> I'm able to find faSearch, When however setting it using state I get the error:
Could not find icon {prefix: 'fas', iconName: 'faSearch'}

Here's my take so far. I'd be really happy if someone is able to assist and is able to explain what I'm missing.
class Search extends React.Component {

  state = {
    displayIcon: "faSearch",
  }

  onChange(event) {
    console.log(event.target.value)

    if(event.target.value === ''){
      this.setState({
        displayIcon: "faShuffle",
      })
    } else {
      this.setState({
        displayIcon: "faSearch",
      })
    }
  }

  render(){
    const { displayIcon } = this.state //destucture state

    console.log( );
    return (
      <>

        <InputGroup className="mb-3">
        <FormControl
          placeholder="search or feel lucky..."
          onChange={this.onChange}
        />

        <Button variant="primary" id="search" size="lg">
          <FontAwesomeIcon icon={displayIcon} />
        </Button>

        </InputGroup>
      </>
    )
  }

}

A: you can also do that like this and render it conditionally:
class Search extends React.Component {
  state = {
    value: '',
  };

  onChange(event) {
    this.setState({
      value: event.target.value,
    });
  }

  render() {
    const { value } = this.state; //destucture state

    return (
        <InputGroup className='mb-3'>
          <FormControl placeholder='search or feel lucky...' onChange={this.onChange} />

          <Button variant='primary' id='search' size='lg'>
            {value ? <FontAwesomeIcon icon={faSearch} /> : <FontAwesomeIcon icon={faShuffle} />}
          </Button>
        </InputGroup>
    );
  }
}

A: Maybe instead of passing an object you could try to pass a string for fa-search like so:
<FontAwesomeIcon icon='fas fas-search />
The implementation in onChange being:
if(event.target.value === ''){
      this.setState(
        'fa fa-shuffle', // don't know this one check it on https://fontawesome.com/v5/icons/random?s=solid
      )
    } else {
      this.setState(
        'fas fas-search'
      )
    }


text:
Q: How can I access the value of input inside yup object? I'm using formik in react for validation but right now I need the value of firstName inside yup.object({}). How can I access that?
const validationSchema = yup.object({
        firstName: yup
          .string("Enter your First Name")
          .required("First Name is required"),
    })
 const formik = useFormik({
    initialValues: {
      firstName: ""
    },
    validationSchema: validationSchema,
})

A: You can use test for this
const validationSchema = yup.object({
        firstName: yup
          .string("Enter your First Name")
          .test(name for the test, validation message, (value) => this gives your value)
    })

Refer
1.Using Test in Yup
2.Using When in Yup


text:
Q: missing custom event in GA4 through Google Analytics Data API v4 We have a website with GA4 and want to set up data collection using Google Analytics Data API v4. We can see all custom events we defined show up Google Analytics UI under Engagement/Events. But when we call https://analyticsdata.googleapis.com/v1beta/ some of them are missing.
To be specific we are running the following to get list of all dimensions and metrics:
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import GetMetadataRequest

property_id = "PROPERTY_ID"
client = BetaAnalyticsDataClient()
request = GetMetadataRequest(name=f"properties/{property_id}/metadata")
print(client.get_metadata(request=request))

Does anyone know why some events are not showing up with the above code?
Thank you!
EDIT:
I found that only events marked as conversion (Configure/Events) show up in the metadata. But why?
EDIT2:
According to https://developers.google.com/analytics/devguides/reporting/data/v1/advanced#event-scoped_custom_dimensions https://analyticsdata.googleapis.com/v1beta/properties/GA4_PROPERTY_ID/metadata only returns metrics and dimensions. So I guess I need to use something else to retrieve all events?


text:
Q: web config error unable to uplaod files on server on asp.net i am using web config below  to upload files in the server asp.net 4.0 but i am getting error regrading this    below is my web config code what to do ?
<?xml version="1.0"?>
<configuration>

  <system.webServer>
     <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
  <system.web>
 <authentication mode="Windows"/>
 <identity impersonate="true" />

    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>

    <sessionState timeout="1000" regenerateExpiredSessionId="true">

    </sessionState>

<customErrors mode="Off" />
<machineKey validationKey="1234567890123456789012345678901234567890AAAAAAAAAA"
 decryptionKey="123456789012345678901234567890123456789012345678"
 validation="SHA1" decryption="Auto" />

</system.web>
  <connectionStrings>
   <add name="cityxisConnectionString" connectionString="Data Source=66.63.181.66;Initial Catalog=testdb;User ID=testadmin;Password=Trial@!789" providerName="System.Data.SqlClient"/>

    <add name="myConnectionString" connectionString="Data Source=192.168.1.1;Initial Catalog=temp;User ID=temp;Password=temp" providerName="System.Data.SqlClient"/>

  </connectionStrings>
<system.webServer>
    <handlers>
      <add name="AjaxFileUploadHandler" verb="POST" path="AjaxFileUploadHandler.axd" type="AjaxControlToolkit.AjaxFileUploadHandler, AjaxControlToolkit"/>
    </handlers>
  </system.webServer>

</configuration>

but i am Unable to upload files  on server error
  Access to the path 'E:\domains\mywebsite.co.in\httpdocs\cover\3128.jpg' is denied.

    FileUpload1.SaveAs(Server.MapPath("/cover/" + Session["upkey"].ToString() + fileName));


text:
Q: Current Of a Charged Rod at Constant Velocity Imagine you have a charged rod (more precisely, a charged line), with uniformly distributed total charge q, moving through space at a constant velocity v. What would be the resulting current from said moving charges? I thought that it would just be q*v, but current has units of coulombs per second, and charge times velocity would result in units of coulombs * meters per second, which doesn't add up.

A: Let $L$ be the length of the rod. The charge per unit length of the rod is $q/L$. Now imagine a surface through which you want to calculate the current. Suppose the rod is passing through the surface and is normal to it (this second assumption isn't actually necessary, it might just help you picture it). During a time interval $\Delta t$, a portion of the rod of length $v\Delta t$ passes through the surface, carrying a charge of $qv\Delta t/L$. The current is the charge passing through the surface per unit time, which is $qv/L$.

A: Let's find the  current density as in this situation I believe its more appropriate.
$\vec{J} = \rho \vec{V}$
Where $\rho$ is charge density, not charge. (Q/m^3)
$\rho$ = total charge/volume
Once you find the current density this should give you enough information to find the corresponding magnetic field.
However if for some reason you'd want to find the current through a cross sectional area of the rod, then compute the flux integral of $\vec{J}$ about your chosen cross section.
P.s if $\vec{V}$ is not parrallel to axis of the rod, then I would not even attempt to find current  and instead use current density. If the velocity is parrallel to the axis  simply multiply $|\vec{J}|$ by the area of your rod to find current.


text:
Q: Using SweetAlert to Display messages after inserting data to MySql using php I have combined html, php and ajax to insert data in mysql database. And I want to display success or error messages in ajax success function using SweetAlert. The data is getting inserted into the database but I am unable to display the messages.
Following is my code:
insert.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("hotelmanagement", $connection);

$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$phone =  $_POST['phone'];
$email =  $_POST['email'];
$checkInDate =  $_POST['checkInDate'];
$checkOutDate =  $_POST['checkOutDate'];
$adults =  $_POST['adults'];
$children =  $_POST['children'];
$specialInstructions =  $_POST['specialInstructions'];
$query = mysql_query("INSERT INTO reservation(FirstName,LastName,Address1,Address2,Phone,Email,Adults,Children,CheckInDate,CheckOutDate,SpecialInstructions) VALUES('$fName','$lName','$address1','$address2','$phone','$email','$checkInDate','$checkOutDate','$adults','$children','$specialInstructions')");

echo json_encode($query);

mysql_close($connection);

?>
And this is my ajax code:
$("#submit").click(function(){
    var fName = $("#fName").val();
    var lName = $("#lName").val();
    var address1 = $("#address1").val();
    var address2 = $("#address2").val();
    var phone = $("#phone").val();
    var email = $("#email").val();
    var checkInDate = $("#checkinDate").val();
    var checkOutDate = $("#checkoutDate").val();
    var adults = $("#adults").val();
    var children = $("#children").val();
    var specialInstructions = $("#specialInstructions").val();

    if(fName == '' || lName == '' || phone == ''){
        swal("Oops!!", "Looks like you missed some fields. Please check and try again!", "error");
    }else{
        $.ajax({
            type:'post',
            url:'insert.php',
            data: {fName:fName,lName:lName,address1:address1,address2:address2,phone:phone,email:email,checkInDate:checkInDate,checkOutDate:checkOutDate,adults:adults,children:children,specialInstructions:specialInstructions},
            dataType:'json',
            succcess:function(data){
                swal("Success", "Data Saved Successfully", "success");
            },
            error:function(xhr, thrownError, ajaxOptions){

            },
        });
    }
});

Could you please tell me what am I missing. Thank you.

A: your success callback is triple ccc and try to remove dataType:'json',
try this ajax request
$.ajax({
            type:'post',
            url:'insert.php',
            data: {fName:fName,lName:lName,address1:address1,address2:address2,phone:phone,email:email,checkInDate:checkInDate,checkOutDate:checkOutDate,adults:adults,children:children,specialInstructions:specialInstructions},

            success:function(data){
                swal("Success", "Data Saved Successfully", "success");
            },
            error:function(xhr, thrownError, ajaxOptions){

            }
       });


text:
Q: EnumMap & streams Hi tried to figure out how to map to a EnumMap without success.
At the moment I'm doing it in 2 steps, I create the map and then I make it a EnumMap.
Question are.

*

*Is it possible to do it in only one step?

*From efficiency perspective would be better to get Values from
input, make them a set and then stream it, or just using  toMap as
its right now is correct. thanks
Map<CarModel, CarBrand> input...
final Map<CarBrand, CarsSellers> ret = input.values()
            .stream().filter(brand -> !brand.equals(CarBrand.BMW))
            .collect(toMap(Function.identity(), brand -> new CarsSellers(immutableCars, this.carsDb.export(brand))));

 final EnumMap<CarBrand, CarsSellers> enumMap = new EnumMap<>(CarBrand.class);
    enumMap.putAll(ret);

A: TL;DR: You need to use the other toMap method.
By default a toMap uses HashMap::new as the Supplier<Map> - you need to supply a new EnumMap instead.
final Map<CarBrand, CarsSellers> ret = input.values()
        .stream()
        .filter(brand -> brand != CarBrand.BMW)
        .collect(toMap(
                identity(),
                brand -> new CarsSellers(immutableCars, this.carsDb.export(brand)),
                (l, r) -> {
                    throw new IllegalArgumentException("Duplicate keys " + l + "and " + r + ".");
                },
                () -> new EnumMap<>(CarBrand.class)));

Arguments are:

*

*the key extractor

*the value extractor

*a "mergeFunction" that takes two values, one that already exists in the Map and one to be added. In this case, we simply throw an IllegalArgumentException as keys should be unique

*the "map supplier" - this returns a new EnumMap.

Notes on your code:

*

*program to the interface - Map not EnumMap

*enum is singleton, so you can use a != Enum.VALUE

*an import static for Function.identity() makes things less verbose


text:
Q: Why are primary network interfaces forced to inherit all the security groups of their EC2 instances? I'm testing a virtual load balancer which is running on an EC2 instance.  I'd like to be able to alter the setup and test the balancer under various conditions.  In order to simulate a physical load balancer I've assigned three network interfaces to the instance:

*

*External (Primary) - An exposed interface to the web.  The AWS rules will be set to allow all traffic to this interface.  The load balancer will set up its own IP/port rules to filter this traffic internally.  Connections to this interface will arrive from both inside and outside the VPC.

*Management - A dedicated interface with rules set to allow HTTPS traffic to the Load balancer's web interface or SSH traffic to a management shell running on the load balancer.  Management connections will be established from computers which are outside the VPC.

*Internal - The interface through which all instances behind the load balancer will connect.  Connections on this interface will be mapped to connections on the external interface by the load balancer.  Connections to the internal interface will only arrive from instances which are inside the VPC.

In order to simulate physical connections I'd like to apply some AWS security group rules to these interfaces so that only connections between certain instances in the VPC are allowed (IE: they're plugged into each other).  In order to do this I've created a separate security group for each interface (internal, management, and external).
My understanding is that rules within a security group are applied to all inbound and outbound traffic on the interfaces which belong to them.  Since each interface in this setup serves a distinct role I'd like each interface to belong to one (and only one) security group.
What's unclear to me is what it means for an instance itself (as opposed to its interfaces) to belong to a security group.  My thinking is that since the load balancer instance will be communicating on all three interfaces that it should belong to all three security groups.
Unfortunately, when I apply the internal and management security groups to the instance it forces the external interface to also be in the internal and management security groups.
Likewise, when I remove the internal and management security groups from the external interface it removes the instance from those security groups too.
Are security groups applied to an instance just a superfluous configuration shortcut (IE: only the security groups applied to the network interfaces actually matter), is there some other way to achieve the configuration that I want, or am I thinking about the problem wrong and there's a reason for AWS to prevent this configuration?

A: While it might be implied that AWS instances have security groups, in practice network interfaces have security groups. Each interface (provided with the instance or an ENI) can have its own security groups. Any security group can be applied to as many network interfaces as you need.

A: Because that's how it works, and how it's documented to work.
The ability to apply a security group to an instance is just syntactic sugar. As documented, it applies the security group to that instance's primary network interface.


text:
Q: How to return Array List element from method I'm trying to pass an individual elements of CordsArray from the public class Enemy() to the main.
public class Enemy {

//constructor
public Enemy()
{
    //*create array of coordinates
    ArrayList<Integer> CordArray = new ArrayList<Integer>();

    CordArray.add(0,2);
    CordArray.add(1,5);
    CordArray.add(2,8);
    CordArray.add(3,10);
}

public static int returnCords(int[] CordArray, int index)
{
    return CordArray[index];
}

I'm wanting to output elements of the CordArray to the console by calling returnCords in main:
System.out.println(returnCords(CordArray, 0));
But a 'CordArray cannot be resolved to a variable' error appears. Apologies for bad English.

A: The problems are:
-variable names should begin with lowercase letter,
-lists can contain single objects/values, you are trying to store two at one index
Create Coords object instead:
public class Coords{
    private int x;
    private int y;

    public Coords(int x, int y){
        this.x = x;
        this.y = y;
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }
}

Now you can do this:
ArrayList<Coords> cordArray = new ArrayList<Coords>();

Hope it helps.

A: try using point and a global arraylist with a get function
import java.awt.Point;
import java.util.ArrayList;

public class Enemy {

    private final ArrayList<Point> points;

    public Enemy() {
        points = new ArrayList<>();
        points.add(new Point(2, 5));
        points.add(new Point(8, 10));
    }

    public ArrayList<Point> getPoints() {
        return points;
    }

    public static void main(String[] args) {
        Enemy enemy = new Enemy();
        int index = 0;
        Point point = enemy.getPoints().get(index);
        int x = point.x;
        int y = point.y;
    }
}


text:
Q: Можно ли перебирать строки в stdout_lines без указания конкретной строки в ansible Я написал плейбук который сохранял в переменную названия таблиц в базе данных. Теперь мне нужно сопоставить каждую! строку с grep. Т.е. если grep нашел файл который подходит под название то он отправлял его в базу данных (для восстановления). Саму процедуру отправки в базу данных я понимаю как сделать. Сама суть что я хочу сделать: чтобы задача Compare tables and dumps выполнялась для каждого значения в переменной. Можно ли как-нибудь сделать чтобы stdout_lines прогонялась не для конкретно 0 или 1 элемента а для каждого. Что то вроде цикла for на манер ansible
- name: Getting tables into clickhouse
  shell:
    cmd: 'docker exec -i clickhouse clickhouse-client -d default --query "SHOW TABLES;"'
  register: tables

- debug:
    var: tables.stdout_lines

- name: Compare tables and dumps
  shell:
    cmd: "ls /data/data/backups/clickhouse/ | grep -E {{ tables.stdout_lines[0] }} "
  register: output

- debug:
    var: output.stdout_lines