text:
Q: Python can't find BBIO.GPIO library on Raspberry I am trying to set up an Adafruit 'RGB backlight positive LCD 20x4'  using this tutorial:
https://learn.adafruit.com/character-lcd-with-raspberry-pi-or-beaglebone-black/usage
When I go to the examples directory and run 'char_lcd_rgb.py', I get an error:
'ImportError: No module named Adafruit_BBIO.GPIO'
Why am I getting an error for a Beaglebone library on a Raspberry Pi?
Should I install BBIO.GPIO on the Raspberry or is there something wrong elsewhere?
[(Pi Version 3), (Python v 2.7.9)]

A: Found my problem.  A function in Platform.py was not finding the string 'BCM2835' assuming my platform was a Beaglebone.
A kind user suggested that I re-install Adafruit_Python_GPIO as that includes code for the 4.9 kernel.


text:
Q: Communication between Meteor and nodejs apps I have a Meteor platform with four node apps/servers inside. I'm using seamless iframes to make it look like they are all a whole package while I stay in control, so if one app goes wrong it won't affect the other three nor the platform.
Now, my question is: How to share the same userid between the apps? I can query MongoDB from Node asking for a userid, but how can I query asking for the same userid the online user has in Meteor? One login for everything, that's what I need.
Edit: What about Faye or SimpleBus?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to specify the command line width in octave? I would like to use octave as a "calculator" in a python script. Currently I am running octave like so:
octave -q --eval 'some code'

and read the stdout to interpret the results.
However, I am running into problems once matrices reach a certain width so that octave starts to output them with column numerations like so:
ans =

 Columns 1 through 5:

   6.6264e-01   2.6142e-01   9.2413e-01   1.6814e-01   6.3117e-01

Columns 6 and 7:

   6.6392e-01   4.0483e-01

which makes the interpreting of the result a little harder.
Is there a way to tell octave not to split up the printing of results?

A: The split_long_rows () command should be able to change this behavior.  From the documentation,

Query or set the internal variable that controls whether rows of a matrix may be split when displayed to a terminal window


text:
Q: windows phone sidebar menu I have some application on my Android. an some of this apps have unvisible menu on left side. when user clicks on icon on the top of form it shows menu on left but do not close current form. here is picture from GooGLE+ app for android.
I want to create app with left side menu as in Google+ app but for Windows Phone 7.X
I have Visual Studio 2010, Silverlight 4 and Silverlight 5 installed. And i use C# as a language

Update(clarification): My question is what is the alternative to the menu in the picture in WP platform?

A: Well there is not an easy way to do that like iOS. But you can use Visual State Manager.
Basically, Shape a bigger screen than your stage. Then, you need to create a state which will shift your screen a little bit left in the stage and you can use a button. You need to call the state on button's on click method.
PS: Do not use storyboard. Use the States it is easiest way to do that.


text:
Q: Finding Overlaps between interval sets / Efficient Overlap Joins Overview:
I need to join two tables:
ref  contains the time intervals (from t1 to t2) along with an id for each interval and a space where this interval occurs.
map contains time intervals (t1 to t2) each with a result res and its corresponding space.
I wish to obtain/join all intervals (and their score) of map that fall within the intervals in ref onto ref.
example:
ref <- data.table(space=rep('nI',3),t1=c(100,300,500),t2=c(150,400,600),id=letters[1:3])

map <- data.table(space=rep('nI',241),t1=seq(0,1200,by=5),t2=seq(5,1205,by=5),res=rnorm(241))

they look like:
> ref
space  t1  t2 id
1:    nI 100 150  a
2:    nI 300 400  b
3:    nI 500 600  c

> map
space   t1   t2        res
1:    nI    0    5 -0.7082922
2:    nI    5   10  1.8251041
3:    nI   10   15  0.2076552
4:    nI   15   20  0.8047347
5:    nI   20   25  2.3388920
---
237:    nI 1180 1185  1.0229284
238:    nI 1185 1190 -0.3657815
239:    nI 1190 1195  0.3013489
240:    nI 1195 1200  1.2947271
241:    nI 1200 1205 -1.5050221

(UPDATE) Solution

*

*?data.table::foverlaps is the key here.

I need to join all the map intervals that occur "within"  the intervals of ref and I am not interested in intervals that do not match this key so use nomatch=0L.
setkey(ref,space,t1,t2)

foverlaps(map,ref,type="within",nomatch=0L)

which gives:
space  t1  t2 id i.t1 i.t2         res
1:    nI 100 150  a  100  105 -0.85202726
2:    nI 100 150  a  105  110  0.79748876
3:    nI 100 150  a  110  115  1.49894097
4:    nI 100 150  a  115  120  0.47719957
5:    nI 100 150  a  120  125 -0.95767896
6:    nI 100 150  a  125  130 -0.51054673
7:    nI 100 150  a  130  135 -0.08478700
8:    nI 100 150  a  135  140 -0.69526566
9:    nI 100 150  a  140  145  2.14917623
10:    nI 100 150  a  145  150 -0.05348163
11:    nI 300 400  b  300  305  0.28834548
12:    nI 300 400  b  305  310  0.32449616
13:    nI 300 400  b  310  315  1.16107248
14:    nI 300 400  b  315  320  1.08550676
15:    nI 300 400  b  320  325  0.84640788
16:    nI 300 400  b  325  330 -2.15485447
17:    nI 300 400  b  330  335  1.59115714
18:    nI 300 400  b  335  340 -0.57588128
19:    nI 300 400  b  340  345  0.23957563
20:    nI 300 400  b  345  350 -0.60824259
21:    nI 300 400  b  350  355 -0.84828189
22:    nI 300 400  b  355  360 -0.43528701
23:    nI 300 400  b  360  365 -0.80026281
24:    nI 300 400  b  365  370 -0.62914234
25:    nI 300 400  b  370  375 -0.83485164
26:    nI 300 400  b  375  380  1.46922713
27:    nI 300 400  b  380  385 -0.53965310
28:    nI 300 400  b  385  390  0.98728765
29:    nI 300 400  b  390  395 -0.66328893
30:    nI 300 400  b  395  400 -0.08182384
31:    nI 500 600  c  500  505  0.72566100
32:    nI 500 600  c  505  510  2.27878366
33:    nI 500 600  c  510  515  0.72974139
34:    nI 500 600  c  515  520 -0.35358019
35:    nI 500 600  c  520  525 -1.20697646
36:    nI 500 600  c  525  530 -0.01719057
37:    nI 500 600  c  530  535  0.06686472
38:    nI 500 600  c  535  540 -0.40866088
39:    nI 500 600  c  540  545 -1.02697573
40:    nI 500 600  c  545  550  2.19822065
41:    nI 500 600  c  550  555  0.57075648
42:    nI 500 600  c  555  560 -0.52009726
43:    nI 500 600  c  560  565 -1.82999177
44:    nI 500 600  c  565  570  2.53776578
45:    nI 500 600  c  570  575  0.85626293
46:    nI 500 600  c  575  580 -0.34245708
47:    nI 500 600  c  580  585  1.21679869
48:    nI 500 600  c  585  590  1.87587020
49:    nI 500 600  c  590  595 -0.23325264
50:    nI 500 600  c  595  600  0.18845022
space  t1  t2 id i.t1 i.t2         res

A: Ha, nice timing :). Just a few days back, overlap joins (or interval joins) was implemented. in data.table The function is foverlaps() and is available from the github project page. Make sure to have a look at ?foverlaps.
setkey(ref, space, t1, t2)
foverlaps(map, ref, type="within", nomatch=0L)

I think this is what you're after. This'll result in the join result only where there's a match, and it'll check for t1,t2 overlaps between ref and map within space identifier.. If you don't want that, just remove space from the key column. And if you want all matches, remove nomatch=0L - the default is nomatch=NA which returns all.
The function is new (but has been rigorously tested) and is therefore not feature complete. If you've any suggestions for improvement or come across any issues, please feel free to file an issue.


text:
Q: How to *secure erase* a NVMe SSD Since SSD has write amplification, I want to reset the SSD to the initial out-of-box performance. Most tutorials are for SATA SSD (hdparm --secure-erase), I want to know how to erase a partition of NVMe SSD (maybe use nvme command?).
One more question: does dd if=/dev/zero of=/dev/nvme0n1 help? Or does fio --filename=/dev/nvme1n1 --direct=1 --buffered=0 --rw=trim --bs=4k --size=100G --numjobs=16 --iodepth=32  --group_reporting --name=trim help?
Thanks!

A: For resetting to Out Of Box performance you DO NOT want to use the "write zeroes" technique of dd/fio. There is a BIG semantic difference saying "this area must contain and maintain zeroes" (fio/dd technique) and saying "this area is must be empty" (secure erase). For example the Solid State Storage (SSS) Performance Test Specification (PTS) specifies techniques it considers reasonable for preconditioning.

A: As OldFred's post states, you need to use an actual secure erase utility, such as the nvme-cli package.
The reason this will run so quickly is because the drive's contents are already transparently encrypted. That is, if you were to read the flash chips directly, you would not find any of the content you see on your drive when accessing it normally. The onboard controller handles this process completely transparently, storing the encryption key in a secure enclave within the controller.
This is useful both from a security and longevity standpoint. Encrypting data helps soften repetitive pattern writes from being so repetitive, which in turn helps to decrease the wear and tear on flash cells.
When you run a secure erase on an SSD, no data is actually being erased -- instead, the controller is generating a new encryption key and writing it into the secure enclave, overwriting the old key in the process and permanently rendering all binary data on the flash cells unrecoverable.

A: To totally erase a NVMe drive.
This will erase entire drive.
You may need to first install nvme - the NVMe storage command line interface utility (nvme-cli). Then review commands and list all nvme devices. List wil also show firmware revision & you should check that you have latest firmware.
sudo apt install nvme-cli
nvme help
nvme --help
nvme --help format
sudo nvme list
sudo nvme format -s1 <device>

    fred@z170-focal-k:/mnt/data$ sudo nvme list
[sudo] password for fred:
Node             SN                   Model                                    Namespace Usage                      Format           FW Rev
---------------- -------------------- ---------------------------------------- --------- -------------------------- ---------------- --------
/dev/nvme0n1     S4P2NF0M514514L      Samsung SSD 970 EVO Plus 500GB           1         164.30  GB / 500.11  GB    512   B +  0 B   2B2QEXM7


text:
Q: How to enrich data from custom react hook In my React application I have created a custom hook which returns a set of data wherever used.
It's used like const projects = useProjects();
It's an array of objects , we can assume it looks like this :
 [{project_id : 123 , name : 'p1'} , {project_id : 1234 , name : 'p2'} ]

Now I need to enrich this data with data from an API. So i have to loop through projects and basically add a new field to each object, so the new array of objects will look like this :
[{project_id : 123 , name : 'p1' field3: 'api data'} , {project_id : 1234 , name : 'p2' , field3: 'api data1' } ]

