text:
Q: Prevent Carousel scroll within scrollable Container (Sencha 2)? I've got a Container with a header, content (Carousel) and a footer. The Container itself is therefor scrollable (vertical) to be able to scroll down to the footer. The Carousel can be swiped horizontally to change active item. I want to lock it to do only two thing:

*

*If starting to move vertically, only scroll Container

*If starting to move horizontally, only scroll Carousel

If you now grab the Carousel you are able to scroll both ways at the same time. Example code:
Ext.define('MyApp.view.MyContainer', {
    extend: 'Ext.Container',

    config: {
        scrollable: true,
        items: [
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'label',
                        html: 'abc'
                    }
                ]
            },
            {
                xtype: 'carousel',
                height: 200,
                scrollable: false,
                items: [
                    {
                        xtype: 'label',
                        html: 'x'
                    },
                    {
                        xtype: 'label',
                        html: 'y
y
y
y
y
y
y
y'
                    }
                ]
            },
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'label',
                        html: 'def'
                    }
                ]
            }
        ]
    }

});

Using Sencha Touch 2.

A: You might need to block the over scrolling .This will help to prevent both vertical scrolling and carousel item change happening at the same time.Try this code inside your scrollable of container.
 scrollable: {
           directionLock: true,
            direction: 'vertical',
            momentumEasing:  {
             momentum: {
               acceleration: 30,
               friction: 0.5
             },
             bounce: {
                acceleration: 0.0001,
                springTension: 0.9999,
             },
             minVelocity: 3
          },
          outOfBoundRestrictFactor: 0
        },

A: If starting to move horizontally, only scroll Carousel
Just add this to the config of your container :
config: {
  scrollable: {
    direction: 'vertical',
    directionLock:true
  }
}

I still haven't figured out how to lock the carousel when you scroll vertically. I'll let you know if I find out.

A: Try this one.It is working fine for me.
Ext.define('MyApp.view.MyContainer', {
    extend: 'Ext.Container',

    config: {
        scrollable: {
            direction: 'vertical'
        },
        items: [
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'label',
                        html: 'abc'
                    }
                ]
            },
            {
                xtype: 'carousel',
                height: 200,
                direction: 'horizontal',
                directionLock: true,
                items: [
                    {
                        xtype: 'label',
                        html: 'x'
                    },
                    {
                        xtype: 'label',
                        html: 'y
y
y
y
y
y
y
y'
                    }
                ]
            },
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'label',
                        html: 'def'
                    }
                ]
            }
        ]
    }
});


text:
Q: How to use config module on main.ts file I have set a config module, according to https://docs.nestjs.com/techniques/configuration then how can I use it on main.ts??
nestjs version: 6.1.1

A: In your main.ts file after you use the NestFactory method to create the application you can use const configService = app.get<ConfigService>(ConfigService); to get the service from the context. If you want to leave out the generics that works too. After that you use it just like you would anywhere else in your app: configSerivce.get('key');

redpajama_set_name: RedPajamaStackExchange


text:
Q: Data loss in TCP Java DataOutputStream CLIENT SENDING SIDE
        if((readerInput = bufferedReaderFromCMD.readLine()) != null ){

            if(readerInput.equals("-file")){
                System.out.println("Checking If condition..");
                String receiver,filename;
                printWriter.println(readerInput);
                System.out.println("Enter File name: ");

                if((filename = bufferedReaderFromCMD.readLine()) != null){

                    File f = new File(filename);
                    FileInputStream fin = new FileInputStream(f);
                    DataInputStream din = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

                    printWriter.println(filename);
                    System.out.println("Enter receiver name: ");
                    receiver = bufferedReaderFromCMD.readLine();
                    printWriter.println(receiver);

                    byte b[] = new byte [8192];
                    long sz = (int) f.length();

                    printWriter.println(Long.toString(sz));

                    System.out.println("Size: "+ sz);

                    int read;

                    while((read = fin.read(b)) > 0){
                        dout.write(b, 0, read);
                        dout.flush();
                        System.out.println("sending...From Client buffer = "+ read);
                    }
                    System.out.println("sent...");

                    fin.close();

                }
            }

CLIENT RECEIVING SIDE
                String s,filename;
                if(s.equals("-file"))
                {
                    if((filename = bufferedReader.readLine()) != null)
                    {
                        File f = new File("recieved from "+filename);
                        long filesize = Long.parseLong(bufferedReader.readLine());
                        FileOutputStream fos = new FileOutputStream(f,true);
                        DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

                        System.out.println(filesize);

                        byte b[] = new byte [8192];
                        long bytesRead;

                        int file_check = 0;
                        long buffersize = b.length;
                        long file_left = filesize;

                        while(file_check == 0){

                            if(file_left < 8192){
                                buffersize = file_left;
                                file_check++;
                            }

                            bytesRead = din.read(b, 0,((int) buffersize));
                            fos.write(b,0,((int) bytesRead));
                            file_left = file_left -((int) bytesRead);
                            System.out.println ("Left = "+file_left + " | Buffersize = " + buffersize);
                        }

                        fos.close();
                        System.out.println("File received From client Reciever");
                    }
                }
                else
                {
                    System.out.println(s);
                }

Server SIDE
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
        printWriter.println("You are now Connected to the Server");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        string message;

         while((message = bufferedReader.readLine()) != null )
        {
            System.out.println("Incoming Client Message From "+ message);

            if(message.equals("-file"))
            {       String filename;
                if((filename = bufferedReader.readLine()) != null)
                {
                    if((reciever = bufferedReader.readLine()) != null)
                    {
                        long filesize = Long.parseLong(bufferedReader.readLine());
                        Socket rsocket = hm1.get(reciever);
                        PrintWriter rprintWriter = new PrintWriter(rsocket.getOutputStream(), true);
                        filename = "Server - " + filename;

                        File f = new File(filename);
                        FileOutputStream fos = new FileOutputStream(f,true);
                        DataInputStream _din = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

                        byte b[] = new byte [8192];
                        int read;
                        int file_check = 0;
                        long buffersize = b.length;
                        long file_left = filesize;

                        long bytesRead;

                        while(file_check == 0){

                            if(file_left < 8192){
                                buffersize = file_left;
                                file_check++;
                            }

                            bytesRead = _din.read(b, 0,((int) buffersize));
                            fos.write(b,0,((int) bytesRead));
                            file_left = file_left -((int) bytesRead);
                            System.out.println ("Left = "+file_left + " | Buffersize = " + buffersize);
                        }

                        // Arrays.fill(b, null);

                        System.out.println("recieved ");
                        fos.close();

                        File new_file = new File(filename);
                        FileInputStream fin = new FileInputStream(new_file);
                        DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(rsocket.getOutputStream()));

                        long sz = (int) new_file.length();
                        //System.out.println("Size: "+ sz);

                        rprintWriter.println("-file");
                        rprintWriter.println(filename);
                        rprintWriter.println(Long.toString(sz));

                        while((read = fin.read(b)) > 0){
                            dout.write(b, 0, read);
                            dout.flush();
                            System.out.println("sending...From Server BUFFER = "+ read);
                        }

                        System.out.println("sent...From Server");
                        fin.close();
                    }
                }
            }

My terminal out is as follows this on 3 different terminals
Client sending
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 1976
        sent...
Server recieveing
        Left = 92088 | Buffersize = 8192
        Left = 83896 | Buffersize = 8192
        Left = 75704 | Buffersize = 8192
        Left = 67512 | Buffersize = 8192
        Left = 59320 | Buffersize = 8192
        Left = 51128 | Buffersize = 8192
        Left = 42936 | Buffersize = 8192
        Left = 34744 | Buffersize = 8192
        Left = 26552 | Buffersize = 8192
        Left = 18360 | Buffersize = 8192
        Left = 10168 | Buffersize = 8192
        Left = 1976 | Buffersize = 8192
        Left = 0 | Buffersize = 1976
        recieved
Server Sending
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 8192
        sending...From Server BUFFER = 1976
        sent...From Server
Client recieveing
        Left = 92088 | Buffersize = 8192
        Left = 83896 | Buffersize = 8192
        Left = 75704 | Buffersize = 8192
        Left = 67512 | Buffersize = 8192
        Left = 59320 | Buffersize = 8192
        Left = 51128 | Buffersize = 8192
        Left = 42936 | Buffersize = 8192
        Left = 34744 | Buffersize = 8192
        Left = 26552 | Buffersize = 8192
        Left = 18360 | Buffersize = 8192
        Left = 16359 | Buffersize = 8192

I am implementing a normal client server model in Java. The idea is where a client can send file to other clients. It works in the following way.
1-Client sends file to the Server
2-Server receives the file and make it's own version
3-Server send the file to the client
I am using DataOutputStream and DataInputStream. I know it not possible to loose a packet but i do not know why but sometimes my client receiving side losses some packets.
My code works in the following way.
1- First i send file size to the server.
2- Server receives the file in chunks.
3- It minuses the chunk size for file size to know when file has been received.
My problem does not always happen but sometimes it does and the receiving side is left in the loop as it has not received those packets. Surprisingly the server sides always gets the file and also sends it but somehow the client side misses some packets.
I have been stuck on this problem for over 4 days any help would appreciated.

A: Possibly your bug is:
file_left = file_left - buffersize;

It should be:
file_left = file_left - (int)bytesRead;

The read is not guaranteed to fill the entire buffer.


text:
Q: Как перебирает значения цикл for в Python 3.5 Всем привет! Пока я занимался своим проектом, я заметил, что если прибавить число к переменной из цикла for, то он начинает себя вести "не соовсем адекватно".
Обычный, непримечательный цикл for:
for x in range(1,10):
    logging.info('X = {}'.format(x))

На выходе стандартная ситуация:
[03.14.2019 18:17:40 | INFO]: X = 1
[03.14.2019 18:17:40 | INFO]: X = 2
[03.14.2019 18:17:40 | INFO]: X = 3
[03.14.2019 18:17:40 | INFO]: X = 4
[03.14.2019 18:17:40 | INFO]: X = 5
[03.14.2019 18:17:40 | INFO]: X = 6
[03.14.2019 18:17:40 | INFO]: X = 7
[03.14.2019 18:17:40 | INFO]: X = 8
[03.14.2019 18:17:40 | INFO]: X = 9

Но стоит только сделать так:
for x in range(1,10):
    x += 7
    logging.info('X = {}'.format(x))

То мой Python 3.5 сходит с ума:
[03.14.2019 18:18:03 | INFO]: X = 8
[03.14.2019 18:18:03 | INFO]: X = 9
[03.14.2019 18:18:03 | INFO]: X = 10
[03.14.2019 18:18:03 | INFO]: X = 11
[03.14.2019 18:18:03 | INFO]: X = 12
[03.14.2019 18:18:03 | INFO]: X = 13
[03.14.2019 18:18:03 | INFO]: X = 14
[03.14.2019 18:18:03 | INFO]: X = 15
[03.14.2019 18:18:03 | INFO]: X = 16

В чём собственно причина данной проблемы и как можно её решить?

A: На самом деле, все правильно.
Когда интерпретатор обрабатывает строку for x in range(1,10): вычисляются все значения x по которым надо пройти.
То есть, список выражений вычисляется один раз, а затем набор выполняется один раз для каждого элемента,
В вашем случае список выражений будет 1, 2, 3 ...
Потом вы меняете x внутри цикла, но на новой итерации цикла x снова принимает значения из заранее вычисленного списка выражений, и вы снова его увеличиваете.
Первая итерация:
for x in range(1,10): # x = 1
    x += 7 # x = 1 + 7 = 8
    logging.info('X = {}'.format(x))

Вторая итерация:
for x in range(1,10): # x = 2
    x += 7 # x = 2 + 7 = 9
    logging.info('X = {}'.format(x))

Ну и ссылка на доку


text:
Q: CSS Body Tag for OnUnload? I have a page that needs an "OnUnload" attribute for the  tag. I know how to make it work for a normal  tag:
<body onunload="offline()">

however, in this particular case, I am using a CSS-styled tag, which is set up like this:
<style type="text/css">
body
{
background-image:url('<?php echo $profile[24]; ?>');center;
<?php
if($profile[25]{0}=="F") echo "background-repeat:no-repeat;"; //You can ignore this
if($profile[25]{1}=="T") echo "background-size:100% 100%;";   //entire PHP script, it
if($profile[25]{2}=="T") echo "background-attachment:fixed;"; //isn't important.
?>
}
</style>

What I need, is for an "OnUnload" attribute to work along with that format.
I've tried Google many different times, worded many different ways, and I've even found a similar question in another forum (it was left unanswered). But as far as I can tell, this attribute doesn't actually exist in CSS format. I'm assuming that's wrong, however, which is why I'm here.
Please let me know what I can do about it, even if I have to ditch the CSS format. I think it might still be able to work in standard http format, but I know this code here works the way it is, so I'd rather not mess with it if I don't have to.

A: Maybe you could try
<script type="text/javascript">
    function offline(){
        //whatever
    }
    window.onbeforeunload = offline;
</script>


text:
Q: How to use recycleview inside an alertdialog in fragment I was having problem showing items in a recycleView inside an alertdialog in a Fragment
The items that I was showing are the filenames.
This is the stucture of my design that I was doing >Activity > Fragment > AlertDialog
In my AlertDialog I am inflating a new layout to get my custom design where I can put event to open a storage and get the files multiple or single.
Below the code to Open files only
getActivity().startActivityForResult(intent, 1001); It means I am getting the result in my activity overriding OnActivityResult
private void browseDocuments(){

    String[] mimeTypes =
            {"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
                    "application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
                    "application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
                    "text/plain",
                    "application/pdf",
                    "application/zip"};

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
        if (mimeTypes.length > 0) {
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        }
    } else {
        String mimeTypesStr = "";
        for (String mimeType : mimeTypes) {
            mimeTypesStr += mimeType + "|";
        }
        intent.setType(mimeTypesStr.substring(0,mimeTypesStr.length() - 1));
    }

    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
    getActivity().startActivityForResult(intent, 1001);

}

