text:
Q: How to Lock a file and avoid readings while it's writing My web application returns a file from the filesystem. These files are dynamic, so I have no way to know the names o how many of them will there be. When this file doesn't exist, the application creates it from the database. I want to avoid that two different threads recreate the same file at the same time, or that a thread try to return the file while other thread is creating it.
Also, I don't want to get a lock over a element that is common for all the files. Therefore I should lock the file just when I'm creating it.
So I want to lock a file till its recreation is complete, if other thread try to access it ... it will have to wait the file be unlocked.
I've been reading about FileStream.Lock, but I have to know the file length and it won't prevent that other thread try to read the file, so it doesn't work for my particular case.
I've been reading also about FileShare.None, but it will throw an exception (which exception type?) if other thread/process try to access the file... so I should develop a "try again while is faulting" because I'd like to avoid the exception generation ... and I don't like too much that approach, although maybe there is not a better way.
The approach with FileShare.None would be this more or less:
    static void Main(string[] args)
    {
        new Thread(new ThreadStart(WriteFile)).Start();
        Thread.Sleep(1000);
        new Thread(new ThreadStart(ReadFile)).Start();

        Console.ReadKey(true);
    }

    static void WriteFile()
    {
        using (FileStream fs = new FileStream("lala.txt", FileMode.Create, FileAccess.Write, FileShare.None))
        using (StreamWriter sw = new StreamWriter(fs))
        {
            Thread.Sleep(3000);
            sw.WriteLine("trolololoooooooooo lolololo");
        }
    }

    static void ReadFile()
    {
        Boolean readed = false;
        Int32 maxTries = 5;

        while (!readed && maxTries > 0)
        {
            try
            {
                Console.WriteLine("Reading...");
                using (FileStream fs = new FileStream("lala.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
                using (StreamReader sr = new StreamReader(fs))
                {
                    while (!sr.EndOfStream)
                        Console.WriteLine(sr.ReadToEnd());
                }
                readed = true;
                Console.WriteLine("Readed");
            }
            catch (IOException)
            {
                Console.WriteLine("Fail: " + maxTries.ToString());
                maxTries--;
                Thread.Sleep(1000);
            }
        }
    }

But I don't like the fact that I have to catch exceptions, try several times and wait an inaccurate amount of time :|

A: You can handle this by using the FileMode.CreateNew argument to the stream constructor.  One of the threads is going to lose and find out that the file was already created a microsecond earlier by another thread.  And will get an IOException.
It will then need to spin, waiting for the file to be fully created.  Which you enforce with FileShare.None.  Catching exceptions here doesn't matter, it is spinning anyway.  There's no other workaround for it anyway unless you P/Invoke.

A: i think that a right aproach would be the following:
create a set of string were u will save the current file name
so one thread would process the file at time, something like this
//somewhere on your code or put on a singleton
static  System.Collections.Generic.HashSet<String> filesAlreadyProcessed= new  System.Collections.Generic.HashSet<String>();

//thread main method code
bool filealreadyprocessed = false
lock(filesAlreadyProcessed){
  if(set.Contains(filename)){
    filealreadyprocessed= true;
  }
  else{
     set.Add(filename)
  }
}
if(!filealreadyprocessed){
//ProcessFile
}

A: Do you have a way to identify what files are being created?
Say every one of those files corresponds to a unique ID in your database. You create a centralised location (Singleton?), where these IDs can be associated with something lockable (Dictionary). A thread that needs to read/write to one of those files does the following:
//Request access
ReaderWriterLockSlim fileLock = null;
bool needCreate = false;
lock(Coordination.Instance)
{
    if(Coordination.Instance.ContainsKey(theId))
    {
        fileLock = Coordination.Instance[theId];
    }
    else if(!fileExists(theId)) //check if the file exists at this moment
    {
        Coordination.Instance[theId] = fileLock = new ReaderWriterLockSlim();
        fileLock.EnterWriteLock(); //give no other thread the chance to get into write mode
        needCreate = true;
    }
    else
    {
        //The file exists, and whoever created it, is done with writing. No need to synchronize in this case.
    }
}

if(needCreate)
{
    createFile(theId); //Writes the file from the database
    lock(Coordination.Instance)
        Coordination.Instance.Remove[theId];
    fileLock.ExitWriteLock();
    fileLock = null;
}

if(fileLock != null)
    fileLock.EnterReadLock();

//read your data from the file

if(fileLock != null)
   fileLock.ExitReadLock();

Of course, threads that don't follow this exact locking protocol will have access to the file.
Now, locking over a Singleton object is certainly not ideal, but if your application needs global synchronization then this is a way to achieve it.

A: Your question really got me thinking.
Instead of having every thread responsible for file access and having them block, what if you used a queue of files that need to be persisted and have a single background worker thread dequeue and persist?
While the background worker is cranking away, you can have the web application threads return the db values until the file does actually exist.
I've posted a very simple example of this on GitHub.
Feel free to give it a shot and let me know what you think.
FYI, if you don't have git, you can use svn to pull it http://svn.github.com/statianzo/MultiThreadFileAccessWebApp

A: The question is old and there is already a marked answer. Nevertheless I would like to post a simpler alternative.
I think we can directly use the lock statement on the filename, as follows:
lock(string.Intern("FileLock:absoluteFilePath.txt"))
{
    // your code here
}

Generally, locking a string is a bad idea because of String Interning. But in this particular case it should ensure that no one else is able to access that lock. Just use the same lock  string before attempting to read. Here interning works for us and not against.
PS: The text 'FileLock' is just some arbitrary text to ensure that other string file paths are not affected.

A: Why aren't you just using the database - e.g. if you have a way to associate a filename with the data from the db it contains, just add some information to the db that specifies whether a file exists with that information currently and when it was created, how stale the information in the file is etc. When a thread needs some information, it checks the db to see if that file exists and if not, it writes out a row to the table saying it's creating the file. When it's done it updates that row with a boolean saying the file is ready to be used by others.
the nice thing about this approach - all your information is in 1 place - so you can do nice error recovery - e.g. if the thread creating the file dies badly for some reason, another thread can come along and decide to rewrite the file because the creation time is too old. You can also create simple batch cleanup processes and get accurate data on how frequently certain data is being used for a file, how often information is updated (by looking at the creation times etc). Also, you avoid having to do many many disk seeks across your filesystem as different threads look for different files all over the place - especially if you decide to have multiple front-end machines seeking across a common disk.
The tricky thing - you'll have to make sure your db supports row-level locking on the table that threads write to when they create files because otherwise the table itself may be locked which could make this unacceptably slow.


text:
Q: How to Sort the Gridview Based Session values I have a gridview with hyperlink if i click on hyperlink the values going to button of the gridview.
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
    try
    {
        if (e.Row.DataItem != null)
        {
            // DataTable readDt = null;
            List<String> rows = null;
            //Fetching the List from Session Object
            if (Session["ReadJobDetails"] != null)
            {
                rows = (List<String>)Session["ReadJobDetails"];
            }
            if (rows.Contains(DataBinder.Eval(e.Row.DataItem, "JobTitle").ToString()))
            {
                //since we used GridView level CSS class, individual CSS class is not applying, so added manually
                //e.Row.BackColor = System.Drawing.Color.FromArgb(208, 217, 206);
                e.Row.BackColor = System.Drawing.Color.Silver;
                e.Row.ForeColor = System.Drawing.Color.White;
                e.Row.Font.Bold = false;
            }
            else
            {
                e.Row.BackColor = System.Drawing.Color.FromArgb(247, 247, 247);
                e.Row.ForeColor = System.Drawing.Color.Black;
                e.Row.Font.Size = 9;
                e.Row.Font.Bold = true;
            }
        }
        }
    catch (Exception)
    {
        throw;
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a vector of players and adding information to each I am creating a monopoly game that allows 1-6 players to play (if you choose one then you'll go up against an AI). I created a vector
vector <int> players;

and have asked for the user to enter how many players are playing
    int numplayers =0 ;
vector <int> players(numplayers);

cout << "How many players will be playing this round of Monopoly? 1-6" << endl;
cin >> numplayers;

}
after the user indicates how many players are playing I need to have each player choose a game piece and then display their game piece, amount of money, eventually properties owned etc.
I'm wondering how I can move through chosen number of players in the vector and assign each the entered information.
Any information would be very helpful.

A: I would recommend creating a class Player, add attributes to the players based on user input, and then store them in the vector players. This will also be more flexible for future changes, imo.


text:
Q: Do I have to populate tm_gmtoff and tm_zone? and, Which function shall I use mktime or gmtime to get a timezone-less datetime in C? I am trying to code a function which populates a struct tm from year, month, day, hour and minutes values.
The application deals with no time zone information, i.e., we assume that the input data time zone matches with the application and user time zone.
I have tried this:
void timeCreate(struct tm* pTm1, int year, int month, int day, int hour, int minute) {

    pTm1->tm_year = year - 1900;
    pTm1->tm_mon = month - 1;
    pTm1->tm_mday = day;
    pTm1->tm_hour = hour;
    pTm1->tm_min = minute;
    pTm1->tm_sec = 0;
    pTm1->tm_isdst = -1;
    mktime(pTm1);

}

If I don't do anything else, I get the CET time set by mktime (CET is my local timezone) and it seems that mktime changes the time and date, so it is no longer 2014/01/01 00:00 but the day before.
If I do this:
    pTm1->tm_gmtoff = 0;
    pTm1->tm_zone = "UTC";

Then I do not get any correction.
I have also seen the function gmtime() instead of mktime(). Which would be the "right" way of setting up this struct?
Also I get a random value for tm_wday, can that value be calculated automatically?

A: mktime only works with local time, and its behavior is constrained by the specification so that it cannot examine any nonstandard fields of struct tm like tm_gmtoff. And gmtime is not an analog of mktime but of localtime - it converts in the opposite direction. If you want a normalization/conversion of broken-down UTC time in struct tm format to time_t, you need to either use the nonstandard but widely available timegm function, or write it out yourself. Thankfully POSIX exactly specifies the formula:
tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
    (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
    ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400

Note that if copied as written to C code, this is full of integer overflows, so some type promotions or other fixes need to be introduced to make it valid.
If you need the normalization aspect timegm also performs, but need it done portably without depending on the nonportable timegm, you can just call gmtime_r after using the above formula to invert it and get a normalized result.

A:
Do I have to populate tm_gmtoff and tm_zone?
Which would be the "right" way of setting up this struct?

For portable code, yes.
The C spec has
"The tm structure shall contain at least the following members, in any order." (C spec) --> struct tm has at least the following 9 members:
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;

And may include others like tm_gmtoff, tm_zone, tm_msec, etc.

The mktime function converts the broken-down time, expressed as local time, in the structure pointed to by timeptr into a calendar time value with the same encoding as that of the values returned by the time function. The original values of the tm_wday and tm_yday components of the structure are ignored, and the original values of the other components are not restricted to the ranges indicated above. ...
... On successful completion, the values of the tm_wday and tm_yday components of the structure are set appropriately, and the other components are set to represent the specified calendar time, but with their values forced to the ranges indicated above; the final value of tm_mday is not set until tm_mon and tm_year are determined.
C17dr § 7.27.2.3 2

Since mktime() is only specified to ignore tm_wday and tm_yday, all other members may contribute to the result.  There is no C spec that limits the result to 7 of the above required members.
Good programing practice would zero out all members not explicitly initialized/assigned before calling mktime().
void timeCreate(struct tm* pTm1, int year, int month, int day, int hour, int minute) {
  memset(pTm1, 0, sizeof *pTm1);  // Zero all members.
  pTm1->tm_year = year - 1900;
  pTm1->tm_mon = month - 1;
  pTm1->tm_mday = day;
  pTm1->tm_hour = hour;
  pTm1->tm_min = minute;
  pTm1->tm_sec = 0;
  pTm1->tm_isdst = -1;
  mktime(pTm1);
  // recommend to return the result of mktime() so caller can ID invalid timestamps.
}

If you code is used on a sub-set of platforms, it may get away without such zeroing assignments.


text:
Q: Impossible to run app with Parse I have an issue with Parse. I had the sdk (downloaded on Parse.com and unzip inside /libs folder in my project) and when I build everything is good.
But when I run the app,I have this following error :
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_66\bin\java.exe'' finished with non-zero exit value 2

I don't know what to do, I search and tried everything I found on StackOverflow and github repo of Parse but nothing works :/
Any idea ?
Thanks in advance for your answer.

A: Simple in your gradle file add these ...
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {

    minSdkVersion 14
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"

    // Enabling multidex support.
    multiDexEnabled true

}

 // add dexOptions
dexOptions {
    incremental true
    javaMaxHeapSize "4g"
}
}

dependencies {
provided fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.parse:parse-android:1.11.0'
 // add multidex dependency
compile 'com.android.support:multidex:1.0.1'

}

reference: Error:Execution failed for task ':app:dexDebug' error in my project while I added new dependency

A: Try to clean your project (Build -> Clean Project) or try to add this:
 defaultConfig {
     multiDexEnabled true
 }

to your build.gradle file

A: Try to add the following code to your build.gradle (module: app)
dependencies{
...
...
compile 'com.parse.bolts:bolts-android:1.+'
compile fileTree(dir: 'libs', include: 'Parse-*.jar')
}

and no need of adding multiDex.
Hope this should work.


text:
Q: Combobox ListCollectionView Header not displaying. Groups Items correctly but blank Header I'm trying to fill a Combobox with a list of class objects.  The list items are the class object properties OptionName and they are supposed to be grouped by class object properties OptionCategory.  It seems to almost work, the items are grouped correctly and displayed correctly but the Header is just blank.  I've checked that the class objects are being correctly generated so they aren't just null/blank properties for OptionCategory.  As you can see in the below picture there are two blank headers.  The two categories right now are Release and Development and you can see they grouped correctly.
Image of Combobox
XAML
                    <ComboBox Name="ConfigList"  Grid.ColumnSpan="3" HorizontalContentAlignment="Center" VerticalContentAlignment="Top"
                              SelectedIndex="0" Grid.Column="1" Grid.Row="1" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center"
                              Width="224" Height="26" SelectionChanged="ConfigList_SelectionChanged">
                        <ComboBox.GroupStyle>
                            <GroupStyle>
                                <GroupStyle.HeaderTemplate>
                                    <DataTemplate>
                                        <TextBlock Text="{Binding OptionName}"/>
                                    </DataTemplate>
                                </GroupStyle.HeaderTemplate>
                            </GroupStyle>
                        </ComboBox.GroupStyle>
                        <ComboBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding OptionName}"/>
                            </DataTemplate>
                        </ComboBox.ItemTemplate>
                        <ComboBox.ItemContainerStyle>
                            <Style TargetType="{x:Type ComboBoxItem}">
                                <Setter Property="HorizontalContentAlignment" Value="Left"/>
                            </Style>
                        </ComboBox.ItemContainerStyle>
                    </ComboBox>

CODE BEHIND
        private void PopulateList()
        {
            ConfigList.SelectionChanged -= new SelectionChangedEventHandler(ConfigList_SelectionChanged);

            List<LoadedOption> xmlOptions = xmlFile.AllOptions;
            DataContext = this;
            ListCollectionView lcv = new ListCollectionView(xmlOptions);
            lcv.GroupDescriptions.Add(new PropertyGroupDescription("OptionCategory"));

            ConfigList.ItemsSource = lcv;

            ConfigList.SelectionChanged += new SelectionChangedEventHandler(ConfigList_SelectionChanged);
        }

CLASS
    public class LoadedOption
    {
        public Guid OptionID { get; private set; }
        public string OptionName { get; set; }
        public string OptionCategory { get; set; }
        public string SubPathName1 { get; set; }
        public string SubPathName2 { get; set; }
        public string SubPathName3 { get; set; }
        public string DriveLetterSub1 { get; set; }
        public string DriveLetterSub2 { get; set; }
        public string DriveLetterSub3 { get; set; }
        public string DrivePathBase { get; set; }
        public string DrivePathSub1 { get; set; }
        public string DrivePathSub2 { get; set; }
        public string DrivePathSub3 { get; set; }

        public LoadedOption()
        {
            this.OptionID = Guid.NewGuid();
        }
    }

A: I got it to work by changing Binding OptionName to Binding Name under the GroupStyle.HeaderTemplate section in the XAML.  Below is the answer I found.
"The TextBlock Text property is bound to a Name property, but please be aware that this is not the Name property on the data object (in this case the User class). Instead, it is the name of the group, as assigned by WPF, based on the property we use to divide the objects into groups."


text:
Q: Iterate over columns and rows (selected by label from label column) without overwriting I want to do the following thing:

*

*Get min and max for every measurement column within the same label (range of rows)

*Define a range for the interesting values (e.g. maximum * 0.6 up to maximum)

*Check for every measurement column within the same label if value lies in this interval (=True) or not (=False)

*Replace values outside this interval with NaN

I have a df like this:
df = {'Measurement_1': [1, 2, 7, 9, 34, 67, 50], 'Measurement_2': [3, 4, 30, 22, 55, 13, 45], 'Label': ['cable', 'cable', 'cable', 'wood', 'wood', 'wood', 'wood']}

I´m getting the maximum and minimum value for every measurement and every label as a separate df and define maximum_set and minimum_set for further conditions like this:
df_sort = df.groupby('Label')
measurement_values = df.columns.tolist()
measurement_values.remove('Label')

labels = df['Label'].unique().tolist()

df_sort = df_sort[measurement_values]

for label, data in df_sort:
    minimum = df_sort.min()
    maximum = df_sort.max()
    maximum_set = maximum
    minimum_set = maximum*0.6

Now I want to iterate over the original df to get a "measurement_filtered" column with a boolean value for every measurement and every label (e.g. check if all measurement_1 values lies between minimum_set and maximum_set). I´m doing this with the following loop:
for measurement in measurement_values:
     for label in labels:
         df[measurement +'_filtered'] = df.loc[df['Label'] == label,measurement].between(minimum_set.loc[label][measurement],maximum_set.loc[label][measurement], inclusive ='both')

This loop gives the correct boolean entries for every measurement and label. The problem is that the for loop and the .loc are overwriting the iterations before. So the final  df_filtered columns only include the last "label"-iteration (in this example 'wood'), the rest of the _filtered columns is empty. I don´t know how to fix this problem.

A: Let us not use for-loop instead we can use a vectorized/fast approach, here is the annotated code:
# select the measurement cols
cols = df.filter(like='Measure')

# groupby label and find the max value per grp
max_ = cols.groupby(df['Label']).transform('max')

# Create a boolean condition
cond = cols.ge(max_ * 0.6) & cols.le(max_)

# Mask the values with NaN where the above condition is
# False then assign the result back to original dataframe
df.assign(**cols.where(cond))

   Measurement_1  Measurement_2  Label
0            NaN            NaN  cable
1            NaN            NaN  cable
2            7.0           30.0  cable
3            NaN            NaN   wood
4            NaN           55.0   wood
5           67.0            NaN   wood
6           50.0           45.0   wood


text: Q: Wizard with wicked gem - use one page for multiple steps How is it possible to use one and the same view for several steps (for example, you have to loop on several questions to answer and the questions should be generated dynamically in the controller via before_action filter)?


text:
Q: Using tryCatch in the integral and mapply I have the date (test):
test<-structure(list(X = c(630L, 631L, 977L, 978L), si = c(1.063166618,
1.063166618, 1.063166618, 1.063166618), ho = c(-0.071587466,
-0.071587466, -0.071587466, -0.071587466), bd = c(0.998351574,
0.999361098, 0.999978304, 0.944579005), i1 = c(0.997434318, 0.997434318,
0.997434318, 0.997434318), x1b1m = c(2.938615084, 3.220915079,
4.088527679, 1.818297207), x1b1e = c(3.561241746, 3.843541741,
4.711154342, 1.594420075), x1b0m = c(2.714737952, 2.997037947,
3.864650548, 1.594420075), x1b0e = c(2.938615084, 3.220915079,
4.088527679, 0.971793413), x2b1m = c(7.432558537, 8.66190052,
8.643460274, 6.17045182), x2b1e = c(8.055185199, 9.284527183,
9.266086936, 5.946574688), x2b0m = c(7.208681405, 8.438023388,
8.419583142, 5.946574688), x2b0e = c(7.432558537, 8.66190052,
8.643460274, 5.323948026)), .Names = c("X", "si", "ho", "bd",
"i1", "x1b1m", "x1b1e", "x1b0m", "x1b0e", "x2b1m", "x2b1e", "x2b0m",
"x2b0e"), class = "data.frame", row.names = c(NA, -4L))

test<-
 X       si          ho        bd        i1    x1b1m    x1b1e    x1b0m     x1b0e    x2b1m    x2b1e    x2b0m    x2b0e
1 630 1.063167 -0.07158747 0.9983516 0.9974343 2.938615 3.561242 2.714738 2.9386151 7.432559 8.055185 7.208681 7.432559
2 631 1.063167 -0.07158747 0.9993611 0.9974343 3.220915 3.843542 2.997038 3.2209151 8.661901 9.284527 8.438023 8.661901
3 977 1.063167 -0.07158747 0.9999783 0.9974343 4.088528 4.711154 3.864651 4.0885277 8.643460 9.266087 8.419583 8.643460
4 978 1.063167 -0.07158747 0.9445790 0.9974343 1.818297 1.594420 1.594420 0.9717934 6.170452 5.946575 5.946575 5.323948

I am trying to find the integral using the following code. I want the code to return NA if error occurs, otherwise the integral value. For the row 1 and 4, it returns the value but for the row 2 and 3, it returns an error. Unfortunately, I have no success using tryCatch.
funint<- function(a,b,si,ho,bd,i1){
integrate(function(x){(1/bd)*(1/si)*dnorm((log(x)-b)/si)*pnorm(a+((ho/si)*(log(x)-b))/i1)},0,Inf)$value}

rowno<-as.list(rownames(test))
var<-c("b","e")
x1b1<-as.list(c("x1b1m","x1b1e"))
x1b0<-as.list(c("x1b0m","x1b0e"))
x2b1<-as.list(c("x2b1m","x2b1e"))
x2b0<-as.list(c("x2b0m","x2b0e"))

In the following code, for each i (row number), the integral function (funint) uses the values from columns x1b1 and x2b1 or x1b0 and x2b0 plus other four variables: si,ho,bd,and i1.
 kk<-data.frame(
tryCatch(
mapply(
function(j1b1,j2b1,j1b0,j2b0){
(sapply(rowno,
function(i){
funint(test[i,j1b1],test[i,j2b1],test[i,"si"],test[i,"ho"],test[i,"bd"],test[i,"i1"])-
                     funint(test[i,j1b0],test[i,j2b0],test[i,"si"],test[i,"ho"],test[i,"bd"],
    test[i,"i1"])}))
},x1b1,x2b1,x1b0,x2b0),error=function(e) print("hello")))
                           test[i,"i1"])
}))},x1b1,x2b1,x1b0,x2b0))
names(kk)<-paste0("var")