How can I achieve this ?
What I did was loop through the projects data and directly added the field inside the loop. But I dont know if i should be mutating this data like that ? I was hoping to see if this is good practice or not.

A: There's a few ways you could solve this - it all depends on how you're getting the data back from the API. If you want to have that injected into the hook, you could do something like this -
const DEFAULT_PROJECTS = [
    { project_id : 123, name: 'p1' },
    { project_id : 1234, name: 'p2' },
];

const useProjects = (dataFromApi) => {
    // Assuming that dataFromApi is what you got back from your API call,
    // and it's a dictionary keyed on the project_id.
    return useMemo(() => {
        return DEFAULT_PROJECTS.map(proj => {
            const extraData = dataFromApi.get(proj.project_id) || {};

            return {
                ...proj,
                ...extraData,
            };
        });
    }, [dataFromApi]);
};

The useMemo here isn't super helpful if the dataFromApi is always changing - it will just rebuild the returned object every time.
If you wanted to get the data as part of your hook, you do something like this -
import { useEffect, useMemo, useState } from 'react';

const DEFAULT_PROJECTS = [
  { project_id : 123, name: 'p1' },
  { project_id : 1234, name: 'p2' },
];

const useProjects = () => {
  const [dataFromApi, setDataFromApi] = useState(null);

  useEffect(() => {
    if (!!dataFromApi) return;

    // Simulate the data fetch
    const fetchData = async () => {
      return new Promise(resolve => {
        setTimeout(() => {
          const map = new Map();
          map.set(123, {
            field3: 'api data',
            field4: 'other data',
          });

          setDataFromApi(map);
        }, 2000);
      });
    };

    fetchData();
  }, [dataFromApi]);

  return useMemo(() => {
    let extraData = dataFromApi || new Map();

    return DEFAULT_PROJECTS.map(proj => {
      const extraFields = extraData.get(proj.project_id) || {};

      return {
          ...proj,
          ...extraFields,
      };
    });
  }, [dataFromApi]);
}

export default useProjects;

Here's a code sandbox that shows it in action.


text:
Q: get values of object in an array with another array of objects I have an array of objects :
let formInputs = [
    {"name" : "NOM_MANDATAIRE", "fieldType": "input", "type": "text", "values": []},
    {"name" : "SECTEUR_VENTE", "fieldType": "select", "type": null, "values": [
        {"key": "1", "value": "text of the select"},
        {"key": "2", "value": "text of the select"}
    ]},
    {"name" : "TITRE_VERSION", "fieldType": "input", "type": "text", "values": []},
];