Below code adding filesNames to arraysList in OnActivityResult in my Activity which is perfectly running and getting the files
 if (requestCode == 1001){

        FileAdapter = new fileAdapter(announcement_fragment.FileListName);
        LayoutInflater inflater = this.getLayoutInflater(); //Is this correct?
        View dialogView = inflater.inflate(R.layout.add_announcement, null);
        RecyclerView listFiles = dialogView.findViewById(R.id.containerForFiles);
        listFiles.setLayoutManager(new LinearLayoutManager(dialogView.getContext()));
        listFiles.setHasFixedSize(true);
        listFiles.setAdapter(FileAdapter);

       if(resultCode == RESULT_OK){
            //Upload Mutliple
            if(data.getClipData() !=null){
                announcement_fragment.FileListName.clear();

               // Toast.makeText(this,"Mutliple",Toast.LENGTH_LONG).show();
                int count = data.getClipData().getItemCount();
                int i=0;
                while (i<count){
                    announcement_fragment.FileListName.add(getFileName(File));
                    FileAdapter.notifyDataSetChanged();
                    i++;
                }
            }else if(data.getData() != null){
                announcement_fragment.FileListName.add(getFileName(File));
                FileAdapter.notifyDataSetChanged();
            }else{
                //Do nothing
            }
      }

 }

I call and set adapter in my activity inside OnActivityResult (see above code) to notify the adapter but it doesnt work, next I dont know what could be done to achieve it, Where hould I put the adapter to trigger the recycleview items

A: You could either try using ListView first, then see if it works.
The problem could be with your code.
Try using ListView, if it works, then try RecycleView.


text:
Q: usggplot legend position & layout I am trying to use my ggplotly output in shiny, here is my plot.

Here is my script,
    output$Plot1 <- renderPlotly({
  resourcenoplot <-
    resultsdf2 %>%
    filter(region == input$region2) %>%
    ggplot()+
    geom_bar(aes(x=mon, y= round(totalresources,2), fill=ValuerType,
                 text = paste(ValuerType,": ", round(totalresources,2))),
             position="stack",stat = "identity") +
    xlab("\nMonths")+
    ylab("Number of Resources\n\n") +
    guides(fill=guide_legend(title=NULL,reverse=T))+
theme(axis.text.x=element_text(angle=50),
legend.position="bottom",legend.background = element_rect(fill="white",size=0.5, linetype="solid",colour ="darkblue"))

  q <- ggplotly(resourcenoplot,tooltip = c("text"))
  q
})

Here is where i am using this plot in server.R in shiny,
tabPanel("Typewise Utilisation",br(),fluidRow(wellPanel(htmlOutput("selectRegion2")),
                                                        plotlyOutput("Plot1",width = "100%", height = "450px")))

I dont know what's wrong with this code, I have two issues with this.

*

*Cannot bring the legend down, though i specified the legend position, its not working.

*I cannot create space between axis text & axis labels. See the text "Months" is overlapping with the x-axis months. Similarly in y-axis

*If I specify x-axis text angle to be 90 degree, its showing full Month name, here I have specified 70 degree, see the starting part of my month names is cut off.

If I increase the plot size in plotlyOutput("Plot1",width = "100%", height = "450px") , its just increasing the plot size and the issues remain the same.
EDIT 1 :- Subset of the data. This is how the whole dataset looks like

Can someone help me with this please.


text:
Q: Why are type hints for variables not handled as type hints for function parameters? When writing a function in Python with type hints like this:
def foo(token: Token=None):
  pass

It translates to this type hint: Optional[Token]. With optional, a None value is accepted too.

When writing the same type hint for a class field, it doesn't behave the same:
class bar:
  foo: Token = None

Here type hint checkers like the integrated one in PyCharm reports:

Expected type 'Token', got None instead.

My questions are:

*

*Why is in the parameter case the hint and None implicitly combined to Optional[...]?

*Why do fields behave differently, while having the same syntax?

I use PyCharm 2019.3.

A:
Why is in the parameter case the hint and None implicitly combined to Optional[...]

This is how PyCharm's static type checker infers the type of arguments when their default values that are set to None. It infers the type to become Optional[type] of what you declared. This inference rule is applied differently for variable declarations outside of signatures.

Why do fields behave differently, while having the same syntax?

From what we are given to understand from the below sources this was a syntax detail choice aimed at making signatures more concise although introducing an implicit rule.
The way PyCharm's static type checker is implemented aligns with historical PEP 484 changes. The current revision states:

Union types - PEP 484
A past version of this PEP allowed type checkers to assume an optional type when the default value is None, as in this code:
def handle_employee(e: Employee = None): ...

This would have been treated as equivalent to:
def handle_employee(e: Optional[Employee] = None) -> None: ...

This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit.

Looking at the revision history "PEP 484: Do not require type checkers to treat a None default special…" the reasons are given in Pull request #689 linking back to typing issue #275.
I altered your code, because Token was undefined, to:
def foo(token: int = None) -> None:
  pass

class bar:
  foo: int = None

Using the mypy static type checker with default configurations the warnings are issued as expected:
error: Incompatible default for argument "token" (default has type "None", argument has type "int")
error: Incompatible types in assignment (expression has type "None", variable has type "int")

I didn't find any PyCharm inspection having a configurable option for this.


text:
Q: reading array and summation of elements #! /bin/bash I omitted here though I have used it. I used bash shell only. first integer is the no of variables in the array. yes I did get syntax error.
need to read the array and sum of the array elements.
given an array of integers of size N . You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large.
Input Format:
The first line of the input consists of an integer N . The next line contains space-separated integers contained in the array (1<=N<=10, 0<=A[i]<=10000000000).
5
1000000001 1000000002 1000000003 1000000004 1000000005

Output Format:
Print a single value equal to the sum of the elements in the array.
5000000015

what I have done so far:
code:
#input array size
read N
while [ $N -ge 1 -a $N -le 10 ]
do
echo $N
break
done
for i in `seq 0 N-1`;
do
read -a array[i]
if[ "${array[i]}" -ge 0 -a "${array[i]}" -le 10000000000 ]; then
echo "${array[i]}"
fi
done
#sum=expr `sum + ${ array[i] }`

Syntax error:
operator expected
Could you please let me know where I went wrong?

A: If we operate in bash we don't need to use indexes
#!/bin/bash
read N
read -a A
for elem in "${A[@]::N}"; do
    ((ar_sum+=$elem))