Expected output:
kk

 b        e
1 601.2711 2578.3789
2 NA        NA
3 NA         NA
2 188.4013  354.9656

Any help in this regard will be highly appreciated.
Note: The code works. My only problem is how to skip the error (by returning NA when error occurs) and keep the code working for other rows.

A: I think you just need to move the tryCatch farther inside the loop so that it catches exactly where the error is happening.
foo <- mapply(function(j1b1, j2b1, j1b0, j2b0) {
  sapply(rowno, function(i) {
    tryCatch({
      funint(test[i,j1b1], test[i,j2b1], test[i,"si"],
             test[i,"ho"], test[i,"bd"], test[i,"i1"]) -
      funint(test[i,j1b0], test[i,j2b0], test[i,"si"],
             test[i,"ho"], test[i,"bd"], test[i,"i1"])
    }, error=function(e) NA)
  })
}, x1b1, x2b1, x1b0, x2b0)
kk <- data.frame(foo)
names(kk) <- var
kk

##           b         e
## 1  601.2711 2578.3789
## 2 2046.8451        NA
## 3 2002.7819        NA
## 4  188.4013  354.9656


text:
Q: git over ssh: Repository read access denied I have a git server set up on Linux, and it's working great:
[git@HOST ~]$ git clone -v git://HOST.com/repositories/Extras
Cloning into Extras...
remote: Counting objects: 12, done.
remote: Compressing objects: 100% (12/12), done.
remote: Total 12 (delta 3), reused 0 (delta 0)
Receiving objects: 100% (12/12), 23.54 MiB | 16.63 MiB/s, done.
Resolving deltas: 100% (3/3), done.

