问:
Generating the Linux kernel .config file is making the source folder unclean
I am currently trying to rebuild a linux kernel, and I'm experimenting some difficulties.

I have modified the .config using make menuconfig.

```<code>...
make[1]: Entering directory '/home/doe/build/linux'
  CHK     include/config/kernel.release
  GEN     ./Makefile
  CHK     include/generated/uapi/linux/version.h
  CHK     include/generated/utsrelease.h
  Using /home/doe/workspace/linux as source for kernel
  /home/doe/workspace/linux is not clean, please run 'make mrproper'
  in the '/home/doe/workspace/linux' directory.
/home/doe/workspace/linux/Makefile:1027: recipe for target 'prepare3' failed
make[1]: *** [prepare3] Error 1
...
</code>```

Then I tried to run make mrproper. It works well and deletes my .config file from my build folder. Without surprise I cannot build because a .config file is missing.

I did a make defconfig followed by a make -j 8, just to try to build with some basic config file.

```<code>  ...
  HOSTCC  scripts/mod/file2alias.o
  HOSTLD  scripts/mod/modpost
  HOSTCC  arch/x86/tools/relocs_32.o
  HOSTCC  arch/x86/tools/relocs_64.o
  HOSTCC  arch/x86/tools/relocs_common.o
  Using /home/doe/workspace/linux as source for kernel
  /home/doe/workspace/linux is not clean, please run 'make mrproper'
  in the '/home/doe/workspace/linux' directory.
/home/doe/workspace/linux/Makefile:1027: recipe for target 'prepare3' failed
make[1]: *** [prepare3] Error 1
make[1]: *** Waiting for unfinished jobs....
  HOSTLD  arch/x86/tools/relocs
make[1]: *** wait: No child processes.  Stop.
Makefile:152: recipe for target 'sub-make' failed
make: *** [sub-make] Error 2
</code>```

How am I supposed to build if generating a .config makes the source folder unclean ?

答:
You should check whether the "include/config" directory  exists in your kernel source.

The prepare3 target checks the '.config' file and the 'include/config' directory. You could find this by searching "prepare3" in the Makefile

Body:
I am currently trying to rebuild a linux kernel, and I'm experimenting some difficulties.

I have modified the .config using make menuconfig.

...
make[1]: Entering directory '/home/doe/build/linux'
  CHK     include/config/kernel.release
  GEN     ./Makefile
  CHK     include/generated/uapi/linux/version.h
  CHK     include/generated/utsrelease.h
  Using /home/doe/workspace/linux as source for kernel
  /home/doe/workspace/linux is not clean, please run 'make mrproper'
  in the '/home/doe/workspace/linux' directory.
/home/doe/workspace/linux/Makefile:1027: recipe for target 'prepare3' failed
make[1]: *** [prepare3] Error 1
...

Then I tried to run make mrproper. It works well and deletes my .config file from my build folder. Without surprise I cannot build because a .config file is missing.

I did a make defconfig followed by a make -j 8, just to try to build with some basic config file.

  ...
  HOSTCC  scripts/mod/file2alias.o
  HOSTLD  scripts/mod/modpost
  HOSTCC  arch/x86/tools/relocs_32.o
  HOSTCC  arch/x86/tools/relocs_64.o
  HOSTCC  arch/x86/tools/relocs_common.o
  Using /home/doe/workspace/linux as source for kernel
  /home/doe/workspace/linux is not clean, please run 'make mrproper'
  in the '/home/doe/workspace/linux' directory.
/home/doe/workspace/linux/Makefile:1027: recipe for target 'prepare3' failed
make[1]: *** [prepare3] Error 1
make[1]: *** Waiting for unfinished jobs....
  HOSTLD  arch/x86/tools/relocs
make[1]: *** wait: No child processes.  Stop.
Makefile:152: recipe for target 'sub-make' failed
make: *** [sub-make] Error 2

How am I supposed to build if generating a .config makes the source folder unclean ?


来源: stackexchange

问:
QGraphicsEffect doesn t refresh correctly
Actually i have a QPolygonF who can only move horizontally and when it does, it draws an shadow effect from its initial point to his current. That works great but when i m moving the polygon too fast i got residual effects who doesnt clear correctly or some blank point appears in my shadows.

here is my code s effect

```<code>void    ShadowEffect::draw(QPainter *painter)
{
    QBrush b(QColor(0,0,0,128)); // adjust color and alpha to taste
    painter->setBrush(b);
    painter->setPen(QPen(QColor(0,0,0,128)));
    painter->drawRect(0, 0, *dist, 10+slider->size().height()*1.5);
    drawSource(painter);
}
</code>```

答:
Resolved. The scene wasn t updated correctly so i just put a trigger in my class to call it everytime i moved the polygone</p>

```<code>    connect(myPolygon, &MyPolygon::valueChanged, [scene](){scene->update();});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Actually i have a QPolygonF who can only move horizontally and when it does, it draws an shadow effect from its initial point to his current. That works great but when i m moving the polygon too fast i got residual effects who doesnt clear correctly or some blank point appears in my shadows.

here is my code s effect

void    ShadowEffect::draw(QPainter *painter)
{
    QBrush b(QColor(0,0,0,128)); // adjust color and alpha to taste
    painter->setBrush(b);
    painter->setPen(QPen(QColor(0,0,0,128)));
    painter->drawRect(0, 0, *dist, 10+slider->size().height()*1.5);
    drawSource(painter);
}

Body:
Resolved. The scene wasn t updated correctly so i just put a trigger in my class to call it everytime i moved the polygone

    connect(myPolygon, &MyPolygon::valueChanged, [scene](){scene->update();});


问:
How to call external javascript function in angular 5?
I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

```<code><body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/main.85741bff.js"></script>
  <script type="text/javascript" src="./assets/js/common.js"></script>
</body>
</code>```

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

```<code>document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});
</code>```

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

答:
You can use javascript in the Angular application.

Step 1. Create demo.js file in assets/javascript folder.

```<code>export function test1(){
    console.log('Calling test 1 function');
}
</code>```

Step 2. Create demo.d.ts file in assets/javascript folder.

```<code>export declare function test1();
</code>```

Step 3. Use it in your component

```<code>import { test1 } from '../assets/javascript/demo';
 @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    console.log(test1());
  }
}
</code>```

Note: js and .d.ts file name should be same

ContentLicense: CC BY-SA 4.0

Body:
I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

  <app-root></app-root>

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

Body:
You can use javascript in the Angular application.

Step 1. Create demo.js file in assets/javascript folder.

export function test1(){
    console.log('Calling test 1 function');
}

Step 2. Create demo.d.ts file in assets/javascript folder.

export declare function test1();

Step 3. Use it in your component

import { test1 } from '../assets/javascript/demo';
 @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    console.log(test1());
  }
}

Note: js and .d.ts file name should be same


问:
R - Plot with tmap() does not display the legend
I use the tmap package. I plot a map with the qtm() function but the legend is not displayed. Indeed, I understand that the legend is automatically display, unless you specify to hide it.

I also try to use a work-around with the tm_add_legend() but it doesn't work.

Here is my code :

```<code>library(sp) ; library(rgdal) ; library(rgeos) ;
library(tmap) ; library(maptools)

Directory <- ""

MapFrance <- readOGR(dsn = paste0(Directory, "Departements"),  layer = "DEPARTEMENT")

MapFrance@data$Score <- round(runif(96, min = 1, max = 10), 0)

brk <- c(1, 2.5, 5, 7.5, 10)
ClassScore <- classIntervals(MapFrance@data$Score, style = "fixed", fixedBreaks = brk)
Palette <- brewer.pal(length(brk) - 1, "Greens")

MapFrance@data$Categorie <- as.character(cut(MapFrance@data$Score,
                                             breaks = ClassScore$brks,
                                             labels = Palette,
                                             include.lowest = TRUE))

ExampleData <- MapFrance[MapFrance$CODE_REG == "11", ]

qtm(ExampleData, fill = "Categorie", text = "CODE_DEPT", text.size = "AREA", style = "gray",
    text.root = 5, fill.title = "Opinion scale")
</code>```

And a link to the geographic data :
https://drive.google.com/file/d/1wksMnkufQPdOfSbhWoZbPKMqlcLcll_j

答:
A solution who has three advantages :

Solve the legend issue

Solve the title issue

Avoid the classIntervals call to discretize the continuous variable before the plot

The code :

```<code>library(sp) ; library(rgdal) ; library(rgeos) ;
library(tmap) ; library(maptools)

Directory <- ""

MapFrance <- readOGR(dsn = paste0(Directory, "Departements"),  layer = "DEPARTEMENT")

MapFrance@data$Score <- round(runif(96, min = 1, max = 10), 0)

ExampleData <- MapFrance[MapFrance$CODE_REG == "11", ]

brk <- c(1, 2.5, 5, 7.5, 10)

tm_shape(ExampleData) +
  tm_fill("Score",
          title = "Satisfaction score",
          style = "fixed",
          breaks = brk,
          palette = brewer.pal(length(brk) - 1, "Greens"),
          auto.palette.mapping = FALSE) +
  tm_borders() +
  tm_text("CODE_DEPT",
          size = "AREA",
          root = 10) +
tm_layout(main.title = "Satisfaction score in France",
          legend.position = c("left", "bottom"))