done
echo $ar_sum

for-loop can be exchanged by
expr $(printf '%b + ' "${A[@]::N}"\\c)


text:
Q: I can't install detectron2 installation in Windows I try to install detectron2 but this is what i got
ERROR: Could not build wheels for pycocotools, which is required to install pyproject.toml-based projects
I try to fix that using pip install pycocotools or pip install pyproject-toml but it still not work.
Please help! Thank you so much.


text:
Q: Android: Draw a bitmap on top of another, matrix applied I have an imageview, which uses matrix to scale/drag an image. Now I want to overlay another image. The matrix transformation should be applied to the combination of background and overlay.
I did overwrite onDraw and used
    canvas.drawBitmap(overlay, matrix, null);

whereas overlay is the new overlay, matrix is the currently applied matrix. This works fine. Unfortunately I can't specify an offset at which the overlay shall appear on top of the background. This works
    canvas.drawBitmap(overlay, 50, 10, null);

but the overlay remains on that position, once I draw and scale the background again...
How can I accomplish an offset while drawing a bitmap with matrix applied?
Regards

A: You may need to create a new bitmap of approprite size where your overlay will be saved with the matrix transformation. Something like:
Bitmap overlay2 = Bitmap.createBitmap(....)

Canvas c2 = new Canvas(overlay2);

c2.drawBitmap(overlay, matrix, null);

canvas.drawBitmap(overlay2, 50, 10, null);

The other way perhaps better is to do canvas.translate:
canvas.save();
canvas.translate(50,10);
canvas.drawBitmap(overlay, matrix, null);
canvas.restore();


text:
Q: can we define a method in parent class which can be called within a child but not the other one i ran into into a problem , i want to have a method(M) in a parent class (A) then B and C extend the class A . in this situation i want method(M) can be accessible by B but not C . any solution?
public class A
{
    ????? string M()
    {
        return "Hi there";
    }
}
public class B:A
{
}
public class C:A
{
}
B newClassB = new B();
C newClassC = new C();
Console.WriteLine(newClassB.M()); //the correct one
Console.WriteLine(newClassC.M()); //the incorrect one

A: Some of the other answers seem to encourage you to violate the Liskov Substitution Principle, which is very poor practice and will only lead to awful code.
What you have here is a design problem.  If you want C to inherit A then it should behave exactly like an A but with added or modified functionality.
The Liskov Principle states:

"Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program."

With what you want to do, you could potentially break things.  Lets say you have a method that accepts your parent class A, but you pass it a derived class C.  What happens when your method attempts to call C.M()?
What you need to do is re-think your class design.  Is a C really a subtype of an A if you aren't supposed to call M() from C?
Your question's code is very vague so I cannot propose an alternate solution to your class structure, but I will edit if you can make your code less ambiguous.

A: Ok, a useful answer (my previous one was not).
No, you can't and you shouldn't do this, due to the Liskov Substitution Principle already pointed out in other answers and comments.
However, there are cases where it can be justified, and as a matter of fact, some classes in NET do implement the following pattern:
public class A
{
    public virtual bool CanCallM => true;
    public void M() {
        if (!CanCallM) throw new NotSupportedException();
        //do whatever }
}

public class B: A { }

public class C: A
{
    public override bool CanCallM => false;
}

Pretty? Not much, but you do give the consumer a way to know beforehand if M can be called, and you are ensuring at runtime that c.M fails.
I personally prefer this pattern to simply doing nothing because the later is probably a bug in the code; someone is calling M with an expectation that is not met.

A:
in this situation i want method(M) can be accessible by B but not C . any solution?

You can't do that, as I said in the comment, but you can do something like:
class A
{

  public virtual bool Before() { return false; }

  public void BaseMethod ()
  {
      if(Before())
         Console.WriteLine("Called method AMethod");
  }
}

class B : A
{
    public override bool Before() {return true; }
}

class C : A
{
}

void Main()
{
    var c = new C();
    var b = new B();

    c.BaseMethod();
    b.BaseMethod();
}

In this case BaseMethod() will be void execution for C instance.


text:
Q: Check if the webpage a href points to contains certain text I would like to know a way to check if the webpage a href points to contains certain text using javascript.
click

A: Try this:

test


text:
Q: Spark TextArea or RichText autosize I have done lots of searching on this subject, but it seems what I am finding is either out of date or just does not seem to work.
With TextFields in the past, you could set the TextField to a certain width, set wordWrap to true and you would end up with a textfield that changed height according to the text you added.
Now I am trying to do this with either the Spark TextArea or RichText.
I tried this HeightInLines = NAN, but that seems to be out of date.
I also tried this routine:
var totalHeight:uint = 10;
this.validateNow();
var noOfLines:int = this.mx_internal::getTextField().numLines;
for (var i:int = 0; i < noOfLines; i++)
{
     var textLineHeight:int =
                     this.mx_internal::getTextField().getLineMetrics(i).height;
     totalHeight += textLineHeight;
}
this.height = totalHeight;

But the mx_internal is not in the Spark components.
I am trying to do this with AS3, not MXML. If anyone has any suggestions or links that could help me figure this out using AS3, I'd really appreciate it.

A: Been struggling with this all afternoon.  But it looks like the RichEditableText component will autosize if you set its width and leave its height undefined.

A: This works fine:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
    <s:TextArea updateComplete="event.currentTarget.heightInLines = NaN" />
</s:Application>

Found in comments here. You can do the same in ActionScript using the same updateComplete event.

A: This is how I set the height of a TextArea to fit its content when used inside an ItemRenderer (e.g. for a List component):
private function onUpdateComplete( e: Event ): void
{
    // autoresize the text area
    if ( theText ) {
      var actualNumOfLines: int = theText.textFlow.flowComposer.numLines;
      theText.heightInLines = actualNumOfLines;

      invalidateSize();
    }
}

ItemRenderer must have this property set:
<s:ItemRenderer ... updateComplete="onUpdateComplete(event)>

Maybe the updateComplete event is not the optimal trigger for auto-resize actions but works fine for me.

A: You can remove scrollers from TextArea's skin and it becomes autoresizable. You can download completed skin here: http://www.yumasoft.com/node/126

A: Here's a solution for spark text areas (it works as mx text areas do):
var ta_height:int;
for(var i:int=0; i < StyleableTextField(myTextArea.textDisplay).numLines; i++) {
        ta_height += StyleableTextField(myTextArea.textDisplay).getLineMetrics(i).height;
}
myTextArea.height = ta_height;

A: This seems to work for me:
<s:TextArea id="testTextArea"
            change="testTextArea_changeHandler(event)"
            updateComplete="testTextArea_updateCompleteHandler(event)"/>

<fx:Script>
    <![CDATA[
        protected function testTextArea_changeHandler(event:TextOperationEvent):void
        {
            testTextArea.height = RichEditableText(testTextArea.textDisplay).contentHeight + 2;
        }

        protected function testTextArea_updateCompleteHandler(event:FlexEvent):void
        {
            testTextArea.height = RichEditableText(testTextArea.textDisplay).contentHeight + 2;
        }
    ]]>
</fx:Script>

A: Been doing the same head banging over that s:TextArea, and then found out that this gets the job done :
<s:RichEditableText id="txtArea" left="0" right="0" backgroundColor="#F7F2F2"
                    change="textChanged()" />


text:
Q: local linear regression with streaming data From a data stream i'm receiving a pair of measurements consisting of a current consumption and a current percentage every second. By accumulating the consumption over time it will represent eventually the maximum capacity when the percentage reaches from 100% to 0%.
I want to predict the maximum capacity in (almost) real time using linear regression with a small sample size window of two percent. However, when i compare the models of these local regressions of every two percent with the model of the whole data regression, i get very different results due to perhaps local fluctuation. (see figure)
Is there a way to bring the local regression models closer to the whole data model? (in a way that i can see the differences due to fluctuation but overall closer predictions to the whole data model)

A: First of all, if your fluctuations are caused mainly by randomness of your data you might try some regularization techniques: Lasso, Ridge, ElasticNet.
The other solution could be to remember previous model (the one you get at the previous step with data from the previous window) and take its coefficients into account when fitting model with data from a new window. You might get some inspiration from momentum gradient descent techniques.


text:
Q: Difference between copy functions in python What is difference between copy.copy and copy.deepcopy functions in python?
>>> copy.deepcopy(li)
[1, 2, 3, 4]

>>> copy.copy(li)
[1, 2, 3, 4]

both does the same thing , can anyone tell what these functions does specifically

A: >>> import copy
>>> L = [[1,2,3]]
>>> A = copy.copy(L)
>>> A[0].append(4)
>>> A
[[1, 2, 3, 4]]
>>> L
[[1, 2, 3, 4]]
>>> L = [[1,2,3]]
>>> A = copy.deepcopy(L)
>>> A[0].append(4)
>>> A
[[1, 2, 3, 4]]
>>> L
[[1, 2, 3]]

A: copy.copy performs a shallow copy as opposed to copy.deepcopy which performs a deep copy.
When considering:
li = [1, 2, 3, 4]

you will not notice any difference, because you are copying immutable objects, however consider:
>>> import copy
>>> x = copy.copy(li)
>>> x
[[1, 2], [3, 4]]
>>> x[0][0] = 9
>>> li
[[9, 2], [3, 4]]

Since a shallow copy only makes copies of each reference in the list, manipulating these copied references will still affect the original list.
However the following code:
>>> x.append(1)

will have no effect on the original list.


text:
Q: Fourier coefficients of Eisenstein series Several questions/reading reference requests for the following topics.

*

*I require some point-wise bounds on the absolute value of the Eisenstein series $E_{\mathfrak{a}}(\sigma_{\mathfrak{b}}z,1/2 + it)$ for the congruence subgroup $\Gamma_0(q)$, when $|t|\le 1$.

*Is there any place in the literature where someone constructs an explicit bound on the Fourier coefficients of the Eisenstein series? For example for the constant term, $\phi_{\mathfrak{a},\mathfrak{b}}(s)$ where
$$E_{\mathfrak{a}}(\sigma_{\mathfrak{b}}z, s) = \delta_{{\mathfrak{a}} = {\mathfrak{b}}}y^{s} + \phi_{{\mathfrak{a}},{\mathfrak{b},0}}(s)y^{1 - s} + \sum_{m\neq0}a_{{\mathfrak{a}},{\mathfrak{b}},m}(1/2 + it,y)e(mx)...$$
I am particularly interested in upper bounds on $\phi_{\mathfrak{a},\mathfrak{a}}(1/2 + it)$ when $|t|\le 1$. I know that it is at most 1 in absolute value, however I need something that is strictly less than 1 when $q$ is large, say.

*I found some information on a paper by Deshouillers and Iwaniec where they compute $\phi_{\mathfrak{a},\infty,m}(s)$ explicitly, but without much detail I find it hard to deduce how their construction generalizes. Is there any place in the literature you would suggest a student to search for in order to decipher this text?

*Perhaps this is somewhat of a duplicate of #2, however, I found a lot of material in the literature on upper bounds on the Fourier coefficients of cusp forms, but couldn't find anything on those of the Eisenstein series. Is there any obvious way to bound the coefficients $\phi_{\mathfrak{a},\mathfrak{b},m}(s)$ in terms of $m$ and $s$? I surely am missing out on something.

Any answer to any one of the questions would be much appreciated.
Thanks in advance!

A:

*I don't think much is explicitly written down in the literature anywhere. With that being said... the bounds should be at least as strong as those for Maass cusp forms.

*You want the Bruhat decomposition. See Theorem 2.7 of Iwaniec's book "Spectral methods of automorphic forms". I do something similar in my paper on lower bounds for $L(1,\chi)$ via Eisenstein series.

*See below.

The long answer is that this question is relatively easy to answer when $q$ is squarefree, because then every cusp is of the form $1/v$ for some $v \mid q$ with the crucial fact that $(v,\frac{q}{v}) = 1$. If your cusp is of this form, then the Bruhat decomposition isn't too hard and you can write things out explicitly.
A somewhat better approach is to use the theory of Eisenstein newforms (see Matt Young's recent paper on explicit calculations for Eisenstein series). The benefit of this approach is that you use a different basis of Eisenstein series for which the Fourier coefficients are completely explicit off the bat.

Anyway, it's hard for me to answer this question without knowing more about your applications and exactly what bounds you need, so you're welcome to email me for more specific discussions.

A: My recent preprint, Eisenstein series and an asymptotic for the $K$-Bessel function, gives some bounds on both the Fourier coefficients and the Eisenstein series but for large |t|.  I also give some references to recent papers that may be helpful.


text:
Q: Parse::RecDescent and Grammar I defined the following grammar using Parse::RecDescent
my $grammar = q{

top : operand equal value { print $item{value} }

operand: /\w+/

equal : /\=/

value : { my $value = extract_quotelike($text) ;$return =$value;}

};

which i wants it to handle the following cases :
X = 2 -> should print 2
X = "2" -> should print 2
x = '2' -> should print 2
but the above grammar provide different results :
for x=2 it fail to parse it
for x="2" -> it print "2"
for x ='2' -> it pring '2'
any idea to change the above grammar to print 2 on all the the 3 above cases , i.e removing the quotes

A: build_parser.pl:
use strict;
use warnings;

use Parse::RecDescent qw( );

Parse::RecDescent->Precompile(<<'__EOS__', "Parser");
   {
      # The code in rules is also covered by these pragmas.
      use strict;
      use warnings;

      sub dequote { substr($_[0], 1, -1) =~ s/\\(.)/$1/srg }
   }

   start     : assign /\Z/ { $item[1] }

   assign    : lvalue '=' expr { [ 'assign', $item[1], $item[3] ] }

   lvalue    : IDENT

   expr      : NUM_LIT { [ 'num_const', $item[1] ] }
             | STR_LIT { [ 'str_const', $item[1] ] }

   # TOKENS
   # ----------------------------------------

   IDENT     : \w+

   NUM_LIT   : /[0-9]+/

   STR_LIT   : /'(?:[^'\\]++|\\.)*+'/s { dequote($item[1]) }
             | /"(?:[^"\\]++|\\.)*+"/s { dequote($item[1]) }

