text:
Q: Make a div non-scroll able I have two div in side a row named sidenav and mainscreen. I have assigned sidenav 1 column and mainscreen 11 columns by bootstrap. Floowing is the output of the following.

I want to make sidenav non scrollable but mainscreen should be srollable. Many solutions suggest using position:fixed. I tried making the position of sidenav fixed but it ruins the style of whole page. Following is the output after using fixed position of sidenav.

following is html!

                         home

                       approval

                         document

                         wukla

                            <button class="searchinputbtn btn btn-secondary" type="button" style="border-style: none;border-radius: 0">hate</button>

                          <input type="text" class="form-control" placeholder="Product name" style="border-style: none">

                            <button class="searchinputbtn btn btn-secondary" type="button" style="border-style: none;border-radius: 0">love</button>

                        <button class="uploadbtn btn btn-secondary" type="button" style="border-style: none;border-radius: 0">Upload Document</button>

pending signatures

                                <app-pendingdoc [requestid]="pendingdoc.requestid" [title]="pendingdoc.title"></app-pendingdoc>
                                <app-pendingdoc [requestid]="pendingdoc.requestid" [title]="pendingdoc.title"></app-pendingdoc>
                                <app-pendingdoc [requestid]="pendingdoc.requestid" [title]="pendingdoc.title"></app-pendingdoc>
                                <app-pendingdoc [requestid]="pendingdoc.requestid" [title]="pendingdoc.title"></app-pendingdoc>

all documents

                                <app-paksigndocument></app-paksigndocument>
                                <app-paksigndocument></app-paksigndocument>
                                <app-paksigndocument></app-paksigndocument>
                                <app-paksigndocument></app-paksigndocument>

wukla documents

and following is scss!
#ID {
overflow: hidden
}
.sidenav {
    position: fixed;
    padding: 0;
    background-color: #e6e6e6                                                                                ;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    height: auto;
}
.menu {
    padding: 0px;
    list-style: none;
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}
.menu-item {
    border-bottom: 1px solid #ffffff;
    height: 10%;
  display: flex;
  flex-direction: column;
  width: 100%;
  justify-content: center;
    align-items: center;
}
.mainscreen {
    padding: 0;
    height: 1450px;
}
.header {
    display: flex;
    align-items: center;
     flex-direction: column;
    justify-content: center;
    //width: 1259px;
    width: 100%;
    height: 36%;
    opacity: 0.58;
    background-color: #8cd1bc;
}

.mainbody {
    height: 64%;
    background-color: #f6f6f6;
}
.input-group{
    width: 100%;
}
.searchinputbtn {
    height: 20px;
}
.uploadbtn {
    margin-top: 42px;
    padding-left: 30px;
    padding-right: 30px;
    border-radius: 2px;
  background-color: #e6e6e6;
  font-size: 16.8px;
  font-weight: bold;
  letter-spacing: -0.3px;
  text-align: left;
  color: #ffffff
}
.inputs {
    width: 35%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.navtext {
    font-size: 11px;
  line-height: 0.95;
  letter-spacing: -0.3px;
  text-align: left;
  color: #59626a;
}

.itemstodisplay {
    width: 100%;
    height: 100%;
}

.notification {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    height: 26%;
    background-color: azure;
}
.bodytext{
    margin-bottom: 20px;
    margin-top: 50px;
     font-size: 20px;
  line-height: 0.53;
  letter-spacing: -0.5px;
  text-align: left;
  color: #73c7af;
}
.alldocs{
     display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    height: 38%;
    background-color: cornsilk;
}
.wukladocs {
     display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    height: 38%;
    background-color:floralwhite;
}
.components {
    height: 80%;
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    justify-content: center;
}

can anybody help me making sidenav non-scroll able?

A: You can use position: fixed and stretch the div to the length of the whole page. This can be done with the following CSS:
div {
    position: fixed;
    top: 0;
    bottom: 0;
}

Then you can make the mainscreen scrollable and keep the sidenav fixed.

A: Try this:
.navbar-fixed-left {
  width: 140px;
  position: fixed;
  border-radius: 0;
  height: 100%;
}

.navbar-fixed-left .navbar-nav > li {
  float: none;  /* Cancel default li float: left */
  width: 139px;
}

refer this article for more:
Usefull Article


text:
Q: Regular Expression does not match correct words I have a problem. I have this regex:
([\w ]*[^'entre']{1}) entre ([\w ]*) y ([\w ]*)

And some possible strings to match are:

*

*av cordoba entre medrano y gascon

*esmeralda entre av rivadavia y lavalle

*av cor1doba entre entre rios y suipac2ha

*monroe entre aizpurra y av de los constituyentes

The thing is, The regular expression matches the first 3 strings, but the other is not being matched and I don't know really why
Can you help me?
Thanks in advance
EDIT
The strings are names of streets and intersections of them. So, I want to find that expression and then replace it in the form:
street1/street2-street3
For the first example string, the replacement looks like
av cordoba/medrano-gascon
And the ^['entre] is there because a street name can contain the string "entre", and I must take it as the name of the street
EDIT
I found the solution. I have to use *([\w ]*(?<!entre)) entre ([\w ]*) y ([\w ]*)*
Thank you all

A: $pattern = (.*?)(?: entre )(.*?)(?: y )(.*?$)
See Demo
It can match string containing "entre" as first street name.

A: I suppose you can just use
([\w ]*?) entre ([\w ]*) y ([\w ]*)

See demo
No need to use more entres since we are using greedy matching.
Replacing with $1/$2-$3 we get:
av cordoba/medrano-gascon
esmeralda/av rivadavia-lavalle
av cor1doba entre/rios-suipac2ha
monroe/aizpurra-av de los constituyentes

A: Why don't you try it without the whitespaces?
([\w ]*[^'entre']{1})entre([\w ]*) y ([\w ]*)

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery - Syntax Error in a Conditional $(".editAd").change({
    if ($(this).val() == 1)
        {
            $("#submitBtn").val("Next Step");
        }
        else
        {
            $("#submitBtn").val("Submit Changes");
        }
    });

There is a syntax error on the second line of this code. Missing : after property ID. I swore this was the proper use of val() in a conditional, but I suppose I could be wrong...
I know this is a pretty simple fix, but I can't find any resources off of a few minutes of research, and I was hoping the users of SO could help me out. :)
Thank you!
EDIT: There's always a silly error that developers make that stumps them for a period of time... Always review the ENTIRETY of your code for errors because the developer tools may not actually pick up the proper line of the error, as in this case.

A: You forgot to include function(){}
$(".editAd").change(function(){
    if ($(this).val() == 1)
        {
            $("#submitBtn").val() = "Next Step";
            console.log($("#submitBtn").val());
        }
        else
        {
            (element.attr("name") == "submitBtn").val() = "Submit Changes"; // no idea  what this is but it doesn't look like it will work
        }
    });

A: val() is a function execution.
to set a value do something like
$('selector').val('set me');
not
$('selector').val() = 'set me';
start there.  Other things might clear up.

A:  Missing : after property ID
This is caused by the lack of a function () identifier before the conditional.  Because it was bracketed {} the javascript parser thought you were passing an object literal with if as a property identifier.  It was looking for a colon after it to identify the value of the property.

Not sure what you are trying to do on this line:

(element.attr("name") == "submitBtn").val() = "Submit Changes";

But it looks like you are trying to call val on a boolean value, which is not valid.  You are also assigning a string to the output of val() which won't work.
To assign a value to an element, jQuery's val takes one parameter:
element.val("Submit Changes");

A: There are numerous problems with your code. Firstly, the cause of the error you are talking about, is the missing function keyword. That's required as the change method takes a function as an argument.
Next, you're assigning a value to the val method, which is incorrect ($("#submitBtn").val() = "Next Step";). You need to pass the string in as an argument.
Third, your else block is very confusing. I'm not sure what you were trying to do there, but  it will evaluate to something like true.val() = "Submit Changes"; which is completely wrong. It's another assignment to a function, and you're trying to call that function on a boolean value, not a jQuery object.
So, based on all that, this is what I think you were trying to do:
$(".editAd").change(function(){
    if ($(this).val() == 1) {
        $("#submitBtn").val("Next Step");
        console.log($("#submitBtn").val());
    }
    else {
        if($(element).attr("name") == "submitBtn") {
            $(element).val("Submit Changes");
        }
    }
});


text:
Q: Specify port inside the mail() function I haven't found a coherent answer to my quesion here :(
My server's ISP has blocked the default SMTP port, so I need to switch it manually from 25 to 587.
mail("example@example.com","Hello","World"); //This uses the default value

PS.
I don't know why the answer had been removed - that link was very useful... however, I suppose it could be accomplished in simplier way.

A: You should use the ini_set function
ini_set("smtp_port", "587");

A: On Windows, SMTP settings used by the mail function are defined in php.ini file (smtp section). Either edit the file and make necessary changes or use ini_set function.


text:
Q: pspell global namespace dictionary is it possible to create something like "a global dictionary" for pspell?
I tried a lot but i can only create a personal dictionary for languages which are installed.
Am im blind, or is there a better way than just insert a word for the global dictionary to the personal dictionary for each language?
Best Regards,
Beerweasle

A: For everyone else who has a similar problem:
Now im just using an dictionary-iso of an other latin1-language that i normally wouldnt use


text:
Q: Problems with javascript date with different time zones I have an object with a DateTime property (get;set;) which is inside a collection (List) in C#. This property holds the value of DateTime.MinValue (01/01/0001 12:00:00 AM).
I am using the Newtsonsoft.Json.Net library to serialize my collection of objects as JSON like this
JsonConvert.SerializeObject(collectionValues,
    new JsonConverter[] { new JavaScriptDateTimeConverter() })

The converted output of my datetime property is new Date(-62135578800000) which in UTC-5 gives me a date of "Mon Jan 01 1 00:00:00 GMT-0500", but doing some tests in other time zones my serialization is still new Date(-62135578800000) but output in javascript is quite different "Sun Dec 31 0 22:00:00 GMT-0700"
I ran this test on the w3schools site changing the time zone of my computer.
How can I do to return always the value of "Mon Jan 01 1 00:00:00" no matter what time zone when my property server side is DateTime.MinValue?

A: Check DateTimeZoneHandling setting. I suggest you to always serialize date in UTC to avoid such collisions:
JsonConvert.SerializeObject(collectionValues, new JsonSerializerSettings
{
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
});


text:
Q: Is there some kind of security issue in this code? This is my code:
void handle(int s)
{
char inbuf[4096];//we defined inbuf as 4096 size

dup2(s, 0);
dup2(s, 1);

setbuf(stdout, NULL);

alarm(ALARM_TIMEOUT_SEC);

printf("crackme> ");

if (NULL == fgets(inbuf, sizeof(inbuf), stdin)) {
    return;
}

right_trim(inbuf);

if (is_correct(inbuf)) {
    printf("Good job!\n");
}
}

And if there is, what is the problem?
Little explanation about this program:
The first part of her running Server
When someone connects to the server and enter an input (i did a loop to examine the length of the input)
So this function looks at it and if the pass is correct then its print "good job"

A: Answering the question as titled: yes. The use of
void setbuf(FILE *stream, char *buffer);

is deprecated due to security issues, and is retained by MSVC only for compatibility purposes. Please use
int setvbuf(FILE *stream, char *buffer, int mode, size_t size);

which is more secure since the buffer size is also provided (as well as more flexibility by providing mode) and it returns a function value to indicate success or failure.


text:
Q: How to create a Function2 instance using lambdas in Java? I am trying to implement a lambda Function2 in Java:
JavaPairRDD<String, Integer> reducedCounts = counts.reduceByKey(new Function2<Integer, Integer, Integer>() {
    @Override
    public Integer call(final Integer value0, final Integer value1) {
        return Integer.valueOf(value0.intValue() + value1.intValue());
    }
});

The above is a sample, but how to change it to a lamb8 format? I wanna define as a separate function
Function2<...> f2 = LAMBDA;
counts.reduceByKey(f2);

A: You can go for a method reference which is the easiest option in this case:
Function2<Integer, Integer, Integer> f2 = Integer::sum;
counts.reduceByKey(f2)

which is equal to:
Function2<Integer, Integer, Integer> f2 = (i1, i1) -> i1 + i2;
counts.reduceByKey(f2)

Also, such simplification is possible because you perform a lot of unnecessary boxing/unboxing in order to calculate the sum of two integers.

A: Since Function2 is a functional interface, you can implement it with a simple lambda expression:
Function2<Integer,Integer,Integer> plus = (x,y)->Integer.valueOf(x.intValue()+y.intValue());

If your logic is more than a simple expression, you can use a block:
Function2<Integer, Integer, Integer> plus = (x, y) -> {
   // do stuff
   return Integer.valueOf(x.intValue()+y.intValue());
};

In case of a simple integer addition, you can take advantage of auto-unboxing and write this more simply as:
Function2<Integer, Integer, Integer> plus = (x, y) -> x + y;

You can also take advantage of sum method in Integer class to use a method reference:
Function2<Integer, Integer, Integer> plus = Integer::sum;


text:
Q: How to fill (based on the index of a dataframe) an empty column I'm trying to add the column 'Information' to my dataframe (df3) and filling it with string values ('True' if the index is 0 and 'False', otherwise). The problem is pandas put 'False' in every single row, even in the ones having an index 0 (see the output below).
Input :
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'Column1': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
                    'Column2': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                    'Column3': ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'],
                    'Column4': ['K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'],
                    'Column5': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
                    'Column6': ['XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XVII', 'XVIII', 'XIX', 'XX'],
                    'Column7': ['U', 'V', 'W', 'X', 'Y', 'Z', '', '', '', ''],
                    'Column8': [21, 22, 23, 24, 25, 26, pd.NA, pd.NA, pd.NA, pd.NA],
                    'Column9': ['XXI', 'XXII', 'XXIII', 'XXIV', 'XXV', 'XXVI', '', '', '', '']})

