text:
Q: Entity Framework orderby doesnt order query result var comments =  (from p in _ctx.CommentRottas
                                .Where(s => s.Rotta_Id == Id && s.Status == 1)
                                .Include(s => s.Client)
                            orderby p.Date descending
                            select new CommentDTO
                                {
                                    CommentId = p.Id,
                                    Rotta = new RottaDTO
                                    {
                                        RottaId = p.Rotta_Id,
                                        RottaDate = p.SU_ROUTES.Date,
                                        ClientId = p.SU_ROUTES.ClientId,
                                        COMMENTS_NUM = p.SU_ROUTES.COMMENTS_NUM,
                                        LIKES_NUM = p.SU_ROUTES.LIKES_NUM,
                                    },
                                    Client = new ClientDTO
                                    {
                                        Id = p.Client_Id,
                                        UserName = p.Client.UserName,
                                        Profile_Image = p.Client.Profile_Image,
                                    },
                                    CommentDate = p.Date,
                                    Comment = p.comment,
                                }
                            )
                            .ToList();

            return comments;

Hi guys. I am trying to order comments in descending order by their date. But whatever I tried it does not order. I have similar query to this one and it works. But this one does not. I also tried using OrderByDescending(m => m.CommentDate) but still it does not order query. Do I make some mistake that I do not see or it's some entity framework issue ?
EDIT: Added DB Values
Id RID Comment UID DATE
107 680 test    27  2017-08-24 10:49:41.583 1
108 680 gdfg    27  2017-08-24 10:50:06.630 1
109 681 Khgs gdlkdg 18  2017-08-24 12:08:01.793 1
110 680 ttt 27  2017-08-24 13:24:52.407 1
111 684 dasdasd 27  2017-08-24 13:32:22.997 1
112 680 fdsfs   27  2017-08-24 13:59:24.317 1
113 684 OK  27  2017-08-25 07:35:43.627 1
114 684 Ghfgjn  20  2017-08-25 13:43:15.020 1
Result From Query For RID 684:
[
    {
        "CommentId": 111,
        "CommentDate": "2017-08-24T13:32:22.997",
        "Comment": "dasdasd",
        "Client": {
            "Id": 27,
            "UserName": "Test",
            "Profile_Image": "https://rota2.blob.core.windows.net/profile-images/profile.png"
        },
        "Station": null,
        "Rotta": {
            "RottaId": 684,
            "RottaDate": "2017-08-24T13:30:40.51",
            "COMMENTS_NUM": 3,
            "LIKES_NUM": 2,
            "Completed": 0,
            "STATUS": 0,
            "Is_Started": null,
            "ClientId": 19,
            "Stations": null,
            "Client": null
        },
        "Media": null
    },
    {
        "CommentId": 114,
        "CommentDate": "2017-08-25T13:43:15.02",
        "Comment": "Ghfgjn",
        "Client": {
            "Id": 20,
            "UserName": "Besart2",
            "Profile_Image": "https://rota2.blob.core.windows.net/profile-images/Date-2017-08-28T08-06-21-User-20.jpg"
        },
        "Station": null,
        "Rotta": {
            "RottaId": 684,
            "RottaDate": "2017-08-24T13:30:40.51",
            "COMMENTS_NUM": 3,
            "LIKES_NUM": 2,
            "Completed": 0,
            "STATUS": 0,
            "Is_Started": null,
            "ClientId": 19,
            "Stations": null,
            "Client": null
        },
        "Media": null
    },
    {
        "CommentId": 113,
        "CommentDate": "2017-08-25T07:35:43.627",
        "Comment": "OK",
        "Client": {
            "Id": 27,
            "UserName": "Test",
            "Profile_Image": "https://rota2.blob.core.windows.net/profile-images/profile.png"
        },
        "Station": null,
        "Rotta": {
            "RottaId": 684,
            "RottaDate": "2017-08-24T13:30:40.51",
            "COMMENTS_NUM": 3,
            "LIKES_NUM": 2,
            "Completed": 0,
            "STATUS": 0,
            "Is_Started": null,
            "ClientId": 19,
            "Stations": null,
            "Client": null
        },
        "Media": null
    }
]

GO

/****** Object:  Table [dbo].[CommentRottas]    Script Date: 8/28/2017 7:14:59 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[CommentRottas](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [Rotta_Id] [bigint] NOT NULL,
    [comment] [nvarchar](500) NULL,
    [Client_Id] [int] NOT NULL,
    [Date] [datetime] NOT NULL,
    [Status] [int] NOT NULL,
 CONSTRAINT [PK_dbo.CommentRottas] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
GO

ALTER TABLE [dbo].[CommentRottas]  WITH CHECK ADD  CONSTRAINT [FK_dbo.CommentRottas_dbo.SU_ROUTES_Rotta_Id] FOREIGN KEY([Rotta_Id])
REFERENCES [dbo].[SU_ROUTES] ([ROUTE_ID])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[CommentRottas] CHECK CONSTRAINT [FK_dbo.CommentRottas_dbo.SU_ROUTES_Rotta_Id]
GO

I finally solved problem. I dont know what caused problem but returning object instead of DTO solved problem. This is my solution.
   public ICollection<Object> GetRouteComments(long Id)
    {
        /*
        var result = await _ctx.CommentRottas
                        .Where(s => s.Rotta_Id == Id)
                        .Include(s => s.Client)
                        .Where(s => s.Status == 1)
                        .OrderByDescending(p => p.Date)
                        .ToListAsync();
        */
        var comments = (from p in _ctx.CommentRottas
                           .Where(s => s.Rotta_Id == Id && s.Status == 1)
                           .Include(s => s.Client)
                        orderby p.Date descending
                        select new CommentDTO
                        {
                            CommentId = p.Id,
                            Rotta = new RottaDTO
                            {
                                RottaId = p.Rotta_Id,
                                RottaDate = p.SU_ROUTES.Date,
                                ClientId = p.SU_ROUTES.ClientId,
                                COMMENTS_NUM = p.SU_ROUTES.COMMENTS_NUM,
                                LIKES_NUM = p.SU_ROUTES.LIKES_NUM,
                            },
                            Client = new ClientDTO
                            {
                                Id = p.Client_Id,
                                UserName = p.Client.UserName,
                                Profile_Image = p.Client.Profile_Image,
                            },
                            CommentDate = p.Date,
                            Comment = p.comment,
                        }
                        )
                        .ToList().Cast<Object>().ToList();

        return comments;

A: Have you tried having the .OrderBy after the select and not before?

A: If it's nullable, try orderby p.Date.GetDefaultOrValue()

