text:
Q: "Could not load file or assembly SqlPackageBase" error when trying to query in SSMS I've just installed SSMS 17.2.  I'm connecting to a SQL Server DB using a VPN.  I can connect in fine, but when I click to query, I get the following error:

Could not load file or assembly 'SqlPackageBase, Version=14.100.0.0,
  Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its
  dependencies. The system cannot find the file specified.

I don't get the error when I connect to a local SQL Server instance so I'm guessing it has something to do with the VPN connection?
I did do a search of my hard drive for the "sqlpackagebase.dll" and find that it's in the SQL Server files.
Any ideas on how to fix this?


text:
Q: Using excel VBA to change format of headers/footers date and time in powerpoint I currently have the following set up. Everything is working fine, except .DateAndTime.Format is not changing the date format in the bottom left hand corner of the slide. The date is visible as 4/10/2020, but I can't get it to change to April 10, 2020 using the below:
  Set PowerPointApp = GetObject(class:="PowerPoint.Application")
  Set myPresentation = PowerPointApp.Presentations.Add
    myPresentation.ApplyTemplate "[template file here]"
  Const ppSlideSizeA4Paper = 2
    myPresentation.PageSetup.SlideSize = ppSlideSizeA4Paper
  With myPresentation.SlideMaster.HeadersFooters

    .SlideNumber.Visible = True
    .DateAndTime.Visible = True
    .DateAndTime.UseFormat = True
    .DateAndTime.Format = ppDateTimeMMMMdyyyy

  End With

A: I think you found a bug, because VBA won't change the date format on a master or its child layouts. It's possible to set on the slides:
Sub DateTime()
    Dim oSlide As Slide
    For Each oSlide In ActivePresentation.Slides
        With oSlide.HeadersFooters
            .SlideNumber.Visible = True
            With .DateAndTime
                .Format = ppDateTimeMMMMdyyyy
                .Visible = msoTrue
            End With
        End With
    Next oSlide
End Sub

However, when you insert a new slide, the date will still reflect the format set on the layout and you'll have to rerun the macro.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Apps Script Convert Positive into Negative Value When Pasting In Cell How do I make a positive value be converted automatically into negative without adding formula to a cell when someone pastes/or added a value to a cell.
In this example I want that 5 2 and 3 be a negative value.

A: In your situation, how about using the simple trigger of onEdit as follows?
Sample script:
Please copy and paste the following script to the script editor of Spreadsheet and save the script. When you use this script, please put a positive value to a cell. By this, the positive value is converted to the negative value.
function onEdit(e) {
  const value = e.range.getValue();
  if (!isNaN(value) && value > 0) {
    e.range.setValue(-value);
  }
}

Note:

*

*If you want to limit the sheet and the range, please tell me.

*If you want to convert all cell values in a sheet by a script, how about the following script? When this script is run, the positive values in a sheet are converted to negative values.
  function myFunction() {
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set your sheet name.
    const range = sheet.getDataRange();
    const values = range.getValues().map(r => r.map(c => !isNaN(c) && c > 0 ? -c : c));
    range.setValues(values);
  }

Reference:

*

*Simple Triggers
Added 1:
From your following additional request,

Is it possible to apply it with certain range only. Like to cell C45:AK76 and C84:AK115?

In this case, how about the following sample script?
Sample script:
function onEdit(e) {
  const ranges = ["C45:AK76", "C84:AK115"]; // These ranges are from your reply.
  const sheetName = "Sheet1"; // Please set your sheet name.

  const { range } = e;
  const sheet = range.getSheet();
  const value = range.getValue();
  const check = sheet.getRangeList(ranges).getRanges().some(r => {
    const startRow = r.getRow();
    const endRow = startRow + r.getNumRows() - 1;
    const startCol = r.getColumn();
    const endCol = startCol + r.getNumColumns() - 1;
    return range.rowStart >= startRow && range.rowEnd <= endRow && range.columnStart >= startCol && range.columnEnd <= endCol;
  });
  if (sheet.getSheetName() != sheetName || !check || isNaN(value) || value < 0) return;
  range.setValue(-value);
}

*

*In this sample, the script is run when the cells "C45:AK76", "C84:AK115" are edited.

Added 2:
From your following additional request,

Im wondering if I can apply this to two other sheets with the same cell range?

In this case, how about the following sample script?
Sample script:
function onEdit(e) {
  const ranges = ["C45:AK76", "C84:AK115"]; // These ranges are from your reply.
  const sheetNames = ["Sheet1", "Sheet2",,,]; // Please set your sheet names.

  const { range } = e;
  const sheet = range.getSheet();
  const value = range.getValue();
  const check = sheet.getRangeList(ranges).getRanges().some(r => {
    const startRow = r.getRow();
    const endRow = startRow + r.getNumRows() - 1;
    const startCol = r.getColumn();
    const endCol = startCol + r.getNumColumns() - 1;
    return range.rowStart >= startRow && range.rowEnd <= endRow && range.columnStart >= startCol && range.columnEnd <= endCol;
  });
  if (!sheetNames.includes(sheet.getSheetName()) || !check || isNaN(value) || value < 0) return;
  range.setValue(-value);
}

Added 3:
From your following additional request,

If I paste for example these 3 different values into the cell., example the number 4 5 and 6. Instead of just having -4,-5, and -6. The result I'm getting is -4,-4 and -4.

In this case, how about the following sample script?
Sample script:
function onEdit(e) {
  const ranges = ["C45:AK76", "C84:AK115"]; // These ranges are from your reply.
  const sheetNames = ["Sheet1", "Sheet2",,,]; // Please set your sheet names.

  const { range } = e;
  const sheet = range.getSheet();
  const values = range.getValues();
  const check = sheet.getRangeList(ranges).getRanges().some(r => {
    const startRow = r.getRow();
    const endRow = startRow + r.getNumRows() - 1;
    const startCol = r.getColumn();
    const endCol = startCol + r.getNumColumns() - 1;
    return range.rowStart >= startRow && range.rowEnd <= endRow && range.columnStart >= startCol && range.columnEnd <= endCol;
  });
  if (!sheetNames.includes(sheet.getSheetName()) || !check) return;
  range.setValues(values.map(r => r.map(c => (!isNaN(c) && c > 0) ? -c : c)));
}


text:
Q: Multi-Page vs Multi-PDF Loop problems I have a form that contains multiple partners that share a "pool". The partners are listed on a subform. After I'm done entering the information, I want a button to run a report for each of the partners with their specific information. But since it's multiple partners and I need one report for each (which I then want to email), I want to use a Loop to go through each of the partners.
EDIT1: Added entire code for review. I do have Option Explicit in and I have compiled it as well.
Private Sub btn_Run_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String