column_names = ['Letters', 'Numbers', 'RomanNumerals']
df3 = pd.DataFrame(columns = column_names)

i=0
while i<len(df1.columns):
    df2 = df1.iloc[:, i:i+3]
    df2.columns = column_names
    df3 = pd.concat([df3, df2])
    i+=3

df3.dropna(inplace=True)

for index, row in df3.iterrows():
    df3['Information'] = np.where(index == 0, True,  False)

display(df3)

Output :

Letters
Number
RomanNumeral
Information

0
A
1
I
FALSE

1
B
2
II
FALSE

2
C
3
III
FALSE

3
D
4
IV
FALSE

4
E
5
V
FALSE

5
F
6
VI
FALSE

6
G
7
VII
FALSE

7
H
8
VIII
FALSE

8
I
9
IX
FALSE

9
J
10
X
FALSE

0
K
11
XI
FALSE

1
L
12
XII
FALSE

2
M
13
XIII
FALSE

3
N
14
XIV
FALSE

4
O
15
XV
FALSE

5
P
16
XVI
FALSE

6
Q
17
XVII
FALSE

7
R
18
XVIII
FALSE

8
S
19
XIX
FALSE

9
T
20
XX
FALSE

0
U
21
XXI
FALSE

1
V
22
XXII
FALSE

2
W
23
XXIII
FALSE

3
X
24
XXIV
FALSE

4
Y
25
XXV
FALSE

5
Z
26
XXVI
FALSE

Is there an explanation to this scenario ?

A: Change the for loop with this snippet

df3['Information']= df3.index.map(lambda x: x==0)

What happen in the for loop is you actually make a new column based on a scalar. Note that you typed

df3['Information'] = np.where(index == 0, True,  False)

Instead of

row['Information'] = np.where(index == 0, True,  False)

But even the code above won't work because you assign to nothing
Edit:
Another way to do this (for further explanation you can check pandas dataframe apply)

def get_information(index):
    if index==0:
        return True
    else:
        return False

df3['Information']= df3.index.map(get_information)


text:
Q: IE10 - avoid form names in global scope for javascript I've got a web application with a search box, and an onKeypress event calls Query.keyPress().  Query is defined in an included javascript file.  Most of the time this works correctly.
On IE10 from some screens, trying to use the search box gives an error:
Error: Object doesn't support property or method 'keyPress'

What I have found is some of the screens have a query form with a name and id of 'Query'.  It seems in IE10 this appears in the global scope, and overrides the object literal from the javascript.  For info, the search box is not inside this form.
I've replaced the onKeypress code with alert(Query); and I see [object HTMLFormElement] which confirms what is happening.
Does anyone know how to stop this happening on IE10?

A: This problem can be negated by using your own namespace, rather than polluting the global scope time and time again.
var MY_STUFF = {};

MY_STUFF.Query = function () {};
MY_STUFF.MY_CONST = 4;
MY_STUFF.utilityFunction = function () {};

... this way, everything breaks if you add a form element named MY_STUFF, but it won't break if you add form elements called Query, MY_CONST or utilityFunction (not the best names, but you get the gist).
Like I said, it doesn't fix the problem, but it negates it. Polluting the global scope is also a bad practise.

You can, of course, not use a global variable at all, through closures. But this will likely require a lot of restructuring, if you have your application spread over multiple files, and no build process in place to combine your files.
(function () {
    var Query = function () {};

    // Query.keyPress() as much as you want!
}());

// Note you can't use it outside of the closure.

A: Probably, this should work. When declaring your variable Query, provide a var keyword before it.
var Query = new Object (); //right practice

Query = new Object (); //wrong practice


text:
Q: Expression "Something" ? "Something" : "Something else" shorter? Quick question. Can I write it in shorter way?
Actually, I would like to have the same variable from I can take value of:
{this.state.members[activeMemberId] ? this.state.members[activeMemberId].id : null}
e.g
{this.state.members[activeMemberId] ? (<-the same).id  : null}

A: You can just do:
this.state.members[activeMemberId].id || null

A: You can use logical OR
{ this.state.members[activeMemberId].id || null }

How this works ?
   x  ||  y
   |
   |________________ If `x` is true return `x` else return `y`

Thumb rule :- Logical OR return first true value if there's any else return the last value

A: You can use ||
this.state.members[activeMemberId].id || null

A: Be careful not to get a undefined reference exception trying to access the id property of undefined

function getMemberId(activeMemberId) {
    this.state = { members: {
      id1: { id: 1 }
    } };
    const { members: { [activeMemberId]: { id = null } = {} } = {} } = this.state;
    return id;
 }

 console.log(getMemberId('id1'));
 console.log(getMemberId('id2'));

 // Or you could chain the && operator and || operator
 function getMemberIdAlt(activeMemberId) {
    this.state = { members: {
      id1: { id: 1 }
    } };

    return (
      this.state
      && this.state.members
      && this.state.members[activeMemberId]
      && this.state.members[activeMemberId].id
    ) || null;
 }

 console.log(getMemberIdAlt('id1'));
 console.log(getMemberIdAlt('id2'));


text:
Q: Remote Powershell: New-SPUser : Access is denied. (Exception from HRESULT: 0x80070005) I am running a remote powershell script which attempts to setup a web-application and site collection and then attempts to add a user to that site collection.
I receive the following error:
New-SPUser : Access is denied. (Exception from HRESULT: 0x80070005)
This does not occur if I run the same script locally with the same administrative account.

A: The answer is to run GrantAccessToProcessIdentity on your web-application
$webApp = Get-SPWebApplication -Identity <Identity>
$webApp.GrantAccessToProcessIdentity(<User>)


text:
Q: While using laravel-Vue-pagniation i not able to move to another page In a Table, data is displayed but when I click on the page number provided by the laravel vue pagination it shows me that same page number 1. Well, the main issue is page number is not passed into the function(Composable API).
Template Table

      SN
      Account Type
      Name
      Shop Name
      Address
      contact No
      Email

        {{ ++i }}
        {{ account.account_type }}
        {{ account.name }}
        {{ (account.shop_name)?account.shop_name: 'EMPTY'}}
        {{ account.address }}
        {{ account.contact_number }}
        {{ account.email }}

  <Pagination :data="accounts" @pagination-change-page="getAccounts" />
</template>

In : data is passed the data that comes from composable API and in the @pagination-change-page the function is also passed from composable.
Script Tag
import LaravelVuePagination from 'laravel-vue-pagination';

export default {
    components: {
        'Pagination': LaravelVuePagination
    },
  setup() {
    }
    const paginates = ref(10);
    const { accounts, loading, getAccounts } = accountDetails();//Composables API
    onMounted(() => {
      getAccounts({paginate:paginates});
    });

    return { accounts, loading,getAccounts };
  },
};

Composable API
In this function I received two parameters, here is where Pagination(@pagination-change-page)should throw page number!!
import { ref } from '@vue/reactivity';
import axios from 'axios';

const accountDetails = () => {
    const accounts = ref({});
    const loading = ref(true);
    const accountError = ref({});

    const getAccounts = async ({page=1,paginate}) => {
        await axios.get('api/account/getAccounts?page='+page+'paginate='+paginate, {
            headers: {
                Authorization: `Bearer ${localStorage.getItem('token')}`,
                Accept: 'application/json',
            }
        }).then((res) => {
            accounts.value = res.data;
            loading.value = false;
            console.log(accounts.value);
        }).catch((resErr) => {
            loading.value = false;
            accountError.value = resErr;
        })
    }
    return { accounts, loading, accountError, getAccounts }
}
export default accountDetails;

A: Worked Successfully with Composition API Vue3
just remove paginate parameter from getAccounts and don't pass paginates to that function.

Updated Code  </>
Script
import LaravelVuePagination from 'laravel-vue-pagination';

export default {
    components: {
        'Pagination': LaravelVuePagination
    },
  setup() {
    }

    const { accounts, loading, getAccounts } = accountDetails();//Composables API
    onMounted(() => {
      getAccounts();
    });

    return { accounts, loading,getAccounts };
  },
};

Composable API
import { ref } from '@vue/reactivity';
import axios from 'axios';

const accountDetails = () => {
    const accounts = ref({});
    const loading = ref(true);
    const accountError = ref({});

    const getAccounts = async (page=1) => {
        await axios.get('api/account/getAccounts?page='+page, {
            headers: {
                Authorization: `Bearer ${localStorage.getItem('token')}`,
                Accept: 'application/json',
            }
        }).then((res) => {
            accounts.value = res.data;
            loading.value = false;
            console.log(accounts.value);
        }).catch((resErr) => {
            loading.value = false;
            accountError.value = resErr;
        })
    }
    return { accounts, loading, accountError, getAccounts }
}
export default accountDetails;