</code>```

The plot :

Body:
I use the tmap package. I plot a map with the qtm() function but the legend is not displayed. Indeed, I understand that the legend is automatically display, unless you specify to hide it.

I also try to use a work-around with the tm_add_legend() but it doesn't work.

Here is my code :

library(sp) ; library(rgdal) ; library(rgeos) ;
library(tmap) ; library(maptools)

Directory <- ""

MapFrance <- readOGR(dsn = paste0(Directory, "Departements"),  layer = "DEPARTEMENT")

MapFrance@data$Score <- round(runif(96, min = 1, max = 10), 0)

brk <- c(1, 2.5, 5, 7.5, 10)
ClassScore <- classIntervals(MapFrance@data$Score, style = "fixed", fixedBreaks = brk)
Palette <- brewer.pal(length(brk) - 1, "Greens")

MapFrance@data$Categorie <- as.character(cut(MapFrance@data$Score,
                                             breaks = ClassScore$brks,
                                             labels = Palette,
                                             include.lowest = TRUE))

ExampleData <- MapFrance[MapFrance$CODE_REG == "11", ]

qtm(ExampleData, fill = "Categorie", text = "CODE_DEPT", text.size = "AREA", style = "gray",
    text.root = 5, fill.title = "Opinion scale")

And a link to the geographic data :
https://drive.google.com/file/d/1wksMnkufQPdOfSbhWoZbPKMqlcLcll_j

Body:
A solution who has three advantages :

Solve the legend issue

Solve the title issue

Avoid the classIntervals call to discretize the continuous variable before the plot

The code :

library(sp) ; library(rgdal) ; library(rgeos) ;
library(tmap) ; library(maptools)

Directory <- ""

MapFrance <- readOGR(dsn = paste0(Directory, "Departements"),  layer = "DEPARTEMENT")

MapFrance@data$Score <- round(runif(96, min = 1, max = 10), 0)

ExampleData <- MapFrance[MapFrance$CODE_REG == "11", ]

brk <- c(1, 2.5, 5, 7.5, 10)

tm_shape(ExampleData) +
  tm_fill("Score",
          title = "Satisfaction score",
          style = "fixed",
          breaks = brk,
          palette = brewer.pal(length(brk) - 1, "Greens"),
          auto.palette.mapping = FALSE) +
  tm_borders() +
  tm_text("CODE_DEPT",
          size = "AREA",
          root = 10) +
tm_layout(main.title = "Satisfaction score in France",
          legend.position = c("left", "bottom"))

The plot :


问:
java.lang.NullPointerException on save object / Hibernate
I'm trying to save an object in my MySQL database with Hibernate and Spring, in HQL.
However, when saving, here is the error message:

org.springframework.web.util.NestedServletException: Request
  processing failed; nested exception is java.lang.NullPointerException

```<code>public void addCountry(Country country) throws Exception {

    Session session = sessionFactory.openSession();
    Transaction transaction = null;

    try {
        transaction = session.beginTransaction();

        //Add new Country object
        Country c = new Country();
        c.setId(""); //id value is auto into mySQL
        c.setCity1(country.getCity1());
        c.setCity2(country.getCity2());
        session.save(c);

        transaction.commit();

    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        throw e;
    } finally {
        session.close();
    }
}
</code>```

答: As juanlumn said remove setId("") as Hibernate will create this for you. Need to debug to see which object is causing NullPointerException like need to know if you are getting Hibernate session which will let you know that you have  configured Hibernate properly. Again you are passing country as method parameter but saving c by populating in dao itself not sure why.</p>

Body:
I'm trying to save an object in my MySQL database with Hibernate and Spring, in HQL.
However, when saving, here is the error message:

org.springframework.web.util.NestedServletException: Request
  processing failed; nested exception is java.lang.NullPointerException

public void addCountry(Country country) throws Exception {

    Session session = sessionFactory.openSession();
    Transaction transaction = null;

    try {
        transaction = session.beginTransaction();

        //Add new Country object
        Country c = new Country();
        c.setId(""); //id value is auto into mySQL
        c.setCity1(country.getCity1());
        c.setCity2(country.getCity2());
        session.save(c);

        transaction.commit();

    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        throw e;
    } finally {
        session.close();
    }
}


问:
How to generate multiple orders from cart in Hybris storefront?
I'm working with Hybris 6.3 we generated a module for a B2B implementation  and I have the requirement of splitting the cart contents into different orders depending on the products in the cart, the billing address, payment, delivery, etc must share the same parameters.

From the requirements we've gathered from our client, we concluded applying consignments strategies aren't what we requiere here, since that handles one order and splits it for shipping and delivery purposes, instead our client's needs are that the different products in the cart to be grouped by a set of shared attributes and generate an order for each group of products.

So far I have identified the class in charge of placing the order in the storefront extension, DefaultCheckoutFacade, which contains the following method:

```<code> @Override
 public OrderData placeOrder() throws InvalidCartException
 {
     final CartModel cartModel = getCart();
     if (cartModel != null)
     {
         if (cartModel.getUser().equals(getCurrentUserForCheckout()) || getCheckoutCustomerStrategy().isAnonymousCheckout())
         {
             beforePlaceOrder(cartModel);
             final OrderModel orderModel = placeOrder(cartModel);
             afterPlaceOrder(cartModel, orderModel);
             if (orderModel != null)
             {
                 return getOrderConverter().convert(orderModel);
             }
         }
     }
     return null;
 }
</code>```

From what I understand, I should override this method to generate a different CartModel accordingly to the criteria set in my requirements and place an order for each CartModel. I revised the CartModel class, and it's superclass AbstractOrderModel, I'm guessing after the getCart() call in the method above, I just need to modify the entries in the CartModel and make a call to the method placeOrder() for each order I need to place, but is it allowed to modify the CartModel object in this way?

Or if I need to split my cart into different orders, should I approach this in a different way? Is something like having multiple carts but showing them as one something that should be done? Does this kind of modification should be done on the OOTB commercefacades extension? Is there a way to extend it somewhere in our module?

EDIT

I started to read about Multiple Carts and it seems to be what I need, but I haven't found how to save entries to a saved cart. In this link I can see how to save the cart, the method saveCart returns a CommerceSaveCartResultData object, both saveCart and the method getCartForCodeAndCurrentUser receive a CommerceSaveCartParameter which must contain a CartModel, how can I generate an instance of this object to set in a CommerceSaveCartParameter?

答: We had a quite similar requirements. Our strategy was to use SplittingService as suggested before, and override CloneAbstractOrderStrategy to convert consignments to OrderModel (or SubOrderModel). It can be complex since you would have to manage the calculation of your orders and so on properly but it can be achieved using this approach.</p>

Body:
I'm working with Hybris 6.3 we generated a module for a B2B implementation  and I have the requirement of splitting the cart contents into different orders depending on the products in the cart, the billing address, payment, delivery, etc must share the same parameters.

From the requirements we've gathered from our client, we concluded applying consignments strategies aren't what we requiere here, since that handles one order and splits it for shipping and delivery purposes, instead our client's needs are that the different products in the cart to be grouped by a set of shared attributes and generate an order for each group of products.

So far I have identified the class in charge of placing the order in the storefront extension, DefaultCheckoutFacade, which contains the following method:

 @Override
 public OrderData placeOrder() throws InvalidCartException
 {
     final CartModel cartModel = getCart();
     if (cartModel != null)
     {
         if (cartModel.getUser().equals(getCurrentUserForCheckout()) || getCheckoutCustomerStrategy().isAnonymousCheckout())
         {
             beforePlaceOrder(cartModel);
             final OrderModel orderModel = placeOrder(cartModel);
             afterPlaceOrder(cartModel, orderModel);
             if (orderModel != null)
             {
                 return getOrderConverter().convert(orderModel);
             }
         }
     }
     return null;
 }

From what I understand, I should override this method to generate a different CartModel accordingly to the criteria set in my requirements and place an order for each CartModel. I revised the CartModel class, and it's superclass AbstractOrderModel, I'm guessing after the getCart() call in the method above, I just need to modify the entries in the CartModel and make a call to the method placeOrder() for each order I need to place, but is it allowed to modify the CartModel object in this way?

Or if I need to split my cart into different orders, should I approach this in a different way? Is something like having multiple carts but showing them as one something that should be done? Does this kind of modification should be done on the OOTB commercefacades extension? Is there a way to extend it somewhere in our module?

EDIT

I started to read about Multiple Carts and it seems to be what I need, but I haven't found how to save entries to a saved cart. In this link I can see how to save the cart, the method saveCart returns a CommerceSaveCartResultData object, both saveCart and the method getCartForCodeAndCurrentUser receive a CommerceSaveCartParameter which must contain a CartModel, how can I generate an instance of this object to set in a CommerceSaveCartParameter?


问:
How can I create a data structure starting at a specified memory address (without using new)?
I asked a similar question before, but I only realized now that the answer I received isn't totally what I wanted.

If I simply have a pointer of some structure type, how can I either move to, or create an instance of the same structure type starting at an address specified by the struct pointer (which I have assigned an address to) without using "new".

答:
Okay. Let's say you have a structure of Type A.

```<code>A a;
A b;
</code>```

If you want to copy b to a (i.e. to the address of a), you would use memcpy.
http://www.cplusplus.com/reference/clibrary/cstring/memcpy/.
This would make the content of "b" start at the adress of a, given by &a.

If you have tow different structure types, ensure that both have the same size or you have unexpected behaviour.

ContentLicense: CC BY-SA 2.5

Body:
Okay. Let's say you have a structure of Type A.

A a;
A b;

If you want to copy b to a (i.e. to the address of a), you would use memcpy.
http://www.cplusplus.com/reference/clibrary/cstring/memcpy/.
This would make the content of "b" start at the adress of a, given by &a.

If you have tow different structure types, ensure that both have the same size or you have unexpected behaviour.


问:
The result not found message displays with the searched data

```

 This is the code for searching and displaying data from a table.The searching works well but it shows  "No result found message " with the searched result even though the searched data in the table.I got the searched data with the no result found message.I need the warning message "no result found" only when the searched result not in the table.

答:
I think you need to use a different flag to check if search keyword is found in table or not. occurrence is used to hide and display the table row based on search keyword. So you can use another variable to print the "No Result found".

Posting the edited code here. I added one boolean var found as a flag to search query.

```<code><script>
 function myFunction() {
      // Declare variables
      var input, filter, table, tr, td, i, occurrence, found=false;

      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("helpseekers");
      tr = table.getElementsByTagName("tr");

      // Loop through all table rows, and hide those who don't match the search query
     for (i = 0; i < tr.length; i++) {
         occurrence = false; // Only reset to false once per row.
         td = tr[i].getElementsByTagName("td");
         for(var j=0; j< td.length; j++){
             currentTd = td[j];
             if (currentTd ) {
                 if (currentTd.innerHTML.toUpperCase().indexOf(filter) > -1) {
                     tr[i].style.display = "";
                     occurrence = true;
                     found = true;
                 }
             }
         }

        if(!occurrence){
             tr[i].style.display = "none";
         }

     }

    if(!found){
         $('#error4').html('<p style="color:red;font-size:14px;" align="center">No results found</p>');
           window.setTimeout(function(){location.reload()},3000)
    }
   }
</script>
</code>```

Body:
I think you need to use a different flag to check if search keyword is found in table or not. occurrence is used to hide and display the table row based on search keyword. So you can use another variable to print the "No Result found".

Posting the edited code here. I added one boolean var found as a flag to search query.

<script>
 function myFunction() {
      // Declare variables
      var input, filter, table, tr, td, i, occurrence, found=false;

      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("helpseekers");
      tr = table.getElementsByTagName("tr");

      // Loop through all table rows, and hide those who don't match the search query
     for (i = 0; i < tr.length; i++) {
         occurrence = false; // Only reset to false once per row.
         td = tr[i].getElementsByTagName("td");
         for(var j=0; j< td.length; j++){
             currentTd = td[j];
             if (currentTd ) {
                 if (currentTd.innerHTML.toUpperCase().indexOf(filter) > -1) {
                     tr[i].style.display = "";
                     occurrence = true;
                     found = true;
                 }
             }
         }

        if(!occurrence){
             tr[i].style.display = "none";
         }

     }

    if(!found){
         $('#error4').html('<p style="color:red;font-size:14px;" align="center">No results found</p>');
           window.setTimeout(function(){location.reload()},3000)
    }
   }
</script>