strSQL = "Select * FROM Cobind_qryReport WHERE PartPoolName = """ & Me.TopLvlPoolName & """"
Debug.Print "strSQL: " & strSQL

Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)

On Error GoTo Err_PO_Click

If MsgBox("Do you wish to issue the cobind invites?", vbYesNo + vbQuestion, "Confirmation Required") = vbYes Then
rs.MoveFirst
Do While rs.EOF = False
DoCmd.OutputTo acOutputReport, "Cobind_rptMain", acFormatPDF,_
   "K:\OB MS Admin\Postage\CoBind Opportunities\Sent Invites\" _
   & rs!CatCode & "_" & rs!PartPoolName "Cobind Invite_" & _
Format(Now(), "mmddyy") & ".pdf"
DoCmd.SendObject acSendReport, "Cobind_rptMain", acFormatPDF, ,_
, , " Cobind Invite", "Please find the cobind invite attached._
 Response is needed by " & [RSVP] & ". Thank you.", True
rs.MoveNext
Loop
End If

Exit_PO_Click:
MsgBox ("It didn't work")
rs.Close
Set rs = Nothing
Set db = Nothing
Exit Sub

Err_PO_Click:
MsgBox Err.Description
Resume Exit_PO_Click
End Sub

This should allow me to create a report for each record in my query, save it to my server, then open an email to send it out. Right now, it appears that the [PartPoolName] is hanging up the code because I'm getting a "Microsoft Office Access can't find the field "|" referred to in your expression." If I take out the [PartPoolName], it'll create a PDF with four pages (each page showing a partner), where I want to end up with four separate PDFs.

A: The first thing you should do is add Option Explicit to the Declarations section of your module.
Then, from the Visual Basic editor's main menu, select Debug->Compile [your project name here]
Fix all the problems the compiler complains about.  I suspect one of the compiler's first complaints may be triggered by this section of your code:
rs.MoveFirst

Do While Recordset.EOF = False

Do you have two recordset objects open, or one?
After you fix everything the compiler complains about, try your revised code.
If you get runtime errors, show us the exact error message and which code line is highlighted.
If the part of your code you haven't shown us includes an error hander, you can disable that error handler like so:
'On Error GoTo Err_PO_Click

Error handlers are great for production to shield users from errors.  However, during development you really need to be able to identify which code line causes the error.
Alternatively, you can leave your error handler active and select Tools->Options from the editor's main menu.  In the Options dialog, select the General tab, then select the "Break on All Errors" radio button and click OK.  You can switch that option back to "Break on Unhandled Errors" after you finish your testing.
Update: You wrote: Right now, it appears that the [PartPoolName] is hanging up the code because I'm getting a "Microsoft Office Access can't find the field "|" referred to in your expression."
What is [PartPoolName]?  If it's a field in the recordset, you can reference its value as rs!PartPoolName If it's something else, perhaps a global variable, give us more information about it.
Update2: Whenever your current code completes without error, you will hit this:
Exit_PO_Click:
MsgBox ("It didn't work")

Can that be right?
Update3: This OutputTo statement is your issue now, right?
DoCmd.OutputTo acOutputReport, "Cobind_rptMain", acFormatPDF,_
   "K:\OB MS Admin\Postage\CoBind Opportunities\Sent Invites\" & _
   "Cobind Invite_" & Format(Now(), "mmddyy") & ".pdf"

Cobind_rptMain is a report.  It has a RowSource for its data.  You're calling OutputTo with that report 4 times (once for each of the 4 rows in the recordset).  Yet you expect 4 different versions of that report ... a separate report for each PartPoolName value?

A: To finish off the fine work by HansUp visit a page on how to print a report for a single record and how to generate reports to attach to emails.  See the Emailing reports as attachments from Microsoft Access page.


text:
Q: Trying to validate a RegExp in Flutter I have a few reg expressions that work on dart but this one for some reason always returns false. I'm trying to validate an ID, code below
 if (RegExp(r'/^[0-9]{3}-[0-9]{4}-[0-9]{7}-[0-9]{1}$/').hasMatch('123-1234-1234567-1')) {
              debugPrint('ID valid');
            } else {
              debugPrint('Invalid');
            }

A: Drop the slashes, regex delimiters are not needed:
print(RegExp(r'^[0-9]{3}-[0-9]{4}-[0-9]{7}-[0-9]{1}$').hasMatch('123-1234-1234567-1'));

prints true.


text:
Q: How to set drop-down value in Angular I have a drop-down menu where I would like to set a value using some logic in my TS file. This is what my drop-down looks like:
 <select [(ngModel)]="selectedEntity" (change)="onChange();">
     <option *ngFor="let item of Entities" [ngValue]="item.EntityID">{{item.EntityName}}</option>
 </select>

On change, I would like to check for a condition, and then set a value based on that condition. However, I'm stuck because I can't seem to get the drop-downs value to update in the view. I've tried to set the selectedEntity to a new value, but no success. How would I be able to set the selected value using the TS file?
Edit: For more clarity, I'm basically trying to confirm whether the selected choice is allowed for the current item in the Entities array. If it is allowed, select the option the user picked, if not, reset it to the previous value.

A: Try this out my friend, ngModelChange is the way to go. You can hook to the event.value to get access to your values
 <select [(ngModel)]="selectedEntity" (ngModelChange)="onChange($event)">
 <option *ngFor="let item of Entities" [ngValue]="item.EntityID">{{item.EntityName}}</option>

I made some changes to the stackblistz. On event you can hook to the value and use it
    onChange(event) {   if (event.id==1){
console.log("Value 1");
}
else if(event.id==2){
console.log("Value 2");
}
 else if(event.id==3){
console.log("Value 3");
}else{
  console.log("Update to Value 1");
} }

A: event handler registered in ngModelChange will be fired before the value of model changes.
You have to pass event with change's event handler. You can try
   (change)="onChange($event);"

Code
    <select [(ngModel)]="selectedEntity" (change)="onChange($event);">
       <option *ngFor="let food of foods" [ngValue]="food.name">{{food.name}}</option>
     </select>

TS File
    onChange(event:any){
        console.log(this.selectedEntity)
    }


text:
Q: Enable Javascript in WKWebView iOS 9 I was successfully using a WKWebView to load a url in iOS 8 using Xcode 6.4. I've upgraded to Xcode 7 and now the my WKWebView does not have Javascript enabled any longer. How do I enable Javascript in my WebView again?

A: JavaScript is enabled by default. There is a javaScriptEnabled property on WKPreferences that you can flip to true in case some code has turned it off.
Are you sure that the problem you are seeing is related to JavaScript? Do you see any errors in the console? Did you implement the error/failure delegate methods to catch problems?
My gut feeling is that you are running into something different. For example a resource not loading because of the new App Transport Security requirements in iOS9.


text:
Q: How to do multiple python exercises in one file, so that previous code does not affect future code #write a program that prints out all the elements of
the list
# are less than 5
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
  89,6,5,3,2,1,7,9]
for x in a:
   if x < 5:
      print(x)

#Ask the user for a string and print out whether this
 string is a
# palindrome or not.

Print("Input a text!")
txt= input()
if txt == txt[::-1]:
  print("This is a palindrome")
else:
print("This is not a Palindrome")

What would I put so that the previous code doesn't affect the future code for these python exercises? am new to python :(

A: There are various ways to handle this. First, as mentioned in previous answers, you could use different variable names to isolate ( which would not be a good practice ). Second, create functions for each separate code fragment(I strongly suggest this) so you could make a respective function call when needed.

A: you could use functions to isolate the code, in such way you use local variables and not globals, because using global variables will influence other code, witch would be very difficult and counterproductive.


text:
Q: Find out how many arguments a block needs Let's say I have an array containing Blocks, and I need to assert that all of them expect a given number of arguments.
Is there a way to find this out programmatically?

A: This is indeed possible, for any recent version of Clang.
The Apple ABI for Blocks is private but also published. Since that document tells us the layout the compiler will use for a Block object, we can duplicate that information in a header file and use it to access the components of a Block.
Mike Ash's MABlockForwarding project does just that (see also the article) -- much of the stuff at the top of this file is a copy-paste from the ABI doc. The thing that he created which we are interested in is the BlockSig() function:
static const char *BlockSig(id blockObj)
{
    struct Block *block = (__bridge void *)blockObj;
    struct BlockDescriptor *descriptor = block->descriptor;

    assert(block->flags & BLOCK_HAS_SIGNATURE);

    int index = 0;
    if(block->flags & BLOCK_HAS_COPY_DISPOSE)
        index += 2;

    return descriptor->rest[index];
}

which will return (for Blocks that have it (which they all do with recent Clang)), a type encoding string describing the Block's return and argument types. From there, you can create an NSMethodSignature object, and ask it for its numberOfArguments:
 NSString * (^block)(int, NSArray *) = ^NSString * (int i, NSArray * a){
        return @"Oh, yeah!";
 };
 const char * types = BlockSig(block);
 NSMethodSignature * sig = [NSMethodSignature signatureWithObjCTypes:types];
 [sig numberOfArguments];

The result there is 3, because it includes a hidden argument for the Block itself (and Blocks don't use the hidden _cmd argument or it would be 4).

A: The answer is you cannot. See the comment on Mike Ash's page regarding this:
Search for Intropection which sends you here
So, what is your real problem? If you structure the arguments properly, you can insure that your system functions properly. For instance, you can do what C++ does with default values for arguments, and cast each block to a type that takes the max number of args, and always push that many items on the stack. Or you could always have the first argument be the number of arguments you are pushing on the stack. If you push objects and not numbers/pointers, then you r blocks can look at the class of each argument and dynamically adapt.


text:
Q: Flutter ChangeNotifierProxyProvider ChangeNotifier in create needs arguments I am in the process of programming my app and need to use a ChangeNotifierProxyProvider. Unfortunately my ChangeNotifier (in this case Entries) needs 3 positional arguments. I already managed to specify the arguments in update, but how can I do it in create?
I would be very happy about an answer, because I can't find anything on the internet.
Hey!
I am in the process of programming my app and need to use a ChangeNotifierProxyProvider. Unfortunately my ChangeNotifier (in this case Entries) needs 3 positional arguments. I already managed to specify the arguments in update, but how can I do it in create?
I would be very happy about an answer, because I can't find anything on the internet.
Here is my code for the providers: []:
providers: [
   ChangeNotifierProvider.value(value: Auth()),
   ChangeNotifierProxyProvider<Auth, Entries>(
      create: (_) => Entries(),
      update: (_, auth, previousEntries) => Entries(
        auth.token,
        auth.userId,
        previousEntries == null ? [] : previousEntries.items,
     ),
   ),
],

A: In this question ChangeNotifierProxyProvider not initiated on build the author did this:
return MultiProvider(
        providers: [
          ChangeNotifierProvider<WhatEver>(create: (context) => WhatEver()),
          ChangeNotifierProxyProvider<AuthProvider, ProductList>(
            create: (_) => ProductList(Provider.of<AuthProvider>(context, listen: false)),
            update: (_, auth, productList) => productList..reloadList(auth)
          ),
        ],

i.e. he used Provider.of to get the AuthProvider required by his ProductList. You could use a similar approach, but I expect it will need to be created in a parent context.
Note that the answer to the other question pointed out the need to use lazy: false. So here is your example:
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => AuthService(),
      builder: (context, _) => MultiProvider(
        providers: [
          ChangeNotifierProxyProvider<AuthService, Entries>(
            create: (_) =>
                Entries(Provider.of<AuthService>(context, listen: false).user),
            lazy: false,
            update: (_, auth, previousEntries) => Entries(
              auth.user,
            ),
          ),
        ],
        child: MaterialApp(

Obviously you no longer need to use MultiProvider, but it does not hurt.


text:
Q: Ember - data is nested n levels deep, want findBy in route to work from URL New to Ember (will be obvious), but I have an issue that I think others will run across while learnging. Basically I have incoming data that is a tree hierarchy of tags. The app basically represents a node of the tree by showing any children. Click a child, and the display is replaced with a list of their children and so on. Simple.
The problem comes when routing from the URL (manual refresh or whatever):
If a user were to type in the URL "#/tags/0", the application is able to find and serve the list of the children of tag with 'id' 0 (because it is top level, I assume). But if the user types in an URL with the id of a n-deep child, the findBy method fails to find the right node in the data.
Is there a recursive version of findBy or something like that?
Here's the relevant lines and some dummy data to illustrate what I mean about the hierarchy.
App.Router.map(function(){
    this.resource('tags', function () {
        this.resource('tag', { path: ':tag_id' });
    });
});

App.TagsRoute = Ember.Route.extend({
    model: function() {
        return tags;
    }
});

App.TagRoute = Ember.Route.extend({
    model: function(params) {
        return tags.findBy('id', params.tag_id);
    }
});

var tags = [{
                weight: "plus size3",
                untaggable: true,
                id: '0',
                label : "Existing Tags",
                children: [{
                        id: "2",
                        weight: "plus size7",
                        label: "take-out"
                    },
                    {   id: "3",
                        weight: "plus size9",
                        label: "busy environment"
                    },
                    {   id: "4",
                        weight: "minus size9",
                        label: "casual-attire environment"
                    },
                    {   id: "5",
                        weight: "minus size0",
                        label: "classical-crossover-music"
                    },
                    {   id: "6",
                        weight: "plus size0",
                        label: "knowledgeable"
                    },
                    {   id: "7",
                        weight: "plus size3",
                        label: "busy environment"
                    }
                ]
            },
            {
                untaggable: true,
                id: '1',
                weight: "minus size9",
                label: "Add More Tags",
                children: [{
                        untaggable: true,
                        id: '1111',
                        weight: "plus size9",
                        label: "interior",
                        children: [{
                            id: '8',
                            weight: "minus size9",
                            label: "modern",
                        },{
                            id: '9',
                            weight: "plus size3",
                            label: "classic",
                        },{
                            id: '10',
                            weight: "plus size3",
                            label: "dive",
                        }]
                    },{
                        untaggable: true,
                        id: '2222',
                        weight: "minus size9",
                        label: "exterior",
                        children: [{
                            id: '11',
                            weight: "minus size9",
                            label: "elegent exterior",
                            children: [{
                                id: '111',
                                weight: "minus size9",
                                label: "boroque exterior",
                            },{
                                id: '112',
                                weight: "plus size0",
                                label: "expensive exterior",
                            }]
                        },{
                            id: '12',
                            label: "dingy exterior",
                            children: [{
                                id: '121',
                                weight: "plus size0",
                                label: "shabby exterior",
                            },{
                                id: '122',
                                weight: "minus size6",
                                label: "dirty exterior",
                            }]
                        },{
                            id: '13',
                            weight: "plus size6",
                            label: "discrete exterior"
                        }]
                    },{
                        untaggable: true,
                        id: '3333',
                        weight: "minus size6",
                        label: "pricing",
                        children: [{
                            id: '14',
                            weight: "plus size3",
                            label: "$0-10 per person",
                        },{
                            id: '15',
                            weight: "minus size0",
                            label: "$10-20 per person",
                        },{
                            id: '16',
                            weight: "plus size9",
                            label: "$20-30 per person",
                        },{
                            id: '17',
                            weight: "minus size3",
                            label: "$30-40 per person",
                        },{
                            id: '18',
                            weight: "plus size9",
                            label: "$40-50 per person",
                        },{
                            id: '19',
                            weight: "minus size0",
                            label: "$50+ per person",
                        }]
                    },{
                        untaggable: true,
                        id: '4444',
                        weight: "plus size1",
                        label: "features",
                        children: [{
                            id: '20',
                            weight: "minus size0",
                            label: "beer-buckets"
                        },{
                            id: '21',
                            weight: "plus size8",
                            label: "big-screen-tv"},
                        {
                            id: '22',
                            weight: "zero size7",
                            label: "comedy"},
                        {
                            id: '23',
                            weight: "plus size9",
                            label: "drink-specials"},
                        {
                            id: '24',
                            weight: "zero size2",
                            label: "games",
                            children: [
                            {
                                id: '241',
                                weight: "minus size0",
                                label: "darts"},
                            {
                                id: '242',
                                weight: "plus size9",
                                label: "pool-table"}]},
                        {
                            id: '25',
                            weight: "plus size0",
                            label: "growlers"},
                        {
                            id: '26',
                            weight: "plus size3",
                            label: "happy-hour"},
                        {
                            id: '27',
                            weight: "minus size0",
                            label: "music"}]
                    },{
                        untaggable: true,
                        id: '5555',
                        weight: "plus size3",
                        label: "staff",
                        children: [{
                            id: '30',
                            weight: "minus size0",
                            label: "argumentative"},
                        {
                            id: '31',
                            weight: "plus size8",
                            label: "attentive"},
                        {
                            id: '32',
                            weight: "zero size5",
                            label: "available"},
                        {
                            id: '33',
                            weight: "plus size3",
                            label: "capable"},
                        {
                            id: '34',
                            weight: "minus size9",
                            label: "careless"},
                        {
                            id: '35',
                            weight: "plus size0",
                            label: "chatty"},
                        {
                            id: '36',
                            weight: "minus size6",
                            label: "cheerful"},
                        {
                            id: '37',
                            weight: "plus size3",
                            label: "competent"},
                        {
                            id: '38',
                            weight: "minus size0",
                            label: "considerate"},
                        {
                            id: '39',
                            weight: "minus size3",
                            label: "easy-going"},
                        {
                            id: '40',
                            weight: "plus size0",
                            label: "efficient"},
                        {
                            id: '41',
                            weight: "plus size3",
                            label: "engaging"},
                        {
                            id: '42',
                            weight: "plus size8",
                            label: "experienced"},
                        {
                            id: '43',
                            weight: "minus size1",
                            label: "friendly"}]
                }]
        }];

A: Unfortunately, there isn't a recursive version of findBy.  The "standard" way to handle something like this is to store your objects in a flat data structure: either a hash with object IDs as keys, or an array of objects.
Your tree of tags is a somewhat arbitrary/unique data structure, so you have two options:

*

*Represent your data in a more standard way, thereby allowing you to use the standard functions for arrays and objects.finder function.

*Keep your data in tree format, but write your own recursive

If you go with option 2, what you want is something like this:
function findTagById(tags, id) {
  var potentialMatch, match;

  for (var i = 0; i < tags.length; i++) {
    potentialMatch = tags[i];

    if (potentialMatch.id === id) {
      return potentialMatch;
    }

    if (potentialMatch.children) {
      match = findTagById(potentialMatch.children, id);

      if (match) {
        return match;
      }
    }
  }
}

In your example, the tag data is hard-coded into the app. However, in the real world, the vast majority of apps built using Ember consume data from received from a web server, usually via a JSON API. Ember Data has all sorts of customizable serializers responsible for taking potentially oddly-structured data received from the server and transforming it into individual models that can be included in a flat array. I recommend making use of Ember Data if you can.


text:
Q: WP Query. Ordering posts by another post types meta I have a custom post type called BID which contains a users bid (similar to freelancer.com, upwork, etc) However I need the BID results on the page to be ordered by meta stored in a users profile, which is a custom post type PROFILE.
How would I go about doing this?
Here is my current Query
new WP_Query( array(    'post_type' => BID,

                        'post_parent' => get_the_ID(),

                        'posts_per_page' => 20,

                        'post_status' => array('publish','complete', 'accept', 'unaccept')

                            )

               );


text:
Q: Regular expression to extract dimensions from a string like '2" (7cm) high, 3" (9cm) long and 2" (7cm) wide' I am trying to extract the physical dimensions of items in a dataset from an unformatted string description. There are quite a few different ways they are expressed in the string. Here are some examples:
2" (7cm) high, 3" (9cm) long and 2" (7cm) wide
7" (20cm) high, 5" (15cm) wide and 5" (13cm) deep
4" high, 7" wide and 5" deep
6 inches high, 17 inches wide, and 6 inches deep

I am trying to extract them in the most elegant way possible using just a single regular expression for each dimension, ideally, but I can't seem to wrap my head around how to do it and I don't even know where to start, really. I am using a pandas DataFrame and the extract() method, if that makes a difference. Here is what I have so far:
r'(?P<height_cm>\d+)cm\) high'
r'?P<width_cm>\d+)cm\) wide'
r'(?P<length_cm>\d+)cm\) [deep|long]'

But this obviously only captures the cm numbers. How can I also capture the inches if present? And how can I use either the inch symbol or the word inches so that they both match?
Any help would be greatly appreciated.

A: Following examples given (assuming deep and long are the same dimension):
(?:(?:((?:(?P<height_inch>\d+)(?:"| inches))(?: \((?P<height_cm>\d+)(?:\s?cm)\))? high)|((?:(?P<deep_inch>\d+)(?:"| inches))(?: \((?P<deep_cm>\d+)(?:\s?cm)\))? (?:deep|long))|((?:(?P<wide_inch>\d+)(?:"| inches))(?: \((?P<wide_cm>\d+)(?:\s?cm)\))? wide)).*?)+

Edit: above regex updated to work with re.fullmatch and Series.str.extractall
This one might be simpler to work with:
((?:(?P<inch>\d+)(?:"| inches))(?: \((?P<cm>\d+)(?:\s?cm)\))? (?P<side>high|wide|deep|long))

Also use with Series.str.extractall
On regex101

A: Note that these regular expressions will also match strings of the format x inches (ycm). I am assuming that's not a problem.
r'(?P<height_inches>\d+)(\"|\sinches)(\((P<height_cm>\d+)\scm\))?\shigh'
r'(?P<width_inches>\d+)(\"|\sinches)(\((P<width_cm>\d+)\scm\))?\swide'
r'(?P<length_inches>\d+)(\"|\sinches)(\((P<length_cm>\d+)\scm\))?\s(deep|long)'


text:
Q: Perpendicular vectors in $\Bbb R^3$ Hi I am struggling with this simple question. Let $\vec{v}$ be a unit vector in $\Bbb R^3$.
How can I construct two periodic functions $\vec{x}(\theta)$ $\vec{y}(\theta)$
such that $\vec{v}$,  $\vec{x}(\theta)$ and  $\vec{y}(\theta)$ are all perpendicular to each other, for all $\theta\in R$ ?
pic: https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Euler_AxisAngle.png/800px-Euler_AxisAngle.png

A: Take $v=(v_1,v_2,v_3)^T$, take $x_0=(-v_2,v_1,0)$ and $y_0=v\times x_0$ and rotate
\begin{align}
x(\theta)&=R(\theta)x_0,\\
y(\theta)&=R(\theta)y_0
\end{align}
with Rodrigues' rotation matrix.


text:
Q: Ant fileset matching only files but excluding all sub directories How do I copy only files immediately under the directory and not its subdirectories? I don't know a priori the names of the files or the subdirectories.  I've tried the following to no avail:
<include name="*">  # includes all files and subdirs
===
<include name="*">
<exclude name="*/**> # or "*/" or "**"

Any help would be appreciated.
UPDATE:
I ended up just adding a delete task to delete the copied subdirectories:
<delete includeemptydirs="true">
    <fileset dir="${targetdir}">
        <type type="dir"/>
    </fileset>
</delete>

A: <?xml version="1.0" encoding="UTF-8"?>
<project default="copy-top-most-files-only" name="My Project">

    <property name="to.dir" value="/path/to/dest/folder/" />
    <property name="from.dir" value="/path/to/source/folder/" />

    <target name="copy-top-most-files-only">
        <copy todir="${to.dir}" includeEmptyDirs="false" >
            <fileset dir="${from.dir}">
                <exclude name="*/**/*" />
            </fileset>
        </copy>
    </target>
</project>

A: One way to do this is to specify a <depth> selector, for example:
<copy todir="dest">
    <fileset dir="src">
        <depth max="0" />
    </fileset>
</copy>

That will prevent subdirectories from being copied.
You can combine selectors with include/exclude rules if needed.


text:
Q: having issue connecting my mongodb to my nodejs app //in my .env file
MOVIEREVIEWS_DB_URI=mongodb+srv://driiisdev:password123@cluster1.ektx7.mongodb.net/sample_mflix?retryWrites=true&w=majority

PORT=8000 //starting port of server

//in my index.js file
import app from "./server.js"
import mongodb from "mongodb"
import dotenv from "dotenv"

dotenv.config();

const uri = process.env.MOVIEREVIEWS_DB_URI;

const client = new mongodb.MongoClient(uri);

const port = process.env.PORT||5000;

(async ()=>{

try{
    //Connect to the MongoDB cluster
    await client.connect();
    app.listen(port, ()=>{
        console.log("server is running on port:" +port);
    })
}catch(e){
    console.error(e);
    process.exit(1)
    }
})().catch(console.error);

//in my server.js file
import express from 'express'
import cors from 'cors'
import movies from './api/movies.route.js'

const app = express()
app.use(cors())
app.use(express.json())
app.use("/api/v1/movies", movies)

app.use('*', (req,res)=>{
    res.status(404).json({error:"not found"})
})

export default app

// on running nodemon server , the error i get:
Error: listen EACCES: permission denied 8000 //starting port of server
at Server.setupListenHandle [as _listen2] (node:net:1317:21)
at listenInCluster (node:net:1382:12)
at Server.listen (node:net:1480:5)
at Function.listen (C:\xampp\htdocs\driiisdev\movie-reviews\backend\node_modules\express\lib\application.js:635:24)
at main (file:///C:/xampp/htdocs/driiisdev/movie-reviews/backend/index.js:19:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1361:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EACCES',
errno: -4092,
syscall: 'listen',
address: '8000 //starting port of server',
port: -1
}


text:
Q: Main.exe producing no output? I am trying to learn SDL2 using c and gcc, so I copied this from a website (probably from 2011).
Problem
My code doesn't produce any output as soon.
For instance, in the code (right below this paragraph) the two printf() never do a thing.
The test(), which is supposed to create an empty SDL2 window is, too, not working.
Code
    #include <stdio.h>
    #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
    #define SDL_MAIN_HANDLED
    #endif
    #include <SDL2/SDL.h>

void test(){
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

        SDL_Window* window = NULL;

        if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
        {
            printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        }
        else
        {
            window = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
            if( window == NULL )
           {
                printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
            }

    }}

    int main(int argc,char* argv[]){
        printf("Test", "\n"); //Debug
        test();
        printf("Done", "\n"); //Debug
    }

Console Command
gcc -std=c11 main.c -IC:\Users\Utilisateur\Desktop\sdl2\SDL2-devel-2.0.18-mingw\SDL2-2.0.18\i686-w64-mingw32\include -LC:\Users\Utilisateur\Desktop\sdl2\SDL2-devel-2.0.18-mingw\SDL2-2.0.18\i686-w64-mingw32\lib -Wall -lmingw32 -lSDL2main -lSDL2
a.exe

What I tried
I completely removed any reference to test(), which fixed the problem(I saw my output again).
But its still a problem; I need my test()
Conclusion
Although it may be obvious now, I would like it to work, and so I wrote this stack overflow question hoping that someone explains me what have I done wrong.


text:
Q: How to set jshint/jsxhint "esnext" option in Atom I am using Atom's linter, react, and linter-jshint/linter-jsxhint.
In my JSX files, I keep getting the warning

Warning: 'import' is only available in ES6 (use esnext option). (W119)

That's pretty straightforward. I did some searching, and found that this can be set under the jshintConfig option in package.json (when using NPM). My project uses NPM and I have a package.json. I added:
"jshintConfig": {
  "esnext": true
}

After that, I did a reload but the warnings persist. I also modified my linter-jshint/linter-jsxhint config in Atom (config.cson) with:
"linter-jshint":
  harmony: true
  esnext: true

"linter-jsxhint":
  harmony: true
  esnext: true

And did a reload but that didn't help it either.
So: when using linter-jshint/linter-jsxhint as Atom packages, how to I set the esnext option?

A: You can create a .jshintrc in your project folder, it will be read by the linter as a json source file.
To use esnext option,
{
    "esnext": true
}

You will probably need to reopen your JS file to be able to see the new changes.

A: You can use the inline configuration adding this comment in your file .js:
/* jshint esversion: 6 */

http://jshint.com/docs/

A: First possibility, recommended : you can create a .jshintrc in you home directory and jshint will read it in case there is none in the project directory. You might need to restart Atom after.
Another possibility not recommended : you could also change the config of jshint in Atom and specify the location of your global .jshintrcif for some reason you don't want to put it in your home directory with the flag --config
'linter-jshint':
  'jshintExecutablePath': /path/to/jshint --config /path/to/.jshinrc

Run 'which jshint' to find the path.
It is not recommended because every other .jshinrc file (in the project, etc.) will be ignore:

jshint will look for this configuration in a number of locations, stopping at the first positive match:

*

*The location specified with the --config flag

*A file named package.json located in the current directory or any parent of the current directory (the configuration should be declared as the jshintConfig attribute of that file's JSON value)

*A file named .jshintrc located in the current directory or any parent of the current directory

*A file named .jshintrc located in the current user's "home" directory (where defined)


text:
Q: How to run a bot created with the help of QnA Maker on the local machine? (Please note that this FAQ bot is created without any coding with the help of Microsoft QnA Maker and then connecting it to Bot Framework).
I created a FAQ bot on Microsoft Bot Framework with the help of its "no-coding-required" QnA Maker and then registered it on Bot Framework. Now I need to insert Message Endpoint for bot to function. But I am not subscribing to Azure Bot Service or any other hosting service to host the bot as of now. I want to run it on my local Windows machine.
I downloaded Bot Framework Emulator and ran node.js http-server command to its folder, tunneled it with ngrok and put the resultant URL followed by /api/messages (like https://xxxxxxxx.ngrok.io/api/messages) for the message endpoint as well as in Botframework Emulator. But it didn't work. Ngrok gives an error as Bot is remote and tunneling is to my local machine, where software too is needed. But I haven't got the bot software code with me as QnA Maker apparently don't provide it for downloading. So what are the options before me to create a working endpoint for my bot?
Hope my query is clear, if not, please ask me to clarify further. TIA!

A: How do you want to use your QnA layer?
The QnA Maker page is automatically hosting (for free now but the are looking at the usage) the QnA functionality so you can integrate it in many ways:

*

*using a bot

*but also in a classic Asp.Net app

*or in many other project types

How?
To use your knowledge base, once you have set it up (and trained), the first step is to publishin https://qnamaker.ai/). You will got this kind of information:
Integration in a bot
You can use the QnA template: https://learn.microsoft.com/en-us/bot-framework/azure/azure-bot-service-template-question-and-answer
It will use a dedicated dialog type called QnAMakerDialog available through NuGet / npm:

For C#, the QnAMaker Dialog is distributed via the
Microsoft.Bot.Builder.CognitiveServices NuGet package.
For Node.js, the QnAMaker Dialog is distributed via the
botbuilder-cognitiveservices npm module.

Here is how you use your parameters from the publish phase: the QnASubscriptionKey and QnAKnowledgebaseId are used in the following sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.CognitiveServices.QnAMaker;

[Serializable]
public class BasicQnAMakerDialog : QnAMakerDialog
{
    //Parameters to QnAMakerService are:
    //Required: subscriptionKey, knowledgebaseId,
    //Optional: defaultMessage, scoreThreshold[Range 0.0 – 1.0]
    public BasicQnAMakerDialog() : base(new QnAMakerService(new QnAMakerAttribute(Utils.GetAppSetting("QnASubscriptionKey"), Utils.GetAppSetting("QnAKnowledgebaseId"), "No good match in FAQ.", 0.5)))
    {}
}

Directly in another projet
As QnA Maker is publishing your QnA knowledge base as a web API, you can directly use it from code with web calls. Here is the link to the API reference: https://qnamaker.ai/Documentation/ApiReference
If you have a look to the methods provided on the API list you will use Generate answer


text:
Q: Do you want a/one sandwich? I took an online English test, where a question was as follows:

Do you want ___ sandwich or two?
a) a
  b) one

I chose option "a" but it was incorrect. We usually say "do you want a sandwich?", then why was my option incorrect?

A: We use a/an before singular countable nouns like cat, dog, sandwich, etc.
However, we use one rather than a/an if we want to emphasize that we are talking about only one thing or person rather than two or more:

*

*Do you want one sandwich or two.

Therefore, the usage of one is correct here.
Similar examples are:
• Are you staying just one night.
• I just took one look at him and he started laughing.


text:
Q: using pure query on zend pagination so I've been using Zend Pagination, and I don't like the fact that I have to keep on using the Zend_DB_Select object to paginate things...
I want to just use a raw select query
"SELECT * FROM db etc etc"

and then pass that query into zend pagination without converting it to zend db select
is it possible to do so?

A: If you dislike Zend_DB_Select for your pagination, no-one stops you from writing what you want as your own Zend_Paginator_Adapter_Interface. See Zend Pagination Advanced Usage, but take care you do not reinvent the wheel.


text:
Q: setAutoScroll with QTreeView and custom model does not work I have made a QTreeView to display a very large and continuous data set. Since the data set is continuous, I delete initial rows when the total number of rows is greater than a specified amount.
I have used a custom model for this purpose
The whole system is working correctly and displaying data.
But I want it to autoscroll to the bottom to display latest data. If i use scrollToBottom at row addition it completely slows down the entire view-model. But If i use m_pTreeView->setAutoScroll at the start, it has not effect.
Moreover if i click on the view, it completely slows down.
I am using Qt 4.7.1
How should I auto scroll to the bottom without compromising on performance?
And show I remove the lag/drastic performance hit when I click on the view?
the whole code is available at this repo:
https://github.com/daniyalyasin93/qt_qtreeview_hugedata/


text:
Q: how to remove attribute from div using css in wordpress cms I use wordpress cms for an e-commerce site, on my shop page pagination is  not displayed and when I inspect element I see this

in inspection when I remove display:none from style attribute it work
I also tried this on shop page but it does not work
document.getElementByClassName('shop-loop-after').removeAttr('style')

I want to how to remove the display attribute using css

A: Given this HTML:

With JavaScript:
document.getElementsByClassName("item")[0].removeAttribute("style");

With CSS:
.item{
    display: inherit !important;
}

Examples:

document.getElementsByClassName("item")[0].removeAttribute("style");
.item{
     width: 300px;
     height: 300px;
     border: solid gray 3px;
     display: inherit !important;
}


text:
Q: Intercommunication between two .Net Applications using WCF service I have a WPF application. On the same machine I have a console application.From this console application i want to see if user has successfully logged in and a particular page is open in WPF application. If this is the case then i want to show a popup in WPF application.
To implement this I Thought of using WCF services. I have got 2 options. Create a seperate WCF service and run it as soon as WPF application runs and then ask the client application to communicate.
Second option is to host the WCF service inside the WPF application and run it when WPF application starts.
I am not able to decide on which way to choose. If anyone of u has implemented this kind of setup before,please share your ideas.

A: Because you want to see if a page is open in the WPF application, I'd suggest hosting the WCF service in the WPF application (i.e., using the ServicHost class). Then have the console application consume the service to determine the page status as per your requirement.
Also, use the NetNamedPipeBinding (http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx).


text:
Q: What is .foo(), .bar(), .baz() in python? as mentioned is below link Execute multiple python files using a single main
As of the solution in the below link, what is foo baz and bar in python programming and why it is used for?

A: It's a metasyntactic variable.
These names are often used as example variables. On python, ham, eggs and spam are used too.
Wikepedia says: https://en.wikipedia.org/wiki/Metasyntactic_variable


text:
Q: select columns that match designated number in excel HB  1   2   3   4
1   0   0   0   0
2   0   0   0   0
3   0   0   0   0
4   0   0   0   0
5   0   0   0   0
6   0   0   0.1 0
7   0   0   0   0
8   0   0   0   0

I have a table like this but with much larger number of columns and rows. I want to select columns and rows based on a set of numbers in another sheet shown below. Select the columns (and rows) if the first row (and first column) in the above table matches the number listed in the below table. And add the values for the selected intersection of columns and rows together.
ColumntoSelect
2
4
8
23

How to achieve that in excel? Thanks.

A: Using a SUMPRODUCT with a MATCH to tell which rows and columns are desired:
=SUMPRODUCT(ISNUMBER(MATCH($B$1:$X$1,$B$12:$B$15,0))*ISNUMBER(MATCH($A$2:$A$9,$D$12:$D$15,0))*$B$2:$X$9)


text:
Q: How to not cancel touch drag event inside ListView item? I'm implementing a swipe gesture similar to the one in Android Gmail app where you drag across an item to archive it.
I attach a touch listener to the item view and a gesture detector and listener to listen to touch events like this:
GestureDetector.OnGestureListener gl;
gl = new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) {
        // ... handle horizontal scrolling
        return true;
    }
};
final GestureDetector gd = new GestureDetector(getContext(), gl);
itemView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent e) {
        gd.onTouchEvent(e);
        // ... handle TOUCH_UP and TOUCH_CANCEL
        return true;
    }
});

The problem is that as soon as I start dragging vertically, or go outside the bounds of the item view, the gesture is cancelled and list view starts handling it for normal vertical list scrolling. I need the gesture to not cancel until the user releases the finger, even if it moves outside the table cell, like it's done in Gmail app.
How do I have it not cancelled?


text:
Q: adding hebrew value to sql using PDO I am trying to add a Hebrew value to a database using php's PDO class.
After finally succeeding doing that
(by using:  array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"), I found out that COLLATE HEBREW_CI_AS is added to my value.
Is there any way to prevent this addition?
thank you, and sorry for my bad English.

A: PHP: The Right Way is a good source of information on this.
Basically check whether your PDO-connection specifies the charset in the DSN:
new PDO(
    'mysql:host=your-hostname;dbname=your-db;charset=utf8',
    'your-username',
    'your-password',
    array(
        # ... PDO Connection Options
    )
);

Make sure your database tables are set to use the utf8-collation, either by phpmyadmin or using the mysql-command line utility and the following query:
ALTER TABLE table_name COLLATE utf8;

Also you might want to consider using utf8mb4 as is suggested in the book.


text:
Q: getting data from database in laravel using the username I have a table in database called 'User'. All I want is to get the basic information of the user. I've tried to get data from database but the thing that keep me bugging is that I get all the data inside the  table.
UserTable
|id|username|firstname|lasttname|middlename|gender|age|birthdate|address|contact_number|designation|
 1   admin    lee       chiu      kim        male  47   07-22-87  cebu     0977452445    admin
 2   lrose    rose       loo      mar       female 27   04-02-88  cebu     0977452445    manager
 3   mgray    gray       men      try        male  37   01-22-89  cebu     0977452445    employee

UserProfile.php --> Model
<?php
    class UserProfile  extends Eloquent   {
        public $timestamps=false;
        protected $table = 'users';
        protected $fillable=array('firstname','lastname', 'middlename', 'gender', 'age', 'birthdate', 'address', 'contact_number', 'designation');
    }

This is the model of my site.
UserProfileContoller.php --> Controller
<?php
class UserProfileController extends \BaseController {
    public function index($id)
    {
        $userprofile = User::find($id);

        return View::make('userprofile.index', array('userprofile' => $userprofile));

        //return View::make('userprofile.index')->with('UserProfiles',UserProfile::get());
    }

For example I am currently log in to username admin and I want to edit and view my profile. How can I get the data just for admin only. Please Help.
The situation hers is that. let say they have 3 employees. So in the table 3 username. lets assume that I'm not the admin. I will log in using lrose. and the other one log in as admin and so.on. If the three of us will go to our profiles the only thing to display there is their own profile and can edit it.

A: Assuming you property set-up your database why not just use the DB object?
 // In the User table find the item with the username 'admin'
 DB::table('User')->where('username', '=', 'admin')->get();

To get the information of some user that is logged in (given you have their username), called something like $userprofile. Then all we need to do is find by id then get the username:
 // $id is the ID of the logged in user
 $userprofile = User::find($id)->username; // get username of logged in user

A: $userprofile::find($id) will get you the information for admin only, if $id = 1.
find() only returns 1 tuple from the database.
After you call find(), you can access the data as such:
$userprofile->firstname

A: you mean when you pass $id to index method of User Controller all the data of other users are returned?
That's kinda weird.

*

*$userprofile = User::find($id); change that line to $userprofile = User::find(1); and see if you can only get the data of admin.

*If not, probably you are calling other method. Probably you iterate over the index method somewhere else for multiple times so that you get all the data in the database. To confirm both possibilities, just add echo 'I am in' at the entry point of your index method. If no echo message is shown, the first possibility is true. If multiple echo messages occur, the second possibility is true.

Hope this helps.

A: first of all, you need to use Session after login and store the id of the username in the Session.
e.g.
Step 1:
if($login) //successfull login
{
    Session::put('userid', $userid);
    //this id, you have to retreive it from the database after successful login
}

Step 2:
Setup the route
Route::get('profile',['uses' => 'UserProfileContoller@index']);

Step 3:
Controller
public function index()
{
     if(is_null(Session::get('userid'))) return Redirect::to('login');

     return View::make('userprofile.index', ['userprofile' => $this->model->index()]);
     // Above code uses dependency injection to retrieve the information from db.
}

Step 4:
UserProfileModel
public function index()
{
    return DB::table('user')->where('id','=', Session::get('userid'))->first();
}

p.s. i find it easier to use query builder than eloquent orm. if you want to use orm, change the code where needed.


text:
Q: infinite loop debug in VBA using .FindNext method I'm learning VBA and I stuck with a loop while using .FindNext method. I tried many ways to fix the loop but what ever I do I end up in an infinite loop, and you know how annoying this can be when you coding in excel. Please, if anyone can fix my code would be a great Help!
Private Sub cbGO_Click()

    Dim ws As Worksheet, OutputWs As Worksheet
    Dim rFound As Range
    Dim strName As String
    Dim count As Long, LastRow As Long
    Dim IsValueFound As Boolean

    IsValueFound = False
    Set OutputWs = Worksheets("Summary")    '---->change the sheet name as required
    LastRow = OutputWs.Cells(Rows.count, "A").End(xlUp).Row

    On Error Resume Next
    strName = ComboBox1.Value
    If strName = "" Then Exit Sub
    For Each ws In Worksheets

        If ws.Name <> "Lists" And ws.Name <> "Summary" Then

            With ws.UsedRange

                Set rFound = .Find(What:=strName, LookAt:=xlWhole)
                If Not rFound Is Nothing Then
                    firstAddress = rFound.Address

                    Do

                    rFound.EntireRow.Cells(1, "B").Resize(1, 4).Copy
                    OutputWs.Cells(LastRow + 1, 1).PasteSpecial xlPasteAll
                    Application.CutCopyMode = False
                    LastRow = LastRow + 1
                    Set rFound = .FindNext(rFound)

                    Loop While Not rFound Is Nothing And rFound.Address <> fristAddress

                End If
            End With
        End If
    Next ws
    On Error GoTo 0
    If IsValueFound Then
       OutputWs.Select
       MsgBox "Result pasted to Sheet Output"
    Else
        MsgBox "Value not found"
    End If

End Sub

A: you need to write "firstAddress", not "fristAddress". :D
Loop While Not rFound Is Nothing And rFound.Address <> fristAddress

After fixing this typo, it should work.
Another note: you are not setting IsValueFound to True yet.
Edit: oh ok, others were faster to spot it :)


text:
Q: How to set throttling on JMS proxy in WSO2 ESB 4.9.0 We are facing an issue with MQ JMS proxy in WSO2 ESB 4.9.0 when bulk messages are pilled up on Queue.
Back end services invoked by proxy can process only 50 requests per second and beyond that our back end services will fail.
The issue here is, when messages are pilled up on the Queue (1000messages), proxy is reading all the messages from the queue and sending to back end services & back end services are failing.
Is there any setting that we can set to on proxy to control message read by proxy service.
Here the main problem is proxy is very quick to read messages from Queue and flooding back end services. Back end services are failing because they are not designed to handle higher load

A: If you need to listen to a JMS queue and want to send messages to a backend service in a controlled manner, you have to use Message store and Message Processor.

A: You can define parameters in your proxy service :
<parameter name="transport.jms.ConcurrentConsumers">1</parameter>
<parameter name="transport.jms.MaxMessagesPerTask">1</parameter>
<parameter name="transport.jms.MaxConcurrentConsumers">1</parameter>

(adapt these values to your needs)
Furthermore, if you send a message to a back end service, you can choose to send it in a synchronous manner, using call mediator with blocking="true" : your proxy won't dequeue next jms message until it receive the response from your backend service.
If, on the other hand, you use send mediator, it's asynchronous : your mediation will continue while an other thread (callback) wait for the response and therefore, your proxy will dequeue next jms message

A: By setting below properties we can enable throttling or control the messages that are being sent to the backend.
Proxy level Throttling using JMS
<parameter name="jms.proxy.throttle.enabled">true</parameter> <parameter name="jms.proxy.throttle.limitPerMinute">3</parameter>


text:
Q: insert composite type array gives error postgresql 9.4-- CREATE TABLE people(
name_ varchar(50) NOT NULL,
count int NOT NULL DEFAULT 0
)

CREATE TABLE person_added(
date_ date NOT NULL,
all_people_ people[],
all_people_count int NOT NULL
)

CREATE TABLE all_people_array_table(
id SERIAL,
people_array person_added[]
)

INSERT INTO all_people_array_table(people_array) (SELECT ARRAY[CURRENT_DATE,  ARRAY[('Jack',3)::people,  ('John',6)::people], 1000]   )

I get this error;
ERROR:  ARRAY types date and emotions[] cannot be matched
What is the correct insert statement?

A: This works for me:
insert into all_people_array_table(people_array)
select array[
    (current_date,
     array[
        ('Jack',3)::people,
        ('John',6)::people
     ], 1)::person_added
];


text:
Q: ''don't/can't [verb] no...'' I have seen the following sentence: I can't get no satisfaction.
Can we say ''don't/can't [verb] no...''? I would like an explanation about this expression.

A: Grammatically it is wrong because we can't use negative form of the verb with no.
the correct form is in example below, but in lyrics and musics they don't care about grammar that much.
E1.I can get no satisfaction.
E2.I can't get any satisfaction.
for more info go to Grammarly.

A: The use of the double negative has come about in English in the  speech patterns of people for whom English is their second language. In many languages (re)iteration denotes emphasis and such is the intention here. The parsing becomes a problem for purists because the technically correct meaning of such a backward-spoken statement is the opposite of what the statement is intended to mean.


text:
Q: Put a variable as text on a button, when i click the button So I have a color randomizer for the button background color. I am trying to put the color that returns from the variable color and put it as text on the button. I also want this to happen on click.
Example:
I click on the button, a random color sets on the button background color. That color is #ff0000. I want the button to say something like:

"The background color of this button is x"

Where x is the exact color as the background, but in text.
Here is my js:
    function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color='#';
    for (var i = 0; i<6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;

}

function setRandomColor(){
    $("#buttonB").css("background-color", getRandomColor())

}

and here is what i have in html:
<div>
        <button id="buttonB" class="button" onclick="setRandomColor();">

        </button>
    </div>

I also have the jquery library to it.

A: take the result of getRandomColor(), and save it to a variable, and apply to both locations: the text, and the css.
This would change just the setRandomColor() function.
JS:
function setRandomColor(){
    var color = getRandomColor()
    $("#buttonB").css("background-color", color)
    $("#buttonB").html("Button color: "+color)
}

A: Try this
function setRandomColor(){
    var color = getRandomColor();
    $("#buttonB").css("background-color", color).html("The background color of this button is " + color);
}

A: You just need to take the color returned from your getRandomColor function and set it to the background and text of your button.
Like this:

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color='#';
    for (var i = 0; i<6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }

    return color;

}

function setRandomColor(){
    var color = getRandomColor();
    $("#buttonB").css("background-color", color );
    $("#buttonB").text("My color is " + color );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
      <button id="buttonB" class="button" onclick="setRandomColor();">
        Click me!
      </button>
  </div>

A: 1-Just change remove onclick attribute from <button> tag
<button id="buttonB" class="button">
     click to change
</button>

2- Add click event handler
$("#buttonB").on('click',function(){
    var new_color = getRandomColor();
    $(this).css("background-color", new_color);
    $(this).text('bg color: '+new_color);
});


text:
Q: datagrid freezing before bind I have a simple ASP.net page with an old datagrid. When a user clicks a button, a select statement runs and binds the data to the grid. The problem is after the page loads, the screen just hangs. There is only 1 record in the table.
ASP PAGE
<asp:Button ID="buttonclick" OnClick="clickit" runat="server" Text="GO" />

<asp:DataGrid ID="mygrid"  runat="server"
AutoGenerateColumns="true"></asp:DataGrid>

CODE BEHIND
  public void clickit(Object sender, EventArgs e)
    {
         string sql = "SELECT a from table1";
        SqlConnection connection = new SqlConnection(connectionstring);
        SqlDataAdapter adap= new SqlDataAdapter(sql, connection);
        DataTable table = new DataTable();
        connection.Open();
        adap.Fill(table); //page reloads here, but hangs
        mygrid.DataSource = table;
       connection.Close();
   }

A: I have refactored your code , now it should work.
public void clickit(Object sender, EventArgs e)
{
    //call the function
    this.bindGrid();
}

 //function to populate the datagrid with the data from the datasource
   private void bindGrid()
   {
    string sql = "SELECT a from table1";
    SqlConnection connection = new SqlConnection(connectionstring);
    SqlDataAdapter adap= new SqlDataAdapter(sql, connection);
    DataTable table = new DataTable();
    connection.Open();
    adap.Fill(table); //page reloads here, but hangs
    mygrid.DataSource = table;
    //bind the control with the data in the datasource
    mygrid.DataBind();
   connection.Close();
   }

A: Do you need to call mygrid.DataBind() after assigning the DataSource? It might not be hanging. It's probably just not displaying the grid with the data bind.


text:
Q: fillna() method's behavior in Pandas -- does not obey to inplace argument - returns error on axis 1 I am experimenting with the fillna() method.  I have created a small dataframe and two Series for that purpose:
        col1    col2    col3      col4
     0  NaN      NaN    3           4
     1  NaN      NaN    7           8
     2  9.0     10.0    11         12

     n1 = pd.Series([10, 20])
     n2 = pd.Series([30, 40, 50, 60])
     n2.index = list(df.columns.values)

When I try the command:
    df.fillna(n1, axis=0, inplace = True)

Nothing happens, the NaNs remain intact.  I would expect to see them replaced with the values 10 (col1) and 20 (col2).
When I try
    df.fillna(n2, axis =1)

I get an error message:
   NotImplementedError: Currently only can fill with dict/Series column by column

Could you explain this behavior?  Your advice will be appreciated.

A: fillna (like many other methods in pandas) isn't inplace by default. You need to either pass inplace=True or reassign its return value.
df.fillna(n1, axis=0, inplace=True)

or
df = df.fillna(n1, axis=0)

In such cases it helps to read the docs:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html

inplace : boolean, default False.
  If True, fill in place. Note: this will modify any other views on this object, (e.g. a no-copy slice for a column in a DataFrame)
  .
  .
Returns: filled : DataFrame


text:
Q: Django ORM how to use datetime_trunc_sql I am trying to truncate a datetime field to a date and afterwards use that filed for aggregation operations. I managed to that with date_trunc_sql function like this:
truncate_date = con
inner_query = "mytable.datetime AT TIME ZONE '%s'" % 'Europe/Amsterdam'
truncate_date = conection.ops.date_trunc_sql('day', inner_query)
queryset = queryset.extra({'day': truncate_date})

Now i saw that there is also a function datetime_trunc_sql that takes the timeozone as paramater but could not make that work. I tried:
truncate_date = conection.ops.datetime_trunc_sql('day','mytable.datetime','Europe/Amsterdam')
queryset = queryset.extra({'day': truncate_date})

It fails with the error StopIteration at api/v3/... and closes the connection at the second line: queryset = queryset.extra({'day': truncate_date}) Any ideas why?
Thanks


text:
Q: Akka persistence of unprocessed messages In my application I have a service that sends email in response to various user events. There has been an ongoing issue whereby the email sending will fail for some reason so we drop the message and do not attempt to retry it. Included in this failure model is the JVM being shut down. The rules are that duplicate emails should not happen and that failing to send an email is highly undesirable but acceptable. Basically we should be able to retry without fear of duplicates.
Akko-Persistence would appear on the surface to solve the above problem however it seems geared towards storing all messages then replaying a subset of them to recover.
The desired behaviour is that any unprocessed messages (including the message being processed when a failure occurs) are replayed when the actor recovers. In addition if the system is bounced then any pending email are sent.
Is there some section of the Akka documentation I've missed or an easy way to accomplish the above?
For the record we're evaluating Akka 2.4.8 for this : http://doc.akka.io/docs/akka/2.4.8/

A: Exactly once delivery may be impossible to guarantee, but you can probably be close enough for this kind of use case.
If you get an exception or some kind of callback when sending fails and something that you can see as a certain acknowledgement that it succeeded you can do like this:
Give each mail a unique id and keep a persistent actor state which consists of mails in flight, only send the mail after persisting the fact that you are going to send it, when a mail has been confirmed to be sent, remove it from the in flight.
This will result in two domain events, something like MailSent and MailSendConfirmed, in the event log. After a restart when the actor replay completes you can resend mails that were inflight but not confirmed.
Of course if you want to take everything else that can fail with sending an email, then it will be much harder (send completing but mail bouncing because email address misspelled for example).


text:
Q: Excel VBA: Trouble pasting formats from table I have a few tables in different worksheets that I want to compile in another sheet, however I'm having trouble getting the formatting to paste across.
My current code is:
Sub Compiler()

Dim wbRaw As Workbook
Set wbRaw = ThisWorkbook
Dim wsCompiled As Worksheet
Set wsCompiled = wbRaw.Sheets("ALL PROGRAMMES COMPILED")
Dim wsACF As Worksheet
Set wsACF = wbRaw.Sheets("ACF")
Dim wsASPIRE As Worksheet
Set wsASPIRE = wbRaw.Sheets("ASPIRE")

Application.ScreenUpdating = False

wsCompiled.Cells.ClearContents

wsACF.Cells(1, 1).CurrentRegion.Copy

With wsCompiled
    .Range("A1").PasteSpecial xlPasteFormats
    .Range("A1").PasteSpecial xlPasteValues
End With

Application.CutCopyMode = False

wsASPIRE.Cells(1, 1).CurrentRegion.Offset(1).Copy

With wsCompiled
    .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
    .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
End With

Application.CutCopyMode = False

End Sub

The first table pastes across fine with the correct formatting, but the next table only pastes the values, with no formatting.
If I remove the offset from the copy line:
wsASPIRE.Cells(1, 1).CurrentRegion.Copy

The formatting pastes fine, but this then includes the headers from the second table which messes up the compiled data.
Can anyone explain why this happens and any suggestions how I can get around this?

A: I have not managed to find out why the formatting of tables does not paste across, however I figured out a workaround to the problem by looping through the tables in each worksheet and then unlisting them.:
Sub LoopTables()

Dim tbl As ListObject
Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        For Each tbl In ws.ListObjects
                 tbl.Unlist
        Next tbl
    Next ws

End Sub


text:
Q: Proving Deligne's formula If $A$ is a noetherian ring, $X = \text{Spec } A$, and $U = X - V(\mathfrak{a})$ for $\mathfrak{a}$ an ideal of $A$, then the following formula holds for any $A$-module $M$ (with associated $\mathcal{O}_X$-module $\tilde{M}$):
$$\Gamma(U,\tilde{M}) \cong \text{colim}_n \hom_A(\mathfrak{a}^n,M).$$
I've tried to prove this result by showing $\Gamma(U,\tilde{M})$ satisfies the required universal property. To that end, I defined a cocone to $\Gamma(U,\tilde{M})$ from the $\hom_A(\mathfrak{a}^n,M)$, taking
$$h_n: \hom_A(\mathfrak{a}^n,M) \to \Gamma(U,\tilde{M}), \quad h_n(f)(\mathfrak{p}) = \frac{f(x)}{x} \in M_\mathfrak{p},$$
where $\mathfrak{p} \in D(x) = V(x)^c$ for $x \in \mathfrak{a}^n$. It's easy to check that $h_n(f)$ is a well-defined section over $U$.
The next step is to show that for any other cocone $(C, \gamma_n)$, there is a unique mediating morphism $\theta: \Gamma(U,\tilde{M}) \to C$. Finding $\theta$ should depend on realising an arbitrary $g \in \Gamma(U,\tilde{M})$ as a value of some $h_n$, but this is where I've become stuck.
Are my maps $h_n$ wrong? If not, how to produce $g = h_n(f)$? Reductions so far: since $A$ is noetherian, $g$ can be represented as a tuple $\left ( \frac{m_1}{x_1^r}, \dots, \frac{m_k}{x_k^r} \right )$, where $m_i \in M$, the $x_i$ generate $\mathfrak{a}$, and $r$ is large.

A: Rodney Sharp and Markus Brodmann's contribution towards helping people to understand the Deligne isomorphism is Section 20.1 of the Second Edition of their book "Local cohomology" here, but see also 2.3.2.
Brodmann, M. P.; Sharp, R. Y. Local cohomology. An algebraic introduction with geometric applications. Second edition. Cambridge Studies in Advanced Mathematics, 136. Cambridge University Press, Cambridge, 2013. xxii+491 pp.
The family $(h_n)$ of maps you suggest is alright. This family implies a map$$h: D_\mathfrak{a}(M) \to \Gamma(U, \tilde{M})$$which is the inverse of the isomorphism $\nu_{\mathfrak{a}, M}$ of 20.1.14. You will recognize this, if you consider the local family $\delta$ on page 449. (Clearly, in your case, the situation is slightly simpler, as you consider the standard affine case, whereas the hypothesis 20.1.2 concern a more general situation.)
You are actually asking whether $h$ is surjective. To prove this, you will need the fact, that for each $g \in \Gamma(U, \tilde{M})$ there is some $n \in \mathbb{N}$ such that (in the notations used in 20.1.14) $\mathfrak{a}^n g \subseteq \mathrm{Im}(\varepsilon^U_M)$. In the more general setting of the standard hypotheses 20.1.2 this is shown in 20.1.10.

Can you elaborate on how exactly to use $\mathfrak{a}^n g \subseteq \text{Im}(\varepsilon_M^U)$? Clearly I'd like to use it to construct a map $f: \mathfrak{a}^n \to M$.

Let $g \in \Gamma(U, \tilde{M}) = \tilde{M}(U)$. Then by 20.1.10 there is some $k \in \mathbb{N}$ such that $\mathfrak{a}^kg \subseteq \varepsilon_M^U(M)$. By 2.1.8(iii) we have $\text{Ker}(\varepsilon_M^U) = \Gamma_\mathfrak{a}(M)$ and so, we may identify$$\varepsilon_M^U(M) = \overline{M} := M/\Gamma_\mathfrak{a}(M).$$There is a finitely generated $R$-submodule $N \subseteq M$ such that$$(N + \Gamma_\mathfrak{a}(M))/\Gamma_\mathfrak{a}(M) = \mathfrak{a}^k g\subseteq \overline{M}.$$By Artin-Rees, there is some $t \in \mathbb{N}$ such that $\mathfrak{a}^tN \cap \Gamma_\mathfrak{a}(M) = 0$. Set $n = k + t$. Then, we get$$\mathfrak{a}^ng = (\mathfrak{a}^t N + \Gamma_\mathfrak{a}(M))/\Gamma_\mathfrak{a}(M) = (\mathfrak{a}^tN)/(\mathfrak{a}^tN \cap \Gamma_\mathfrak{a}(M)) = (\mathfrak{a}^tN)/0 = \mathfrak{a}^tN \subseteq M.$$Hence we have a map$$f \in \text{Hom}_R(\mathfrak{a}^n, M), \quad x \mapsto f(x) := xg \quad(\forall x \in \mathfrak{a}^n).$$In your notations we get:$$h_n(f)_\mathfrak{p} := {{f(x)}\over x} = {{xg}\over x} = g_\mathfrak{p} \text{ for all }\mathfrak{p} \in U \text{ and all }x \in \mathfrak{a}^n \setminus \mathfrak{p}.$$This shows that $h_n(f) = g$.
You see, that my former hint was incomplete (which I was aware of), as I did not mention the equality $\text{Ker}(\varepsilon_M^U) = \Gamma_\mathfrak{a}(M)$ of 20.1.8(iii).
Here are a few additional hints for the reading of the proof of 20.1.10 in the ordinary affine case (with $S = R$ and $T = \text{Spec}(R)$). The arguments become slightly simpler than in the book, but they base on the same ideas. Do not forget, that the situation in the book covers much more, for example the case of (multi-)projective schemes $T$...
You represent $g$ by$$\left({{m_1}\over{s_1}}, \ldots, {{m_r}\over{s_r}}\right), \text{ with }s_1, \ldots, s_r \in \mathfrak{a} \text{ and }\bigcup_{i = 1}^r (\text{Spec}(R) \setminus \text{Var}((s_i))) = U$$so that for each $\mathfrak{p} \in U := \text{Spec}(R) \setminus \text{Var}(\mathfrak{a})$ there is an $i$ such that $s_i \ni \mathfrak{p}$ and moreover, if $s_i \ni \mathfrak{p}$, then it holds in $M_\mathfrak{p}$ that $g_\mathfrak{p} = {{m_i}\over{s_i}}$ (see 20.8.1(i)).
The essential point is to show that there is some $n \in \mathbb{N}$ such that$$s_i^ng \in \varepsilon_M^U(M) \text{ for all }i = 1, 2, \ldots, r.\tag*{$(*)$}$$This is shown in the first 12 lines on page 446, on use of 20.1.19. I suggest that you read this and the proof of 20.1.9 in the book and translate it step by step to your "classical" situation in which $S = R$ and $T = \text{Spec}(R)$. I suggest this, as this reading will face you with arguments which are of basic significance if you want to learn algebraic geometry.
Let $\mathfrak{b} := \sum_{i = 1}^r Rs_i^n$. Then by $(*)$ you get$$\mathfrak{b}g \subseteq \varepsilon_M^U(M).$$It is not hard to see, that $\text{Var}(\mathfrak{b}) \subseteq \text{Var}(\mathfrak{a})$ so that $\mathfrak{a}^k \subseteq \mathfrak{b}$ for some positive integer $k$ (cf. line 14 and 15 on page 446). Therefore $\mathfrak{a}^kg \in \varepsilon_M^U(M)$.


text:
Q: Flutter - Image persistence on the phone where I develop the app It is the first app I develop. I notice that I get a problem with image persistence on the phone where I develop the app. It looks like it doesn't really refresh the screen (When it opens a new screen, you can still see a faded version of the former screen, or some parts of it). It is a Samsung A21s.
Is this linked to the developing ? It doesn't seem to do the same thing on other apps that I use ? Or is it a problem with the phone ?
I bought it exclusively for the developing work.
Anyone has the same problem ?


text:
Q: Why does strtok with \n, only read the first line of the txt file? I have had some problems with strtok, I am trying, in my code in C, read from a text file, however, only the fist line is being read, because for some reason, the variable arq becomes NULL after first line.
the txt:
ola
oi
a
b
e
z

code:
void le_arquivo(char *optarg) {
    FILE *respostas;
    char *arq;
    char resp[SBUFF];
    char *tokens[SBUFF];
    int c = 0;

    respostas = fopen(optarg, "r");
    if (respostas == NULL) {
        printf("Erro ao abrir o arquivo\n");
        return;
    }
    fgets(resp, sizeof(resp), respostas);
    arq = strtok(resp, "\n");
    while (arq != NULL) {
        tokens[c] = arq;
        arq = strtok(NULL, "\n");
        c++;
    }
    fclose(respostas);
    organiza_dados(tokens, c);
}

A: strtok does not read from the file, it splits the character array. By definition fgets() reads a single line including the trailing newline if present in the file, so strtok() only splits a single item. Instead of fgets(), you should try and read the whole file with fread(), and null terminate the array before the strtok() loop:
#include <stdio.h>
#include <string.h>

void le_arquivo(char *optarg) {
    FILE *respostas;
    char *arq;
    char resp[SBUFF];
    char *tokens[SBUFF];
    int n, c;

    respostas = fopen(optarg, "r");
    if (respostas == NULL) {
        printf("Erro ao abrir o arquivo\n");
        return;
    }
    n = fread(resp, 1, sizeof(resp) - 1, respostas);
    resp[n] = '\0';
    arq = strtok(resp, "\n");
    for (c = 0; arq != NULL; c++) {
        tokens[c] = arq;
        arq = strtok(NULL, "\n");
    }
    fclose(respostas);
    organiza_dados(tokens, c);
}


text:
Q: Share files between azure pipeline Jobs In the documentation of the Azure pipelines, I read that:

Each agent can run only one job at a time. To run multiple jobs in
  parallel you must configure multiple agents.
When you run a pipeline on a self-hosted agent, by default, none of
  the sub-directories are cleaned in between two consecutive runs. As a
  result, you can do incremental builds and deployments, provided that
  tasks are implemented to make use of that. You can override this
  behavior using the workspace setting on the job.
Pipeline artifacts provide a way to share files between stages in a
  pipeline or between different pipelines. They are typically the output
  of a build process that needs to be consumed by another job or be
  deployed.

As a beginner, after reading this, I have some doubts:

*

*If I have 2 jobs (2nd job runs after the 1st) in an azure-pipelines.yaml, will both the jobs run in the same agent? Do different jobs in the same pipeline share the same workspace that can be referenced via the variable Pipeline.Workspace? ( It is clear that in the parallel job run case, it would need multiple agents).

*The 1st job generates some files in one step. Is it possible to consume those files in 2nd job without using artifacts (normally using artifacts, 1st job publishes the artifact and 2nd job downloads it)?

Can some please help me to clear these doubts?

A:
If I have 2 jobs (2nd job runs after the 1st) in an
  azure-pipelines.yaml, will both the jobs run in the same agent?

Strictly speaking, NO, neither UI nor YAML can achieve that.
As what you saw from the document: Each agent can run only one job at a time. Our design logic is, in theory, one job is an independent running individual, the communication between different jobs requires the use of "middleware", like variable, artifact and etc.

Do different jobs in the same pipeline share the same workspace that
  can be referenced via the variable Pipeline.Workspace?

Sample1:
I have 2 jobs in one pipeline, one is job01 and another is job02.
In job01, I create one json file into $(Pipeline.Workspace) names project.json:

In job02, print the files list that under path $(Pipeline.Workspace):

You can see, the second job could not access the output directory of first job.

BUT, there has one special case, that the pipeline is running with self-agent pool and only one agent exists in that pool.
At this time, they can run on same agent since there is only one agent in the pool. And, if you do not manually perform clean operation in the job definition, files can be shared between jobs in this special scenario because they are using a constant local path.
Sample2:
Same with previous sample, but this time change the running pool to the one that only contain 1 agent.

The 1st job generates some files in one step. Is it possible to
  consume those files in 2nd job without using artifacts

I think my above special case description and sample2 has answer this.
Yes, it possible. You can refer to that to achieve this demand. But, mostly we recommend you use artifacts to pass files between jobs.

A: If your agents are on-prem, you can use a network share. Add a pipeline variable:
SharePath = \\machine\automation\$(Build.BuildID)

Make sure the account running the agent has r/w access to the share. JobN can write or robocopy whatever it needs to the share, JobN+1 can read or copy it to continue work. On success, a final job should clean up any content from the share that doesn't need to hang around forever.
Also, if JobN+1 fails because the output from JobN was bad, (you of course will be fixing JobN, but in the meantime) you can fix the share output by hand and re-run JobN+1.


text:
Q: trace 0 implies product of symmetric and skew symmetric If $A$ is symmetric and $B$ is skew-symmetric, then
$tr(AB)=0$.
I would like to know if the converse holds true. If not, can you give me an example?

A: Let $C$ be any real nonsingular $3\times3$ matrix with a zero trace. Then $C$ is not a product of a square matrix (symmetric or not) and a skew-symmetric matrix, because every $3\times3$ skew-symmetric matrix is singular.


text:
Q: Android fragment illegalstateexception i searched and found custom listview's library and i try to use it (QuickReturnHeaderHelper)
in this library's example used activity and this library can load like this
QuickReturnHeaderHelper helper = new QuickReturnHeaderHelper(getActivity(),
            R.layout.activity_main, R.layout.header);
    View view = helper.createView();
    getActivity().setContentView(view);

but in my project i use fragment but i do not know how i can use this source code
    View rootView = inflater.inflate(R.layout.activity_main,
            container, false);
    QuickReturnHeaderHelper helper = new QuickReturnHeaderHelper(getActivity(),
            R.layout.activity_main, R.layout.header);
    View view = helper.createView();
    getActivity().setContentView(view);

i wrote my code like this but i can not recive result same as a  activity.
how i can change my code if anyone knows solution please help me
thanks

A: You should override onCreateView() of your Fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    QuickReturnHeaderHelper helper = new QuickReturnHeaderHelper(getActivity(),
        R.layout.activity_main, R.layout.header);
    return helper.createView();
}


text:
Q: How to send the email by using the google cloud functions without third party service I deployed a google cloud function with Python 3.7 and it is called by google cloud scheduler every day. Now I need a function to send the email with specific cases while running the cloud function.
However, I didn't find any API or modules for this service provided by proper GCP. Of course there are google partner services like SendGrid. But I don't want to use it. So If you have any idea to send the email with cloud function, could you give me some tips?

A: GCP does not offer a general email delivery service, so you will have to consider something else.
If you want to stay within Google, you could send through gmail, but that's not part of GCP at all, and your email will always appear to come from the Google account for which it's configured.


text:
Q: NotificationCompat difficulties in Koitlin I've been trying to follow
https://developer.android.com/training/notify-user/expanded
in order to create a media notification. My SDK target is 21+.
I got a basic notification working but when I got to doing the media one I've had this problem:
import android.support.v4.app.!NotificationCompat!
import android.support.v4.media.!app!.NotificationCompat as MediaNotificationCompat

The two exclamation marked items (NotificationCompat and app) turn red in the editor and I can't use them :(
What do I need to do to get to the media style?
Notes:
I have this implementation "com.android.support:support-compat:28.0.0" in my application build filee
It's underlined suggesting I move to androidx but I don't think that's an option?

A: I can't speak for where the old Android Support edition of NotificationCompat.MediaStyle might be hiding. In AndroidX, you can find it in the androidx.media:media artifact. Right now, the latest stable version is 1.1.0, so you can add:
implementation "androidx.media:media:1.1.0"

to your dependencies to pull that in.


text:
Q: MySQL Update SET replace with PHP mutiple queries I'm trying to run 3 lines of the same code as seen below.I've also tried the W3Schools PHP mysqli_multi_query() Function but it gives me a syntax error and only the 1-st line of code works the ExistingWord1
I also read a couple of stackoverflow posts about this and this can't figure it out
<?php
include 'words.php';
include('../config.php');
$servername = DB_HOSTNAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_DATABASE;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
/*UTF-8 format*/
$conn->set_charset("utf8");

$sql = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord1', '$ReplacerWord1') WHERE name LIKE '%$SearchWord1%';";
$sql = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord2', '$ReplacerWord2') WHERE name LIKE '%$SearchWord2%';";
$sql = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord3', '$ReplacerWord3') WHERE name LIKE '%$SearchWord3%';";

if ($conn->query($sql) === TRUE) {
    echo "Products updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

This is the full Code that i am trying to run as by itself it only runs the 1st $sql =""
and ignores the other 2
as for the variables in the REPLACE
$ExistingWord1 words that are in the database name
$ReplacerWord1  replaces the ExistingWord1
'%$SearchWord1%' real database names

Thanks for the help guys
Everyone in this post was really helpful i really do appriciate it.

A: Why not just nest the REPLACE functions, and get it done in one fell swoop.
  SET t.name = REPLACE(REPLACE(REPLACE( t.name, 'fee','bah'),'fi','hum'), 'fo','bug')

You don't really need a WHERE clause, if you're going to be scanning the whole table anyway.
 WHERE t.name LIKE '%fee%'
    OR t.name LIKE '%fi%'
    OR t.name LIKE '%fo%'

That's only going to require one scan through the table.
But this approach only "works" if you're not "swapping" keywords, and don't have collisions. (For example, first replacing "fee" with "foo" and the replacing  "foo" with "bar"... the order the operations is important.

NOTES:
The REPLACE function replaces strings, not words. This is important if you are planning on running this against text or comments.
Code that incorporate potentially unsafe values in SQL text is vulnerable SQL Injection.
Potentially unsafe values must be properly escaped using e.g. mysql_real_escape_string.
Or, the preferred pattern is to use prepared statements with bind placeholders.
Enabling multiquery opens up a whole host more opportunities for even nastier SQL injection; giving the ability to slide in whole statements, like DROP TABLE statements. Don't enable multiquery until you are positive your code isn't vulnerable.
FOLLOWUP
Preferred pattern is to use prepared statement with bind placeholders.
I'd prefer doing the replacement with one scan through the table, rather than three. The LIKE '%...' predicates in the WHERE clause aren't sargable, it's gonna be a full scan anyway.

$sql = "UPDATE product_description SET name = REPLACE(REPLACE(REPLACE(name,?,?)?,?)?,?)
         WHERE name LIKE CONCAT('%',?,'%')
            OR name LIKE CONCAT('%',?,'%')
            OR name LIKE CONCAT('%',?,'%') ";

$sth=$conn->prepare($sql);
$sth->bind_param("sssssssss",$ExistingWord1,$ReplacerWord1
                            ,$ExistingWord2,$ReplacerWord2
                            ,$ExistingWord3,$ReplacerWord3
                            ,$SearchWord1
                            ,$SearchWord2
                            ,$SearchWord3
                );

$sth->execute();

(Add appropriate error checking around the prepare and execute calls. With PDO, we'd use try/catch/finally blocks.)

A: According to the fragment provided only last $sql value will be executed, since you redefine same variable 3 times, only the last value stored in var $sql.
To fix that you can try:
$sql = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord1', '$ReplacerWord1') WHERE name LIKE '%$SearchWord1%';";
$sql .= "UPDATE product_description SET name = REPLACE(name, '$ExistingWord2', '$ReplacerWord2') WHERE name LIKE '%$SearchWord2%';";
$sql .= "UPDATE product_description SET name = REPLACE(name, '$ExistingWord3', '$ReplacerWord3') WHERE name LIKE '%$SearchWord3%';";

UPDATE So now you have just debug your query and code any preffered way. For example:
 $sql = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord1', '$ReplacerWord1') WHERE name LIKE '%$SearchWord1%';";
if ($conn->query($sql) === TRUE) {
    echo "1. Products updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
    $sql = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord2', '$ReplacerWord2') WHERE name LIKE '%$SearchWord2%';";
if ($conn->query($sql) === TRUE) {
    echo "2. Products updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

    $sql = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord3', '$ReplacerWord3') WHERE name LIKE '%$SearchWord3%';";

if ($conn->query($sql) === TRUE) {
    echo "3. Products updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

A: I don't know if this is the right way but upon reading your guys comments mainly @Alex's  comment
I changed the variables to
$sql = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord1', '$ReplacerWord1') WHERE name LIKE '%$SearchWord1%';";
$A = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord2', '$ReplacerWord2') WHERE name LIKE '%$SearchWord2%';";
$B = "UPDATE product_description SET name = REPLACE(name, '$ExistingWord3', '$ReplacerWord3') WHERE name LIKE '%$SearchWord3%';";

And added
if ($conn->query($sql) === TRUE) {
    echo "Everything worked as planned";
} else {
    echo "Error updating record: " . $conn->error;
}
if ($conn->query($A) === TRUE) {

} else {
    echo "Error updating record: " . $conn->error;
}
if ($conn->query($B) === TRUE) {

} else {
    echo "Error updating record: " . $conn->error;
}


text:
Q: JPA EntityGraph DISTINCT with Parameter results in cartesian product 2
I have an entity with 4 1:n relationships
@Entity
@Table(name="REPORT_MESSAGE")
@NamedEntityGraph(name=ReportMessage.GRAPH_ALL, attributeNodes= {@NamedAttributeNode("reportEvents"), @NamedAttributeNode("reportLabels"), @NamedAttributeNode("reportReceivers"), @NamedAttributeNode("reportSenders")})
public class ReportMessage implements Serializable {

    @Id
    @Column(name="REPORT_MESSAGE_ID")
    private Long reportMessageId;

    //bi-directional many-to-one association to ReportEvent
    @OneToMany(mappedBy="reportMessage")
    private List<ReportEvent> reportEvents;

    //bi-directional many-to-one association to ReportLabel
    @OneToMany(mappedBy="reportMessage")
    private Set<ReportLabel> reportLabels;

    //bi-directional many-to-one association to ReportReceiver
    @OneToMany(mappedBy="reportMessage")
    private Set<ReportReceiver> reportReceivers;

    //bi-directional many-to-one association to ReportSender
    @OneToMany(mappedBy="reportMessage")
    private Set<ReportSender> reportSenders;

I want to use the entity graph for eager fetching
@Override
public List<ReportMessage> findAllEagerly() {
    EntityGraph<?> graph = em.createEntityGraph(ReportMessage.GRAPH_ALL);
    List<ReportMessage> reportMessages = em.createQuery("SELECT DISTINCT r FROM ReportMessage r")
            .setHint("javax.persistence.loadgraph", graph)
            .getResultList();
    return reportMessages;
}

this method works like expected: I have 8 entries in the DB and it return 8 ReportMessage
However when I add a paremeter to the query I get back the cartesian product:
@Override
public List<ReportMessage> findForMessagidEagerly(String messageid) {
    EntityGraph<?> graph = em.createEntityGraph(ReportMessage.GRAPH_ALL);
    Query query = em.createQuery("SELECT DISTINCT r  FROM ReportMessage r WHERE r.messageid=:messageid")
            .setHint("javax.persistence.loadgraph", graph);
    query.setParameter(ReportMessage.PARAM_MSG_ID, messageid);
    List<ReportMessage> messages = query.getResultList();

    return messages;
    }

I expect to get back 1 ReportMessage but get 84. With a named query I get the same result. What's going on?

A: The problem was caused by the bidirectional relations. After changing to unidirectional relations the code works like expected.
However, does anybody know if I have a bug in my original code, or if this is a hibernate or not specified in JPA?