__EOS__

Adjust the definition of string literals to your needs (but remember to adjust both the rule and dequote).
Running build_parser.pl will generate Parser.pm, which can be used as follows:
use strict;
use warnings;

use FindBin qw( $RealBin );
use lib $RealBin;

use Data::Dumper qw( Dumper );
use Parser       qw( );

my $parser = Parser->new();
print(Dumper( $parser->start('x = 2') ));


text:
Q: SSD drives with SAS Interface Why there aren't any SSD with SAS interface? Are there any technological limitations or it is simply because manufacturers haven't produced one yet?

A: The Zeus IOPS SSD (used by Oracle storage and others) uses SAS interfaces at 3G or 6G.
http://www.stec-inc.com/product/zeusiops.php
In addition, the Sandisk/Pliant line has SAS 6G interfaces.
http://www.sandisk.com/business/industries/enterprise/
Other options are listed here: http://www.storagesearch.com/ssd-sas.html

A: There are, HP have them for some of their mid/high-end SAN boxes for instance.
That said I believe there will be less need for SAS SSD as the main benefit SAS brings over SATA is that of dealing with the longer and more diverse queues seen in multiuser environments. SSDs are inherently better at dealing with random workloads than regular disks; look at the performance differentials between magnetic and flash disks when used in sequential and random operations, essentially SSDs slow down less than regular disks as a percentage of their sequential performance.

A: SATA drives are supposedly upward compatible for use in SAS bays. See this Wikipedia article.


text:
Q: Is there a bamboo task for sleep / wait / timeout? Is there an easy and working way to achieve a defined waiting period before executing/proceeding to the next stage of a bamboo build plan?
I have tried a "timeout 120" within the script body of an script task in its own stage (bamboo host runs on windows 7). But this was failing.

A: Windows 7 has sleep command. Try
sleep 120

in your script

A: To add a hard coded wait use ping command. Following is the example with 10 mins wait:
ping 127.255.255.255 -n 10 -w 60000 >NUL
ping 127.0.0.1 -n 1 -w 6000 >NUL
Explanation:

*

*127.255.255.255 = Invalid IP Address which returns time out error
-n 10 = try pinging 10 times
-w 60000 = wait for 60 seconds before each try
NUL = don't save the output
This will always return 1 (failure; since we are not using a ping-able IP address)

*ping 127.0.0.1 -n 1 -w 6000 >NUL
127.0.0.1 is loopback address and will always return True i.e 0
Hence your task would Pass and would move to the next task; without using Ping used in step 2 your task would always fail since Step 1 would always fail.

So, step 1 : ensures 10 minutes of wait and step 2 ensures that task gets passed.

A: If you're using bamboo powershell task, you can use this cmdlet -
Start-Sleep -s 600


text:
Q: Fallback Database with Hibernate do someone of you know a way to have 2 Databases running parallel?
We are using Hibernate 4 and as a main database Postgres 9.3 - this db is hosted on another machine then the application - if the database is down we still have to save some stuff.
So first intention was to write it into a csv, but I'm not a friend of writing stuff into an unordered file. So I want just to use a fallback Database (thinking of H2 Database). Does someone has experience with such a construct?
We are also using Spring 4 - I would just set up another datasource + sessionfactory + transactionmanager - and add the name at the @Transactional method to use the right manager. any other ideas?
Thank you!!

A: You can extend the Spring AbstractRoutingDataSource and configure two actual data sources:

*

*a primary PostgreSQL data source

*a secondary H2 data source

The application logic will see only one data source, which is the router which will decide which data source is going to switch to on demand.
When the primary data source is down you need to instruct the router to pick the fall-back H2 one.


text:
Q: OffsetHeight value is varing in IE8 standard mode and IE8CompatabilityView mode I am browsing my page in IE8 version.
When I am browsing my .net page in IE8 CompatabilityView mode, I am able to see my Iframe content.
When I am browsing my .net page in IE8 Standard mode, I am unable to see my Iframe content.
In javascript I have setted Iframe width and Height respectively offsetwidth and offsetHeight.
When I am browsing my .net page in IE8 CompatabilityView mode, the offsetHeight value is coming as 258px, but When I am browsing my .net page in IE8 Standard mode offsetHeight value coming as 43px.Because of this low height I am unable to see my I frame content.
My doubt is why offset value is changing in different modes.
Thanks in advance for who will help me to resolve this.


text:
Q: Running MySQLdump for XAMPP in CentOS Hopefully I am posting it in the right forums..
Basically, I am trying to run a script that will do a MySQL database dump which works when I run it manually, but crontab doesn't seem to run that particular script for some reason.
My crontab is setup as such (for testing purposes, running every minute):
* * * * * /opt/lampp/htdocs/xyz/backup/backup.sh

The script is setup as such:
#!/bin/bash
# Script to backup the database
/opt/lampp/bin/mysqldump -u root xyz > backup_$(date +%Y%m%d).sql
echo " backup_$(date +%Y%m%d)" > /opt/lampp/htdocs/xyz/backup/log.txt

I know the script runs, because the log.txt is created. But for some reason, no SQL file is generated. I also know that the line
/opt/lampp/bin/mysqldump -u root xyz > backup_$(date +%Y%m%d).sql

works because it generates the file if I run it at the command line.
Any help greatly appreciated!

A: Try this:
/opt/lampp/bin/mysqldump -u root xyz > backup_$(date +%Y%m%d).sql

Put password of that root user -p(password) without space and it should work.

A: What user ID is this script running under? It'll be trying to write your backup file into the homedir of that particular account. Make sure that this account has write privs for that dir, and can access all the parent dirs leading up to that spot.
Beyond that, note that your script is somewhat racey. Consider than you (maybe) will set the script to run at 11pm every day. If the dump takes more than 1 hour, you'll be dumping a DIFFERENT date into the log file (which you'll be overwriting, not appending, by the way, since you'r eusing >, not >>). To work around this, you'd want to generate/assign the date to a variable at the start of your script, then use that variable instead of more date calls down the road.

A: So when crontab runs the shell script, the backup_(date).sql file is actually saved under the /root folder.
Running the shell script manually places the SQL file where the shell script is.