问:
Design pattern tracking method calls/callers
I don't know what to do in a specific software designing situation. Just searched the internet for solution, but did not find a satisfying answer. So i just want to know your expertise and what the best pratice would be.
I have got a system with several layers of abstraction to begin with. The API shown to the user is a simple class with a compact number of methods. Calling those methods will trigger a avalanche of method calls all the way through the whole abstraction. Certain decissions will be made along the way. Each element on this way can send there decissions and reasons for that decissions via a messageing system back to whoever wants to read it. The system is also logging all the calls and the decissions, which is quite important - well rather the most important. To be honest that is the core issue.

The problem is: I want to know WHO called a certain Method. So i can hand some kind of handle down the way and every abstraction knows: "Right, this guy wants that. So i can log: This guy wanted that."

Why i believe i need this is, because different other systems will be able to use that api. Maybe a GUI wants to drop a command, maybe a HTTP driven remote controller, maybe a hardware trigger, maybe an auto executing routine.

I don't want to let the system make decissions basing on WHO called. I know that would be the absolute opposite of what i intended in abstracting all thouse layers. I just want to log properly. WHO wanted to do WHAT.

Right now i just cannot see the wood for the trees. I just let hand out the API a ticket like object instance. The system is registering that ticket with a id. The API users have to hand in the ticket when calling a command so the system knows who just called.

Well, to put the question to single sentence:
Is there a good pattern for tracking/identifying the caller of a method?

edit:
Altough it is a general problem the used language in this situation is c#!

答:
My current solution is working like a charm... So far. But i would like to know if it would be considered bad practice or if you might see a bottleneck jsut form the first glance.</p>

```<code>    //< API user will call this kind of method handing in their requested Accessor!
    public void Command( int a, int b, KomiAccessorBase accessor=null ){
        if( !AccessGranted( accessor ) ) return;
        this.SubController.CommandA( a, b , accessor );
    }

    //< Accessor is checked on validity
    private bool AccessGranted(KomiAccessorBase accessor, [CallerMemberName] string callerName = null ) {
        if (accessor == null) {
            log("KOMI - Access to ["+callerName+"] denied: No Accessor handed in!", MsgType.LOG);
            return false;
        }
        if ( !_kacc_inventory.ContainsKey(accessor.KACCHashId)) {
            log("KOMI - Access to [" + callerName + "] denied: Accessor not registered in KOMI!", MsgType.LOG);
            return false;
        }
        return true;
    }

    protected Dictionary<int, KomiAccessorBase> _kacc_inventory = new Dictionary<int, KomiAccessorBase>();

    //< The Accessor base class. API user have to derive from that!
    public abstract class KomiAccessorBase : RecieverBase, INameable {
        public int KACCHashId { get; private set; }
        private string _name;
        public string Name {
            get {
                return _name;
            }
            private set {

            }
        }
        protected KomiAccessorBase(string name, KOMI komi) : base(komi.Office) {
            Name = name;
            KACCHashId = -1;
            KACCHashId = komi.RegisterAccessor(this); //Perform the real registration
        }
    }

    //< Registeres the Accessor on KOMI for access checking!
    public int RegisterAccessor(KomiAccessorBase acc) {
        if (acc.KACCHashId != -1) return -1; //Abbort registration if already registered!
        int salt = 1;
        int hashId = (salt + "#" + acc.Name).GetHashCode();
        while (_kacc_inventory.ContainsKey(hashId)) {
            salt++;
            hashId = (salt + "#" + acc.Name).GetHashCode();
        }
        _kacc_inventory.Add(hashId, acc);
        return hashId;
    }
</code>```

Body:
My current solution is working like a charm... So far. But i would like to know if it would be considered bad practice or if you might see a bottleneck jsut form the first glance.

    //< API user will call this kind of method handing in their requested Accessor!
    public void Command( int a, int b, KomiAccessorBase accessor=null ){
        if( !AccessGranted( accessor ) ) return;
        this.SubController.CommandA( a, b , accessor );
    }

    //< Accessor is checked on validity
    private bool AccessGranted(KomiAccessorBase accessor, [CallerMemberName] string callerName = null ) {
        if (accessor == null) {
            log("KOMI - Access to ["+callerName+"] denied: No Accessor handed in!", MsgType.LOG);
            return false;
        }
        if ( !_kacc_inventory.ContainsKey(accessor.KACCHashId)) {
            log("KOMI - Access to [" + callerName + "] denied: Accessor not registered in KOMI!", MsgType.LOG);
            return false;
        }
        return true;
    }

    protected Dictionary<int, KomiAccessorBase> _kacc_inventory = new Dictionary<int, KomiAccessorBase>();

    //< The Accessor base class. API user have to derive from that!
    public abstract class KomiAccessorBase : RecieverBase, INameable {
        public int KACCHashId { get; private set; }
        private string _name;
        public string Name {
            get {
                return _name;
            }
            private set {

            }
        }
        protected KomiAccessorBase(string name, KOMI komi) : base(komi.Office) {
            Name = name;
            KACCHashId = -1;
            KACCHashId = komi.RegisterAccessor(this); //Perform the real registration
        }
    }

    //< Registeres the Accessor on KOMI for access checking!
    public int RegisterAccessor(KomiAccessorBase acc) {
        if (acc.KACCHashId != -1) return -1; //Abbort registration if already registered!
        int salt = 1;
        int hashId = (salt + "#" + acc.Name).GetHashCode();
        while (_kacc_inventory.ContainsKey(hashId)) {
            salt++;
            hashId = (salt + "#" + acc.Name).GetHashCode();
        }
        _kacc_inventory.Add(hashId, acc);
        return hashId;
    }


问:
Promise.all: What are arguments of promise.all.catch(e)
What are arguments of promise.all.catch(e)

Is e an array of errors or object?

```<code>Promise.all([promise1, promise2, ..])
.then((result1, result2,..)=>{})
.catch((error1,error2..???)=>{

})
</code>```

How can we get array of errors? if not Promise.all then how?

答:
What you might want to accomplish requires a different approach:</p>

```<code>const promises = [p1, p2];

const promisesWithExceptionInfo = promises.map(p => {
  return new Promise(resolve => {
    p.then(result => resolve({result})).catch(error => resolve({error}));
  });
});

// now your promises will always be resolved but contain either a result or an error

Promise.all(promisesWithExceptionInfo).then(res => {
  // res is an array of objects where each promise result or error can be evaluated
});
</code>```

Body:
What are arguments of promise.all.catch(e)

Is e an array of errors or object?

Promise.all([promise1, promise2, ..])
.then((result1, result2,..)=>{})
.catch((error1,error2..???)=>{

})

How can we get array of errors? if not Promise.all then how?

Body:
What you might want to accomplish requires a different approach:

const promises = [p1, p2];

const promisesWithExceptionInfo = promises.map(p => {
  return new Promise(resolve => {
    p.then(result => resolve({result})).catch(error => resolve({error}));
  });
});

// now your promises will always be resolved but contain either a result or an error

Promise.all(promisesWithExceptionInfo).then(res => {
  // res is an array of objects where each promise result or error can be evaluated
});


问:
Limit the string length of TextBox when it is updated with Binding
I know that you can limit the input characters of TextBox from user by setting MaxLength property.

Is there a similar way to limit the number of characters shown in Text when the Text is updated with Binding? For example, when it is updated from Binding just show the first 5 characters and leave the rest?

Update:
Thanks for all the info, I got inspired by your recommendation and in the end did it with a converter. Here is how I did it, if someone wants to use it later.

```<code>    public class StringLimiter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }
    }
</code>```

答: A simple but very flexible way of doing it would be to introduce a projected property in your Viewmodel that returns the first 5 characters of the original property and then bind your control to this property. Since you're only showing part of the property value, I assume that you don't want to write to this property from that TextBox. So make you projected property read-only too.</p>

Body:
I know that you can limit the input characters of TextBox from user by setting MaxLength property.

Is there a similar way to limit the number of characters shown in Text when the Text is updated with Binding? For example, when it is updated from Binding just show the first 5 characters and leave the rest?

Update:
Thanks for all the info, I got inspired by your recommendation and in the end did it with a converter. Here is how I did it, if someone wants to use it later.

    public class StringLimiter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }
    }


答:
The displaying of "No Result Found" should be taken outside the main loop (the loop over the rows).
Otherwise you will display "No Result Found" once for every single row that does not match.
Also, the occurrence flag should not be reset at each row, if in the end you want to determine that there was some rows found.

Title: The result not found message displays with the searched data

Body: This is the code for searching and displaying data from a table.The searching works well but it shows  "No result found message " with the searched result even though the searched data in the table.I got the searched data with the no result found message.I need the warning message "no result found" only when the searched result not in the table.


问:
delete first 5 lines and last 2 lines from txt
Need to delete the first 5 lines and the last 2 lines of a txt file using a bat, been trying with a script that works on win 10 but not on win server 2012 r2.

Any idea why?

heres the script, i have

```<code>@echo off
setlocal EnableDelayedExpansion

set "FileToModify=getdoc.txt"
 if not exist "%FileToModify%" goto:leavenow

 set "TempFile=%TEMP%\FileUpdate.txt"
 if exist "%TempFile%" del "%TempFile%"
 if exist newFile.txt del newFile.txt
 if exist Testfinal.txt del Testfinal.txt
 if exist Test1.txt del Test1.txt
 if exist myOriginalFile.txt del myOriginalFile.txt

set "Line=0"
for /F "useback delims=" %%L in ("%FileToModify%") do (
if !Line! GTR 4 (
    echo %%L>>"%TempFile%"
) else (
    set /A Line+=1
    if !Line! GTR 4 echo %%L>>"%TempFile%"
)
)
copy /Y "%TempFile%" "%FileToModify%" >nul

set row=
  for /F "delims=" %%j in (%FileToModify%) do (
if  defined row echo.!row!>>Test1.txt
set row=%%j
   )

set row=
for /F "delims=" %%j in (Test1.txt) do (
 if  defined row echo.!row!> Testfinal.txt
 set row=%%j
   )

 echo { > newFile.txt
 type %FileToModify% >> newFile.txt
 type newFile.txt > getdoc.txt

 del FileUpdate.txt
 del newFile.txt
 del Testfinal.txt
 del Test1.txt

 :leavenow
 echo no file to clean!!!!
 pause
 exit
</code>```

Ps- im sure there is a simple way to do this thanks

答:
I suggest to use the following commented batch file for this task:

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion

set "FileToModify=getdoc.txt"
if not exist "%FileToModify%" (
    set "ErrorMessage=No file "%FileToModify%" to clean"
    goto ErrorOutput
)

rem Get number of lines in file to modify by searching with FINDSTR for begin
rem of line which is true for every line in the file. Output by FINDSTR is the
rem line number a colon and the line itself for each line in file. For interest
rem is here just the line number left to first colon from last output line.

for /F "delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /N /R "^" "%FileToModify%"') do set "LastLineNumber=%%I"

rem Has the file at least 8 lines to remove five lines at top and two
rem lines at bottom and have finally a file with at least one line?

