text:
Q: Flot chart only displaying first series data I'm using flot and with the JSON returned, and the initialzation provided, only the first series is visible on the chart, however, the legend displays all 3 series labels.  Any Idea what I'm doing wrong?
var data = [];

    function onDataReceived(seriesData) {

        var options = {
            series: { stack: false,
                lines: { show: true, steps: false },
                bars: { show: false, barWidth: 0.5, align: 'center', horizontal: true },
                points: { show: true, radius: 3, symbol: 'circle' }
            },
            yaxis: { show: true, tickLength: 0 },
            xaxis: { tickSize: [1, "month"], tickLength: 0, mode: 'time', timeformat: '%b %y' },
            legend: { show: true, container: $('#@(ctlId)chartLegend'), noColumns: 3 },
            grid: { borderWidth: 0, hoverable: true, clickable: true }

        };

        var p = $.plot($('#@(ctlId)'), seriesData.seriesData, options);

And My MVC Handler:
return Json(new
        {
            axisNames = new List<string[]>() { },
            seriesData = new[]
        {
            new {
            color = "#e17009",
            label = "RN",
            data = new List<string[]>() {
                new string[] {DateTime.Parse("7/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "4.2"},
                new string[] {DateTime.Parse("8/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "4.8"},
                new string[] {DateTime.Parse("9/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.5"},
                new string[] {DateTime.Parse("10/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "5.0"},
                new string[] {DateTime.Parse("11/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "3.6"}
                }
            },
            new {
            color = "#ff0000",
            label = "RA",
            data = new List<string[]>() {
                new string[] {DateTime.Parse("7/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "3.2"},
                new string[] {DateTime.Parse("8/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "3.8"},
                new string[] {DateTime.Parse("9/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "3.5"},
                new string[] {DateTime.Parse("10/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.0"},
                new string[] {DateTime.Parse("11/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.6"}
                }
            }
            ,
            new {
            color = "#5c9ccc",
            label = "RA",
            data = new List<string[]>() {
                new string[] {DateTime.Parse("7/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.2"},
                new string[] {DateTime.Parse("8/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.8"},
                new string[] {DateTime.Parse("9/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.5"},
                new string[] {DateTime.Parse("10/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "1.0"},
                new string[] {DateTime.Parse("11/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.4"}
                }
            }
        }
        },
        JsonRequestBehavior.AllowGet);

A: I finally got this worked out.  Flot does not seem to want to render more than one series with the use of the stack: false option when it is set to false and you are also referencing the jquery.flot.stack.js plugin.  Removing the stack attribute in the code below resolved my issue.  If you are not referencing the stack plugin, you can keep the stack: false attribute and it will display the additional series properly as well.  Hope it helps someone.
The returned JSON was correct.
var data = [];

function onDataReceived(seriesData) {

    var options = {
        series: {
            lines: { show: true, steps: false },
            bars: { show: false, barWidth: 0.5, align: 'center', horizontal: true },
            points: { show: true, radius: 3, symbol: 'circle' }
        },
        yaxis: { show: true, tickLength: 0 },
        xaxis: { tickSize: [1, "month"], tickLength: 0, mode: 'time', timeformat: '%b %y' },
        legend: { show: true, container: $('#@(ctlId)chartLegend'), noColumns: 3 },
        grid: { borderWidth: 0, hoverable: true, clickable: true }

    };

    var p = $.plot($('#@(ctlId)'), seriesData.seriesData, options);


text:
Q: after insert | multiple tables MySQL So, I want to create a trigger that activates after an insert operation on any table in my database, and I have created a log table for each table in my database.
However, my professor says that I can create just one table and one trigger for 'AFTER INSERT, UPDATE, DELETE', but I don't have any idea how to do this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to insert text file to database table phpmyadmin I have a batchcode.txt which contains list of batch code.
645863
302422
430307
821773
599738
671768
732159

and so on
I have a table in my database which is called batchcode with fields 'id','batchcode'.
My problem is it wont insert my text file into my table called batchcode. I already did the import and select table but nothing works...
I need some help can anyone help me please.

A: You have to split txt file by new line
$file = fopen("batchcode.txt","r");

$file = explode("\n", $file);

foreach ($file as $value){
   $sql = "INSERT INTO batchcode( batchcode ) VALUES ('$value')";
}

A: Try this :
<?
$host= "localhost"; //These 7 lines to connect to database
$user= "root";
$pass= "";
$db="database_name";

$connect= mysql_connect($host,$user,$pass);
if (!$connect)die ("Cannot connect!");
mysql_select_db($db, $connect);

$file = fopen("batchcode.txt","r");  // Open the txt file for reading

while(! feof($file))
{
$line = fgets($file);
$sql = "INSERT INTO batchcode( batchcode ) VALUES ('$line')"; //Insert every read line from txt to mysql database
mysql_query($sql);
}
fclose($file);
?>

Note: Specify your database name in $db="database_name"; create table named batchcode, create columns named id and batchcode (idcolumn should have AUTO_INCREMENT property).


text:
Q: calculation by adding textview string values               for(int x = 1; x < i ; x++){

            int id =1000;
            int id1 = 2000;

            LinearLayout overall = new LinearLayout(this);
            overall.setOrientation(LinearLayout.VERTICAL);
            //LinearLayout
            LinearLayout llingredient = new LinearLayout(this);
            llingredient.setOrientation(LinearLayout.HORIZONTAL);
            llingredient.setLayoutParams(para4);

            LinearLayout llcal = new LinearLayout(this);
            llcal.setOrientation(LinearLayout.VERTICAL);

            LinearLayout llamt = new LinearLayout(this);
            llamt.setOrientation(LinearLayout.VERTICAL);

            //

            // ingreident name
             TextView ingredient = new TextView(this);
            ingredient.setId(x);
            ingredient.setGravity(Gravity.CENTER);
             ingredient.setLayoutParams(textcenter);

             // amount of ingredient
             TextView  amount = new TextView(this);
             TextView amt = new TextView(this);
             amount.setId(id);

             // cal for each ingredients
             TextView cal = new TextView(this);
             TextView calories = new TextView(this);

            calories.setId(id1);

             switch(x){

             case 1:

                 //ingreidents properties

                ingredient.setText("Eggs");
                ingredient.setTextSize(25);

                 //amt properties
                 amt.setText("Amt");
                 amount.setText(" 2 ");

                 // amt propertieses
                 amount.setTextSize(20);
                 amt.setTextSize(20);

                    cal.setText("Cal");
                    calories.setText("600");
                     // cal properties
                    cal.setTextSize(20);
                    calories.setTextSize(20);

                break;
             case 2:
                 //ingreidents properties

                ingredient.setText("Grilled Beef Steak");
                ingredient.setTextSize(25);

                 //amt properties
                 amt.setText("Amt(g)");
                 amount.setText("100");

                 // amt propertieses
                 amount.setTextSize(20);
                 amt.setTextSize(20);

                    cal.setText("Cal");
                    calories.setText("450");
                     // cal properties
                    cal.setTextSize(20);
                    calories.setTextSize(20);

                break;
             case 3:
                 //ingreidents properties

                ingredient.setText("Fried Bacon ");
                ingredient.setTextSize(25);

                 //amt properties
                 amt.setText("Amt(g)");
                 amount.setText("100");

                 // amt propertieses
                 amount.setTextSize(20);
                 amt.setTextSize(20);

                    cal.setText("Cal");
                    calories.setText("350");
                     // cal properties
                    cal.setTextSize(20);
                    calories.setTextSize(20);

                 break;
             case 4:
                 //ingreidents properties

                ingredient.setText("Oil");
                ingredient.setTextSize(25);

                 //amt properties
                 amt.setText("Amt(g)");
                 amount.setText("3");

                 // amt propertieses
                 amount.setTextSize(20);
                 amt.setTextSize(20);

                    cal.setText("Cal");
                    calories.setText("250");
                     // cal properties
                    cal.setTextSize(20);
                    calories.setTextSize(20);

                 break;
             case 5:
                 //ingreidents properties

                ingredient.setText(" lettuce ");
                ingredient.setTextSize(25);

                 //amt properties
                 amt.setText("Amt(g)");
                 amount.setText("100");

                 // amt propertieses
                 amount.setTextSize(20);
                 amt.setTextSize(20);

                    cal.setText("Cal");
                    calories.setText("90");
                     // cal properties
                    cal.setTextSize(20);
                    calories.setTextSize(20);

                 break;
             default:
                 //ingreidents properties

                ingredient.setText("error");
                ingredient.setTextSize(25);

                 //amt properties
                 amt.setText("");
                 amount.setText("");

                 // amt propertieses
                 amount.setTextSize(20);
                 amt.setTextSize(20);

                    cal.setText("");

                    calories.setText("0");
                     // cal properties
                    cal.setTextSize(20);
                    calories.setTextSize(20);

                 break;
             }

            TextView xc =(TextView) findViewById(id1);
             int b =  Integer.parseInt(xc.getText().toString()) ;
             sum += b;

                llamt.addView(amt);
                llamt.addView(amount);
                llamt.setLayoutParams(right);

                llcal.addView(cal);
                llcal.addView(calories);
                llcal.setLayoutParams(left);

                llingredient.addView(llamt);
                llingredient.addView(llcal);

                overall.addView(ingredient);
                overall.addView(llingredient);

             wrapper.addView(overall);

     id++;
     id1++;

        }

This codes runs in the on create method. Basically is a for loop that sums up all the value of the calories
The app keeps crashing everytime i try to enter this page. i tell me a null pointer exception. let me show u the log cat:
07-07 22:06:58.872: E/AndroidRuntime(12150): FATAL EXCEPTION: main

07-07 22:06:58.872: E/AndroidRuntime(12150): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.caloriecal/com.example.caloriecal.IngreCal}: java.lang.NullPointerException

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2183)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.app.ActivityThread.access$600(ActivityThread.java:144)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.os.Handler.dispatchMessage(Handler.java:99)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.os.Looper.loop(Looper.java:137)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.app.ActivityThread.main(ActivityThread.java:5086)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at java.lang.reflect.Method.invokeNative(Native Method)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at java.lang.reflect.Method.invoke(Method.java:511)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-07 22:06:58.872: E/AndroidRuntime(12150):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at dalvik.system.NativeStart.main(Native Method)
07-07 22:06:58.872: E/AndroidRuntime(12150): Caused by: java.lang.NullPointerException

07-07 22:06:58.872: E/AndroidRuntime(12150):    at com.example.caloriecal.IngreCal.onCreate(IngreCal.java:260)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.app.Activity.performCreate(Activity.java:5104)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)

07-07 22:06:58.872: E/AndroidRuntime(12150):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2147)

07-07 22:06:58.872: E/AndroidRuntime(12150):    ... 11 more

A: The problem is in your TextView's like:
TextView xc =(TextView) findViewById(id1);

The id1 you are using should be in the form R.id.theIdYouHavePlacedInYourXML
I see you are using
int id1 = 2000;

but you should never use any value that is defined outside R.id as a parameter to findViewById().
So I guess you have a layout file with a TextView and you inflate this layout inside your main activity (I assume that is IngreCal).
To fix this you should just assign an id to the TextView (in the xml file) and then use that id in your java code. So if you have
    <TextView
        android:id="@+id/yourIdIsHere"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="5"/>

then this would be your correct call:
TextView xc =(TextView) findViewById(R.id.yourIdIsHere);

You should do the same for other TextView's as well.


text:
Q: Alinhar verticalmente ao centro itens do rodapé Estou tentando alinhar verticalmente ao centro, itens do meu rodapé, só que pela imagem ocupar um height maior fica desalinhado, Como resolver?

Entre em contato:
(99) 99999-9999

Endereço:
 Rua tal , 123
 Bairro - Cidade - Estado

© Todos os direitos reservados.

A: Podes resolver a questão declarando uma altura para as colunas da primeira linha do teu rodapé e depois com um pouco de CSS e a ajuda da propriedade transform, alinhar verticalmente os parágrafos:
.panel-footer .cell{
  height:120px;                 /* mesma altura da imagem */
}
.panel-footer p{
  position: relative;           /* relativo para não sair do seu local com a próxima declaração */
  top: 50%;                     /* empurrar para iniciar ao meio do seu contentor */
  transform: translateY(-50%);  /* puxar a distancia equivalente a metade da sua altura */
}

Exemplo

.panel-footer .cell{
  height:120px;
}
.panel-footer p{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

Entre em contato:
(99) 99999-9999

Endereço:
 Rua tal , 123
 Bairro - Cidade - Estado

© Todos os direitos reservados.

A: Use display: table-cell e vertical-align: middle


text:
Q: SQL: Delete rows in a table where one field's value is lesser than group average For now, I am first running the following query:
select group_name, avg(numeric_field) as avg_value, count(group_name) as n from table_name group by group_name order by n desc;

Suppose I get output:
group_name     | avg_value | n
----------------------------------------
nice_group_name| 1566.353  | 2034
other_group    | 235.43    | 1390
.
.
.

I am then deleting records in each group one by one manually using the following query for each group:
delete from table_name where group_name = 'nice_group_name' and numeric_field < 1567;

Here 1567 is the approximate avg_value for nice_group_name.
How can I run the second query for all rows of the result of first query automatically?

A: You can use a correlated subquery:
delete from table_name
    where numeric_field < (select avg(t2.numeric_field)
                           from table_name t2
                           where t2.group_name = table_name.group_name
                          );

For performance, you want an index on tablename(group_name, numeric_field).
If you have few groups, you might find this more efficient:
with a as (
      select group_name, avg(numeric_field) as anf
      from table_name
      group by group_name
     )
delete from table_name
    where numeric_field < (select a.anf from a where a.group_name = table_name.group_name);

A: If table_name has some primary key field (say id) then use the following:
alter table table_name rename to bak;
create temp table avg_val as
    select group_name as g, avg(numeric_field) as a from bak
    group by group_name;
create table table_name as
    select * from bak where id in (
        select bak.id from
        avg_val join bak on bak.group_name = avg_val.g
        where avg_val.a <= bak.numeric_field
);

Check table_name. If all has went well you can delete the backed up old table:
drop table bak;

Briefly, the steps are:

*

*Rename the original table

*Create a temporary table of average value for each group

*Create a new table with all rows from original table where numeric_field is not less than average for that group.

*delete the renamed original table.


text:
Q: How can I identify adjacent shapes in SVG? I need to identify adjacent shapes in an SVG drawing where the definition of adjacent is: two shapes A and B are adjacent if more than one point on the path defining shape A is closer than e (an arbitrary threshold) to a point on shape B.
See image below - shape 1 is adjacent to shape 2, and shape 2 is adjacent to shape 3, while shapes 1 and 3 are not adjacent.

The image represents a tile, the production process of which does work if two adjacent shapes are made from the same color. For the curious, see the video for a look at the production process.
Short of coding things by hand, how can I check if two shapes are adjacent, so that I can ensure that (in an app) they won't be colored in the same way?
I have thought of 2 approaches:

*

*enlarge the shapes by a certain amount (by offsetting them, for example) and then see if they overlap with each other

*divide the image in a grid of small squares and check if any square contains more than shape

I expect that grid size or offset parameters will have to be set carefully to avoid that shapes 4 and 5 are identified as adjacent.
Is there a better approach than these two?
I plan to build this in SVG + javascript, using paper.js for calculating overlaps.


text:
Q: Change the default systemFont used by controls I have a big App and need to change the Font but I don't want to touch every Label, Textfield and so on. How can I access the "systemFont" used in IB and in [UIFont systemFontOfSize:x]?
I already tryed this one: iOS 5: Curious about UIAppearance but that's not the solution, cause I have different FontSizes and Bold/Regular all over my App and I can't set it overall.
Can I set it via UIApplication or somewhere in InfoPlist?

A: You can create Category for UILabel, UITextField and UIButton and can in the "awakeFromNib" method, you can just change the font name to new font and can just keep the same size. I added code for UILabel category below. You can do the same for UITextField and UIButton.
@implementation UILabel (CustomFontLabel)

-(void)awakeFromNib{
    [super awakeFromNib];
    float size = [self.font pointSize];
    NSString *stringfontstyle=self.font.fontName;
    if([stringfontstyle rangeOfString:@"Bold"].location != NSNotFound) {
        self.font = [UIFont fontWithName:@"MyCustomFont-Bold" size:size];
    }
    else if ([stringfontstyle rangeOfString:@"Italic"].location != NSNotFound) {
        self.font = [UIFont fontWithName:@"MyCustomFont-Italic" size:size];
    }
    else if ([stringfontstyle rangeOfString:@"Medium"].location != NSNotFound) {
        self.font = [UIFont fontWithName:@"MyCustomFont-Medium" size:size];
    }
    else {
        self.font = [UIFont fontWithName:@"MyCustomFont" size:size];
    }
}

@end

A: Actually the answer from Paramasivan is only partially right. The problem is that if for example UILabel were to implement awakeFromNib it would never get called. Your category would override this method. You can either swizzle or override it like shown here:
http://www.mikeash.com/pyblog/friday-qa-2010-01-29-method-replacement-for-fun-and-profit.html


text:
Q: Log browser settings, rendered html on client's browser. We regularly receive reports about different client side errors especially our users seeing "this page contains secure and nonsecure items" warnings when using our site. We know that the various screens in our site contains all secure elements. If the client receives a "this page contains secure and nonsecure items" warning, is there a way to log
a. the rendered html on the client's browser.
b. The browser settings that the client might have. eg: in Internet Explorer, Tools=> Internet Options=> Security Tab => the "Custom Level" button => Display mixed content option.

A: I think there is no way to track IE alerts, but as described here "MVC Bundling with HTTPS IE7" you could have some contents or scripts in your page that come from an HTTP request (not secure), and some others coming from HTTPS (secure).
Are you maybe providing pages from HTTPS and you have some scripts include from HTTP?


text:
Q: Replacing a row in 2d numpy array I am trying to replace a row in a 2d numpy array.
array2d = np.arange(20).reshape(4,5)
for i in range(0, 4, 1):
    array2d[i] = array2d[i] / np.sum(array2d[i])

but I'm getting all 0s:
 [[0 0 0 0 0]
     [0 0 0 0 0]
     [0 0 0 0 0]
     [0 0 0 0 0]]

The expected result is:
[[0 0.1 0.2 0.3 0.4]
 [0.14285714 0.17142857 0.2        0.22857143 0.25714286]
 [0.16666667 0.18333333 0.2        0.21666667 0.23333333]
 [0.17647059 0.18823529 0.2        0.21176471 0.22352941]]

A: The reason you are getting 0's is because the array's dtype is int but the division returns floats in range 0 to 1 and because you modify the rows in-place they are converted to integers (i.e. to 0 in your example). So to fix it use array2d = np.arange(20, dtype=float).reshape(4,5).
But there is no need for the for-loop:
array2d = np.arange(20).reshape(4,5)
array2d = array2d / np.sum(array2d, axis=1, keepdims=True)

Note that here I didn't specify the dtype of the array to be float, but the resulting array's dtype is float because on the second line we created a new array instead of modifying the first array in-place.
https://numpy.org/doc/stable/user/basics.indexing.html#assigning-values-to-indexed-arrays


text:
Q: I want to know where does the value go after deleting from an array? lets say I've an array
int size=6;
int a[size]={0,1,2,3,4,5};

and I wanted to delete k=3 element.
for(i=k;i<size-1;i++)
a[k]=a[k+1];
size=size-1;

here I've just removed the element from index k, for sure that value would not be present in the array, but if not in the array then where is the data, that value.

A: Nothing is deleted.
The line a[k]=a[k+1]; sets the value of a[k] to the value of a[k+1].
So if the array starts with {0,1,2,3,4,5} and k is 3, then afterwards the array holds {0,1,2,4,4,5}.

A: In C language, an array has a fixed size. That means that you can neither add nor remove elements to an array. You can only re-write them.
What is closest to an array of dynamic size is a dynamic array which can be obtained by malloc. It can later be resized by realloc but:

*

*the standard library if free to ignore any shrinking call and keep the array with its maximum size

*released memory can be returned to the operating system to be accessible to other processes or can remain stuck to the current process

*an extending call can involve a full copy of the existing elements

Reallocing dynamic arrays is indeed a common idiom in C language, but you must be aware of its limits an not abuse it. In your example it would be overkill.

Dynamic allocated memory has to be released by free. After calling free:

*

*the pointer keeps its previous value and is called a dangling pointer because it points to unallocated memory and dereferencing it explicitely invokes Undefined Behaviour (the hell for C programmers...)

*the implementation of the standard library is free to do what it wants with the released memory:

*

*it can be returned to the Operating System

*if can be recycled to become available to later malloc calls or even become no longer usable. The underlying algorithm used to manage the dynamic memory is not specified by the standard

That being said a common algorithm is to exchange pages of a certain size with the OS, and allocate memory for the program from those pages. The empty blocs are often handled as a list, and a new released bloc is concatenated with an adjacent free bloc to try to have as large blocs as possible. And only when a page is contained in a free bloc, it can be returned to the OS. But this is the problem of the implementer of the standard library, not the one of the C programmer.

A: You cannot "delete" items in an array, just overwrite them with other data. C is close to the hardware and in physical RAM there is no "deleted" state of a cell, it must always hold a value.
Deleting one item is therefore done by moving all items behind the one you wish to delete one step forward (which is quite inefficient to do). The allocated size will still be the same though. So you'll need a counter variable to keep track of the actual data size used.

*

*Given an array int array[]={0,1,2,3,4,5};

*Then the number of items is sizeof array / sizeof *array;
size_t items = sizeof array / sizeof *array;

items will be the above mentioned counter variable.

*We wish to remove one item at a certain index:
size_t index = 3;

*The size of the chunk behind the item you wish to remove is then expressed as:
size_t size_to_move = (items-index-1) * sizeof *array;

Which on a 32 bit computer is (6-3-1) * 4 = 8 bytes.

*We are moving data inside the same array, which means there are overlapping memory segments. In case of overlaps we can't use memcpy, so we have to used the specialized function memmove instead, which uses temporary buffers internally to deal with overlaps.
Complete example:
#include <stdio.h>
#include <string.h>

int main()
{
  int array[]={0,1,2,3,4,5};
  size_t items = sizeof array / sizeof *array;
  size_t index = 3;
  size_t size_to_move = (items-index-1) * sizeof *array;

  memmove(&array[index], &array[index+1], size_to_move);
  items--;

  for(size_t i=0; i<items; i++)
  {
    printf("%d ", array[i]);
  }
}

Output:
0 1 2 4 5

Note that if we don't decrease the item counter with item--, we would get 0 1 2 4 5 5. The allocated array size remains 6 so we can still access the last item, and that one used to hold a 5, so it still contains it, because items aren't actually "moved" but copied.


text:
Q: Can anybody help me adequate this code (PHP, mysqli_stmt::get_result / mysqli_stmt::bind_result and mysqli_stmt::fetch This a multi login system, so when a user logs in, they can only see what is meant for them to see, only the admin can see all of the user's info.
This works at home, but when I take it to the server it won't work because of outdated PHP libraries. I know at some point that would have to be updated but it is out of my hands. I hope someone can help me out with this.
I can't use mysqli_stmt::get_result (because of outdated PHP). Can anybody help me adequate this code with mysqli_stmt::bind_result and mysqli_stmt::fetch?
To update libraries in PHP is not an option at this point.
<?php
    session_start();

    $conn = new mysqli("localhost","root","root","numbers");

    $msg="";

    if(isset($_POST['login'])){
        $username = $_POST['username'];
        $password = $_POST['password'];
        $password = sha1($password);
        $userType = $_POST['userType'];

        $sql = "SELECT * FROM users WHERE username=? AND password=? AND user_type=?";

        $stmt=$conn->prepare($sql);
        $stmt->bind_param("sss",$username,$password,$userType);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();

        session_regenerate_id();
        $_SESSION['username'] = $row['username'];
        $_SESSION['role'] = $row['user_type'];
        session_write_close();

        if($result->num_rows==1 && $_SESSION['role']=="user1"){
            header("location:user1.php");
        }
        else if($result->num_rows==1 && $_SESSION['role']=="user2"){
            header("location:user2.php");
        }
        else if($result->num_rows==1 && $_SESSION['role']=="user3"){
            header("location:user3.php");
        }
        else if($result->num_rows==1 && $_SESSION['role']=="admin"){
            header("location:admin.php");
        }
        else {
            $msg = "Username and/or password incorrect!";
        }
    }
?>


text:
Q: Searching for "PHP ===" is worthless on stackoverflow
Possible Duplicate:
We need to be able to search for punctuation (symbols)

There's a recent question asking the difference between PHP's == and ===:
What's the difference between == and ===?
A bunch of people downvoted the question and asked if the OP did any googling.  However, googling for "php == vs ===" or "php ===" turns up front page results which are not very helpful.  Even worse, searching for those strings on stackoverflow is not helpful at all.  It seems that the search function completely ignores "==" and "===".  Looking in the "search tips" page (https://stackoverflow.com/search) doesn't mention anything about it.
I think that on a programming site, queries shouldn't ignore common programming operators like == and ===.


text:
Q: passing dropdownlist value to controller I have dropdown list which display data from the database. I get database data in drop down list but after selecting value in drop down list the selected value I want to pass in controller, then I want to display all detail data of that selected value. But clicking on submit button the selected value of dropdown list is not getting passed to controller.
this is my code
View: Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ApricaCRMEvent.Models.CRM.DatabaseEntities.CRM_Doctor_Request>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    SearchIndex
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

SearchIndex

    <%--

          <% Html.RenderPartial("SelectDoctors"); %>

--%>

Search by MDLNo

     <% using (Html.BeginForm())
        { %>

         <%: Html.ValidationSummary(true, "Profile Updation was unsuccessful. Please correct the errors and try again.") %>

        Select MDLno

        <%= Html.DropDownList("ddlMDLNo", ViewData["MDLno"] as SelectList, "--Select One--", new { onchange = "TestFun()" })%>
        <%: Html.TextBoxFor(m => m.Request_For_Id)%>

         <input type="submit" value="search" name="SearchMDLNo" />
    <% } %>

 <% Html.RenderPartial("ListDoctors"); %>

</asp:Content>

Controller: SearchMDLNoController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ApricaCRMEvent.Models.CRM.DataLayer;
using ApricaCRMEvent.Models.CRM.DatabaseEntities;

namespace ApricaCRMEvent.Controllers
{
    public class SearchMDLNoController : Controller
    {
        CRM_Doctor_Request mdlnoObj = new CRM_Doctor_Request();

        public ActionResult Index()
        {
            ViewData["MDLno"] = new SelectList(SearchMDLNoDL.getAllMDLno(), "Request_For_Id", "Request_For_Id");
            return View();
        }

        [HttpPost]
        public ActionResult Index(CRM_Doctor_Request model)
        {
            ViewData["MDLno"] = new SelectList(SearchMDLNoDL.getAllMDLno(), "Request_For_Id", "Request_For_Id");

            //CRM_Doctor_Request mdlnoObj = SearchMDLNoDL.getMDLData("GJ04_D023");
            //mdlnoObj = SearchMDLNoDL.getMDLData(model.Request_For_Id);
            return View();
        }
        public ActionResult getMDLNoDetails(string id)
        {
            mdlnoObj=SearchMDLNoDL.getMDLData(id);
            return View();
        }
        public ActionResult ListDoctors()
        {
            return View(mdlnoObj);
        }

    }
}

this is partial view and in this view selected drop down value .. detail data will be display
partical View : ListDoctors.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ApricaCRMEvent.Models.CRM.DatabaseEntities.CRM_Doctor_Request>" %>

<%: Html.DisplayFor(m => m.Request_For_Id) %>

            Request_For_Id

            Territory

            Estimated_Amount

            Actual_Amount

            Date_Created

            Compute_CRM_State

            Compute_Event_Type

            <%: Html.DisplayFor(m => m.Request_For_Id) %>

            <%: Html.DisplayFor(m => m.Territory) %>

            <%: Html.DisplayFor(m => m.Estimated_Amount) %>

            <%: Html.DisplayFor(m => m.Actual_Amount) %>

            <%: Html.DisplayFor(m => m.Date_Created) %>

            <%: Html.DisplayFor(m => m.Compute_Service_State) %>

            <%: Html.DisplayFor(m => m.Compute_Event_Type) %>

by selecting value in drop down list and clicking on submit button value is not getting passed. In Index.aspx I have tried some javascript code but it does not work.

I have changed something in code. And now this is working.
View: Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ApricaCRMEvent.Models.CRM.DatabaseEntities.CRM_Doctor_Request>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    SearchIndex
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

SearchIndex

    <%--

          <% Html.RenderPartial("SelectDoctors"); %>

--%>

Search by MDLNo

     <% using (Html.BeginForm())
        { %>

         <%: Html.ValidationSummary(true, "Profile Updation was unsuccessful. Please correct the errors and try again.") %>

        Select MDLno

        <%= Html.DropDownList("ddlMDLNo", ViewData["MDLno"] as SelectList, "--Select One--", new { onchange = "TestFun()" })%>
        <%: Html.TextBoxFor(model => model.Request_For_Id) %>

         <input type="submit" value="search" name="SearchMDLNo" />
    <% } %>

<%--
 <% Html.RenderPartial("ListDoctors"); %>
--%>

    <fieldset>
    <legend>CRM_Doctor_Request</legend>

Territory

        <%: Html.DisplayFor(model => model.Territory) %>

CRM_Request_For_Type_Id

        <%: Html.DisplayFor(model => model.CRM_Request_For_Type_Id) %>

Request_For_Id

        <%: Html.DisplayFor(model => model.Request_For_Id) %>

Requestor

        <%: Html.DisplayFor(model => model.Requestor) %>

Division_Id

        <%: Html.DisplayFor(model => model.Division_Id) %>

Suggester

        <%: Html.DisplayFor(model => model.Suggester) %>

Estimated_Amount

        <%: Html.DisplayFor(model => model.Estimated_Amount) %>

Actual_Amount

        <%: Html.DisplayFor(model => model.Actual_Amount) %>

Priority

        <%: Html.DisplayFor(model => model.Priority) %>

CRM_Service_Type_Id

        <%: Html.DisplayFor(model => model.CRM_Service_Type_Id) %>

Deadline

        <%: Html.DisplayFor(model => model.Deadline) %>

Executed_Date

        <%: Html.DisplayFor(model => model.Executed_Date) %>

Entry_Done_By

        <%: Html.DisplayFor(model => model.Entry_Done_By) %>

Date_Created

        <%: Html.DisplayFor(model => model.Date_Created) %>

Date_Modified

        <%: Html.DisplayFor(model => model.Date_Modified) %>

Event_Type_Id

        <%: Html.DisplayFor(model => model.Event_Type_Id) %>

Compute_Event_Type

        <%: Html.DisplayFor(model => model.Compute_Event_Type) %>

CRM_State_Id

        <%: Html.DisplayFor(model => model.CRM_State_Id) %>

Compute_CRM_State

        <%: Html.DisplayFor(model => model.Compute_CRM_State) %>

Service_State_Id

        <%: Html.DisplayFor(model => model.Service_State_Id) %>

Compute_Service_State

        <%: Html.DisplayFor(model => model.Compute_Service_State) %>

Is_Active

        <%: Html.DisplayFor(model => model.Is_Active) %>

Comment

        <%: Html.DisplayFor(model => model.Comment) %>

</fieldset>

</asp:Content>

Controller: SearchMDLNoController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ApricaCRMEvent.Models.CRM.DataLayer;
using ApricaCRMEvent.Models.CRM.DatabaseEntities;

namespace ApricaCRMEvent.Controllers
{
    public class SearchMDLNoController : Controller
    {
        CRM_Doctor_Request mdlnoObj = new CRM_Doctor_Request();

        public ActionResult Index()
        {
            ViewData["MDLno"] = new SelectList(SearchMDLNoDL.getAllMDLno(), "Request_For_Id", "Request_For_Id");
            return View();
        }

        [HttpPost]
        public ActionResult Index(CRM_Doctor_Request model)
        {
            ViewData["MDLno"] = new SelectList(SearchMDLNoDL.getAllMDLno(), "Request_For_Id", "Request_For_Id");

            //CRM_Doctor_Request mdlnoObj = SearchMDLNoDL.getMDLData("GJ04_D023");
            //mdlnoObj = SearchMDLNoDL.getMDLData(model.Request_For_Id);
            mdlnoObj = SearchMDLNoDL.getMDLData(model.Request_For_Id);
            return View(mdlnoObj);
        }
    }
}

A: Try this :
$.getJSON("/SearchMDLNo/getMDLNoDetails",{id : mdlno}, function (data) {
         alert(data.Request_For_Id);
});

This should work for you

Then in your controller change it like this:
    [HttpPost]
    public ActionResult getMDLNoDetails(string id)
    {
        mdlnoObj=SearchMDLNoDL.getMDLData(id);
        return Json(true);
    }


text:
Q: android facebook sdk - set permissions for openActiveSession I am trying to integrate Facebook SDK to an android app. I got the code from Facebook manual. It uses Session.openActiveSession and then request a graph user. How could I request for more permissions without using LoginButton class?
Session.openActiveSession(this, true, new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        onSessionStateChange(session, state, exception);

        if (session.isOpened()) {
            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    if (user != null) {
                        // got user graph
                    } else {
                        // could not get user graph
                    }
                }
            });
        }
    }
});

Thank you.

A: This solves the problem using opensession and extended persmission just once. Facebook SDK 3.5
Session s = new Session(this);
Session.setActiveSession(s);
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("basic_info","email"));
request.setCallback( new Session.StatusCallback() {
         // callback when session changes state
         @Override
         public void call(Session session, SessionState state, Exception exception) {
             if (session.isOpened()) {
                 Request.newMeRequest(session, new Request.GraphUserCallback() {
                         @Override
                         public void onCompleted(GraphUser user, Response response) {
                             if (user != null) {
                                 Toast.makeText(getApplicationContext(), "User email is:"+user.getProperty("email"), Toast.LENGTH_SHORT).show(); }
                             else {
                                 Toast.makeText(getApplicationContext(), "Error User Null", Toast.LENGTH_SHORT).show();
                             }
                         }
                 }).executeAsync();
             }
         }
}); //end of call;

s.openForRead(request); //now do the request above

A: Try this:
mCallback = new Session.StatusCallback() {...}; // the code you already have

Session.OpenRequest request = new Session.OpenRequest(mContext);
request.setPermissions(Arrays.asList("email", "user_birthday"));
request.setCallback(mCallback );

// get active session
Session mFacebookSession = Session.getActiveSession();
if (mFacebookSession == null || mFacebookSession.isClosed())
{
    mFacebookSession = new Session(mContext);
    Session.setActiveSession(mFacebookSession);
}
mFacebookSession.openForRead(request);


text:
Q: TaskCreationOptions for an async Task Method I have a method returning an async Task. I wish to call this but I'd like to customise the TaskCreationOptions sent to it, I'm trying to work out best practise for this, or how I should modify my approach?
Sample..
void Main(){
    _runTask=Test(); // I wish to provide creation options here, ie LongRunning, and possibly also a cancellation token
}
async Task Test()
{
    await Task.Delay(10);
}

A:
I wish to provide creation options here, ie LongRunning, and
  possibly also a cancellation token

You can't customize TaskCreationOptions on the Task object returned by an async method. Essentially, it doesn't make sense: you don't create the initial Task here, Task.Delay does. You can think of it like this:
Task Test()
{
    var scheduler = SynchronizationContext.Current != null ?
        TaskScheduler.FromCurrentSynchronizationContext() :
        TaskScheduler.Current;

    return Task.Delay(10).ContinueWith((t) => { },
        CancellationToken.None,
        TaskContinuationOptions.None, scheduler);
}

Now, that's possible to control TaskContinuationOptions for the task returned by ContinueWith (including TaskContinuationOptions.LongRunning), but not TaskCreationOptions.
You can however provide a cancellation token:
async Task Test(CancellationToken token)
{
    await Task.Delay(10, token);
    // ...
    token.ThrowIfCancellationRequested();
}

A: You can't, and you don't need to. Neither of those options do what you think they do.
LongRunning is useless for async workloads; it would (in the current implementation) spin up a separate dedicated thread just to execute the first part of the async method (until the first await of an incomplete operation), and then resume the async method as regular work queued to the thread pool, ignoring that dedicated thread for the rest of the method.
Passing a CancellationToken to the task constructor is unnecessary; the only benefit it would get you in async code is that the code wouldn't start if the token is already canceled. And you can do the same thing by just checking it yourself before calling the async method. The proper way to handle cancellation with async methods is described in the Task-based Asynchronous Pattern documentation:
async Task TestAsync(CancellationToken cancellationToken)
{
  await Task.Delay(10, cancellationToken);
}


text:
Q: asp.net HyperLink unable to locate url Below is the asp:HyperLink which the hyperlink wasn't correctly bind:
<asp:HyperLink runat="server" Text="Go to project" NavigateUrl='<%#"~/Project/ProjectMaster.aspx?ProjectID=" + projectID %>'></asp:HyperLink>

Why the hyperlink was disabled (Like the below image) and how to bind URL correctly?

A: It depends on where you use this hyperlink.
If it is a part of the page or user control then it should look like this:
<asp:HyperLink runat="server" Text="Go to project" NavigateUrl='~/Project/ProjectMaster.aspx?ProjectID=<%= projectID %>' />

If it is a part of repeater or some other template container, then you chould use Eval or Bind methods
<asp:HyperLink runat="server" Text="Go to project" NavigateUrl='~/Project/ProjectMaster.aspx?ProjectID=<%# Eval("projectID") %>' />

A: Assign some id to hyperlink and give NavigateUrl in code behind. Suppose you have hyperlink id hlProject
hlProject.NavigateUrl = "~/Project/ProjectMaster.aspx?ProjectID=" + projectID;


text:
Q: Conditional with a preference I have two items A and B. I have an object with the methods hasA(): bool and hasB(): bool.
I also have a variable $preference that can be A or B.
I want to

*

*Select the item that is both available and preferred if it exists.

*If the preferred item is not available, select the one that is available.

*If neither are available, return an error.

What would be the cleanest way to do this?


text:
Q: Entity Framework - Updating entity's few columns only I need some more understanding of how Entity Framework works. I have implemented code which is running ok and doing the job.
But I need to know that it is the good way or not.
I have a table with 8 columns, say
Table1

*

*Column1 (pk)

*Column2, Column3, Column4, Column5, Column6, Column7, Column8

Now when I click a button, I need to insert (if new) or update (for existing record) first 6 columns.
And on the same button click event, as part of the same process, I will call a stored procedure (with a parameter of primary key id, Column1) that will fetch these 6 columns values in the stored procedure itself and will do some calculations based on six column values and return two new values which I need to update in Column7, Column8.
So, process will be:

*

*New record: insert (six columns data), calculations (call stored procedure), update (last 2 column)

*Existing record: update (six columns data), calculations (call stored procedure), update(last 2 column)
Now, for insert, I use
_dbContext.Table1.Add(entity);
 _dbContext.SaveChanges();

For existing record update (of first 6 columns), I use
//code - Entity property values are updated with new ones
_dbContext.Table1.Attach(entity);
_dbContext.Entry(entity).State = EntityState.Modified;
_dbContext.SaveChanges();

For last update, Column7, Column8, I use
var entity = GetById(Id);

if (entity != null)
{
    entity.Column7 = value1;
    _dbContext.Entry(entity).Property(t => t.Column7).IsModified = true;
    entity.Column8 = value2;
    _dbContext.Entry(entity).Property(t => t.Column8).IsModified = true;

    _dbContext.SaveChanges();
}

I am not sure why I need not to attach entity for last update. Is it due to I have called GetById method for same table just above that?
Without attaching entity how it updates columns? (if I attach entity it gives error saying already being tracked)
Also, I have to call GetById multiple times to get record for both updates (in existing record scenario). Any other solution for that?

A: for that you can use MapToModel method
here is example
//code - Entity property values are updated with new ones
var newEntity= new Entity
{
    Id = p.Id, // the Id you want to update
    Column1= ""  // put value for column/s that you need to update
};
newEntity.MapToModel(oldEntity);
_dbContext.SaveChanges();

A: IMHO I don't think you need to specify IsModified for each property if you fetch through the Context.
EF Context will automatically track Entities unless you change the default behavior
EF knows which entities are changed after loading from the database,hence it will be only updated.
Assuming GetById is fetching the data from data-store.
var entity = GetById(Id);

if (entity != null)
{
    entity.Column7 = value1;
    entity.Column8 = value2;
    _dbContext.SaveChanges();
}

Detect Changes
Similar Question


text:
Q: Pull Post Into PHP Page with Embedded YouTube Video Currently in WordPress 3.5 when you create a new post you can simply paste in a YouTube URL and on the live post this gets converted into an embedded video.  This is working great for me within Wordpress, however I'm pulling the wordpress post into my non-WP site using get_post and the URL comes over instead of embedded video.
I'm trying to determine the best method to make any YouTube video link that is found in the content of a post, show as embedded video.
Not sure if there is a function I can borrow from Wordpress on my page (and how I would do that) or if need to parse the content somehow with PHP to find video links.  Not sure how to do that either, given that each video is going to have a different url parameter at the end such as: http://www.youtube.com/watch?v=abcdefghijk
Any thoughts on this?

A: Try to apply filters:
$posts = get_posts(array('suppress_filters' => false));

A: I stumbled across this function:
    function get_string_between($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");

echo $parsed; // (result = dog)

I used this as a basis to write an advanced search and replace.  this may have been doable with REGEX, I'm not sure, but this has served the purpose.  Thanks all!


text:
Q: How to change assets cache directory in Yii2? I am begin to learn Yii2 and installed Advanced version. Add extensions. Configure application and load to server. After sometime I noticed that Yii save the assets cache to directory web/assets. But is logical use this directory for real assets. Because I use Twig web/assets uses for js and css files.
And I start search how to change assets cache directory, but not found this. Exist several questions on stackoverflow about like themes, but answer was not found.
Yii2 save ti this dir cache of bootstrap, jquery and any assets.
How to change this directory to web/cache?

A: You can configure the assets directory using the basePath and baseUrl properties of the Asset Manager. There's is a description in the documentation. you can do this in your config file, so
return [
// ...
    'components' => [
        'assetManager' => [
            'baseUrl' => 'your/url',
            'basePath => 'your/path'
        ],
    ],
];


text:
Q: Sql statment where in doesn't work select TO_CHAR(TRUNC(SYSDATE),'DD MONTH,YYYY'),a.appl_no,a.assigned_to,c.trading_name co_name, ' ' co_name2, d.bank_acct_no  credit_acct_no, d.bank_no credit_bank_no, d.bank_branch_no credit_branch_no,a.service_id
    from newappl a, newappl_hq b, newappl_ret c, newappl_ret_bank d where a.appl_no = c.appl_no and c.ret_id= d.ret_id and a.appl_no=(select appl_no from newappl where appl_no='224') and c.outlet_no in ('1','2') and rownum=1

Why the out put for above statment is only one row while I have 1 & 2 for following statement
select c.outlet_no from newappl_ret c where appl_no = '224'

A: its hard to say when you dont see data stored in db but try this one:
select c.outlet_no from mss_t_newappl_ret c where appl_no = 224

check if in the column appl_no there isnt any spacebar
maybe this?
and a.appl_no IN (select appl_no from newappl where appl_no='224')

or delete this expression
and rownum=1


text:
Q: Retrieving SQL Server Full Text Index terms Using Lucene, one can retrieve the terms contained within in an index, i.e. the unique, stemmed words, excluding stop-words, that documents in the index contain. This is useful for generating autocomplete suggestions amongst other things. Is something similar possible with MS SQL Server full text indices?

A: I agree that this information (words in the index, stemmed words, etc.) is usefull - and if SQL Server is serious about offering a serch platform, this information needs to be exposed. It's really not available in previous versions, as far as I can tell. However, the game changes in SQL Server 2008.
SQL Server 2008 offers new dynamic management views that offer this metadata for full text. Pay particular note to sys.dm_fts_parser and sys.dm_fts_index_keywords.
The sys.dm_fts_parser view takes in a phrase, along with a couple of other parameters and outputs a table showing a row set, showing stemmed versions of the individual words after the word breaker has deemed them as separate words.
MSDN gives the example of this query against the view:
SELECT * FROM sys.dm_fts_parser (' "The Microsoft business analysis" ', 1033, 0, 0)

To get the keywords, you can use sys.dm_fts_index_keywords.
I hope that points you in the right direction. Cheers.

A: You can use the new system view in SQL Server 2008 to get you the terms and count of occurrences, is this what you want?
sys.dm_fts_index_keywords_by_document
(
    DB_ID('database_name'),
    OBJECT_ID('table_name')
)

You need to supply the db_id and object_id of the fulltext table. This is the MSDN link for this: sys.dm_fts_index_keywords_by_document.

A: With the following you can take the table name and column name as variables.
It will work on the current database that it is run, omit end of file results and order the results descending by number of occurrences.
Note that full text indexing must be enabled on that table and column
DECLARE @TableName NVARCHAR(200) = 'MyTable'
DECLARE @ColumnName NVARCHAR(200) = 'MyColumn'

SELECT DISTINCT(display_term), occurrence_count FROM sys.dm_fts_index_keywords_by_document
(
    DB_ID(),
    OBJECT_ID(@TableName)
)
WHERE column_id =
(
    SELECT TOP 1 col.column_id FROM sys.objects obj
    INNER JOIN sys.columns col ON col.object_id = obj.object_id
    WHERE obj.name = @TableName
    AND col.name = @ColumnName
)
AND keyword != 0xFF
ORDER BY occurrence_count DESC

A: sys.dm_fts_index_keywords gives returns the list of indexed terms, with additional statistics, not the list of noise words which is retruned thanks to sys.fulltext_stopwords.


text:
Q: How can I include my folder header in my index.php I'm developing a web application with apache2 and mySQL using LAMP.
I have a basic page index.php and i would like to include my header.php file located in 'header_footer/header.php'
I tried using <?php include("./header_footer/header.php");?> but it doesn't work.
It works when i put the header.php file in the same folder as my index.php with <?php include("./header.php");?> but i would like to have it in a different folder.
Does anyone have an idea why it's working on one case but not on the other ?

A: See:
include path
ini.core:ini.include path
After It is configured problem is solved with:
include("../header_footer/header.php");


text:
Q: Interactive notification support iOS 8 I have an existing application that supports both local and push notifications, with the introduction of iOS 8 and its newly added features (link referred) ,i thought of adding some of the features in app. My question is how to use interactive notification feature in my app.should i add any new framework; coding or an any tutorial link would be helpful. Also help me creating widgets for my app.

A: This video helped me
https://developer.apple.com/videos/wwdc/2014/#713
and this link about notifications UI guidelines too
https://developer.apple.com/library/ios/documentation/userexperience/conceptual/mobilehig/NotificationCenter.html
and this link for widgets
https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/NotificationCenter.html


text:
Q: What is the correct way to use JavaScript to perform arithmetic on a DOM object? I've been trying to use the following code to add 1 from the value within the paragraph tags, but only get NaN as the output value:

5

<button onclick="increment()">Click</button>

Can anyone say why this is outputting NaN?

A: It is NaN because the .value of the
 element is undefined. As a result you are doing this:
undefined + 1

Which is NaN. Get the value from the element using .textContent or .innerHTML depending on the structure, then use parseInt.
function increment() {
    document.getElementById("myNumber").textContent = parseInt(document.getElementById("myNumber").textContent,10) + 1;
}

A: You need to parse the innerText (String) property of myNumber as an Integer:
document.getElementById("myNumber").innerText = parseInt(document.getElementById("myNumber").innerText) + 1;


text:
Q: PPM Image flip using a one-dimensional vector C++ for(int i = 0; i < hdr.getHeight(); i++){
    for(int j = 0; j < hdr.getWidth(); j++){
        Pixel temp = vec.at(i * hdr.getWidth()  + j);
        vec.at(i * hdr.getWidth() + j) = vec.at(i * hdr.getWidth() + ((i * hdr.getWidth()) - j));
        vec.at(i * hdr.getWidth() + ((i * hdr.getWidth()) - j)) = temp;

     }
}

I've been working on this class assignment pretty much all day, and all sense and reason and critical thinking abilities have absolutely left me. I understand the concept of iterating through a 1D vector as a 2D, in that
i * # of cols + j
Basically bypasses an entire row and references the first element in a "column," but trying to do that, and replacing the original pixel with the pixel at the mirrored position is absolutely escaping me.


text:
Q: How do I fix this cross-domain ActionScript 3 error? I'm going to be as specific and verbose as possible and include some of the code I'm using. I already did a search and found this question, which seems similar; however the author there was using ActionScript 2 instead of 3, and I couldn't seem to apply any of the answers given to my own situation effectively.
I am trying to emulate (in a limited way) the behavior of JavaScript's XMLHttpRequest object through Flash/ActionScript 3, in order to overcome the same-domain limitation. But I'm discovering that ActionScript has its own limitations in that regard. I admit that I might be mistaken, but from what I understand it is theoretically still possible to do this sort of cross-domain scripting using ActionScript, so long as you get all the permissions right. And that's where I'm running into trouble.
First, I borrowed some open-source code for a class called AjaxRequest, which I have saved as /ajax/AjaxRequest.as. I then created a Flash file called /jsajax.fla which exports to the final SWF file, /jsajax.swf. Now, here's the ActionScript code that comprises the first and only frame of the Flash file:
import ajax.AjaxRequest;
Security.allowDomain("domainone.com");
Security.allowDomain("domaintwo.com");

function jsAjax(stringURL:String, stringMethod:String, stringData:String):void
{
    var xhr:AjaxRequest = new AjaxRequest(stringURL);
    xhr.contentType = "application/x-www-form-urlencoded";
    xhr.dataFormat = URLLoaderDataFormat.TEXT;

    if ( stringMethod.toUpperCase() == "POST" ) {
        xhr.method = URLRequestMethod.POST;
    } else {
        xhr.method = URLRequestMethod.GET;
    }

    xhr.addEventListener("complete", jsAjaxResponse);
    xhr.send(stringData);
    return;
}

function jsAjaxResponse(evt:Event):void
{
    ExternalInterface.call("jsAjaxResponse", evt.currentTarget.data.toString());
    return;
}

ExternalInterface.addCallback("jsAjax", jsAjax);
ExternalInterface.call("jsAjaxReady");

So far so good. I have a feeling that one or more of those Security.allowDomain calls are not needed, but they were my (unsuccessful) attempts to try to solve this problem.
In my JavaScript, I've got three functions defined: jsAjax, jsAjaxResponse, and jsAjaxReady. The last one is just a very basic function used to indicate that the Flash object loaded successfully (which is only called once and immediately upon loading it), while the other two are used for sending and receiving the data. As you can see, they have corresponding ActionScript counterparts.
Finally, I created a simple HTML page called /test.html that embeds this SWF file (using swfobject) and has a couple of simple form controls for calling the jsAjax function. All of my JavaScript definitions are embedded in this HTML file too. I also created a very simple PHP script called /test.php that prints out the contents of the $_REQUEST array. That's the script I intend to request using this ajax method.
There are three scenarios that I tested, but I was only able to get two of them working:

SCENARIO ONE: All on one server
If I upload all of these files to domainone.com, and then request test.php, it works fine. My file/folder structure then looks like this:
domainone.com/jsajax.swf
domainone.com/test.html
domainone.com/test.php

Again, this works. The jsAjaxResponse function receives back the data from test.php just fine.

SCENARIO TWO: On both servers, leaning left
When I uploaded the HTML and SWF to the first server, and then just have it call the PHP script on the second server, it didn't work right away. I did some digging, and found that by creating a crossdomain.xml file on domaintwo.com that granted access to domainone.com, this fixed it. So my file/folder structure looked like this:
domainone.com/jsajax.swf
domainone.com/test.html
domaintwo.com/test.php
domaintwo.com/crossdomain.xml

When explicitly allowing domainone.com in the crossdomain.xml file, this works. Again, the jsAjaxResponse function receives back the data from test.php just fine.

SCENARIO THREE: On both servers, leaning right
When I uploaded all but the HTML to domaintwo.com, I could no longer get it to work. In other words, the HTML on domainone.com is referencing an SWF file hosted on domaintwo.com, and that SWF file is trying to make a request to domaintwo.com. I left the same crossdomain.xml file from Scenario 2, just in case. My file/folder structure looked like this:
domainone.com/test.html
domaintwo.com/jsajax.swf
domaintwo.com/test.php
domaintwo.com/crossdomain.xml

This is the only case I could not get working, and this is the case I need to get working. The first two were really just test scenarios to see if the script was working at all. When I try to run my jsAjax function here, I wind up with an error that shows up twice in Firebug:
uncaught exception: Error calling method on NPObject! [plugin exception: Error in Actionscript. Use a try/catch block to find error.].
uncaught exception: Error calling method on NPObject! [plugin exception: Error in Actionscript. Use a try/catch block to find error.].

Help! How do I get it working in scenario 3?

A: I just figured it out! It did have to do with the Security.allowDomain commands in my Flash file. I was actually hosting the test.html on a subdomain of domainone.com, and that was throwing it off. It has to be an exact match, subdomain and all. It turns out I didn't need the Security.allowDomain command that referenced domaintwo.com, nor did I need the crossdomain.xml file to be present at all for Scenario 3!
Since in the "real" version of this script that I end up using, I won't necessarily know what domainone.com actually is, I changed the code on the top of the Flash file to this:
import ajax.AjaxRequest;
try {
    var domain1:String = LoaderInfo(this.root.loaderInfo).parameters["allow"];
    if ( domain1.length > 0 ) {
        Security.allowDomain(domain1);
    }
} catch (error:Error) { }
try {
    var domain2:String = LoaderInfo(this.root.loaderInfo).parameters["allowhttps"];
    if ( domain2.length > 0 ) {
        Security.allowInsecureDomain(domain2);
    }
} catch (error:Error) { }
...

Then, in the JavaScript I'm using to embed the SWF there in the first place, I basically grab the current domain of the page from document.location.toString(), check whether it's using http or https, and then pass the domain in as allow and/or allowhttps in the flashvars parameter. There might be a "better" way to do this that doesn't rely on setting the domain up explicitly in the Flash Vars (some kind of automatic detection from within Flash), but I'm not versed in ActionScript well enough to figure that out. And since this file is already doing a whole bunch of bidirectional communication between JavaScript and ActionScript, it's not that big of a deal. This solution is good enough for me.


text:
Q: Using jquery to create checkboxes from string I do have a string that contains keywords, like:
$keywords = "shoes, bags, shirts, accessoires"

I want to have created a list of checkboxes out of this string.
The checkboxes should show up after loading the page and all checkboxes should be checked, like:
[x] shoes [x] bags [x] shirts [x] accessoires

So user should be able to uncheck some keywords to narrow down search results.
Is this possible with jquery? Thanks,

A: split up the keywords, and iterate over them creating a label and a checkbox :
var keywords = "shoes, bags, shirts, accessoires";

$.each(keywords.split(','), function(_, word) {
    var lbl = $('<label />', {text: word}),
        box = $('<input />', {type: 'checkbox', name: word, checked: 'checked'});

    lbl.prepend(box).appendTo('body');
});

FIDDLE

A: $keywords = "shoes, bags, shirts, accessoires";

var keyword_array=$keywords.split(",");
var str="";
$.each(keyword_array, function( index, value ) {
str +="<input type='checkbox' >"+ value + "</input>";

});

now use this str to set html by html
reference each


text: Q: $\lambda$ an eigenvalue then $T-\lambda$ not surjective I'm stuck in this question and I'm wondering if this is true for a linear transformation $T:V\to V$ with $V$ an arbitrary vector space (not necessarily with finite dimention)


text:
Q: self.customView.backgroundColor assignment causes leak? I'm working with creating my own custom view templates programmatically for the app I'm working on. To achieve this i have a custom view controller MyVC with a a custom view myView added on to it which is a property of MyVC. The class looks something like this:
MyVC.h
#import <UIKit/UIKit.h>

@interface MyVC : UIViewController{
MyCustomView *myView;
}

@property(nonatomic, retain) MyCustomView *myView

@end

In the implementation i want to assign a background color to 'myView' and i do something like this in the viewDidLoad (after synthesizing my property of corse)
-(void)viewDidLoad{
self.myView = [[MyCustomView alloc] initWithFrame:someFrame];

self.myView.backgroundColor = [UIColor clearColor];

}

Now when i analyze my code i get a 'potential leak of an object' message when i assign the color. Is it because myView or the background color or both are being retained?
In any case id like to know how this can be done correctly without potential leaks?

A: If you don't using ARC you should release over retained property:
-(void)viewDidLoad{
//allocate and initialize myView

self.myView = [[[MyCustomView alloc] initWithFrame:someFrame] autorelease];
self.myView.backgroundColor = [UIColor clearColor];
}


text:
Q: How to add new element for XML in PowerShell I haven't worked that much with XML in Powershell and I can't make it work, so hope there is someone who can help
I have this XML file, and want to add a new element name ExitProcess below the element name ExitProcesses
How do you add that?
I want to go from this
```
<ExitProcesses>
<ExitProcess>
  <ProcessName>outlook.exe</ProcessName>
  <ForceClose>False</ForceClose>
</ExitProcess>
</ExitProcesses>

```

To this
```
<ExitProcesses>
<ExitProcess>
  <ProcessName>outlook.exe</ProcessName>
  <ForceClose>False</ForceClose>
</ExitProcess>
<ExitProcess>
  <ProcessName>Test.exe</ProcessName>
  <ForceClose>False</ForceClose>
</ExitProcess>
</ExitProcesses>

```

A: First we need to construct the new subtree:
<ExitProcess>
  <ProcessName>outlook.exe</ProcessName>
  <ForceClose>False</ForceClose>
</ExitProcess>

So we need to:

*

*Create an <ExitProcess> node

*Create a <ProcessName> node

*

*Add it as a child of <ExitProcess>

*Create a <ForceClose> node

*

*Add it as a child of <ExitProcess> / sibling of <ProcessName>
Let's create a small function to do this:
function New-ExitProcessNode
{
  param(
    [Parameter(Mandatory)]
    [xml]$Document,

    [Parameter(Mandatory)]
    [string]$ProcessName,

    [switch]$ForceClose
  )

  # Create ExitProcess node
  $exitProcessNode = $Document.CreateElement('ExitProcess')

  # Create ProcessName node, add process name as inner text
  $processNameNode = $Document.CreateElement('ProcessName')
  $processNameNode.InnerText = $ProcessName

  # Create ForceClose node, add setting as inner text
  $forceCloseNode = $Document.CreateElement('ProcessName')
  $ForceCloseNode.InnerText = $ForceClose.IsPresent

  # Add the child nodes to the ExitProcess node
  [void]$exitProcessNode.AppendChild($processNameNode)
  [void]$exitProcessNode.AppendChild($forceCloseNode)

  # return new ExitProcess node
  return $exitProcessNode
}

Now that we've gotten that squared away, we just need to append this new subtree to <ExitProcesses>:
[xml]$xmlDocument = Get-Content .\path\to\document.xml

# Use XPath to retrieve the <ExitProcesses> node(s)
$xmlDocument |Select-Xml -XPath '//ExitProcesses' |ForEach-Object {
    # Create a new <ExitProcess> subtree with our function from above
    $newChild = New-ExitProcessNode -Document $xmlDocument -ProcessName "Test.exe"

    # Append to <ExitProcesses>
    [void]$_.Node.AppendChild($newChild)
}

$xmlDocument is now updated with your new <ExitProcess> node and you can save it with:
$xmlDocument.Save("$PWD\path\to\output.xml")


text:
Q: golang wikitext parser from scratch I am asked to build a wiki in golang. Some of the editors are familiar with the wikitext, so they want to keep it. I find it's really hard to build a wikitext parser from scratch and there's no open source golang parser. Can anyone give me some suggestion?
I have searched go.pkg, there's no available pkg

A: You could call an external tool (https://github.com/5j9/wikitextparser) from your go code with https://pkg.go.dev/os/exec, which is probably easier to parse than raw wikitext.


text:
Q: What happens to the charge density under parity? A question came to me when I tried to think about the parity prperties of the Maxwell's equations.
The charge density $\rho(\vec{r})$ actually stands for a scalar quantity $\rho(x,y,z)$. Since the total charge of a system is $Q=\int dV \rho(x,y,z)$ is independent of the choice of a coordinate system and since $dV\to -dV$ under parity, and since another minus will be contributed by the limits of integration, the transformation property of $\rho(\vec{r})$ under parity must be $$\rho(\vec{r})\xrightarrow{\rm parity}\rho(-\vec{r})=+\rho(\vec{r}).$$
Now, I can think of two different scalar functions representing the charge density. First $\rho_1(x,y,z)=ax+by+cz$ and second $\rho_2(x,y,z)=ax^2+by^2+cz^2$. Evidently $\rho_1(\vec{r})$ is a function that flips sign under parity. However, the sign of $\rho_2(\vec{r})$ does not flip under parity (and satisfies the parity property derived above).
The question is this.
Physically, why is $\rho_1(\vec{r})$ not a permissible charge density? What stops one to create such a distribution of charge density which is odd (or even mixed) under parity transformation?

A: Your parity-odd charge distribution $\rho_1$ has nonzero dipole moment. It's a totally legal charge distribution.
It's frequently convenient to decompose a charge distribution into multipoles.  There are parity-even terms in a multipole expansion (monopole, quadrupole, etc.) and parity-odd terms (dipole, octupole, etc.).
The only requirement from parity symmetry is that inverting space twice has to return you to the original state: for any state $\left|\psi\right>$, you have to have $\hat P\hat P \left|\psi\right> = \left|\psi\right>$.  That means that the only allowed eigenvalues of the parity operator are $\pm 1$, but it doesn't mean that any particular observable must be in a parity eigenstate.

A: I believe you are confused as to what a parity transformation actually is. Parity transformations are changes of coordinate system, in which we simply modify how we label points in space.
Let's say you write down a coordinate system in which some point $p$ has coordinates $(x,y,z)=(1,0,1)$, and let the charge density there be $\rho$.  Now, you decide that you don't like those coordinates.  You want to use different coordinates $(x',y',z')=(-x,-y,-z)$, so in this coordinate system, $p$ has coordinates $(-1,0,-1)$.
When I relabel my points, what happens to $\rho$ at the point $p$?  The answer should be obvious - nothing happens to $\rho$.  It's exactly the same as it was before, because the charge density does not care about how I choose to label points in space.
This can be formalized by saying that when $\mathbf r \mapsto \mathbf r'$, $\rho \mapsto \rho'$ such that $\rho'(\mathbf r') = \rho(\mathbf r)$.  If the coordinate transformation is written $\mathbf r' = T[\mathbf r]$, then we can say that $\rho'(\mathbf r') = \rho\left(T^{-1}[\mathbf r']\right)$
Quantities which transform in this way under all coordinate transformations are called scalars.  If we restrict our attention to parity transformations, then such quantities are called parity-even.  This immediately implies that scalars must be parity-even; if $\rho'(\mathbf r') = \rho\left(T^{-1}[\mathbf r']\right)$ for all coordinate transformations, then it certainly is true in the specific case of parity inversions.  The reverse, however, is not necessarily true.

Rather than talking about a scalar quantity, we could talk about a vector quantity.  Consider the velocity of a fluid at some point $p$,  $\mathbf v = v_x \hat e_x + v_y \hat e_y + v_z \hat e_z$, and perform the same transformation.  What happens?
$\hat e_{x'} = -\hat e_{x}$, $\hat e_{y'}=-\hat e_y$, and $\hat e_{z'} = -\hat e_z$.  Therefore, the components of the vector must also transform in the same way, i.e.
$$v_{x'} = -v_x$$
$$v_{y'} = -v_y$$
$$v_{z'} = -v_z$$
Therefore,
$$\pmatrix{v_x\\v_y\\v_z}\mapsto \pmatrix{v_{x'}\\v_{y'}\\v_{z'}}= -\pmatrix{v_x\\v_y\\v_z}$$
so we say that the velocity is parity-odd.  Note that this is a bit of an abuse of terminology - we should really say that the components of the velocity are parity-odd.

From both of the above examples, you should see that "symmetry" under parity transformations revolves completely around changes of coordinate system; in that sense, it is a gauge symmetry, not a real symmetry of a physical system.  For some parity transformation $\mathbf r \mapsto T(\mathbf r)$, we say that a quantity $f(\mathbf r)$ is parity-even if
$$f'(\mathbf r') = f\left(T^{-1}(\mathbf r')\right)$$
and we say it is parity-odd if
$$f'(\mathbf r') = - f\left(T^{-1}(\mathbf r')\right)$$
On the other hand, you are talking about actual, honest-to-goodness symmetries of specific charge distributions, i.e. those such that
$$\rho(\mathbf r') = \rho\left(T^{-1}(\mathbf r')\right)$$
or
$$\rho(\mathbf r') = -\rho\left(T^{-1}(\mathbf r')\right)$$
The lack of primes on the $\rho$'s on the LHS of these equations is crucial.  Parity "symmetry" is not a statement about the universe, but rather a statement about how our description of the universe changes when we pick new labels for points.

A: Let $Q(\Omega)$ denote the charge inside the volume $\Omega\subset\mathbb R^3$. We have
$$
Q(\Omega)=\int_\Omega\rho(\vec x)\,\mathrm d\vec x\tag1
$$
where $\vec x\in\mathbb R^3$. If you change variables $\vec x\to-\vec x$ you get
$$
Q(\Omega)=\int_{\Omega'}\rho(-\vec x)\,\mathrm d\vec x\tag2
$$
where $\Omega'$ is the image of $\Omega$ under $\vec x\to-\vec x$ (i.e., it is the mirror image of $\Omega$ with respect to the origin).
Note that in general $\Omega\neq \Omega'$. We indeed have the equality of the integrals
$$
\int_\Omega\rho(\vec x)\,\mathrm d\vec x\equiv \int_{\Omega'}\rho(-\vec x)\,\mathrm d\vec x\tag3
$$
but this does not mean that the integrands are themselves equal. In other words, in general
$$
\rho(\vec x)\neq\rho(-\vec x)\tag4
$$
Indeed, consider the following trivial 1d example:
$$
\int_1^2 (x^2+x)\,\mathrm dx=\frac{23}{6}\tag5
$$
If you perform the same change of variables as before, you get
$$
\int_{-2}^{-1}(x^2-x)\,\mathrm dx=\frac{23}{6}\tag6
$$
The two integrals are identical – we just performed a change of variables. But the integrands are $x^2+x$ and $x^2-x$, which are different.
The same thing happens in the 3d case. While it is true that the integral of $\rho(\vec x)$ over a region $\Omega$ is equal to the integral of $\rho(-\vec x)$ over the region $\Omega'$, the functions $\rho(\vec x)$ and $\rho(-\vec x)$ need not be equal. In general, they are not, as the example in the OP demonstrates. The charge density, or any other source for that matter, need not be invariant under parity, or any other preconceived transformation.
More generally, the charge $Q(\Omega)$ could also be computed by using any other system of coordinates $\vec x\to\vec y(\vec x)$, but one must remember that the integration region gets transformed too, $\Omega\to y^*\Omega$, see e.g. wikipedia.
But even if the integration regions were the same, i.e., if for a particular $\Omega$ and change of variable $\vec y(\vec x)$ we had $\Omega=y^*\Omega$, equality of integrals does not imply equality of integrands. So you cannot conclude from $Q=Q$ that $\rho=\rho\circ \vec y$.


text:
Q: How to NOT Have Tables/DataFiles Appear in SAS Enterprise Guide Window What option may I select in SAS Enterprise Guide so that generated tables or datasets do not appear in the Project Workspace? I have a lot of them and it is getting very messy.
Please note that I already defined my own library to place data files - and there are plenty of them.
I can right-click on my Workspace, then click on Project/Properties and I set Output Data Sets to zero, and that sort of solves the program. However, numerous messages, or Reports, appear within my Window specifying that the output was not written. I think it was still written to my user-defined libraries though - I HOPE I am correct there.
Any help and/or links are appreciated.

A: You should be ok.  Read the SAS Blog entry "SAS Enterprise Guide: Suppress Output Data tab when programming", By Cindy Cragin on SAS Learning Post June 17, 2015.

There is an easy way to suppress the Output Data tab in the data grid window from opening up in your Enterprise Guide session after submitting a SAS program.
  …
  Here is your answer. Select Tools -> Options -> Results -> Results General and set the value of 'Maximum number of output data sets to add to the project' to 0.

This will also prevent the output data sets from being listed in the process flow diagram.
Suppose you had a program node such as:
libname t 'c:\temp';

data t._1 t._2 t._3 t._4 t._5;
  set sashelp.class;
  select (mod(_n_,5));
    when (0) output t._1;
    when (1) output t._2;
    when (2) output t._3;
    when (3) output t._4;
    when (4) output t._5;
    otherwise;
  end;
run;

The Enterprise Guide 8.1 UI would show

with Log panel indicating the output was indeed created.


text:
Q: Can´t add product to cart, litespeed and sm-maxshop theme Im trying to get litespeed cache to work with my magento installation.
Litespeed is working and load speed is faster. The problem is when a user tries to add a product to the cart in product page, it doesn't add the product.
Add-button is working fine when litespeed is disabled.
Is there a way to exclude the addbutton from caching.
Magento 1.9.2.3
Lightspeed Cache from litespeedtech 1.3.6
SM-Maxshop theme 1.1.0

A: It maybe some javascript breaking if that button does not work. Does your footer show up properly? There's one known issue for sm theme. If this is not your case, you can create a ticket with LiteSpeed support, they can help you there.
LiteMage is very flexible and can be configured to fit most cases for Magento 1.9. FormKey is handled as a private ESI block and should not break CSRF check.


text:
Q: TSQL error on JDBC call "Incorrect syntax near '@P1" The "Incorrect syntax near '@P1" from a TSQL stored procedure seems to be a common issue but none of the advice that I have seen has solved my problem.   My query works in SQL Management Server Studio is not working from my JDBC code.
ALTER PROCEDURE [dbo].[Get-ErrorLogByWorkflowId] (
       @workflowId AS NVARCHAR(255) -- removed second parameter to simplify: , BIGINT @numSecondsOfErrors=300
)
AS
BEGIN
...

This is the Java code using JDBC that I use to call the stored procedure:
CallableStatement stmt = conn.prepareCall("{ call dbo.Get-ErrorLogByWorkflowId(?) }");
stmt.setString(1, workflowId);
//second parameter removed to simplify call: stmt.setLong(2, seconds);
ResultSet rs = stmt.executeQuery();

I have tried calling the stored procedure both with and without brackets, e.g., [dbo][Get-...].  I have also tried declaring the parameter both as a VARCHAR and NVARCHAR.  What should I do to correct this?
Note: I had previously observed some odd problems handling names beginning with "Get-", but the prefix is part of my company's standards and I eventually got such queries to work.

A: @AlwayLearning was correct.  Uniformly using brackets around the portions of the names of the stored procedure worked - so I now use [dbo].[Get-ErrorLogByWorkflowId] to be on the safe side


text:
Q: Redirecting stdout output in cpp I've been searching for an answer regarding this issue for a few days now, I hope you guys will be able to assist me. (I've searched and found some solutions, but each has its own issue...).
Here is the thing:
I'm writing an automation at work, which is responsible for launching an external ".exe" file of a code written by my colleagues. As those programs they write go to customers, I'm not allowed to make any modification to their code. Those programs, once launched, are waiting for specific key strokes, and prints a message when a legal key stroke has been received.
My goal is this:
To write a program which will execute the external program, send it key strokes, and receive the output from their stdout.
So far, I have been able to run the program from my program (using ShellExecute), and simulate some sort of keyboard listener (using SendMessage) to the other program. I can see that it works - I can see the output in the tested program's console.
I'm trying to fetch the messages printed on the tested program's shell in real-time (and just get a bulk of data when the program terminates) so that I could analyse it when it occurs.
Those I've tried:

*

*Writing an external batch file with inline output redirection to a text file.

*Using freopen.

*Redirecting the output while exectuing "ShellExecute".

A: You use handles for stdin, stdout, and stderr. Create process with CreateProcess function to get that handles.
Sample code - incomplete for your case, but good example of how to do it:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>

    /*for test.exe
#include <iostream>
#include <string> */

void _tmain( int argc, TCHAR *argv[] )
{
    /*for test.exe
    std::cout << "test output" << std::endl;
    for (;;)
    {
        std::string line;
        std::getline(std::cin, line);
        std::cout << "line: " << line << std::endl;
    }
    return;*/
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    // Start the child process.
    if( !CreateProcess( NULL,   // No module name (use command line)
        "test.exe",        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    )
    {
        printf( "CreateProcess failed (%d)\n", GetLastError() );
        return;
    }

   /*     HANDLE  hStdInput;
    HANDLE  hStdOutput;
    HANDLE  hStdError;*/
    HANDLE me_hStdInput = GetStdHandle(STD_INPUT_HANDLE);
    HANDLE me_hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    HANDLE proc_hStdInput = si.hStdInput;
    HANDLE proc_hStdOutput = si.hStdOutput;

                char buff[64];
                DWORD chars;
    while (!ReadConsole(me_hStdInput, buff, sizeof(buff), &chars, NULL))
    {
                    for (DWORD written = 0, writtenThisTime; written < chars; written += writtenThisTime)
                        if (!WriteConsole(proc_hStdOutput, buff + written, chars - written, &writtenThisTime, NULL))
                        {
                            //handle error - TODO
                        }
                }
                //possibly handle error for ReadConsole - TODO

    // Wait until child process exits.
    //WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles.
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}


text:
Q: Numpy arrays created from pandas dataframe show strange behaviour I've a csv file which is having long image vectors. The format of the file is:
imgName,-0.947363,0.83463728,0.635252,0.787878.....

I need to drop my first column and use rest of the data. When I create my numpy array using numpy library like:
from numpy import genfromtxt
my_data = genfromtxt('fewvec.csv', delimiter=',')
data = np.delete(my_data, 0, 1)
data = data.astype(np.float64)

everything works well. When I create my nparray using pandas
df = pd.read_csv("fewvec.csv", header=None)
data1 = df.iloc[:, 1:].values

the created data1 array looks exactly same to me as data array created above. But when I pass this to a library(nmslib) it generates wrong answer using data1 array. Is there any fundamental difference between these two arrays?


text:
Q: How to receive Github WebHook in Google Apps Script web application? I have Google Apps Script web application:
function doPost(request){
  request.postData;
  // operations based on received JSON
}

and I have setup webhook in Github.
Why my GAS app is rejecting HTTP requests from GitHub WebHook? Every time I check WebHook log I see error messages:
Error 401 "Sorry, unable to open the file at this time.".

A: You can retrieve JSON data from WebHook of GitHub using e.parameters.payload for doPost(). About this parameter, you can see at https://developers.google.com/apps-script/guides/web
So you can write your function as follows.
function doPost(request){
  Logger.log(request.parameters.payload)

}

payload is a JSON key from GitHub.
WebHook of GitHub doesn't support redirects. So although the WebHook log of GitHub will leave warnings, doPost() at GAS can retrieve data from the WebHook.


text:
Q: SQL Server datetime2 parse issue When I run the following SQL at my local SQL Server instance:
DECLARE @t DATETIME2 = '2019-12-12 00:00:00'

I get the following error:

Unable to convert @t to a System.Data.SqlClient.SqlParameter object. The specified literal cannot be converted to DateTime2(System.Data.SqlDbType), as it used an unsupported date/time format. Use one of the supported date/time formats. Literal value: 2019-12-12 00:00:00

The only way to fix it is to add 'T' between date and time
DECLARE @t DATETIME2 = '2019-12-12T00:00:00'

At the same time, this script runs perfectly fine at my production server (without adding 'T').
I tried to find the difference and don't see anything that could affect the behavior:

*

*Collation is the same at both servers - SQL_Latin1_General_CP1_CI_AS

*Language is the same - English (United States)

*Server version: LOCAL is Microsoft SQL Server 2017 Developer Edition (64-bit) v14.0.2027 RTM; REMOTE is Microsoft SQL Server 2017 Enterprise Edition: Core-based Licensing (64-bit) v14.0.1000 RTM

*Host OS: LOCAL is Windows 10 Pro; REMOTE is Windows Server 2016 Datacenter

Can somebody explain, why I'm getting the error locally?

A: This is a client-side error so it seems you are running the query from SSMS with the Enable Always Encrypted (column encryption) option for the connection (connection Options-->Always Encrypted) on the remote client but not the prod server. With the option enabled, the SSMS client parses literals in order to build parameters for AE.
Unlike '2019-12-12 00:00:00', the ISO 8601 datetime format literal '2019-12-12T00:00:00' is unambiguous and can be reliably parsed regardless of the client regional settings.
So your options are to either use an ISO 8601 datetime format or turn of the SSMS Enable AE option for the connection.


text:
Q: Why does my variable not keep its value outside of my loop I've been programming in Java for a while and I decided to try and learn Groovy. I'm going through the project euler problems and one the first problem I've already noticed something strange.
class Problem1
{
    public static void main(String[] args)
    {
        def multiple = 1;
        for(i in 1..1001)
        {
            //if it is divisible by three then multiply is
            if(i%3 ==0)
            {
               multiple = multiple * i;
            }

            if(i%5 ==0)
            {
                multiple = multiple * i;
            }
            holder = multiple
        }

        println(multiple)
    }
}

my value to multiple is being set incorrectly. Everything works as expected inside of the loop but when I try to print my value I get 0. It doesn't even print the 1 that I set the variable to initially. I wouldn't expect this to happen in Java. Why does it happen in Groovy? I thought that groovy was supposed to be like Java under the hood.

A: You're overflowing an integer (as you would in Java also)
Try using a BigInteger by changing
def multiple = 1;

To
def multiple = 1G


text:
Q: Understanding the # of buckets for my SnappyData table? The default # of buckets is 113. Why?  Why not 110?  Does the bucket logic perform better with a certain "divisible by"  value.
There are a lot of examples in SnappyData with less buckets.  Why is that?  What logic went into determining to use less buckets than the default 113?
What are the implications of choosing less?   What about more buckets?  I see a lot of logging in my Spark SQL queries looking for data at each bucket.  Is it worse on performance of a query to have more buckets?

A: Follow these guidelines to calculate the total number of buckets for the partitioned table:

*

*Use a prime number. We use hashing function internally and this provides the most even distribution. Check this post for more details : Why use a prime number in hashCode?

*Make it at least four times as large as the number of data stores
you expect to have for the table. The larger the ratio of buckets to
data stores, the more evenly the load can be spread across the members.
Note that there is a trade-off between load balancing and overhead, however. Managing a bucket introduces significant overhead, especially with higher levels of redundancy.

A: We have chosen a prime number which is most efficient in distributing data in a hash based partitioning logic. Number of buckets will have some impact on query performance. As buckets are translated to Spark tasks , there will be task scheduling overhead with a higher number of buckets.
But If your cluster has more capacity in terms of number of cpus, you should certainly try to match number of buckets to a near by prime number.


text:
Q: Adding custom indentation for C# code in Visual Studio (not VS Code) I have C# code as below:
Log.Step("step 1");
int x = 10;
int y = 20;

Log.Step("step 2");
int a = 10;
int b = 20;

I want the editor to auto-format those lines as below:
Log.Step("step 1");
    int x = 10;
    int y = 20;

Log.Step("step 2");
    int a = 10;
    int b = 20;

After every Log.Step method, I want to be able to indent the next lines of code till a newline is entered. Is there a way I can define indentation rules in VS to do so?

A: Your indentation format is very specific, but there is a approach using { }:
static void Main(string[] args)
{
    Log.Step("step 1");
    {
        int x = 10;
        int y = 20;
    }

    Log.Step("step 2");
    {
        int a = 10;
        int b = 20;
    }
}

Is not a "identation" rule, but maybe this can help you


text:
Q: Symplectic form on moduli space of connections Let $M$ be the moduli space of flat $GL(n,\mathbb{C})$ connections on a compact oriented surface, and $\alpha$ the natural symplectic form on it.
Is there any known construction of a bundle with a connection such that it's curvature is $\alpha$?


text:
Q: Sublime Text Plugin Open file symbol I was trying to execute a command to open a file at the line of a text symbol.
I tried to achieve that using the show_overlay command, but it will not open correctly if you try to use the '#' in the search.
Example. create a project that contains a file,
app/code/community/MagicToolbox/MagicZoomPlus/Model/Observer.php:
class MagicToolbox_MagicZoomPlus_Model_Observer {
    public function fixLayoutUpdates($observer) {
    }
}

if you try to create a plugin with command like this:
class MyPluginCommand(sublime_plugin.TextCommand):
    def run(self, view):
            sublime_api.window_run_command(
                self.view.window().id(),
                'show_overlay',
                {
                    'overlay': 'goto',
                    'show_files': True,
                    'text': 'MagicToolbox/MagicZoomPlus/Model/Observer#fixLayoutUpdates'
                }
            )

it will not display the file on first hand. but if you remove all the text from the search input, and then paste it again MagicToolbox/MagicZoomPlus/Model/Observer#fixLayoutUpdates it will display the file and highlight the function.
Maybe there is another way to achieve the same.

A: After some investigation, it looks like when you provide text to the show_overlay it's just applied directly to the contents of the text field and used as a simple filter for initial display without any of the extra handling that would occur if you entered the text manually. Thus when you insert text that includes special goto features such as the # that you're using here, it's applied strictly as a filter on the files being displayed but no extra action happens.
As you've noted, opening the overlay and then entering the text as two actions has the desired effect. So in order to do this via a plugin, you need to do this in two actions:
import sublime
import sublime_plugin

class ExampleCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.window().run_command("show_overlay", {
            "overlay": "goto",
            "show_files": True
        })
        self.view.window().run_command("insert", {
            "characters": "Observer#fixLayoutUpdates"
        })

Here we first open the overlay and then use the insert command to insert the text. The important key here is asking the window to run the insert command. Although insert is a TextCommand, asking the window to execute it tells the window to forward the command to whatever view happens to have the input focus in that window, which is the input area in the overlay.
If the command that you're doing this in isn't modifying the selection or contents of the file on it's own, you can shorten this up by making it a WindowCommand instead and using self.window instead of self.view.window().


text:
Q: Имя типа или пространства имен отсутствует в пространстве имен (пропущена ссылка на сборку?) Выполняя сборку проекта через Tfs builds, проект выдает ошибку:

Имя типа или пространства имен "Office" отсутствует в пространстве имен "Microsoft" (пропущена ссылка на сборку?).

При этом ссылка в References проекта указана. В коде тоже указано:

using Word = Microsoft.Office.Interop.Word;

Также в процессе сборки проекта на сервере возникает Warning:

Не удалось разрешить данную ссылку. Не удалось обнаружить сборку "Microsoft.Office.Interop.Word, Version=15.0.0.0,...". Убедитесь, что данная сборка существует на диске. Если данная ссылка требуется в коде, это может вызвать ошибки компиляции.

При этом, локально, проект успешно собирается.

A: Проблема решена. Для этого необходимо выбрать соответствующий Build controller в настройках сборки во вкладке Build Defaults.


text:
Q: Why boolean is set false at the beginning and is the code right? i would like to know first why Boolean is set to be false at the beginning and the pre-last "else"  i ca not understand that condition that code is suppose to differentiate vowels from consonants  ??
https://beginnersbook.com/2017/09/java-program-to-check-vowel-and-consonant-using-switch-case/

A: Please post the Code when you ask a Question and don't just put a link in here.
To answer your Question the Code is correct, just the 2nd ; in
boolean isVowel=false;;

isn't necessary. The boolean is set to false to Show that they assume by Default that the given char is no Vowel.
The switch basically checks if the given char is an a,e,i… and has to check for upper and lower case because they are treated different. If the given char Matches any of the given values the boolean is set to true because the char is a vowel.
The second last else Statement checks the UTF-16 values of the Alphabet, you can cast a char to an int which determines ist value in UTF-16 encoding for the lower cases it is 97-122 and for the upper cases their values are 65-90. If the int value of the char is not in this range the char is not in the Alphabet. You can refer to an ascii table to know which char is equivalent to which int.