text:
Q: Why do I have two identical arrays when trying to separate struct stat by files and folders? I need to output files, sorted by creation date and folders. I went straight to separate everything in current catalogue into two arrays(one for file and one for files) and then do the stuff with them but suddenly I realized that I have two SIMILAR arrays. I need help.
#define _DEFAULT_SOURCE ;
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void insertionSort(struct stat* myArray)
{
  for(int i = 0; i < sizeof(myArray)/sizeof(struct stat); ++i)
      {
        int j = i - 1;
        while (j >= 0 && myArray[j].st_ctime > myArray[i].st_ctime)
         {
            myArray[j + 1].st_ctime = myArray[j].st_ctime;
            j = j - 1;
        }
        myArray[j + 1].st_ctime = myArray[i].st_ctime;
      }
}

int main()
{
  char cwd[PATH_MAX];
   if (getcwd(cwd, sizeof(cwd)) != NULL)
   {
     struct dirent *pDirent;
     DIR *pDir;
     pDir = opendir(cwd);
     if(pDir != NULL)
     {
       struct stat sb;
       struct stat* fileArray;
       struct stat* folderArray;
       fileArray = malloc(sizeof(struct stat));
       folderArray = malloc(sizeof(struct stat));
       int fiIndex = 0, foIndex = 0;
      while ((pDirent = readdir(pDir)) != NULL)
      {
        if(strcmp(pDirent->d_name, ".") != 0
        && strcmp(pDirent->d_name, "..") != 0)
        {
          stat(pDirent->d_name,&sb);
//I suppose that the mistake is somewhere in this switch but I'm not really so sure
           switch (sb.st_mode & S_IFMT)
           {
           case S_IFDIR:
           folderArray[foIndex++] = sb;
           folderArray = realloc(folderArray, sizeof(folderArray)+sizeof(struct stat));
           break;
           case S_IFREG:
           fileArray[fiIndex++] = sb;
           folderArray = realloc(fileArray, sizeof(fileArray)+sizeof(struct stat));
           break;
           }
        }
      }
      insertionSort(fileArray);
      insertionSort(folderArray);
       for(int i = 0; i<sizeof(fileArray)/sizeof(stat); ++i)
      {
        rewinddir(pDir);
         while ((pDirent = readdir(pDir)) != NULL)
         {
            if(strcmp(pDirent->d_name, ".") != 0
            && strcmp(pDirent->d_name, "..") != 0)
            {
              stat(pDirent->d_name,&sb);
              if(sb.st_ino == fileArray[i].st_ino)
              {
                printf("%s\n",pDirent->d_name);
              }
            }

         }
      }
     }
     closedir(pDir);
   }
  return 0;
}

And also I have a few questions like should I be using switch at all? Is there any more elegant way to compare for files or folders? The same about print, I think I made it kinda ugly :/

A: folderArray = realloc(fileArray, ...
Surely that is not what you intended.


text:
Q: AsyncTask within custom Adapter for gallery i want to use an asynctask in my custom adpater ImageAdapter to display all images from the phone because of the message too much work on UI Thread. I tried with this code (retrieving the case of a gifview for now) :
Adapter:
 public ImageAdapter(ArrayList<Media> liste, Context context) {
        this.listeImages = liste;
        mContext = context;
    }

    @Override
    public int getCount() {
        return listeImages.size();

    }

    @Override
    public Object getItem(int position) {
        return listeImages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolderPic viewHolder= new ViewHolderPic();

        if (convertView == null) {
             convertView = lInflater.inflate(R.layout.imagegallery, null);
             viewHolder.imageView = (ImageView)
convertView.findViewById(R.id.picGallery);
          //  viewHolder.gifView = (GifImageView)
convertView.findViewById(R.id.gifG);
              convertView.setTag(viewHolder);
            } else {
                viewHolder =(ViewHolderPic) convertView.getTag();
            }

            viewHolder.filePic = new
File(listeImages.get(position).getPath());
        PopulateGallery populate=new PopulateGallery();

            populate.execute(viewHolder);

            return convertView;
    }
}

AsyncTask :
class PopulateGallery extends AsyncTask {
        ViewHolderPic viewHolder;
        Bitmap bitmap;

    @Override
    protected Boolean doInBackground(ViewHolderPic... params) {
         viewHolder=params[0];
        int widhtPic=(screenWidth/3)-6;
      //  if(!getExtensionFile(viewHolder.filePic).equals("image/gif")) {
           // viewHolder.gifView.setVisibility(View.GONE);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            options.inPreferredConfig = Bitmap.Config.ARGB_4444;
            options.inDither = true;
           bitmap = decodeFile(viewHolder.filePic, widhtPic, (int)
   getResources().getDimension(R.dimen.imageGallery_height));

        return true;
    }

    @Override
    public void onPostExecute(Boolean result){
        viewHolder.imageView.setImageBitmap(bitmap);
    }
}

But it's a mess. There are blanks spaces the size of images aren't the same. And sometimes OutOfMemoryError i didn't had before in UI thread. I tried to use :
  try {
            populate.execute(viewHolder).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
       } catch (ExecutionException e) {
           e.printStackTrace();
        }

But no result.I thought it was because the task wasn't finished before returning convertView but the problem remains. What can i do to fix this thing. Thanks.

A: You can use Picasso. It is a nice library to handle image related task like showing large image, image from network or others.


text:
Q: Is it possible to detect the suppression of an object in InDesign using CEP/ExtendScript? I'm currently creating a plugin on InDesign and I would like to know if it's possible to detect if the user deletes an object ?
Because I would need to retrieve the id of the deleted object to remove it from an array.
I didn't find anything in the documentation about this I hope I didn't miss it.
if it's possible, i need to detect it on all elements of all pages.
I was thinking something like:
app.activeDocument.allPages.allItems.addEventListener("delete", function () {
     var idOfDeleteElement = this.id;
})

And also if the user selects several objects to delete, how to do ?
Here is an image to illustrate what I am talking about :

Thank you in advance !

A: The solution of @YuriKhristich is a good compromise :
Create a panel with a delete button and ask the user to use this button to delete items.


text:
Q: Unable to install @mui/x-data-grid in react npm install @mui/x-data-grid

throws an error
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: highradius@0.1.0
npm ERR! Found: react@18.0.0
npm ERR! node_modules/react
npm ERR!   react@"^18.0.0" from the root project
npm ERR!   peer react@"^17.0.0 || ^18.0.0" from @mui/material@5.6.0
npm ERR!   node_modules/@mui/material
npm ERR!     @mui/material@"^5.6.0" from the root project
npm ERR!     peer @mui/material@"^5.2.8" from @mui/x-data-grid@5.8.0
npm ERR!     node_modules/@mui/x-data-grid
npm ERR!       @mui/x-data-grid@"*" from the root project
npm ERR!   4 more (@emotion/react, @emotion/styled, react-dom, @mui/system)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^17.0.2" from @mui/x-data-grid@5.8.0
npm ERR! node_modules/@mui/x-data-grid
npm ERR!   @mui/x-data-grid@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\01kar\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\01kar\AppData\Local\npm-cache\_logs\2022-04-06T12_50_46_543Z-debug-0.log