Note that HOST.com is not real. :)
I would now like to get the same thing working over SSH, so I can add privacy and authentication. At the moment, it is not working:
[git@HOST ~]$ git clone -v ssh://HOST.com/repositories/Extras
Cloning into Extras...
Enter passphrase for key '/home/git/.ssh/id_rsa':
ERROR:gitosis.serve.main:Repository read access denied
fatal: The remote end hung up unexpectedly

It looks like the SSH connecting is working, but git is having some permissions problems. SELinux is not enabled.
In /var/log/messages, I see the following:
Sep 23 16:26:18 HOST sshd[32115]: Accepted publickey for git from X.X.X.X port 51023 ssh2
Sep 23 16:26:18 HOST sshd[32116]: fatal: mm_request_receive: read: Connection reset by peer
Sep 23 16:26:18 HOST sshd[32115]: pam_unix(sshd:session): session opened for user git by (uid=0)
Sep 23 16:26:19 HOST sshd[32121]: Received disconnect from X.X.X.X: 11: disconnected by user
Sep 23 16:26:19 HOST sshd[32115]: pam_unix(sshd:session): session closed for user git

Anyone have some advice on where I might start looking?
Thanks!
Mike

A: It looks like you're using Gitosis.  Have you configured your {{gitosis.conf}} to permit access to the repository you're tryng to use?  Have you installed your public key?
Start by turning on debug logging in your gitosis configuration:
[gitosis]
loglevel = DEBUG

This will result in verbose logging when you connect with ssh.
The most common causes of this problem are:
emphasized text
- A typo in the repository or user name.
- The wrong key installed, or key filename not matching the username in the configuration.
The debug output will highlight these problems effectively.  For example, connecting to our local gitosis repository with debug logging on includes the following:
Access check for 'lars@obliquity.example.com' as
  'writable' on 'gitosis-admin.git'...

(This shows who gitosis thinks I am.)
found 'lars@obliquity.example.com' in 'admins'