if %LastLineNumber% LSS 8 (
    set "ErrorMessage=File "%FileToModify%" has less than 8 lines"
    goto ErrorOutput
)

rem Decrement the number of last line because the
rem last two lines should be removed from the file.

set /A LastLineNumber-=1

rem Derive name of temporary file to create in folder for temporary files
rem from name of file to modify by replacing its file extension by "tmp".

for %%I in ("%FileToModify%") do set "TempFile=%TEMP%\%%~nI.tmp"

rem Make sure the temporary file does not already exist from a previous
rem run of this batch file broke during processing by command interpreter.
del "%TempFile%" 2>nul

for /F "skip=5 tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /N /R "^" "%FileToModify%"') do (
    if %%I == %LastLineNumber% goto ReplaceFile
    echo/%%J>>"%TempFile%"
)

:ReplaceFile
move /Y "%TempFile%" "%FileToModify%" 2>nul
if errorlevel 1 (
    del "%TempFile%"
    set "ErrorMessage=File "%FileToModify%" is write-protected"
    goto ErrorOutput
)
endlocal
exit /B

:ErrorOutput
cls
echo %~f0
echo/
echo Error: %ErrorMessage%.
echo/
pause
</code>```

Note: This batch file does not produce the right output for a file containing lines starting with 1 or more : because on second FOR option delims=: is used which results in splitting up such lines in line number output by FINDSTR assigned to loop variable I and everything after 1 or more colons assigned to loop variable J being the next character in ASCII table after specified loop variable I.

But this batch file handles files containing command line critical characters like &()[]{}^=;!'+,`~|<> well.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /? ... explains %~f0 (name of batch file with file extension and full path).

cls /?

del /?

echo /?

endlocal /?

exit /?

findstr /?

for /?

goto /?

if /?

move /?

pause /?

rem /?

set /?

setlocal /?

See DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ to understand why echo/ is used instead of echo. in batch file.

Body:
Need to delete the first 5 lines and the last 2 lines of a txt file using a bat, been trying with a script that works on win 10 but not on win server 2012 r2.

Any idea why?

heres the script, i have

@echo off
setlocal EnableDelayedExpansion

set "FileToModify=getdoc.txt"
 if not exist "%FileToModify%" goto:leavenow

 set "TempFile=%TEMP%\FileUpdate.txt"
 if exist "%TempFile%" del "%TempFile%"
 if exist newFile.txt del newFile.txt
 if exist Testfinal.txt del Testfinal.txt
 if exist Test1.txt del Test1.txt
 if exist myOriginalFile.txt del myOriginalFile.txt

set "Line=0"
for /F "useback delims=" %%L in ("%FileToModify%") do (
if !Line! GTR 4 (
    echo %%L>>"%TempFile%"
) else (
    set /A Line+=1
    if !Line! GTR 4 echo %%L>>"%TempFile%"
)
)
copy /Y "%TempFile%" "%FileToModify%" >nul

set row=
  for /F "delims=" %%j in (%FileToModify%) do (
if  defined row echo.!row!>>Test1.txt
set row=%%j
   )

set row=
for /F "delims=" %%j in (Test1.txt) do (
 if  defined row echo.!row!> Testfinal.txt
 set row=%%j
   )

 echo { > newFile.txt
 type %FileToModify% >> newFile.txt
 type newFile.txt > getdoc.txt

 del FileUpdate.txt
 del newFile.txt
 del Testfinal.txt
 del Test1.txt

 :leavenow
 echo no file to clean!!!!
 pause
 exit

Ps- im sure there is a simple way to do this thanks

Body:
I suggest to use the following commented batch file for this task:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

set "FileToModify=getdoc.txt"
if not exist "%FileToModify%" (
    set "ErrorMessage=No file "%FileToModify%" to clean"
    goto ErrorOutput
)

rem Get number of lines in file to modify by searching with FINDSTR for begin
rem of line which is true for every line in the file. Output by FINDSTR is the
rem line number a colon and the line itself for each line in file. For interest
rem is here just the line number left to first colon from last output line.

for /F "delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /N /R "^" "%FileToModify%"') do set "LastLineNumber=%%I"

rem Has the file at least 8 lines to remove five lines at top and two
rem lines at bottom and have finally a file with at least one line?

if %LastLineNumber% LSS 8 (
    set "ErrorMessage=File "%FileToModify%" has less than 8 lines"
    goto ErrorOutput
)

rem Decrement the number of last line because the
rem last two lines should be removed from the file.

set /A LastLineNumber-=1

rem Derive name of temporary file to create in folder for temporary files
rem from name of file to modify by replacing its file extension by "tmp".

for %%I in ("%FileToModify%") do set "TempFile=%TEMP%\%%~nI.tmp"

rem Make sure the temporary file does not already exist from a previous
rem run of this batch file broke during processing by command interpreter.
del "%TempFile%" 2>nul

for /F "skip=5 tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /N /R "^" "%FileToModify%"') do (
    if %%I == %LastLineNumber% goto ReplaceFile
    echo/%%J>>"%TempFile%"
)

:ReplaceFile
move /Y "%TempFile%" "%FileToModify%" 2>nul
if errorlevel 1 (
    del "%TempFile%"
    set "ErrorMessage=File "%FileToModify%" is write-protected"
    goto ErrorOutput
)
endlocal
exit /B

:ErrorOutput
cls
echo %~f0
echo/
echo Error: %ErrorMessage%.
echo/
pause

Note: This batch file does not produce the right output for a file containing lines starting with 1 or more : because on second FOR option delims=: is used which results in splitting up such lines in line number output by FINDSTR assigned to loop variable I and everything after 1 or more colons assigned to loop variable J being the next character in ASCII table after specified loop variable I.

But this batch file handles files containing command line critical characters like &()[]{}^=;!'+,`~|<> well.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /? ... explains %~f0 (name of batch file with file extension and full path).

cls /?

del /?

echo /?

endlocal /?

exit /?

findstr /?

for /?

goto /?

if /?

move /?

pause /?

rem /?

set /?

setlocal /?

See DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ to understand why echo/ is used instead of echo. in batch file.