text:
Q: MPU6050 Power Management using Tiva C Direct Register Mode Having no success getting the MPU6050 out of SLEEP mode. I understand that the SLEEP bit (bit 6) needs to be cleared, but reading the Power Management register after performing the clear returns 0x40. i.e bit 6 has not been cleared.
Yes this is for an assignment, and as such we are not allowed to make use of any libraries etc. My tutor was unable to assist and suggested I ask here.
My I2C setup is as follows
void I2C1_Setup(void)
{
//Setup I2C 1 on PORT A Pins 6, 7

// GPIO A

SYSCTL_RCGCGPIO |= (1<<0); while ((SYSCTL_PRGPIO & (1<<0)) != (1<<0)) {}

GPIOA_AFSEL |= (1<<6)|(1<<7);
GPIOA_PCTL &= ~(0xFF<<24);
GPIOA_PCTL |= (3<<28)|(3<<24);
GPIOA_DEN |= (1<<6)|(1<<7);
GPIOA_ODR |= (1<<7);

// I2C 1

SYSCTL_RCGCI2C |= (1<<1); while ((SYSCTL_PRI2C & (1<<1)) != (1<<1)) {}
/*
TPR = (System Clock/(2*(SCL_LP + SCL_HP)*SCL_CLK))-1;
TPR = (16MHz/(2*(6+4)*100000))-1;
TPR = 7
*/

I2C1_MCR = (1<<4);                  //master mode
I2C1_MTPR = (7<<0);                 //100Kbps

//Disable SLEEP mode
I2C1_MSA = 0xD0;                    // Set slave address and write mode
I2C1_MDR = 0x6B;                    // Power management register
I2C1_MCS = 0x3;                     // start run mode
while ( !((I2C1_MCS & 1) != 0) ) {}
while ( (I2C1_MCS & 1) == 0 ) {}    // poll busy
I2C1_MDR = 0;
I2C1_MCS = 0x7;                     // stop start run mode
while ( !((I2C1_MCS & 1) != 0) ) {}
while ( (I2C1_MCS & 1) == 0 ) {}    // poll busy
}

To test the value of the power management register is use
    I2C1_MSA = 0xD0;                                // transmit mode
    I2C1_MDR = 0x6B;                                // register address
    I2C1_MCS = 3;                                   // start run mode
    while ( !((I2C1_MCS & 1) != 0) ) {}
    while ( (I2C1_MCS & 1) != 0 ) {}                // poll busy

    I2C1_MSA = 0xD1;                                // receive mode
    I2C1_MCS = 7;                                   // stop start run mode
    while ( !((I2C1_MCS & 1) != 0) ) {}
    while ( (I2C1_MCS & 1) != 0 ) {}                // poll busy
    int data;
    data = I2C1_MDR;

The return value for this is 0x40. When I perform the same steps to check the WHO_AM_I register (0x75) it is confirmed that the slave address is 0x68.
I know the MPU is functioning generally as we were able to get readings on an arduino using the simple sketch provided here (https://playground.arduino.cc/Main/MPU-6050)
I'm using the TM4C123GH6PM and keil uvision5.
Really not sure what is going wrong here.
Any help is appreciated.

A: seems i used the wrong run mode when trying to send/rec. the data.
instead of using stop start run (0x7), needed to no resend the start command and just send stop run (0x5).
instead of
I2C1_MCS = 0x7;                     // stop start run mode

use
I2C1_MCS = 0x5;                     // stop run mode


text:
Q: Calculate the dot product of an array of matrices and the rows or columns of another matrix Having two ndarrays, array d with shape (3,10,10) and array e with shape (3,10), how do I calculate the dot product of the first 10x10 matrix of d and the first row of e, the second 10x10 matrix of d and the second row of e, etc.
For example, having the following two arrays:
d = np.array([np.diag([1,1,1,1,1,1,1,1,1,1]),
              np.diag([2,2,2,2,2,2,2,2,2,2]),
              np.diag([3,3,3,3,3,3,3,3,3,3])])
e = np.arange(30).reshape((3,10))

How do I calculate the 3x10 array:
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
       [60, 63, 66, 69, 72, 75, 78, 81, 84, 87]])

I tried using np.dot and np.tensordot and also transposing and adding a new axis to e before doing so, but I coulnd't figure out how to solve this problem.

A: We can use np.einsum -
np.einsum('ijk,ij->ik',d,e)

Play around with its optimize flag to use BLAS.
Or np.matmul -
np.matmul(d,e[...,None])[...,0]

Note : On Python 3.x np.matmul could be replaced by @ operator.


text:
Q: Use an exported CCK content type in an install schema of a module I have a content type built by CCK in Drupal 6. If I export it, I get a php code. How can use this code in my module's hook_install, to have this content types imported when the module is installed?

A: Check out the modules called features, this out of the box gives you the ability to create modules that can contain entire CCK definitions. Very easy, and little to no custom coding is required

A: Programatic CCK Now Possible!
Also see other comments there...