A: I Found Solution, But i am not sure why it works.
 public ICollection<Object> GetRouteComments(long Id)
    {
        /*
        var result = await _ctx.CommentRottas
                        .Where(s => s.Rotta_Id == Id)
                        .Include(s => s.Client)
                        .Where(s => s.Status == 1)
                        .OrderByDescending(p => p.Date)
                        .ToListAsync();
        */
        var comments = (from p in _ctx.CommentRottas
                           .Where(s => s.Rotta_Id == Id && s.Status == 1)
                           .Include(s => s.Client)
                        orderby p.Date descending
                        select new CommentDTO
                        {
                            CommentId = p.Id,
                            Rotta = new RottaDTO
                            {
                                RottaId = p.Rotta_Id,
                                RottaDate = p.SU_ROUTES.Date,
                                ClientId = p.SU_ROUTES.ClientId,
                                COMMENTS_NUM = p.SU_ROUTES.COMMENTS_NUM,
                                LIKES_NUM = p.SU_ROUTES.LIKES_NUM,
                            },
                            Client = new ClientDTO
                            {
                                Id = p.Client_Id,
                                UserName = p.Client.UserName,
                                Profile_Image = p.Client.Profile_Image,
                            },
                            CommentDate = p.Date,
                            Comment = p.comment,
                        }
                        )
                        .ToList().Cast<Object>().ToList();

        return comments;

A: It is a waste of computing time to convert it to a List twice. Besides don't ise Include if you are only using certain parts of the Include result. Entity Framework will know which columns to query.
Having said that. I think your problem is because of the mixing of method syntax and query syntax. Maybe putting some extra parentheses would help.
I've translated your query into method syntax, and used your input. The output is as expected.
int Id = 684;
var result = myDbContext.CommentRottas
    .Where(comment => comment.Id == Id && comment.Status == 1)
    .OrderByDescending(comment => comment.Date)
    .Select(comment => new CommentDTO()
    {
        CommentId = comment.Id,
        Rotta = new RottaDTO
        {
            RottaId = comment.Rotta_Id,
            // not tested all properties
        },
        Client = new ClientDTO()
        {
            Id = comment.Client_Id,
            // not tested all properties
        },
        CommentDate = comment.Date,
        Comment = comment.Comment,
    })
    .ToList();

This works and gives the expected order. So my advise would be to stick to one syntax: method or query. If you use query syntax, be use parentheses.
Finally: consider not to return the list, but the IEnumerable. If your caller only wants the first element, or the first few, It would be a wast to query everything. Let your caller decide if he wants to add other functions to your IEnumerable before enumerating over it (or put it in a list)


text:
Q: Dynamic collection validation with vuelidate i have a variable items(array of objects) with 3 attributes for every item (value, other and otherKey), for every item, the value field is required, the other field is required only if value field value is equal to otherKey field.
Look the example on jsfiddle

https://jsfiddle.net/dyquv3ek/5/

// Template

       <input type="text" v-model="item.value"
          @input="$v.items.$each[i].$touch"
         :class="{error: $v.items.$each[i].value.$error}">
       <input type="text" v-model="item.other"
          @input="$v.items.$each[i].$touch"
          :class="{error: $v.items.$each[i].other.$error}">

{{ $v }}

// Js
Vue.use(window.vuelidate.default)

const { required } = window.validators

new Vue({
    el: "#app",
  data: {
    items: [{
        value: 'A',
      other: 'B',
      otherKey: 'C'
    }, {
        value: 'D',
      other: 'E' ,
      otherKey: 'F'
    }, {
        value: 'G',
      other: 'H'  ,
      otherKey: 'I'
    }]
  },
  validations: {
    items: {
        $each: {
        value: { required },
        other: {} // { required } only if value === otherKey
      }
    }
  }
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to filter out rows from a table with an unnamed column I'm currently trying to do analysis of rolling correlations of a dataset with four compared values but only need the output of rows containing 'a'
I got my data frame by using the command newdf = df.rolling(3).corr()
Sample input (random numbers)
    a b c d
1 a
1 b
1 c
1 d
2 a
2 b
2 c
2 d
3 a
3 b   5 6 3
3 c   4 3 1
3 d   3 4 2
4 a 1 3 5 6
4 b 6 2 4 1
4 c 8 6 6 7
4 d 2 5 4 6
5 a 2 5 4 1
5 b 1 4 6 3
5 c 2 6 3 7
5 d 3 6 3 7

and need the output
    a b c d
1 a 1 3 5 6
2 a 2 5 4 1

I've tried filtering it by doing adf = newdf.filter(['a'], axis=0) however that gets rid of everything and when doing it for the other axis it filters by column. Unfortunately the column containing the rows with values: a, b, c, d is unnamed so I cant filter that column individually. This wouldn't be an issue however if its possible to flip the rows and columns with the values being listed by index to get the desired output.

A: Try using loc. Put the column of abcdabcd ... as index and just use loc
df.loc['a']

A: The actual source of problem in your case is that your DataFrame
has a MultiIndex.
So when you attempt to execute newdf.filter(['a'], axis=0) you want
to leave rows with the index containing only "a" string.
But since your DataFrame has a MultiIndex, each row with "a" at
level 1 contains also some number at level 0.
To get your intended result, run:
newdf.filter(like='a', axis=0)

maybe followed by .dropna().
An alterantive solution is:
newdf.xs('a', level=1, drop_level=False)


text:
Q: How to play audio from audio array on click in xml in android      public void getSound(String file) {
                    MediaPlayer mp;
                        try{
                            String SoundFile=file;
                            System.out.println("Here is the File"+SoundFile);
                            mp = MediaPlayer.create(getActivity().getBaseContext(),Uri.parse("android.resource://himanshu.sound/raw/"+file));
                            mp.start();
                            System.out.println("PLAYED");
                        }catch(Exception e){
                            System.out.println("Exception->"+e);
                        }
                }

This is my code file name is game.mp3 comming from assets.
Now I want to the audio to be played
This is my xml
    <ImageView
                        android:id="@+id/soundbtn"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:clickable="true"
                        android:gravity="right"
                        android:onClick="getSound"
                        android:paddingLeft="5dp"
                        android:paddingRight="15dp"
                        android:paddingBottom="5dp"
                        android:src="@drawable/audio" />

mp = MediaPlayer.create(getActivity().getBaseContext(),Uri.parse("android.resource://himanshu.sound/raw/"+file));

in this line i am having error
getActivity().getBaseContext()  i think proper thing must be there

A: You''d better have an ImageButton
                  <ImageButton
                    android:id="@+id/soundbtn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:gravity="right"
                    android:onClick="onClick"
                    android:paddingLeft="5dp"
                    android:paddingRight="15dp"
                    android:paddingBottom="5dp"
                    android:src="@drawable/audio" />

and the OnClick method has to be with a different signature
public final void onClick(View v) {

    // todo ............
     }


text:
Q: Create a new link to a document using SharePoint 2010 I need to add a new document link to a document library using the client object model. I suspect I could copy the format of the .aspx file used in the "link to a document" items and upload it as a normal file but I'm hoping there is a neater way.
So what I want to do is the same as the code sample below but instead of creating a new document I want to create a new link to a document.
ClientContext context = new ClientContext("http://wdev2008:22880");
context.Load(context.Web);
List list = context.Web.Lists.GetByTitle("Test Doc Link Library");
context.Load(list);
context.ExecuteQuery();

FileCreationInformation fileCreateInfo = new FileCreationInformation();
fileCreateInfo.Content = new byte[] { 0x33 };
fileCreateInfo.Url = "zerobyte";
File file = list.RootFolder.Files.Add(fileCreateInfo);
context.Load(file);
context.ExecuteQuery();

Update: According to the mod on this forum I'm not allowed to ask how to do this with a web service in a separate question so I'll change the title, tags and content on this question. Does anyone know how to do the insert with a SharePoint web service or server side control or anything else?

A: Turns out it can be done but it's a bit of a hack that involves taking a copy of the .aspx file SharePoint uses for document links and doing a string search and replace on it Creating a 'Link to a Document' Item in a SharePoint Document Library programmatically.
I tailored the example to use the client object model:
 string docLinkTemplate = null;
 using (System.IO.StreamReader sr = new System.IO.StreamReader("SharePointDocLinkTemplate.txt"))
 {
     docLinkTemplate = sr.ReadToEnd();
 }

 string docLink = "http://myserver/test.doc";
 docLinkTemplate = String.Format(docLinkTemplate, docLink);

 FileCreationInformation fileCreateInfo = new FileCreationInformation();
 fileCreateInfo.Content = Encoding.UTF8.GetBytes(docLinkTemplate);
 fileCreateInfo.Url = "testlinkfordoc.doc.aspx";
 File file = list.RootFolder.Files.Add(fileCreateInfo);
 ListItem fileListItem = file.ListItemAllFields;
 fileListItem["ContentType"] = "Link to a Document";
 FieldUrlValue urlValue = new FieldUrlValue();
 urlValue.Description = "Link to doc test";
 urlValue.Url = docLink;
 fileListItem["URL"] = urlValue;
 context.Load(file);
 context.ExecuteQuery();

(Hopefully the mod won't deem this answer unworthy again. Pity the mods on these programming web sites don't have to get stackoverflow rep before they can start throwing their weight around.)


text:
Q: How to prevent building / compiling files that have not changed in Xcode? I am using the cocos2d template in Xcode.
I initially made some changes to some of the cocos2d files, to comment out class I don't use that are deprecated, and which produce warnings.
It is unlikely I am going to make any more changes to any of the cocos2d files again.
Is there a way to set my Xcode project settings to only recompile "my files", and not just the cocos2d files each time (since there won't be any changes in the cocos2d files)? Ideally, the cocos2d files should be recompiled only if there is a change.
I am using cocos2d 2.1, and Xcode 5.0.2


text:
Q: Convert Int32 to String I have a small piece of code that converts a string to Int32
Dim sample As String = "H۩llo!"
For Each c As Char In sample
    Dim enc As String = Convert.ToInt32(c)
    Console.Write(enc + " ")
Next
Console.ReadKey()

This will convert the text to Int32
Output:
72 1769 108 108 111 33

But is there a way to conver the output back to "H۩llo!"?

A: You can convert it back to the original string with
Dim nums As Int32() = { 72, 1769, 108, 108, 111, 33 }
Dim cs As Char() = nums.Select(Function(x) Microsoft.VisualBasic.ChrW(x)).ToArray()
Dim s = New String(cs)
Console.OutputEncoding = System.Text.Encoding.UTF8
Console.WriteLine(s)


text:
Q: Ngrok "HTTP Error 404". The requested resource is not found Error picture
I've tried to execute my django-app with "ngrok". Added url to "ALLOWED_HOSTS" and other variables which need that. I did 'py manage.py runserver' and 'ngrok http 80' together => no result.

A: A few hours later, I figure out that you must run your ngrok from CMD, not from IDE Terminal.
P.S. If you set domain in 'C:\Windows\System32\Drivers\etc\ hosts' for your local address, that command help may help you:

ngrok http --host-header=rewrite mysite.com:80

where mysite.com - your domain name, :80 - your port.


text:
Q: Date { NaN } React Native I'm using react native and I'm trying to convert my timestamp data to date but the output said "Date { NaN }"
       const [eventData1, setEventData1] = useState({});

          useEffect(() => {
            database()
              .ref('path')
              .on('value', snapshot => {
                if (snapshot.val() !== null) {
                  setEventData1({...snapshot.val()});
                } else {
                  setEventData1({});
                }
              });

            return () => {
              setEventData1([]);
            };
          }, []);

     const dates = Object.keys(eventData1).map(
        id => eventData1[id].start_DATE * 1000,
      );
      const sDate = new Date(dates);

Outputs
    console.log(dates) -----> //[1648703685000, 1648623600000]//

    console.log(sDate) ------> //Date { NaN }//

A: dates is an array of UNIX timestamps [1648703685000, 1648623600000] which you are trying to pass to the Date() constructor. But Date() does not take an array but can take a single timestamp as a parameter. You will have to loop over the dates to get the start and (presumably) end date parsed.

const dates = [1648703685000, 1648623600000]
const parsedDates = dates.map(date => new Date(date));
const [startD, endD] = parsedDates;

console.log("Start:", startD);
console.log("End:", endD);

BTW: You can do the above in one line if you want to:
const [startD, endD] = dates.map(date => new Date(date));


text:
Q: lambdas in removeIf HashSet<Integer> liczby = new HashSet<Integer>();
liczby.add(1);
liczby.add(2);
liczby.add(3);
liczby.add(4);
liczby.removeIf ((Integer any) -> { return liczby.contains(3); });

for(Iterator<Integer> it = liczby.iterator(); it.hasNext();){
    Integer l2 = it.next();
    System.out.println(l2);
}

I can't understand why removeIf deletes not only 3 but also 1 and 2 condition should be satisfied only by 3...

A: Think of it this way... as long as the set contains 3 it will keep removing hence the current outcome.
If you want to remove the 3 only then do this:
liczby.removeIf(e -> e == 3);

A: The lambda is applied on each element and check if 3 is present, if yes it will delete the element :
1 -> 3 is present -> delete 1
2 -> 3 is present -> delete 2
3 -> 3 is present -> delete 3
4 -> 3 is not present -> don't delete 4

To remove all 3 element, you can use one of those solutions :
liczby.removeIf(any -> any.equals(3));
//-------------------------------------------------
liczby.removeIf(new Integer(3)::equals);
//-------------------------------------------------
Integer toRemove = 3;
liczby.removeIf(toRemove::equals);

TIPS
Your lambda can be simplified as :
liczby.removeIf(any -> liczby.contains(3));

For-each loop might be easier to use for simple iteration :
for(Integer i : liczby){
    System.out.println(i);
}


text:
Q: Google App Engine deployment issue- main app not found I am trying to deploy my app using Google App Engine. I have edited app.yaml to reflect the flexible environment and also gave all the app information. Below is the app.yaml file.
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app
runtime_config:
  python_version: 3

Once the deployment is in progress, I am getting the following error
[2018-08-24 06:57:14 +0000] [1] [INFO] Starting gunicorn 19.7.1
[2018-08-24 06:57:14 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)
[2018-08-24 06:57:14 +0000] [1] [INFO] Using worker: sync
[2018-08-24 06:57:14 +0000] [7] [INFO] Booting worker with pid: 7
App Deployed
Failed to find application: 'main'
[2018-08-24 06:57:14 +0000] [7] [INFO] Worker exiting (pid: 7)
[2018-08-24 06:57:14 +0000] [1] [INFO] Shutting down: Master
[2018-08-24 06:57:14 +0000] [1] [INFO] Reason: App failed to load.

Please note that App Deployed is the line in my print statement. It is getting executed. But the deployment is getting failed
Thank you in advance

A: In your app.yaml, you're starting gunicorn with gunicorn -b :$PORT main:app. This tells it to look for the object app in the file main.py
The error you're getting comes from gunicorn and occurs when you have a main.py file, but it does not have an app object in it.
You probably want to set up a Flask app as follows:
from flask import Flask

app = Flask(__name__)

See a full example app here: https://cloud.google.com/appengine/docs/flexible/python/quickstart#hello_world_code_review

A: I have had the same issue.
Failed to find application: 'main'

The reason in my case was that I had a directory called also main in the root project directory.
drwxr-xr-x   2 user  staff    64 Nov 30 10:12 main
-rw-r--r--   1 user  staff  1178 Nov 29 20:58 main.py

I guess gunicorn got confused.
The solution (worked for me): to rename main directory.
P.S. Just don't rename it to code directory. It will cause another issue with debugging in PyCharm. :)

A: My folder structure is looks llike this the main.py is not in the root directory how I can specify this in app.yaml file.
/app
 |__main.py
app.yaml


text:
Q: React useState initialise with an existing object I'm new to React and don't know if this is allowed in React:
I want to collect form data and send requests with such data in a modal.
I also want the input fields to have default values from existing data (props.itemInfo).
I'm trying to initialise the formData with
function Parent() {
  const [state, setState] = useState(false);
  const [itemInfo, setItemInfo] = useState({})

  // itemInfo get from somewhere in the middle

  return (

      <button onClick={() => setState(true)> Render modal </button>
      <Modal itemInfo={itemInfo} state={state} setState={setState} />

  )
};

function Modal(props) {
  let itemInfo = props.itemInfo;
  console.log(typeof itemInfo); // 1
  console.log(itemInfo);        // 2

  /* I also tried
    const [formData, setFormData] = useState({itemInfo});
    but not working
  */

  const [formData, setFormData] = useState({
    itemID: itemInfo.itemID,
    userID: itemInfo.userID,
    isActive: itemInfo.isActive,
    purchaseCost: itemInfo.purchaseCost,
    dateModified: itemInfo.dateModified,
    dateCreated: itemInfo.dateCreated,
    description: itemInfo.description,
    itemGrouping: itemInfo.itemGrouping,
  });
  console.log(itemInfo.itemID); // 3
  console.log(formData.itemID); // 4

  const handleCloseModal = () => {
    props.setState(false);
  };

  const handleFormChange = (e) => {
    const { id, value } = e.target;
    setFormData((prevState) => ({
      ...prevState,
      [id]: value,
    }));
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    // send request with formData
  };
  return (
    <ReactModal isOpen={props.state} ariaHideApp={false}>
      <form id="login">

          Grouping:
          <input
            id="grouping"
            type="text"
            defaultValue={formData.itemGrouping}
            onChange={handleFormChange}
            required
          />

          Cost:
          <input
            id="cost"
            type="text"
            defaultValue={formData.purchaseCost}
            onChange={handleFormChange}
            required
          />

          Description:
          <input
            id="description"
            type="text"
            defaultValue={formData.description}
            onChange={handleFormChange}
            required
          />

        <button type="submit" onClick={handleSubmit}>
          Submit
        </button>
      </form>
      <button onClick={handleCloseModal}>Close Modal</button>
    </ReactModal>
  );
}

The existing object received is
{
    "itemID": 3,
    "userID": 2,
    "isActive": 1,
    "purchaseCost": 0,
    "dateModified": "2022-10-05 03:44:07",
    "dateCreated": "2022-10-05",
    "description": "Gift from my sister for my 29th birthday!",
    "itemGrouping": null
}

and the 4 console.log() gives the following output:
object        // 1

{
    "itemID": 3,
    "userID": 2,
    "isActive": 1,
    "purchaseCost": 0,
    "dateModified": "2022-10-05 03:44:07",
    "dateCreated": "2022-10-05",
    "description": "Gift from my sister for my 29th birthday!",
    "itemGrouping": null
}              // 2

3              // 3

undefined      // 4

I don't know why this is not working, and is there any approach that can achieve the goal I want.
Thanks

A: There is an issue with storing the prop itemInfo inside the state value.
You are storing the object in a new object like,
const [formData, setFormData] = useState({itemInfo});

It will create a state with itemInfo property,
So after using this, You will only be able to access the state by following statements,
formData.itemInfo.itemID

This is JavaScript where if you add an object by its name in the new object it will add new property similar to the object name and value with the placed object.
You can also simply store the prop item in a state like below,
const [formData, setFormData] = useState({ ...itemInfo });

The above statement will extract all the object properties into the new object, and can be accessible by formData state.


text:
Q: How to draw an entity-relationship diagram with "at least" and "exactly" relationships The business rules are:

*

*An order must have at least one product, and

*a customer must have created exactly one order.

How can I draw an entity-relationship diagram for this?


text:
Q: How to read lines of a file in Ruby I was trying to use the following code to read lines from a file. But when reading a file, the contents are all in one line:
line_num=0
File.open('xxx.txt').each do |line|
  print "#{line_num += 1} #{line}"
end

But this file prints each line separately.

I have to use stdin, like ruby my_prog.rb < file.txt, where I can't assume what the line-ending character is that the file uses. How can I handle it?

A: I'm partial to the following approach for files that have headers:
File.open(file, "r") do |fh|
    header = fh.readline
    # Process the header
    while(line = fh.gets) != nil
        #do stuff
    end
end

This allows you to process a header line (or lines) differently than the content lines.

A: It is because of the endlines in each lines.
Use the chomp method in ruby to delete the endline '\n' or 'r' at the end.
line_num=0
File.open('xxx.txt').each do |line|
  print "#{line_num += 1} #{line.chomp}"
end

A: how about gets ?
myFile=File.open("paths_to_file","r")
while(line=myFile.gets)
 //do stuff with line
end

A: Ruby does have a method for this:
File.readlines('foo').each do |line|
    puts(line)
end

http://ruby-doc.org/core-1.9.3/IO.html#method-c-readlines

A: File.foreach(filename).with_index do |line, line_num|
   puts "#{line_num}: #{line}"
end

This will execute the given block for each line in the file without slurping the entire file into memory.  See: IO::foreach.

A: Don't forget that if you are concerned about reading in a file that might have huge lines that could swamp your RAM during runtime, you can always read the file piece-meal.  See "Why slurping a file is bad".
File.open('file_path', 'rb') do |io|
  while chunk = io.read(16 * 1024) do
    something_with_the chunk
    # like stream it across a network
    # or write it to another file:
    # other_io.write chunk
  end
end

A: Your first file has Mac Classic line endings (that's "\r" instead of the usual "\n"). Open it with
File.open('foo').each(sep="\r") do |line|

to specify the line endings.

A: I believe my answer covers your new concerns about handling any type of line endings since both "\r\n" and "\r" are converted to Linux standard "\n" before parsing the lines.
To support the "\r" EOL character along with the regular "\n", and "\r\n" from Windows, here's what I would do:
line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
  print "#{line_num += 1} #{line}"
end

Of course this could be a bad idea on very large files since it means loading the whole file into memory.


text:
Q: Parsing JSON Array I'm trying to print company list.
My JSON object:
{
    "Name": "crunchify.com",
    "Author": "App Shah",
    "Company List": [
        "Compnay: eBay",
        "Compnay: Paypal",
        "Compnay: Google"
    ]
}

code:
public class ProductTypeParser {

    public  void parseJson(JSONObject jsonObject) throws ParseException {

        JSONObject object = (JSONObject) jsonObject;
        String name = (String) object.get("Name");
        System.out.println(name);

        String age = (String) object.get("Author");
        System.out.println(age);

        //loop array
        JSONArray msg = (JSONArray) object.get("Company List");
        Iterator<String> iterator = msg.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Error:
SEVERE: Servlet.service() for servlet [contextServlet] in context with path [/SpringSafeHouseService2.0]
  threw exception [Request processing failed; nested exception is
    java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.json.simple.JSONArray]
  with root cause java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.json.simple.JSONArray

A: Cast into ArrayList instead of JSONArray (because can be a JSONArray or an ArrayList or an implementation of List it's depends how you deserialize your string so use an ArrayList or the interface List ensure you can't have a Class cast exception):
JSONObject parser = new JSONParser();
    JSONObject object = (JSONObject) parser.parse("{\n" +
            "    \"Name\": \"crunchify.com\",\n" +
            "    \"Author\": \"App Shah\",\n" +
            "    \"Company List\": [\n" +
            "        \"Compnay: eBay\",\n" +
            "        \"Compnay: Paypal\",\n" +
            "        \"Compnay: Google\"\n" +
            "    ]\n" +
            "}"); // Here there is a JSONArray for companies property

    Map<String, Object> obj = new HashMap();
    List<String> companies = new ArrayList<>();
    companies.add("a");
    companies.add("b");
    companies.add("c");
    obj.put("Name", "toto");
    obj.put("Author", "titi");
    obj.put("Company List", companies);
    JSONObject object2 = new JSONObject(obj); // here you have an ArrayList for companies property

    String name = (String) object.get("Name");
    System.out.println(name);

    String age = (String) object.get("Author");
    System.out.println(age);

    //loop array
    List msg = (List) object.get("Company List");
    Iterator<String> iterator = msg.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }

A: Json-simple (which you seem to be using although the version is missing so my information might be outdated) normally creates an instance of JSONArray (which extends ArrayList btw.) for arrays in json strings, i.e. your "Company List" field.
However, you are also able to pass in a different ContainerFactory which might create a different List instance for arrays so that might be the reason your cast doesn't work (again there's too little information in your question to further comment on that).
Finally, since you should get a List anyways it should be safe to cast to that:
List<?> msg = (List<?>) object.get("Company List");

A: Try JSONArray msg = object.getJSONArray("Company List"); instead of JSONArray msg = (JSONArray) object.get("Company List");

A: You are using org.json.simple which has a different interface.
Here is how you iterate over the ArrayList
 for(String s : object.get("Company List"))
      System.out.println(s);


text:
Q: SSL Certificate fails for CA certificate in mosquitto 1.2.1/1.2.2 While trying to upgrade from mosquitto 1.1.3 to 1.2.1/1.2.1. I am getting this error while trying to subscribe to an event.

mosquitto_sub -h 192.168.255.2 -p 8883 -v -t "test" --cafile /etc/certs/rootCA/ca.root.crt –d
OpenSSL Error: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

The same CA certificate is working fine with 1.1.3 version.
Is there any problem with the openssl version ?
I have the version 1.0.0.

A: The problem is that the commonName in your certificate does not match the hostname (in this case the IP address) you are connecting to. 1.1.3 did not verify this, and so was vulnerable to your server being impersonated.
You should either fix your commonName to match the hostname you are using, or better use the subjectAltName certificate extension to provide your hostname/IP address. subjectAltName allows you to specify any number of hostnames and IP addresses in a certificate. Mqttitude has an example of how to generate certificates: https://github.com/binarybucks/mqttitude/blob/master/tools/TLS/generate-CA.sh
I believe that using an IP address as the commonName is frowned upon.
As a final option, you can also use the --insecure options for mosquitto_pub/sub, or set tls_insecure if you are using a bridge. As these options suggest, doing so will reduce the security of your system.


text:
Q: How to specify a caption outside of figure element I have a situation where I need physically separate a caption from the associated figure, e.g. this sort of markup:

…later in the code…

  Caption text

This isn't semantically correct (there are existing SO questions addressing it), and it produces a validation error. Given that, I'm wondering what the appropriate way to represent this would be (considering markup and accessibility).
Ideally, there would be some sort of attribute (like the label elements for attribute) that would let you associate a figcaption with a figure. Currently I am using an aria-describedby attribute (see below), but I'm not sure if this is accurate either.

…later in the code…

  Caption text

A: There are a couple of ways you could approach this, either by adding a role and using aria-labelledby, or with JavaScript.
Method 1 - HTML Only
The aria-labelledby attribute is only recognized on form controls (e.g. buttons, inputs, checkboxes, etc.) or on elements that have a role attribute assigned. Without either of these conditions, the accessible name computation will not be calculated on the element.

…later in the code…

Caption text

In my testing on NVDA/Chrome this works as long as the alt attribute on the image is not empty.  I would strongly recommend testing this using different browsers and screen-readers before deploying to a production environment for the reason that it's essentially a label on a non-interactive element.
Method 2 - JavaScript and CSS
This method is more inline with your original question. It produces a non-visual figcaption element as a child of the figure element.

…later in the code…

Caption text


text:
Q: How can I make my DynamicMethod security-critical? I have a rather convoluted scenario where I want to create a DynamicMethod that's attached to a class in an in-memory AssemblyBuilder. The dynamic method calls a method "GetReplacement" in a (regular) assembly of mine.
This worked fine in .NET 2.0, but in .NET 4.0 I get an error:
MethodAccessException: Attempt by security transparent method 'DynamicClass.Max(Int32, Int32)'
to access security critical method 'xxx.GetReplacement()' failed.

From what I've read, my dynamic method (Max in the error above) is security-transparent because the assembly it's attached to (the AssemblyBuilder) is transparent. I'm guessing the AssemblyBuilder is transparent because it's a dynamic assembly.
How do I make my dynamic method critical or do whatever it takes to grant it permission to call GetReplacement? There are a couple of other methods I want to call in GetReplacement's assembly so fixing the dynamic method would be better than marking GetReplacement in some way.
I'm a bit lost and would love some help!

A: While creating the AssemblyBuilder you should use a CustomAttributeBuilder  to assign a SecurityCriticalAttribute to the assembly.
Once the assembly is marked a Security-Critical you could add the same attribute to any DynamicMethod.

A: Oops, this was a mistake on my part. The docs are right: the dynamic method inherits its security from the type to which it's attached. Methods that you don't attach to a type are attached to a security transparent assembly. You can't add an attribute to a DynamicMethod overriding the security -- you have to attach it to an appropriate type.
I was making a dumb mistake: looking at the dynamic method attached to an AssemblyBuilder, not the one attached to mscorlib (which is security transparent).


text:
Q: OpenESB - EmailBC: Attached File I'm working on a BPEL in OpenESB for sending emails with attachment files.
I have installed the email binding component and I followed the steps described in the manual, so now my BPEL is able to send an email with an attachment file.
I have added the option SMTPAttachemnt in the binding as you can see in the image :

But I have a problem because the bpel receives a base64 encode file, so when I check my email inbox the file attached remains encode :(
So I think if I want to receive the file decoded in my email inbox,  I would have to decode the "attachedFile" element before sending the email. My question is: what's the best way to decode the a base64 encode file element in OpenESB ?
Thanks in advance!!
I will look forward to hearing your solutions,
Girish

A: You can use direct java call from BPEL itself. on java-6, we use it like
DatatypeConverter.parseBase64Binary("encoded="); just map input and outputs.


text:
Q: Targetting DataGrid Row Header is being applied to many rows I'm importing an excel file to a wpf DataGrid to save the data in the database.
Before importing the DataGrid to the database the user needs to check if the data is correct.
In the database there are some parameters to be compared with the data coming from the excel File. One of these parameters is Start_Import_Row whic is basically the starting point to the import i.e. everything above the starting row will not be included to the database import.

The blue arrow on the row header shows the user where the import will start and the user can change the starting point before the import, the default value is set in the database depending on the selected type in the ComboBox at the top left corner.
When the DataGrid is small everything is working as it should, but whenever the DataGrid gets a vertical scroller the blue arrow keeps getting repeated every few rows like this:

I'm almost sure that the fail is occurring when I'm targeting the DataGrid row because as you might know, DataGrid has a Columns property but it does not have a Rows property.
I tried changing the way I'm picking the rows but I'm using this method GetRow in many other places in the application and it was the most efficient way among the things i tried and yet nothing really worked as it should.
and here is my code (I deleted any code that has nothing to do with the problem) :
 Private Sub OpenFileCommandExecute(obj As Object)
    Dim openFile As OpenFileDialog = New OpenFileDialog()
    openFile.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm"
    openFile.DefaultExt = ".xlsx"
    If openFile.ShowDialog() = True Then
        Try
                ExcelToDataGrid(openFile)
                SetStartingRowArrowHeader()
        Catch ex As Exception
            MessageBox.Show("Failed" + vbNewLine + ex.Message)
        Finally
            Mouse.OverrideCursor = Nothing
        End Try

    End If

End Sub

 Private Sub SetStartingRowArrowHeader()
    Dim _window = TryCast(Me.NotifyWindow, Import)
    Dim dg = _window.dgExcelDataGrid
    Dim startingRow = ExcelSheetTypeSelected.Start_Import_Row
    Dim fa = New FontAwesome.WPF.ImageAwesome()
    fa.Icon = FontAwesome.WPF.FontAwesomeIcon.ArrowCircleOutlineRight
    fa.Width = 15
    fa.Height = 15
    fa.Foreground = Brushes.Blue
    dg.GetRow(startingRow).Header = fa
    RaiseCanShiftStartingRowCommandChanged()
End Sub

and here is the extension method that is picking the row :
  <Extension()>
Public Function GetRow(ByVal grid As DataGrid, ByVal index As Integer) As DataGridRow
    Dim row As DataGridRow = CType(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)

    If row Is Nothing Then
        grid.UpdateLayout()
        grid.ScrollIntoView(grid.Items(index))
        row = CType(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
    End If

    Return row
End Function


text:
Q: Extracting Facebook Comments With IMacros I'm trying to extract comments from certain facebook posts and put that information into a table.
I can copy the commenter and and their comment with:
TAG POS=1 TYPE=DIV ATTR=CLASS:UFICommentContent EXTRACT=TXT
but I'm unsure how to get this information separately to put it in a table like so:
COMMENTER NAME | COMMENT | COMMENTER'S FACEBOOK URL
Any advice?

A: Use VBA to run your imacro if you're planning to store it in Excel(this feature is available only on Enterprise editions, vba integration, ie.).
All you'll need to do is create a loop with the imacro script and row iteration update inside.
Like so:
row=1 'choose which row to start from
Do While True
    ret = imac.iimPlay("CODE:TAG <line to extract commenter name>" & vbCrLf & _
    "TAG <line to extract comment>" & vbCrLf & "TAG <line to extract URL>")
    'Determine when to stop
    If not ret < 0 then
        Worksheets("Ur wksht").cells(row, 1).value = imac.iimGetExtract(1)
        Worksheets("Ur wksht").cells(row, 2).value = imac.iimGetExtract(2)
        Worksheets("Ur wksht").cells(row, 1).value = imac.iimGetExtract(3)
    Else
        MsgBox("All Done!")
        Exit Sub
    End If
    'iterate row
    row = row + 1
Loop

Hope this helps.


text:
Q: Scala's HashSet doesn't seem to implement Set? I have a Scala class:
class Example {
    def fooBar() : String = {
        // do some stuff

        var whistles = new HashSet[String]()
        fizzBuzz(whistles)

        // do some more stuff
    }

    def fizzBuzz(whistles : Set[String]) : Unit = {
        // do some stuff down here
    }
}

This gives me compiler errors when I call the fizzBuzz method (from inside fooBar), stating:

type mismatch; found : java.util.HashSet[String] required: Set[String]

What am I missing here?!? HashSet implements Set, the last time I checked...

A: You're mixing java.util.HashSet[A], the java version of HashSet, with scala.collection.immutable.Set[A]. You want scala.collection.immutable.HashSet[A] instead:
val whistles = scala.collection.immutable.HashSet[String]()
fizzBuzz(whistles)

A: Scala has neat implementation of collections.It has two flavor of  collection.

*

*Mutable collection (Read and write)
scala.collection.mutable.*

*Immutable collection (read-only)
scala.collection.immutable.*
you should not confuse between two variants.
Mutable
    val mutableHashset = scala.collection.mutable.HashSet[String]()
    mutableHashset += "name"
    mutableHashset.foreach { println }

Immutable
  val immutableHashSet = scala.collection.immutable.HashSet[String]("Name", "Age", "Address")
    immutableHashSet.foreach { println }


text:
Q: error invalid hook call issue while using Redux store to do api calls in React-Native So as preface I am learning react-native and I am developing an app which connects to an backend api using redux.
I am getting the following error when I try to run the app.
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

This error is located at:
    in ComplaintsMenu (created by HomePage)
    in RCTView (created by View)
    in View (created by HomePage)
    in RCTView (created by View)
    in View (created by HomePage)
    in HomePage (created by SceneView)
    in StaticContainer
    in EnsureSingleNavigator (created by SceneView)
    in SceneView (created by CardContainer)
    in RCTView (created by View)
    in View (created by CardContainer)
    in RCTView (created by View)
    in View (created by CardContainer)
    in RCTView (created by View)
    in View
    in CardSheet (created by Card)
    in RCTView (created by View)
    in View (created by AnimatedComponent)
    in AnimatedComponent
    in AnimatedComponentWrapper (created by PanGestureHandler)
    in PanGestureHandler (created by PanGestureHandler)
    in PanGestureHandler (created by Card)
    in RCTView (created by View)
    in View (created by AnimatedComponent)
    in AnimatedComponent
    in AnimatedComponentWrapper (created by Card)
    in RCTView (created by View)
    in View (created by Card)
    in Card (created by CardContainer)
    in CardContainer (created by CardStack)
    in RNSScreen (created by AnimatedComponent)
    in AnimatedComponent
    in AnimatedComponentWrapper (created by InnerScreen)
    in Suspender (created by Freeze)
    in Suspense (created by Freeze)
    in Freeze (created by DelayedFreeze)
    in DelayedFreeze (created by InnerScreen)
    in InnerScreen (created by Screen)
    in Screen (created by MaybeScreen)
    in MaybeScreen (created by CardStack)
    in RNSScreenContainer (created by ScreenContainer)
    in ScreenContainer (created by MaybeScreenContainer)
    in MaybeScreenContainer (created by CardStack)
    in RCTView (created by View)
    in View (created by Background)
    in Background (created by CardStack)
    in CardStack (created by HeaderShownContext)
    in RNCSafeAreaProvider (created by SafeAreaProvider)
    in SafeAreaProvider (created by SafeAreaInsetsContext)
    in SafeAreaProviderCompat (created by StackView)
    in RNGestureHandlerRootView (created by GestureHandlerRootView)
    in GestureHandlerRootView (created by StackView)
    in StackView (created by StackNavigator)
    in PreventRemoveProvider (created by NavigationContent)
    in NavigationContent
    in Unknown (created by StackNavigator)
    in StackNavigator (created by App)
    in EnsureSingleNavigator
    in BaseNavigationContainer
    in ThemeProvider
    in NavigationContainerInner (created by App)
    in RCTView (created by View)
    in View (created by SafeAreaWrap)
    in SafeAreaWrap (created by App)
    in Provider (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)

my reducer is-
export function complaintReducer(state = initalComplaintsFormState, action) {
  switch (action.type) {
    //...other cases

    case GET_COMPLAINT_LIST:
      return { ...state, complaintList: action.payload };

    default:
      return state;
  }
}

and my ComplaintsMenu component has the following code-

//...other imports

import { useSelector, useDispatch } from "react-redux";
import { getComplaintList } from "../Redux/Actions";

export default function ComplaintsMenu() {

  const { ComplaintList } = useSelector((state) => state.complaintReducer);
  const dispatch = useDispatch;

----------

// From my understanding this is where the issue is, since the dispatch function (hook?) is being called conditionally under the useEffect hook. but I don't understand what exactly is happening and how to implement what I am trying to implement, I followed steps from the youtube video mentioned below where he did the same thing

useEffect(() =\> {
dispatch(getComplaintList());
}, \[\]);

return (
  \<FlatList
    data={ComplaintList}
    renderItem={({ item }) =\> (
      \<ComplaintCard
        key={item.complaint_id}
        title={item.issue}
        status={item.status}
      /\>
     )}
   /\>
);

these are my dependencies version

{
"name": "poll-app",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web"
},
"dependencies": {
"@expo-google-fonts/inter": "^0.2.2",
"@expo/webpack-config": "^0.17.2",
"@react-navigation/native": "^6.1.3",
"@react-navigation/stack": "^6.3.12",
"expo": "\~47.0.12",
"expo-status-bar": "\~1.4.2",
"react": "18.1.0",
"react-dom": "18.1.0",
"react-native": "0.70.5",
"react-native-safe-area-context": "4.4.1",
"react-native-screens": "\~3.18.0",
"react-native-web": "\~0.18.9",
"react-redux": "^8.0.5",
"redux": "^4.2.1",
"redux-thunk": "^2.4.2"
},
"devDependencies": {
"@babel/core": "^7.12.9",
"eslint-plugin-react-hooks": "^4.6.0"
},
"private": true
}

Note: I am using an older version of node because expo had some legacy dependency issue with the current lts version of node

I have tried This answer, I believe my question is a duplicate of this question, I don't know how to revive unanswered questions so I am asking this question here, I apologize if this is not the correct way to ask for the answer on stack.
I followed this Youtube tutorial for the implementation
As of now

*

*I have reinstalled react-redux and redux and also tried npm update.

*To check for the react version mismatch issue. I have also verified that all the dependencies use the same react version.

I have included my thoughts about the problem in the a comment in the code above

A: try like this const dispatch = useDispatch(), you're not calling the function useDispatch


text:
Q: What does ''?'' mean in SQL Server? I've written this code and someone helped me out but I can't figure out what ''?'' means to the DB engine. It would really help me understand what I've written here.
 USE master
 EXEC sp_MSforeachdb 'use ? select ''?'', st.NAME, sc.NAME,
 sc.system_type_id, db_name()
 FROM sys.tables st
 INNER JOIN sys.columns sc ON st.object_id = sc.object_id
 WHERE (st.name LIKE ''rawp%'' or st.name like ''main'')'

I understand I'm searching all db in the instance for the name of the columns and their related tables but I need to understand how ''?'' fits into the Query. Thanks!

A: From http://weblogs.sqlteam.com/joew/archive/2008/08/27/60700.aspx

Notice that [?] is used as a placeholder for the heretofore unspecified database name

So the ? will be replaced with the database name.
Note that it is probably better to write it as
EXEC sp_MSforeachdb 'use [?] select ''?'', st.NAME, sc.NAME,

to support databases with "funny" names, like [Hello[] World'

A: The ? is a placehold for all database names when you use sp_MSforeachdb.  So when it loops through all databases, it replaces the ? with the actual database name in the specified ad hoc query you are calling the stored procedure with.
Note: it is not recommended to use this stored procedure.  Please see the following blog post on reasons why not to use sp_MSforeachdb.

A: This usually implies a prepared statement, Parameters are filled in later. (see http://en.wikipedia.org/wiki/Prepared_statements#Parameterized_statements). But here it is a placeholder for the database name

A: You may want to check out this question, which has the answer.
What does a question mark represent in SQL queries?

A: ? it is usually a placeholder for parameters that will be filled in later. See https://en.wikipedia.org/wiki/Prepared_statement#Parameterized_statements for more details.

A: sp_msforeachdb is kind of... special. And I mean partly in the "riding the short bus" sense of the word (and even that's not entirely fair here; my main complaint is that it's undocumented), but mostly I just mean that it's unique. This syntax is only used with sp_msforeachdb and sp_msforeachtable, and nowhere else in Sql Server itself.
What you should think of, though, is if you've ever written code that used an OLE or ODBC provider to do parameterized queries. Those tools use the ? character as a parameter placeholder. Something similar is going on here. The ? character is a parameter placeholder, where the value of the parameter will later be set to the name of each DB in your server, including master, tempdb, model, and msdb.
Try running this code to get a sense of how it works:
EXEC sp_MSforeachdb 'print ''?'' '

It's tempting to use this procedure for things like maintenance, reporting, and alerting scripts, but it's something you probably want to do only sparingly. Best not to rely on undocumented behavior. The sqlblog link posted first in another answer is the standard thinking on the subject.
Basically, there are likely no specific plans to retire or break this procedure (or other sp_* procedures), but there is also pretty much zero investment in moving these procedures forward from version to version. For example, the linked article indicates that sp_msforeachdb relies on the old dbo.sysdatabases rather than the more-correct sys.databases. I wouldn't expect Microsoft to target sp_msforeachdb directly, but if they ever decide to remove dbo.sysdatabases my expectation would be that their testing will discover that sp_msforeachdb is broken, at which time they'll also just remove sp_msforeachdb rather than fix it.


text:
Q: With Xcode 4.5.2, Clang compiler seems not to be SDK version dependent. Why? With Xcode 4.4 and earlier versions, each SDK used to have either a copy or a symlink to a Clang compiler available at
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/
    SDKs/iPhoneOS${IPHONE_SDKVERSION}.sdk/usr/bin/clang++

With Xcode 4.5.2, there is no Clang compiler at the path above. However, I found it at
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang

b) Why does it not depend on the SDK version anymore ?

A: It's because clang can compile for multiple architectures with a single (top-level) binary.  The previous gcc-based toolchains needed one gcc per arch.
See how to compile libcurl with arch armv7s under macosx? for examples of passing arch flags to clang.
Also, you can use xcrun to find your tools instead of hardcoding their locations.  For example, when cross compiling for iOS:
export CC=`xcrun --sdk iphoneos --find clang`


text:
Q: Why "PG::UndefinedColumn:" from a column who come from a gem? I've got a gem named Foo. In this gem I've got 2 branches : master and develop.
In my project I need to use the develop branch (which contain new migrations).
So in my gemfile I add :
gem "foo", git: "https://github.com/orsay/foo.git", branch: "develop"

Then run bundle install then re launch my server.
This is the error I get when I go on localhost:3000:

PG::UndefinedColumn: ERROR:  column my_added_column does not exist`

Why does it happen ? I should not need to import migrations from the gem...
When I run bundle show foo the code is correct.
Any idea please ? :)

A: Migrations defined in gems are not run when running rake db:migrate. Gems that wish to migrate the parent-app database should define a Rails Engine which will make a rake task available to install the gems migrations in the host app. For example, in your case (where the Gem is foo) that would be bundle exec rake foo:install:migrations. Your gem must be properly configured as a Rails engine to do this.
As an alternative to installing the migrations, you can use an initializer to automatically run the migrations in a required gem if you'd rather do that, but it's a bit more complex. There's more detail on that in Syncing Migrations


text:
Q: Not setting additional header parameter in angularjs XHR request without mannual refresh I am trying to send extra header in XHR request (init with $resource).Following is my config
var app = angular.module('app',['angularMoment']).
run(function ($rootScope,$location,$route, $timeout, $http) {
    var token = localStorage.getItem("userToken");
    $http.defaults.headers.common.token = token;
}

I am changing hash params (eg. after login process) to navigate in app. So when I am sending any XHR request after login process (wihout mannual reload), it's sending token (request header) as NULL. But when I reload my page manually it's working fine (i.e sending token as header). Also I tried with $route.reload() but it's not working.
Please suggest how can I get rid of this issue.
Thanks
EDIT :
After trying with follwing code :
app.factory('tokenInterceptorService', ['$q', '$location', function ($q, $location) {

var tokenInterceptor = {};

var request = function (config) {

    config.headers = config.headers || {};

    var token = localStorage.getItem("userToken");

    config.headers.token = token;

    return config;
}

// if response errors with 401 redirect to lgoin
var response = function (rejection) {
    if (rejection.status === 401) {
        $location.path('/');
    }
    return $q.reject(rejection);
}

tokenInterceptor.request = request;
tokenInterceptor.response = response;

return tokenInterceptor;
}]);

app.config(function ($httpProvider) {
$httpProvider.interceptors.push('tokenInterceptorService');
});

app.run(function ($rootScope, $location,$route, $timeout, $http) {

$rootScope.config = {};
$rootScope.config.app_url = $location.url();
$rootScope.config.app_path = $location.path();
$rootScope.layout = {};
$rootScope.layout.loading = false;

$rootScope.$on('$routeChangeStart', function () {
    //need to validate
    console.log($rootScope.isValidated + "app");

    //show loading
    $timeout(function(){
      $rootScope.layout.loading = true;
    });
});
$rootScope.$on('$routeChangeSuccess', function () {
    //hide loading
    $timeout(function(){
      $rootScope.layout.loading = false;
    }, 200);
});
$rootScope.$on('$routeChangeError', function () {

    alert('Something went wrong. Please refresh.');
    $rootScope.layout.loading = false;

});
})

It stop rendring the views in application with ".run" and trapping in $rootScope.$on('$routeChangeError', and giving the error Error: [$rootScope:inprog] $digest already in progress.

A: You need to set up an interceptor that alters every request sent to the server. You can find out more form the docs here, but essentially you need to set up a factory service on your app to add the token header like so:
app.factory('tokenInterceptorService', ['$q', '$location', 'localStorage', function ($q, $location, localStorage) {

    var tokenInterceptor = {};

    var request = function (config) {

        config.headers = config.headers || {};

        var token = localStorage.getItem("userToken");
        if (token) {
            config.headers.token = token;
        }

        return config;
    }

    // if response errors with 401 redirect to lgoin
    var response = function (rejection) {
        if (rejection.status === 401) {
            $location.path('/login');
        }
        return $q.reject(rejection);
    }

    tokenInterceptor.request = request;
    tokenInterceptor.response = response;

    return tokenInterceptor;
}]);

and then register it during the config stage with:
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('tokenInterceptorService');
});

A: module.run executes well before anything else in the app (but after module.config). Would the localStorage have been set by then? I think that is happening later, which is why you see this value after reloading the page.
An interceptor would be the way to go.
How are you setting the value in localStorage?
Fiddle

A: Since if I understand correctly your user token is always taken from localstorage, you can setup a watch on that localStorage key in your run function (Demo plunker for working with Localstorage in angular: http://plnkr.co/edit/7hP13JAjPybxkRuMZLZ0?p=preview )
angular.module('app',[]).run(['$rootScope', '$http', function($root, $http) {
    $root.$watch(function() {
          return localStorage.getItem('userToken');
    }, function(userToken) {
       $http.defaults.headers.common.token = userToken;
    });
});

This should solve your problems without any interceptors etc.
However I'd actually recommend using http interceptor as calls to localStorage are slow, or setting the defaults where you actually set the user token after login or logout (save it also on a scope variable, and initialize it in the run part like you do now).


text:
Q: PNG files in SO questions Can we prevent PNG files from being uploaded to SO?  Or at least suggest that they be pasted in as text and surrounded by braces?
It is very difficult for me to convert PNG data to usable XLS or TXT that can be used to duplicate the users problems.


text:
Q: trying to find which static port for NIS or NFS service in firewalld On our slave NIS server we have in /etc/sysconfig/network I've set
YPSERV_ARGS="-p 944"
YPXFRD_ARGS="-p 945"

and OTHER_YPBIND_OPTS="-p 3000" in /etc/ypbind.conf and YPPASSWDD_ARGS="--port 946" in  /etc/sysconfig/yppasswdd
But on the master server when running make -C /var/yp and debug enabled on firewalld the destination port (DPT) always changes. It's always UDP.
kernel: FINAL_REJECT: IN=eno3 OUT= MAC=00:0a:f7:e1:f8:6c:00:0a:f7:e1:d3:71:08:00 SRC=nis-slave DST=nis-master LEN=76 TOS=0x00 PREC=0x00 TTL=64 ID=59404 DF PROTO=UDP SPT=1003 DPT=676 LEN=56

Also in the new /etc/nfs.conf we have:
[lockd]
port=4002
udp-port=4002
[mountd]
port=4003
[nfsd]
port=2049
port=4001
outgoing-port=4004

And the logs in the slave server show: ypxfr_callback call: RPC: Unable to receive; errno = No route to host
Stopping firewalld and all is well. So what service is using UDP?

A: The ancient YP/NIS stuff is not at all firewall friendly. It literally predates the wide use of host firewalls. As you've noticed, it expects to be able to communicate on arbitrary ports. Most protocols from the last 20 years or so no longer do this, and run on predictable (or at least configurable) ports.
As a workaround, if you only have one IP address, though, you can just add it to the trusted zone in firewalld, and all traffic from that IP address will be allowed. (Sources can also be given by CIDR range or MAC address.)
 firewall-cmd --zone=trusted --add-source=10.193.35.1 [--permanent]

A: agree with the NIS being ancient, don't use it if you do not have to.
For NFS here is an example I am taking from SLES 11.4 /etc/sysconfig/nfs
Be aware things may be slightly different given the NFS version and linux distribution you are using.  But the port numbers you need to open in your firewall are at least MOUNTD_PORT and SM_NOTIFY_OPTIONS and STATD_PORT and LOCKD_TCPPORT and LOCKD_UDPPORT in addition to the ports for the NFS service which is typically 111 and 2049 for both TCP and UDP.
for custom_number_1 to custom_number_4 use something above 1024, anything below 1024 is reserved for privilege services.  You don't want to choose a number that conflicts with some other service obviously, the range 1024..9999 you can use but as personal preference i have mine set above 10,000.  The range >= 49152 is believe is the dynamic range which i don't think you should choose; what happens if you don't configure NFS (tell it what to use) then it choose them dynamically and it would be some port number >= 49152 and would be different each time because it's dynamic... and why you would have problems because the firewall would be blocking all those ports and you would never know what they would be because of the NFS choosing them dynamically.
that dynamic choosing of port numbers, that you describe for NIS, same deal; the service was not fully configured so things that were left blank or default or chosen dynamically = different each time = no way to properly configure or use a firewall.
## Path:        Network/File systems/NFS server
## Description: number of threads for kernel nfs server
## Type:        integer
## Default:     4
## ServiceRestart:  nfsserver
#
# the kernel nfs-server supports multiple server threads
#
USE_KERNEL_NFSD_NUMBER="4"

## Path:        Network/File systems/NFS server
## Description:     use fixed port number for mountd
## Type:        integer
## Default:     ""
## ServiceRestart:  nfsserver
#
#  Only set this if you want to start mountd on a fixed
#  port instead of the port assigned by rpc. Only for use
#  to export nfs-filesystems through firewalls.
#
MOUNTD_PORT="custom_number_1"

## Path:                Network/File systems/NFS server
## Description:         GSS security for NFS
## Type:                yesno
## Default:             yes
## ServiceRestart:      nfs nfsserver
#
# Enable RPCSEC_GSS security for NFS (yes/no)
#
NFS_SECURITY_GSS="no"

## Path:                Network/File systems/NFS server
## Description:         NFSv4 protocol support
## Type:                yesno
## Default:             yes
## ServiceRestart:      nfs nfsserver
#
# Enable NFSv4 support (yes/no)
#
NFS4_SUPPORT="no"

## Path:                Network/File systems/NFS server
## Description:         NFSv4 server minor version
## Type:                integer
## Default:             0
## ServiceRestart:      nfsserver
#
# Select NFSv4 minor version for server to support (0, 1).
# If '1' is selected, both NFSv4.0 and NFSv4.1 will be supported.
NFS4_SERVER_MINOR_VERSION="0"

## Path:                Network/File systems/NFS server
## Description:         Network Status Monitor options
## Type:                string
## Default:             ""
#
# If a fixed port should be used to send reboot notification
# messages to other systems, that port should be given
# here as "-p portnumber".
#
SM_NOTIFY_OPTIONS="-p custom_number_2"

## Path:                Network/File systems/NFS server
## Description:         Always start NFS services
## Type:                yesno
## Default:             no
## ServiceRestart       nfs
#
# Always start NFS services (gssd, idmapd), not only if
# there are nfs mounts in /etc/fstab.  This is likely to be
# needed if you use an automounter for NFS.
#
NFS_START_SERVICES=""

## Path:                Network/File systems/NFS server
## Description:         Port rpc.statd should listen on
## Type:                integer
## Default:             ""
## ServiceRestart:      nfsserver
#
# Statd will normally choose a random port to listen on and
# SuSE-Firewall is able to detect which port and allow for it.
# If you have another firewall, you may want to set a fixed
# port number which can then be opened in that firewall.
STATD_PORT="custom_number_3"

## Path:                Network/File systems/NFS server
## Description:         Hostname used by rpc.statd
## Type:                string
## Default:             ""
## ServiceRestart:      nfsserver
#
# statd will normally use the system hostname in status
# monitoring conversations with other hosts.  If a different
# host name should be used, as can be useful with fail-over
# configurations, that name should be given here.
#
STATD_HOSTNAME=""

## Path:                Network/File systems/NFS server
## Description:     TCP Port that lockd should listen on
## Type:                integer
## Default:             ""
## ServiceRestart:      nfsserver
#
# Lockd will normally choose a random port to listen on and
# SuSE-Firewall is able to detect which port and allow for it.
# If you have another firewall, you may want to set a fixed
# port number which can then be opened in that firewall.
# lockd opens a UDP and a TCP port.  This setting only affect
# the TCP port.
LOCKD_TCPPORT="custom_number_4"

## Path:                Network/File systems/NFS server
## Description:     UDP Port that lockd should listen on
## Type:                integer
## Default:             ""
## ServiceRestart:      nfsserver
#
# Lockd will normally choose a random port to listen on and
# SuSE-Firewall is able to detect which port and allow for it.
# If you have another firewall, you may want to set a fixed
# port number which can then be opened in that firewall.
# lockd opens a UDP and a TCP port.  This setting only affect
# the UDP port.
LOCKD_UDPPORT="custom_number_4"

## Path:                Network/File systems/NFS server
## Description:         Lease time for NFSv4 leases
## Type:                integer
## Default:             ""
#
# Set the lease time for the NFSv4 server.  This allows new locks
# to be taken sooner after a server restart, so it is useful for
# servers which need to recover quickly after a failure, particularly
# in fail-over configurations.  Reducing the lease time can be a
# problem is some clients connect over high latency networks.
# The default is 90 seconds.  A number like 15 might be appropriate
# in a fail-over configuration with all clients on well connected
# low latency links.
NFSV4LEASETIME=""

## Path:                Network/File systems/NFS server
## Description:         Alternate mount point for rpc_pipefs filesystem
## Type:                string
## Default:             ""
#
# In a high-availabilty configuration it is possible that /var/lib/nfs
# is redirected so some shared storage and so it is not convenient to
# mount the rpc_pipefs filesystem at /var/lib/nfs/rpc_pipefs.  In that
# case an alternate mount point can be given here.
RPC_PIPEFS_DIR=""

## Path:                Network/File systems/NFS server
## Description:         Options for svcgssd
## Type:                string
## Default:             ""
#
# Normally svcgssd does not require any option.  However in a
# high-availabilty configuration it can be useful to pass "-n"
# to guide the choice of default credential.  To allow for that
# case or any other requiring options ot svcgssd, they can
# be specified here.
SVCGSSD_OPTIONS=""

## Path:                Network/File systems/NFS server
## Description:         Extra options for nfsd
## Type:                string
## Default:             ""
#
# This setting allows extra options to be specified for NFSD, such as
# -H <shared_hostname> in a high-availability configuration.
NFSD_OPTIONS=""

## Path:                Network/File systems/NFS server
## Description:         Extra options for gssd
## Type:                string
## Default:             ""
#
# Normally gssd does not require any options.  In some circumstances,
# -n, -l or other options might be useful. See "man 8 rpc.gssd" for
# details.  Those options can be set here.
GSSD_OPTIONS=""

## Path:                Network/File systems/NFS server
## Description:         Extra options for mountd
## Type:                string
## Default:             ""
#
# Normally mountd does not require any options.  In some circumstances,
# -n, -t, -g or other options might be useful. See "man 8 rpc.mountd" for
# details.  Those options can be set here.
# -p or -N should be set using MOUNTD_PORT or NFS4_SUPPORT rather than
# this option.
MOUNTD_OPTIONS=""

## Path:                Network/File systems/NFS server
## Description:         Avoid DNS lookups for kerberos principal
## Type:                yesno
## Default:             no
## ServiceRestart:      gssd
#
# Avoid DNS lookups when determining kerberos identity
# of NFS server (yes/no)
# "yes" is safest, but "no" might be needed to preserve
# correct behaviour at sites that don't use
# Fully Qualified Domain Names when mounting NFS Shares.
#
NFS_GSSD_AVOID_DNS="no"


text:
Q: Secure Upload (SSL) a file in to Amazon S3 in c# Currently I am working on a MVC application, I want to upload a file(s) to amazon s3 using SSL from c#. (Sometimes i need to upload using SSL and some other times without SSL based on boolean value).
Thanks in Advance..

A: All S3 endpoints support both HTTP and HTTPS so it shouldn't be a problem to use either one, based on your use case.
You can see the full list of endpoints on:
http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region


text:
Q: (Strange ListView item transition when in second HubSection but not first For some reason, only the first item in a ListView in the second HubSection of a Hub control animates on entrance, but a ListView in the first HubSection animates as expected. You can replicate it like this:

*

*Open Visual Studio 2013 Update 2.

*Create a new blank windows store app.

*Open MainPage.xaml.

*Set the contents to this:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Hub Header="my app">
        <HubSection Header="section">
            <DataTemplate>
                <ListView>
                    <TextBlock>Hello</TextBlock>
                    <TextBlock>Hello</TextBlock>
                    <TextBlock>Hello</TextBlock>
                    <TextBlock>Hello</TextBlock>
                </ListView>
            </DataTemplate>
        </HubSection>
        <HubSection Header="section">
            <DataTemplate>
                <ListView>
                    <TextBlock>Hello</TextBlock>
                    <TextBlock>Hello</TextBlock>
                    <TextBlock>Hello</TextBlock>
                    <TextBlock>Hello</TextBlock>
                </ListView>
            </DataTemplate>
        </HubSection>
    </Hub>
</Grid>

*Run the app.
The first ListView animates in (slides left), but only the first item of the second ListView transitions in. How can I make the whole list transition in?
Here's a GIF screencast of what it looks like (I added an extra page with button on it to show the transition easily):


text:
Q: Fluxxor - how to dispatch an action in response to another? I feel like subtitling this question "Does Fluxxor want my application to work?". No doubt however I have not grasped how to co-operate with Fluxxor...
The error is:
Cannot dispatch an action ('NEXT_AJAX_REQUEST_IS_ABOUT_TO_BE_MADE') while another action ('FIRST_AJAX_REQUEST_IS_RETURNED') is being dispatched
Component A is the owner of Component B
Component A calls an action creator in its componentWillReceiveProps. This action creator makes an AJAX request. If successful we dispatch FIRST_AJAX_REQUEST_IS_RETURNED with some data into a store. The store updates. It emits change. Component A is listening for this change. Component A updates its state. Component A re-renders passing this state as props to Component B. Component B in its componentWillReceiveProps calls an action creator to make a second AJAX request based on the data it now has. Before the actual AJAX request is made the action creator dispatches NEXT_AJAX_REQUEST_IS_ABOUT_TO_BE_MADE - in order to put a store into a certain state.
I get the message about dispatching one action while another is in progress it seems because Fluxxor does not consider the first action complete  - even though I cannot have made the second until the AJAX request was completed and I have the data. The issue seems to be calling the second action from the componentWillReceiveProps method of a child component in response to changes in the owner component's state arising from the first action.
So. I tried moving the second action to the success 'callback' in the first store. I still get the same message. Even if this was the right thing to do...
The second action depends on data contained in the first action. I cannot merge these two into one single request/action and then update 2 stores using waitFor.

A: http://fluxxor.com/guides/react.html#batched-updates
This fixed it.
However I do not understand why and would really appreciate an explanation if anyone has it.
I think that the effect is that Component A will not re-render until state changes arising from getStateFromFlux have fully completed. So that when Component B calls its action creator we are now fully done with the first action.
Is this approximately correct?


text:
Q: Vectorization/optimising for loop with numpy in Python Im writing a script to handle some data from a sensor represented in the signal_gen function. As you can see in the testing function it is quite loop sentered. Since this function is called many times it makes it a bit slow and it would be lovely with a push in the right direction for optimising it.
I have read that it is possible to exchange the for loop with a vectorizatid array, but I can't get my head around how the i_avg[i] line should be written, since we have single element y[i] multiplied with the whole array x inside a np.cos, and all this is again just one irritation of i_avg.
def testing(signal):
    y = np.arange(0.0108, 0.0135, 0.001) # this one changes over time, set
    #to constant for easier reading
    x = np.arange(0, (len(signal)))
    I_avg = np.zeros(len(y))
    Q_avg = np.zeros_like(I_avg)
    for i in range(0, len(y)):
        I_avg[i] = np.array(signal * (np.cos(2 * np.pi * y[i] * x))).sum()
        Q_avg[i] = np.array(signal * (np.sin(2 * np.pi * y[i] * x))).sum()
    D = np.power(I_avg, 2) + np.power(Q_avg, 2)
    max_index = np.argmax(D)
    phaseOut = np.arctan2(Q_avg[max_index], I_avg[max_index])

#just a test signal
def signal_gen():
    signal = np.random.random(size=251)
    return signal

A: One vectorized approach using matrix-multiplication with numpy.dot to replace the nested loop to give us I_avg, Q_avg and also incorporating NumPy broadcasting and thus achieve a more efficient solution would be like so -
mult = 2*np.pi*y[:,None]*x
I_avg, Q_avg = np.cos(mult).dot(signal), np.sin(mult).dot(signal)

Please note that for the given sample, we are competing against a loopy version that only has to iterate for 3 iterations (y being of length 3). As such, we won't be seeing a huge speedup here.
Runtime test -
In [9]: #just a test signal
   ...: signal = np.random.random(size=251)
   ...: y = np.arange(0.0108, 0.0135, 0.001)
   ...: x = np.arange(0, (len(signal)))
   ...:

# Original approach
In [10]: %%timeit I_avg = np.zeros(len(y))
    ...: Q_avg = np.zeros_like(I_avg)
    ...: for i in range(0, len(y)):
    ...:     I_avg[i] = np.array(signal * (np.cos(2 * np.pi * y[i] * x))).sum()
    ...:     Q_avg[i] = np.array(signal * (np.sin(2 * np.pi * y[i] * x))).sum()
    ...:
10000 loops, best of 3: 68 µs per loop

# Proposed approach
In [11]: %%timeit mult = 2*np.pi*y[:,None]*x
    ...: I_avg, Q_avg = np.cos(mult).dot(signal), np.sin(mult).dot(signal)
    ...:
10000 loops, best of 3: 34.8 µs per loop

A: You can use np.einsum for broadcasting:
yx = 2*np.pi*np.einsum("i,j->ij", y, x)
I_avg = np.sin(yx) @ signal
Q_avg = np.cos(yx) @ signal


text:
Q: Zend Framework 2 Form Erros Default Decorators How to set default form errors decorators on ZF2 ? I want set custom class on error html how to do ?

A: There are no more decorators in ZF2. The thing you're looking at are called ViewHelpers. This is actually explained inside the official Documentation (even more than once).
This would be the code you're looking at:
/**
 * Example #1: Default options
 */
echo $this->formElementErrors($element);
//

Value is required and can't be empty

/**
 * Example #2: Add attributes to open format
 */
echo $this->formElementErrors($element, array('class' => 'help-inline'));
//

Value is required and can't be empty

/**
 * Example #3: Custom format
 */
echo $this->formElementErrors()
          ->setMessageOpenFormat('
')
          ->setMessageSeparatorString('

')
          ->setMessageCloseString('
')
          ->render($element);

This obviously is for a per-element basis.

A: As Sam said already, it would be the right way to write a new ViewHelper. But you could also call setMessageOpenFormat() in a Module.php file:
$serviceManager = $e->getApplication()->getServiceManager();
$viewHelperManager = $serviceManager->get('viewhelpermanager');
$formElementErrorsViewHelper = $viewHelperManager->get('FormElementErrors');
$formElementErrorsViewHelper->setMessageOpenFormat('

');
$formElementErrorsViewHelper->setMessageCloseString('

');


text:
Q: Make colab use the latest installation of a library I am trying to use the bleeding edge version of sklearn installing it from their github as shown on line 2 in the below image. Line 5 imports some functions from this version of sklearn. This line works in my local and not on Google Colab. Am I missing something to hint the tool to use the latest installed version and not its cached version?

A: I am not sure why that's happening but if you uninstall scikit-learn before installing the latest dev, it would work:
[1] !pip uninstall scikit-learn -y
Uninstalling scikit-learn-0.19.1:
  Successfully uninstalled scikit-learn-0.19.1

[2]!pip install Cython
   !pip install git+git://github.com/scikit-learn/scikit-learn.git
Requirement already satisfied: Cython in /usr/local/lib/python3.6/dist-packages (0.28.2)
Collecting git+git://github.com/scikit-learn/scikit-learn.git
  Cloning git://github.com/scikit-learn/scikit-learn.git to /tmp/pip-req-build-d59ukisw
Requirement already satisfied: numpy>=1.8.2 in /usr/local/lib/python3.6/dist-packages (from scikit-learn==0.20.dev0) (1.14.3)
Requirement already satisfied: scipy>=0.13.3 in /usr/local/lib/python3.6/dist-packages (from scikit-learn==0.20.dev0) (0.19.1)
Building wheels for collected packages: scikit-learn
  Running setup.py bdist_wheel for scikit-learn ... done
  Stored in directory: /tmp/pip-ephem-wheel-cache-is88dk15/wheels/a1/50/0e/316ef2ff8d4cfade292bd20b49efda94727688a153382745a6
Successfully built scikit-learn
Installing collected packages: scikit-learn
Successfully installed scikit-learn-0.20.dev0

[3] !pip freeze | grep scikit
scikit-image==0.13.1
scikit-learn==0.20.dev0

[4] from sklearn.preprocessing import CategoricalEncoder

[5] import sklearn
    sklearn.__version__
'0.20.dev0'


text:
Q: PHP Json Encoding Syntax I'm new to json and decided to use it because it looks promising. How does the syntax work?
Here is my simple php script:
$usernames = array('jake', 'john', 'jackie', 'jared');
$users = array();
for($i = 0; $i < 4; $i++)
{
    $users[$i]['id'] = $i;
    $users[$i]['name'] = $usernames[i];
}
$data = json_encode( $users );
echo $data;

It Outputs:
{"i":{"id":3,"name":null}}

I want it to output:
[{"id": 1,"name": "jake"},{"id": 2,"name": "john"},{"id": 3,"name": "jackie"},{"id": 4,"name": "jared"}]

A: Try to use:
$usernames = array('jake', 'john', 'jackie', 'jared');
$users = array();
foreach($usernames as $id => $username)
{
    $users[$id]['id'] = $id + 1;
    $users[$id]['name'] = $username;
}
$data = json_encode( $users );
echo $data;

A: Just one line inside the loop will do it
$usernames = array('jake', 'john', 'jackie', 'jared');
$users = array();
for($i = 0; $i < 4; $i++)
{
    $users[] = array("id"=>$i+1,"name"=>$usernames[$i]);

}
$data = json_encode( $users );
echo $data;

Output as you wanted in your question
[{"id":1,"name":"jake"},{"id":2,"name":"john"},{"id":3,"name":"jackie"},{"id":4,"name":"jared"}]

A: $usernames = array('jake', 'john', 'jackie', 'jared');
$users = array();
for($i = 0; $i < 4; $i++)
{
    $user=array();
    $user['id'] = $i;
    $user['name'] = $usernames[$i];
    $users[]=$user;
}
$data = json_encode( $users );
echo $data;

Output:
[{"id":0,"name":"jake"},{"id":1,"name":"john"},{"id":2,"name":"jackie"},{"id":3,"name":"jared"}]

A: Try this,
$usernames = array('jake', 'john', 'jackie', 'jared');
$users = array();
for($i = 0; $i < 4; $i++)
{
    $users[$i]['id'] = $i;
    $users[$i]['name'] = $usernames[$i];
}
$data = json_encode( $users );
echo $data;

Changed,
$usernames[i]

To,
$usernames[$i]

And I think its better using a foreach loop instead of for..

A: $usernames = array('jake', 'john', 'jackie', 'jared');

$users = array();

foreach($usernames as $id=>$username{
    $id++;
    $users[]=array('id'=>$id,'name'=>$username);
}

$data=json_encode($users);echo $data;


text:
Q: Click path tracking on a single page site I have a single page site that has a flash interface and a html nav bar that changes content on the site without a page reload. The problem is the client wants to see the click paths users are going though to access content ( using html nav bar or flash ui to get there ). I know I can use the externalInterface in flash to callback to javascript on click events but there seems to be no custom way to trigger building a click path.
Basically on a page that doesn't have per-page content I want to track the path users are navigating the site ( not per-click tracking but full on path tracking ) through. Is this possible through custom events of some sort or just not possible?

A: You can try GAVisual for Google Analytics, or other options as mentioned here:
click paths in logs or analytics?


text:
Q: How to export data from different mysql tables in one excel file in separate sheets in yii2 basic I am using Yii2 basic. I have 3 tables with the fields as,
ascteacherreport - ASCTeacherReportId,ASCId,UserId, DateofReport
ascteacherreportdetails - ASCReportDetailsId,ASCTeacherReportId, Time
ascteacherreporttimedetails - ASCTeacherReportTimeDetailsId, ASCReportDetailsId, StudentId ,Subject, Topic, Confidence
The relation between these 3 tables is as One ascteacherreport has many ascteacherreportdetails and One ascteacherreportdetails has many ascteacherreporttimedetails.
Now I am generating the data into excel using PHPExcel library. So the user creates the report for Date say 1st March for three hours like 11 to 12, 12 to 1 and 1 to 2.
And there are many student details for each hour(time) of each day. Say Student John for 11 to 12, 12 to 1 and 1 to 2. Similarly for student Nick for 11 to 12, 12 to 1 and 1 to 2  for 1st March.
Now each dates should be exported as new sheets in one excel file. And for each date sheet the particular time details and student details should be displayed. So for 1 st March there are time details for 2 hours like 11 to 12 and 12 to 1. Then the time should be displayed in 1st March sheet in Column C5 and D5.
Similarly for each time there are many student records. For 11 to 12 there are 3 student records then those student records should be displayed in 11 to 12 column.
I have a function actionExport in controller. The excel file gets downloaded and I can see the dates in different sheets coming but there is sheet Worksheet which should not be displayed.
The time is not displayed properly for each sheet
public function actionExport()
    {

    $objPHPExcel = new \PHPExcel();

    $date = \Yii::$app->db->createCommand('SELECT ASCTeacherReportId, ASCId, DateofReport from
                          ascteacherreport where UserId=:Id order by ASCTeacherReportId DESC')->bindValues([':Id'=>\Yii::$app->user->identity->getonlyid()])->queryAll();

    $timedetails = \Yii::$app->db->createCommand('SELECT Time from ascteacherreportdetailS,
             ascteacherreport WHERE ascteacherreport.ASCTeacherReportId=ascteacherreportdetails.ASCTeacherReportId AND
ascteacherreport.UserId=:id1')->bindValues([':id1'=>\Yii::$app->user->identity->getonlyid()])
               ->queryAll();

      foreach($date as $date1)
     {
         $objWorkSheet = $objPHPExcel->createSheet(0); //Setting index when creating

         $objWorkSheet->setTitle(''.$date1['DateofReport']);

          foreach($timedetails as $timedetails1)
        {
                 $row = 8;
                 $lastColumn = $objWorkSheet->getHighestColumn();
                 $lastColumn++;
                for ($column = 'C'; $column != $lastColumn; $column++)
                {
                     $objWorksheet->setCellValue($column.'8',''.$timedetails1['Time']);
                }
        }
}

ob_end_clean();

header('Content-type: application/.xlsx');
header('Content-Disposition: attachment; filename="report.xlsx"');
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');

}

Below is the excel file screenshot where dates are displayed in sheets. For each dates the time should be displayed in the respective sheets.
Export


text:
Q: Javascript onclick function does not display text assigned I am trying to display the text using javascript with the onclick function.
i) When I click on both button it only displays the red color , not the blue one.
ii) As well as, when I click on red button 1st time then it displays the red color and if I choose the red button again then it displays the blue color.

function myFunction() {

  if (document.getElementById("demo").value == "11") {
    document.getElementById("flight").innerHTML = "
Red Color
";
  }

  if (document.getElementById("demo").value == "22") {
    document.getElementById("flight").innerHTML = "
Blue Color
";
  }

}
<button id="demo" onclick="myFunction()" value="11">Red</button>
<button id="demo" onclick="myFunction()" value="22">Blue</button>

A: As you can see in the comments, an ID should be unique. Otherwise, it will screw up your JS.
I suggest you pass the current DOM element to your function, and use it like so:

function myFunction(elem) {
  switch(elem.getAttribute('value')) {
    case "11":
      document.getElementById("flight").innerHTML = "
Red
";
      break;
    case "22":
      document.getElementById("flight").innerHTML = "
Blue
";
      break;
  }
}
<button onclick="myFunction(this)" value="11">Red</button>
<button onclick="myFunction(this)" value="22">Blue</button>

A: Ids need to be unique in your document. The browser always only recognizes the first button with id flight and discards the id of the second for this reason.

Instead, you could solve the problem with multiple event handlers:

function displayRed() {
  document.getElementById("flight").innerHTML = "
Red Color
";
}

function displayBlue() {
  document.getElementById("flight").innerHTML = "
Blue Color
";
}
<button onclick="displayRed()" value="11">Red</button>
<button onclick="displayBlue()" value="22">Blue</button>

A: Try this :
Html :
<button onclick="myFunction(this)" value="11">Red</button>

<button onclick="myFunction(this)" value="22">Blue</button>

JavaScript :
function myFunction(x) {

if (x.value == "11")
 document.getElementById("flight").innerHTML = "
Red Color
";

else if (x.value == "22")
   document.getElementById("flight").innerHTML = "
Blue Color
";

}

Final code :

<!DOCTYPE html>

<button class="demo" onclick="myFunction(this)" value="11">Red</button>
<button class="demo" onclick="myFunction(this)" value="22">Blue</button>


text:
Q: Booting from USB/CD on Lenovo y510p I forgot my windows 7 password on a Lenovo y510p laptop. I'm trying to boot from CD, in order to reinstall the OS or boot from USB to reset the password. Both options fail because of EFI security policy -- EFI XXX has been blocked by the current security policy.

How do I solve this problem? I don't see any security policy related options in BIOS, to reset them.


text:
Q: LiDAR first and last returns eCognition Recently I downloaded the new version of eCognition Developer. Earlier in LiDAR data processing using algorithms, it was pretty easy to generate LiDAR first and last returns.
Before, when you chose the algorithm "LiDAR File Converter" there were options under the Converter Parameters such as "Convert Parameter" and "Returns". By setting the parameter "Returns", I could create two new image layers, i.e., LiDAR first and last returns.
Now with the new version, I don't know how to do that because there's no "Return" parameter listed anymore. I couldn't find any instructions either. How do I generate LiDAR's first and last returns in eCognition?


text:
Q: Most efficient way to hide all rows in which a certain value occurs The Excel auto filter is not properly working if there is more than one row for headings, and it is also not assignable to specific columns, only. So I want to filter by VBA macro.
I have

Sheet2.Range("A1:A40").Find(what:="Software", _
After:=Cells(4, 1), _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False _
).EntireRow.Hidden = True

But this only hides the row with the first occurance of "Software". Is there no way to use .find for that or do I have to use a loop?

A: If your range isn't super big, you can always loop through it, checking for a value, and hiding if found:
Sub test()
Application.ScreenUpdating = False
Dim lastRow As Integer, i As Integer
Dim rng As Range, cel As Range

lastRow = Sheet2.UsedRange.Rows.Count

For i = lastRow To 1 Step -1
  If Cells(i, 1).Value = "Software" or cells(i,1).Value = "software" Then
     Cells(i, 1).EntireRow.Hidden = True
  End If
Next i
Application.ScreenUpdating = True
End Sub

Note: the software part is case sensitive, which is why I used Or.


text:
Q: Unable to locate ntpd package I am trying to install ntp for my server. However, on running sudo apt-get install ntpd
i get the response Unable to locate package ntpd. I have run sudo apt-get update and the problem still remains

A: Install ntp server
Type the following command:
apt-get install ntp

A: Try the following sequence :
sudo apt-get update
then
sudo apt-get install ntp
will be succeeded...