问:
Adding items to Swift array across multiple threads causing issues (because arrays aren't thread safe) - how do I get around that?
I want to add given blocks to an array, and then run all the blocks contained in the array, when requested. I have code similar to this:

```<code>class MyArrayBlockClass {
    private var blocksArray: Array<() -> Void> = Array()

    private let blocksQueue: NSOperationQueue()

    func addBlockToArray(block: () -> Void) {
        self.blocksArray.append(block)
    }

    func runBlocksInArray() {
        for block in self.blocksArray {
            let operation = NSBlockOperation(block: block)
            self.blocksQueue.addOperation(operation)
        }

        self.blocksQueue.removeAll(keepCapacity: false)
    }
}
</code>```

The problem comes with the fact that addBlockToArray can be called across multiple threads. What's happening is addBlockToArray is being called in quick succession across different threads, and is only appending one of the items, and so the other item is therefore not getting called during runBlocksInArray.

I've tried something like this, which doesn't seem to be working:

```<code>private let blocksDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

func addBlockToArray(block: () -> Void) {
    dispatch_async(blocksDispatchQueue) {
        self.blocksArray.append(block)
    }
}
</code>```

答:
Details

Xcode 10.1 (10B61)

Swift 4.2

Solution

```<code>import Foundation

class AtomicArray<T> {

    private lazy var semaphore = DispatchSemaphore(value: 1)
    private var array: [T]

    init (array: [T]) { self.array = array }

    func append(newElement: T) {
        wait(); defer { signal() }
        array.append(newElement)
    }

    subscript(index: Int) -> T {
        get {
            wait(); defer { signal() }
            return array[index]
        }
        set(newValue) {
            wait(); defer { signal() }
            array[index] = newValue
        }
    }

    var count: Int {
        wait(); defer { signal() }
        return array.count
    }

    private func wait() { semaphore.wait() }
    private func signal() { semaphore.signal() }

    func set(closure: (_ curentArray: [T])->([T]) ) {
        wait(); defer { signal() }
        array = closure(array)
    }

    func get(closure: (_ curentArray: [T])->()) {
        wait(); defer { signal() }
        closure(array)
    }

    func get() -> [T] {
        wait(); defer { signal() }
        return array
    }
}

extension AtomicArray: CustomStringConvertible {
    var description: String { return "\(get())"}
}
</code>```

Usage

The basic idea is to use the syntax of a regular array

```<code>let atomicArray = AtomicArray(array: [3,2,1])

 print(atomicArray)
 atomicArray.append(newElement: 1)

 let arr = atomicArray.get()
 print(arr)
 atomicArray[2] = 0

 atomicArray.get { currentArray in
      print(currentArray)
 }

 atomicArray.set { currentArray -> [Int] in
      return currentArray.map{ item -> Int in
           return item*item
      }
 }
 print(atomicArray)
</code>```

Usage result

Full sample

```<code>import UIKit

class ViewController: UIViewController {

    var atomicArray = AtomicArray(array: [Int](repeating: 0, count: 100))

    let dispatchGroup = DispatchGroup()

    override func viewDidLoad() {
        super.viewDidLoad()

        arrayInfo()

        sample { index, dispatch in
            self.atomicArray[index] += 1
        }

        dispatchGroup.notify(queue: .main) {
            self.arrayInfo()
            self.atomicArray.set { currentArray -> ([Int]) in
                return currentArray.map{ (item) -> Int in
                    return item + 100
                }
            }
           self.arrayInfo()
        }

    }

    private func arrayInfo() {
        print("Count: \(self.atomicArray.count)\nData: \(self.atomicArray)")
    }

    func sample(closure: @escaping (Int,DispatchQueue)->()) {

        print("----------------------------------------------\n")

        async(dispatch: .main, closure: closure)
        async(dispatch: .global(qos: .userInitiated), closure: closure)
        async(dispatch: .global(qos: .utility), closure: closure)
        async(dispatch: .global(qos: .default), closure: closure)
        async(dispatch: .global(qos: .userInteractive), closure: closure)
    }

    private func async(dispatch: DispatchQueue, closure: @escaping (Int,DispatchQueue)->()) {

        for index in 0..<atomicArray.count {
            dispatchGroup.enter()
            dispatch.async {
                closure(index,dispatch)
                self.dispatchGroup.leave()
            }
        }
    }
}
</code>```

Full sample result

Body:
I want to add given blocks to an array, and then run all the blocks contained in the array, when requested. I have code similar to this:

class MyArrayBlockClass {
    private var blocksArray: Array<() -> Void> = Array()

    private let blocksQueue: NSOperationQueue()

    func addBlockToArray(block: () -> Void) {
        self.blocksArray.append(block)
    }

    func runBlocksInArray() {
        for block in self.blocksArray {
            let operation = NSBlockOperation(block: block)
            self.blocksQueue.addOperation(operation)
        }

        self.blocksQueue.removeAll(keepCapacity: false)
    }
}

The problem comes with the fact that addBlockToArray can be called across multiple threads. What's happening is addBlockToArray is being called in quick succession across different threads, and is only appending one of the items, and so the other item is therefore not getting called during runBlocksInArray.

I've tried something like this, which doesn't seem to be working:

private let blocksDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

func addBlockToArray(block: () -> Void) {
    dispatch_async(blocksDispatchQueue) {
        self.blocksArray.append(block)
    }
}

Body:
Details

Xcode 10.1 (10B61)

Swift 4.2

Solution

import Foundation

class AtomicArray<T> {

    private lazy var semaphore = DispatchSemaphore(value: 1)
    private var array: [T]

    init (array: [T]) { self.array = array }

    func append(newElement: T) {
        wait(); defer { signal() }
        array.append(newElement)
    }

    subscript(index: Int) -> T {
        get {
            wait(); defer { signal() }
            return array[index]
        }
        set(newValue) {
            wait(); defer { signal() }
            array[index] = newValue
        }
    }

    var count: Int {
        wait(); defer { signal() }
        return array.count
    }

    private func wait() { semaphore.wait() }
    private func signal() { semaphore.signal() }

    func set(closure: (_ curentArray: [T])->([T]) ) {
        wait(); defer { signal() }
        array = closure(array)
    }

    func get(closure: (_ curentArray: [T])->()) {
        wait(); defer { signal() }
        closure(array)
    }

    func get() -> [T] {
        wait(); defer { signal() }
        return array
    }
}

extension AtomicArray: CustomStringConvertible {
    var description: String { return "\(get())"}
}

Usage

The basic idea is to use the syntax of a regular array

let atomicArray = AtomicArray(array: [3,2,1])

 print(atomicArray)
 atomicArray.append(newElement: 1)

 let arr = atomicArray.get()
 print(arr)
 atomicArray[2] = 0

 atomicArray.get { currentArray in
      print(currentArray)
 }

 atomicArray.set { currentArray -> [Int] in
      return currentArray.map{ item -> Int in
           return item*item
      }
 }
 print(atomicArray)

Usage result

Full sample

import UIKit

class ViewController: UIViewController {

    var atomicArray = AtomicArray(array: [Int](repeating: 0, count: 100))

    let dispatchGroup = DispatchGroup()

    override func viewDidLoad() {
        super.viewDidLoad()

        arrayInfo()

        sample { index, dispatch in
            self.atomicArray[index] += 1
        }

        dispatchGroup.notify(queue: .main) {
            self.arrayInfo()
            self.atomicArray.set { currentArray -> ([Int]) in
                return currentArray.map{ (item) -> Int in
                    return item + 100
                }
            }
           self.arrayInfo()
        }

    }

    private func arrayInfo() {
        print("Count: \(self.atomicArray.count)\nData: \(self.atomicArray)")
    }

    func sample(closure: @escaping (Int,DispatchQueue)->()) {

        print("----------------------------------------------\n")

        async(dispatch: .main, closure: closure)
        async(dispatch: .global(qos: .userInitiated), closure: closure)
        async(dispatch: .global(qos: .utility), closure: closure)
        async(dispatch: .global(qos: .default), closure: closure)
        async(dispatch: .global(qos: .userInteractive), closure: closure)
    }

    private func async(dispatch: DispatchQueue, closure: @escaping (Int,DispatchQueue)->()) {

        for index in 0..<atomicArray.count {
            dispatchGroup.enter()
            dispatch.async {
                closure(index,dispatch)
                self.dispatchGroup.leave()
            }
        }
    }
}

Full sample result


问:
Casting, unboxing, conversion..?
Recently I am learning value types and I am bit confused. Also both casting and unboxing uses the same syntax - (expected type)(object), right?
And what about simple conversion between types, that is casting or just conversion?</p>

```<code>int x = (int)2.5; //casting?

object a=x;
int Y=(int)a;  //unboxing I think

Random r=new Random();
object X=r;
Random R=(Random)X;  // casting
</code>```

答:
Boxing and unboxing is done behind the scenes by compiler. So correct comments would be

```<code>int x = (int)2.5; //casting with conversion

object a=x; //casting with boxing
int Y=(int)a;  //casting with unboxing

Random r=new Random();
object X=r;
Random R=(Random)X;  //casting without unboxing
</code>```

about casting vs conversion check this question: What is the difference between casting and conversion?

Title: Casting, unboxing, conversion..?

Body:
Recently I am learning value types and I am bit confused. Also both casting and unboxing uses the same syntax - (expected type)(object), right?
And what about simple conversion between types, that is casting or just conversion?

int x = (int)2.5; //casting?

object a=x;
int Y=(int)a;  //unboxing I think

Random r=new Random();
object X=r;
Random R=(Random)X;  // casting

Body:
Boxing and unboxing is done behind the scenes by compiler. So correct comments would be

int x = (int)2.5; //casting with conversion

object a=x; //casting with boxing
int Y=(int)a;  //casting with unboxing

Random r=new Random();
object X=r;
Random R=(Random)X;  //casting without unboxing

about casting vs conversion check this question: What is the difference between casting and conversion?


问:
Fullcalendar - Can we add custom data to our event Json Data?
I want to send a type in my Event Json Response.

Here is my code:

```<code>$('#calendar').fullCalendar({

eventSources: [

{"id":"46_l","title":"CustomEvent-Chargement","start":"2013-12-02","end":"2013-12-03","className":"customEventsClass","type":1},
{"id":"46_d","title":"Custom Event-Livraison","start":"2013-12-11","end":"2013-12-12","className":"customEventsClass","type":2}

]

});
</code>```

You see I send a type in JSON Response array, is this possible? What parameter can we use for sending our custom data?

答:
You can also pass url endpoint to events as long as the url returns json response </p>

```<code>            cId.fullCalendar({
             header: {
                right: '',
                center: 'prev, title, next',
                left: ''
             },

            theme: true, //Do not remove this as it ruin the design
            selectable: true,
            selectHelper: true,
            editable: true,
             //it will load data from this url
            events: "{{ url('api/events') }}",
//               events: getData(),

            //Add Events
        });
</code>```

<p>and in your controller or function </p>

```<code>  $events = $request->user()->events()->select('title','color','date')->get();

   //        dd($even,$events)
          $eventsResponse = [];
 //        created_at->format('Y-m-d')
          foreach ($events as $event)
          {
           $eventsResponse[] = [
            'title'=>$event->title,
            'color'=>$event->color,
            'start'=> Carbon::parse($event->date)->toDateTimeString(),
           ];
        }

       return $eventsResponse;
</code>```

Body:
I want to send a type in my Event Json Response.

Here is my code:

$('#calendar').fullCalendar({

eventSources: [

{"id":"46_l","title":"CustomEvent-Chargement","start":"2013-12-02","end":"2013-12-03","className":"customEventsClass","type":1},
{"id":"46_d","title":"Custom Event-Livraison","start":"2013-12-11","end":"2013-12-12","className":"customEventsClass","type":2}

]

});

You see I send a type in JSON Response array, is this possible? What parameter can we use for sending our custom data?

Body:
You can also pass url endpoint to events as long as the url returns json response

            cId.fullCalendar({
             header: {
                right: '',
                center: 'prev, title, next',
                left: ''
             },

            theme: true, //Do not remove this as it ruin the design
            selectable: true,
            selectHelper: true,
            editable: true,
             //it will load data from this url
            events: "{{ url('api/events') }}",
//               events: getData(),

            //Add Events
        });

and in your controller or function

  $events = $request->user()->events()->select('title','color','date')->get();

   //        dd($even,$events)
          $eventsResponse = [];
 //        created_at->format('Y-m-d')
          foreach ($events as $event)
          {
           $eventsResponse[] = [
            'title'=>$event->title,
            'color'=>$event->color,
            'start'=> Carbon::parse($event->date)->toDateTimeString(),
           ];
        }

       return $eventsResponse;


问:
Dynamic pivot with time datatype in SQL Server
```<code>SELECT
    PARTNO, BATCHNO, ' +   @IdleHoursColumns + '
INTO
    TEMPTABLE_IH
FROM
    [dbo].[PRODUCTION_IH]
PIVOT
    (SUM(IDLETIME))
          FOR REASON IN (' + @IdleHoursColumns + ')) AS P'

--printed query
SELECT
    PARTNO, BATCHNO, [POWERCUT]
INTO
    TEMPTABLE_IH
FROM
    [dbo].[PRODUCTION_IH]
PIVOT
    (SUM(IDLETIME)
          FOR REASON IN ([POWERCUT])) AS P
</code>```

How to use dynamic pivot with time datatype in SQL Server? I tried to move my data into a temp table and display the row values to as columns dynamically. The query works perfectly for integer datatype columns. But I got an error

Operand data type time is invalid for sum operator

I tried with cast function and Datediff but it is also throwing errors.

答:
Try the following:

```<code>SELECT T1.PARTNO, T1.BATCHNO, T2.[POWERCUT] FROM (
SELECT PARTNO,BATCHNO,[POWERCUT]
    --INTO TEMPTABLE_IH
    FROM [DBO].[PRODUCTION_IH]
    PIVOT(MAX(IDLETIME)
          FOR REASON IN ([POWERCUT])) AS P)T1
    JOIN
    (
    SELECT PARTNO,BATCHNO, SUM(DATEDIFF(MINUTE, 0, IDLETIME)) / 60.0 AS [POWERCUT]
    FROM [DBO].[PRODUCTION_IH]
    GROUP BY PARTNO,BATCHNO
    ) T2
ON T1.PARTNO = T2.PARTNO AND T1.BATCHNO = T2.BATCHNO
</code>```

It will give you total time in hours. You can modify it to include all "Reason" columns.

HTH

Thanks.

Body:
SELECT
    PARTNO, BATCHNO, ' +   @IdleHoursColumns + '
INTO
    TEMPTABLE_IH
FROM
    [dbo].[PRODUCTION_IH]
PIVOT
    (SUM(IDLETIME))
          FOR REASON IN (' + @IdleHoursColumns + ')) AS P'

--printed query
SELECT
    PARTNO, BATCHNO, [POWERCUT]
INTO
    TEMPTABLE_IH
FROM
    [dbo].[PRODUCTION_IH]
PIVOT
    (SUM(IDLETIME)
          FOR REASON IN ([POWERCUT])) AS P

How to use dynamic pivot with time datatype in SQL Server? I tried to move my data into a temp table and display the row values to as columns dynamically. The query works perfectly for integer datatype columns. But I got an error

Operand data type time is invalid for sum operator

I tried with cast function and Datediff but it is also throwing errors.

Body:
Try the following:

SELECT T1.PARTNO, T1.BATCHNO, T2.[POWERCUT] FROM (
SELECT PARTNO,BATCHNO,[POWERCUT]
    --INTO TEMPTABLE_IH
    FROM [DBO].[PRODUCTION_IH]
    PIVOT(MAX(IDLETIME)
          FOR REASON IN ([POWERCUT])) AS P)T1
    JOIN
    (
    SELECT PARTNO,BATCHNO, SUM(DATEDIFF(MINUTE, 0, IDLETIME)) / 60.0 AS [POWERCUT]
    FROM [DBO].[PRODUCTION_IH]
    GROUP BY PARTNO,BATCHNO
    ) T2