(This shows what group I'm associated with.)
Access ok for 'lars@obliquity.example.com' as
  'writable' on 'gitosis-admin'

(And this shows my access.)

A: If you're going to spend significant time on this, it's better to switch to gitolite. There will be no impact to the users as you can commit the same keys to the gitolite admin repo.
For your current problem, try accessing via SSH with the -vvvv option to see a detailed debug output of what key is being used etc.
Hope this helps.

A: Thanks everyone... In the end I went with gitolite, but that was not the source of the problem. It was a key mismatch between the client and the SSH server... A simple thing that I thought I'd checked. Once I matched up the user's .pub key that I had registered with git, and their ~/.ssh/id_rsa.pub, everything started working as expected.
Thanks!
Mike


text:
Q: Further extension needed for game tree (tikz) I've started making a game tree, but I get stuck after the second level. Suggestions for extending to the desired output or cleaner code are much appreciated.
Desired output

Current output

Current code
\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{figure}
\begin{tikzpicture}[
                   font = \footnotesize,
edge from parent/.style = {draw ,thin},
      SN/.style = {%solid node
                   circle, inner sep=1.2 ,fill=blue},
      HN/.style = {%hollow node
                   circle, inner sep=1.2, draw=blue,
                   },
 level distance = 25mm,
 level 1/.style = {sibling distance=50mm},
 level 2/.style = {sibling distance=40mm},
                    ]
    \node (n0) [HN] {}
        child{ node (n1) [SN]  {}
                edge from parent node[left]{text 1}
            }
        child{ node (n2) [SN]  {}
            child{node[HN]  {}
                edge from parent node[left]{text 3}}
            child{node[HN]  {}
                edge from parent node[right]{text 4}}
                edge from parent node[right]{text 2}};
\draw[<-,shorten <=1pt]
        (n0) -- + (2,1) node[right,align=left] {nodetext 1 };
\draw[<-,shorten <=1pt]
        (n2) -- + (2,1) node[right,align=left] {nodetext 2};
\end{tikzpicture}
    \caption{Game tree}
    \label{fig:Game tree}
\end{figure}

\end{document}

A: It is not true that the text has to go where the nodes are if you use one of the easier tree specification syntaxes. forest allows you to put the text from the nodes somewhere else entirely.
For example,
\documentclass[border=10pt,multi,tikz]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest}
  for tree={
    parent anchor=children,
    anchor=center,
    inner sep=0pt,
    l sep*=5,
    s sep*=5,
    delay={
      edge label/.wrap value={node [above, midway, sloped] {#1}; },
      if content={}{}{
        if n=1{
          pin/.wrap pgfmath arg={135:#1}{content()},
        }{
          pin/.wrap pgfmath arg={45:#1}{content()},
        }
      },
      circle,
      minimum size=2.5pt,
      fill,
      content={},
    }
  }
  [node text 1
    [, edge label=text 1]
    [node text 2, edge label=text 2
      [node text 3, edge label=text 3
        [node text 4, edge label=text 5
          []
          []
        ]
        []
      ]
      [, edge label=text 4]
    ]
  ]
\end{forest}
\end{document}

It is much easier to specify many or large trees this way because the brackets reflect the structure, the trees can be formatted consistently and flexibly and parts of the construction (or all of it!) can even be done automatically.

A: It may not be that easy to read, but it looks like it's possible to continue the way you started:
\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{figure}
\begin{tikzpicture}[
                   font = \footnotesize,
edge from parent/.style = {draw ,thin},
      SN/.style = {%solid node
                   circle, inner sep=1.2 ,fill=blue},
      HN/.style = {%hollow node
                   circle, inner sep=1.2, draw=blue,
                   },
 level distance = 25mm,
 level 1/.style = {sibling distance=50mm},
 level 2/.style = {sibling distance=40mm},
                    ]
    \node (n0) [HN] {}
        child{ node (n1) [SN]  {}
                edge from parent node[left]{text 1}
            }
        child{ node (n2) [SN]  {}
            child{node (n3) [HN] {}
                child{node (n4) [SN] {}
                    child{node[HN] {}
                        edge from parent node[left]{text 7}}
                    child{node[HN] {}
                        edge from parent node[right]{text 8}}
                    edge from parent node[left]{text 5}}
                child{node[SN] {}
                    edge from parent node[right]{text 6}}
                edge from parent node[left]{text 3}}
            child{node[HN]  {}
                edge from parent node[right]{text 4}}
                edge from parent node[right]{text 2}};
\draw[<-,shorten <=1pt]
        (n0) -- + (2,1) node[right,align=left] {nodetext 1};
\draw[<-,shorten <=1pt]
        (n2) -- + (2,1) node[right,align=left] {nodetext 2};
\draw[<-,shorten <=1pt]
        (n3) -- + (-2,1) node[left,align=right] {nodetext 3};
\draw[<-,shorten <=1pt]
        (n4) -- + (-2,1) node[left,align=right] {nodetext 4};
\end{tikzpicture}
    \caption{Game tree}
    \label{fig:Game tree}
\end{figure}

\end{document}

I suggest you to also note on your drawing the names of your nodes (n1 etc) when you name them, this helps.
There are also other kind of tree systems that can be easier to use, but note that the examples in this link put the text where you put nodes: drawing tree using tikz, child overlap .
See cfr's answer for an example more adapted to your needs.

A: Edit: istgame version 2.0
The istgame version 2 provides a new macro \xtCommentTo to put a comment to a node. The input mode changer \setistmathTF* is also a new macro available in the version 2.

\documentclass{standalone}

\usepackage{istgame}

\begin{document}

\begin{istgame}[sloped]
% action labels in text mode
\setistmathTF*000{textrm}
% tree part
\setistSolidNodeStyle[blue]
\setistHollowNodeStyle[blue]
\xtShowEndPoints[hollow node]
\xtdistance{30mm}{60mm}
\istroot(n0)[hollow node]
  \istb*{text 1}[above] \istb{text 2}[above]  \endist
\istroot(n1)(n0-2)
  \istb{text 3}[above]  \istb{text 4}[above]  \endist
\istroot(n2)(n1-1)[hollow node]
  \istb{text 5}[above]  \istb*{text 6}[above] \endist
\istroot(n3)(n2-1)
  \istb{text 7}[above]  \istb{text 8}[above]  \endist
% comment part
\xtCommentTo[bend right](n0)(2,1){nodetext 1}[r]
\xtCommentTo(n1)(2,1){nodetext 2}[r]
\xtCommentTo[bend left,dashed](n2)(-2,1){nodetext 3}[l]
\xtCommentTo[solid](n3)(-2,1){nodetext 4}[l]
\end{istgame}

\end{document}

Original answer
Here is a solution to use the istgame package. You can use the istgame package just like the tikzpicture environment, which means that you can use all the commands and options of tikzpicture together with macros provided with the istgame package within the istgame environment.

MWE:
\documentclass{standalone}
\usepackage{istgame}
%\usepackage{makecell}
\begin{document}

\begin{istgame}[sloped]
% tree part
\setistSolidNodeStyle[blue]
\setistHollowNodeStyle[blue]
\xtShowEndPoints[hollow node]
\xtdistance{30mm}{60mm}
\istroot(n0)[hollow node]
  \istb*{\mbox{text 1}}[above]
  \istb{\mbox{text 2}}[above]
  \endist
\istroot(n1)(n0-2)
  \istb{\mbox{text 3}}[above]
  \istb{\mbox{text 4}}[above]
  \endist
\istroot(n2)(n1-1)[hollow node]
  \istb{\mbox{text 5}}[above]
  \istb*{\mbox{text 6}}[above]
  \endist
\istroot(n3)(n2-1)
  \istb{\mbox{text 7}}[above]
  \istb{\mbox{text 8}}[above]
  \endist
% add some more
\begin{scope}[<-,shorten <=1pt]
\draw [->,shorten >=1pt,bend right=30] ($(n0)+(2,1)$) node [right] {nodetext 1} to (n0);
\draw (n1) -- +(2,1) node [right] {nodetext 2};
\draw (n2) -- +(-2,1) node [left] {nodetext 3};
\draw (n3) -- +(-2,1) node [left] {nodetext 4};
\end{scope}
\end{istgame}

\end{document}


text:
Q: Making image text to be black Is it possible to change the image text to be black and the background image to be white using java?
I'm able to make image grayscale or black and white but the text in the image will be white and the background black. Like below:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

public class GrayScalingImage {
public static void main(String args[]) throws Exception {

try {
File inputImage = new File("image.jpg");

BufferedImage image = ImageIO.read(inputImage);

for(int i=0; i<image.getHeight(); i++) {
for(int j=0; j<image.getWidth(); j++) {
Color color = new Color(image.getRGB(j, i));
int red = (int)(color.getRed() * 0.299);
int green = (int)(color.getGreen() * 0.587);
int blue = (int)(color.getBlue() * 0.114);

Color newColor = new Color(red+green+blue, red+green+blue,red+green+blue);

image.setRGB(j, i, newColor.getRGB());
   }
 }

File ouptut = new File("newImage.jpg");
ImageIO.write(image, "jpg", ouptut);
  }
catch (Exception e) {
     }
   }
}

What I want is the text to be black and the background image to be white.
Thank you


text:
Q: HighChart pie tooltip fixed Here is pie chart http://jsfiddle.net/hAnCr/, but when I enable tooltip with mouse it moves depending of cursor. How can I fix tooltip, but not like options.tooltip.positioner = (function () {return { x: 20, y: 100 }});, because tooltip must be near the pie piece. Is it possible? Thanks

A: please look for followPointer: Boolean option for highchart
http://api.highcharts.com/highcharts#tooltip.followPointer


text:
Q: conversion from int to void * is possible? I am learning multithreading concept from http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm.
i had come across this doubt..here in below example program he is trying to convert int to void*..
i think converting int to void* is illegal,int address should be converted to void *..
I mentioned code belw please have a look.
Example 1:-
 #include <iostream>
 #include <cstdlib>
 #include <pthread.h>

 using namespace std;

 #define NUM_THREADS     5

 void *PrintHello(void *threadid)
{

  long tid;
 tid = (long)threadid;
 cout << "Hello World! Thread ID, " << tid << endl;
 pthread_exit(NULL);
}

  int main ()
 {
   pthread_t threads[NUM_THREADS];
    int rc;
    int i;
    for( i=0; i < NUM_THREADS; i++ ){
     cout << "main() : creating thread, " << i << endl;
     rc = pthread_create(&threads[i], NULL,
                      PrintHello, (void *)i);//this was the line where he is converting int to void *,i feel this is correct (void *)&i but result is not as expected if i change it
     if (rc){
       cout << "Error:unable to create thread," << rc << endl;
       exit(-1);
    }
  }
  pthread_exit(NULL);
  }

Example 2:-
#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS     5

 struct thread_data{
 int  thread_id;
 char *message;
};

  void *PrintHello(void *threadarg)
 {
    struct thread_data *my_data;

     my_data = (struct thread_data *) threadarg;

   cout << "Thread ID : " << my_data->thread_id ;
   cout << " Message : " << my_data->message << endl;

   pthread_exit(NULL);
}

  int main ()
  {
    pthread_t threads[NUM_THREADS];
    struct thread_data td[NUM_THREADS];
   int rc;
   int i;

   for( i=0; i < NUM_THREADS; i++ ){
     cout <<"main() : creating thread, " << i << endl;
  td[i].thread_id = i;
  td[i].message = "This is message";
  rc = pthread_create(&threads[i], NULL,
                      PrintHello, (void *)&td[i]);//in this he is typecasting by thread_data address to void *
  if (rc){
     cout << "Error:unable to create thread," << rc << endl;
     exit(-1);
  }
 }
   pthread_exit(NULL);
   }

can you explain the difference why he is not typecasting int address variable to void *

A: You are right that in general it might not work, as we have few guarantees about the relative sizes of int and void*. However, on systems that succeed in implementing pthread, a void* will be large enough to hold the int.
The reason for doing so, is the interface of pthread_create which takes a void* and passes that to the thread function when that starts. The idea is likely that this parameter should be a pointer to some data structure. However (again), when the data is as small as an int, you can cheat and pass it directly.
Note that the PrintHello function immediately casts the parameter back to its original type (which must be agreed on).
Also, you don't have to cast a data pointer to void*, as that conversion is implicit. You do have to use a cast to get the original type back though.


text:
Q: C++ it changes the value of the variable because of..? That is the code:
point [1][2][1] = 3;
cout << point[1][2][1] << endl;
point [1][3][0] = 4;
cout << point[1][2][1] << endl;

And that is what the console says when I run the application:
3
4

If I change to
point[1][3][0] = 5;

it says
3
5

How can I remove this annoying error? I cant continue that way.

A: When your variable is declared as
int point[100][100][1];

Then the valid indexes are respectively 0...99, 0...99, 0...0.
Your access to point[1][2][1] is therefore quite inappropriate.  Depending on which index you make out of range, you might access an area outside the array entirely, or in a different slice of the array.
If you really want to access array elements arbitrarily, then I suggest you discard the triple-subscript notation and use:
int point[m][n][p];
int* p = &point[0][0][0];
p[x*n*p + y*p + z]

Now you are in control over row-major vs column-major access, and any computation that yields an offset less than m*n*p is valid.
Note that in your case m=n=100 and p=1, so that point[1][3][0] is p[1*100*1 + 3*1 + 0] = p[103] and also point[1][2][1] is p[1*100*1 + 2*1 + 1] = p[103].  So both really are the same location.


text:
Q: PayPal API no longer showing the credit card form first with SetExpressCheckout I have the following variables defined in my SetExpressCheckout API code:
SOLUTIONTYPE=Sole
LANDINGPAGE=Billing
USERSELECTEDFUNDINGSOURCE=CreditCard

Previously, this worked so that the shopper is first shown a form where he can enter his credit card details, followed by an option to log into his existing PayPal account. Since about a week however, everyone gets this screen:

Yes, I tested it from several machines, several countries, with cookies cleared, etc. And the sandbox is giving me the same issue.
Unfortunately, not all of our users are tech savvy and we've heard from several of them that they found no way to pay with credit card, even though the PayPal button to pay with a card is there - just not very visible because it's grey.
Is anyone experiencing the same thing lately? Have you found a way around it to display the credit card form first?

A: Unfortunately, there's nothing you can do about this.
PayPal is split testing those checkout pages.  I've seen 3 different versions pop up lately.  The old/original one where the full form is displayed by default, this new page design/style with the button only, and I've also seen another new page design that does display the full form as well by default.
They are letting their split tests run their course, though, and in theory will choose the one that performs the best over all.


text:
Q: Angular symlinked module isn't added to the compiled javascript output I am creating a test application with angular to test my angular library. When I symlink to the library in my package.json and set preserveSymlinks to true in the angular.json like this:
package.json
{
  "dependencies": {
    "@org/library": "file:../v6/library/libs",
  }
}

angular.json
{
  "projects": {
    "application-name": {
      "architect": {
        "build": {
          "configurations": {
            "local": {
              "tsConfig": "tsconfig.lcl.json",
              "main": "src/main.ts",
              "preserveSymlinks": true
            }
          }
        }
      }
    }
  }
}

tsconfig.lcl.json ("preserveSymlinks": true in the extended file)
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ]
}

I then get this error:

ERROR TypeError: Cannot read properties of undefined (reading 'ɵcmp')

And that is because angular/webpack is not including the @org/library in the final js file:
/***/ 9760:
/*!*******************************************************!*\
  !*** ./node_modules/@org/library/button/src/index.ts ***!
  \*******************************************************/
/***/ (() => {

/***/ }),

/***/ 2583:
/*!*****************************************************************************!*\
  !*** ./node_modules/@org/library/button/src/lib/button/button.component.ts ***!
  \*****************************************************************************/
/***/ (() => {

/***/ }),

What I did to fix this, is to include them in the tsconfig.lcl.json:
{
  "include": [
    "src/**/*.d.ts",
    "./node_modules/@org/library/*/src/index.ts",
    "./node_modules/@org/library/*/src/**/*.component.ts",
    "./node_modules/@org/library/*/src/**/*.model.ts",
    "./node_modules/@org/library/*/src/**/*.service.ts",
    "./node_modules/@org/library/*/src/**/*.directive.ts",
    "./node_modules/@org/library/*/src/**/*.pipe.ts",
    "./node_modules/@org/library/*/src/**/*.module.ts",
  ],
}

This removes the error but now I get hundreds of warnings saying:

[webpack-dev-server] WARNING
/test/node_modules/@org/library/button/src/lib/button.component.ts is part of the TypeScript compilation but it's unused.
Add only entry points to the 'files' or 'include' properties in your tsconfig.

How can I fix this so I don't have to use the "include" part within the tsconfig? The entry point is already there using the "files" options. Shouldn't it automatically include the dependency file(s)?


text:
Q: Summation of series of first $2n$ natural numbers and first $3n$ natural numbers I am having an issue understanding the concept of the sum of the first $2n$ and $3n$ natural numbers.
So as I have gathered, the sum of the first $2n$ natural numbers is $n(2n+1)$, and the sum of the first $3n$ natural numbers is $(3n(3n+1))/2$.
But this is what is confusing me, $2n$ implies that it is $2+4+6 + \ldots$ or does it mean $2$ lots of natural numbers. It is really the way it worded is confusing me.

A: $1+2+3+\dots + n=\frac{n(n+1)}{2}$, so $1+2+3+\dots+2n=\frac{2n(2n+1)}{2}=n(2n+1).$
In the same fashion, $1+2+3+\dots+3n=\frac{3n(3n+1)}{2}$

A: I'm not exactly sure, whet you're asking but I'll give a shot answering. Just to remind you, the formula for the sum of $n$ natural numbers is
$$\sum_{i=1}^n i = \frac{n(n+1)}{2}.$$
The formulae you gave seem to be for summing natural numbers up to $2n$ and $3n$. I.e. you just substitute $2n$ to the equation above to get the formulae you were talking about.
$$1+2+\ldots + 2n = \frac{(2n)(2n+1)}{2} =n(2n+1)$$

If you instead want to find the sum of first $n$ even numbers you do the following
$$\sum_{i=1}^n 2i = 2\cdot \sum_{i=1}^n i = 2(\frac{n(n+1)}{2}) = n(n+1)$$
So for example the sum of first five even numbers is
$$2+4+6+8+10 = 5(5+1)=5\cdot6=30$$
I let you figure out how it works for $\sum_{i=1}^n 3i$.


text:
Q: Pass message to Chrome extension content script without specifying it as a background script I'm trying to add a feature to the Chrome context menu to add a todo item from selected text. I pass the selected text from a context menu in background.js like so:
function onClickHandler(info, tab) {
  chrome.extension.sendMessage(info.selectionText, function(){});
}

chrome.contextMenus.onClicked.addListener(onClickHandler);

chrome.runtime.onInstalled.addListener(function() {

  chrome.contextMenus.create({"title": "Add: %s", "contexts":["selection"]});

});

And then listen for the message in an app.js content script:
chrome.extension.onMessage.addListener(function(task, sender, sendResponse) {
  Task.setNewTask(task); // Saves the task in storage
});

The message is received correctly when my extension is open in a tab, but doesn't work when it is closed. This is because I don't set app.js as a background script in my manifest.json:
"permissions": [
    "storage",
    "contextMenus",
    "tabs",
    "notifications"
],

"background": {
  "scripts": ["background.js"]
}

The reason I don't include app.js as a background script is because it includes the rest of my app's code, which generates errors when tried to run in the background without a DOM.
Unfortunately I can't easily do the storage in the background.js file because I need access to the function Task.setNewTask which is in my content script.
My app has various methods of storing data depending on the environment – there would be a lot of duplication if I had to put this logic in background.js.
I've tried including my app as a background page:
"background": {
  "page": "index.html"
},

And then including both scripts at the bottom of the page:
  <script src="background.js"></script>
  <script src="js/app.js"></script>
</body>

But my app still won't add new tasks in the background.
Is there a way to:

*

*Keep background.js as simple as possible,

*Not include app.js as a background script,

*Still receive a message when app.js is not in the background?

A: Oh dear. Where did you find the base code you're modifying?
chrome.extension.sendMessage/chrome.extension.onMessage are deprecated to the point of not even being in the documentation anymore.
But even if you change them to the proper chrome.runtime equivalents, it's still the wrong function to communicate with a content script.

*

*Your original code fails, since chrome.runtime.sendMessage (and deprecated chrome.extension equivalent) are sending only to extension pages (e.g. to the chrome-extension://yourid/ origin), not to content scripts.

*Your modified code fails, since messaging never sends a message to the same JS context it's running from.
What you need is chrome.tabs.sendMessage function, that allows you to specify the tab where your context script is. If you want to send it to the current tab, it's passed as a parameter to the onClicked listener.
function onClickHandler(info, tab) {
  chrome.tabs.sendMessage(tab.id, info.selectionText);
}

On the context script side, don't forget to change to chrome.runtime:
chrome.runtime.onMessage.addListener(function(task, sender, sendResponse) {
  Task.setNewTask(task); // Saves the task in storage
});


text:
Q: Saving data and retrieving the id of the data at the same time I just started sql and have a problem that I have been dealing with for days.
I have two data tables. The first is the book, the second is the author. The fields of the book table:
Book
Book ID (PK)
AuthorID
BookName
...
Author
AuthorID (PK)
Author Name
What I want to do here is to create the database for the author while the book is registered.
1-Book Name, Author name will be written in the textboxes in the Windows form application and the save button will be clicked. The author name will first be saved in the 'author' table and the id as the automatic pk key will be created.
2-The 'author name' written on the textbox and the corresponding id in the author table will be taken.
3- Finally, the title of the book and the author id will be recorded in the "book" table.
To give an example:
To textboxes in the Windows form application:
Book Title: IT
Author Name: Stephen King
Hit the save button.
Author table
AuthorID: 97 (automatically assigned)
Author Name: Stephen King
Book table
Book ID: 11
AuthorID: 97
Book Name: IT
In short, with a single click, there is both an author and a book record and a database at the same time.
I have tried many methods, but I cannot store the Author ID I took.
string sqlcom1 = "INSERT INTO author (authorName) VALUES(@Pauthor)";
            commandObject = new SqlCommand(sqlcom1, connectionObject );
            commandObject.Parameters.AddWithValue("@Pauthor", textBoxauthorName.Text);

string sqlcom2 = "SELECT authorID FROM author WHERE authorName='" + textBoxauthorName.Text + "'");
            commandObject = new SqlCommand(sqlcom2 , connectionObject );

string sqlcom3 = "INSERT INTO book (bookName,authorID) VALUES(@PbookName,@PauthorID)";
            commandObject = new SqlCommand(sqlcom3, connectionObject);
            commandObject.Parameters.AddWithValue("@PbookName", textBoxbookName.Text);
            commandObject.Parameters.AddWithValue("@PauthorID", sqlcom2);

connectionObject.Open();
commandObject.ExecuteNonQuery();
connectionObject.Close();

Error:
'Conversion failed when converting the nvarchar value 'SELECT authorID FROM author WHERE authorName='author30'' to data type int.'
author30 --> The value I entered into the textbox for the author name.
Note: I can see that by registering to the author table, names are automatically assigned ids. Registration to the author table is taking place.
The author ID is associated with the author ID in the book table.

A: SOLUTION
            connectionObject.Open();
            string sqlcom1 = "INSERT INTO author (authorName) VALUES(@Pauthor); SELECT SCOPE_IDENTITY()";
            commandObject= new SqlCommand(sqlcom1, connectionObject);
            commandObject.Parameters.AddWithValue("@Pauthor", textBoxauthorName.Text);
            string SolutionVariable = commandObject.ExecuteScalar().ToString();

            string sqlcom3 = "INSERT INTO book (bookName,authorID) VALUES(@PbookName,@PauthorID)";
            commandObject = new SqlCommand(sqlcom3, connectionObject);
            commandObject.Parameters.AddWithValue("@PbookName", textBoxbookName.Text);
            commandObject.Parameters.AddWithValue("@PauthorID", SolutionVariable);

            commandObject.ExecuteNonQuery();
            connectionObject.Close();

A: SQLServer supports a clause called OUTPUT for (amongst other things) INSERT statements, which lets you retrieve a set of rows for all the inserted values. This is more useful than selecting SCOPE_IDENTITY because it allows you to retrieve multiple values; you can insert N rows, and retrieve O columns per inserted row, for example
INSERT INTO T(CreateDate,A,B,C) --imagine that T has a PK int autonumber
OUTPUT inserted.PK,inserted.CreateDate
VALUES (GetUtcDate(),'A','BB','CCC'),(GetUtcDate(),'A2','BB2','CCC2')

ExecuteReader()ing this (rather than NonQuery) will respond with a 2x2 resultset of the inserted values - the PK and the date calc'd by the DB. You can of course use it in 1x1 mode also (and executescalar it) but generally with SQLs we should aim to work in sets of data

A: You need to use SCOPE_IDENTITY()  to get the inserted ID, and pass it through to the other table. Do this in a single command.
You have a number of other issues with your code:

*

*SQL injection risk

*You are not disposing the connection correctly

*You should use the correct length for varchar parameters

I will demostrate how to do this properly
const string query = @"
INSERT INTO author (authorName)
VALUES(@Pauthor);

INSERT INTO book (bookName, authorID)
VALUES(@PbookName, SCOPE_IDENTITY());
";

using(var connectionObject = new SqlConnection(connString))
using(var commandObject = new SqlCommand(query, connectionObject))
{
    commandObject.Parameters.Add("@Pauthor", SqlDbType.VarChar, 100).Value = textBoxauthorName.Text;
    commandObject.Parameters.Add("@PbookName", SqlDbType.VarChar, 100).Value = textBoxbookName.Text;
    connectionObject.Open();
    commandObject.ExecuteNonQuery();
}

If you have multiple rows then you need to use the OUTPUT clause. Again, you can do this in a single batch command, just send it to a table variable first.


text:
Q: Login with joomla external PHP I am writing a code to authenticate with the datas which are in my mysql database.
My script is "almost" ready but i dont know how to successfully use the password.
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$shapass=sha1($password);
$query = mysql_query("select * from alw73_users where password='$shapass' AND username='$username'", $connection);

But not working. Does not authenticate successfully. I think Joomla isnt uses sha1 for password coding or maybe i totally doing it wrong. But what should i use insted of?
The end of the script:
$rows = mysql_num_rows($query);
if ($rows == 1) {
$error = "OK";
echo "OK";
} else {
$error = "NOT OK";
echo "BAD!";

}

A: Here is how I am initializing Joomla Framework variables inside an external script, that might help you.
if ($JEXEC_defined==TRUE) {
    defined('_JEXEC') OR defined('_VALID_MOS') OR die( 'Restricted access' ); //security reason
    $direct_script_access=FALSE;
}

if ($JEXEC_defined==FALSE) {
    define( '_JEXEC', 1 );
    define( 'DS', DIRECTORY_SEPARATOR );
    define('JPATH_BASE', dirname(__FILE__) );
    require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
    require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
    $direct_script_access=TRUE;

    // initialize the application
    $mainframe =& JFactory::getApplication('site');
    $mainframe->initialise();
}

if ($user->username!="") if ($direct_script_access==TRUE) {
    //PHP code when script is accessed directly
}


text:
Q: what is the difference between org_id and organization_id in oracle apps? org_id is the unique id for the operating unit whereas organization _id is the ID for the Inventory Organization which is under an Operating Unit. what is an operating unit then. I went through many tutorials online could not able to understand. the solution I got is :
ORG_ID:

Unique ID for the Operating Unit.
Come under operating unit in Multiorg.
Used to distinguish the data of different business organizations.
ORGANIZATION_ID:

ID for the Inventory Organization which is under an Operating Unit.
Come under inventory organization.
Used to identify the items belongs to which inventory organization it has assigned.
and inventory organisations comes under operating units.I mean many inventory organisations can have one operating unit.am I correct???

A: Generally, Operating unit is based on a Region/Location. Multiple Inventory Organization can be assigned to a single Operating Unit. An operating unit is assigned to one General Ledger.
If the Company is registered in different countries, then the GL are different and so the operating unit should be different.
Table Names:
Operating Unit - HR_OPERATING_UNITS
Organization - HR_ALL_ORGANIZATION_UNITS
You can read further about the same in the below link. https://docs.oracle.com/cd/E18727_01/doc.121/e13423/T443823T443826.htm
If you want to know how the columns are mapped to these tables, please check the table in the Oracle ETRM (http://etrm.oracle.com/). You will be able to find the foreign key information of the object.
Select version and FND Data
Input your object name and submit
Select the object type
Select the object name
Object's information

A: In Oracle EBS, all organizations, regardless of which type are stored in the same table hr_all_organization_units.
Depending on how they are used for the business, they are classified for example as inventory orgs, operating units, HR organizations etc..
You might find systems, where an inventory organization_id is the same as the operating unit org_id, which means that the organization record is both at the same time.
Have a look at the example data sheet of our PER Organizations Blitz Report, which shows the different organization classifications in columns G to P (filter for OU or INV not null to only see operating units and inv orgs).
An Inventory Organization typically means a physical warehouse with items and stock, whereas an Operating Unit is just a logical concept to segregate data access when working with modules such as AP, AR, ONT and others.
For financial reporting (e.g. to the tax authorities), the transactions done in operating units are transferred into a ledger, and there is a hierarchy: Ledger-> Operating Unit-> Inventory Organization as show in the GL Ledgers and Organizations report.


text:
Q: Add area in Asp.net MVC in vs code or .net cli We could easily create Aria with graphical user interface in VS, but it seems impossible in VS Code and Terminal.

A: From your description, I assume your application is an Asp.net core (asp.net 5/6/7) application, right?
If that is the case, you can open the MVC application using VS code and open a Terminal, then, use the following command to install the dotnet-aspnet-codegenerator tool and Microsoft.VisualStudio.Web.CodeGeneration.Design package:
dotnet tool install -g dotnet-aspnet-codegenerator
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design --version 6.0.8

After that, use the following code to add the Area:
dotnet-aspnet-codegenerator area AreaNameToGenerate

The screenshot as below:

More detail information about the area code generate command, see Area options.


text:
Q: Date.now() on server in advance relative to client? Here is my situation:
I have a client connected to a server with Node.js, socket.io.
If I calculate Date.now() on server, send it to the client, and then make the client print the time received from the server and it's own Date.now() I get a very strange result: The server time is 514ms bigger than the client time. But logically the server Date.now() has to happen before the client-one.
I don't understand what is happening here. Does the server calculate Date.now() differently than the client because of its time zone ? Is something else happening ?

A: What you're seeing is called clock skew.  Like any clock, the clock inside a computer has to be set to the correct time, and the clocks for any two computers slowly diverge from one another.  Therefore, it's almost certain that any two computers will think its a slightly different time.  Usually, this difference is small enough that you don't notice, but it can be big enough to see it when you deliberately run an experiment like the one you just did.


text:
Q: Java - Add values to two-dimensional Array and how see the array? I have an array (Arr). I fill points1 and points2 with values.
public class Arr {
    float pointX;
    float pointY;
    boolean yesNo;
    String text;
}

public Arr points1[];
public Arr points2[];

points1 = new Arr[100];
for (int i = 0; i < 100; i++) points1[i]= new Arr();

for (int j = 0; j < 100; j++) {
    points1[j].pointX = getFloat;
    points1[j].pointY = getFloat;
    points1[j].yesNo = getBoolean;
    points1[j].text = getText;
}

points2 = new Arr[100];
for (int x = 0; x < 100; x++) points2[x]= new Arr();

for (int y = 0; y < 100; y++) {
    points2[y].pointX = getFloat;
    points2[y].pointY = getFloat;
    points2[y].yesNo = getBoolean;
    points2[y].text = getText;
}

This works, but what is, when I have five of them or more (points1, points2, points3...)
How can I make "public Arr points[][]"? And then fill and get the values with e.g. points[0][22].pointX or points[1][10].text?
And how can I see the points[][] array like var_dump in PHP? How list the array?
var_dump example:
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

A: This is a working example
package com.stackoverflow.q15134193;

public class Test1 {
    public static Arr[][] points;
    static float getFloat = 1;
    static boolean getBoolean = true;
    static String getText = "hi";

    public static void main(String[] args) {

        points = new Arr[100][];
        for (int i = 0; i < points.length; i++) {
            points[i] = new Arr[100];
            for (int j = 0; j < points[i].length; j++)
                points[i][j] = new Arr();
        }

        for (int i = 0; i < points.length; i++) {
            for (int j = 0; j < points[i].length; j++) {
                points[i][j].pointX = getFloat;
                points[i][j].pointY = getFloat;
                points[i][j].yesNo = getBoolean;
                points[i][j].text = getText;
            }
        }

        for (int i = 0; i < points.length; i++)
            for (int j = 0; j < points[i].length; j++)
                System.out.println("X: " + points[i][j].pointX + " Y: "
                        + points[i][j].pointY + " YesNo: "
                        + points[i][j].yesNo
                        + " text: "+ points[i][j].text);
    }
}

class Arr {
    public float pointX;
    public float pointY;
    public boolean yesNo;
    public String text;
}

A: I'm not completely clear on what you're trying to achieve, but Java isn't PHP.
Java has an extensive set of Collections which will give you much better coverage then simple array's.
As I'm not completely sure what you're trying to do, I can't really tell you what collections could do the job, but you could read up on things like Maps and ArrayList.
You could make, per example an ArrayList of 'Arr's like
ArrayList<Arr> list = new ArrayList<Arr>();

Similarly you can do ArrayList<Arr, Arr>, or start working with Maps if you want to store your object Arr together with a key to find it with.
Once you're using a Java Collection, the clearest way to print these is just looping over it  , with something like
for(Arr a : list){
  Log.d("my_tag", "My list contains"+a.toString());
}

A: Instead of 2D array, you can use ArrayList.
ArrayList<Arr> points = new ArrayList<Arr>();

Now, access an index as following:
points.get(22).pointX OR points.get(10).text

Try to print the arraylist points, to see a near about string output:
System.out.println(points);

A: You need to implement a toString() method in your class Arr, and then call
Log.i("mytag", Arrays.toString(points1));

as explained here how see an array in logcat for android


text:
Q: C++ Generic Object Pointer I have recently been working on a C++ project that requires a system whereby classes can be stored in a map (a library). From my research, I have concluded that I need to use a pointer to an object of the class. That's fine, I have the object, however I need to make the pointer fit multiple different objects from different classes. If this is unclear, here is my code.
typedef NO-IDEA-WHAT-GOES-HERE;
struct library {
    std::map<std::string, objPointer> lib;
};

I need to know how to create a pointer that can accept an object from more than just one single class, i.e.
//NOT WHAT I WANT
module someMod;
library *objPointer;
objPointer = &someMod;

But something more like...
typedef POINTER; //Not sure what to put here
module someMod;
std::map<std::string, POINTER> lib;
lib["something"] = someMod;
otherModule someOtherMod;
lib["somethingelse"] = someOtherMod;

Thank you in advance!

A:
That's fine, I have the object, however I need to make the pointer fit multiple different objects from different classes.

This is a common pattern in many libraries and applications.

*

*Create a namespace specific to your application.

*Create an abstract class that can be used as the base class of all the important classes in your application.

*Make sure that all the important classes are derived from the base class.

That will allow you to store pointers to instances of all the important classes in your application in whatever container you wish to store them.
Over time, you will find that you will be able to implement a lot of  functionality using just the base class interface.


text:
Q: PHP/Tinymce issue, carriage returns displaying in the output I'm using tinymce on this page:
http://coachbrian.ca/CoachBrian4/admin/index.php?public=7&page=1
On that page the user can edit whatever text they want, which later gets viewed and displayed on this page:
http://coachbrian.ca/CoachBrian4/index.php?public=1
What's happening right now is that every time the user edits and saves whatever text they want, the next time they go in, there's a bunch of "rn"'s in the text.
I've used this in my PHP to try and clean them out:
$order   = array("\r\n", "\n", "\r", "rn", "rnrn", "<p> </p>");
$replace = '';

// Processes \r\n's first so they aren't converted twice.
$formatOne = str_replace($order, $replace, $unformattedText);

And then I save the entry in the database. I also use the same code on the the 'display' page that the public would see, and for some reason the "rn"'s don't show, but there's extra carriage returns.
I've been banging my head for 2 days now looking for what is probably an obvious issue but I can't seem to find it.
Thanks in advance.

A: I recognize this is an old issue but I had the same problem but discovered I was using mysql_real_escape_string on the contents of tinymce twice. I removed the second occurrence of the escape and it is fixed.


text:
Q: Is Android driver implementation needed JNI or not? I'm using an application which needed driver utilities..For acheiving for this is JNI must or we can do it in any other option???

A: Actually, you will probably want to build a custom Kernel module to read the hardware and provide a standard interface.  You can get more details from the Android development site and should download the Android Source here
If you are interfacing a USB device then check out the new USB development tools in the Android 3.1 SDK
Android JNI can be used,  but it is not as powerful as a kernel module.  However, you also don't need root to install it.  It really just depends on what type of hardware you are trying to support.


text:
Q: ¿Cómo puedo reiniciar el valor de un Sampler2D? Estoy trabajando en un programa para cargar modelos 3D utilizando OpenGL. Por el momento, mis shader y código cuentan con soporte para cargar mapas Difuso, Especular y Emisivo.
Tengo entendido que los uniforms están hechos de tal modo que, una vez configurados, estos se quedan con el último valor insertado hasta el próximo cambio, pero es ahí donde empiezan los problemas porque, suponiendo que cargo un modelo con los 3 mapas, y después otro que solo tiene mapas D y S pero no E; el E de este último no es nulo, cero, o lo q sea con lo q se inicialice, sino se queda con el Emisivo del modelo anterior. ¿Hay algún modo de solucionar esto?
Este es el código que utilizo para renderizar mi mesh:
void Mesh::Draw(Shader& shader, World::Transform transform, World::Camera camera) {
        {
            // Activate shader and pass transform and camera
            shader.Use();
            shader.setMat4("view", camera.getView());
            shader.setMat4("projection", camera.getProjection());
            shader.setMat4("model", transform.getTransformMatrix());

            // Sampler2D assignation
            unsigned int nDiff = 0;
            unsigned int nSpec = 0;
            unsigned int nNorm = 0;
            unsigned int nHeig = 0;
            unsigned int nEmit = 0;

            for (unsigned int i = 0; i < textures.size(); i++) {
                glActiveTexture(GL_TEXTURE0 + i + 1);
                std::string number;
                std::string name = textures[i].type;
                if      (name == "diffuse")  number = std::to_string(nDiff++);
                else if (name == "specular") number = std::to_string(nSpec++);
                else if (name == "normal")   number = std::to_string(nNorm++);
                else if (name == "height")   number = std::to_string(nHeig++);
                else if (name == "emissive") number = std::to_string(nEmit++);

                textures[i].setSampler2D(&shader, ("material." + name + number).c_str(), i + 1);
                textures[i].Bind();
            }

            // Draw call
            vao.Bind();
            glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
            vao.Unbind();

            // Unbind buffers
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, 0);
        }
    }

Y este es el de setSampler2D, por si acaso:
void Texture::setSampler2D(Shader* shader, const char* name, int slot) {
        shader->Use();
        shader->setInt(name, slot);
    }

A: Con las siguientes líneas estás restableciendo el texture unit 0 únicamente:
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);

Pero tu código muestra la posibilidad de usar más de un texture unit. Por lo tanto debes restablecerlos todos.
Reemplazando las líneas mencionadas por un for como este debería solucionar tu problema:
for (unsigned int i = 0; i < textures.size(); i++) {
    glActiveTexture(GL_TEXTURE0 + i + 1);
    glBindTexture(GL_TEXTURE_2D, 0);
}

Con esto estarías dejando los binding points que usaste tal como los encontraste.


text:
Q: Is SSH a part of standard unix package? SSH - Secured shell runs on all Unix-like operating systems, but originally was it a part of standard Unix package?

A: Nope, it didn't come out until much later (1995) unix was from 1969.
http://en.wikipedia.org/wiki/Secure_Shell#Version_1.x
It was originally released as freeware:

The goal of SSH was to replace the earlier rlogin, TELNET and rsh
  protocols, which did not provide strong authentication nor guarantee
  confidentiality. Ylönen released his implementation as freeware in
  July 1995, and the tool quickly gained in popularity.


text:
Q: Move first letter for each word to the end and add a char, with condition Okay, i will make it short.
This is my code
String s = edittextkata.getText().toString();
            String[] vowels = {"a","e","i","o","u","A","I","U","E","O"};
            String firstLetter;
            if (s.equals("")) {
                Toast.makeText(getApplicationContext(), "EMPTY, CAN NOT ENCRYPT!", Toast.LENGTH_SHORT).show();
            } else if (s.contains(" ")) {
                String[] wordArray = s.split(" ");
                firstLetter="";
                StringBuilder sb = new StringBuilder(" ");
                outerloop:
                for(String word:wordArray){
                    for(int i=0;i<word.length();i++){
                        if(word != null){
                        String words=wordArray[i].trim();
                        firstLetter+=(words.charAt(0));
                        input+=words.substring(1);
                        if(wordArray[i].startsWith(vowels[i]))
                        {
                            hasil=input+firstLetter+"IN"+" ";
                            sb.append(hasil);
                            i++;
                            continue outerloop;
                        } else{
                            hasil=input+firstLetter+"AN"+" ";
                            sb.append(hasil);
                            i++;
                            continue outerloop;
                        }}
                    }break outerloop;
                }
                sb.toString(); // Re-join string
                edittexthasil.setText(sb);
            } else {
                int i=0;
                firstLetter="";
                if(s.startsWith(vowels[i])){
                    firstLetter += s.charAt(0);
                    input = s.substring(1);
                    hasil = input + firstLetter + "IN";
                    edittexthasil.setText(hasil.toString());
                } else {
                    firstLetter += s.charAt(0);
                    input = s.substring(1);
                    hasil += input + firstLetter + "AN";
                    edittexthasil.setText(hasil.toString());
                } edittexthasil.setText(hasil.toString());
            }

My Question is
My input is "hello world"
But why my output is "nullellohAN nullelloellohhAN ",
and when i clicked the button again the output become " nullelloellohhAN nullelloelloelloellohhAN"
Why world part from hello world didn't show? just hello part.
And why theres too many null?
Why is changed everytime i clicked the butto? i want the input is stay like that ("ellohAN orldwAN") except when the input text is changed.
Theres no Error on Logcat, thats why i'm confused. Help me~

A: Is it some interview task? I'd advise you to pay more attention to code quality, not only to the final result. Regarding the errors you've listed - I see that you're trying to assign a String to String array:
String[] characterArray = word;

or create a String from an array:
wordArray[i] = new String(characterArray);

which are both illegal statements. Other ones are similar.
Try to use an IDE (like Eclipse or IDEA) which will show you those errors on the spot with advice on how to fix them.
Also, if I were you I'd rethink the logic and rewrite the code from scratch :).


text:
Q: How do i block my website from loading on mobiles? For example when someone visit my website he see a page for downloading an app

A: Use navigator.platform to get the platform of the browser. According to it open different pages.


text:
Q: Number of ways to form a Board of Representatives A board of representatives for a local university is to be formed from a pool of five professionals. The board will consist of a chair, a vice-chair, and one additional member.
(a) In how many ways may the board be formed?
Is this 5C3 or 5P3?
(b) If the board will be formed from a pool of ten applicants, with a chair, a vice-chair, and three additional members, in how many ways may the board be formed?
10C6 or 10P6?
(c) Suppose that two of the professionals in the part (b) refuse to serve as the vice-chair. In how many ways may the committee then be formed?
I'm not sure how to do this one.

A: Combinations are used when we are selecting a subset, that is, when the order of selection does not matter.  Permutations are used when we are counting arrangements, that is, when order matters.

A board of representatives for a local university is to be formed from a pool of five professionals. The board will consist of a chair, a vice-chair, and one additional member.  In how many ways may the board be formed?

There are five ways to choose the chair, four ways to choose the vice-chair from among the remaining members of the pool, and three ways to choose the additional member from the remaining members of the pool.  Hence, by the Multiplication Principle, the number of ways the board can be formed is
$$5 \cdot 4 \cdot 3$$
Notice that
$$5 \cdot 4 \cdot 3 = \frac{5 \cdot 4 \cdot 3 \cdot 2 \cdot 1}{3 \cdot 2 \cdot 1} = \frac{5!}{2!} = \frac{5!}{(5 - 3)!} = P(5, 3)$$
Since it matters which person occupies which position, order matters.  Therefore, this is a permutation problem.

If the board will be formed from a pool of ten applicants, with a chair, a vice-chair, and three additional members, in how many ways may the board be formed?

There are $10$ ways to choose the chair and $9$ ways to choose the vice-chair from the remaining members of the pool.  We then need to select three of the eight remaining members of the pool to be additional members, which can be done in $\binom{8}{3}$ ways.  The order in which the additional members are selected does not matter since they do not serve in roles with different responsibilities.  Hence, the number of ways the board can be formed is
$$10 \cdot 9 \cdot \binom{8}{3}$$

Suppose that two of the professionals in the part (b) refuse to serve as the vice-chair. In how many ways may the committee then be formed?

Since two of the ten people will not accept the vice-chair position, there are eight ways to fill the vice-chair position, leaving nine ways to choose the chair from among the remaining members of the pool.  The three additional members can be selected from among the remaining eight members of the pool in $\binom{8}{3}$ ways.  Hence, the number of ways the board can be formed is
$$8 \cdot 9 \cdot \binom{8}{3}$$


text:
Q: Remove icon from searchview in ActionBar I am using action bar support v7 library. When I expand search view I get look like this.

I dont want this search icon on left. Instead I want to place it in hint like image below.

I want to do this programmatically. How can I achieve this?
Thanks.

A: I think I figured out what the answer is.
To expand searchview by default if I use
mSearchView.setIconifiedByDefault(false);

it will show search bar like first image
If I use mSearchView.onActionViewExpanded(); then it shows like second image.


text:
Q: circular layout design in Android ui I am trying to design ui part in android which hold a logo in the center of the layout.and every image take a certain distance and take position respect radius with making circle and another image take same and some   far than the one..just like solar system pictorial view.i got round view of those images but ,there are no line...plz help me...layout will just like,except multiple image,there just one image in one circle..

A: https://github.com/sababado/CircularView
This may also be of assistance. It allows for a center image and background color. It also allows for the same customization for each of it's surrounding Markers.

A: Have a look at CircleLayout: https://github.com/dmitry-zaitsev/CircleLayout
Just put it in a FrameLayout together with your center image, and you are good to go.


text:
Q: TP-Link TL-SG108PE - 802.1Q VLAN config I have a scenario where I need to connect 2 groups of devices using 5 switches to 2 different routers.
I'm thinking that 802.1Q VLAN would be the solution.
I would create two VLAN's, one for each device group and have the following connections between the switches/routers:

*

*Switch 1 Port 8 connecting to Switch 5 Port 8 - Tagged - VLAN1,2

*Switch 2 Port 8 connecting to Switch 1 Port 7 - Tagged - VLAN1,2

*Switch 3 Port 8 connecting to Switch 1 Port 6 - Tagged - VLAN1,2

*Switch 4 Port 8 connecting to Switch 1 Port 5 - Tagged - VLAN1,2

*Switch 5 Port 8 connecting to Switch 1 Port 5 - Tagged - VLAN1,2

*Switch 5 Port 6 connecting to Router 1 - Untagged - VLAN1

*Switch 5 Port 7 connecting to Router 2 - Untagged - VLAN2

A picture of the setup:

Will this setup work?

A: I have a TL-SG1016PE, and, as @user1686 said, it has some strange behavior regarding VLAN1 (it seems to be propagated untagged in some cases).
However, I was able to fix it by using the following configuration:

*

*Enable 802.1Q VLAN PVID

*Set all ports to have PVID 2. WARNING this will probably break your connection. Remember that the switch auto-assigns IP 192.168.0.1 if it can't reach a DHCP Server.

*On 802.1Q VLAN Configuration, input 1 for the VLAN ID, and mark ALL ports as Tagged. Click on Add/Modify.

*Now input 2 for VLAN ID, and mark all ports you wish as Untagged. (Remember to add the tagged/untagged trunk also). Click on Add/Modify.

With this setup, I was able to confirm that no traffic from VLAN1/untagged escapes to another port.
As the other answer also said, it's better to just leave VLAN 1 for management purposes and you can avoid all this problems altogether.

A: In theory, it's a very typical 802.1Q setup and should work fine.
(If the switch has "PVID" settings, make sure your "tagged" ports have the same PVID. In some switches the 'trunk' or 'tagged' mode indeed means "tag everything", but in some other switches it means "tag everything except the PVID VLAN", which remains untagged.)
However, I've heard from a few different people that TL-SG108PE (and the whole series) has issues with its VLAN implementation. That is, no matter what tagging settings you use, all ports will be able to receive traffic assigned to VLAN 1. (That is especially an issue with broadcasts, such as ICMPv6 RAs, which can greatly confuse devices when they arrive on the 'wrong' VLAN.)
A possible workaround might be to reserve VLAN 1 as the "management" VLAN, and shift your "Internet" and "Siemens" networks to VIDs 2 and 3 respectively. (All port 8s would become "1 untagged, 2/3 tagged".) I haven't tried this practically.
For example, this Netgate forum thread, or this Amazon review:

Regardless of PVID or 802.1Q VLANs, every port on this switch passes untagged traffic on VLAN 1. Even if you set another VLAN to be untagged on a given port, you cannot then remove VLAN 1 from that port


text:
Q: Is it possible to add an eventlistener on a DIV? I know this function:
document.addEventListener('touchstart', function(event) {
    alert(event.touches.length);
}, false);

But is it possible to add this to a div? Example:
document.getElementById("div").addEventListener('touchstart', function(event) {
        alert(event.touches.length);
    }, false);

I haven't tested it yet, maybe some of you know if it works?

A: Yeah, that's how you do it.
document.getElementById("div").addEventListener("touchstart", touchHandler, false);
document.getElementById("div").addEventListener("touchmove", touchHandler, false);
document.getElementById("div").addEventListener("touchend", touchHandler, false);

function touchHandler(e) {
  if (e.type == "touchstart") {
    alert("You touched the screen!");
  } else if (e.type == "touchmove") {
    alert("You moved your finger!");
  } else if (e.type == "touchend" || e.type == "touchcancel") {
    alert("You removed your finger from the screen!");
  }
}

Or with jQuery
$(function(){
  $("#div").bind("touchstart", function (event) {
    alert(event.touches.length);
  });
});

A: The other way round if you are not using addEventListener, probably a alternative to get control over ID.
 $(document).ready(function () {
            $('#container1').on("contextmenu", function (e) {
                e.preventDefault();
            });
        });

A: Of course, let's assume you have to insert text in h1 element when a user clicks on the button. It's pretty easy to bind HTML's specific element to addEventListener() method
<button id="button">Show me</button>

document.getElementById("button").addEventListener("click", function(){
  document.getElementById("name").innerHTML = "Hello World!";
});


text:
Q: How can I run the same Python program (script) on multiple servers (or machines)? How can I run the same Python program (script) on multiple servers (or machines)? I programming a telegram bot (using python-telegram-bot API) and I wish my program running on multiple servers at the same time.
How can do it? without get something like "telegram.error.Conflict: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"
This bot will be used for concurrency porpuse (like checking graphical administrative information).
Thanks a lot for the help (and suggestions).
def main() -> None:
    global updater
    global dispatcher

    updater = Updater(token="here should be the bot token provided by BotFather", use_context=True, workers=999)

    dispatcher = updater.dispatcher

    start_handler = CommandHandler('start', start,
                                    run_async=True)

    choice_handler = MessageHandler(Filters.text & ~Filters.command,
                                    choice, run_async=True)

    income_handler = MessageHandler(Filters.regex(DECLARATION),
                                    income, run_async=True)

    end_handler = MessageHandler(Filters.regex('Fin') | Filters.regex('Done') | Filters.regex(FINISH),
                                    end, run_async=True)

    stmt_handler = MessageHandler(Filters.regex(STMT) & ~Filters.command,
                                  declaracion_por_dia, run_async=True)

    stmt2_handler = MessageHandler(Filters.regex(STMT2) & ~Filters.command,
                                   calendario_ultimos_siete, run_async=True)

    return_handler = MessageHandler(Filters.regex(RETURN) & ~Filters.command,
                                    choice, run_async=True)

    callbackquery_handler = CallbackQueryHandler(declaracion_por_rango, run_async=True)

    cancel_convhandler = CommandHandler('cancel', cancel,
                                            filters=Filters.regex('Cancel')
                                            | Filters.regex('CANCEL'), run_async=True)

    conversation_handler = ConversationHandler(
                                                entry_points=[start_handler],
                                                states={
                                                        CHOICE: [choice_handler, end_handler],
                                                        INCOME: [income_handler, end_handler],
                                                        CHOOSE: [stmt_handler, stmt2_handler, return_handler],
                                                        DEC_BY_RANGE: [callbackquery_handler]
                                                       },
                                                fallbacks=[cancel_convhandler],
                                                run_async=True
                                            )

    dispatcher.add_handler(conversation_handler)
    # dispatcher.add_error_handler(stmt_handler, run_async=True)
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':

    main()


text:
Q: How to update DB records to active/inactive for inputs inside loop in codeigniter I am trying to update specific row in tables using select options tag .But it is updating last inserted row only and not the specificed.
I need solution.
controller:
public function user_status()
{
    $this->load->model('customize_model');
    $data = array("user_status" => $this->input->post('status'),
     "user_id" => $this->input->post('user_id'));
    $data1['user'] = $this->customize_model->update_status($data);
    $this->load->view('custom/user',$data1);
}

Model:
public function update_status($data)
{
    $user_id = $this->input->post('user_id');
    $this->db->set($data);
    $this->db->where('user_id',$user_id);
    return $this->db->update('user',$data);
}

My View:
                <?php
                 foreach($user->result() as $row)
                 {
                ?>

                        <input type="hidden" class="form-control"
                         value="<?php echo $row->user_id; ?>"
                         name="user_id" />
                        <?php echo $row->user_id; ?>
                        <?php echo $row->user_status; ?>

                            <select class="form-control" name="status"
                             id="user_status">
                                <option value="Active">Active</option>
                                <option
                                value="Inactive">Inactive</option>
                            </select>

                        <button class="btn btn-primary" name="submit"
                         type="submit" value="<?php echo $row->user_id;?
                         >"> Update<?php echo $row->user_id;?></button>

                <?php
                    }
                ?>

A: The problem here is the same name="user_id" is looped in your view along with other name attributes. So the last value is sent to the controller.
In View:
Create two inputfields
<input type="hidden" name="global_userId" id="global_userId" />
<input type="hidden" name="global_status" id="global_status" />

Try setting the name and id as
name="status-<?php echo $row->user_id; ?>" id="status-<?php echo $row->user_id; ?>"

for all name attributes in loop.
and make the button type button rather than submit and make it call function onclick.
like
onClick="submitForm(<?php echo $row->user_id; ?>)"

and create the Jquery function to update the input field and submit the form:
function submitForm(userId){
  $('#global_userId').val(userId);
  var status = $('#status-'+userId).val();
  $('#global_status').val(status);
  $('#formId').submit();
}

In controller and model accept the 'global_userId' and 'global_status' for the values.
$user_id = $this->input->post('global_userId');


text:
Q: Most Efficient Way To Retrieve MYSQL data in random order PHP I have a query like so :
SELECT * FROM table WHERE premium = 3

I'm just wondering how I can have it return a random order for the results!
i was told not to use ORDER BY RAND(); because of the amount of system resources it uses.

A: How many results are you expecting? If it's small, why not just grab all of the results and then select random indices from them?

A: Sort in random order in PHP instead of MySQL
I read from the scalability blog that Digg got an improve of 4000% sorting in PHP instead of Mysql. So my advice would be to do the sorting in PHP instead of Mysql. I guess you could put the results in an array which you shuffle.

When implementing the comment feature
  a 4,000 percent increase in
  performance was created by sorting in
  PHP instead of MySQL

Store results in APC(memory)
Instead of fetching the results from the database every time you should try to cache them using for example APC(in memory which is lightning fast) to minimize the database load. Update the cache when SELECT * FROM table WHERE premium = 3 has changed.  APC is a must anyway for any big site because compiling PHP code consumes (a lot of) time.
If you can't compile APC then your site will never run as fast as it could. You could store the database fetch in a file, but then you have to do disc IO which can hurt you a lot.
App engine
If you can't compile APC(to be honest I would always have a look at google's app engine) then I would advise you to have a look at google's app engine because they have memcached which is an in memory database(lightning fast). You can even run PHP code via quercus on app engine. Google has a generous free quota and is cheap once you use the free quota.