I use a forEach to get each objects and manipulate them :
formInputs.forEach(element => {
    console.log(element.name);
    ...
    for (let items in element.values) {
        for (item in items) {
            console.log(item.key);
        }
    }
}

My issue is that i'm stuck when I want to retrieve the object associated to the key "values".
In the forEach block i also tried to use a for each :
item returns 0 and item.key returns undefined.


text:
Q: Attempting to do a fetch DELTE but keep getting syntax error: Unexpected end of JSON input I am attempting to do a fetch DELETE request from my client React app and am getting the following error when I try to delete a note from my app:

error: SyntaxError: Unexpected end of JSON input

I get this error in the console and I can still see the note however, if I refresh the page the note is gone. How can I fix this?
handleClickDelete = e => {
  e.preventDefault();
  const noteId = this.props.id;

  fetch(`http://localhost:8000/api/notes/${noteId}`, {
      method: "DELETE",
      headers: {
        "content-type": "application/json"
      }
    })
    .then(res => {
      if (!res.ok) return res.json().then(error =>
        Promise.reject(error));
      return res.json();
    })
    .then(() => {
      this.context.removeNote(noteId);
      this.props.onDeleteNote(noteId);
    })
    .catch(error => {
      console.error({
        error
      });
    });
};

A: @Laxmikant is right. You should have an empty body and in your response and in your callback you are trying to parse your response to a JSON: res.json()


text:
Q: Remove space between bounds and button border How do I remove those space between Button border and view bounds tried setting padding to 0dp but with no results.
These is material button with default style.

A: The MaterialButton has a default style with these insets:
 <style name="Widget.MaterialComponents.Button"..>
    <item name="android:insetLeft">0dp</item>
    <item name="android:insetRight">0dp</item>
    <item name="android:insetTop">@dimen/mtrl_btn_inset</item>
    <item name="android:insetBottom">@dimen/mtrl_btn_inset</item>
    ...
 </style>

The value of @dimen/mtrl_btn_inset is 6dp.
Just use:
  <com.google.android.material.button.MaterialButton
      android:insetTop="0dp"
      android:insetBottom="0dp"
      ../>

A: you can use weight and make the width 0dp then space will be removed.


text:
Q: Question about a sentence construction (has/have)

*

*Who have we got in the next round?

*Who have you arranged to meet later on?

*Who have they coming over for dinner?

i know that after who we put has like this example

who has the car?

but in those 3 sentences thay put have could you tell me why please ?

A: The verb matches the subject of each sentence:  1. We , 2. You, 3. They.
Example:

Who have we got in the next round?   We have Bruce the Bruiser against Max the Mangler!

In the case where we don't know the subject, we assume it's a singular entity (he, she, or it, some proper name like Michael, Francine, or Bill the Cat, or some other named entity like the President, the neighbor, etc.).

Who is making dinner tonight?  Frank is -- he is making stew.

Side note: You originally wrote "ye" which I changed to "you".  "Ye" is Old English and is no longer commonly used.


text:
Q: Document removal workflow I am trying to create a solution by creating a workflow that moves documents from one site collection to another upon request. We have users that do not have permission to delete documents and we don't want to give that permission, instead we want them to be able to move the document to a different library on a different site collection to be reviewed and decided by a lead whether or not the document should  be deleted. Also, we want to collect information about the need for the removal, such as: reason for removal and the source location of the document, as we have several libraries we want this solution be used in.
So the challenge is, first how to move the document to a different site collection and second, how to add the move reason and document origin with out changing the content types the different libraries use.

A: If you are attempting to do this with SharePoint OOTB, you cannot move documents across site collections in a workflow.
A solution I could propose to this might be making the request process automated, but then manually moving the document across site collections, which you can do. When you select a document in the library, in the documents tab on the ribbon, you can select the Send To command. When using this, you would simply input the location of the document library you want to send it to.


text:
Q: What's Taylor expansion of: $f(x)=\frac 1x\ln{(1+2x^2)}$? What's Taylor development on the next function: $f(x)=\frac 1x\ln{(1+2x^2)}$?
Actually this one is the first question I've seen with $ln$, My instincts tell me to try and do derivative in order to get a series i can deal with.
But i got to: $-\frac 1{x^2}\ln{(1+2x^2)}+\frac {4}{1+2x^2}$
I know how to deal with: $\frac {4}{1+2x^2}$
But it seems that keep doing derivatives on: $-\frac 1{x^2}\ln{(1+2x^2)}$ won't help that much, How can i develop this function properly?

A: Hint: find the Taylor expansion for $\ln(1+z)$, if you don't have it in a table.  From there, substitute $z=2x^2$, and divide (term-by-term) by $x$.
I find this is much easier than directly trying to calculate successive derivatives of $f(x)$.

How to deal with the $\frac1x$:
As an example, suppose we were finding the taylor series for $f(x) = \frac1x \sin x$. We know that
$$\sin x =\sum_{k=0}^{\infty} \frac{x^{2k+1}}{(2k+1)!}$$
It follows that
$$
\begin{align}
\frac1x \sin{x}&=\frac1x \sum_{k=0}^{\infty} \frac{x^{2k+1}}{(2k+1)!}\\
&=\sum_{k=0}^{\infty} \frac1x \frac{x^{2k+1}}{(2k+1)!}\\
&=\sum_{k=0}^{\infty} \frac{x^{2k+1-1}}{(2k+1)!}\\
&=\sum_{k=0}^{\infty} \frac{x^{2k}}{(2k+1)!}
\end{align}
$$


text:
Q: Publishing a NuGet package to an organization feed from yaml pipeline Having trouble publishing a NuGet package from a yaml pipeline, restore/build/pack all works ok it's just the pushing that is failing and it seems to be related to the Push generating a bad url for the Artefact feed that I am pushing the package to.
I've been able to push the package from a NuGet command locally and connect to the Artefact feed, the "d____i" is an organization scoped feed and the library is in that feed as you can see, the url seems incorrect to what I get when I go to the "Connect to feed" from the DevOps page, which looks like this below
<add key="d_____i" value="https://pkgs.dev.azure.com/d_____i/_packaging/d_____i/nuget/v3/index.json" />

I'm actually back here again because I had a long break working on some other stuff but now I am back to having to publish my packages to a feed and I'm still running into the same issue.
Different projects but essentially the same issue.
I've given the source project Build Service COntributor access to the target project scoped feed and that didn't work.
I've tried a custom nuget.config but I get 401 errors.
Just strugging with this so bad, I have decided to create a support ticket with Microsoft because I can't believe this is so hard, I'm sure it's not but it's driving me crazy and I'm simply can't move forward now.
Here is my pipeline

Everything works apart from the last step and I get the following error

error: Unable to load the service index for source https://pkgs.dev.azure.com/dorsavi/f021750e-bf44-48e3-8892-3afd18dcddca/_packaging/bf8fd47b-0475-41e9-80fc-8e5c23e7ff8b/nuget/v3/index.json.
error:   Response status code does not indicate success: 404 (Not Found - VS800075: The project with id 'vstfs:///Classification/TeamProject/f021750e-bf44-48e3-8892-3afd18dcddca' does not exist, or you do not have permission to access it. (DevOps Activity ID: 97338923-B00F-4CE5-BB79-0D6BF964864C)).

I'm still going at it, trying different configurations with the push command but so far nothing has worked, including using guids or names of projects/feeds
I'm trying to go from one project "CompanyName.Logging" this has the build pipeline and I'm trying to push to a feed which is a project scoped feed called "CompanyName.Platform" in a project called "CompanyName.Platform" both projects are in the same organization.
If I try to push to a feed called Test in "ComnpanyName.Logging" it works fine.

A: It appears to me your publishVstsFeed isn't set correctly. You would expect to see a GUID of the feed or name (I think in your case, d_____i) here and the path to the package in the packagesToPush property.
This is documented in the task documentation for NuGetCommand@2.
Example:
- task: NuGetCommand@2
  inputs:
    command: 'push'
    nuGetFeedType: 'internal'
    publishVstsFeed: '99303781-4bbb-41d6-a13e-fe40603b9cb7'
    packagesToPush: 'packages/*.nupkg'
    allowPackageConflicts: true


text:
Q: How to apply Zend ACL with neo4j database I have developed a project using zend and neo4j db. Till now I haven't used sessions now I have requirement of applying authorization to various types of users. I don't know whether Zend Acl can be directly implemented with neo4j. If any one used ACL with neo4j and can provide some examples then I would be very grateful to that person. On searching I came up with this link..
Graph Acl
Is it helpful ?

A: There are no built-in ZendAcl Neo4j backed plugins. Note that ZendAcl does not have any built-in persistence features at the core.
You'll need to write an ACL plugin that will then create the necessary Cypher queries.
An example with Doctrine : https://monzee.wordpress.com/2009/06/14/developing-a-doctrine-backed-acl-helper-tdd-style-part-1/


text:
Q: PHP - How to generate unconventional data from a multidimensional array after 10 years I'm starting programming again, just for fun. I'm struggling with the following code in PHP:
This is what I get from the database:
$data[0] = ['id' => NULL, 'titel' => NULL, 'category_id' => NULL];

$data[1] = ['id' => '1', 'titel' => 'Apple', 'category_id' => '123'];
$data[2] = ['id' => '2', 'titel' => 'Pear', 'category_id' => '123'];
$data[3] = ['id' => '3', 'titel' => 'Orange', 'category_id' => '123'];

$data[6] = ['id' => '6', 'titel' => 'Strawberry', 'category_id' => '297'];
$data[7] = ['id' => '7', 'titel' => 'Blueberry', 'category_id' => '297'];
$data[8] = ['id' => '8', 'titel' => 'Raspberry', 'category_id' => '297'];

$data[12] = ['id' => '12', 'titel' => 'Cucumber', 'category_id' => '557'];
$data[13] = ['id' => '13', 'titel' => 'Pumpkin', 'category_id' => '557'];

That's the string I have to generate for the javascript:

'choices': {

    0: {
        text: [''],
        value: ['']
    },
    123: {
        text: ['Apple', 'Pear', 'Orange'],
        value: ['1', '2', '3']
    },
    297: {
        text: ['Strawberry', 'Blueberry', 'Raspberry'],
        value: ['6', '7', '8']
    },
    557: {
        text: ['Cucumber', 'Pumpkin'],
        value: ['12', '13']
    }

}

Can someone help me on that one? I'm trying something like this, but struggling with:
  $text = 'text: [';
  $value = 'value: [';
  $final_str = '';
  $current_category_id = '';

  foreach ($data as $foo) {
    if (($foo['category_id'] != $current_category_id)) {
      $text .= ']';
      $value .= ']';
      $final_str .= '}, ' . $product_id . ': { ' . $text . $value;
      $text = 'text: [';
      $value = 'value: [';
    }

    $text .= '\'' . $foo['titel'] . '\', ';
    $value .= '\'' . $foo['id'] . '\', ';
    $current_category_id = $foo['category_id'];
  }
  $text .= ']';
  $value .= ']';
  $final_str .= $current_category_id . ' { ' . $text . $value;

Thank you very much!

A: Instead of manually building a string, you should generate the data structure and then output it via json_encode:
<?php

$return = [];
foreach($data as $d) {
    $cat_id = intval($d['category_id']);

    if (!isset($return[$cat_id])) {
        $return[$cat_id] = [
            'text' => [],
            'value' => [],
        ];
    }

    $return[$cat_id]['text'][] = strval($d['titel']);
    $return[$cat_id]['value'][] = strval($d['id']);
}

?>

<script>
    ...
    'choices': <?= json_encode($return); ?>
    ...
</script>

If you do echo json_encode($return); it will output:
{"0":{"text":[""],"value":[""]},"123":{"text":["Apple","Pear","Orange"],"value":["1","2","3"]},"297":{"text":["Strawberry","Blueberry","Raspberry"],"value":["6","7","8"]},"557":{"text":["Cucumber","Pumpkin"],"value":["12","13"]}}

You can see it in action at https://3v4l.org/VrHXO

A: First things first: don't try to build that string by hand, you'll just get headaches. Instead, build up the array structure in PHP, and then use json_encode to convert it to JSON.
You can then either cheat and use the JSON directly as a JavaScript variable (always remember that JSON and JavaScript are not the same language, but JSON is almost always valid JavaScript), or use JSON.parse to parse it properly.
The next trick is that since you're building an associative array, you don't need to track the "current" category, you can just add each item into the right place:
$data_by_category = [];
foreach ( $data as $item ) {
    // Force the vategory to be an integer, 0 for null
    $category_id = (int)$item['category_id'];

    // Set up the category the first time you see it
    $data_by_category[$category_id] ??= ['text'=>[], 'value'=>[]];

    // Add the items as you see them, forcing them to be strings
    $data_by_category[$category_id]['text'][] = (string)$item['titel'];
    $data_by_category[$category_id]['value'][] = (string)$item['id'];
}


text:
Q: How to get XML node value in XSLT if we have got XML path in PARAM I am using XSLT 1.0 and have below sample code:
In my XSLT, I have got a param which has my XML path
<xsl:param name="sitespath"/>

I know I can load it as document and then further get the values accordingly, like below
  <xsl:variable name="siteInfoPath" select="document($sitespath)/sitedata/region/site/language"/>

The above siteInfoPath XSLT varaible is loading the document with /sitedata/region/site/language data, however now I want to take PublishDate, below is the XML sample format
<?xml version="1.0"?>
<sitedata>
<resources>
<WorldwideSites>Worldwide sites</WorldwideSites>
<PublishedDate>10/3/2011 9:12:35 AM</PublishedDate>
</resources>
<region code="global" title="Global">
<site defaultLanguage="en" id="tcm:0-233-1" url="/english" countryCode="" title="" order="1">
<language code="en" pubId="tcm:0-233-1" pubPath="\english" Culture="en-GB" ShortDate="dd MMM yy" ShortDateShortDay="ddd dd MMM yy" ShortDateTime="dd MMM yy, HH:mm" LongDate="d MMMM, yyyy" LongDateTime="d MMMM, yyyy, HH:mm" LongDateExtendedShortDay="ddd dd MMM, yyyy" LongDateExtended="dddd, d MMMM, yyyy" LongDateExtendedTime="dddd, d MMMM, yyyy, HH:mm" MonthYear="MMMM, yyyy" OmniturePrefix="ek global:en:" OmnitureReportSuite="emirnewglobalenglish,emirnewibems" OmnitureDevReportSuite="emirglobalendev" sifr="Y" localTitle="" url="/english" mobileRedirect="true" flightStatusAlert="true" GoLiveDate="20071110" targetHost="http://fly1.com" hpSearchF="Yes" hpHotelsCars="Yes" hpMYB="Yes" hpOLCI="Yes" hpFStatus="Yes" hpServicesF="Yes">English</language>
</site>

Do I need to use another variable and need to load document like this
<xsl:variable name="siteInfoDate" select="document($sitespath)/sitedata/resources/PublishedDate"/>

I don't want to load same xml again...please suggest!!

A: Dynamic Xpath evaluation in general requires using an extension function --both in XSLT 1.0 and in XSLT 2.0. This is not a good idea, because you may or maynot find such an extension and may end up needing to write your own. Also, the code's portability is ruined.

Do I need to use another variable and need to load document like this

<xsl:variable name="siteInfoDate" select="document($sitespath)/sitedata/resources/PublishedDate"/>

I don't want to load same xml again...please suggest!!

This is actually the best way to solve the problem.
It is a widespread misconception that issuing more than one calls to the document() function  with the same URL loads and parses the same document more than once.
The W3C XSLT specification defines that the URL typically is loaded and parsed only once -- the function is stable, regardless how many times the document() function is called.
Therefore, there isn't any loss of efficiency.
To eliminate your fears, do (this will help you sleep well, but isn't at all necessary):
<xsl:variable name="vDoc" select="document($sitespath)"/>

<xsl:variable name="siteInfoDate"
              select="$vDoc/sitedata/resources/PublishedDate"/>

<xsl:variable name="siteInfoPath"
   select="$vDoc/sitedata/region/site/language"/>

Here you obtain the document using only one, single call to the document() function.

A: In general in XSL 1, you would have to use an extension function for this as there is not a direct way to accomplish this. This is somewhat dependent on the actual parser you are using, but here is an example that works with Xalan which supports optional EXSLT functions:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:dyn="http://exslt.org/dynamic">
    <xsl:param name="sitespath">/sitedata/region/site/language</xsl:param>

    <xsl:template match="/">
        <xsl:message>
            <xsl:value-of select="dyn:evaluate($sitespath)/@code"/>
        </xsl:message>
    </xsl:template>
</xsl:stylesheet>

The evaluate() function will dynamically evaluate a XPath string and the example above will simply print it out the value of attribute code under whatever XPath the value of sitespath evaluates to.
If you are not using Xalan, then what you need to do may be different. For example, for Saxon parser all you need to do is change the namespace dyn URI to http://saxon.sf.net/ for more recent versions, or to http://icl.com/saxon for older ones.


text:
Q: How do I create classes and consume dynamic json in C#? I am consuming an API using c# (visual studio 2022 .net 6.0) and I am stumped on how to handle the json being returned because it looks to be dynamic. When I look at the data from the front end of the application, each menu item (ie. 11111_1112) is it's own object. Menu items can change, be added, or removed.
Typically, I have only delt with json that has static classes and are simple to reference and consume.
When I use the built in "paste JSON as classes" function in VS for the below snippet, it creates static classes for each reference.(This is just a subset of the data, there are thousands of menus).
An example of the JSON being returned:
{
"error": 0,
"success": 1,
"data": {
    "Stockroom": {
        "price_levels": {
            "100": "Regular Price",
            "200": "Spillage"
        },
        "plFilter": "\\_\\_\\_100\\_\\_\\_\\_11111111",
        "menus": {
            "11111_1112": {
                "name": "TEST PRODUCT 123",
                "plu": "100",
                "tax_discount": "0",
                "prices": {
                    "100": "0",
                    "200": "0"
                },
                "details": {
                    "1": {
                        "name": "Beer 5",
                        "qty": "90",
                        "upc": "",
                        "unit": "imp oz",
                        "cost": "10.00"
                    },
                    "2": {
                        "name": "Beer 6",
                        "qty": "90",
                        "upc": "",
                        "unit": "imp oz",
                        "cost": "11.00"
                    },
                    "3": {
                        "name": "Beer 9",
                        "qty": "90",
                        "upc": "",
                        "unit": "imp oz",
                        "cost": "12.00"
                    },
                    "4": {
                        "name": "Beer 10",
                        "qty": "90",
                        "upc": "",
                        "unit": "imp oz",
                        "cost": "13.00"
                    },
                    "5": {
                        "name": "Beer 20",
                        "qty": "90",
                        "upc": "",
                        "unit": "imp oz",
                        "cost": "14.00"
                    }
                },
                "cost": "60.00",
                "total_sales": {
                    "100": "0",
                    "200": "0"
                }
            },
            "22222_2223": {
                "name": "Drink 1",
                "plu": "300",
                "tax_discount": "0",
                "prices": {
                    "100": "0",
                    "200": "0"
                },
                "details": {
                    "1": {
                        "name": "Drink Wine White",
                        "qty": "6",
                        "upc": "",
                        "unit": "imp oz",
                        "cost": "4.00"
                    }
                },
                "cost": "4.00",
                "total_sales": {
                    "100": "0",
                    "200": "0"
                }
            }
        }
    }
}

}
My basic program so far:

namespace APIClient
{

    public class Menu
    {
        public string? data { get; set; }
        public string? stockroom { get; set; }
        public string? menus { get; set; }
    }

    public class Program
    {
        public static void Main()
        {

            try
            {

                using (var client = new HttpClient())
                {
                    var endpoint = new Uri("https://thisismybasicurl.com/?alltheparameters=xxx");
                    var result = client.GetAsync(endpoint).Result;
                    var json = result.Content.ReadAsStringAsync().Result;
                    var recipes = JsonConvert.DeserializeObject<Menu>(json);

                    Console.WriteLine(recipes);

                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR -- Exception Message: " + ex.Message.ToString());
                System.Threading.Thread.Sleep(300);
            }

        }
    }
} ```

**Questions:**

1. How can generate classes as the json classes change (add/remove)?
2. How can I reference each menu item when I deserialize the data to my SQL Server database?


text:
Q: How to retrieve a string value from a URL API using Json (C#)? Hello Stackoverflow Masters!
I am trying to retrieve a random Chuck Norris joke from the API using JSON, but I am not sure how to retrieve the string value for value on the URL.  This is what I was using, but I feel lost!
Thank you for your kind help!
using (var client = new HttpClient())
                {
                    joke = client.GetStringAsync(@"https://api.chucknorris.io/jokes/random").Result;
                    JObject result = JObject.Parse(joke);
                    foreach (var results in result)
                    {
                        string value = (string)result["value"];
                    }

                }
                MessageBox.Show(value);

A: There are some issues with the code provided (regarding best practices). The following would be better to call the API and get the response.
You need to create a class to deserialize the json into:
public class ChuckNorrisJoke {
    public string Icon_Url { get; set; }
    public string Id { get; set; }
    public string Url { get; set; }
    public string Value { get; set; }
}

Then you can send the request and deserialize the response:
private static HttpClient httpClient = new HttpClient();

var uri = new Uri("https://api.chucknorris.io/jokes/random");
var reqMessage = new HttpRequestMessage(HttpMethod.Get, uri);

var response = httpClient.SendAsync(reqMessage);
var responseContent = await response.Content.ReadAsStringAsync();
var chuckNorrisJoke = JsonConvert.DeserializeObject<ChuckNorrisJoke>(responseContent);

This code will call the endpoint you provided with a GET request. Get the response, and read the content returned from the response, then turn the json in the response into the ChuckNorrisJoke object.
After that, you can access the joke by using:
var joke = chuckNorrisJoke.Value;

A: Frist create a POCO class like:
public class Random
{
    public string[] categories { get; set; }
    public DateTime created_at { get; set; }
    public string icon_url { get; set; }
    public string Id { get; set; }
    public DateTime updated_at { get; set; }
    public string url { get; set; }
    public string value { get; set; }
}

then deserialize using Newtonsoft.Json nutget pack, you can add static function inside a class, this return a Random object type:
public static Random deserialize(string res)
{
    return JsonConvert.DeserializeObject<Random>(res);
}

for using:
        using (var client = new HttpClient())
        {
            var joke = client.GetStringAsync(@"https://api.chucknorris.io/jokes/random").Result;

            var returnedObject = Random.deserialize(joke);
            string value = returnedObject.value;

            // Console.WriteLine(value);
            MessageBox.Show(value);
        }


text:
Q: Is showing the sso key a security issue? I realized that when we access the URL https://cdns.gigya.com/js/gigya.js?apikey=MY_API_KEY
A SSO KEY is shown, along with baseDomains
Are these values something an attacker can exploit?
Thanks.

A: Answer needs to be thirty characters: The answer is "No".

A: Gigya API keys are public keys. An attacker can not do anything with the Gigya API keys because even in the case of trying to use them in a Frontend, it won't work because of the domain must be allow-listed in Gigya.


text:
Q: jquery is not working in wordpress iam a beginner level developer in wordpress now am trying to convert my html into wordpress..i have few jquery in my html . but after conversion my jquery seems to be not working..
it showing the following error
Uncaught TypeError: Object [object Object] has no method 'superfish'

please help me to solve the issue..
Header.php
    <!DOCTYPE html>

    <meta http-equiv="Content-Type" charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width,initial-scale=1.0" >

    <title><?php echo wp_title( '|', true, 'right' );?></title>

    <link rel="stylesheet" href="<?php echo bloginfo('template_directory'); ?>/css/style.css" type="text/css"  media="all" />
    <link rel="stylesheet" href="<?php echo bloginfo('template_directory'); ?>/css/colour.css" type="text/css"  media="all" />
    <link rel="stylesheet" href="<?php echo bloginfo('template_directory'); ?>/css/flexslider.css" type="text/css"  media="all" />
    <link rel="stylesheet" href="<?php echo bloginfo('template_directory'); ?>/css/superfish.css" type="text/css"  media="all" />
    <link rel="stylesheet" href="<?php echo bloginfo('template_directory'); ?>/css/responsive.css" type="text/css"  media="all" />
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,700,900' rel='stylesheet' type='text/css'>

    <link rel="profile" href="http://gmpg.org/xfn/11" />
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">

    <link rel="shortcut icon" href="<?php echo bloginfo('template_directory'); ?>/favicon.html" type="image/x-icon" />

    <?php wp_head(); ?>

Payment/

Terms and Conditions/

+1 919 673 3608

alexmm@k2asoftwaresolutions.com

<img src="<?php echo bloginfo('template_directory'); ?>/images/logo.png"

            <?php wp_nav_menu( array(
                                     'theme_location' => '',
                                     'container'=> '',
                                     'container_class' => '',
                                     'container_id'    => '',
                                     'menu_class'=>'',
                                     'menu_id'=>'main-menu',
                                     'item_wrap'=>'

'

                                      )

             ); ?>

            <form method="get" action="#" class="menu-search-form">
                    <input class="menu-search-field" type="text"
                            onBlur="if(this.value=='')this.value='To search, type and hit enter';"
                            onFocus="if(this.value=='To search, type and hit enter')this.value='';"
                            value="To search, type and hit enter" name="s" />
            </form>

Script.js(from where am invoking jquery)
jQuery(document).ready(function() {

// Main Menu Drop Down
jQuery('ul#main-menu').superfish({
    delay:       600,
    animation:   {opacity:'show',height:'show'},
    speed:       'fast',
    autoArrows:  true,
    dropShadows: false
});

$.noConflict();
// Accordion
jQuery( ".accordion" ).accordion( { autoHeight: false } );

$.noConflict();

// Toggle
jQuery( ".toggle > .inner" ).hide();
jQuery(".toggle .title").toggle(function(){
    jQuery(this).addClass("active").closest('.toggle').find('.inner').slideDown(200, 'easeOutCirc');
}, function () {
    jQuery(this).removeClass("active").closest('.toggle').find('.inner').slideUp(200, 'easeOutCirc');
});

$.noConflict();
// Tabs
jQuery(function() {
    jQuery( "#tabs" ).tabs();
});

$.noConflict();
// PrettyPhoto
jQuery(document).ready(function(){
    jQuery("a[rel^='prettyPhoto']").prettyPhoto();
});

$.noConflict();
// Search Button Toggle
jQuery(".menu-search-button").click(function() {
    jQuery(".menu-search-field").toggleClass("menu-search-focus", 200);
});});


text:
Q: Override !important In WordPress Parent Theme I have the following CSS code in a custom.css style sheet which is part of the Main theme
.thm-unit-test h3 {
    font-size: 28px !important;
}

I have added the following code to my child theme CSS
.thm-unit-test h3 {
    font-size: 18px !important;
    color: #222;
    font-weight: 700;
}

But it is not not working. With this in mind how do I override the !important in the main custom.css. Because if I can override it than the code in my child theme can take effect

A: Use the Body tag in front of it... be more specific:
body .thm-unit-test h3 {
    font-size: 28px !important;
}

Or other parent elements...
Take some time to understand CSS Selector Priority:
Understanding CSS selector priority / specificity

A selector's specificity is calculated as follows:
count 1 if the declaration is from is a 'style' attribute rather than
a rule with a selector, 0 otherwise (= a) (In HTML, values of an
element's "style" attribute are style sheet rules.
These rules have no
selectors, so a=1, b=0, c=0, and d=0.) count the number of ID
attributes in the selector (= b) count the number of other attributes
and pseudo-classes in the selector (= c) count the number of element
names and pseudo-elements in the selector (= d) The specificity is
based only on the form of the selector.
the form "[id=p33]" is counted as an attribute selector (a=0, b=0,
c=1, d=0), even if the id attribute is defined as an "ID" in the
source document's DTD. Concatenating the four numbers a-b-c-d (in a
number system with a large base) gives the specificity.
In particular, a selector of the form "[id=p33]" is counted as an attribute selector
(a=0, b=0, c=1, d=0), even if the id attribute is defined as an "ID" in the source
document's DTD.
Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the > specificity.

https://www.w3.org/TR/CSS2/cascade.html#cascading-order
I'd use an ID in front of it tbf.

A: It should work, make sure that the call for the css of the main theme is above your custom css in the HTML
<head>
    <link rel="stylesheet" type="text/css" href="themeCss.css">
    <link rel="stylesheet" type="text/css" href="yourCustomCss.css">
</head>

Let me know if that help you!


text:
Q: Login failed to connect Database using windows account? I have deployed a asp.net web application in iis 7.5 (remote server) as "windows authentication"
...
 <system.web>
    ...
    <authentication mode="Windows"/>
    <identity impersonate="false"/>
    ...
 </system.web>

and application running on "NetworkService" identity.
and my connectionstring has <add key="dbKey" value="Server=Test_Server$123;Database=Master;Trusted_Connection=True;"/>
While I am trying to connect database from code it is throwing Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'NT AUTHORITY\NETWORK SERVICE'
Code:
Public Shared Function GetServerConnection(connectionString As String) As ServerConnection
    Dim serverCon As New Microsoft.SqlServer.Management.Common.ServerConnection(Connection(connectionString))
    serverCon.Connect() 'Error is showing here
    Return serverCon
End Function

How can user can connect to database with his windows credentials to Database and read tables data?


text:
Q: Dynamic Work shifts in Tabular model I have a static calendar hierarchy in SSAS Tabular model with minutes, hours, days. This way I can do cool metric grouping by dates like:
2017-01-01 45
2017-01-02 3
2017-01-03 17

I want to be able to do groupings by work shifts which are no more then 24 hours long. I could extend my calendar hierarchy with static shifts. But I need work shifts to be user definable on the fly.
For example user can set 22-hour shift from 03:00 to 01:00.
What approach should I take to include dynamic shifts into calendar hierarchy?


text:
Q: How to rename MySQL query result How do I rename an output of a query?
I have this query:
   select *
   from (generalprofile left join applicant on applicant.profileID =
   generalprofile.profileID) as A
   inner join (generalprofile left join applicant on applicant.profileID =
   generalprofile.profileID) as B on A.applicationID = B.applicationID ;

and I need to inner join the results of 2 queries.
"AS" doesnt seem to work

A: You don't build the select tables in right way
inside the ( ) you must place a valid select  .. not only the table name and join
  select *
   from ( select * form generalprofile
          left join applicant on applicant.profileID =
   generalprofile.profileID) A
   inner join (select * from generalprofile
          left join applicant on applicant.profileID =
   generalprofile.profileID) B on A.applicationID = B.applicationID ;


text:
Q: displaytag : Needs to send POST request rather than GET I am using DisplayTag 1.1, using server side pagination/sorting (partialList=true). But I am not finding any documentation to make POST request rather than GET request for "next page" or "First/Last" page link is clicked. The code is standard such as
<display:table name="testList" sort="external" defaultsort="1" pagesize="20" id="element" partialList="true" size="resultSize">
  <display:column property="id" title="ID" sortable="true" sortName="id" />
  <display:column property="firstName" sortable="true" sortName="firstName" title="First Name" />
  <display:column property="lastName" sortable="true" sortName="lastName" title="Last Name" />
  <display:column property="address" sortable="true" sortName="address" title="Email Address"/>
</display:table>

All the pagination links are done using GET method, need POST method.

A: There is "form" attribute on  tab to make it POST request. But the problem was 1.1 version does not support "form" attribute and there is a documentation error that mentions it under 1.1 .
I changed my displaytag version to 1.2 (with some hiccups) and then POST worked.


text:
Q: Rails Post Date Params I am attempting to build a Rails blog and I am currently in the final stages. I've managed to work around and develop most if not all features of a Wordpress blog, but one which is currently blocking me is being able to have an 'archive' of blogs.
I know how to display a post by it's date time and/or sort posts which were created at a specific time, but i'm unsure how to have a page with a month and year and display those posts.
For example
I've uploaded a post in July 2014, how could I automatically have rails create a new page with parameters called /july-2014 which would then automatically display Posts where created_at == july 2014.
The creation of a new parameter with a set field is my main problem.
Thanks

A: You need a catch-all route for routes like /july-2014 to work, so put this at the bottom of your routes file:
get '/:month_name', to: 'posts#index'

The string July-2014 should actually be parseable as is, so give this a try:
Class PostController < ApplicationController
  def index
    date = Date.parse(params[:month_name])
    @posts = Post.where("created_at >= ? AND created_at <= ?", date.beginning_of_month, date.end_of_month)
  end
end

This example is the bare minimum, you'll probably want to guard against invalid dates and missing month_name param


text:
Q: How to set widget data from local storage using gridstack.js Scenario
I have a dashboard with some widgets grouped into tabs that the user can click through. The widgets have default starting positions including height and width, but if the user moves or resizes them (using gridstack.js) I save the new widget data to local storage.
If the user clicks between tabs the new widget positions are maintained.
Problem
When the user refreshes the page, the default widget positions are loaded instead of the data in local storage. I tried to set the new positions using getWidgetData() but no luck.
I have checked local storage for my grid-layout data and the new positions are present.
Code example
Here is Codepen since I think SO  requires allow-same-origin, thus breaking the snippet.

// Initialize zurb foundation
$(document).foundation();

$(function() {
  var grid = $('.grid-stack').data('gridstack');

  var options = {
    cellHeight: 40,
    verticalMargin: 28,
    animate: false,
  };

  // Initialize grid-stack widgets
  widgetsInit = function(options) {
    $('.grid-stack').gridstack(options);
    getWidgetData(); // Find and set positions from local storage
  }

  updateVisibleWidgetHeights = function(options) {
    var targetPanel = '.tabs-panel.is-active';

    $(targetPanel + ' .grid-stack .grid-stack-item').each(function(i){
      $(targetPanel + ' .grid-stack').data('gridstack').resize(
        $(targetPanel + ' .grid-stack .grid-stack-item')[i],
        $($(targetPanel + ' .grid-stack .grid-stack-item')[i]).attr('data-gs-width'),
        Math.ceil(($(targetPanel + ' .grid-stack .grid-stack-item .grid-stack-item-content')[i].scrollHeight + $(targetPanel + ' .grid-stack').data('gridstack').opts.verticalMargin) / ($(targetPanel + ' .grid-stack').data('gridstack').cellHeight() + $(targetPanel + ' .grid-stack').data('gridstack').opts.verticalMargin))
      );
    });
  }

  updateAllWidgetHeights = function(options) {
    $('.grid-stack .grid-stack-item').each(function(i){
      $('.grid-stack').data('gridstack').resize(
        $('.grid-stack .grid-stack-item')[i],
        $($('.grid-stack .grid-stack-item')[i]).attr('data-gs-width'),
        Math.ceil(($('.grid-stack .grid-stack-item .grid-stack-item-content')[i].scrollHeight + $('.grid-stack').data('gridstack').opts.verticalMargin) / ($('.grid-stack').data('gridstack').cellHeight() + $('.grid-stack').data('gridstack').opts.verticalMargin))
      );
    });
  }

  getWidgetData = function() {
    // // Load from local storage
    var serialization = null;
    if (serialization = localStorage.getItem("grid-layout")) {
      _.each(JSON.parse(serialization), function (node) {
        // Update each widget's properties from values in storage
        $('.grid-stack-item[data-custom-id='+ node.id +']').attr({
          'data-gs-x': node.x,
          'data-gs-y': node.y,
          'data-gs-width': node.width,
          'data-gs-height': node.height,
        });
      });
    } else {
      console.log("There was no local storage data to read")
    }
  }

  widgetsInit(options);
  updateVisibleWidgetHeights();

  $('.grid-stack').on('change', function (event, items) {
    // Save data to local storage
    var res = _.map($('.grid-stack .grid-stack-item'), function (el) {
      el = $(el);
      node = el.data('_gridstack_node');
      return {
        // Grab widget properties
        id: el.attr('data-custom-id'),
        x: node.x,
        y: node.y,
        width: node.width,
        height: node.height
      };
    });
    localStorage.setItem("grid-layout", JSON.stringify(res))
  });

  // On tab change update widget heights to the height of the content they contain
  $(document).on('change.zf.tabs', function() {
    updateVisibleWidgetHeights();
  })
});
.grid-stack > .grid-stack-item > .grid-stack-item-content {
    background-color: #fff;
    cursor: move;
    border: 1px solid #e3e3e3;
    border-radius: 4px;
 padding: 1rem;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/gridstack.js/0.4.0/gridstack.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/css/foundation.min.css" rel="stylesheet"/>

Tab 1

Tab 2

#1

#2

#3

#4

#5

#6

A: You need to look into few things.
The default examples that are available are for a single instance whereas you have multiple.
You are saving and loading the gridstack in one go which means you have no track of the element grid-stack-item and also you have no track which point belongs to which instance the first tab or the second,
So even if you get it to work it will try to position all the 6 different widgets inside the very first tab rather than loading it in their respective tabs.
So you need to make changes to the following

*

*$('.grid-stack').on('change', function (event, items) {

*getWidgetData()

*assign id or custom-data-id attribute in you grid-stack-items so that they have a unique identifier

*wrap the tabs inside a conatiner with id tabs-cotnainer.
on the event change for the gridstack you should create the json object consisting the points in the sections dedicated to the tabs it will store like below.
{
  "items": {
    "panel1": [
      {
        "id": "panel1-item1",
        "x": 0,
        "y": 0,
        "width": 4,
        "height": 2
      },
      {
        "id": "panel1-item2",
        "x": 4,
        "y": 0,
        "width": 4,
        "height": 2
      },
      {
        "id": "panel1-item3",
        "x": 8,
        "y": 0,
        "width": 4,
        "height": 2
      }
    ],
    "panel2": [
      {
        "id": "panel2-item1",
        "x": 0,
        "y": 0,
        "width": 4,
        "height": 2
      },
      {
        "id": "panel2-item2",
        "x": 4,
        "y": 0,
        "width": 4,
        "height": 2
      },
      {
        "id": "panel2-item3",
        "x": 8,
        "y": 0,
        "width": 4,
        "height": 2
      }
    ]
  }
}

replace with the following
$('.grid-stack').on('change', function (event, items) {
    let tabs = $('#tabs-container >ul >li');
    let totalTabs = $('#tabs-container >ul >li').length;

    let storagePositions = {
        items: {}
    };
    $.each(tabs, function (index, elem) {
        let panel = $(elem).find('a').attr('href').replace("#", '');
        let stackItems = $('#' + panel + ' .grid-stack .grid-stack-item');

        storagePositions.items[panel] = _.map(stackItems, function (el) {

            el = $(el);
            node = el.data('_gridstack_node');
            //console.log(node);

            return { // Grab widget properties
                id: el.attr('data-custom-id'),
                x: node.x,
                y: node.y,
                width: node.width,
                height: node.height
            };
        });
    });

    // Save data to local storage
    localStorage.setItem("grid-layout", JSON.stringify(storagePositions))
});

and then load the tabs in the similar manner
getWidgetData = function () {

    // // Load from local storage
    var serialization = null;
    let tabs = $('#tabs-container >ul >li');
    let totalTabs = $('#tabs-container >ul >li').length;

    if (localStorage.getItem("grid-layout") !== null) {

        serialization = JSON.parse(localStorage.getItem("grid-layout"));

        $.each(tabs, function (index, elem) {
            let panel = $(elem).find('a').attr('href').replace('#', '');
            let myGrid = $('#' + panel + ' .grid-stack').data('gridstack')

            var items = GridStackUI.Utils.sort(serialization.items[panel]);
            _.each(items, function (node) {

                myGrid.update($('div[data-custom-id="' + node.id + '"]'),
                    node.x, node.y, node.width, node.height);
            });
        });
    } else {
        console.log("There was no local storage data to read")
    }
}

Your updated HTML will look like following

            Tab 1

            Tab 2

#1

#2

#3

#4

#5

#6

See here the full working demo on JSFIDDLE you can update positions in both of the tabs and then try refreshing the page it will show the updated positions.
NOTE: just remove the previous values once by writing localStorage.removeItem("grid-layout") on the top of the script, and them remove this line after running for the first time.


text:
Q: Как можно поместить url адреса из строки в массив? Имеется примерно такой текст:
1.http://example.com(example) (пробела перед http нет намеренно)
2. https://vk.com (vk)
3. И так далее

Я хочу средствами php получить массив, который содержит только url адреса, без стороннего текста.
Подскажите, какими методами это будет удобнее и правильнее всего сделать, хочу понять сам принцип.

A: $pattern = '%http[^>]*.com%im';
preg_match_all($pattern, $content_post, $out);

В массиве $out будет вся выборка доменов. Но это при условии, что все домены в зоне *.com. Если другие зоны, то надо менять конструкцию регулярного выражения.

A: Для того, чтобы вытащить все URL адреса из текста, нужно использовать регулярные выражения. Для новичка это будет не совсем легко, ну а что делать? :)
<?php

$string = "1.http://example.com(example) (пробела перед http нет намеренно)
2. https://vk.com (vk)
3. И так далее";

$regExp = "/(?:http)?[s]?\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?/";

preg_match_all($regExp, $string, $values);

var_dump($values);

Результат:
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(18) "http://example.com"
    [1]=>
    string(14) "https://vk.com"
  }
}

Может регулярное выражение на каких-то случаях может давать неверный результат, но во многих случаях работает, более продвинутые регулярные выражения с РФ доменами и т.д. можно найти в интернете под требуемую задачу :)


text:
Q: Jquery Isotope - Unable to center multiple divs inside a container - Isotope causes the issue I'm using a combination of Bootstrap and PHP to create a Portfolio section.
I have around 12 items, and I want to display 4 of them on each row.
Problem is that no matter what I do, the units are stick to the left side of the container, and I seem unable to center them, even with all the searches here on SO.

Here's the code I'm using.
HTML

Portfolio

CSS
.container{
    width: 70%;
}

#portfolio{
    height: 100%;
    background-color: white;
    padding-bottom: 50px;
}

#portfolio .filter{
    height: 50px;
    text-align: center;
    background: transparent;
    border-top: 1px solid #7f8c8d;
    border-bottom: 1px solid #7f8c8d;
    width: 100%;
    margin-top: 30px;
}

.thumb-container{
    width: 100%;
    margin: 15px auto;
    text-align: center;
    background: red;
}

.thumb-unit{
    width: 300px;
    height: 225px;
    display: inline-block;
    margin: 5px;
    position: relative;
    overflow: hidden;
    cursor: pointer;
    background: blue;
}

How in this earth can I center those thumb-units inside the thumb-container?
Any help highly appreciated.
EDIT
The weird thing is that on JSFiddle it works, but I don't understand why it doesn't on mine.
Tried to refresh cache and on another browser, but the result is the same.
EDIT 2
I found out that the problem is isotope, the library I'm using for filtering.
Has anyone encountered this problem?

A: It´s look center aligned, but... if you are using Bootstrap, why dont you try to use this Bootstrap component?
http://getbootstrap.com/components/#thumbnails-custom-content
Your css code would be shorter.

A: .container{
    width: 70%;
    display:block;
    margin:0 auto;
    float:none
}

/**************************

http://jsfiddle.net/cd2js8m2/
**************************/

A: I was using jquery isotope - that was causing the issue.
I switched to MixItUp and now everything works just fine!

A: I am just working on something which needs exactly that. You need to use isotope v2 and use element sizing new feauture.
In jQuery you'd run:
var $container = $('#container').isotope({
 itemSelector: '.item',
 masonry: {
   columnWidth: '.grid-sizer'
 },
  isFitWidth: true
});

Your html woud look like this:

Not just this would center your layout but it will also be responsive. grid-sizer will be your columnWidth and it would change its width based on your bootstrap classes col..." making the whole thing responsive as you'd expect with bootstrap, on top of this the number of elements that you will see on each row will be based on your bootstrap class settings.


text:
Q: Animal Crossing: Wild World Communication Error I keep getting an error that says that I've been disconnected when doing DS to DS communications. There is no error code.

A: Sadly there are many things contributing to a communication error, so many in fact that there are very little you can do about them. I've been playing Wild Word since it came out with various people, and we haven't found the source of the problem. However, there are some things you can do to reduce the frequency of these errors:

*

*When playing, put your DS down on a surface and avoid moving it too much with respect to the other DS's around.

*Keep your DS away from sources of interference, such as microwaves and even other wireless devices (such as laptops, cellphones and routers).

*Make sure to not move out of range of communication when playing over Wi-Fi.

Like I said, these disconnections are frequent at best, and require some preventive measures. Despite those measures, we could not prevent connection issues completely.
I hope this helps alleviate your problem a bit!


text:
Q: Pyserial: readline() is blocking, although timeout is defined I have an issue with readline() from pyserial.
My code is:
import serial

uart = serial.Serial(port='/dev/ttyS0', baudrate=9600, timeout=3)

data = uart.readline().decode()
print(data)
uart.close()

I'm receiving data from a microcontroller. The problem is, if no data is send from the mc, the program is waiting "forever", although I defined a timeout of 3 seconds.
What am I doing wrong?

A: Ok, I have discovered the solution
The problem is, that the Raspberry Pi 3 and 4 uses the "miniUART" as the primary UART and the Raspberry Pi 1 and 2 uses the "PL011".
You can the details here: https://www.raspberrypi.org/documentation/configuration/uart.md
To get the timeout break working, you have to change the "PL011" to UART0. By default UART0 (GPIO 14 and 15) is set to "miniUART" and "PL011" is used for the bluetooth modem.
You have to edit the /boot/config.txt and add dtoverlay=disable-bt.
You also have to disable the system service, that initialises the modem, so it does not connect to the UART, using sudo systemctl disable hciuart.
I have done that and now the program waits the timeout for a message and goes on, if no message is received.

A: timeout will only affect the maximum time that  readline() will wait

timeout = x: set timeout to x seconds (float allowed) returns immediately when the requested number of bytes are available, otherwise wait until the timeout expires and return all bytes that were received until then

try this  :
import serial
uart = serial.Serial(port='/dev/ttyS0', baudrate=9600, timeout=3)
while True:
   data = uart.readline().decode()
   print(data)
   if not data :
      break
uart.close()


text:
Q: Creating Mesh from Point Cloud I'm looking for a way to create a mesh .obj file from point cloud for an academic research project. I'm flexible about the algorithm and its runtime and space complexity.
After searching for a while I couldn't find out and 3-party library that could do this.

A: ARKit 4.0
In ARKit 3.5 and ARKit 4.0 you can create a mesh from dense point cloud using LiDAR scanner and Scene Reconstruction option. Also, in ARKit 4.0 you can find Depth API.

ARKit 3.0
There's no way in ARKit 3.0 to create a mesh from Point Cloud at the moment. You can do it in third party solutions like Abound SDK. There are four simple steps to save and access maps for a photogrammetry: create the delegate, implement saving and just run your app for viewing the map.

After your spatial map will be uploaded, the data's quickly processed and then made available. A convenient way to access the data is via the web dashboard:

*

*Open the dashboard scans view at dashboard.aboundlabs.com/scans.

*Scans made from your apps will appear as thumbnail images with your
latest scans listed first. To view the 3D scan, click on the image.

*To download the 3D textured mesh in zipped obj format click on ⤓ icon.

Here's how AboundScanController class looks like:


text:
Q: Не могу скачать файл через написанный браузер (с гугл диска) Написал браузер все работает но проблема в чем: я пытаюсь скачать с гугл диска     файл проходит загрузка и все (ничего не скачивает и ошибки не выдает !)

//
 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <WebView
            android:id="@+id/webView"
            android:layout_marginTop="5dp"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:visibility="visible"
            android:layout_weight="1"/>

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="?android:attr/progressBarStyleHorizontal" />

    </LinearLayout>

//
  public class MainActivity2_3 extends AppCompatActivity {

        ProgressBar progressBar;

        WebView webView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main_activity2_3);

            webView = (WebView) findViewById(R.id.webView);
            webView.setWebViewClient(new myWebClient());
            WebSettings webset = webView.getSettings();
            webset.setJavaScriptEnabled(true);

            String loadUrl="https://drive.google.com/open?id=1j5uEZYQ2G4Xp1OnSRXpseNSpqz5wpGK1";

            webView.loadUrl(loadUrl);

            progressBar = (ProgressBar) findViewById(R.id.progressBar);
            webView.setWebChromeClient(new WebChromeClient(){
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    progressBar.setProgress(newProgress);
                    if(newProgress==100)
                        progressBar.setVisibility(View.GONE);
                    else
                        progressBar.setVisibility(View.VISIBLE);
                }
            });

        }

    }

//
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

//

A: Я добавил этот код теперь загружается
спасибо  Yura Ivanov . Но загрузку можно сделать только через другую программу как сделать , чтобы через мою загружало ?
 webView.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {

                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                startActivity(intent);
            }
        });

A: Теперь грузит нормально но как сделать  нормальное имя при загрузке файла пишет (1hjdh3je)
   webView.setDownloadListener(new DownloadListener()
        {
            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimeType,
                                        long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));

                request.setDestinationInExternalPublicDir(
                        Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
                                url, contentDisposition, mimeType));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
            }});


text:
Q: Modify global javascript variable inside a function I'm trying clone a json object inside a function wanting to access the object outside the function. But when function is done, the object still seems to be undefined. Seems like it's not the same variable?
var jsonUserObj;
$.getJSON("user.json", function(content){
    jsonUserObj = $.parseJSON(JSON.stringify(content));
    console.log(content);
    console.log(jsonUserObj); //looks fine!
});
console.log(jsonUserObj); //undefined

inside the callback function it contains all the data, but it does not remain outside of it. How to make it assessible globally?

A: $.getJSON is asynchronous so console.log at the end of your code runs before $.getJSON returns its result.
You should modify the variable inside the callback (where it looks fine) and then use the variable inside that function, this callback is the only place where you can guarantee your variable is set.
You could also use the synchronous version of $.ajax but that's really not recommended (and probably unnecessary).

A: You got a typo:
console.log(jsonUserObject);

It should be
console.log(jsonUserObj);

A: You need to declare var jsonUserObj outside a function.
Also it looks like you have a typeo, is it jsonUserObj or jsonUserObject?

A: Could it be a question of timing? If that getJSON method is firing asynchronously then it may not have returned it's value by the time you have fired the last line. Does that make sense?

A: $.getJSON performs an ajax call, which is asynchronous. The code after it will continue evaluating while it waits for a response. When the response comes back, the program flow will jump back into the success/error/complete handlers of the ajax call.
tldr: Anything you do with data from an ajax call must be in the success handler of that ajax call.


text:
Q: How to select items in app and updating the state in react I want to build a simple app like in picture attached with react js, I just cannot find the right idea of:
How to "select" photos(or item) in an application and have the "cart"-like component appear at the bottom when at least one photo/item is selected(and close and deselect all already selected photo/items) and expand the cart-like component at the bottom when clicked to show what's been already selected.
What is the best approach to this?
P.S I'm new to react with a big idea in mind xD
app's view

A: This question definitely needs more information, but I will try to point you in the right direction. There are hundred of ways to create the UI/functionality you are describing but here is a very generic overview;
The "items" (Img1-6) looks like a grid of ShopItem components, possibly in a CSS Grid / flexbox. Each ShopItem would probably make use of an onClick method to "do something" when it is clicked - this may involve updating a state (using the useState react hook) somewhere which tells you if a ShopItem is checked or not. It could also potentially use a callback method to do something in the parent when the items are checked.
I imagine that each ShopItem may own its own "checked" state or may update a global state (Such as Zustand or Redux) or a Context (React) when it is toggled on and off. The checked state of a ShopItem would also inform the UI of the component.
The "cart-like" component could be looking at the global state/context/callback from the item component, and could change based on its value and how many checked items there are. (Eg/ checkedItems !== 0 ? show : don't show)
This is just one way in which this UI can be built, if you would like a more specific solution, please edit your question to include code snippets and what you've already tried.


text:
Q: Reduce Grub Menu Items I have done quite a bit of fiddling and reinstalling of grub. I can get my machine to boot using the first few entries, but I would like to clean up the grub menu. I have tried deleting grub.cfg and regenerating it via update-grub. I have also tried using 40_custom in /etc/grub.d. I have tried reinstalling grub with boot repair.
I only have Xubuntu 14.04 and Linux Mint 17. I'd like to eliminate all entries after the 5th one.
Update: I was able to remove some of the duplicate entries in 40_custom. The bottom five entries are listed in 40_custom. (I know this because I changed them.) However, I am not sure where the top entries are coming from. Today I had created a fat32 boot partition but was doing legacy boot with grub before. I noticed too that I have two grub.cfg files one in /boot/grub/ and the other in /boot/efi/EFI/ubuntu/.
Any input is appreciated. Thank you

A: I think you have duplicate entries in your 40_custom, just check it once more. To remove the memtest entries, run:

sudo chmod –x 20_memtest86+
sudo update-grub

A: After following Ron's answer and looking at 40_custom a little closer, I eliminated duplicate sections of:
### BEGIN /etc/grub.d/10_linux ###
### END /etc/grub.d/10_linux ###
### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

(Of course there was content between the BEGIN and END comments.) This eliminated some of the duplicate entries in grub. (Those ones are actually not shown in the grub screen shot above.)
However, I should have read this article more closely to begin with.
https://linuxnorth.wordpress.com/2011/03/09/grub2-revisited
I did the following:
cd /etc/grub.d
sudo chmod -x 10_linux 30_os-prober 30_uefi-firmware
sudo update-grub

These steps eliminated the first five entries seen in the screen shot above of grub.
You may also want to do the same for 20_memtest86+ and 25_custom.
I suppose installing grub-customizer would work also. I only like to do things manually/hands-on if possible. I feel I learn my system better that way. Customization and freedom, one of the reasons I love Linux.

A: Install Grub-customizer. Grub Customizer is a graphical interface to configure the GRUB2/BURG settings and menu entries. In terminal do:
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer


text:
Q: Why does the inclusion of a .Dim attribute cause d_ply to fail? Why does the inclusion of a .Dim attribute cause d_ply to fail?
library(plyr)

dt <- structure(
    c(946771200, 947376000, 947980800)
    ,.Dim = 3L # FIXME: including the .Dim attribute will cause d_ply to fail
    ,class = c("POSIXct","POSIXt")
    ,tzone = "")

myDF <- data.frame(
    dt = dt
    ,dat = seq(1:3))
#attr( myDF$dt, "dim" ) <- NULL # FIXME: removing the .Dim attribute will make d_ply work again
attr( myDF$dt, "dim" )

d_ply( .data = myDF, .variables = .(dt), .fun = show )

returns
Error in attributes(out) <- attributes(col) :
  dims [product 3] do not match the length of object [1]

myDF and str(myDF) look completely fine to the eye.  When I tried to create a reproducible example, I started with:
myDF <- data.frame(
    dt = as.POSIXct( c("2000-01-01", "2000-01-08", "2000-01-15") )
    ,dat = seq(1:3)
    )
d_ply( .data = myDF, .variables = .(dt), .fun = show )

... which works just fine.  I had to dput (or attr) my dataset before I found that .Dim attribute.
The reason I'm looking at this is because I have a function that aggregates each date by week and returns a vector including this '.Dim' attribute.
dt <- c(
    seq( as.POSIXct( '2001-01-01'), by = '5 days', length.out = 52 ))
weekCutoffPoints <- cut( dt, breaks ="week", labels = FALSE )
endpoints <-
    # R Inferno 8.3.22: "by is for data frames", but I get the same result with tapply
    #tapply( X = dt, INDEX = weekCutoffPoints, FUN = max )
    by( data = dt, INDICES = weekCutoffPoints, FUN = max )
dt <- as.POSIXct(
    endpoints[ rownames(endpoints)[weekCutoffPoints] ]
    , origin = as.POSIXct('1970-1-1') )

# now try to use these dates in the same simple d_plyr call
myDF <- data.frame(
    dt = dt
    ,dat = seq(1:52))
#attr( myDF$dt, "dim" ) <- NULL # FIXME: removing the .Dim attribute will make d_ply work again
attr( myDF$dt, "dim" )

d_ply( .data = myDF, .variables = .(dt), .fun = show )

Bonus points: This cut/by works for me, but is my actual problem this way I use to align dates within the same week?
Thanks, guys!


text:
Q: Which of the following improper integrals are convergent? Which of the following improper integrals are convergent?
a.$\quad\displaystyle \int_{1}^{\infty} \frac{dx}{\sqrt{x^3+ 2x + 2}}$
b. $\quad\displaystyle \int_{0}^{5}\frac{dx}{(x^2− 5x + 6)}$
c.$\quad\displaystyle \int_{0}^{5} \frac{dx}{\sqrt[\large 3]{7x + 2x^4}}$
how can I able to solve this.thanks for your help

A: The first one is convergent. Because $$\lim_{x\to\infty}x^{\frac{3}{2}}\cdot\frac{1}{\sqrt{x^3+2x+2}}=1$$ and we know when the resulted limit is finite when the power of $x$ is greater than $1$ (I mean that $x^{\frac{3}{2}}$ ), the improper integral $\int_a^{\infty}$ converges.
About the second. If we divide it to 3 parts, we have: $$\int_0^5=\int_0^2+\int_2^3+\int_3^5$$ Consider the first part: $$\int_0^2\frac{dx}{x^2-5x+6}=\int_0^2\frac{dx}{(x-2)(x-3)}$$ You see that if we consider $(x-2)^1$ and multiply it to the integrand $\frac{1}{(x-2)(x-3)}$ and take the limit of the result when $x\to 2^-$, then: $$\lim_{x\to 2^-}(x-2)^1\frac{1}{(x-2)(x-3)}=-1\neq0$$ whenever you can find a power like $1$ (I mean in $(x-2)^1$) and so find the above limit non zero, the improper integral diverges. So the second one is divergent.


text:
Q: Adding backwards compatibility for iOS 7 failing due to framework I have an app that utilizes iOS 8's new touch ID using:
#import "LocalAuthentication/LocalAuthentication.h"

But at startup on an iOS 7, the app crashes. I do not call the touch ID program if it is not running on iOS 8+. The log tells me it is from importing the framework, but I have the framework set to optional, so it should work unless I missed a step... Why would the log tell me otherwise?


text:
Q: Twilio.MVC ValidateRequest on AppHarbor I am trying to get the twilio.MVC helper attribute ValidateRequest to work on a MVC 4 controller running in AppHarbor.  I can't seem to get it to work and I assume it is because my app is running behind a load balancer.  I've tried supplying the UrlOverride parameter in the call, but I can't seem to get it correct.  Assuming my appharbor app url = myapp.apphb.com, my controller = callhandler, my action = handlecall, how should I be calling the ValidateRequest attribute?
ValidateRequest[("MYAUTHTOKEN","myapp.apphb.com")]

Doesn't seem to work, I constantly get a 403 Forbidden error back.
Just an FYI- I am decorating the individual MVC action and not the entire controller at this point.

A: In case anybody runs into this same issue, I got this working by specifying the UrlOverride as a Named Parameter along with the controller and the action, like so:
ValidateRequest[("MYAUTHTOKEN", UrlOverride="http://myapp.apphb.com/controller/action")]


text:
Q: Why do two ways of defining properties in C# have different results? Two ways to defining properties in C#
public class Program {

    public static bool[] Property1 => new bool[1];
    public static bool[] Property2 { get; } = new bool[1];

    public static void Main() {

        Property1[0] = true;
        Property2[0] = true;

        Console.WriteLine($"{Property1[0]} {Property2[0]}");

        Console.ReadLine();

    }

}

These two ways have different results

False True

A: public static bool[] Property1 => new bool[1];

Here you define a getter that is executed every time you read the property, so you return a new bool[] every time. And the default value of the one element in that array is false.
public static bool[] Property2 { get; } = new bool[1];

Here you initialize the value of the property just once, after that you return the same array every time, including the value that you set it to.

A: When you write:
public static bool[] Property=>new bool[1] gets translated to something like:
public static bool[] Property()
{
  return new bool[1];
}

Whereas when you define a auto property like:
public static bool[] Property2 { get; } = new bool[1];
It is translated to:
public static bool [] property=new bool[1];
public static bool[] Property
{
  get
  {
      return property;
  }
}

You can see that in the first case you would always get the array reinitialized on every call.
P.S In the second case I am not 100%  sure internally where the default initialization takes place (either in the private field or in the setter).


text:
Q: How can one convert rational matrices into integer ones? Let $G$ be a finite subgroup of $GL_n(\Bbb{Q})$. I want to show the existence of a matrix $A\in GL_n(\Bbb{Q})$ with the property that $AGA^{-1} \subseteq M_n(\Bbb{Z})$.

A: There is a standard trick here, which works for any principal ideal domain. You are looking for a change of $\mathbb{Q}$-basis which makes the matrices representing group elements integral. Let $V$ be the underlying $\mathbb{Q}G$-module, with $\mathbb{Q}$-basis
$\{v_{i} : 1 \leq i \leq n \}$. Let $M$ be the $\mathbb{Z}$-submodule of $V$ generated by the vectors in $\{ v_{i}g : 1 \leq i \leq n, g \in G \}$. Then $M$ is in fact a $\mathbb{Z}G$-submodule of $V$ by its construction, because $mg \in M$ whenever $m \in M$ and $g \in G$.
  Now $M$ is a finitely generated torsion-free $\mathbb{Z}$-module, so has a $\mathbb{Z}$-basis. Furthermore $M \otimes_{\mathbb{Z}}\mathbb{Q} = V$, so this $\mathbb{Z}$-basis has $n$ elements, say it is $\{ m_{i} : 1 \leq i \leq n \}$. Then $m_{i}g $ is a $\mathbb{Z}$-linar combination of $\{m_{j} : 1 \leq j \leq n \}$ for each $i$ and each $g \in G$. Hence the matrices representing the elements of $G$ with respect to the $\mathbb{Q}$-basis  $\{ m_{i} : 1 \leq i \leq n \}$ of $V$ are all integral, as required.


text:
Q: Cannot target text element in CSS I am using a very simple free Wordpress theme that I am really happy with but I cannot figure out how to move the names of the budgies along to the right:
http://swearingbudgies.co.uk/
I have tried Firebug to find out how to do this but the only tag I can see is a: - problem is when I apply padding-left to a: it also shunts the images along. Will this require changes to the html/php as well as the CSS to fix?

A: Add the following class in your CSS. Next time onwards don't come up with site url. Add your problem in fiddle/codepen or something like that and post here your code. Otherwise people will give downvote and close your question including me.
a.image_link + div
{
  text-align:right;
}

A: try
 #main-content div.post div{
      text-align:right;
    }


text:
Q: Need proof for a property in Analytic Geometry When I was taught Vector Calculus, we assumed the following properties of the dot product (without proof):
$$\vec{\mathbf{a}} \cdot \vec{\mathbf{b}} = \vec{\mathbf{b}} \cdot \vec{\mathbf{a}}$$
$$\vec{\mathbf{a}} \cdot (\vec{\mathbf{b}} + \vec{\mathbf{c}}) = \vec{\mathbf{a}} \cdot \vec{\mathbf{b}} + \vec{\mathbf{a}} \cdot \vec{\mathbf{c}}$$
And then derived the following component form of the Dot Product:
$$\vec{\mathbf{a}} \cdot \vec{\mathbf{b}} = a_1 b_1 + a_2 b_2 + a_3 b_3$$
In G. E. Hay's Vector and Tensor Analysis, this is done in exact reverse order. First, he derives $\vec{\mathbf{a}} \cdot \vec{\mathbf{b}} = a_1 b_1 + a_2 b_2 + a_3 b_3$ and then proves both the commutativity and the distributivity over vector addition properties of the Dot Product.
For deriving $\vec{\mathbf{a}} \cdot \vec{\mathbf{b}} = a_1 b_1 + a_2 b_2 + a_3 b_3$, he uses the formula that the cosine of the acute angle between two lines is the sum of the products of corresponding direction cosines of the two lines. He writes nearby: by a formula of analytic geometry.
Now, I was taught this formula in analytic geometry. But, the proof used the dot product in component form directly.
So, I want a proof for "cosine of the acute angle between two lines is the sum of the products of corresponding direction cosines of the two lines" that does not involve $\vec{\mathbf{a}} \cdot \vec{\mathbf{b}} = a_1 b_1 + a_2 b_2 + a_3 b_3$ because without such a proof the proof in G. E. Hay becomes circular reasoning.

A: Let a, b, and c be any three vectors. We can always resolve a and b into components in the direction of c whose unit vector is u. The diagram below shows a.u + b.u $= ($ a + b $)$ u.

If we multiply both sides by the scalar $\lambda$; where c $ = \lambda$ u, we have
a.c + b.c = (a + b)c.
Added:
In the revised picture, we have
a . u = |a| . |u| $\cos \gamma$ = |a| $\cos \gamma$ = OH.
Similarly, b . u = … = |b| $\cos \alpha$ = AK = HM;
And, (a+b) . u = |a+b| . $\cos \beta$ = OM = OH + HM
∴ (a + b) . u =a . u + b . u


text:
Q: Constructor use null value as parameter Following is a simple scala class definition, there are 2 constructors defined inside Person class.
Person.scala:
// class that has field and method,
class Person(var name:String, var age:Short) {
    def this() {
        this("", 0);
    }
    def this(name:String) {
        this(name, 0);
    }
    def hi() = printf("hi, I am %s!\n", name)
}

// var nobody = new Person();
var eric = new Person("Eric", 12);
eric.hi;

The question is:

*

*When age field is not provided in constructor's argument list, I want to initialize it to null, not 0, what is the proper way to do that. Same requirement for the name field.

A: So basically the scala class you wanted to create is
case class Person(name:String, age:Option[Short] = None) {
    def hi() = println(s"hi, I am $name.\nMy age is ${age.getOrElse("not provided")}.")
}

Which returns
scala> var eric = new Person("Eric", Some(12));
eric: Person = Person(Eric,Some(12))

scala> eric.hi
hi, I am Eric.
My age is 12.

scala> var eric = new Person("Eric");
eric: Person = Person(Eric,None)

scala> eric.hi
hi, I am Eric.
My age is not provided.


text:
Q: how to fetch nested elements in jquery Earlier in the day I got stuck with jquery's find method working. And now I am unable to fetch nested elements from my html table below:

what I am trying to do : on each checkbox selected columns i.e. select, I want to print values of siblings i.e. name and address but I am unable to do that. Below is my code:
$("#but").click(function(){
        $(".tabclass tr td input[type='checkbox']:checked").each(function(){
            var sibs=$(this).siblings("td");
            var v1=$(sibs[0]).text();
            var v2=$(sibs[1]).children[0].val();
            alert(v1+" & "+v2);
        });
});

HTML Code:

    select
    Name
    Address

        <input type="checkbox" name="selectCheck" class="select" id="ch1" value="1" />
      Nitin

        <select name="address">
          <option>Gurgaon</option>
          <option>Noida</option>
          <option>Rohini</option>
        </select>

        <input type="checkbox" name="selectCheck" class="select" id="ch2" value="2" />
      Abc

        <select name="address">
          <option>Gurgaon</option>
          <option>Noida</option>
          <option>Rohini</option>
        </select>

        <input type="checkbox" name="selectCheck" class="select" id="ch3" value="3" />
      Xyz

        <select name="address">
          <option>Gurgaon</option>
          <option>Noida</option>
          <option>Rohini</option>
        </select>

  <button id="but">Test</button>

A: You have 2 issues with the code

*

*You need the parent of the checked input before getting their siblings.

Change
var sibs=$(this).siblings("td");

to
var sibs=$(this).parent().siblings("td");

*

*.children[0] gives you a DOM object, which does not have the val() method.

Replace
var v2=$(sibs[1]).children[0].val();

with
var v2 = $('select', sibs[1]).val(); OR  var v2=$(sibs[1]).children()[0].value;

Also use console.log instead of alert as the latter stops the thread on which the UI runs.
JS
$("#but").click(function() {
  $(".tabclass tr td input[type='checkbox']:checked").each(function() {
    var sibs = $(this).parent().siblings("td");
    var v1 = $(sibs[0]).text();
    var v2 = $('select', sibs[1]).val();
    alert(v1 + " & " + v2);
  });
});

Check Fiddle

A: Problem: Is that the check box is child of td and it doesn't have any siblings. As per your this code var sibs=$(this).siblings("td"); it fetches nothing .
Solution: Is to go one level up to its parent ie:td and now this td has siblings. So use this code
var sibs=$(this).parent().siblings("td");
Also change $(sibs[1]).children[0].val();
To
$(sibs[1]).children('select').val();


text:
Q: Characteristic of an integral domain is prime.
Let $D$ be the Integral Domain with characteristic $m>0$. Prove that $m$ is prime.

My Proof:
Since the characteristic of $D$ is $m$, $m\cdot b=0$ for all $b\in D$ and if $n\cdot b=0$ for all $b\in D$, then $m\leq n$.
Assume that $m$ is composite number. Then $m=n_1n_2$ where $n_1,n_2>1$.
Let $a\in D$. Then $m\cdot a=0$ i.e., $n_1(n_2\cdot a)=0$. Take $c=n_2\cdot a$, then $n_1\cdot c=0$. Since $a$ is an arbitrary element of $D$, $c$ is also an arbitrary element of $D$. So, we have $n_1\cdot c=0$ for all $c\in D$ and $m> n_1$. This is a contradiction. So, our assumption that $m$ is composite number,  is false. Hence $m$ is a prime number.

A: If your definition of integral domain requires an identity, it's easy: the unique ring homomorphism (preserving identities)
$$
\chi\colon\mathbb{Z}\to D
$$
has kernel $m\mathbb{Z}$, so $\mathbb{Z}/m\mathbb{Z}$ is isomorphic to a subring of $D$ and therefore is a domain. Hence either $m=0$ or $m$ is prime.
If $D$ is not required to have an identity, you can still consider the field of quotients $Q$ of $D$, which has the same characteristic as $D$ and so the previous argument works.

A: To simplify things, let $m$ be the characteristic of $D$. Let $m=nk$ be a factorization of $m$. Then $m\cdot 1=(nk)\cdot 1=(n \cdot 1)(k\cdot 1)=0$. Since $D$ is an integral domain, either $n \cdot 1=0$ or $k \cdot 1=0$. But $m$ is the least integer for which $m \cdot 1=0$, implying $n=1$ or $k=1$, so $m$ is prime.

A: As an integral domain has no zero divisors, if it has a finite characteristic it is itself finite. So it is a field and contains an unit element, $1$. Let $m=a.b$ if possible, for some integers $a,b>1$. Then $a.1=a\in D$. Let all the elements of $D$ be $x_1,\cdots,x_n$. If $a.x_i=a.x_j$ for $i\neq j$ then as $D$ has no zero divisors $x_i-x_j=0$, contradicting  $i\neq j$. Hence $a.x_1,\cdots,a.x_n$ constitute all elements of $D$. But $b.(a.x_i)=0$ for all $i$. But then $b<m$ satisfies $b.x=0$ for all $x\in D$, contradicting the fact that the characteristic is $m$.


text:
Q: How to access constant with class pointer in python - AUTH_USER_MODEL = 'django_restframework_2fa.User' I have defined AUTH_USER_MODEL = 'django_restframework_2fa.User' in the settings.py file of Django application.
django_restframework_2fa is the name of the package and it has module named models where class User is defined.
Now, I want to access that User() class using AUTH_USER_MODEL constant. How can this be done?
I tried to access it like this settings.AUTH_USER_MODEL(**data) which should be equivalent to User(**data) but it doesn't work.

A: In python module can be imported using import_module() method of  import importlib. Then to get the attributes of that module use method getattr() which takes two arguments module and attribute name.
This is how I have accomplished it -
def get_class(module_class_string):

    """
    :param module_class_string: full name of the class to create an object of
    :return: class
    """

    module_name, class_name = module_class_string.rsplit(".", 1)

    module_name = module_name + '.models'

    module = importlib.import_module(module_name)

    return getattr(module, class_name)