What I think is that there is some version mismatch in the dependencies.
New to react so can't understand the dependencies. Please give a step by step process to resolve this error.
{
  "name": "highradius",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.9.0",
    "@emotion/styled": "^11.8.1",
    "@mui/base": "^5.0.0-alpha.75",
    "@mui/material": "^5.6.0",
    "@testing-library/jest-dom": "^5.16.3",
    "@testing-library/react": "^12.1.4",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

This is the package.json file.
I tried installing npm install @mui/material @emotion/react @emotion/styled and it was installed successfully now I am trying to install data grid but its showing me this error.

A: npm i @mui/x-data-grid --legacy-peer-deps

Installing using this solved the issue for me.

A: Based on @mui/x-data-grid's documentation, it looks like this snippet of code should fix this issue
"peerDependencies": {
  "@mui/material": "^5.0.0",
  "react": "^17.0.0"
},

A: add --legacy-peer-deps at the end of your npm command like below
npm i @mui/x-data-grid --legacy-peer-deps

A: try npm install @mui/x-data-grid --legacy-peer-deps and it will work fine.


text:
Q: Can not push Docker Image to Artifactory in Jenkins pipeline using Artifactory plugin I'm using a Docker Registry on Artifactory. I'm able to pull/push images using docker commands. Now I try to push an image using a Jenkins pipline.
The image is called registry-url/docker/image:latest.
I have a docker repository on Artifactory which is called docker. (I'm able to pull and push to this repo using docker commands).
This stage describes my Artifactory configuration:
...
        stage('Deploy Docker image'){
            steps {
                script {
                    def server = Artifactory.server 'xxx'
                    def rtDocker = Artifactory.docker server: server
                    def buildInfo = rtDocker.push('registry-url/image:latest', 'docker')
                    //also tried:
                    //def buildInfo = rtDocker.push('registry-url/docker/image:latest', 'docker')
                    //the above results in registry/docker/docker/image..
                    server.publishBuildInfo buildInfo
                }
            }
        }
...

When I use different paths I face the manifest.json error which is probably normal.
I'm able to download the manifest.json manually on: https://registry-url/artifactory/docker/image/latest/manifest.json.
I'm using a pretty new version of Docker on Jenkins:
Docker version 18.01.0-ce, build 03596f51b1

So far so good. But When I run the pipeline I receive the following error in Jenkins (it takes 50 seconds):
Pushing image: registry-url/image:latest
...
com.github.dockerjava.api.exception.DockerClientException: Could not push image: unknown: Not Found
    at com.github.dockerjava.core.command.PushImageResultCallback.awaitSuccess(PushImageResultCallback.java:49)
    at org.jfrog.hudson.pipeline.docker.utils.DockerUtils.pushImage(DockerUtils.java:60)
    at org.jfrog.hudson.pipeline.docker.utils.DockerAgentUtils$3.call(DockerAgentUtils.java:213)
    at org.jfrog.hudson.pipeline.docker.utils.DockerAgentUtils$3.call(DockerAgentUtils.java:205)
    at hudson.remoting.UserRequest.perform(UserRequest.java:153)
    at hudson.remoting.UserRequest.perform(UserRequest.java:50)
  ...

In Artifactory logs I see:
2018-04-25 14:24:26,663 [http-nio-8081-exec-xx] [ERROR] (o.a.a.d.r.DockerResource:153) - Unsupported docker v2 repository request for 'image'
2018-04-25 14:24:46,684 [http-nio-8081-exec-xx] [ERROR] (o.a.a.d.r.DockerResource:153) - Unsupported docker v2 repository request for 'image'
2018-04-25 14:24:46,689 [http-nio-8081-exec-xx] [ERROR] (o.a.a.d.r.DockerResource:153) - Unsupported docker v2 repository request for 'image'
2018-04-25 14:24:46,702 [http-nio-8081-exec-xx] [ERROR] (o.a.a.d.r.DockerResource:153) - Unsupported docker v2 repository request for 'image'

What am I missing or doing wrong?
EDIT:
Based on this issue I went back to my initial idea:
def buildInfo = rtDocker.push('registry-url/docker/image:latest', 'docker')

I tried the build again. Error:
Could not find manifest.json in Artifactory in the following path: https://registry-url/artifactory/docker/docker/image/latest/manifest.json

Two times 'docker' in the path and it seems not to work. BUT when I check in Artifactory the image is there... I can also pull the image. It seems to be fine but still the jenkins build is failing.
Artifactory Plugin: 2.15.1
Artifactory Version: 5.10.3
Is this really a bug which will be fixed soon?

A: Artifcatory can be configured as a docker registry either with or without a reverse proxy.
It looks like your Artifactory is not configured using a reverse-proxy (proxy-less configuration). You can read more about the configuration options here.
Version 2.16.1 of the Jenkins Artifactory Plugin added support for proxy-less configuration. Upgrading your Artifactory Plugin should resolve your issue.

A: Try following this example. Here we have Jenkins pipeline to pull/push docker image to/from Artifactory: https://github.com/jfrogtraining/kubernetes_example/blob/master/docker-app/Jenkinsfile#L43


text:
Q: Adding custom checkbox to WooCommerce product variation options I've added a custom field to variable products in the WC admin. Using the action:
action_woocommerce_variation_options_pricing

But it's displaying in the wrong location. I'd ideally like the checkbox to display in the options section above. But i can't find the action to move it there.
I've spent ages looking through the WC docs, but can't find the correct action. Does anyone know the correct way for me to move the checkbox to this location?

A: You can use the woocommerce_variation_options action hook, to add a custom checkbox to the WooCommerce product variation options.
(Copied from: views/html-variation-admin.php, line 188)
<?php do_action( 'woocommerce_variation_options', $loop, $variation_data, $variation ); ?>

So you get:
// Add checkbox
function action_woocommerce_variation_options( $loop, $variation_data, $variation ) {
    $is_checked = get_post_meta( $variation->ID, '_mycheckbox', true );

    if ( $is_checked == 'yes' ) {
        $is_checked = 'checked';
    } else {
        $is_checked = '';
    }

    ?>
    <label class="tips" data-tip="<?php esc_attr_e( 'This is my data tip', 'woocommerce' ); ?>">
        <?php esc_html_e( 'Checkbox:', 'woocommerce' ); ?>
        <input type="checkbox" class="checkbox variable_checkbox" name="_mycheckbox[<?php echo esc_attr( $loop ); ?>]"<?php echo $is_checked; ?>/>
    </label>
    <?php
}
add_action( 'woocommerce_variation_options', 'action_woocommerce_variation_options', 10, 3);

// Save checkbox
function action_woocommerce_save_product_variation( $variation_id, $i ) {
    if ( ! empty( $_POST['_mycheckbox'] ) && ! empty( $_POST['_mycheckbox'][$i] ) ) {
        update_post_meta( $variation_id, '_mycheckbox', 'yes' );
    } else {
        update_post_meta( $variation_id, '_mycheckbox', 'no' );
    }
}
add_action( 'woocommerce_save_product_variation', 'action_woocommerce_save_product_variation', 10, 2 );


text:
Q: Как автоматически обновлять страницу на локальном компьютере я соединила два компа локально друг к другу, открыла на втором сайт который верстаю, а на первом IDE, чтобы писать код.
Как мне сделать так, чтобы при сохранений кода, на втором компе сайт автоматически обновлялся?


text:
Q: Append the same key value to a list of dict I have a list of dict and I want to append the same key value to all dict.
For example :
l = [
    {'name' : 'abc', 'age' : '20', 'city' : 'abc'},
    {'name' : 'def', 'age' : '20', 'city' : 'def'},
    {'name' : 'hij', 'age' : '20', 'city' : 'hij'},
    {'name' : 'klm', 'age' : '20', 'city' : 'klm'},
    {'name' : 'nop', 'age' : '20', 'city' : 'nop'}
    ]

for d in l:
    d['date'] = '30/10/2019'

output :
{'name': 'abc', 'age': '20', 'city': 'abc', 'date': '30/10/2019'}
{'name': 'def', 'age': '20', 'city': 'def', 'date': '30/10/2019'}
{'name': 'hij', 'age': '20', 'city': 'hij', 'date': '30/10/2019'}
{'name': 'klm', 'age': '20', 'city': 'klm', 'date': '30/10/2019'}
{'name': 'nop', 'age': '20', 'city': 'nop', 'date': '30/10/2019'}

So it's work but in my real case I have more values (2000 dicts with 40 keys). And I want know if there is a way to append the date to each dict without a for.

A: I would just use a for-loop.
However, in the spirit of actually answering the question as asked, you could use map() to run an implicit for-loop at C-speed:
>>> from itertools import repeat
>>> from collections import deque
>>> from operator import setitem

>>> _ = deque(map(setitem, l, repeat('date'), repeat('30/10/2019')), maxlen=0)

>>> from pprint import pprint
>>> pprint(l)
[{'age': '20', 'city': 'abc', 'date': '30/10/2019', 'name': 'abc'},
 {'age': '20', 'city': 'def', 'date': '30/10/2019', 'name': 'def'},
 {'age': '20', 'city': 'hij', 'date': '30/10/2019', 'name': 'hij'},
 {'age': '20', 'city': 'klm', 'date': '30/10/2019', 'name': 'klm'},
 {'age': '20', 'city': 'nop', 'date': '30/10/2019', 'name': 'nop


text:
Q: Two Pivot Tables in the same excel sheet I have created a Pivot Table in the same sheet with the source data. Now, I want to create a second Pivot Table in the same sheet with same data source, but with different printed data inside the Pivot Table (of course). I keep getting an error, as it says that Pivot Table cannot overwrite another Pivot Table. However, they way I have selected the ranges where the pivot tables are created, they dont overwrite each other. I tested manually too. Also, if I record the process it just uses exact references for the source data, which I dont want to use because the lastrow and lastcolumn change daily. Just to remind it, the macro works great for creating the first table. The second table is the issue. Below, I will provide my code as it is now.
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable1 As PivotTable
Dim PTable2 As PivotTable
Dim PRange As Range

Application.DisplayAlerts = True
Set DSheet = Worksheets("Budget_Report")

Set PRange = DSheet.Range(Cells(1, 53), Cells.SpecialCells(xlCellTypeLastCell))

Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
Set PTable1 = PCache.CreatePivotTable(TableDestination:=DSheet.Cells(4, 1), TableName:="PivotTable1")
Set PTable2 = PCache.CreatePivotTable(TableDestination:=DSheet.Cells(17, 2), TableName:="PivotTable2")

With ActiveSheet.PivotTables("PivotTable1")

  With .PivotFields("T-Lane")
    .Orientation = xlRowField
    .Position = 1
    .Subtotals(1) = True
    .Subtotals(1) = False
  End With

  With .PivotFields("Monthly Cost FCST")
    .Orientation = xlDataField
    .Position = 1
    .Function = xlAverage
    .Caption = "Monthly Cost Forecast"
  End With

End With

With ActiveSheet.PivotTables("PivotTable2")

  With .PivotFields("Oran")
    .Orientation = xlRowField
    .Position = 1
    .Subtotals(1) = True
    .Subtotals(1) = False
  End With

  With .PivotFields("Monthly Cost FCST")
    .Orientation = xlDataField
    .Position = 1
    .Function = xlAverage
    .Caption = "Monthly Cost Forecast"
  End With

End With

A: When you insert the first pivot table and insert another one before populating the first one, the empty pivot table range of the first pivot table occupies the destination cell [DSheet.Cells(17, 2)] of the second pivot table.
I think you should insert the first pivot table and populate it and then insert another one and populate that as well.
See if that resolves your issue.
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable1 As PivotTable
Dim PTable2 As PivotTable
Dim PRange As Range

Application.DisplayAlerts = True
Set DSheet = Worksheets("Budget_Report")

Set PRange = DSheet.Range(Cells(1, 53), Cells.SpecialCells(xlCellTypeLastCell))

Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)
Set PTable1 = PCache.CreatePivotTable(TableDestination:=DSheet.Cells(4, 1), TableName:="PivotTable1")

With ActiveSheet.PivotTables("PivotTable1")

  With .PivotFields("T-Lane")
    .Orientation = xlRowField
    .Position = 1
    .Subtotals(1) = True
    .Subtotals(1) = False
  End With

  With .PivotFields("Monthly Cost FCST")
    .Orientation = xlDataField
    .Position = 1
    .Function = xlAverage
    .Caption = "Monthly Cost Forecast"
  End With

End With

Set PTable2 = PCache.CreatePivotTable(TableDestination:=DSheet.Cells(17, 2), TableName:="PivotTable2")

With ActiveSheet.PivotTables("PivotTable2")

  With .PivotFields("Oran")
    .Orientation = xlRowField
    .Position = 1
    .Subtotals(1) = True
    .Subtotals(1) = False
  End With

  With .PivotFields("Monthly Cost FCST")
    .Orientation = xlDataField
    .Position = 1
    .Function = xlAverage
    .Caption = "Monthly Cost Forecast"
  End With

End With

A: From the MSDN doc on pivot tables:

"Important" If you define multiple PivotTables on the Excel
  Worksheet, it is possible the resulting tables can grow and overlap
  each other if the Activity returns a large dataset. In this scenario,
  you will receive "A PivotTable report cannot overlap another
  PivotTable report" when you refresh the data. You can correct this
  error by adding addition columns or rows between the pivot tables to
  allow the tables to grow with out overlapping.


text:
Q: Unable to import libraries to eclipse When I try to use libraries they all seem empty to me (when I try to import them I can only see 'empty' packages). I tried both: drag-drop libraries to \libs and importing them. I don't know what is causing this problem...
I'm trying to import androidplot libraries, I'm not finding this particular issue on their boards so maybe I'm doing something wrong?!

EDIT

A: You're importing the  androidplot sources jar which wont work because its full of .java files instead of the expected .class files. Use the library jar instead.

A: You should put them in your "libs" folder below, among with the others such as "android-support-v4", not with the Android the dependencies.

A: depending on the ADT version that you use, you may want to start reading here
Note that lib usages is no longer simple process of copying jars to a folder and building. The library project may need to be in eclipse and build as 'library' then referred to as a dependency in the specific idiom mentioned above in link.

A: Follow the below steps .this might help you:
1-> Right Click on Your Project
2-> Click on Build Path
3->  Select Configure Build Path
4-> Select Add External JAR
5-> Locate Jar file in your System and add


text:
Q: Datatables generating character in single cell I am using data tables in jQuery AJAX, but the issue is that the data returned is populating an alphabet in a single cell and filling up a row  with letters instead of whole word in a cell. I need like this
----------------------------------------
title   |     description  |    location
----------------------------------------
abc               def             ghi

while it generates like
----------------------------------------
title   |     description  |    location
----------------------------------------
a                 b                 c

$.ajax({
  type: "POST",
  url: "countr.php",
  data: {
    'countryid': $id
  },
  dataType:'json',
  success: function (data) {
    $.each(data.option2, function(key,value) {
      $('#example').DataTable().row.add(value.title).draw();

country.php page
// some query running and returning data...

while ($row = mysqli_fetch_array($summaryofresult))
{
  $data->option2[] = $row;
}
echo json_encode($data);


text:
Q: Error when building an android APK in Unity3D Might not be an error, maybe it's just me being kinda slow, but once I click on build, on the usual menu, as the image below shows...
Unity asks me to select "something" in my computer, which is weird, it doesn't lets me select a file, or a program, or anything. It's really really weird because I can't select anything. Once I close the window it gives me an error that no Android SDK could be found, also weird since I downloaded it from android's website and installed it properly. What could it be?

A: If you installed the Android Studio is easier to set up.
On Android Studio, follow these steps:
Tools > Android > SDK Manager

Now at new window copy the address from which this SDK (Android SDK location)

At unity go to:
Edit > preferences

At new windown (Unity preferences) go to tab External Tools
Paste andress from SDK location at the SDK place

If you have not Studio but have installed the SDK, you should look where this installed, find the SDK folder, copy this address and puts it in the Unity preferences> External Tools> SDK.


text:
Q: Bash regular expressions: Matching numbers 0-1000 I'm writing a script that executes scripts stored in a given directory, based on an array containing the filenames of the scripts.
Here's a section of my 'menu', just to clarify:
#######

Title: Test script 1
Description: Test script 1
To execute: 0

#######

Title: Test script 2
Description: Test script 2
To execute: 1

#######

I have an array named array that contains the names of the scripts with an index corresponding to the printed value under "to execute". Right now, I'm using a case statement to handle input and provide an exit option.
case $REPLY in
     [Ee]) clear
           exit;;
     [[:digit:]] $scriptDirectory/${array[$REPLY]}

However, the [[:digit:]] expression only matches 0-9. I need a regex that works in the case statement that matches 0-999, or similar.

A: case only uses globs (aka filename expansion patterns), not regular expressions.
You can set extended glob with shopt -s extglob, then you can use +() to match one or more occurrence :
shopt -s extglob

case $REPLY in
     [Ee]) clear
           exit;;
     +([[:digit:]])) $scriptDirectory/${array[$REPLY]};;
esac

Note : I added missing ) after your second case pattern and missing ;; at the end of the same line. Also added the esac missing statement.
Update :
If you just want to match numbers between 0 and 999, try this :
     [0-9]?([0-9])?([0-9]))  $scriptDirectory/${array[$REPLY]};;

Character range are used here as I find it a bit more readable. The result will be the same.

A: The easiest way I've found is bash is:
^(1000|[0-9]{1,3})$

Using this regex combined with the =~ operator (which interprets the string to the right as an extended regular expression) you can construct a simple test. (with your input as "$1")
if [[ $1 =~ ^(1000|[0-9]{1,3})$ ]]; then
    echo "0 <= $1 <= 1000 (1)"
else
    echo "$1 - invalid number"
fi

Example Use/Output
$ for i in -10 -1 0 1 10 100 999 1000 1001; do ./zero1thousand.sh $i; done
-10 - invalid number
-1 - invalid number
0 <= 0 <= 1000
0 <= 1 <= 1000
0 <= 10 <= 1000
0 <= 100 <= 1000
0 <= 999 <= 1000
0 <= 1000 <= 1000
1001 - invalid number

A: In this simple case I suggest you use something like below :
REPLY="$1" # I assumed there is an argument to the script

if [[ $1 =~ ^[[:digit:]]+$ ]]
then
   padded_REPLY=$(printf "%04d" "$REPLY")
   #echo "Padded reply : $padded_REPLY"
else
   padded_REPLY="$REPLY"
   echo "Padded reply : $padded_REPLY"
fi

regexp1="^[[:digit:]]{4}$" #checks padded_REPLY is in the range 0000 to 1000
#the input is padded
regexp2="[eE]+$"

if [[ "$padded_REPLY" =~ $regexp1 ]]
then
   if [ "$REPLY" -le 1000 ] #checking script exist
   then
     echo "$REPLY" # I just echoed, you do the stuff below
     #"$scriptDirectory/${array[$REPLY]}"
   else
     echo "Scripts are numbered from 0 to 1000"
   fi
elif [[ "$padded_REPLY" =~ $regexp2 ]]
then
  clear
  exit
fi

But getopts is suggested to for smarter argument management.

A: Give a try to this:
case $REPLY in
  [Ee])
        clear
        exit 0;;

  [[:digit:]]|[[:digit:]][[:digit:]]|[[:digit:]][[:digit:]][[:digit:]]|1000)
        $scriptDirectory/${array[$REPLY]}
        exit 0;;
esac

The involved pattern list matches 1 digit or 2 digits or 3 digits or 1000.
The pattern used with case is described in Pattern Matching Notation from the Open Group.
Please note that this is not a regular expression.
There is at least one thing taken from Regular Expression; this is the [] (RE Bracket Expression). It is used to match a single char. So, [[:digit:]] is valid. It matches a single char which could be any digit.
To match several digits, it is needed to concatenate several patterns matching a single character, e.g. use [[:digit:]][[:digit:]] to match 2 digits.
| can be used to match more than one pattern. To match a number between 0 and 99, i.e. one digit or 2 digits numbers, use [[:digit:]]|[[:digit:]][[:digit:]]


text:
Q: ArrayPlot3D mesh customization I am trying to visualize a few 2D arrays in ArraryPlot3D. I think I have made it work, however, there is a minor detail on the mesh of the plot I want to improve.
For example, this is what the current 3d plot looks like:

However, if you look closely at the details of the edge, you will see there is a tiny tail, which I want to remove. I wonder if there is a easy way to achieve this? I notice that this effect is not prominent when the Mesh thickness is small.
tl;dr: I want to remove this tiny tail  in ArrayPlot3D when the mesh thickness is large.
Here I attach the sample code:
blank = ConstantArray[0, {10, 10}];

block = ConstantArray[1, {10, 10}];

ArrayPlot3D[{block, blank, blank, block, blank, blank, block, blank,
  blank, block},
 MeshStyle -> Directive[AbsoluteThickness[2.5], Black],
 ImageSize -> 1200]

A: Add an option, BaseStyle->RenderingOptions->{"3DRenderingMethod"->"BSPTree"}
blank=ConstantArray[0,{10,10}];
block=ConstantArray[1,{10,10}];

ArrayPlot3D[{block,blank,blank,block,blank,blank,block,blank,blank,block},
  MeshStyle->Directive[AbsoluteThickness[2.5],Black],ImageSize->1200,
  BaseStyle->RenderingOptions->{"3DRenderingMethod"->"BSPTree"}]

A: blank = ConstantArray[0, {10, 10}];
block = ConstantArray[1, {10, 10}];

ArrayPlot3D[{
  block, blank, blank, block, blank, blank,
  block, blank, blank, block},
 MeshStyle ->
  Directive[AbsoluteThickness[2.5], Black],
 ImageSize -> 1200,
 Method -> "ArrayMesh"]


text:
Q: Draggable with freezed panel I am making a draggable image like google map.
This image has grids.  The left column needs to be freezed.  So I output the same image twice. One is the main image.  The other is the freezed column, narrow and on top.
.freezed {
  width: 120px;
  overflow: hidden;
  position: absolute;
  z-index: 1;
  left: 0;
  top: 0;
}

The size of any grid is unknown, so no snapping to grid.
http://jsfiddle.net/7TMj8/2/
Please advise on how to do the following.  Thanks.

*

*On dragging in x direction, only the big one moves.  The narrow one stays.

*On dragging in y direction, the big one and the narrow one move in sync.

A: Listen the drag event of draggable  to find the moving direction. Set the top position of freezed div using .css() on drag.
Script
$('.draggable').draggable({
    // Narrow one is moving in Y direction while dragging the big one in Y direction
    drag: function (event, ui) {
        var xpos = ui.position.left;
        var ypos = ui.position.top;
        $(".freezed").css('top', ypos);
    }
});

Working DEMO


text:
Q: setting gvim as editor for crontab I've see many post saying that by setting the following evnironment variable
EDITOR=vim

or
VISUAL=vim

will allow to use vim as code editor for crontab.
I would likt to try to use gvim instead of vim,  so I stick it in that environment variable, but every time I call crontab -e a blank page appears.
Is it something missing there? Is it doable?
I am using CENTOS 6.5.

A: You need to add the -f parameter to let gvim start in foreground mode:
EDITOR='gvim -f' crontab -e


text:
Q: is it reasonable to use NoSQL for my project Imagine you want to write a webapp for selling your car online.
A car has a lot of attributes. Like how many doors, color, aircondition, etc. Some of them are simple boolean values, others might need to store more information (number of doors).
Some Accounts will become upgraded to "re/taider" accounts and they will have the possibility to sell more then one car.
From what I learned at school this actually screams for a relational database model.
But I would really like to get into NoSQL.
Would it be very silly to use Mongodb or Couchdb in this case?
Here is a more specific question, which exceeds my understanding and might give you a clue of my thinking.
A car has many attributes and you want to search for a car with as many attributes you like.
Now the only way I know how to handle this in NoSQL is to have a lot of Map-reduced views.
However, with only 12 attributes there is a possibility of 4096 different combinations. One can not do 4096 map-reduces for this use case. It can't be the common way, I mean it does not feel right.

A: Given that you say you believe this data model screams "relational" the thought that comes to mind is, "I have a nail and I would really like to use a crescent wrench.... Can you?  Yes.  Are you aware of the tradeoffs?  Doubtful."
The basic point about NoSQL is that it makes sense when your data use cases are fairly simple and you have encapsulated that behind a full-featured API.  The example I give for an area where NoSQL would generally be very good would be the backplane of an LDAP directory forest.
For the application you mention your big issue is likely to be flexibility in reporting.  You would have to purpose build your reports in advance and that's the major cost.  For an application like this, that is a very big cost.
One other point I would make is that you may find that there are opportunities to use NoSQL along side the RDBMS.  For example you could implement a caching system for the web app using it.


text:
Q: Expectation of the ratio of two $\mathcal{X}^2(1)$ random variables Let $X$ and $Y$ be two possibly dependent Chi-squared random variables both with $k=1$. Is it possible for $\mathbb{E}[X/Y]$ to be unbounded?

A: Yes. For instance,
$$\mathbb{E} 1/Y=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty} \frac{1}{x^2} e^{-x^2/2}\textrm{d}x=\infty
$$
So if $X$ and $Y$ are independent, we have $\mathbb{E}(X/Y)=\infty$.