ON T1.PARTNO = T2.PARTNO AND T1.BATCHNO = T2.BATCHNO

It will give you total time in hours. You can modify it to include all "Reason" columns.

HTH

Thanks.


问:
How to get a running AR app using Wikitude SDK with Xamarin Component in Visual studio 2017?
I am going to build a cross-platform mobile app with Augmented Reality experiences using c# programming language. I use Wikitude SDK with Xamarin Component in Visual Studio 2017. I know that Xamarin is integrated now in  Visual Studio 2017 and I am a beginner to these technologies.

I started using the Wikitude Support for Xamarin, created android project, and added the Wikitude SDK to the project. But when started with Example Tutorials and samples on Github, I was unable to proceed and get the running app with AR experience.

Can someone help me in this case to build and run an app with AR experience?

答:
After adding the SDK to a project as explained here Augmented Reality Wikitude SDK do the following:

Right click on the Wikitude component and open the containing folder.

Open the 'samples' folder and continue to open it in visual studio


问:
How can I change the text "Select all" on my dxDataGrid?
I'm using dxDataGrid with AngularJS and I'd like to change the text "Select All"

I was looking for the solution in the documentation and I think that it is here but I cannot change it:

```<code>headerFilter: {
    visible: true,
    texts: {
      cancel: $i18n.translate("lbl_cancel"),
      emptyValue: $i18n.translate("lbl_empty")
    }
}
</code>```

答:
This is my solution. </p>

```<code>       Globalize.addCultureInfo("es", {
                        calendars: {
                            standard:{
                                days:{
                                    names: [$i18n.translate("lbl_monday"), $i18n.translate("lbl_tuesday"), $i18n.translate("lbl_wednesday"), $i18n.translate("lbl_thursday"), $i18n.translate("lbl_friday"), $i18n.translate("lbl_saturday"), $i18n.translate("lbl_sunday")],
                                    namesAbbr: [$i18n.translate("lbl_abbr_monday"), $i18n.translate("lbl_abbr_tuesday"), $i18n.translate("lbl_abbr_wednesday"), $i18n.translate("lbl_abbr_thursday"), $i18n.translate("lbl_abbr_friday"), $i18n.translate("lbl_abbr_saturday"), $i18n.translate("lbl_abbr_sunday")]
                                },
                                months: {
                                    names: [$i18n.translate("lbl_january"), $i18n.translate("lbl_february"), $i18n.translate("lbl_march"), $i18n.translate("lbl_april"), $i18n.translate("lbl_may"), $i18n.translate("lbl_june"), $i18n.translate("lbl_july"), $i18n.translate("lbl_august"), $i18n.translate("lbl_september"), $i18n.translate("lbl_october"), $i18n.translate("lbl_november"), $i18n.translate("lbl_december"), ""],
                                    namesAbbr: [$i18n.translate("lbl_abbr_january"), $i18n.translate("lbl_abbr_february"), $i18n.translate("lbl_abbr_march"), $i18n.translate("lbl_abbr_april"), $i18n.translate("lbl_abbr_may"), $i18n.translate("lbl_abbr_june"), $i18n.translate("lbl_abbr_july"), $i18n.translate("lbl_abbr_august"), $i18n.translate("lbl_abbr_september"), $i18n.translate("lbl_abbr_october"), $i18n.translate("lbl_abbr_november"), $i18n.translate("lbl_abbr_december"), ""]
                                }
                            }
                        },
                        messages: {
                            "dxList-selectAll": $i18n.translate("lbl_select_all"),
                            "dxCollectionWidget-noDataText": $i18n.translate("lbl_no_data_to_display")
                        }
                    });
       Globalize.culture("es");
</code>```

Body:
I'm using dxDataGrid with AngularJS and I'd like to change the text "Select All"

I was looking for the solution in the documentation and I think that it is here but I cannot change it:

headerFilter: {
    visible: true,
    texts: {
      cancel: $i18n.translate("lbl_cancel"),
      emptyValue: $i18n.translate("lbl_empty")
    }
}

Body:
This is my solution.

       Globalize.addCultureInfo("es", {
                        calendars: {
                            standard:{
                                days:{
                                    names: [$i18n.translate("lbl_monday"), $i18n.translate("lbl_tuesday"), $i18n.translate("lbl_wednesday"), $i18n.translate("lbl_thursday"), $i18n.translate("lbl_friday"), $i18n.translate("lbl_saturday"), $i18n.translate("lbl_sunday")],
                                    namesAbbr: [$i18n.translate("lbl_abbr_monday"), $i18n.translate("lbl_abbr_tuesday"), $i18n.translate("lbl_abbr_wednesday"), $i18n.translate("lbl_abbr_thursday"), $i18n.translate("lbl_abbr_friday"), $i18n.translate("lbl_abbr_saturday"), $i18n.translate("lbl_abbr_sunday")]
                                },
                                months: {
                                    names: [$i18n.translate("lbl_january"), $i18n.translate("lbl_february"), $i18n.translate("lbl_march"), $i18n.translate("lbl_april"), $i18n.translate("lbl_may"), $i18n.translate("lbl_june"), $i18n.translate("lbl_july"), $i18n.translate("lbl_august"), $i18n.translate("lbl_september"), $i18n.translate("lbl_october"), $i18n.translate("lbl_november"), $i18n.translate("lbl_december"), ""],
                                    namesAbbr: [$i18n.translate("lbl_abbr_january"), $i18n.translate("lbl_abbr_february"), $i18n.translate("lbl_abbr_march"), $i18n.translate("lbl_abbr_april"), $i18n.translate("lbl_abbr_may"), $i18n.translate("lbl_abbr_june"), $i18n.translate("lbl_abbr_july"), $i18n.translate("lbl_abbr_august"), $i18n.translate("lbl_abbr_september"), $i18n.translate("lbl_abbr_october"), $i18n.translate("lbl_abbr_november"), $i18n.translate("lbl_abbr_december"), ""]
                                }
                            }
                        },
                        messages: {
                            "dxList-selectAll": $i18n.translate("lbl_select_all"),
                            "dxCollectionWidget-noDataText": $i18n.translate("lbl_no_data_to_display")
                        }
                    });
       Globalize.culture("es");


问:
Price Is Right Program. Need to seperate string into parts and replace losing players with other players from array
I have a couple questions about this program (it's unfinished). I have a string called players that prints 4 random players chosen from an array of 20 players. I need a way to separate these into individual names without using the split command (haven't learned in class yet). Also, I need a way to replace the losers of the Price is Right game with new players. So if there are 4 players total, and 1 is the winner, I need to replace the 3 losers with 3 new people from an array. Lastly, I need a way to not repeat players when the array is choosing randomly from the 20 people. Thanks in advance everyone!</p>

```<code>import java.io.*;
import java.util.*;
public class PriceIsRight
{
   //calls the start method

   public static void main(String[] args) throws FileNotFoundException
   {
      Random rand = new Random();
      start(rand);
   }

   //reads names from a text file of 20 names and stores them in an array

   public static String[] getNames() throws FileNotFoundException
   {
      String[] name = new String[20];
      Scanner input = new Scanner(new File("names.txt"));
      int count = 0;
      while (input.hasNext())
      {
         name[count]=input.next();
         count++;
      }
      return name;
   }

   //reads items from a text file of 20 items and stores them in an array

   public static String[] getItems() throws FileNotFoundException
   {
      String[] item = new String[40];
      Scanner input = new Scanner(new File("items.txt"));
      int count = 0;
      while (input.hasNext())
      {
         item[count]=input.next();
         count++;
      }
      return item;
   }
   //selects 4 random names and stores them in an array

   public static String selectNames(Random rand) throws FileNotFoundException
   {
      int count=0;
      String[] name = getNames();
      String players = "";
      while(count < 4)
      {
      int intRand = rand.nextInt(19);
      players = players + name[intRand] + " ";
      count ++;
      }
      return players;
   }

   //selects 1 random item and stores it in an array

   public static String selectItem(Random rand) throws FileNotFoundException
   {
      String[] item = getItems();
      String items = "";
      int intRand = rand.nextInt(19);
      items = item[intRand];
      return items;
   }

   //displays the name of the selected item. Then gets players' bids and stores them in a size 4 array called bids.

   public static void displayItem(Random rand) throws FileNotFoundException
   {
      Scanner kb = new Scanner(System.in);
      String players = selectNames(rand);
      double guess[] = new double[3];
      String item = selectItem(rand);
      System.out.println("Item: " + item);
      System.out.print

   }

   //accepts player's bids array and the actual price of the item. Finds the closest bid to the price and returns the index of the best bid. Displays all the bids made by the player, the price of the item, and the winner of the round

   public static void priceIsRight() throws FileNotFoundException
   {

   }

   //checks if there are any players left in the array name

   public static void checkPlayers() throws FileNotFoundException
   {
   }

   //calls all the methods to start the game

   public static void start(Random rand) throws FileNotFoundException
   {
      System.out.println("You are about to play price is right game.\nAn item will be displayed on the secreen \nThe players will enter their bids, whoever has the closest bid to the actual price will win.\n\n\n\nWait let me choose the players\n\nHere is the list of the players: ");
      getNames();
      String players = selectNames(rand);
      System.out.println(players);
      getItems();
      selectItem(rand);
      System.out.println();
      displayItem(rand);
   }
}
</code>```

答:
You can use this to split your player string.       </p>

```<code>    String 4players = Arrays.toString(playerarray);

    String[] splited = 4players.split(","); // use the symbol that seperates the players
    for(String s : splited)
    System.out.println(s.trim());
</code>```

Body:
I have a couple questions about this program (it's unfinished). I have a string called players that prints 4 random players chosen from an array of 20 players. I need a way to separate these into individual names without using the split command (haven't learned in class yet). Also, I need a way to replace the losers of the Price is Right game with new players. So if there are 4 players total, and 1 is the winner, I need to replace the 3 losers with 3 new people from an array. Lastly, I need a way to not repeat players when the array is choosing randomly from the 20 people. Thanks in advance everyone!

import java.io.*;
import java.util.*;
public class PriceIsRight
{
   //calls the start method

   public static void main(String[] args) throws FileNotFoundException
   {
      Random rand = new Random();
      start(rand);
   }

   //reads names from a text file of 20 names and stores them in an array

   public static String[] getNames() throws FileNotFoundException
   {
      String[] name = new String[20];
      Scanner input = new Scanner(new File("names.txt"));
      int count = 0;
      while (input.hasNext())
      {
         name[count]=input.next();
         count++;
      }
      return name;
   }

   //reads items from a text file of 20 items and stores them in an array