text:
Q: VueJS getting TypeError: Cannot read properties of undefined when I delete and add an Sensor information I am trying to create sensorArray dynamically in my VueJS application. For this when I create an element and delete it and then when I try to create a new one then I get the following error:
client.js:227 TypeError: Cannot read properties of undefined (reading 'value')
    at eval (templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./pages/Test.vue?vue&type=template&id=cde3d4aa&:44)
    at Proxy.renderList (vue.runtime.esm.js:2643)

Following is the simple Vuejs application I have:
<template>

    Sensor Information :
    <button class="btn btn-info" @click="addSensorInfo($event)">
      Add Sensor
    </button>

     0">Sensor Element:
     0">

        Value
        <input v-model="sensorArray[sensor.ID].value" type="text" class="form-control">
        <button class="btn btn-danger" @click="deleteSensorInfo($event,sensor.ID)"></button>

</template>

*

*Click on Add Sensor button: A text field and delete button will appear.

*Click on Delete ICON and delete the field.

*Now again click on Add Sensor then I get following error:

client.js:227 TypeError: Cannot read properties of undefined (reading 'value')

Since I have a lot of elements within my SensorArray I am not creating the dedicated element and trying to create everything dynamically based on user click. Can someone please let me know how can I fix this issue?

A: First Error
This is not a valid JavaScript operation
this.sensorArray.splice(this.sensorArray.filter(obj => obj.ID === sensorID), 1)