A: A Chi-squared random distribution with $k=1$ can be realized as the square of a standard normal random variable.  So take $X = U^2$ and $Y = V^2$, where
$U$ and $V$ are independent $N(0,1)$.  Then $U/V$ has a Cauchy distribution, which already has no expected value (i.e $\mathbb E[|U/V|] = \infty$).
$U^2/V^2$ is even worse, as $U^2/V^2 \ge |U/V| - 1/4$.


text:
Q: How to use a variable declared in another function Hi,
I want to make global a variable called "lists" and declare its value on this function so I can use it on another function as well:
   var lists;
   document.addEventListener("DOMContentLoaded", function(event) {
  var parentOfMyList = document.body;
    attributes: true,
    childList: true,
    subtree: true
  };

  var callback = function(mutationsList) {
    for (var mutation of mutationsList) {
      if (mutation.type == 'childList') {
        var elt = document.getElementById("contents");
        if (elt) {
          lists = elt.textContent;
          console.log(lists);
          observer.disconnect();
        }
      }
    }
  };
  var observer = new MutationObserver(callback);
  observer.observe(parentOfMyList, config);
});

this other function:
function playthis() {
 const input = lists;
 const sounds = input.toLowerCase();
 console.log(sounds);
}

I tried by removing "var" before the variable "lists" but it didnt work. It says "input" is undefined. Whats wrong?
Thank you