   public static String[] getItems() throws FileNotFoundException
   {
      String[] item = new String[40];
      Scanner input = new Scanner(new File("items.txt"));
      int count = 0;
      while (input.hasNext())
      {
         item[count]=input.next();
         count++;
      }
      return item;
   }
   //selects 4 random names and stores them in an array

   public static String selectNames(Random rand) throws FileNotFoundException
   {
      int count=0;
      String[] name = getNames();
      String players = "";
      while(count < 4)
      {
      int intRand = rand.nextInt(19);
      players = players + name[intRand] + " ";
      count ++;
      }
      return players;
   }

   //selects 1 random item and stores it in an array

   public static String selectItem(Random rand) throws FileNotFoundException
   {
      String[] item = getItems();
      String items = "";
      int intRand = rand.nextInt(19);
      items = item[intRand];
      return items;
   }

   //displays the name of the selected item. Then gets players' bids and stores them in a size 4 array called bids.

   public static void displayItem(Random rand) throws FileNotFoundException
   {
      Scanner kb = new Scanner(System.in);
      String players = selectNames(rand);
      double guess[] = new double[3];
      String item = selectItem(rand);
      System.out.println("Item: " + item);
      System.out.print

   }

   //accepts player's bids array and the actual price of the item. Finds the closest bid to the price and returns the index of the best bid. Displays all the bids made by the player, the price of the item, and the winner of the round

   public static void priceIsRight() throws FileNotFoundException
   {

   }

   //checks if there are any players left in the array name

   public static void checkPlayers() throws FileNotFoundException
   {
   }

   //calls all the methods to start the game

   public static void start(Random rand) throws FileNotFoundException
   {
      System.out.println("You are about to play price is right game.\nAn item will be displayed on the secreen \nThe players will enter their bids, whoever has the closest bid to the actual price will win.\n\n\n\nWait let me choose the players\n\nHere is the list of the players: ");
      getNames();
      String players = selectNames(rand);
      System.out.println(players);
      getItems();
      selectItem(rand);
      System.out.println();
      displayItem(rand);
   }
}

Body:
You can use this to split your player string.

    String 4players = Arrays.toString(playerarray);

    String[] splited = 4players.split(","); // use the symbol that seperates the players
    for(String s : splited)
    System.out.println(s.trim());


答:
You could use "subview" for grouped amounts, or simply use subquery in join, like:</p>

```<code>Select dccdm.*, Isnull(dccdmcsi.SumQuantity,0)
    FROM dbo.[Model]  dccdm LEFT JOIN
    (Select ModelNumber, SUM([Quantity]) as SumQuantity from dbo.ModelColorSizeInventory GROUP BY ModelNumber) dccdmcsi
    ON dccdm.ModelNumber=dccdmcsi.ModelNumber
</code>```

Title: Optimisation of a MSSQL Query - group by multiple columns

Body:
Hey guys i could need some advice, i've the following 2 tables

Table Model:

+----------------+---------------+-------------+------------------------+-------------+--------+-----------------+------------------+------------------+------------------------------+------------------------------+----------------------+----------------------+------------------+
| DLTCountryCode |  SupplierID   | ModelNumber |    ModelDescription    |    Brand    | Fedas  | MeasurementUnit | MinModelNetPrice | MaxModelNetPrice | MinModelSuggestedRetailPrice | MaxModelSuggestedRetailPrice | MinModelInsteadPrice | MaxModelInsteadPrice | PictureAvailable |
+----------------+---------------+-------------+------------------------+-------------+--------+-----------------+------------------+------------------+------------------------------+------------------------------+----------------------+----------------------+------------------+
| AT             | 9120048150008 |     2012266 | xxx                    | Brand       | 115946 | STK             |             6.05 |             6.05 |                        10.95 |                        10.95 |                    0 |                    0 |                1 |
+----------------+---------------+-------------+------------------------+-------------+--------+-----------------+------------------+------------------+------------------------------+------------------------------+----------------------+----------------------+------------------+

Table ModelColorSizeInventory:

+----------------+---------------+-------------+-----------+------+---------------+----------+-------------------------+
| DLTCountryCode |  SupplierID   | ModelNumber | ColorCode | Size |  ItemNumber   | Quantity |    InventoryDateTime    |
+----------------+---------------+-------------+-----------+------+---------------+----------+-------------------------+
| AT             | 9120048150008 |     2012266 |       801 | L    | 9008601584968 |        0 | 2017-09-29 11:16:02.347 |
| AT             | 9120048150008 |     2012266 |       801 | M    | 9008601584951 |        0 | 2017-09-29 11:16:02.347 |
| AT             | 9120048150008 |     2012266 |       801 | S    | 9008601584944 |        2 | 2017-09-29 11:16:02.347 |
| AT             | 9120048150008 |     2012266 |       801 | XL   | 9008601584975 |        4 | 2017-09-29 11:16:02.347 |
| AT             | 9120048150008 |     2012266 |       801 | XXL  | 9008601584982 |        6 | 2017-09-29 11:16:02.347 |
+----------------+---------------+-------------+-----------+------+---------------+----------+-------------------------+

And the following Query:

SELECT dccdm.*, SUM(dccdmcsi.[Quantity]) AS QuantityModel
FROM "Model" AS "dccdm"
LEFT JOIN ModelColorSizeInventory AS dccdmcsi ON dccdm.[ModelNumber] = dccdmcsi.[ModelNumber]
WHERE   (
    dccdm.ModelNumber IN('2012266')
)
AND dccdmcsi.[Quantity] >0
AND dccdm.[DLTCountryCode]='AT'
GROUP BY dccdm.[DLTCountryCode],dccdm.[SupplierID],dccdm.[ModelNumber],dccdm.[ModelDescription],dccdm.[Brand],dccdm.[Fedas],dccdm.[MeasurementUnit],dccdm.[MinModelNetPrice],dccdm.[MaxModelNetPrice],dccdm.[MinModelSuggestedRetailPrice],dccdm.[MaxModelSuggestedRetailPrice],dccdm.[MinModelInsteadPrice],dccdm.[MaxModelInsteadPrice],dccdm.[PictureAvailable]

This Query works as expected, i'm joining ModelColorSizeInventory to find out the sum of all variants with quantities

One thing that bothers me is the group by part, because if i skip the group by statement i'm getting the following error:

Msg 8120, Column 'DLTCountryCode' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Since i'm not that familiar with MSSQL i ask the following question:

How can i write down this query without using this complex GROUP BY clause

The reason behind this question is that writing down multiple columns in a group by statement feels wrong, in queries like these ... ;)

Body:
You could use "subview" for grouped amounts, or simply use subquery in join, like:

Select dccdm.*, Isnull(dccdmcsi.SumQuantity,0)
    FROM dbo.[Model]  dccdm LEFT JOIN
    (Select ModelNumber, SUM([Quantity]) as SumQuantity from dbo.ModelColorSizeInventory GROUP BY ModelNumber) dccdmcsi
    ON dccdm.ModelNumber=dccdmcsi.ModelNumber


问:
function not working properly, codeigniter
The function is fetching data from the database, but the issue is, it is not fetching the next row after printing the first row.

Kindly check and tell me what I'm doing wrong?

```<code>Public function Return_Config($P_name, $WW, $KPI) {
    log_message('debug', 'hd');
    log_message('debug', $P_name . ' ' . $WW . ' ' . $KPI);
    $P_name .= '_one_voice_perf_measured';
    $select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";
    //echo $select_query;

    $query = $this->db->query($select_query);
    if ($query->row() > '0') {
        return $query->row()->config;
    } else {
        return 'Not Measured';
    }
}
</code>```

It is going directly to the else part. please help

答:
try this  </p>

```<code> Public function Return_Config($P_name,$WW,$KPI){
      log_message('debug','hd');
      log_message('debug', $P_name.' '.$WW.' '.$KPI);
            $P_name .= '_one_voice_perf_measured';
        $select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";
        //echo $select_query;

        $query = $this->db->query($select_query)->row_array();
        if (!empty($query)){
          return query['config'];
           }
      else{
                return 'Not Measured' ;
               }
    }
</code>```

Body:
The function is fetching data from the database, but the issue is, it is not fetching the next row after printing the first row.

Kindly check and tell me what I'm doing wrong?

Public function Return_Config($P_name, $WW, $KPI) {
    log_message('debug', 'hd');
    log_message('debug', $P_name . ' ' . $WW . ' ' . $KPI);
    $P_name .= '_one_voice_perf_measured';
    $select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";
    //echo $select_query;

    $query = $this->db->query($select_query);
    if ($query->row() > '0') {
        return $query->row()->config;
    } else {
        return 'Not Measured';
    }
}

It is going directly to the else part. please help

Body:
try this

 Public function Return_Config($P_name,$WW,$KPI){
      log_message('debug','hd');
      log_message('debug', $P_name.' '.$WW.' '.$KPI);
            $P_name .= '_one_voice_perf_measured';
        $select_query = "SELECT config FROM $P_name WHERE KPI = '$KPI' AND Config = '$WW'";
        //echo $select_query;

        $query = $this->db->query($select_query)->row_array();
        if (!empty($query)){
          return query['config'];
           }
      else{
                return 'Not Measured' ;
               }
    }


问:
Parsing CSV file on Java to extract String
On Java Ive make a simple program with search bar. Ive also a CSV File 'file.csv' that contains this:

"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"```
</div>
</div>
</p>

<p>I can open the file on Java with this line.</p>

```String file = "C:\\file.csv";
```

<p>To verify if file exists I use this line.</p>

```if(new File(file).exists()) {
    JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}
```

<p>Now I want to parse the file to extract <b>AD1</b> and display true if exist or false if not exists. Ive declared <b>Scanner</b> for this, but i dont know how to setup for this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));
  scanner.useDelimiter(coma_delimiter);
  while(scanner.hasNext()) {
    String s1= scanner.next();
    System.out.print(s1 +"   ");
    if(s1.equals(search_field.getText())) {
      System.out.print("OKOK");
    } else {
      System.out.println("NOK");
    }
  }

} catch (FileNotFoundException fe) {
  fe.printStackTrace();
} finally {
  scanner.close();
}</code>```

Here the search_field is a JTextField.

答:
You could also use the stream API to process each line individually. It may also have methods that would make this more elegant than my answer.</p>

```<code>final String ENCL = "\"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    Map<String, List<String>> ans = stream.map(s -> {
        String[] split = s.split(",");
        if(split.length > 2) {
            for(int i = 0; i < split.length; ++i) {
                if(split[i].length() >= 2) {
                    if(split[i].startsWith(ENCL)) {
                        split[i] = split[i].substring(1);
                    }
                    if(split[i].endsWith(ENCL)) {
                        split[i] = split[i].substring(0, split[i].length()-1);
                    }
                }
            }
        }
        return split;
    })
    .filter(s->s.length > 2)
    .collect(Collectors.toMap(s -> s[0], s-> Arrays.asList(s[1], s[2])));

    // do what you will with ans
    return ans.containsKey("AD1");
}
catch(IOException ex) {
    // do what you will
}
</code>```