text:
Q: I want to call multiple popups with minimal function When you click onclick, you're popping up.
I want to use multiple popups and bring in different html files.
I don't know how to write the code.
// popup jquery
function layerPop(){
 $("body").append("

");
 $(".popup_wrap").load("popup/marketing_agree.html");
}

function layerClose(){
 $(".popup_wrap").remove();
}

// popup btn

// popup/marketing_agree.html

     <button type="button" onclick="layerClose()" class="close__btn"></button>

If you are currently running the source code, click on <i onclick = "layerPop"
The layerPop function will run and .popup_wrap will be added to the popup/marking_agree.html. But I have a lot of pop-ups and there are many htmls to be added, so I wonder how to reduce reuse with code.

A: One obvious way would be to accept params in your functions like this:
function layerPop(id, resource){
 $("body").append("

");
 $(".popup_wrap").load(resource);
}

function layerClose(id){
 if (id === null) $(".popup_wrap").remove();
 else $("#" + id).remove();
}

Then maybe maintain the resource location and id outside the function. This should give you a lot of code reusability.
layerPop("popup3", "popup/marketing_agree.html");
layerClose("popup3");


text:
Q: Creating a lagged variable subject to some condition in a pandas dataframe i am attempting to create a lagged feature as part of my dataframe.
I have done this using the shift() function and my dataframe has the following updated format:

df1[515:525]
Out[20]:
        store_id  units_sold  Data_lagged
144378      8091          45         18.0
145533      8091          34         45.0
146688      8091          20         34.0
147843      8091          27         20.0
148998      8091          38         27.0
32          8094          33         38.0  **** <- needs to be 0
1187        8094          36         33.0
2342        8094          37         36.0
3497        8094          33         37.0
4652        8094          37         33.0

The 'Data_lagged' feature refers to the lag of the 'units_sold' feature by a time step of 1.
The problem is, I want the 'Data_lagged' feature to equal 0 when the store_id feature changes in value.
For instance the entry 32 (indicated with **** in dataframe), needs to have a Data_lagged value of 0, since the store_id changes from 8091 to 8094.
Instead the value is the lagged unit_sales of the previous entry for store 8091 (as one expects).
This is a problem, since the lagged feature indicates a value of a different store. Store 8094 has a lagged feature value from store 8091.
I have tried many things including for loops etc. I am unable to obtain the results I need.
Can anyone help me with this?

A: This may be redundant, but I think it can be solved in one line.
The following code:
df1.Data_lagged = df1.Data_lagged.where([True] + [a == b for a, b in zip(df1.store_id[:-1], df1.store_id[1:])], 0.)


text:
Q: python decorator for function argument preprocessing my original problem is I need to strip a string and then split by a operator.
s = " a & b | c & d "
l = map(lambda x : map(lambda x:x.strip() , x.strip().split('&')), s.strip().split('|'))

this is too cumbersome for people to read, so I am thinking to use decorator to do this strip() preprocessing.
here is my current solution, but it's not working!
Update:
query_AND =lambda wl:  '.*'+'.*'.join(wl)+'.*'

def d_query_AND(query_split):
    def d_query_AND_f(query_split):
        return query_AND(query_split)
        #return query_spli
    return d_query_AND_f

@d_query_AND
def query_split(p):
    return [v for v in p.split('&')]

print query_split("asd & asdsa & sadsa")

A: I have to admit I don't fully understand why you need a decorator.
One relatively easy way to tokenize these expressions is by using a regex:
In [12]: re.findall(r'[^|&\s]+|&|[|]', ' a & b | c & d ')
Out[12]: ['a', '&', 'b', '|', 'c', '&', 'd']

In [13]: re.findall(r'[^|&\s]+|&|[|]', 'asdasd&sdasd| asdsa & asdsda')
Out[13]: ['asdasd', '&', 'sdasd', '|', 'asdsa', '&', 'asdsda']

The regex consists of three components OR-ed together:

*

*[^|&\s]+ matches a sequence of characters other than &, | and whitespace.

*& matches &.

*[|] matches |.

If you don't need to capture the operators, the regex can be simplified to r'[^|&\s]+'.
edit: If you don't want to split on the spaces, as you imply in the comments, the following should work:
In [18]: map(string.strip, re.findall(r'[^|&]+|&|[|]', 'asdasd&sd  asd| asdsa & asdsda'))
Out[18]: ['asdasd', '&', 'sd  asd', '|', 'asdsa', '&', 'asdsda']


text:
Q: Display get_the_tag_list by order entered in the backend I am currently displaying a post tags in a sidebar, using the PHP Code widget and the following snippet:
if ( is_singular() ) :
    echo get_the_tag_list(
        '

',
        '

',
        '

',
        get_queried_object_id()
    );
endif;

Currently, these tags are ordered alphabetically; what I would like to do is maintain the order in which they are entered in the backend. I tried the approach that was suggested here for the_tags, but to no avail.
Any help with finding a similar or suggested approach would be much appreciated!
Best regards,
Julian

A: To display post tags in order they entered in the backend, use this within the loop where you want to display. Hope this will helps you to display your tag list.
Where, the tag were display in order based on their created term_id.
if ( is_singular() ) :
echo '
';
echo '
';
$ordered_tag_list = wp_get_post_terms(get_the_ID(), 'post_tag', array('orderby' => 'term_id', 'fields' => 'all'));
foreach($ordered_tag_list as $tag) {
    echo '
' . esc_html( $tag->name ) . '
';
}
echo '
';
echo '

endif;


text:
Q: read big-endian data portably without inet.h I'm parsing a file format that represents numbers in a big-endian way.
Normally I would include aarp/inet.h and use ntohl().
In various embedded c environments I use inet.h does not exist
Are there any standard equivalents to ntohl() I could use so I don't need to pull in inet.h?

A: Updated
Now sure why you wouldn't want to link in ntohl, but this should work, although a little slower than what your platform provides.
The code is optimized to use a compile time check to detect an Intel processor (which is always Little Endian).  You can amend that #if defined... block to include your own processor if you know it's endianness.  Otherwise, it falls back to doing a simple runtime check of detecting Little Endian.
#include <stdint.h> // if stdint.h is not available, then "typedef int int32_t" and "typedef unsigned int uint32_t" as appropriate

int compile_time_assert[(sizeof(int32_t) == 4)?1:-1];

int32_t NTOHL(int32_t value)
{

#if defined(_M_X64) || defined(_M_IX86) || defined(_M_X64) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__amd64__)
        const int isBigEndian = 0;
#elif defined(sparc)
        const int isBigEndian = 1;
#else
        const int32_t test = 0x01020304;
        const char* ptr = (const char*)&test;
        int isBigEndian = (ptr[0] == 0x01);
#endif

    int32_t result = value;

    if (!isBigEndian)
    {
        uint32_t uvalue = (uint32_t)value; // cast to unsigned for shifting safely
        result = (uvalue >> 24) | ((uvalue >> 8) & 0x0000FF00) | ((uvalue << 8) & 0x00FF0000) | (uvalue << 24);
    }

    return result;
}

All of this assumes that the only two possible endianess architectures (big and little).  Which should be 99.9% of everything these days.  If you want this to work on an extremely dated architecture - one in which the old guys with the grey beards will speak about about 6-bit bytes, EBCIDIC, and 1's complements, you will need to modify the above code as appropriate.


text:
Q: Laravel validation on array of radio inputs I'm developing a module that have multiple radio inputs and has numeric index,
I have 15 radio input groups and each group has 7 radio input members with the same index.
I want to check each input if empty.
HTML output
I have tried dynamic requests validation on laravel it failed to validate.
I tried to hard code the validation of 15 inputs = failed,
Then I tried to test it individually and adding next index on success and it only validates up to 12th item/index.
my valdation code
$rules = [];
foreach($this->request->get('ratingsd') as $key => $val)
{
   $rules["ratings[$val]"] = 'required';
}

        @foreach($items as $index=>$group)

                {{$group->group_name}}

        @foreach($group->items as $items=>$item)

                {{ $item->number }} {{ $item->entry }}

                @foreach($ratings as $rate_value=>$rate_text)
                    {!!Form::hidden("ratingsd[".$item->item_id."]", $item->item_id)!!}
                    {!!Form::radio("ratings[$item->item_id]", $rate_text, "$group->group_id*$item->item_id*$rate_value")->inline()!!}
                @endforeach
                {!!Form::textarea("remarks[".$item->item_id."]", '')->placeholder('Remarks')->inline()!!}

        @endforeach

                    @endforeach

                Overall Remarks

            {!!Form::textarea("overall_remark", '')->placeholder('Remarks')->inline()!!}

            <button class="btn btn-primary btn-block" type="submit">
                Submit
            </button>

I expect to validate properly each "ratings" radio inputs


text:
Q: Error in multiple uploads I have a problem making multiple uploads of images in CodeIgniter 3. I tried the MY_Upload Class, and I tried other code, but none work for me.
Controller
function do_uploadMultiple(){
        $config['upload_path'] = './assets/page/img/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '0';
        $config['max_width']  = '0';
        $config['max_height']  = '0';
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);

        $nameField = 'imagem';
        if ( ! $this->upload->do_upload($nameField)){
            $error = array('error' => $this->upload->display_errors());
        }else{
            $foto = array('upload_data' => $this->upload->data());

            return $foto['upload_data']['file_name'];

        }
    }

    public function cadastrarPage(){

        $data['nome_menu'] = $this->input->post('nome');
        $data['titulo'] = $this->input->post('titulo');
        $data['text'] = $this->input->post('text');
        $data['video'] = $this->input->post('video');
        $teste['imagem'] = $this->input->post('imagem');

        $id_abrase = $this->Abrase_model->cadastrarPage($data);

        for($i = 0; $i < count($_FILES['imagem']['name']); $i++){
            $img['id_abrase'] = $id_abrase;
            $img['imagem'] = $this->do_uploadMultiple();

            $result = $this->Abrase_model->gravarImagem($img);
            if($result){
                echo 'yeah';
            }else{
                echo 'fail';
            }
        }

    }

View
<form method="post" action="<?php echo base_url('index.php/abrase/cadastrarPage'); ?>" enctype="multipart/form-data">

                    Nome da página no menu
                    <input id="nome" name="nome" type="text" class="form-control">

                    Título
                    <input id="titulo" name="titulo" type="text" class="form-control">

                    Texto da Página
                    <textarea class="form-control" name="text" id="text" cols="30" rows="10"></textarea>

                    Selecione as imagens
                    <input class="file" name="imagem[]" id="imagem" type="file" multiple data-show-upload="false">

                    Vídeo
                    <input type="text" name="video" id="video" class="form-control">

                    Arquivos

                    <input class="btn btn-info" type="submit" value="Cadastrar">

            </form>

Model
public function cadastrarPage($data){
        $this->db->set('data_add', 'NOW()', FALSE);
        $this->db->set('excluido', 0);

        $this->db->insert('abrase', $data);
        return $this->db->insert_id();
    }

public function gravarImagem($data){
        return $this->db->insert('abrase_img', $data);
    }

And now the error
A PHP Error was encountered

Severity: Warning

Message: is_uploaded_file() expects parameter 1 to be string, array given

Filename: libraries/Upload.php

Line Number: 412

Backtrace:

File: C:\xampp\htdocs\Tattica\ABRASE\application\controllers\Abrase.php
Line: 32
Function: do_upload

File: C:\xampp\htdocs\Tattica\ABRASE\application\controllers\Abrase.php
Line: 54
Function: do_uploadMultiple

File: C:\xampp\htdocs\Tattica\ABRASE\index.php
Line: 315
Function: require_once

I tried everything that I found in the web, but can't do it. I need help please.

A: I had the same problem, Codeigniter really cannot handle multiple file uploads, The multiple upload class was for an older codeigniter, But here is a code that you can use, This uses native PHP code and as far as I know, this is the only way to upload multiple in codeigniter.
  foreach($_FILES['file']['tmp_name'] as $index => $f)
  {
  $target_dir =  './assets';
  $target_file = $target_dir . basename($_FILES["file"]["name"][$index]);
  $uploadOk = 1;
  $files_name = $_FILES["file"]["name"][$index];
  // Check if file already exists
  if (file_exists($target_file))
  {
      //Filexists
      $uploadOk = 0;
  }
  // Check file size
  if ($_FILES["file"]["size"][$index] > 5000000)
  {
      echo "Sorry, your file is too large.";
      $uploadOk = 0;
  }
  // Check if $uploadOk is set to 0 by an error
  if ($uploadOk == 0)
  {
      echo "Sorry, your file was not uploaded.";
      // if everything is ok, try to upload file
  }
  else
  {
      if (move_uploaded_file($_FILES["file"]["tmp_name"][$index], $target_file))
      {
            //success
      }
      else
      {
          echo "Sorry, there was an error uploading your file.";
      }
  }
}


text:
Q: Pass input parameters to ruby-written shell? I'm trying to write a shell in Ruby (using readline), implementing some custom commands. To create the correspondence between given input and methods that are defined in an external module I'm using an hash like this
hash = {
  'command_1' => method(:method_1),
  'command_2' => method(:method_2)
}

And once I got the user input I pass it to the hash calling the method associated with the command-key
hash[input.to_s].()

My questions are: how can I handle variants of the same command? (e.g. for the help command give different output depending if a flag is given, something like help -command_1)

How can I pass parameters to methods in the hash? (e.g. pass to an open command the file to be opened like open file_name)
Thanks to all in advance.

A: While that might work if you wrangle it enough, the easy way is this:
hash = {
  'command_1' => :method_1,
  'command_2' => :method_2
}

send(hash[input.to_s])

The send method allows dynamic dispatch which is way easier than trying to deal with method.


text:
Q: Python Import and 'object has no attribute' with Qt From research on Stack Overflow and other sites I'm 99% sure that the problem I'm having is due to incorrect importing.  Below is a QLabel sub class that I'm using to respond to some mouse events:
import Qt
import sys

class ASMovableLabel(Qt.QLabel):

    def mouseReleaseEvent(self, event):

        button = event.button()
        if button == 1:
            print ('LEFT CLICK')

    def mousePressEvent(self, event):

        button = event.button()
        if button == 1:
            print ('LEFT CLICK')
        elif button == 3:
            print ('RIGHT CLICK')
            self.setLayout()

    def mouseMoveEvent(self, event):
        print ("you moved the mouse: %f, %f", event.x, event.y)
        self.frameRect.setTopLeft(Qt.QPoint(event.x, event.y))

When mouseMoveEvent is triggered I get the following error:
    self.frameRect.setTopLeft(Qt.QPoint(event.x, event.y))
AttributeError: 'builtin_function_or_method' object has no attribute 'setTopLeft'

The other solutions to this type of error I've seen have revolved around the name space, so I would or would not need to include Qt. before all the Qt classes but this error is much farther down in the Qt objects.  Please point out my mistake!
I have also tried:
from PyQt4 import Qt

It gives the same error
UPDATE: based on Messa's comment I made few changes:
import Qt
import sys

class ASMovableLabel(Qt.QLabel):

    def mouseReleaseEvent(self, event):

        button = event.button()
        if button == 1:
            print ('LEFT CLICK')

    def mousePressEvent(self, event):

        button = event.button()
        if button == 1:
            print ('LEFT CLICK')
        elif button == 3:
            print ('RIGHT CLICK')
            self.setLayout() #this won't set to nil

    def mouseMoveEvent(self, event):
        self.frameRect().setTopLeft(Qt.QPoint(event.globalX(), event.globalY()))

So it seems that in Python the dot syntax are function calls and need to include that trailing "()".  This doesn't include self ( i.e. self().something() )

A: Try
self.frameRect().setTopLeft(Qt.QPoint(event.x, event.y))

instead of
self.frameRect.setTopLeft(Qt.QPoint(event.x, event.y))


text:
Q: Z-index in front of an element in a fixed position I do not find a solution to my problem so I turn to you :).
Here is the context: I have two brothers elements, one is absolute position and the other is in a fixed position. Basic the fixed element is always at the top. Consider in the code below:

* {
  box-sizing: border-box;
}
html, body{
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}
#element1 {
  background: red;
  height: 100%;
  width: 100%;
  position: absolute;
}
#element2 {
  background: green;
  margin: 0 auto;
  height: 200px;
  position: absolute;
  width: 600px;
}
#element3 {
  background: blue;
  height: 200px;
  position: fixed;
  bottom: 0;
  width: 100%;
}

#element1,
#element3 {
  z-index: 1;
}
#element2 {
  z-index: 10;
}

http://jsfiddle.net/P7c9q/1162/
That the green color area is a modal. My objective is to make the element green over the element in a fixed position.
How can I unlock myself knowing that element 1 and element 2 must remain in absolute position?
Thank you in advance,
cordially.

A: element3 will always be over element1 and all its children even if a child of element1 has higher z-index because its finally related to its parent element1 which has lower z-index than element3
There are two solutions to this case:

*

*put element2 and element3 as children for element1

* {
  box-sizing: border-box;
}
html, body{
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}
#element1 {
  background: red;
  height: 100%;
  width: 100%;
  position: absolute;
}
#element2 {
  background: green;
  margin: 0 auto;
  height: 200px;
  position: absolute;
  width: 600px;
}
#element3 {
  background: blue;
  height: 200px;
  position: fixed;
  bottom: 0;
  width: 100%;
}

#element1,
#element3 {
  z-index: 1;
}
#element2 {
  z-index: 10;
}

*make element2 outside element1 in the same level with element3

* {
  box-sizing: border-box;
}
html, body{
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}
#element1 {
  background: red;
  height: 100%;
  width: 100%;
  position: absolute;
}
#element2 {
  background: green;
  top:25%;
  left:15%;
  margin: 0 auto;
  height: 200px;
  position: fixed;
  width: 600px;
}
#element3 {
  background: blue;
  height: 200px;
  position: fixed;
  bottom: 0;
  width: 100%;
}

A: This will do

* {
  box-sizing: border-box;
}
html, body{
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}
#element1 {
  background: red;
  height: 100%;
  width: 100%;
  position: absolute;
}
#element2 {
  background: green;
  top:25%;
  left:15%;
  margin: 0 auto;
  height: 200px;
  position: fixed;
  width: 600px;
}
#element3 {
  background: blue;
  height: 200px;
  position: fixed;
  bottom: 0;
  width: 100%;
}


text:
Q: Executing a symbolic link yields different results than executing the file to which it points The context
I've downloaded scilab-6.1.0.bin.linux-x86_64.tar.gz from the official website of "Scilab" because I want to be able to use the provided tools.
Within the bin directory of the downloaded files, I've the following files
$ ls -l | cut -d ' ' -f 5-

1713591 Feb 25 05:27 modelicac
2057719 Feb 25 05:27 modelicat
  44563 Feb 25 05:27 scilab
      6 Feb 25 05:27 scilab-adv-cli -> scilab
  24741 Feb 25 05:27 scilab-bin
      6 Feb 25 05:27 scilab-cli -> scilab
  20725 Feb 25 05:27 scilab-cli-bin
  44563 Feb 25 05:27 scinotes
  44563 Feb 25 05:27 xcos
 675942 Feb 25 05:27 XML2Modelica

$ test -L scilab-adv-cli && test -L scilab-cli && echo $?
0

As we can see, both scilab-cli and scilab-adv-cli are symbolic links to scilab. Executing scilab-cli, scilab-adv-cli and scilab yields to different results (see gif below)

The question
Isn't a symbolic link (A) , which points to an executable (B), be supposed to execute (B)?
In the scenario presented above, scilab-cli and scilab-adv-cli would be (A) and scilab would be (B).

A: Running a symlink which points to an executable does indeed run the executable, but there is one important difference: the first argument given to the new process, which (in this case) stores the command given, gives the name of the symlink, not the name of the target executable. This allows programs to implement different behaviours depending on how they're called.
One common instance which is likely to be installed on your system is apropos: it's typically (on Linux systems at least) a symlink to whatis, but the two commands behave differently.
In your case, when scilab is run as scilab-cli, it presents its text-mode interface; when it's run as scilab (as happens with your realpath approach), it starts its GUI.


text:
Q: Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies I have this exception generated on some user machines (~1 of 20):

Could not load file or assembly 'System, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its
dependencies. The system cannot find the file specified.

I found several references to this error over the web and this site but nothing helped.
I have an add-in application which uses WCF to connect to the server. The add-in built with .NET Framework 3.5 with VS 2008.
The error is reproducible on one of the test machines in only one user account. I install my application and can only reproduce this from one account on this machine everywhere else it is working fine. Furthermore it is only reproducible with only one version of host application which I created add-in for (I assume because it uses differnet .NET Frameworks).
I have checked the fuse logs and I see the following:

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll
Running under executable  C:\Program Files\SolidWorks Corp\SolidWorks\sldworks.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: User = Home\User
LOG: DisplayName = System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
 (Fully-specified)
LOG: Appbase = file:///C:/Program Files/SolidWorks Corp/SolidWorks/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = NULL
Calling assembly : System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.

So by some reasons it is trying to use v2.0.50727\mscorwks.dll loader to load the Version=4.0.0.0 of System.dll. On build machine I'm referring 2.0.0.0 version of System.dll.

A: I had this same problem - some users could pull from git and everything ran fine. Some would pull and get a very similar exception:

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

In my particular case it was AjaxMin, so the actual error looked like this but the details don't matter:

Could not load file or assembly 'AjaxMin, Version=4.95.4924.12383, Culture=neutral, PublicKeyToken=21ef50ce11b5d80f' or one of its dependencies. The system cannot find the file specified.

It turned out to be a result of the following actions on a Solution:

*

*NuGet Package Restore was turned on for the Solution.

*A Project was added, and a Nuget package was installed into it (AjaxMin in this case).

*The Project was moved to different folder in the Solution.

*The Nuget package was updated to a newer version.
And slowly but surely this bug started showing up for some users.
The reason was the Solution-level packages/respositories.config kept the old Project reference, and now had a new, second entry for the moved Project. In other words it had this before the reorg:
  <repository path="..\Old\packages.config" />

And this after the reorg:
  <repository path="..\Old\packages.config" />
  <repository path="..\New\packages.config" />

So the first line now refers to a Project that, while on disk, is no longer part of my Solution.
With Nuget Package Restore on, both packages.config files were being read, which each pointed to their own list of Nuget packages and package versions. Until a Nuget package was updated to a newer version however, there weren't any conflicts.
Once a Nuget package was updated, however, only active Projects had their repositories listings updated. NuGet Package Restore chose to download just one version of the library - the first one it encountered in repositories.config, which was the older one. The compiler and IDE proceeded as though it chose the newer one. The result was a run-time exception saying the DLL was missing.
The answer obviously is to delete any lines from this file that referenced Projects that aren't in your Solution.

A: I got this after downgrading a project from .net 4.5 to .net 3.5.
To resolve I had to go in to the project - properties - settings window and delete all my settings, save the project, exit and restart visual studio, go back into project - properties -settings window and re-enter all my settings and their default values

A: This worked for me.
Go to Project->Propertied->Target Frawork->Change frame work like 3.5 to 4.0

A: I had the problem under Linux and I needed to install those. I don't know which one actually fixed the problem, but that error was gone after that:
apt-get install mono-utils mono-runtime-sgen mono-runtime-common \
                mono-runtime-boehm mono-runtime-dbg mono-xbuild

A: I've seen this a couple times, and it is usually fixed by running a repair on .NET Framework (whichever version the application is trying to use).

A: You are using .net 4? - Maybe on the clients there is only the ".net framework 4 client profile" installed. Try to install full package!!
Download here

A: In my case, I was able to find issue with ScriptManager by setting Debug=true in web.config file

A: I answered too late but it has worked in my case.If you are facing this issue in your project please add the following line in your web.config :
<compilation  batch="false" >

This worked in my case. If you already have compilation tag in your web.config then add only batch="false" property to it.

A: You can enable NuGet packages and update you dlls. so that it work.
or you can update the package manually by going through the package manager in your vs if u know which version you require for your solution.

A: Even I have experience some more strange things, I can see there is no dll in GAC from where the dll is loading but windows > Module shows system.dll version=4.0.0.0 loaded

A: i just changed my target .net framework and it worked .in my case i changed from .net 4.7 to .net 4.
Right click your solution and select properties
selct properties
Click Application >> Target Framework

A: FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
this is my problem. I installed system.configuration assembly in the project and other class libraries also. now the problem has gone.

A: am used net 6.0 with aspcore.report and problem like this happened with me
I installed system.configuration assembly in the server project problem solved


text:
Q: How to delete a record from datagridview by clicking on a 'Delete' DataGridViewLinkColumn How to delete a row from DataGridView by clicking on delete hyperlink.Currently, the record is deleted by selecting the entire row. but I need to delete the row only upon clicking on 'Delete' link button.The following code is used to remove the row upon selecting the row.Please help me how to remove the row upon clicking on Delete Link(Not selecting the Row).
   foreach (DataGridViewRow row in datagvRelation.SelectedRows)
        {
             datagvRelation.Rows.Remove(datagvRelation.CurrentRow);

        }

A:  private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
 {
      if (e.ColumnIndex == 0)
      {
           dataGridView1.Rows.RemoveAt(e.RowIndex);
      }
 }

Here you can replace zero with your columnindex containing the link...