Splice signature expects a number at first position
splice(start: number, deleteCount: number)

Filter signature returns an array.
Solution
const idx = this.sensorArray.findIndex(obj => obj.ID === sensorID);
if (idx !== -1) {
    this.sensorArray.splice(idx, 1)
}

Or as mentioned you can use a more concise form
this.sensorArray = this.sensorArray.filter(obj => obj.ID === sensorID);

Second Error
Now I noticed that you are performing a strange array access. An array is indexed by id not by your custom sensor.ID, so this sensorArray[sensor.ID].value makes no sense. It works before a delete by pure chance (due to how you are generating IDs).
This should be your code (note the v-model="sensor.value"):

    Value
    <input v-model="sensor.value" type="text" class="form-control">
    <button class="btn btn-danger" @click="deleteSensorInfo($event,sensor.ID)"></button>

Furthermore .value is never set.

A: You are mixing up splice and filter, to delete the item.
Simply use filter.
this.sensorArray = this.sensorArray.filter(obj => obj.ID === sensorID);


text:
Q: execute shell command with variable To execute 'find' with some variables from txt file i made this
but it doesn't work.
is that wrong with execute statement?
#/bin/bash
while read line;
do
   echo tmp_name: $line
   for ST in 'service.getFile("'$line;
           do
                   find ./compact/ -type f -exec grep -l $ST {} \;
           done
done < tmpNameList.txt

A: Try and quote $ST in your find command.
What's more:

*

*since you operate from the current directory, ./ is not necessary;

*you don't seem to have any special regex character (the ( needs to be quoted in grep's classical regex mode, and I assume you did mean a literal dot), so use fgrep instead (or grep -F). Ie:
           find compact/ -type f -exec fgrep -l "$ST" {} \;

A: grep can read multiple patterns from a file (-f option):
find ./compact/ -type f -exec grep -f patterns.txt {} +

where patterns.txt (prepend 'service.getFile(' to each line) is:
sed 's/^/service.getFile(/' tmpNameList.txt >patterns.txt