A: Why are you doing const input = lists;? Can't you just const sounds = lists.toLowerCase();. If the variable wasn't global, you'd get an error on const input = lists;. Are you sure the variable is a string? Try add console.log(typeof lists) at the top of function playthis

A: You must need to define Global Variable in Global Scope. I am not able to connect with last }); in your first code section. it does not tell whether var lists is in some code block or declared globally outside. if you can post complete code it will be easy to see its scope with respect to function you are calling it in. I mean Put it before $(document).ready(function() {. If you have shown complete code then it would be easy to detect. Please try below code -
//Globally Defined
var lists;

$(document).ready(function() {

   document.addEventListener("DOMContentLoaded", function(event) {
  var parentOfMyList = document.body;
    attributes: true,
    childList: true,
    subtree: true
  };

  var callback = function(mutationsList) {
    for (var mutation of mutationsList) {
      if (mutation.type == 'childList') {
        var elt = document.getElementById("contents");
        if (elt) {
          lists = elt.textContent;
          console.log(lists);
          observer.disconnect();
        }
      }
    }
  };
  var observer = new MutationObserver(callback);
  observer.observe(parentOfMyList, config);
});

function playthis() {
 const input = lists;
 const sounds = input.toLowerCase();
 console.log(sounds);
}

If this does not solve your problem please do below changes to code. I want to see data at few places.
var callback = function(mutationsList) {

    // In case mutationsList if JSON Object Otherwise just console mutationsList
    console.log(JSON.stringify(obj));
    for (var mutation of mutationsList) {
      if (mutation.type == 'childList') {
        var elt = document.getElementById("contents");
        console.log(elt);
        if (elt) {

          lists = elt.textContent;
          console.log(lists);
          observer.disconnect();
        }
      }
    }
};


text:
Q: Can not OAuth using Facebook iOS SDK Since February 6th I have a question about Facebook OAuth.
Since Febrary 6th, I can not connect to Facebook in Developing iOS Apps.
Before,  I can do it.
And, I try to test Facebook sample apps addition of iOS SDK.
The BooleanOGSample of sample in iOS6.0, is able to connect to Facebook, But version iOS5.0 is not able to connect.
Maybe, ver 6.0 is used by 'FBUserSettingsViewController' in SDK, but ver 5.0 is connect by web page.
But the web page 404.
How to connect to Facebook OAuth by iOS5.0, iOS5.1 ?
the facebook sdk is 3.1.1 (release october 2012 )

A: It seems that you are using older sdk of facebook ,you shoudldownload newer versioin of the facebookSDK for iPhone and then try,If still you can not pass from Oauth then try to make a new application on developer.facebook.com .
Hope it will help you.


text:
Q: program windows CE in c# 2012? is their way to developing an application for windows ce device? I have a barcode scanner device with an OS of windows ce and I only have a visual studio 2012. If we buy the 2008 version its only add to cost of development and its possible we only use that in once. If not possible is there any free PL out there that can be use?

A: The development environment available depends on the version of Windows CE that runs on the scanner.
So you'll need to determine the Windows CE version, and then take a look at this page: Developing .NET Compact Framework apps in Post-2008 Visual Studio?


text:
Q: probability event was performed by specific group Toys for boys and for girls are donated to a benefit event by two groups. The Lakeville Do-Gooders donated 5 toys for boys and 7 for girls. The Southside Champions Club donated 6 toys for boys and 5 for girls. The master of ceremonies pulls the first toy out of a bin and it's a toy for a boy. Find the probability that it was donated by the Do-Gooders.
-- My thought process is that the sample space is 11 (total number of boy toys [ha]), and there are 5 instances where those eleven toys were donated by the Do-Gooders, making the solution: 5/11. However, given the nature of this class, I'm quite certain this problem can not be asking something so straight forward. Are there other factors I need to be considering?


text:
Q: Qooxdoo - what's the easiest way to include a specific qx class into the API I'm trying to include qx.io.reques in my application but i can't seem to find the right way to do it!
I tried to configure the configure.json file and added "API_INCLUDE": ["qx.io.request*"] in let section and ran the file again but it didn't work.
Running ./configure.py source-all fixes it but makes it very slow to load the application because it's loading all the classes in the api, i need only the default classes along with qx.io.request.
I read the documentation in qooxdoo website but i couldn't understand all the different options and which one works for me.
i want to enable xhr requests in my application so that i can send ajax requests, is there an easy way to do that?

A: In case anyone else run through the same problem, i found two ways to do it:

1- Run the generate.py file using source-all flag, this would include all the available classes in the api.
./generate.py source-all

then run the generate.py file without flages, this will remove all unnecessary classes and leave the ones used by your application.

./generate.py

2- Edit the file configure.json and scroll to the "let": section and add the property "API_INCLUDE" and set it's value to whatever classes you want to include in your application like this:

"let":
{
    "API_INCLUDE"  :    ["qx.io.request.*", "qx.ui.toolbar.*"],
    "API_EXECLUDE" :   .....
}

then run the generate.py file with api flag:
./generate.py api

A: For one thing, you are trying to include a class into your application. In qooxdoo, you simply do that by using the class. So if you want to make an Ajax request, you simply write code in your application that uses one of qooxdoo's IO classes, e.g.
var req = new qx.io.request.Xhr("/some/path/file.ext");

and let the Generator include the Xhr class in your application.
This will happen with the next run of ./generate.py source or similar (there is no ./configure.py what you wrote). An exception is, as you wrote in your own answer, running the source-all job as it includes all known classes into the app, so the build will work whatever classes you are actually using. As for documentation, jobs are documented here.
So generally speaking, you will normally not need to make any configuration changes, in order to use a specific class from the framework, you just use it in your code. If for some reason a class is not included although you actually use it and have re-build the application, you can use the include config key to force the inclusion of this class. But this should be a rare exception.
The API_INCLUDE macro you mention only influences the generated API documentation which is entirely different from your application itself. (An application is usually not referred to as being an "API"). To see the difference just run ./generate.py source and open source/index.html, as opposed to running ./generate.py api and opening api/index.html. The first is your application, the second the API documentation for your application.


text:
Q: Which hogan.js templeting package to use with express.js? The hogan.js template package that express provide is hjs, however, that package last update was a year ago, and the repo at github got issues opened also a year ago (though not really crucial ones).
There also seems to be more than one hogan.js package for express tempting at npm which left me confused!

A: If you see hjs source code, it's only 63 or so lines and it require hogan.js to work, so it's just a wrapper to make it work on express.
The one I used is hogan-express which is also a wrapper for hogan.js (it's required in package.json) and it's no more than 150.
My point, to try to clarify things, it's that the important module is hogan.js all the rest modules to integrate in express are just wrappers. I believe is also worth to give a try to the consolidate module which also support Hogan.
By looking to githubs stars (not necesarily quality indicator) you will see
consolidate (*548) > express-hogan(*48) > hjs (*8)
If you are wondering why hjs was the "chosen" for the express command line the answer is this pull request You can see by your self what it takes to implement another module. So may be some one should report if hjs is giving problems and there is a better alternative. It's not hard  to change it in express.


text:
Q: How to make progress bar location to be synchronous when maximizing the windows form? I tried docking but it works in some pre defined positions. I want to place it in a small area at the bottom of the form and keep its relative position when maximizing the form.

A: Hold the progressor position steady with the anchor. Anchor = Bottom, Left means that my distance from the bottom and left is the same in all sizes of Windows.
If I am now 10px from the left, I will be 10px away from the resize, and so bottom

A: you can put the progress bar inside a panel then dock the panel on bottom part.
Check this out;
actual size

Maximized

But please take a note to place the progress bar on the upper left corner inside the panel


text:
Q: Can't play MediaPlayer onCreate I have an app where I want, as soon as it starts, a little background music (opa gangam style!) to be played (from the sd card). I use the code:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MediaPlayer mp = new MediaPlayer();
    String filePath = Environment.getExternalStorageDirectory().getPath() + "/mymusic/gangamstyle.mp3";
    try {
        mp.setDataSource(filePath);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mp.start();

But when I test it, no music is played. I see everything is ok however. What could I do wrong? Thanks a lot

A: You have to use setOnPreparedListener in order to know when the media player is ready to play:
MediaPlayer player = new MediaPlayer();
player.setDataSource(filePath);
player.setVolume(100, 100);
player.setLooping(false);
player.setOnPreparedListener(new OnPreparedListener()
{
    @Override
    public void onPrepared(MediaPlayer mp)
    {
        mp.start();
    }
});
player.prepare();

A: There is some problem in your file path. Media player gives this kind of error when the file path is not correct. So, Please check your file path and then try it.


text:
Q: How to dynamically load a panel in Windows Forms? there are some buttons on the top of the winform, and when I click one of them, the panel below will load different predefined panel, how can I implement this ?
please see this example:

A: Here's a solution using a standard WinForms TabControl, where the Tabs are hidden at run-time, but of course they are available at design-time.
Assumptions :

*

*You don't want to get into creating OwnerDrawn Tabs, which is possible.

*A standard WinForms TabControl will meet all your design-time needs.
Code :

*

*In the Form Load event of the Form that hosts your TabControl use code like this :
tabControl1.Region = new Region(tabControl1.DisplayRectangle);

To hide the Tabs.

*Then, "wire" up your buttons to handle selecting the different TabPages in the TabControl. Obviously you could do this in a more elegant way than this :
private void button1_Click(object sender, EventArgs e)
{
  tabControl1.SelectedTab = tabControl1.TabPages[0];
}

private void button2_Click(object sender, EventArgs e)
{
  tabControl1.SelectedTab = tabControl1.TabPages[1];
}

Note : if you want to insert secondary Forms or UserControls into the TabPages of a TabControl : that's not a problem : of course simpler to use UserControls. Insert them into the Controls collection of each TabPage and set their 'Dock Property to 'DockStyle.Fill.
Note : there are fancier ways you can hide the Tabs, like using a derived TabControl as shown here on CodeProject : TabControl on a WinForm without showing the Tab header? There are other solutions out there that use a modified WndProc. They're not hard to find.

A: I don't know exactly what you're trying to do, but if you've got a Panel on your form named contentArea and a bunch of user controls created (but not on the form), then you could use this as an event handler for a button:
public void myButton_Click(object sender, EventArgs e) {
    contentArea.Controls.RemoveAt(0);
    contentArea.Controls.Add(new MyUserControl());
}

...though as other people have said, a tab control would be better in this case.

A: What you can do is have them each in a separate Panel. Set the Visible property to false to each. When the Click event on the button, set the Visible property of all of them to false and set the one you want shown's Visible to true.

A: For example if you have two form Form1 and Form2 and you want to load form2 inside from1. when you press a button to load form2 the code is like this
private void button1_Click(object sender, EventArgs e)
{
     Form2 form2 = new Form2();
     this.Controls.Clear();
     foreach(Control c in this.Controls)
     {
         this.Controls.Add(c);
     }
}

this code will load all the controls in the form2 into form1.


text:
Q: Pulling historical Intraday Volume data from BBG using R I have a question regarding Pulling intraday historical volume data from bloomberg using "RBBG" package. The way to go in excel is =BDH("IBM US Equity","VOLUME","12/31/2014 9:30:00 AM","12/31/2014 3:30:00 PM","BARTP=T","BARSZ=360","DIR=V","Dts=H").
I do understand that using R, one can pull the data from the trade table as
test <- bar(conn, "IBM US Equity","TRADE","2015-02-23 9:30:00.000","2015-02-23 15:45:00.000","375")

..but the output I am getting doesnt seem to be correct if the take the volume from this line
> test
  time   open  high    low  close numEvents volume
2015-02-23T14:30:00.000 2015-02-23T14:30:00.000 164.23 164.4 162.76 163.28      4079 666782

I will really appreciate any inputs on this..


text:
Q: Express & Passport with multiple subdomains I'm merging two little apps into one, that is supposed to be accessed via two subdomains. To do so I'm using the module "express-subdomain". I'm trying to use Passport so when a user logs in in the first app, he is logged in in both apps. However using req.isAuthenticated() I can indeed login in the "first" app, but then I'm not in the "second" one.
I'm searching for any solution to have a passport authentification in the first subdomain and being logged in in the second one, including keeping two disctinct apps if needed.
Assuming that passport is correctly configured for a local strategy, as well as the routers and the rest of the app. Here is what it looks like :
app.js
// <- requires etc

var passport = require('./configurePassport.js')(require('passport'));

var app = express();

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressSession({
    secret: 'bestSecretEver',
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
// and others

var firstRouter = express.Router();
firstRouter.use('/public', express.static(__dirname + '/first/public'));
firstRouter.use(favicon(__dirname + '/first/public/favicon.ico'));

// <- setting first router's GET, POST etc

app.use(subdomain('sub1', firstRouter)); // for sub1.example.com

var secondRouter = express.Router();
secondRouter.use('/public', express.static(__dirname + '/second/public'));
secondRouter.use(favicon(__dirname + '/second/public/favicon.ico'));

// <- setting second router's GET, POST etc

app.use(subdomain('sub2', secondRouter)); // for sub2.example.com

Any idea ?

A: Look into where you're saving your cookies for authentication purposes. Make sure you have it saved to the root domain. ie: *.example.com and not sub1.example.com


text:
Q: Пузырчатая сортировка в JS. Помогите?

var array = new Array(8, 4, 2, 3, 6);

document.write(array);

b = 5;

for (k = 0; k < b - 1; k++) {

  swap = 0;

  for (i = 0; i < b - k - 1; i++) {

    if (array[i] > array[i + 1]) {
      temp = array[i + 1];
      array[i + 1] = array[i];
      array[i] = temp;
      swap++;
    }
  }
  document.write(array[i] + " ");
}

Вместо отсортированного списка выводит: 8 4 2 3 68 6 4 3.

A: Вывод отсортированного массива нужно производить после цикла и вместо явного указания размера массива лучше использовать свойство Length
var array = [8, 4, 2, 3, 6];
swap =0;
for (k = 0; k < array.Length; k++) {
    for (i = 0; i < array.Length - k - 1; i++) {
        if (array[i] > array[i + 1]) {
            temp = array[i + 1];
            array[i + 1] = array[i];
            array[i] = temp;
            swap++;
        }
    }
}
for (i=0;i<array.Length; i++)
    document.write(array[i] + " ");

A:
вместо отсортированного списка выводит:---> 8,4,2,3,68 6 4 3

ну так всё правильно, 8,4,2,3,6 это ваш первый вывод перед циклом document.write(array);
и затем дальше пишется 8 6 4 3 вот этой строкой document.write(array[i] + " "); только поменяйте i на k  - document.write(array[k] + " ");
И вообще лучше вывод делать за циклом. Сортировка и вывод это две логически разные операции, надо такое разделять.

A: Как совет: лучше написать функцию, которая будет сортировать и возвращать отсортированный массив, на мой взгляд так будет правильнее, можно будет использовать в дальнейшем. Смотреть, что получилось в результате - по завершению сортировки. Убрать неиспользуемую переменную swap. Пример рабочего кода:

var array = new Array(8, 4, 2, 3, 6);

function BubbleSort(arr) {
  var n = arr.length;
  for (var i = 0; i < n - 1; i++) {
    for (var j = 0; j < n - 1 - i; j++) {
      if (arr[j + 1] < arr[j]) {
        var temp = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = temp;
      }
    }
  }
}

BubbleSort(array);

for (index = 0; index < array.length; index++)
  document.write(array[index] + " ");

Пузырьковая сортировка выполняет следующие действия: проход
  по массиву с обменом местами соседних элементов, нарушающих заданный
  порядок, до тех пор, пока массив не будет окончательно отсортирован.

Очень полезная ссылка: Алгоритмы сортировок на JavaScript

A: function bubleSorting(arr) {
do {
    var swaped = false;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] > arr[i + 1]) {
            var tmp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = tmp;
            swaped = true;
        }
    }
}
 while(swaped != false);
return arr;
}
var numArray = [5, 21, 6, -12, 0.2, 33];
document.write(bubleSorting(numArray));


text:
Q: REPL hangs on SublimeREPL for Clojure (Windows PC) I'm trying to use SublimeREPL with Sublime Text 2 so that I can programme with Clojure.  I have installed SublimeREPL using the package manager.
I go to

Tools > SublimeREPL > Clojure

and start a repl this seems to start fine, but whatever I type in and hit enter does nothing.  It does not return anything not even an error.
I have Lein installed.
I am using a Windows PC
Has anyone had this problem?

A: Yes, I have had this trouble with versions 2 and 3. From what I can see, it's a known issue. I have also reported it on GitHub: https://github.com/wuub/SublimeREPL/issues/356
Also, this solution worked for me: Sublime Text, SublimeREPL, Clojure & Windows 8


text:
Q: Database design for different kinds of userprofiles in SQL Server I have a web application where I have 2 kinds of users: teachers and others. I have created a usertable where the accountinfo resides. with accountinfo, I mean emailaddress, username, password, lastactivitydate etc. Each user has a profile and a profile contains data like age, aboutme, address etc, so this info is in nature different from what is in the user table, that's why I have a separate UserProfile table with a FK of UserId pointing back to the user table.
I was quite happy with this design till I realized that the profile for a teacher has more fields then for others (the others may get additional fields that differ from those of teachers also in the future). For a teacher, I need for example his school etc. So then I would have an additional TeacherProfile table containing the extra data. So that would mean that I would do a join between 3 tables to get all the data for a teacher: User, BaseUserProfile, TeacherProfile. So I am wondering if it was a good idea to separate the base userprofile data to a separate table, of should I merge that table with the User table? What other options are there for this problem?

A:
2 kinds of users

These are usually called roles. So you would normally  have these tables:

*

*tblUser

*

*UserId (PK)

*RoleId (FK)

*Email

*LastLoggedIn

*PasswordHash

*Salt

*tblUserProfile

*

*UserProfileId (PK)

*UserId (FK)

*Contains columns for both teachers and students, some values will be NULL for students

*tblUserRole

*

*RoleId (PK)

*RoleName

I understand that this is likely to be a learning task, but even there start using good security practices - do not store passwords (encrypted or not) at all. Instead store secure hash of the password and salt used to generate the hash.


text:
Q: how to join sys_query_history and stl_querytext in redshift I need Some Info for Executed query from sys_query_history
like
status,result_cache_hit,start time,end_time,erroor message
and get the full text from stl_querytext
How to join these 2 table Since the queryid is different in these 2 table
i was using sys_query_history.transaction_id= stl_querytext.xid
and sys_query_history.session_id= stl_querytext.pid
but its not working since user can execute more than 1 quert in same session
in that case the query_id in  sys_query_history is not same as query in stl_querytext

A: I'm not sure what you mean by "the queryid is different in these 2 table".  Both sys_query_history and stl_querytext have the query id as a column (query_id and query respectively).
You should just add -
AND sys_query_history.query_id= stl_querytext.query

to your JOIN ON clause.


text:
Q: Issue while build JasperServer with PostgreSQL Database I am trying to customize the installation of JasperServer.
I have downloaded the source. I have deployed successfully using MySQL database. I want to use PostgreSQL and remove the MySQL database. When I do that it does not work. I tried steps mention in Build Guide.
But Tomcat does not start as deployment descriptor has details of MySQL database. I changed the content to PostgreSQL. Then it worked but now it is not uploading the css and showing the weird view.
Please check with image how it shows.![This is the login page when I deploy the jasperserver][1]
Please help if anyone have done it successfully..
Thanks.....
Error on tomcat..
INFO: Server startup in 9759 ms
2011-11-14 17:15:49,647  WARN FileBufferedOutputStream,Finalizer:237 - Error while deleting the temp
orary file
2011-11-14 17:15:49,650  WARN FileBufferedOutputStream,Finalizer:237 - Error while deleting the temp
orary file
2011-11-14 17:15:49,650  WARN FileBufferedOutputStream,Finalizer:237 - Error while deleting the temp
orary file
2011-11-14 17:15:49,651  WARN FileBufferedOutputStream,Finalizer:237 - Error while deleting the temp
orary file
2011-11-14 17:15:49,651  WARN FileBufferedOutputStream,Finalizer:237 - Error while deleting the temp
orary file
2011-11-14 17:15:49,652  WARN FileBufferedOutputStream,Finalizer:237 - Error while deleting the temp
orary file
2011-11-14 17:15:49,652  WARN FileBufferedOutputStream,Finalizer:237 - Error while deleting the temp
orary file
2011-11-14 17:15:49,653  WARN FileBufferedOutputStream,Finalizer:237 - Error while deleting the temp
orary file

A: Make changes in file "decoratorCommonImports.jsp"
Provide direct path of theme folder like
" type="text/css" media="screen"/>
replace above line with following one..

Thanks..


text:
Q: couldn't create a lua module in C++ (can't include local header) I'm using vs code and g++ to compile c++, however I can't include lua.h, lauxlib.h, lualib.h etc.
this is the terminal (using vscode terminal):
C:\MingW\bin> .\g++ C:\Users\leand\Desktop\VSCODE\cpp\template.cpp -o C:\Users\leand\Desktop\VSCODE\cpp\build.exe -I C:\Users\leand\Desktop\VSCODE\cpp\
C:\Users\leand\AppData\Local\Temp\cc6kM8pM.o:template.cpp:(.text+0x1d): undefined reference to `lua_tonumberx'
C:\Users\leand\AppData\Local\Temp\cc6kM8pM.o:template.cpp:(.text+0x3b): undefined reference to `lua_tonumberx'
C:\Users\leand\AppData\Local\Temp\cc6kM8pM.o:template.cpp:(.text+0x59): undefined reference to `lua_pushnumber'
C:\Users\leand\AppData\Local\Temp\cc6kM8pM.o:template.cpp:(.text+0x9f): undefined reference to `luaL_checkversion_'
C:\Users\leand\AppData\Local\Temp\cc6kM8pM.o:template.cpp:(.text+0xba): undefined reference to `lua_createtable'
C:\Users\leand\AppData\Local\Temp\cc6kM8pM.o:template.cpp:(.text+0xd4): undefined reference to `luaL_setfuncs'
c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../libmingw32.a(main.o):(.text.startup+0xa0): undefined reference to `WinMain@16'
collect2.exe: error: ld returned 1 exit status

this is the folder (C:\Users\leand\Desktop\VSCODE\cpp)
this is my code
#ifdef __cplusplus
extern "C" {
#endif
#include "luaconf.h"
#include "lualib.h"
#include "lauxlib.h"
#include "lua.h"

int soma(lua_State *L) {
    double nl = lua_tonumber(L, 1);
    double n2 = lua_tonumber(L, 2);
    double resultado = nl + n2;
    lua_pushnumber(L, resultado); /* Empurra para o stack do Lua o valor resultado return 1; /* Informa quantas variáveis estão sendo retornadas para o Lua */
    return 1; // quantas variaveis retornam para o Lua
}

int luaopen_template(lua_State *L){ /* lua_State *L é um tipo de ponteiro específico para a API do Lua */
    luaL_Reg funcoes[] = { /* Recurso para listar funções C que devem ser levadas para o Lua */
        {"soma", soma},
        {NULL, NULL} /* Indicador que a lista acabou */
    };
    luaL_newlib(L, funcoes); /* Define uma nova biblioteca Lua com as funções passadas por Lual_Reg */
    return 1;
}

#ifdef __cplusplus
}
#endif


text:
Q: UPDATE vs INSERT statement performance in PostgreSQL I am working with a database of a million rows approx.. using python to parse documents and populate the table with terms.. The insert statements work fine but the update statements get extremely time consuming as the table size grows..
It would be great if some can explain this phenomenon and also tell me if there is a faster way to do updates.
Thanks,
Arnav

A: Sounds like you have an indexing problem.  Whenever I hear about problems getting worse as table size grows, it makes me wonder if you're doing a table scan whenever you interact with a table.
Check to see if you have a primary key and meaningful indexes on that table.  Look at the WHERE clause you have on that UPDATE and make sure there's an index on those columns to make finding that record as fast as possible.
UPDATE: Write a SELECT query using the WHERE clause you use to UPDATE and ask the database engine to EXPLAIN PLAN.  If you see a TABLE SCAN, you'll know what to do.


text:
Q: Como faço para incorporar uma pagina HTML dentro de outra sem iframe? Tenho uma pagina comum porém dentro de body em uma div quero por uma li ou um p de outro html, assim eu tenho uma página main caso eu precise fazer alterações e tenho conteúdos externos. Sem precisar mudar todas as páginas quando eu for inserir um novo link no menu, por exemplo. li sobre o  e o import na tag link mas não consegui por. alguem pode me ajudar?

A: Fala Guilherme,
você pode usar a função load() do jQuery
$( "#ul" ).load( "pagina-com-o-ul-modificado #ul-menu" );

http://api.jquery.com/load/
E como o JBueno disse, existem diversas frameworks que possuem suporte pra isso, vai depender da linguagem que você vai usar.


text:
Q: html scroll bar inside scroll box I am making a scroll box for and i put some code in it , the problem is that the horizontal scroll bar is inside the box instead of belonging to it

         [code language="cpp"]
         my code...
         [/code]

I don't see what can cause this behavior.
UPDATE the scroll bar inside the scroll box belongs to the [code] block and its there whither i use
 or not.

A: Try changing its position in css with -webkit-scrollbar.
something like:
div::-webkit-scrollbar{
     bottom:-10px;
}

for more information:
https://css-tricks.com/almanac/properties/s/scrollbar/


text:
Q: Open GL Android 3D Object Rotation Issue I am having trouble rotating my 3D objects in Open GL. I start each draw frame by loading the identity (glLoadIdentity()) and then I push and pop on the stack according to what I need (for the camera, etc). I then want 3D objects to be able to roll, pitch and yaw and then have them displayed correctly.
Here is the catch... I want to be able to do incremental rotations as if I was flying an airplane. So every time the up button is pushed the object rotates around it's own x axis. But then if the object is pitched down and chooses to yaw, the rotation should then be around the object's up vector and not the Y axis.
I've tried doing the following:
glRotatef(pitchTotal, 1,0,0);
glRotatef(yawTotal, 0,1,0);
glRotate(rollTotal, 0,0,1);

and those don't seem to work. (Keeping in mind that the vectors are being computed correctly)I've also tried...
glRotatef(pitchTotal, 1,0,0);
glRotatef(yawTotal, 0,1,0);
glRotate(rollTotal, 0,0,1);
 and I still get weird rotations.
Long story short... What is the proper way to rotate a 3D object in Open GL using the object's look, right and up vector?

A: You need to do the yaw rotation around (around Y) before you do the pitch one. Otherwise, the pitch will be off.
E.g. you have a 45 degrees downward pitch and a 180 degrees yaw. By doing the pitch first, and then rotate the yaw around the airplane's Y vector, the airplane would end up pointing up and backwards despite the pitch being downwards. By doing the yaw first, the plane points backwards, then the pitch around the plane's X vector will make it point downwards correctly.
The same logic applies for roll, which needs to be applied last.
So your code should be :
glRotatef(yawTotal, 0,1,0);
glRotatef(pitchTotal, 1,0,0);
glRotatef(rollTotal, 0,0,1);

A: Cumulative rotations will suffer from gimbal lock. Look at it this way: suppose you are in an aeroplane, flying level. You apply a yaw of 90 degrees anticlockwise. You then apply a roll of 90 degrees clockwise. You then apply a yaw of 90 degrees clockwise.
Your plane is now pointing straight downward — the total effect is a pitch of 90 degrees clockwise. But if you just tried to add up the different rotations then you'd end up with a roll of 90 degrees, and no pitch whatsoever because you at no point applied pitch to the plane.
Trying to store and update rotation as three separate angles doesn't work.
Common cited solutions are to use a quaternion or to store the object orientation directly as a matrix. The matrix solution is easier to build because you can prototype it with OpenGL's built-in matrix stacks. Most people also seem to find matrices easier to understand than quaternions.
So, assuming you want to go matrix, your prototype might do something like (please forgive my lack of decent Java knowledge; I'm going to write C essentially):
GLfloat myOrientation[16];

// to draw the object:
glMultMatrixf(myOrientation);
/* drawing here */

// to apply roll, assuming the modelview stack is active:
glPushMatrix();                    // backup what's already on the stack
    glLoadIdentity();              // start with the identity
    glRotatef(angle, 0, 0, 1);
    glMultMatrixf(myOrientation);  // premultiply the current orientation by the roll

    // update our record of orientation
    glGetFloatv(GL_MODELVIEW_MATRIX, myOrientation);
glPopMatrix();

You possibly don't want to use the OpenGL stack in shipping code because it's not really built for this sort of use and so performance may be iffy. But you can prototype and profile rather than making an assumption. You also need to consider floating point precision problems — really you should be applying a step that ensures myOrientation is still orthonormal after it has been adjusted.
It's probably easiest to check Google for that, but briefly speaking you'll use the dot product to remove erroneous crosstalk from two of the axes to the third, then to remove from one of the first two axes from the second, then renormalise all three.

A: Thanks for the responses. The first response pointed me in the right direction, the second response helped a little too, but ultimately it boiled down to a combination of both. Initially, your 3D object should have a member variable which is a float array size 16. [0-15]. You then have to initialize it to the identity matrix. Then the member methods of your 3D object like "yawObject(float amount)" just know that you are yawing the object from "the objects point of view" and not the world, which would allow the incremental rotation. Inside the yawObject method (or pitch,roll ojbect) you need to call the Matrix.rotateM(myfloatarray,0,angle,0,1,0). That will store the new rotation matrix (as describe in the first response). You can then when you are about to draw your object, multiply the model matrix by the myfloatarray matrix using gl.glMultMatrix.
Good luck and let me know if you need more information than that.


text:
Q: Div doesnt go on bottom of screen My footer seems to interrupt my div bar, and doesnt show until i scroll to the footer,
It is supposed to show up at the bottom of the screen not the bottom of the page, and on the bottom of the footer, Help!
I have tried changing the margin, but that wouldnt make it responsive
Site: http://ultimaterealms.us/MediaUniverse.php
How i want it to be: http://goo.gl/wsJEcj

A: If you remove the position: relative; on the #wrapper, and on the body, then your #info will not position itself relative to it, rather relative to the screen.
You will also have to update #info to have a z-index of 2 or higher to sit above the #main.


text:
Q: haskell( Formulate and prove a base case and inductive step) I have some knowledge on haskell but need support to formulate and prove a base case and inductive step.
The user-defined Haskell function
addtoall :: Int -> [Int] -> [Int]

defined below, adds to each entry of an integer list a specified number (the first argument ofaddtoall).
addtoall :: Int -> [Int] -> [Int]
addtoall n [] = [] -- a.0
addtoall n (x:xs) = (x + n) : (addtoall n xs) -- a.1

The following exemplifies the behaviour of
addtoall:
Exam> addtoall 3 [7,2,9,12]
[10,5,12,15]

Look at the interactive session shown here.
Exam>
addtoall 3 [7,2,9,12]
[10,5,12,15]

Exam>
addtoall 2 [10,5,12,15]
[12,7,14,17]

Exam>
addtoall 2 (addtoall 3 [7,2,9,12]
[12,7,14,17]

Based on this, it is suspected that for all finite lists xs of type
[Int] and all numbers m and n of type Int it is
addtoall m (addtoall n xs) = addtoall (m + n) xs

Prove this statement by Structural Induction on xs. It should be conducted in two steps
a) formulate and prove the base case
b) formulate and prove the inductive step

A: as this is obvious some kind of homework I'll only show you the beginning.
So you should use structural induction - the only structure you have here is the structure of the list (and the exercise even tells you to ;)) - so the base case will be [] - what is the inductive case?
Now you have to prove it for both cases.
how to do it
To prove this using structural induction on xs you have to prove two cases:

*

*the base case with xs := []

*the inductive case with xs := y:ys
In both cases the most simple thing to do is to work on the left and right hand side to see if both are finally equal (if you know how you can work on the left and change it into the right) - always using the function-definitions and the information you`ve got from the case at hand.
For example in the inductive case  you not only have that xs = y:ys but you may also use that
addtoall m (addtoall n ys) = addtoall (m+n) ys (Ind)
base case
so start by simply writing both sides down and massage them with the definitions::
left:
addtoall m (addtoall n [])
{ a.0 }
= addtoall m []
{ a.0 }
= []

right:
addtoall (m+n) []
{ a.0 }
= []

obviously both sides are equal and you proved the first part.
Not think about the inductive case (hint: you surely need a.1 and have to use induction somehow) and try it ... it should not be hard - you basically only have to rewrite the stuff you already have and then play evaluator
inductive case
Please try it with this template:
left:
addtoall m (addtoall n (y:ys))
{ a.1 - inner }
= addtoall m ((y+n) : addtoall n ys)
{ a.1 - outer }
= ((y+n)+m) : addtoall m (addtoall n ys)
{ Ind }
= ((y+n)+m) : addtoall (m+n) ys
{ arithm }
= (y+(m+n)) : addtoall (m+n) ys

right:
addtoall (m+n) (y:ys)
{ a.1 }
(y+(m+n)) : addtoall (m+n) ys

remember in the end you should see the same thing
remarks

*

*I think you tried the right thing there but you should really add the needed steps (but your solution looks like the thing you want to see both left and right - so work towards it)

*usually you write x:xs in the inductive case but I wanted to make sure that you try the steps - also I was afraid that you might missinterpret xs:=x:xs ;)

external links

*

*Structural induction - Wikipedia