text:
Q: How to configure Visual Studio 2015 to develop device driver application(KMDF)? I am newbie to device driver development and trying to configure Visual Studio 2015 to develop KMDF project on my windows 7, I have installed Visual Studio 2015, Windows Driver Kit(WDK)10 and SDK10 too.
In Visual Studio when i create a WDF->KMDF project, project is not able find "device.tmh" file and other object like NTSTATUS, it seems that project is searching for KMDF library or header file.
After installation of WDK10 and SDK10 it create "windows kits" folder along with "8.0, 8.1 and 10" folder inside it.
Please let me know where i goes wrong or how to set library path to remove all error.
Thanks.

A: 1) Install Visual Studio 2015.
2) Install Visual C++ (Not installed by default).
3) Install SDK10 (Not installed by default).
4) Install WDK10 (Not install by default).
There all setup is working fine for me.


text:
Q: Flexible rotating centered SVG I need flexible rotating centered SVG.
Problem is if use
<svg width="100%">

with rotation, browser window start resizing itself on svg rotation.
If i delete "width="100%"", than SVG will svg will not shrink on horizontal window resize.
Any ideas how to fix it?
Codesandbox example.

A: Putting the animation inside the svg is a solution.

    <svg
      viewBox="0 0 29.892 29.892"
      width="100%"
      height="100vh"
      xmlns="http://www.w3.org/2000/svg"
      {...props}
    >
    <g>
      <path
        d="m14.946 0c-8.254 0-14.946 6.692-14.946 14.946 0 8.255 6.692 14.946 14.946 14.946s14.946-6.691 14.946-14.946c-1e-3 -8.254-6.692-14.946-14.946-14.946zm0 26.58c-6.425 0-11.634-5.208-11.634-11.634 0-6.425 5.209-11.634 11.634-11.634s11.633 5.209 11.633 11.634c0 6.426-5.208 11.634-11.633 11.634z"
        opacity=".2"
      />
      <path d="m20.758 4.878 1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012v3.312c2.119 0 4.1 0.576 5.812 1.566z"/>
        <animateTransform repeatCount="indefinite" begin="0s" dur="5s" attributeName="transform" type="rotate" from="0 14.946 14.946" to="360 14.946 14.946" />
    </g>
    </svg>

If you want css to control the animation, you'd still have to group the paths within the svg. You can then target the group in css like below.

#circle {
  animation: rotate 2s linear infinite;
  transform-origin: 50% 50%
}
@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}
 <svg
      viewBox="0 0 29.892 29.892"
      width="100%"
      height="100vh"
      xmlns="http://www.w3.org/2000/svg"
      {...props}
    >
      <g id="circle">
        <path
          d="m14.946 0c-8.254 0-14.946 6.692-14.946 14.946 0 8.255 6.692 14.946 14.946 14.946s14.946-6.691 14.946-14.946c-1e-3 -8.254-6.692-14.946-14.946-14.946zm0 26.58c-6.425 0-11.634-5.208-11.634-11.634 0-6.425 5.209-11.634 11.634-11.634s11.633 5.209 11.633 11.634c0 6.426-5.208 11.634-11.633 11.634z"
          opacity=".2"
        />
        <path d="m20.758 4.878 1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012v3.312c2.119 0 4.1 0.576 5.812 1.566z" />
      </g>
    </svg>


text:
Q: Typescript - variables declaration I'm not sure if this is the place for this question, but I've been told code review is not the place for it.
I'm just learning Angular 2 and Typescript, so am working through this following tutorial:
https://angular.io/docs/ts/latest/tutorial/toh-pt4.html
Between part three and four, the declaration of the heroes variable in the app.component.ts changes from:
export class AppComponent {
    heroes = HEROES;
}

to:
export class AppComponent {
    heroes: Hero[];
}

I understand the first one sets it to a constant of heroes array but why does the second one use a colon and not just set it to an empty array?
Changing the second one to an = actually throws an expression expected error so basically I'm just trying to understand the differences between the two.

A: heroes: Hero[];

doesn't set it to a value.
It just defines a property with

*

*name = heroes

*type = Hero[] which means array of Hero

*without assigning a value which keeps it at default value null.

With initialization it would look like
heroes: Hero[] = [new Hero('Spidey'), new Hero('Batman')];

A: The difference between the two is that the first one is javascript, you are assigning your heroes variable to the constant **HEROES*.
The second one it's a typescript thing, you are saying that the heroes variable will be an array of heroes, basically you are defining an empty variable.
It's like java or c# where you do something like public int myNumber on your class

A: Your first understanding is right with
heroes = HEROES

Now,
heroes : Hero [ ];

Here Hero  reprents class which holds certain properties. by this line, you are telling typescript compiler that heroes variable will hold list of objects having type of  Hero(custom or user defined type) . In OOP world class is a user defined dataType and according that you can declare any variable with that Type.
Please note , you can declare(:) any varaiable with Type, you cant assing(=) Type (in Typescript) but you can assign that Type of data to variable.
So here you cant use =.
I hope this will help you...

A: Just complementing @Günter Zöchbauer,
in class/interface declarations, : after a property name is used to define its type.
However, this might cause a little confusion when you're creating an object on-the-fly, which, in this case, : marks value assignment:
interface MyInterface {
  myBooleanProperty: boolean = false;
}

// ... somewhere

let a = {
  myBooleanProperty: true
};

// and to add a little more fun

let b: MyInterface = {
  myBooleanProperty: true
}


text:
Q: recv function blocks with keep-alive (HTTP) I'm learning about sockets in Windows, also HTTP protocol.
So I was doing some tests with keep-alive but for some reason recv hangs for about 5 seconds, here it's:
VOID TestWinsock()
{
    WSADATA WsaData;
    addrinfo hints;
    addrinfo* hResult;
    SOCKET hsocket;
    int Result;

    WSAStartup(MAKEWORD(2, 2), &WsaData);
    RtlZeroMemory(&hints, sizeof(hints));

    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    Result = getaddrinfo("localhost", "80", &hints, &hResult);
    if (Result != 0)
    {
        return;
    }

    hsocket = socket(hResult->ai_family, hResult->ai_socktype, hResult->ai_protocol);
    if (hsocket == INVALID_SOCKET)
    {
        return;
    }

    Result = connect(hsocket, hResult->ai_addr, (int)hResult->ai_addrlen);
    if (Result == SOCKET_ERROR)
    {
        return;
    }

    char* POSTContent;
    char HTTPRequestBuffer[1024];
    char RecvBuffer[1024];

    char* HTTPRequest =
        "POST %s HTTP/1.0\r\n"
        "Host: %s\r\n"
        "connection: keep-alive\r\n"
        "Content-type: application/x-www-form-urlencoded\r\n"
        "Content-Length: %u\r\n"
        "\r\n"
        "%s"
        "\r\n"
        "\r\n";

    POSTContent = "variable1=10";
    wsprintfA(
        HTTPRequestBuffer,
        HTTPRequest,
        "/tests/test.php",
        "127.0.0.1",
        strlen(POSTContent),
        POSTContent
        );

    int sent = send(hsocket, HTTPRequestBuffer, strlen(HTTPRequestBuffer), 0);
    RtlZeroMemory(RecvBuffer, sizeof(RecvBuffer));

    // here recv blocks for about 5 seconds, yeah, it reads only 100 bytes, tried with something like sizeof(RecvBuffer) as well.
    recv(hsocket, RecvBuffer, 100, 0);

    ....
}

I want to know how to solve this problem or which is the proper way to use keep-alive.

A: In your HTTP request, you send an additional \r\n\r\n which you do not include in your Content-Length, thus the data and and the length announced does not match. The HTTP standard says that :

When a Content-Length is given in a message where a message-body is
     allowed, its field value MUST exactly match the number of OCTETs in
     the message-body.

The MUST is important, it means the server is totally in its right to reject your request. The fact that you specified keep-alive can also mean that the server waits for a next, valid request. Since you only send 4 bytes, the server end up closing the connection anyway after 5s, and probably sends an error (this part is only speculation about what actually happens).


text:
Q: SQL injection dummy site error I am trying to use SQL injection on a dummy site I have made to check that I can hack in to it but it seems as though the site is secure despite me not sanitising it. When I run the query I would use to do the injection on phpMyAdmin everything seems fine and the query runs, so I am wondering why it won't work when I input the data in a simple form which uses the post method.
$myusername=$_POST['username'];
$mypassword=$_POST['password'];

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
   echo "login success";
}else {
   echo "login fail";
}

So can someone explain to me why this data is not prone to SQL injection? The line I am using to hack in to the site is the following
' or ' 1=1

And I add that into both the input fields

A: Your code is not secure:
$myusername=$_POST['username'];

$myusername = " ' or 1=1 LIMIT 1; -- "; // this will allow me to log in


text:
Q: tf.summary.scalar : TypeError: expected string or bytes-like object I am trying to learn how to work with tensorflow summary writers :
loss_summary = tf.summary.scalar(['logistic_loss', 'loss'],[train_logistic_loss, train_loss],
collections=[])

but i come with this error :

new_name = _INVALID_TAG_CHARACTERS.sub('_', name) TypeError: expected
  string or bytes-like object

Thanks,

A: tf.summary.scalar doesn't fit to output lists of tensors. You should output them separately:
logistic_loss_summary = tf.summary.scalar('logistic_loss', train_logistic_loss)
loss_summary = tf.summary.scalar('loss', train_loss)


text:
Q: How to allow a newly inserted user certificate with Apache 'SSLVerifyClient optional'? My web users are able to optionally use a Smart Card Certificate to identify themself via Firefox to my web server running Apache httpd 2.4.
For this I use SSLVerifyClient optional plus for speed SSLSessionCache and SSLSessionCacheTimeout
Sometimes the user forgot to insert his Smart Card.
Then he successfully creates a TLS-connection and see some content but is not logged in.
If he now enters his Smart Card and reloads the page, the browser is not trying to send the certificate from the Smart Card. (I think because there is no need for it because there is a valid SSL-session and so no renegotiation is started.)
If the user waits until the time of SSLSessionCacheTimeout has expired the browser sends the certificate....
So the question: How do I force the browser/server to renegotiation the SSL session?
Is there a trick?
A trick with a second server works:
If I put a link on my server "Click here for a new login attempt" which transfers the user to a different server (without SSLSessionCache) which requires a certificate and that server sets a cookie and redirect back to my original server, I am able to use that cookie to see that this is a logged in user.
But I am hoping there is a better way...
Any ideas?