Body:
On Java Ive make a simple program with search bar. Ive also a CSV File 'file.csv' that contains this:

"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"

I can open the file on Java with this line.

String file = "C:\\file.csv";

To verify if file exists I use this line.

if(new File(file).exists()) {
    JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}

Now I want to parse the file to extract AD1 and display true if exist or false if not exists. Ive declared Scanner for this, but i dont know how to setup for this.

Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));
  scanner.useDelimiter(coma_delimiter);
  while(scanner.hasNext()) {
    String s1= scanner.next();
    System.out.print(s1 +"   ");
    if(s1.equals(search_field.getText())) {
      System.out.print("OKOK");
    } else {
      System.out.println("NOK");
    }
  }

} catch (FileNotFoundException fe) {
  fe.printStackTrace();
} finally {
  scanner.close();
}

Here the search_field is a JTextField.

Body:
You could also use the stream API to process each line individually. It may also have methods that would make this more elegant than my answer.

final String ENCL = "\"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    Map<String, List<String>> ans = stream.map(s -> {
        String[] split = s.split(",");
        if(split.length > 2) {
            for(int i = 0; i < split.length; ++i) {
                if(split[i].length() >= 2) {
                    if(split[i].startsWith(ENCL)) {
                        split[i] = split[i].substring(1);
                    }
                    if(split[i].endsWith(ENCL)) {
                        split[i] = split[i].substring(0, split[i].length()-1);
                    }
                }
            }
        }
        return split;
    })
    .filter(s->s.length > 2)
    .collect(Collectors.toMap(s -> s[0], s-> Arrays.asList(s[1], s[2])));

    // do what you will with ans
    return ans.containsKey("AD1");
}
catch(IOException ex) {
    // do what you will
}


问:
Testing a get action with view model
I have the following controller action:

```<code>public ActionResult Edit(int id)
{
   var news = newsRepository.GetNewsByID(id);

   Mapper.CreateMap<News, NewsEditModel>();
   var newsEditModel =
      (NewsEditModel)Mapper.Map(news, typeof(News), typeof(NewsEditModel));

   return View(newsEditModel);
}
</code>```

And the corresponding test:

```<code>[Test]
public void Edit_should_render_view()
{
   // Arrange
   var id = 1;
   var newsEditModel = new NewsEditModel();

   // Act
   var actual = sut.Edit(id);

   // Assert
   actual
      .AssertViewRendered()
      .WithViewData<NewsEditModel>()
      .ShouldBe(newsEditModel);
}
</code>```

In the NUnit GUI I get the following error:

MyProject.Web.UnitTests.Controllers.NewsControllerTests.Edit_should_render_view:
MvcContrib.TestHelper.AssertionException : was MyProject.Web.Common.ViewData.NewsEditModel but expected MyProject.Web.Common.ViewData.NewsEditModel

I don't know how to write the corresponding unit test.  Can someone please help me?

答:
Your test is comparing two different instances of NewsEditModel - one instance that you create in your test code, and the other that is created in the action method.

If you want to examine the model property values as part of your test, you could do this:

```<code>var model = actual
  .AssertViewRendered()
  .WithViewData<NewsEditModel>();

// Check that model is not null
Assert.That(model, Is.Not.Null);

// Check that model ID is same as passed into action method
Assert.That(model.Id, Is.EqualTo(1));
// or alternatively ...
model.Id.ShouldBe(1);
</code>```

Title: Testing a get action with view model

Body:
I have the following controller action:

public ActionResult Edit(int id)
{
   var news = newsRepository.GetNewsByID(id);

   Mapper.CreateMap<News, NewsEditModel>();
   var newsEditModel =
      (NewsEditModel)Mapper.Map(news, typeof(News), typeof(NewsEditModel));

   return View(newsEditModel);
}

And the corresponding test:

[Test]
public void Edit_should_render_view()
{
   // Arrange
   var id = 1;
   var newsEditModel = new NewsEditModel();

   // Act
   var actual = sut.Edit(id);

   // Assert
   actual
      .AssertViewRendered()
      .WithViewData<NewsEditModel>()
      .ShouldBe(newsEditModel);
}

In the NUnit GUI I get the following error:

MyProject.Web.UnitTests.Controllers.NewsControllerTests.Edit_should_render_view:
MvcContrib.TestHelper.AssertionException : was MyProject.Web.Common.ViewData.NewsEditModel but expected MyProject.Web.Common.ViewData.NewsEditModel

I don't know how to write the corresponding unit test.  Can someone please help me?

Body:
Your test is comparing two different instances of NewsEditModel - one instance that you create in your test code, and the other that is created in the action method.

If you want to examine the model property values as part of your test, you could do this:

var model = actual
  .AssertViewRendered()
  .WithViewData<NewsEditModel>();

// Check that model is not null
Assert.That(model, Is.Not.Null);

// Check that model ID is same as passed into action method
Assert.That(model.Id, Is.EqualTo(1));
// or alternatively ...
model.Id.ShouldBe(1);


问:
React Native, MobX and lifecycle
I'm using MobX in React Native and so far I really lite it.
Is there some lifecycle or method to call a function when the state in Mobx Store is changed?</p>

答:
You can put an autorun in componentDidMount and dispose it in componentWillUnmount:

Example (JSBin)

```<code>const store = observable({
  data: "data"
});

setTimeout(() => {
  store.data += " updated!";
}, 2000);

@observer
class App extends Component {
  componentDidMount() {
    this.disposer = autorun(() => {
      console.log(`Data changed: ${this.props.store.data}`);
    });
  }

  componentWillUnmount() {
    this.disposer();
  }

  render() {
    return <h1>{this.props.store.data}</h1>;
  }
};

ReactDOM.render(
  <App store={store} />,
  document.getElementById("app")
);
</code>```

Title: React Native, MobX and lifecycle

Body:
You can put an autorun in componentDidMount and dispose it in componentWillUnmount:

Example (JSBin)

const store = observable({
  data: "data"
});

setTimeout(() => {
  store.data += " updated!";
}, 2000);

@observer
class App extends Component {
  componentDidMount() {
    this.disposer = autorun(() => {
      console.log(`Data changed: ${this.props.store.data}`);
    });
  }

  componentWillUnmount() {
    this.disposer();
  }

  render() {
    return <h1>{this.props.store.data}</h1>;
  }
};

ReactDOM.render(
  <App store={store} />,
  document.getElementById("app")
);


问:
Loop values in one sheet and apply macros on other sheet with range next to the loop range
I have two main sheets in excel with other multiple sheets..
-> "Control sheet" and "Target sheet" for performing Loop

Control Sheet is with a Range (in column) on which to apply loop and next to the range are cell refernces to be used for "Target sheet".

The Target sheet has a Table named "Hyp_table" and shall be pasted in same "Target sheet" in a number of places, the refernce of which shall be read from the column next to the Range on which loop is to be perfomred on control sheet.

The objective is as follows
For each value in Range in control sheet, if the value in range is 1, then move to the target sheet, copy the "Hyp_table", and paste it on the cell number that is existent in column next to the Range on which loop is perfomred.

I have used the following code but it is not working:

```<code>Sub Testing()
    Dim rng As Range, cell As Range
    Set rng = Sheets("Control").Range("C5:C10")

    For Each cell In rng
        If cell = "1" Then
            'Moving to my target sheet
            Sheets(Sheets.Count).Select
            ActiveSheet.Previous.Select
            'Copying my table
            Application.Goto "Hyp_Table"
            Selection.Copy

            'Selecting my cell on "Target sheet" based on value in "Control sheet"
            ActiveSheet.Range(Sheets("Control").cell.Offset(, 1)).Select

            'Pasting the table where the cell is selected as above
            ActiveSheet.Paste
            Application.CutCopyMode = False
        Else
        End If
    Next cell
End Sub
</code>```

Can anyone help me with the code.

答:
First thing first - avoid using ActiveSheet, Application.GoTo and Selection. In every case.
How to avoid using Select in Excel VBA

Second thing second - avoid declaring variables with names like Cell and Range, because these names are special and they are used by the VBEditor.

Third thing third - try the code below - it will probably not work, because I did not understand what exactly is the offset, but it declares a sheetName and it uses it later. It is a good practice:

```<code>Option Explicit

Sub Testing()

    Dim rng         As Range
    Dim myCell      As Range
    Dim sheetName   As String

    Set rng = Sheets("Control").Range("C5:C10")

    For Each myCell In rng

        If myCell = 1 Then

            Worksheets(Worksheets.Count - 1).Range("Hyp_Table").Copy
            sheetName = Worksheets("Control").Cells(1, 1)
            Worksheets(sheetName).Paste
            Application.CutCopyMode = False

        End If

    Next myCell

End Sub
</code>```

Body:
I have two main sheets in excel with other multiple sheets..
-> "Control sheet" and "Target sheet" for performing Loop

Control Sheet is with a Range (in column) on which to apply loop and next to the range are cell refernces to be used for "Target sheet".

The Target sheet has a Table named "Hyp_table" and shall be pasted in same "Target sheet" in a number of places, the refernce of which shall be read from the column next to the Range on which loop is to be perfomred on control sheet.

The objective is as follows
For each value in Range in control sheet, if the value in range is 1, then move to the target sheet, copy the "Hyp_table", and paste it on the cell number that is existent in column next to the Range on which loop is perfomred.

I have used the following code but it is not working:

Sub Testing()
    Dim rng As Range, cell As Range
    Set rng = Sheets("Control").Range("C5:C10")

    For Each cell In rng
        If cell = "1" Then
            'Moving to my target sheet
            Sheets(Sheets.Count).Select
            ActiveSheet.Previous.Select
            'Copying my table
            Application.Goto "Hyp_Table"
            Selection.Copy

            'Selecting my cell on "Target sheet" based on value in "Control sheet"
            ActiveSheet.Range(Sheets("Control").cell.Offset(, 1)).Select

            'Pasting the table where the cell is selected as above
            ActiveSheet.Paste
            Application.CutCopyMode = False
        Else
        End If
    Next cell
End Sub

Can anyone help me with the code.

Body:
First thing first - avoid using ActiveSheet, Application.GoTo and Selection. In every case.
How to avoid using Select in Excel VBA

Second thing second - avoid declaring variables with names like Cell and Range, because these names are special and they are used by the VBEditor.

Third thing third - try the code below - it will probably not work, because I did not understand what exactly is the offset, but it declares a sheetName and it uses it later. It is a good practice:

Option Explicit

Sub Testing()

    Dim rng         As Range
    Dim myCell      As Range
    Dim sheetName   As String

    Set rng = Sheets("Control").Range("C5:C10")

    For Each myCell In rng

        If myCell = 1 Then

            Worksheets(Worksheets.Count - 1).Range("Hyp_Table").Copy
            sheetName = Worksheets("Control").Cells(1, 1)
            Worksheets(sheetName).Paste
            Application.CutCopyMode = False

        End If

    Next myCell

End Sub