text:
Q: How can I update my DataGrid when a user makes a selection in the ComboBox? Here's my ComboBox:
<ComboBox HorizontalAlignment="Left"
          Margin="125,110,0,0"
          VerticalAlignment="Top"
          Width="120"
          DisplayMemberPath="lot_number"
          ItemsSource="{Binding LotNumList}"
          RenderTransformOrigin="0.583,2" Height="18" />

Here's a DataGrid that I want to update the values to:
<DataGrid HorizontalAlignment="Left" Margin="228,177,0,0" VerticalAlignment="Top"
          Height="292" Width="617" ItemsSource="{Binding ComponentsList}"
          AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Component" Binding="{Binding component}" CanUserResize="False"/>
        <DataGridTextColumn Header="Control" Binding="{Binding aControl}" CanUserResize="False"/>
        <DataGridTextColumn Header="Reference" Binding="{Binding cal_ref}" CanUserResize="False" />
        <DataGridTextColumn Header="Family" Binding="{Binding family}" CanUserResize="False"/>
        <DataGridTextColumn Header="Id" Binding="{Binding componentId }" CanUserResize="False"/>
    </DataGrid.Columns>

Here's how I'm grabbing data from db to populate the ComboBox:
//Grabs the lot_number column from db that is distinct
var lotNum = db.LotInformation.GroupBy(i => i.lot_number)
                              .Select(group => group.FirstOrDefault());

//Loops through the lot numbers column in db and converts to list
foreach (var item in lotNum)
{
    Console.WriteLine(item.lot_number);
}
LotNumList = lotNum.ToList();

Now I am wondering how do I connect my ComboBox so that when I select a value in the ComboBox... then the DataGrid gets updated based on the value of the selection in the ComboBox.
I tried something like this:
private void UpdateExistLotList(string LotNumber)
{
    using (var db = new DDataContext())
    {
        //Grabs the lot_number column from db that is distinct
        var ExistLot = db.LotInformation.First(l => l.lot_number.Equals(LotNumber));
    }
}

Calling the method in my lot number list property but it doesn't get called or just doesn't work. I'm not sure what I'm doing wrong. Any ideas?
EDIT:
Properties:
public List<Components> ComponentsList
    {
        get
        {
           return components;
        }
        set
        {
            components = value;
            RaisePropertyChanged("ComponentsList");
        }

    }

public string LotNumber
    {
        get
        {
            return lotNumber;
        }
        set
        {
            lotNumber = value;
            RaisePropertyChanged("LotNumber");
        }
    }

    public List<LotInformation> LotNumList
    {
        get
        {
            return lotNumList;
        }
        set
        {
            lotNumList = value;
            RaisePropertyChanged("LotNumList");
           UpdateExistLotList(LotNumber);

        }
    }

Here's where LotNumber is declared (I take the deserialized value of lot number from memory and assign it to LotNumber):
public void DeSerializationXML(string filePath)
    {
        XmlRootAttribute xRoot = new XmlRootAttribute();
        xRoot.ElementName = "lot_information";
        xRoot.IsNullable = false;

        // Create an instance of lotinformation class.
        var lot = new LotInformation();

        // Create an instance of stream writer.
        TextReader txtReader = new StreamReader(filePath);

        // Create and instance of XmlSerializer class.
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(LotInformation), xRoot);

        // DeSerialize from the StreamReader
        lot = (LotInformation)xmlSerializer.Deserialize(txtReader);

        // Close the stream reader
        txtReader.Close();

        //Storing deserialized strings to db
        using (var db = new DMIDataContext())
        {

            LotInformation newLot = new LotInformation();

            if (newLot != null)
            {
                newLot.Id = lot.Id;
                newLot.lot_number = lot.lot_number;
                newLot.exp_date = lot.exp_date;

                LotNumber = newLot.lot_number;
                ExpirationDate = newLot.exp_date.ToString();

                //Grabs the lot_number column from db that is distinct
                var lotNum = db.LotInformation.GroupBy(i => i.lot_number).Select(group => group.FirstOrDefault());

                //Loops through the lot numbers column in db and converts to list
                foreach (var item in lotNum)
                {
                    Console.WriteLine(item.lot_number);
                }
                LotNumList = lotNum.ToList();

                foreach (Components comp in lot.Components)
                {
                    newLot.Components.Add(comp);

                }
                ComponentsList = newLot.Components;

                foreach (Families fam in lot.Families)
                {

                    newLot.Families.Add(fam);
                }
                FamiliesList = newLot.Families;

                try
                {
                    db.LotInformation.Add(newLot);
                    db.SaveChanges();
                    Console.WriteLine("successfully");
                }
                catch
                {
                    //TODO: Add a Dialog Here

                }
            }

        }

A: private void UpdateExistLotList()
{
    using (var db = new DDataContext())
    {
        //Grabs the lot_number column from db that is distinct
        var ExistLot = db.LotInformation.First(l => l.lot_number.Equals(LotNumber));
    }
}

This method has no para?
But you call it like this?
{
    lotNumList = value;
    RaisePropertyChanged("LotNumList");
    UpdateExistLotList(LotNumber);

}

Is there something wrong?
Your question is that UpdateExistLotList was never called?
Try to add a breakpoint on RaisePropertyChanged("LotNumList"); in VisualStudio and observe why it doesn't get called.
In your code, I don't know the use of ExistLot and LotNumber.
I guess your demand is like this?
Comobox shows LotInformation, select one LotInformation and make datagrid shows LotInformation.Components ?
If so,you can Binding DataGrid's Itemsource={Binding Components,ElementName=ComboboxName}
or you can Binding Combobox's SelectedItem/SelectedValue, and then set ComponentsList in these events.

Get your demand.
You means you don't set a relationship between Components and LotInformation in EntityFramework or other DB framework.
If you use EF, I advise you make a relationship between Components and LotInformation,and then you can get ComponentsList by LotInformation.Components.
In another way, try like this:
<ComboBox HorizontalAlignment="Left"
          Margin="125,110,0,0"
          VerticalAlignment="Top"
          Width="120"
          DisplayMemberPath="lot_number"
          SelectedItem="{Binding SelectedLot}"
          ItemsSource="{Binding LotNumList}"
          RenderTransformOrigin="0.583,2" Height="18" />

     private LotInformation selectedLot;

    public LotInformation SelectedLot
    {
        get { return selectedLot; }
        set
        {
            selectedLot = value;
            var lot = value as LotInformation;
            if (lot != null)
            {
                ComponentsList = new List<Components>();
                //add ComponentsList
            }
        }
    }


text:
Q: Setting a sign to highlight only text instead of whole line in Vim When defining a :sign you can use the linehl argument to assign a highlight group for the whole line the sign is placed in.
This highlights the whole line until the end, but how I do to highlight only the text of that line?
Edit: The idea is to use Syntastic to show the errors and warnings, but I can't redefine the SyntasticStyleError sign to do what I want. It highlights all the line instead of only the text of that line.

A: It is not possible as far as I know. Look at the :h sign-define:
:sign define {name} {argument}...
        Define a new sign or set attributes for an existing sign.
        The {name} can either be a number (all digits) or a name
        starting with a non-digit.  Leading digits are ignored, thus
        "0012", "012" and "12" are considered the same name.
        About 120 different signs can be defined.

        Accepted arguments:

    icon={bitmap}
        Define the file name where the bitmap can be found.  Should be
        a full path.  The bitmap should fit in the place of two
        characters.  This is not checked.  If the bitmap is too big it
        will cause redraw problems.  Only GTK 2 can scale the bitmap
        to fit the space available.
            toolkit     supports ~
            GTK 1       pixmap (.xpm)
            GTK 2       many
            Motif       pixmap (.xpm)
            Win32       .bmp, .ico, .cur
                    pixmap (.xpm) |+xpm_w32|

    linehl={group}
        Highlighting group used for the whole line the sign is placed
        in.  Most useful is defining a background color.

    text={text}                     *E239*
        Define the text that is displayed when there is no icon or the
        GUI is not being used.  Only printable characters are allowed
        and they must occupy one or two display cells.

    texthl={group}
        Highlighting group used for the text item.

It does not offer you a straight-forward way to distinguish between the text background colour and the background colour of the line - in fact, you can only set the linehl parameter.

Maybe there is a hacky way to do what you want. I've stumbled upon this link you might find useful: https://sunaku.github.io/vim-256color-bce.html
Another interesting idea is explained on vim.wikia.com (link) in the Highlighting that stays after cursor moves section. It suggests using the following command:
:nnoremap <silent> <Leader>l ml:execute 'match Search /\%'.line('.').'l/'<CR>

This way you might mix it with the information you get from :sign place and replace signs with your custom highlighting method I posted above. It requires some scripting though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the area very deep meaning? For example,
Why we say :

If one side of the square is $a$ then $a^2$ is the area of the square.

What is the meaning of area in complex space?
Can you explain academically, this meaning?

A: At the most basic level, area is a function that takes as input a subset of the plane, and as output returns a non-negative real number. Furthermore, any candidate for an "area function" should add properly, in the sense that the area of the union of disjoint sets is the sum of the areas.
It seems reasonable to require that area be translation invariant - that is, if you take a shape and simply translate it from one place to another without changing it otherwise, then the area should stay the same.
With these simple principles, it is already determined that an $n$-by-$n$ square has $n^2$ times as much area as a $1$-by-$1$ square, since you can build an $n$-by-$n$ square out of $n^2$ "tiled" $1$-by-$1$ squares via translation.
You can show that the side-squared formula holds for fractional and rational side lengths via similar tiling constructions, and then extend it to irrational side lengths by "squeezing" the square between inner and outer approximations.
This sort of axiomatic construction of area from simple principles is studied in great detail in the subject of measure theory (and in particular, Haar measures), which is a fascinating topic worth looking into, if you want to understand this stuff deeply.


text:
Q: Using glide with subdirectories I have the following structure for my project
MyCode
== main.go
== user
==== user.go
I would like to build my code with 'go build' so in main.go I have a
import "user"

so that I can access the code in the package in that directory. In order to build this properly I would need my user directory inside my vendor directory. However, when I do a 'glide install' the user directory is deleted. I do not want to move my user directory into my vendor directory manually everytime.
The goal is to git clone my project, do a glide install then a go build and have it work. Is there a way I can have glide move my user directory into the vendor directory without having to do it manually?


text:
Q: Convert dataset into combobox items using LINQ I am trying to take a DataSet and add each item to a ComboBox.
I am currently using a foreach loop, like so:
 foreach (DataRow row in ds.Tables[0].Rows)
 {
     cmbCauseForRepair.Items.Add(row[0].ToString() + ":" + row[1].ToString());
 }

I would like to do this using LINQ.
Here is what I'm trying:
     cmbCauseForRepair.Items.Add(from r in ds.Tables[0].Rows.Cast<DataRow>()
                              select r[0] + ":" + r[1]);

However, my ComboBox only has 1 item: "System.Linq.Enumerable".

A: .Add() only adds a single item.
Try the same approach, but use .AddRange(), which adds a collection of Objects to the ComboBox:
cmbCauseForRepair.Items.AddRange(from r in ds.Tables[0].Rows.Cast<DataRow>()
                                 select r[0] + ":" + r[1]);

A: LINQ isn't looping over the records for you.  You still need to do that.
If cmbCauseForRepair.Items.Add() had an overload which accepted an enumeration of values then you wouldn't need to.  But it doesn't.  It just accepts an object.  And according to that documentation, that object will be treated as:

A visual representation of the item is displayed in the combo box. This content representation is specified by the DisplayMember property. If the DisplayMember property is null, the item's ToString method is called to obtain the string that is displayed in the combo box; otherwise, the property of the stored object as specified by the DisplayMember property is displayed.

Since the object being passed to Add() is of type IEnumerable<string> then the .ToString() representation of it is:
`IEnumerable<string>`

Basically, you need to loop through your objects to add them one at a time:
var items = from r in ds.Tables[0].Rows.Cast<DataRow>()
            select r[0] + ":" + r[1];
foreach (var item in items)
    cmbCauseForRepair.Items.Add(item);

Or use a different method to add them:
cmbCauseForRepair.Items.AddRange(from r in ds.Tables[0].Rows.Cast<DataRow>()
                                 select r[0] + ":" + r[1]);

A: Better to use string.Format instead of concatenation string
cmbCauseForRepair.Items.AddRange(ds.Tables[0].Rows.Cast<DataRow>().Select(p => string.Format("{0}:{1}", p[0], p[1])).ToArray());


text:
Q: Selenium bot with percentages I'm stuck in problem where I want to program selenium/python bot which could answer my own survey. But I'm stuck in problem where I don't know/can't find solution. I want that selenium could choose from more than 1 xpath. But I don't know how to make that. Also is there a chance that you can make like random %? So e.g Vyras could have 70% chance and Moteris 30% to be picked
Pic.1 MV Pic.2 My code
my survey: https://apklausa.lt/f/logistiniu-imoniu-veiklos-modernizavimo-galimybes-efwxu6w/answers/new.fullpage

A: issue in your code
make this change (fix your code here)
protoas = driver.find_element_by_xpath('//*[@id=\'entry_3375494\']/div[2]/label[1]/div/div')

Get data from page using javasscript
if you run this javascript code on the site you will get all the input values for each section/question and also the question itself, do with this as you may
let sections = document.querySelector('section.entry.radio.required').toArray().map((section)=>{
    let section_id = document.querySelector(section).data('id');
    let question = document.querySelector(document.querySelector(section, 'div.question').contents().get(0)).text();
    let options =  document.querySelector('input[name='' + section_id + '']').toArray().map((input)=>{
        return {
            'question': question,
            'name': document.querySelector(input).attr('name'),
            'data-id': document.querySelector(input).data('id'),
            'text': document.querySelector(document.querySelector('input[data-id=' + document.querySelector(input).data('id') + ']').siblings()[0], 'div.value > div.text').text()
        }
    });
    return options;
});

using this javascript on after the page has loaded, you will then get the following data stored in the sections variable
each element of the sections variable is 1 question
in this element, there is the name and ids for each option as well as the text for each option

Get data from Selenium
if you want to run this in python, jus call this code and then your data will be in the data variable

data = driver.execute_script("return document.querySelector('section.entry.radio.required').toArray().map((section)=>{let section_id = document.querySelector(section).data('id');let question = document.querySelector(document.querySelector(section, 'div.question').contents().get(0)).text();let options =  document.querySelector('input[name=\'' + section_id + '\']').toArray().map((input)=>{return {'question': question,'name': document.querySelector(input).attr('name'),'data-id': document.querySelector(input).data('id'),'text': document.querySelector(document.querySelector('input[data-id=' + document.querySelector(input).data('id') + ']').siblings()[0], 'div.value > div.text').text()}});return options;})")

click options
Once you have the data, you can simply click the options you want by using the ID provided form the previous step
data_id = 3375494 # Just set the data id here and then run this for each option you want to click
driver.execute_script("document.querySelector('input[data-id=" + data_id + "]').click()")


text:
Q: Fibonacci series using arrays (as long as user input) I am currently a beginner in programming learning, my professor has instructed me to do a program with the instructions below. However when i wrote my program I did the following to take the input from the user on how long the array should be however because  my array size isnt defined it gives me an error but the professor hasnt instructed me to specify a size so im really confused :S
My attempt :
void displayarray(int n){

int i;
int aray[]={0,1};

for (i=0;i<n;i++){
    printf("%i", aray[i]);
}
printf("\n");

}
int main()
{ int n;
scanf("%i",&n);

displayarray(n);

getchar();
getchar();

}
The Task assigned:

The Fibonacci numbers are a famous sequence of numbers. They begin with 0 and 1, and then the next value in the sequence is the sum of the previous two values.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
  (fib[8] is 21 -- remember to start counting from 0!)
Write a program that calculates the Fibonacci sequence.
-Make a function that accepts n, which is the number of integers to generate.
-Declare an array, initialize it with only the first two Fibonacci numbers, then calculate the rest.
-Display the sequence for n=10 and n=20.
-Try generating output for n=50. If anything goes wrong in this step, you don't need to fix it. Just add a comment explaining what happens, and why.

A: You can use "malloc()" or "calloc()" function to allocate array of given size.
You need to declare it like
int *array;
array = malloc(n, sizeof(int));

// do something
free(array)

A: You can calculate all the Fibonacci sequence by only using a 3 lenght array. Initialize the first two elements of the array with the two first numbers of the Fibonacci sequence (0 and 1) and then, with these two values, calculate the third number of the sequence.
 int f[3];

 f[0] = 0;
 f[1] = 1;
 f[2] = f[0] + f[1]

Try to figure out what to do in the for loop to calculate the Fibonacci number for any integer n.


text:
Q: Dapr: app returned http status code 500 from subscription endpoint I try to find a way to use Dapr in my development machine.
Windows 10
Docker Desktop
WSL 2
Docker Compose
Visual Studio 2019
Asp.Net Core ....
The problem that I'm facing is clear that my existing solution is running in HTTPS scheme. So, I tried to play with Sentry to simulate what a Kubernate do with auto generated certs.
sentry:
        container_name: "dapr.sentry"
        image: "daprio/sentry:latest"
        command: ["./sentry", "-issuer-credentials", "/certs", "-config", "/configuration/dapr-config.yaml"]
        volumes:
            - "./dapr/certs/:/certs"
            - "./dapr/configuration/:/configuration"
        depends_on:
            - placement

The certificates is generated successfully. But still I receive the error in sidecars:
app returned http status code 500 from subscription endpoint

I know it is not an issue, but there is a lake in the documentation.
I think this error is related to https. Am I correct?
How to fix it using https?


text:
Q: Android Room - Cannot find setter for field. - value in java.lang.String even when removing 'is' and changing class properties to var I'm creating a Room DB for an app I've making, and I keep getting the following exception/error whenever I try and run my code:
Cannot find setter for field. - value in java.lang.String
This is extremely frustrating. I have tried to look through some other people's suggestions, and I have tried to fix my code accordingly although I am still getting the same error.
I am extremely confused as to where the source of the problem is because of the vagueness of the error message. I have tried for  a couple of hours to fix the code but nothing is really working, so I'd thought I would ask it here.
PixelArts Kotlin Class

import androidx.room.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Entity
data class PixelArts(
    @ColumnInfo(name = "item_bitmap") var bitmap: String,
    @ColumnInfo(name = "item_title") var title: String,
    @ColumnInfo(name = "item_pixel_data") var pixelData: String,
    @ColumnInfo(name = "item_favourited") var favourited: Boolean,
    @ColumnInfo(name = "item_date_created") var dateCreated: String = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now())) {
    @PrimaryKey(autoGenerate = true) var id = 0
}

PixelArtCreationsDao.kt
@Dao
interface PixelArtCreationsDao {
    @Insert
    suspend fun insertPixelArt(pixelArt: PixelArts)

    @Query("SELECT * FROM PixelArts ")
    fun getAllPixelArtCreations(): String

    @Query("DELETE FROM PixelArts WHERE id=:pixelArtId")
    fun deletePixelArtCreation(pixelArtId: Int)

    @Query("UPDATE PixelArts SET item_pixel_data=:pixelData AND item_bitmap=:bitmap WHERE id=:pixelArtId")
    fun updatePixelArtCreation(pixelArtId: Int, bitmap: String, pixelData: String)
}

AppData class
class AppData {
    companion object {
        var dbFileName = "pixel_art_db"
        lateinit var db: PixelArtDatabase

        var pixelArtsData = mutableListOf<PixelArts>()

        fun initialize() {
            pixelArtsData.add(PixelArts(BitmapConverter.bitmapToString(Bitmap.createBitmap(10, 10, Bitmap.Config.ARGB_8888)), "Creation 1", JsonConverter.convertListOfViewToJsonString(listOf()), true))
        }
    }
}

onCreate method
 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setBindings()
        setOnClickListeners()
        setTitle()

        AppData.db = PixelArtDatabase.getDatabase(this)!!

        if (databaseFileExists()) {
            CoroutineScope(Dispatchers.IO).launch {
                AppData.pixelArtsData = AppData.db.pixelArtCreationsDao().getAllPixelArtCreations()

                withContext(Dispatchers.Main) {
                    binding.activityMainRecentCreationsRecyclerView.layoutManager = GridLayoutManager(this@MainActivity, 2)
                    binding.activityMainRecentCreationsRecyclerView.adapter = RecentCreationsAdapter(AppData.pixelArtsData, this@MainActivity)
                }
            }
        } else {
            AppData.initialize()
            binding.activityMainRecentCreationsRecyclerView.layoutManager = GridLayoutManager(this, 2)
            binding.activityMainRecentCreationsRecyclerView.adapter = RecentCreationsAdapter(AppData.pixelArtsData, this)

            CoroutineScope(Dispatchers.IO).launch {
                for (pixelArts in AppData.pixelArtsData) {
                    AppData.db.pixelArtCreationsDao().insertPixelArt(pixelArts)
                }
            }
        }
    }

Converters (maybe something is wrong here?)
object BitmapConverter {
    fun stringToBitmap(str: String): Bitmap? {
        return try {
            val byte: ByteArray = Base64.decode(str, Base64.DEFAULT)
            BitmapFactory.decodeByteArray(Base64.decode(str, Base64.DEFAULT), 0, byte.size)
        } catch (exception: Exception) {
            exception.printStackTrace()
            null
        }
    }

    fun bitmapToString(bitmap: Bitmap): String {
        val byteArrayOutputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)

        return Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT)
    }
}

object JsonConverter {
    fun convertListOfViewToJsonString(list: List<View>) = Gson().toJson(list)
    fun convertJsonStringToListOfView(str: String) = Gson().fromJson(str, Array<View>::class.java).toList()
}

build.gradle
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
}

android {
    compileSdk 31

    testOptions {
        unitTests.includeAndroidResources = true
    }

    defaultConfig {
        applicationId "com.realtomjoney.pyxlmoose"
        minSdk 27
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        viewBinding true
    }
    testOptions {
        unitTests.returnDefaultValues = true
    }
}

dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    implementation 'com.google.android.material:material:1.5.0-beta01'
    testImplementation 'junit:junit:4.13.2'
    testImplementation 'androidx.test:core-ktx:1.4.0'
    androidTestImplementation 'androidx.test.ext:junit-ktx:1.1.3'
    testImplementation 'org.robolectric:robolectric:4.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0-alpha03'
    androidTestImplementation 'androidx.test:rules:1.4.1-alpha03'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2'

    // ROOM
    implementation "androidx.room:room-runtime:2.3.0"
    implementation "androidx.room:room-ktx:2.3.0"
    kapt "androidx.room:room-compiler:2.3.0"

    // COROUTINE
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0-RC'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0-RC'

    implementation 'com.google.code.gson:gson:2.8.6'
}

Image:

If you find an issue with this question, or you think for some reason it's not well written then tell me in the comments the exact problem. Don't be an elitist.
This question is unique than similar posts because I've tried every possible 'solution' and the problem still resides.


text:
Q: Adding items to DetailsView's DropDownList when in edit mode I'm still new to ASP.net, but have been looking around to see how to use code behind to add items to a DetailsView's DropDownList when in edit mode.  Everything I've come across hasn't been working, but perhaps I'm applying it incorrectly.
The DetailsView starts in ReadOnly mode.  I read that I have to use FindControl within the DataBound event.  This is what I have so far, but it's not adding any values.
Aspx page
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="315px"
    AutoGenerateRows="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
    <Fields>
        <asp:CommandField ShowEditButton="True" ControlStyle-CssClass="button" >
            <ControlStyle CssClass="button"></ControlStyle>
        </asp:CommandField>
        <asp:BoundField DataField="FirstName" HeaderText="First Name"
            SortExpression="FirstName" />
        <asp:BoundField DataField="LastName" HeaderText="Last Name"
            SortExpression="LastName" />
        <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
        <asp:BoundField DataField="JobID" HeaderText="JobID" SortExpression="JobID" />
        <asp:BoundField DataField="SupervisorID" HeaderText="Supervisor"
            SortExpression="SupervisorID" />
        <asp:TemplateField HeaderText="Hire Date" SortExpression="HireDate">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("HireDate","{0:d}") %>' CssClass="datepicker"></asp:TextBox>
            </EditItemTemplate>
            <InsertItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("HireDate","{0:d}") %>'></asp:TextBox>
            </InsertItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("HireDate","{0:d}") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Status" SortExpression="Status">
            <EditItemTemplate>
                <asp:DropDownList ID="StatusList"  runat="server" SelectedValue='<%# Bind("Status") %>'>

                </asp:DropDownList>
            </EditItemTemplate>
            <InsertItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Status") %>'></asp:TextBox>
            </InsertItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

    </Fields>
</asp:DetailsView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:dbConnectionString %>"
    DeleteCommand="DELETE FROM [Users] WHERE [ID] = @ID"
    InsertCommand="INSERT INTO [Users] ([ClientID], [UserName], [Password], [FirstName], [LastName], [Email], [JobID], [SupervisorID], [HireDate], [Status]) VALUES (@ClientID, @UserName, @Password, @FirstName, @LastName, @Email, @JobID, @SupervisorID, @HireDate, @Status)"
    ProviderName="<%$ ConnectionStrings:dbConnectionString.ProviderName %>"
    SelectCommand="SELECT [ID], [ClientID], [UserName], [Password], [FirstName], [LastName], [Email], [JobID], [SupervisorID], [HireDate], [Status] FROM [Users] WHERE [ID] = @ID"
    UpdateCommand="UPDATE [Users] SET [ClientID] = @ClientID, [UserName] = @UserName, [Password] = @Password, [FirstName] = @FirstName, [LastName] = @LastName, [Email] = @Email, [JobID] = @JobID, [SupervisorID] = @SupervisorID, [HireDate] = @HireDate, [Status] = @Status WHERE [ID] = @ID">
    <SelectParameters>
        <asp:QueryStringParameter Name="ID" QueryStringField="curEmp" Type="Int64" />
    </SelectParameters>

    <UpdateParameters>
        <asp:Parameter Name="ClientID" Type="Int64" />
        <asp:Parameter Name="UserName" Type="String" />
        <asp:Parameter Name="Password" Type="String" />
        <asp:Parameter Name="FirstName" Type="String" />
        <asp:Parameter Name="LastName" Type="String" />
        <asp:Parameter Name="Email" Type="String" />
        <asp:Parameter Name="JobID" Type="Double" />
        <asp:Parameter Name="SupervisorID" Type="Double" />
        <asp:Parameter Name="HireDate" Type="DateTime" />
        <asp:Parameter Name="Status" Type="String" />
        <asp:Parameter Name="ID" />
    </UpdateParameters>
</asp:SqlDataSource>

Aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class EmployeeProfile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void DetailsView1_DataBound(object sender, EventArgs e)
    {
        if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
        {

            DropDownList statusList = DetailsView1.FindControl("StatusList") as DropDownList;

            statusList.Items.Add(new ListItem("Test", "Test"));

            statusList.DataBind();

        }

    }

}

Can anyone point out what I'm missing here?  Thanks for any help!

A: Use the DataBound event of DetailsView control.
<asp:DetailsView ID="DetailsView1" runat="server"
     OnDataBound="DetailsView1_DataBound" ...>
</asp:DetailsView>

Check for the EditMode in this event using:
DetailsView.CurrentMode = DetailsViewMode.Edit
protected void DetailsView1_DataBound(object sender, EventArgs e)
        {
         if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
          {
            DropDownList statusList = DetailsView1.FindControl("StatusList") as
                                      DropDownList;
                if (statusList != null)
                {
                    statusList.Items.Add(new ListItem("Test", "Test"));
                    statusList.DataBind();
                }
            }
        }

EDIT::
Now to set the selected value of Dropdownlist in edit mode, use the DataItem property of Details view to get the current item.
The data item is often used to access the field values of the current record directly.
 DataRowView row = (DataRowView)DetailsView1.DataItem
  if (row != null)
   {
     statusList.SelectedIndex =
     statusList.Items.IndexOf(ddl.Items.FindByValue(row["Column_Name"].ToString());
   }

OR try this one:
DataRowView row = (DataRowView)DetailsView1.DataItem
ListItem liItem = statusList.Items.FindByText(row["Column_Name"].ToString());
if (liItem != null)
  {
    statusList.Items.FindByText(row["Column_Name"].ToString()).Selected = true;
  }


text:
Q: Kernel module driver interaction I'm new in kernel development. I'm trying to use PWM module from Beagle bone black board from another kernel module that I'm buinding. I have read these article:
https://www.kernel.org/doc/Documentation/pwm.txt
But it isn't clearly to understand. I have read the pwm-tiehrpwm under kernel source /drivers/pwm/pwm-tiehrpwm.c.
But I don't know how to use it. Are there a manual or a tutorial to use it?
Could someone tell me a skeleton for this driver?
My current system is a beaglebone black board. Running a debian distribution with Kernel version:
Linux beaglebone 4.4.9-ti-r25 #1 SMP Thu May 5 23:08:13 UTC 2016 armv7l GNU/Linux
PWM Modules loaded:
lsmod | grep pwm
pwm_tiecap              3652  0
pwm_tiehrpwm            4706  0
Using the cape-universaln:
cat /sys/devices/platform/bone_capemgr/slots  0: PF----  -1
 1: PF----  -1
 2: PF----  -1
 3: PF----  -1
 4: P-O-L-   0 Override Board Name,00A0,Override Manuf,cape-universaln
Thanks


text:
Q: Preprocess text to feed in model trained on imdb dataset I've trained this model:
(training_eins,training_zwei),(test_eins,test_zwei) = tf.keras.datasets.imdb.load_data(num_words=10_000)
training_eins = tf.keras.preprocessing.sequence.pad_sequences(training_eins,maxlen=200)
test_eins = tf.keras.preprocessing.sequence.pad_sequences(test_eins,maxlen=200)

modell = Sequential()
modell.add(layers.Embedding(10_000,256,input_length=200))
modell.add(layers.Dropout(0.3))
modell.add(layers.GlobalMaxPooling1D())
modell.add(layers.Dense(128))
modell.add(layers.Activation("relu"))
modell.add(layers.Dropout(0.5))
modell.add(layers.Dense(1))
modell.add(layers.Activation("sigmoid"))

modell.compile(loss = "binary_crossentropy", optimizer = "adam", metrics = ["acc"])
modell.summary()

ergebnis = modell.fit(training_eins,
                      training_zwei,
                      epochs = 10,
                      verbose = 1,
                      batch_size = 500,
                      validation_data = (test_eins,test_zwei))

Now, I want to test the model's performance on this text (as an example): very bad, I am truly disappointed
So, how can I transform that text into a list that can be fed to the model?

I only know the model expects lists like
[1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 2, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 2, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38, 76, 15, 13, 1247, 4, 22, 17, 515, 17, 12, 16, 626, 18, 2, 5, 62, 386, 12, 8, 316, 8, 106, 5, 4, 2223, 5244, 16, 480, 66, 3785, 33, 4, 130, 12, 16, 38, 619, 5, 25, 124, 51, 36, 135, 48, 25, 1415, 33, 6, 22, 12, 215, 28, 77, 52, 5, 14, 407, 16, 82, 2, 8, 4, 107, 117, 5952, 15, 256, 4, 2, 7, 3766, 5, 723, 36, 71, 43, 530, 476, 26, 400, 317, 46, 7, 4, 2, 1029, 13, 104, 88, 4, 381, 15, 297,
98, 32, 2071, 56, 26, 141, 6, 194, 7486, 18, 4, 226, 22, 21, 134, 476, 26, 480, 5, 144, 30, 5535, 18, 51, 36, 28, 224, 92, 25, 104, 4, 226, 65, 16, 38, 1334, 88, 12, 16, 283, 5, 16, 4472, 113, 103, 32, 15, 16, 5345, 19, 178, 32]

A: Figured it out:
buch = tf.keras.datasets.imdb.get_word_index()
buch = {k:(v+3) for k,v in buch.items()}
buch["<PAD>"] = 0
buch["<START>"] = 1
buch["<UNK>"] = 2
buch["<UNUSED>"] = 3
eingabe = re.sub(r"[^a-zA-Z0-9 ]", "", "very bad, I am truly disappointed")
munition = [[((buch[inhalt] if buch[inhalt] < 10_000 else 0) if inhalt in buch else 0) for inhalt in (eingabe).split(" ")]]

training_eins = tf.keras.preprocessing.sequence.pad_sequences(munition, maxlen=200)
print(modell.predict(training_eins))

Or, more generally, if you have more than one sentence:
buch = tf.keras.datasets.imdb.get_word_index()
buch = {k:(v+3) for k,v in buch.items()}
buch["<PAD>"] = 0
buch["<START>"] = 1
buch["<UNK>"] = 2
buch["<UNUSED>"] = 3

modell = tf.keras.models.load_model("...")

eingabe_eins = ["the movie was boring and i did not really enjoy it",
                "i love it, great movie",
                "that was a good movie, very funny. i recommend it highly",
                "the worst thing i've seen in my life yet. not good, very very bad!",
                "very bad, fully dissapointed!",
                "very good if u wanna stress out someone. but couldnt ever watch this myself..",
                "Yet another film that tries to pass off a whole lot of screaming and crying as great acting. This fails especially in Brosnan's big crying scene, in which he audibly squeaks",
                "the movie is very good, i love it so much, my favorite movie ever, its beatiful. besides that i acknowledge that im not an expert, but i know this movie is somthing special. Ive never felt such a great atmosphere."]

eingabe_zwei = [re.sub(r"[^a-zA-Z0-9 ]", "", inhalt) for inhalt in eingabe_eins]

munition = [[((buch[inhalt] if buch[inhalt] < 10_000 else 0) if inhalt in buch else 0) for inhalt in eingabe.split(" ")] for eingabe in eingabe_zwei]
maximal = np.max([len(i) for i in munition])

munition = [np.append(i, np.zeros((maximal-len(i),))) if maximal != len(i) else i for i in munition]
print(munition)

training_eins = tf.keras.preprocessing.sequence.pad_sequences(munition,maxlen=200)
print(modell.predict(training_eins))

Btw: All inputs were correctly classified, except very good if u wanna stress out someone. but couldnt ever watch this myself... I used this to check if you can fool the AI - apparently, you can do so pretty easily.


text:
Q: How did I get a segmentation fault in this code? vector<int> cutTheSticks(vector<int> arr) {
    vector<int> res;
    vector<int>::iterator it;
    int i=0, mini=0, c=arr.size();
    while(c>0) {
        res.push_back(c);
        mini=*min_element(arr.begin(),arr.end());
        for(i=0;i<arr.size();i++) {
            arr[i]-=mini;
        }
        for(auto it=arr.begin();it!=arr.end();it++) {
            i=*it;
            if(i==0)
                arr.erase(it);
        }
        c=arr.size();
    }
    return res;
}

I am running this piece of code in the hackerank portal and not on any system.

A: The way you are using erase is causing the problem in this case. In fact, you exactly don't need a complex approach like this for the problem.
You can simply sort the array in reverse order and then use pop_back() while last element is 0. It will also help to reduce complexity as then you won't need to call min_element each time. You can directly use arr.back() for the minimum element.

Logic behind my approach:
In each iteration, you are subtracting minimum element from each element. This makes number(s) having the minimum value as 0. Clearly, since the array is sorted in reverse order, these numbers will be in the end of the array. You then want to remove these elements for which pop_back is one of the best available options.

Here is sample code:
vector<int> cutTheSticks(vector<int> arr) {
    vector<int> res;
    sort(arr.begin(), arr.end(), greater<int>());
    while (not arr.empty()) {
        res.push_back(arr.size());
        for (auto &&i : arr)
            i -= arr.back();
        while (not (arr.back() or arr.empty()))
            arr.pop_back();
    }
    return res;
}

PS:
If you want to stick with your original algorithm then replace
for (auto it = arr.begin(); it!=arr.end(); it++) {
    i = *it;
    if(i == 0)
        arr.erase(it);
}

with something like:
arr.erase(remove(arr.begin(), arr.end(), 0), arr.end()); // called as erase-remove idiom

or
for (auto it = arr.begin(); it!=arr.end(); /* it++ */) {
    i = *it;
    if(i == 0)
        it = arr.erase(it);
    else
        ++it;
}

This thread may help you: Remove elements of a vector inside the loop.


text:
Q: Function for selecting next Day If the last day is weekend I am trying to create a function that checks the range of date. If the last date is an weekend it will select the next day. Suppose, Today is 1 March 2016. If someone add 5 with it, it will make the result 7 March 2016. Because 6 March is Weekend. I have written this code. But it is not working and I cannot find where is the problem. The code is as below:
<?php
$date = "2016-02-29";
$numOfDays = 8;
$futureDate = strtolower(date("l",strtotime($date." +".$numOfDays."days")));
$weekend1= "friday";
$weekend2= "saturday";

        if($futureDate != $$w1 || $futureDate != $w2){
            $finalDate = date("Y-m-d",strtotime($futureDate));
        }
        else{$finalDate = date("Y-m-d",strtotime($futureDate ."+1 day"));}

        echo $finalDate;
?>

A: March 6th, 2016 is a Sunday, but you're checking for Friday and Saturday, you need to check for Saturday and Sunday instead, for the weekend. Also, your variable names need to match, and for Saturday you'll need to add two days to get the next weekday.
<?php
$date = "2016-02-29";
$numOfDays = 8;
$day = 86400;//one day is 86400 seconds
$time = strtotime($futureDate + $numOfDays * $day);//converts $futureDate to a UNIX timestamp
$futureDate = strtolower(date("l", $time));
$saturday = "saturday";
$sunday = "sunday";
if($futureDate == $saturday){
    $finalDate = date("Y-m-d", $time + 2 * $day);
}
else if($futureDate == $sunday){
    $finalDate = date("Y-m-d", $time + $day);
}
else{
    $finalDate = date("Y-m-d", $time);
}
echo($finalDate);
?>

A: Check this:
  <?php
$date = "2016-02-29";
$numOfDays = 11;
$futureDate = strtolower(date("l",strtotime($date ."+".$numOfDays."days")));
$futureDate1 = strtolower(date("Y-m-d",strtotime($date ."+".$numOfDays."days")));
$weekend1= "friday";
$weekend2= "saturday";

if($futureDate == $weekend1){
      $finalDate1 = date("Y-m-d",strtotime($futureDate1 ."+2 days"));
}
if ($futureDate == $weekend2){
      $finalDate1 = date("Y-m-d",strtotime($futureDate1 ."+1 days"));
}

echo $finalDate1;
?>

A: @Fakhruddin Ujjainwala
I have changed in your code and it works now perfect. Thanks. the code is now as below:
<?php
$date = "2016-02-29";
$numOfDays = 4;
$futureDate = strtolower(date("l",strtotime($date ."+".$numOfDays."days")));
$futureDate1 = strtolower(date("Y-m-d",strtotime($date ."+".$numOfDays."days")));
$weekend1= "friday";
$weekend2= "saturday";

if($futureDate == $weekend1){
      $finalDate1 = date("Y-m-d",strtotime($futureDate1 ."+2 days"));
}
else if ($futureDate == $weekend2){
      $finalDate1 = date("Y-m-d",strtotime($futureDate1 ."+1 days"));
}
else{
    $finalDate1 = date("Y-m-d",strtotime($futureDate1));
}

echo $finalDate1;
?>


text:
Q: PowerShell command to pick out a value in an xml file and replace it to another xml I don't even know where to begin, but what powershell cmdlet can I used that can read in a a MDT xml (OperatingSystem.xml) in the following format, and grab just the GUID value (or values) $captureGUID = "{1a65f870-2247-410a-be71-75b6b975b3d5}"
<oss>
  <os guid="{1a65f870-2247-410a-be71-75b6b975b3d5}" enable="True">
  <Name>Windows 7 ENTERPRISE in Windows 7 Ent x64 install.wim</Name>
  <CreatedTime>7/21/2014 8:51:10 PM</CreatedTime>
  <CreatedBy>W2K8R2\Administrator</CreatedBy>
  <LastModifiedTime>7/21/2014 8:51:10 PM</LastModifiedTime>
  <LastModifiedBy>W2K8R2\Administrator</LastModifiedBy>
  <Description>Windows 7 ENTERPRISE</Description>
  <Platform>x64</Platform>
  <Build>6.1.7601.17514</Build>
  <OSType>Windows IBS</OSType>
  <Source>.\Operating Systems\Windows 7 Ent x64</Source>
  <IncludesSetup>True</IncludesSetup>
  <SMSImage>False</SMSImage>
  <ImageFile>.\Operating Systems\Windows 7 Ent x64\Sources\install.wim</ImageFile>
  <ImageIndex>1</ImageIndex>
  <ImageName>Windows 7 ENTERPRISE</ImageName>
  <Flags>Enterprise</Flags>
  <HAL>acpiapic</HAL>
  <Size>11566</Size>
  <Language>en-US</Language>
  </os>
<os guid="{67ee1204-ba8f-47d4-9e6c-34a7bb24dd4d}" enable="True">

Take the captured value from earlier and replace it on another xml file in a different format (e.g. update the OSGUID here)
  <?xml version="1.0" encoding="utf-8" ?>
  <sequence version="3.00" name="Standard Client Task Sequence" description="A complete task sequence for deploying a client operating system">
    <globalVarList>
      <variable name="OSGUID" property="OSGUID">{bc8e6992-5890-4be2-88af-29208f9ab0d5}</variable>
      <variable name="DestinationDisk" property="DestinationDisk">0</variable>
      <variable name="DestinationPartition" property="DestinationPartition">1</variable>
      <variable name="DestinationOSVariable" property="DestinationOSVariable" />

A: PowerShell is the wrong tool for the job. You should create an XSLT transformation.  Using XSLT you can find a specific node and easily write it to another XML sheet --- or any other kind of document for that matter.
Here is just one of several examples you can find on StackOverflow:
XSLT or XPath: how to find a node with a specific tag and text then extract it into a new xml file?

A: You can do this in Powershell, do you need only the first guid? Because your first and second guid are different. You would need to use Regex. Something like this should work.
$OSXML = Get-Content OperatingSystem.xml
$regex = 'guid=\"(\{\w+\-\w+\-\w+\-\w+\-\w+\})\"'
ForEach ($Line in $OSXML)
{   $Line -match $regex
}
$captureGUID = $Matches[1]

$ReplacementXML = [xml](Get-Content "NewXML.xml")

($ReplacementXML.sequence.globalVarList.variable | Where-Object { $_.Name -eq "OSGUID" }).'#text' = $captureGUID

$ReplacementXML.Save("C:\Test\NewXML2.xml")

You will need to change The Get-Content part of     $ReplacementXML to be the name of your second xml file that you want to import the GUID to. And then the same for the last line, change the name of the Save location to the name of the same file, I used 2 separate names to verify the import with the output.


text:
Q: Digitally sign email in Ruby with S/MIME Is there a way in Ruby to digitally sign email messages with S/MIME?  Our group uses PKI and our users are conditioned to expect digital signatures for important messages.
I know I can invoke the openssl command line tool:
openssl smime -sign -signer $CERT_FILE -passin pass:$CERT_PASS
  -in $UNSIGNED_MAIL -out $SIGNED_MAIL -certfile $CERT_CA_FILE
  -from 'your ' -to 'recipients <email@address>'
  -subject 'The Subject'

but I am hoping to utilize a Ruby solution.

A: I ended up using the above solution, but for those in a similar situation, you have to convert the PKI key (in .p12 file format) first: openssl pkcs12 -in #{@cert_file} -passin pass:#{@pass_phrase} -passout pass:#{@pass_phrase} -out #{out_file}


text:
Q: Build primefaces from source with minimized resources How to build primefaces from source and get minimized resources(css,js)?
I am using Primefaces 5.0, and use
mvn clean install

But the resources are not minimized.
primefaces.css/js
jquery-plugins.js
charts.css/js
editor.css/js
...

To make debug easier, it would be nice if there is a switch to turn on/off minimized resources during deploy.
Thanks.


text:
Q: Django can not sent email with attachments I am trying to sent email by using this code. But when I was trying. Either html or email attachment in sent. But not both. If I omit attachment email body is sent. but if I add attachment email body is not sent . Please someone provide you suggestion.
  msg = EmailMultiAlternatives(subject=self.mail_subject, from_email=from_mail, to=(to,),
                                         connection=connection)
            if isinstance(attachment, list):
                for attach_path in attachment:
                    msg.attach_file(attach_path)

            msg.attach_alternative(html_with_context_data, "text/html")
            try:
                msg.send(fail_silently=True)
            except:
                pass

A: With code like this what do you expect?
        try:
            msg.send(fail_silently=True)
        except:
            pass

You are telling django to fail silently which means it will not tell you if something goes wrong. And even if you switched off the silent mode, your exception handling is going to make sure that you never ever hear about it!!
Never do this
        except:
            pass

Always catch specific extensions, and on the rare cases that you need to catch generic exceptions like this, log it.
import traceback

except:
    traceback.print_exc()

Then you will see why exactly your attachment is not being sent.
(perhaps this should be a comment but it's far too long for that)

A: After spending 2 hours I have added only one line. Now I am getting both HTML and attachment.
msg.content_subtype = 'html'


text:
Q: Google chart : Invalid visualization type: gantt I've tried the solution here but the problem persists.
I've changed useGstaticLoader: true in this
and then in the view i get : Invalid visualization type: gantt
Any suggestion is welcome.
Anyone who Have a good Gantt chart  can he please metion it. Thank you

A: You didn't give much details. If you need/want to use AngularJS, you have angular-gantt as an option https://www.angular-gantt.com/demo/.
Or if you want no dependencies and a lightweight library, you could use jsGanttImproved https://github.com/jsGanttImproved/jsgantt-improved
Both are open-source projects.


text:
Q: Vundle not installing properly It seems like not all the plugins are installing properly. I have the following log file:
[2015-09-30 14:58:32] Plugin user/L9                                                                      |~
[2015-09-30 14:58:32] $ git clone --recursive 'https://github.com/user/L9.git' '/home/sachin/.vim/bundle/n|~
ewL9'                                                                                |~
[2015-09-30 14:58:32] > Cloning into '/home/sachin/.vim/bundle/newL9'...                                  |~
[2015-09-30 14:58:32] > remote: Repository not found.                                                     |~
[2015-09-30 14:58:32] > fatal: repository 'https://github.com/user/L9.git/' not found                     Username for 'https://github.com': sachinruk
[2015-09-30 14:58:32] >                                                                                |~
[2015-09-30 14:58:33]                                                                                |~
[2015-09-30 14:58:33] Helptags:                                                                           |~
[2015-09-30 14:58:33] :helptags /home/sachin/.vim/bundle/Vundle.vim/doc                                   |~
[2015-09-30 14:58:33] :helptags /home/sachin/.vim/bundle/vim-fugitive/doc                                 |~
[2015-09-30 14:58:33] :helptags /home/sachin/.vim/bundle/L9/doc                                           |~
[2015-09-30 14:58:33] :helptags /home/sachin/.vim/bundle/command-t/doc                                    |~
[2015-09-30 14:58:33] Helptags: 4 plugins processed

And my .vimrc file is this:
set nocompatible              " be iMproved, required
filetype off                  " required

set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
" plugin on GitHub repo
Plugin 'tpope/vim-fugitive'
" plugin from http://vim-scripts.org/vim/scripts.html
Plugin 'L9'
" Git plugin not hosted on GitHub
Plugin 'git://git.wincent.com/command-t.git'
Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
" Avoid a name conflict with L9
Plugin 'user/L9', {'name': 'newL9'}

call vundle#end()            " required
filetype plugin indent on    " required

Its obvious that there is no https://github.com/user/L9 page but I'm not quite sure what it is that I am doing wrong. It asks for my github username and password before it fails.
More importantly do I need to worry about this error?

A: No you don't need to worry about the error. You seem to have copied the VIMRC from the readme, that the readme is for illustration purposes. you should Remove plugins you don't need. below is the empty Vundle config.
This is all you need.
set nocompatible
filetype off

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'

" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required

Now if you want to add a new plugin example
nerdtree
you just add the line
Plugin 'scrooloose/nerdtree'
now the vimrc will look like this
set nocompatible
filetype off

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
" added nerdtree
Plugin 'scrooloose/nerdtree'
" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required

Now, just save the vimrc and restart vim so it can source the new vimrc then issue the :PluginInstall command:
:PluginInstall

more information on using can be found here


text:
Q: Ошибка компиляции cmake Я пытаюсь запустить в clion чужой проект с использованием cmake и Qt. Долго ковырялся и устанавливал недостающие библиотеки. В итоге пришел к ошибке cmake, которую не нашел как поправить.
Ссылка на проект: github.com/Constantor/fractals3d
"C:\Program Files\JetBrains\CLion 2021.2.1\bin\cmake\win\bin\cmake.exe" -DCMAKE_BUILD_TYPE=Debug -DCMAKE_DEPENDS_USE_COMPILER=FALSE -G "CodeBlocks - NMake Makefiles" C:\Users\degwr\CLionProjects\fractals3d
-- The CXX compiler identification is MSVC 19.29.30133.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Looking for C++ include pthread.h
-- Looking for C++ include pthread.h - not found
-- Found Threads: TRUE
-- Performing Test HAVE_STDATOMIC
-- Performing Test HAVE_STDATOMIC - Success
-- Found WrapAtomic: TRUE
-- Could NOT find Vulkan (missing: Vulkan_LIBRARY Vulkan_INCLUDE_DIR)
-- Could NOT find Vulkan (missing: Vulkan_LIBRARY Vulkan_INCLUDE_DIR)
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/degwr/CLionProjects/fractals3d/cmake-build-debug-visual-studio

Cannot get compiler information:
    Compiler exited with error code 2: "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64\cl.exe" @C:\Users\degwr\AppData\Local\Temp\response-file3070191229199956645 C:\Users\degwr\AppData\Local\Temp\compiler-file12988370343547114978 | @response-file3070191229199956645=/TP -DQT_CORE_LIB -DQT_GUI_LIB -DQT_NO_DEBUG -DQT_OPENGLWIDGETS_LIB -DQT_OPENGL_LIB -DQT_WIDGETS_LIB -DUNICODE -DWIN32 -DWIN64 -D_ENABLE_EXTENDED_ALIGNED_STORAGE -D_UNICODE -D_WIN64 /DWIN32 /D_WINDOWS /GR /EHsc /O2 /Ob2 /DNDEBUG -MD -Wall -Wextra -O3 -ffast-math -Zc:__cplusplus -permissive- -utf-8 -std:c++17 /Be /Bd /EP
    ЋЇвЁ¬Ё§ЁагойЁ© Є®¬ЇЁ«пв®а Microsoft (R) C/C++ ўҐабЁЁ 19.29.30133 ¤«п x64
    (C) Љ®аЇ®а жЁп Њ ©Єа®б®дв (Microsoft Corporation).  'ᥠЇа ў  § йЁйҐл.

    all:
        @cd C:\Users\degwr\CLionProjects\fractals3d\cmake-build-debug-visual-studio
        @set INCLUDE=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\ATLMFC\include;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include;C:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt;C:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared;C:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um;C:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\winrt;C:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt
        @set LIB=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\ATLMFC\lib\x64;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\lib\x64;C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\ucrt\x64;C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x64
        @set CL=
        @set _CL_=
        @set LINK=
        C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64\cl.exe @<< C:\Users\degwr\AppData\Local\Temp\compiler-file12988370343547114978
    /TP -DQT_CORE_LIB -DQT_GUI_LIB -DQT_NO_DEBUG -DQT_OPENGLWIDGETS_LIB -DQT_OPENGL_LIB -DQT_WIDGETS_LIB -DUNICODE -DWIN32 -DWIN64 -D_ENABLE_EXTENDED_ALIGNED_STORAGE -D_UNICODE -D_WIN64 /DWIN32 /D_WINDOWS /GR /EHsc /O2 /Ob2 /DNDEBUG -MD -Wall -Wextra -O3 -ffast-math -Zc:__cplusplus -permissive- -utf-8 -std:c++17 /Be /Bd /EP<<

    cl /TP -DQT_CORE_LIB -DQT_GUI_LIB -DQT_NO_DEBUG -DQT_OPENGLWIDGETS_LIB -DQT_OPENGL_LIB -DQT_WIDGETS_LIB -DUNICODE -DWIN32 -DWIN64 -D_ENABLE_EXTENDED_ALIGNED_STORAGE -D_UNICODE -D_WIN64 /DWIN32 /D_WINDOWS /GR /EHsc /O2 /Ob2 /DNDEBUG -MD -Wall -Wextra -O3 -ffast-math -Zc:__cplusplus -permissive- -utf-8 -std:c++17 /Be /Bd /EP
    cl: Є®¬ ¤ п бва®Є  error D8021: Ґ¤®ЇгбвЁ¬л© зЁб«®ў®©  аЈг¬Ґв "/Wextra"

[Failed to reload]


text:
Q: ¿Cómo crear una instancia en SYBASE? soy nuevo en SYBASE, quisiera saber como se crea un instancia en SYBASE, he buscado información al respecto pero no encuentro, si alguien podría darme alguna información referente a se lo agradecería mucho.

A: En Sybase el concepto de instancia es el nombre que se le da al motor de base de datos durante la instalación.  Sobre la instancia se crean las bases de datos de usuario.   En una maquina pueden existir varios nombres de instancia con sus respectivas bases de datos, todo dependiendo del uso adecuado de recursos (memoria, cpu y disco).
Con el programa sqlsrvbuildres se pueden crear instancias basadas en un archivo de recursos como por ejemplo:
sybinit.release_directory: USE_DEFAULT
sybinit.product: sqlsrv
sqlsrv.server_name: NOMBRE INSTANCIA
sqlsrv.new_config: yes
sqlsrv.do_add_server: yes
sqlsrv.network_protocol_list: tcp
sqlsrv.network_hostname_list: PUT_YOUR_HOSTNAME_HERE
sqlsrv.network_port_list: PUT_YOUR_PORT_NUMBER_HERE
sqlsrv.application_type: USE_DEFAULT
sqlsrv.server_page_size: USE_DEFAULT
Saludos,
(c) White


text:
Q: Jukito/Mockito Test with static method I am trying to test a class (using Jukito and Mockito), which unfortunately extends another class, which has a static method call. Is it possible to somehow skip this call? I would rather not use PowerMockito.
public class A extends B {

    @Inject
    public A(final String s){
        super(s);
    }
}

public abstract class B {

    private String s;

    protected String m = C.get().createUniqueId(); //Exception is thrown here

    public B(String s){
        this.s = s;
    }
}

public class C {
    private static C c; //assume this is never null

    public static C get() {
        return c;
    }

    public final native String createUniqueId() {}

}

@RunWith(JukitoRunner.class)
public class ATest {

    @Inject
    A a;

    @Test
    public void onMethod1Test(){
    }
}

When running ATest, I get the following error:
Error injecting constructor, java.lang.UnsatisfiedLinkError: C
I assumed it's because of a static method, was I wrong?
Note that all the classes are just examples from my real classes and C class was not written by my and can not be changed (unfortunately). But idea behind my classes and these are the same, I just changed names and left only relevant parts.

A: Jukito claims:

The combined power of JUnit, Guice and Mockito.

But thing is: none of these products allows you to mock static methods.
The only frameworks capable of that: PowerMock(ito) and JMockit.
As you already explained: normally you would "bypass" this "deficiency" by simply writing testable code (that avoids static calls). But as you can't improve your design, you only these two choices: use PowerMock(ito) for testing this class - or not testing it.

A: So the goal is to use C to generate m on any new instance of B. You don't control C and you're trying to figure out how to test it, right? I think you'll have to pick your poison, but I can think of another choice of "poison" for your situation.
You add a static field on B and give it more access then would otherwise be appropriate:
public abstract class B {
   static C c = C.get();
   private String s;
   protected String m = c.createUniqueId();
   public B(String s){
     this.s = s;
   }
}

Now you can reassign B.c to a mocked instance in your test. I'm more familiar with JUnit and Spock, so I'll try you could figure out the mechanics of that. Since unit tests are in the same package as the class they are testing, you can use the package private scope. If A is in a different package than B, then you'd have to promote it to protected. This is quick and easy, but exposes you to the possibility of other code reassigning B.c. You'd have to judge that risk against the risk of not testing A at all.
You could also consider adding classes and interfaces to hide C from A and B altogether. Essentially, you create something like BFactory that has Supplier<String> to generate m. In unit tests you mock the supplier and in production you use an implementation based on C. Every way I can think of to do this is messy or doesn't force every subclass of B to generate m in the same way. The only exception would be if it actually makes more sense to use composition and put an instance of B on A. Then you might have a decent way to do it.


text:
Q: How update tinkter button after finished subprocess and thread yet keeping output pipe to textbox I have a GUI that starts a script when Start button is pressed, using Popen and then starts a thread to pipe the output from that process to a window within the GUI.  The Start button turns yellow and the text changes while the process is running.
Everything works fine, except I would really like the "Start" button to return to it's initial state once the process has finished (green in color, text as "Start").
Everything I've tried, using process.wait or thread.join, interrupts the text updating within the GUI text box.  Any suggestions how to do this while keeping everything else working as it currently does?
My subprocess code, saved to testsubprocess.py is:
import time

for i in range(3):
    print("%d.%d" % divmod(i, 10))
    time.sleep(1)

My GUI code is:
import sys
from subprocess import Popen, PIPE
from threading import Thread
import tkinter as tk # Python 3
from queue import Queue, Empty # Python 3

def iter_except(function, exception):
    """Works like builtin 2-argument `iter()`, but stops on `exception`."""
    try:
        while True:
            yield function()
    except exception:
        return

class DisplaySubprocessOutputDemo:
    def __init__(self, root):
        self.root = root

        width=600
        height=350
        xloc=0
        yloc=10
        self.root.geometry('%dx%d+%d+%d' % (width, height, xloc, yloc))
        self.root.title('ICR IRN Test')

        self.statustext = tk.Text(self.root, height=4, width=30)
        self.statustext.grid(row=3, column=1)

        self.startbutton = tk.Button(self.root, text = 'Start', command=self.startprocess, bg='green', activebackground = 'orange')
        self.startbutton.config(height = 2, width = 15)
        self.startbutton.grid(row = 5, column=0,sticky='E')
        self.startbuttonpresses = 0

        exitbutton = tk.Button(self.root, text = 'Exit', command=self.quit, bg='red')
        exitbutton.config(height = 2, width = 15)
        exitbutton.grid(row = 5, column=4, sticky='E')

    def startprocess(self):
        self.startbuttonpresses = self.startbuttonpresses+1

        if self.startbuttonpresses == 1:

            self.startbutton.configure(bg='yellow')
            self.startbutton.configure(text='Stop')

            self.process = Popen([sys.executable, "-u", "testsubprocess.py"], stdout=PIPE)

            # launch thread to read the subprocess output
            #   (put the subprocess output into the queue in a background thread,
            #    get output from the queue in the GUI thread.
            #    Output chain: process.readline -> queue -> label)
            q = Queue(maxsize=1024)  # limit output buffering (may stall subprocess)
            t = Thread(target=self.reader_thread, args=[q])
            t.daemon = True # close pipe if GUI process exits
            t.start()

            # show subprocess' stdout in GUI
            self.updatetext(q) # start update loop

        else:
            self.startbuttonpresses = 0
            self.process.kill()
            self.startbutton.configure(bg='green')
            self.startbutton.configure(text='Start')

    def reader_thread(self, q):
        """Read subprocess output and put it into the queue."""
        try:
            with self.process.stdout as pipe:
                for line in iter(pipe.readline, b''):
                    q.put(line)
        finally:
            q.put(None)

    def updatetext(self, q):
        """Update GUI with items from the queue."""
        for line in iter_except(q.get_nowait, Empty): # display all content
            if line is None:
                return
            else:
                self.statustext.insert(tk.END, line)

        self.root.after(400, self.updatetext, q) # schedule next update

    def quit(self):
        try:
            self.process.kill() # exit subprocess if GUI is closed (zombie!)
        except Exception:
            pass
        self.root.destroy()

root = tk.Tk()
app = DisplaySubprocessOutputDemo(root)
root.protocol("WM_DELETE_WINDOW", app.quit)
# center window
root.eval('tk::PlaceWindow %s center' % root.winfo_pathname(root.winfo_id()))
root.mainloop()

A: You forgot to reset the button after receiving None message:
    def updatetext(self, q):
        """Update GUI with items from the queue."""
        for line in iter_except(q.get_nowait, Empty): # display all content
            if line is None:
                # process is finished
                self.startprocess() # reset the button to "Start"
                return
            else:
                self.statustext.insert(tk.END, line)

        self.root.after(400, self.updatetext, q) # schedule next update


text:
Q: Como estruturar um banco mySQL a partir de um JSON Tenho a seguinte estrutura json de teste:
{
  "CE": {
    "Fortaleza": [
      {
        "nome": "Teste",
        "email": "xx@xxx.com",
        "cel": "(xx) xx-xx"
      },
      {
        "nome": "Teste",
        "email": "xx@xxx.com",
        "cel": "(xx) xx-xx"
      }
    ],
    "Abaiara": [
      {
        "nome": "Cidade Abaiara 1",
        "email": "xx@xxx.com",
        "cel": "(xx) xx-xx"
      },
      {
        "nome": "Cidade Abaiara 2",
        "email": "xx@xxx.com",
        "cel": "(xx) xx-xx"
      }
    ]
  },
  "rn": {
    "pindaiba": [
      {
        "nome": "rtyretyerty",
        "email": "xx@xxx.com",
        "cel": "(xx) xx-xx"
      },
      {
        "nome": "zzzzzz",
        "email": "xx@xxx.com",
        "cel": "(xx) xx-xx"
      }
    ],
    "sorisal": [
      {
        "nome": "sor",
        "email": "xx@xxx.com",
        "cel": "(xx) xx-xx"
      },
      {
        "nome": "sorsor",
        "email": "xx@xxx.com",
        "cel": "(xx) xx-xx"
      }
    ]
  }
}

Criei um banco de dados e estou com dúvidas de como criar minhas estruturas de tabelas a partir do json acima, mas não é necessário os dados.

[PERGUNTA] A pergunta é sobre programação, pois não consigo escrever um código SQL que monte esse estrutura.
Objetivo: Criar um echo json_encode($stm->fetchAll(PDO::FETCH_ASSOC)); que monte a mesma estrutura json acima.

O que já tenho:

*

*Conexão com o banco:
-
function Conectar(){
        try{
            $opcoes = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8');
            $con = new PDO("mysql:host=localhost; dbname=teste;", "root", "", $opcoes);
            return $con;
        } catch (Exception $e){
            echo 'Erro: '.$e->getMessage();
            return null;
        }
    }

*

*Busca de todos os cadastros:
-
function getFilterCidade($estado){
        $pdo = Conectar();
        $sql = 'SELECT * FROM locais WHERE uf = ?';
        $stm = $pdo->prepare($sql);
        $stm->bindValue(1, $estado);
        $stm->execute();
        sleep(1);
        echo json_encode($stm->fetchAll(PDO::FETCH_ASSOC));
        $pdo = null;
    }

- Nome da estrutura json para a criação das **colunas:**
Perceba que um estado poderá ter várias cidades e uma cidade poderá ter vários usuários com: nome , email e celular. Nessa estrutura exemplo temos 2 estados com 2 cidades e cada cidade com 2 usuários.

A: Interessante questão, porque vai na contra-mão da maior parte das perguntas, querendo gerar um json ou invés de somente ler.
Bem vamos lá:
Tabelas:
Criarei apenas uma tabela com as colunas (id, Estado, Cidade, Nome, Email, Cel), acredito que saiba fazer, este não é o problema da questão. Pode optar por duas para evitar duplicações, mas não acredito que seja necessário para a questão!
Solução:

Inicialmente haverá isto na tabela:

0, CE, Fortaleza, Teste, xx@xxx.com, (xx) xx-xx
1, CE, Fortaleza, Teste, xx@xxx.com, (xx) xx-xx

O que realmente deseja é agrupar baseado no CE e Fortaleza, neste caso terá que usar o while.
<?php

$rAux = $mysqli->query("SELECT * FROM tabela ORDER BY Estado ASC, Cidade ASC");
// Pega todos os registros do banco de dados.

while($r = $rAux->fetch_array()){
// Criado um loop finito para cada registro

$nomeCidade = $r['Cidade'];
$nomeEstado = $r['Estado'];

$dados = array('nome' => $r['Nome'], 'email' => $r['Email'], 'cel' => $r['Cel']);
// Esta é a array que deseja que seja retornada

$jsonAux[ $nomeEstado ][ $nomeCidade ][] = $dados;
// CE -> FORTALEZA -> [Nome, Email Tel], [Nome, Email, Tel]
// O [] no final é para adicionar um novo. Assim como $array[] = 'manteiga'.

}
// Fim do loop

$json = json_encode($jsonAux);
echo $json;

Tentei deixar o código mais auto-explicativo possível para que possa compreender passo a passo. O PHP irá criar o caminho CE -> FORTALEZA na primeira vez e  depois irá adicionar a array nele,  uma vez que já existe.
Resultado:

MySQL:

--
-- Criar tabela
--
    CREATE TABLE `tabela` (
  `id` int(11) NOT NULL,
  `Estado` varchar(255) NOT NULL,
  `Nome` varchar(255) NOT NULL DEFAULT 'Inkeliz',
  `Cidade` varchar(255) NOT NULL,
  `Email` varchar(255) NOT NULL,
  `Cel` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dados utilizados para teste
--

INSERT INTO `tabela` (`id`, `Estado`, `Nome`, `Cidade`, `Email`, `Cel`) VALUES
(1, 'CE', 'Inkeliz', 'Fortaleza', 'xxx@xxx.com', '(00)12345678'),
(2, 'CE', 'Inkeliz', 'Fortaleza', 'xxx@xxx.com', '(00)12345678'),
(3, 'CE', 'Inkeliz', 'Aquiraz', 'xxx@xxx.com', '(00)12345678'),
(4, 'RN', 'Inkeliz', 'Pindaiba', 'pinda@xxx.com', '(00)12345678');

--
-- Index
--
ALTER TABLE `tabela`ADD PRIMARY KEY (`id`);

JSON:

{"CE":{"Aquiraz":[{"nome":"Inkeliz","email":"xxx@xxx.com","cel":"(00)12345678"}],"Fortaleza":[{"nome":"Inkeliz","email":"xxx@xxx.com","cel":"(00)12345678"},{"nome":"Inkeliz","email":"xxx@xxx.com","cel":"(00)12345678"}]},"RN":{"Pindaiba":[{"nome":"Inkeliz","email":"pinda@xxx.com","cel":"(00)12345678"}]}}


text:
Q: Using the word "remain" in the question "how many courses do you have?" How to ask about the rest quantity of courses using the word "remain"?
I mean to ask about If I want to use the word "remain" in the context of the question "how many courses do you have to do in order to get the diploma?" or "How many classes do you have in order to get your final mark?" how can I do that?
I build the following sentence:

How many courses do you remain?

but it's not clear to me and I'm afraid to use it without verification.
In addition, I don't know how to build an answer using the word "remain" ("remain to me 4 courses to complete" is correct?).

A: If you have to use the verb remain you could use

How many courses remain in order for me to get the diploma?

A response using remain might be

4 courses remain in order for you to get the diploma


text:
Q: Jquery with call back functions i have one problem with the Jquery callback functions, here is the link:
http://saveenergy.metropolia.fi/views/pihkapuisto/
as you can see, the first page works fine. but all the others are not fine. they always right side and the size is too small. anyone knows how to change the position and size, make it looks like the first one? thanks

A: you may need to use .live() as i believe you are loading elements from scratch,  .live() uses delegation thus looks for new objects that are added to the browser...


text:
Q: Tic tac toe game bug on javascript I'm having a bug on my tictactoe game coded in html/css/javascript (with jquery).
Most of the times the game works properly but in some cases (seems it doesn't depend on the positions of the pieces on the board or the sequence of the moves, I haven't managed to figure out the cases where it breaks as it is quite random) it gives wrong winner numbers (sometimes even shows a win alert when anyone should win) and it changes the expected pieces (it puts a player 1 piece when player 2 is playing and instead).
Every time this bug happens, it shows the alert of the winner (wrong winner always) and when the game resets the last clicked position doesn't reset.
I've already checked that the function WhoWins(board) works properly.
JAVASCRIPT:
const NO_WINNER = 0;
const PL1 = 1;
const PL2 = 2;
const FREE = 0;
const PIECEPL1 = 'X';
const PIECEPL2 = 'O';

$(document).ready(function() {
    TicTacToe();
});

// **** ACTION ****
function TicTacToe() {
    console.log("Game start");
    // Initialization of variables
    var moves = 0;
    var board = [[FREE, FREE, FREE],[FREE, FREE, FREE],[FREE, FREE, FREE]];
    var winner = NO_WINNER;
    $( ".square" ).html( "" ); // Reset of board
    $( "#pnum" ).html( PL1 ); // Player 1 starts
    StartMove(moves, board);
}

// **** ACTION ****
// PRE: moves is integer, board is integer 3x3 matrix.
// POST: The game has been updated.
function StartMove(moves, board) {
    console.log("Move " + moves);
    // We wait for a click on some square
    $( ".square" ).each(function() {
        $( this ).on("click", function() {
            var id = $( this ).attr( "id" );
            // [id[1]][id[2]] is the position of the clicked square in the board
            var i = id[1];
            var j = id[2];
            if (board[i][j] == FREE) { // We update the board only if the clicked position isn't already marked
                if (moves%2 == 0) { // Player 1 is playing
                    $( '#' + id ).html(PIECEPL1);
                    board[i][j] = PL1;
                }
                else { // Player 2 is playing
                    $( '#' + id ).html(PIECEPL2);
                    board[i][j] = PL2;
                }
                ++moves;
                winner = WhoWins(board);
                // We check the situation of the game
                if (moves == 9 && winner == NO_WINNER) {
                    alert( "Draw!" );
                    TicTacToe(); // We start a new game
                }
                else if (winner == NO_WINNER) {
                    $( "#pnum" ).html(moves%2 + 1); // We write the number of next move's player (We add one not because it's the next move but because the players are numbered 1,2 and not 0,1)
                    StartMove(moves, board); // We start the next move
                }
                else {
                    alert( "The winner is Player " + winner );
                    TicTacToe(); // We start a new game
                }
            }
        });
    });
}

// **** FUNCTION ****
// PRE: board is integer 3x3 matrix.
// POST: Returns integer 0 if there is no winner, integer 1 if player 1 wins or integer 2 if player 2 wins
function WhoWins(board) {
    // We check for row equality
    if (board[0][0] != FREE && board[0][0] == board[0][1] && board[0][0] == board[0][2]) return board[0][0];
    if (board[1][0] != FREE && board[1][0] == board[1][1] && board[1][0] == board[1][2]) return board[1][0];
    if (board[2][0] != FREE && board[2][0] == board[2][1] && board[2][0] == board[2][2]) return board[2][0];
    // We check for columns equality
    if (board[0][0] != FREE && board[0][0] == board[1][0] && board[0][0] == board[2][0]) return board[0][0];
    if (board[0][1] != FREE && board[0][1] == board[1][1] && board[0][1] == board[2][1]) return board[0][1];
    if (board[0][2] != FREE && board[0][2] == board[1][2] && board[0][2] == board[2][2]) return board[0][2];
    // We check for diagonal equality
    if (board[0][0] != FREE && board[0][0] == board[1][1] && board[0][0] == board[2][2]) return board[0][0];
    if (board[0][2] != FREE && board[0][2] == board[1][1] && board[0][2] == board[2][0]) return board[0][2];
    return NO_WINNER;
}

HTML:
<!DOCTYPE html>

        <link rel = "stylesheet" type = "text/css" href = "tictactoe.css">
        <title> Tic-tac-toe </title>

Player

CSS:
body { background-color: black }

#board {
    width: 914px;
    height: 914px;
    display: inline-block;
}

.square {
    border: dotted white 3px;
    width: 300px;
    height: 300px;
    display: inline-block;
    vertical-align: top;
    margin-right: -4px;
    border-radius: 20%;
    text-align: center;
    line-height: 310px;
    font-family: Arial;
    font-size: 2000%;
    color: white;
}

p {
    color: white;
    font-size: 80px;
    display: inline-block;
    position: absolute;
    margin-left: 30px;
    top: -60px;
    font-family: Arial;
}

A: Every time you call your StartMove() function you apply a new click event listener. Therefore, with each new game an additional click event is attached to the element. You don't want this, so remove (unbind) the click events before re-applying them.
I.E replace this:
$( this ).on("click", function() {...

with this:
$( this ).unbind("click").on("click", function() {...

Because you're new I also made you a jsFiddle so that you're more familiar with it for next time you post a question ;-)


text:
Q: Left/right harpoon arrow with text? I'd like a left/right harpoon arrow with text above the arrow.
This is the best I have so far, but I'd like the size of the arrow to be dynamic according to the text size.
\documentclass[12pt]{article}
\usepackage{amsmath, amssymb}
\usepackage{stackrel}
\newcommand{\lrhup}[2]{\ooalign{$#1\leftharpoonup$\cr$#1\rightharpoondown$\cr}}
\newcommand{\hpn}{\mathrel{\mathpalette\lrhup\relax}}
\begin{document}
$\stackrel{ABC}{\hpn}$
\end{document}

EDIT: I'm also interested in creating this double sided harpoon, but with fixed width, so "ABC" and "A" above the arrow would produce the same arrow, like the above example, but still somewhat wider.

A: Here is an overlay from mathtools's extensible harpoons:

\documentclass{article}

\usepackage{mathtools}

\newcommand{\xlrharpoonud}[1]{
  \mathrlap{\xleftharpoonup{\phantom{#1}}}%
  \xrightharpoondown{#1}
}
\newcommand{\xlrharpoondu}[1]{
  \mathrlap{\xleftharpoondown{\phantom{#1}}}%
  \xrightharpoonup{#1}
}

\begin{document}

$\xlrharpoonud{abc}\ \xlrharpoondu{abc}\
 \xlrharpoonud{\text{something}}\ \xlrharpoondu{\text{something else}}$

\end{document}

A: Here's an adaptation from a previous answer of mine:
\documentclass{article}
\usepackage{amsmath}

\makeatletter
% adapted from https://tex.stackexchange.com/a/96555/4427
\newcommand\hpn[2][]{%
  \ext@arrow 9999{\hpnfill@}{#1}{#2}}
\newcommand\hpnfill@{%
  \arrowfill@\leftharpoonup\relbar\rightharpoondown}
\makeatother

\begin{document}

\begin{gather*}
F \hpn{A} G
\\
F \hpn{ABC} G
\\
F \hpn{\text{overlong text}} G
\\
F \hpn[q]{p} G
\\
F \hpn[q]{\text{overlong text}} G
\end{gather*}

\end{document}

A: Here is a solution, adapted from codes in mathmode § 38, Extensible Arrows, pp.78-79:
\documentclass{scrartcl}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}

\makeatletter%
\newcommand\xluprdownharpoon[2][]{%
\ext@arrow 0099{\luprdownharpoonfill@}{#1}{#2}}
 \def\luprdownharpoonfill@{%
\arrowfill@\leftharpoonup\relbar\rightharpoondown}
\makeatother

\begin{document}

   \[ \xluprdownharpoon[abcdef]{ABCD} \]%

\end{document}


text:
Q: Counting comparisons in Heapsort using C# I have a heapsort algorithm.
private int heapSize;

    private void BuildHeap(int[] arr)
    {
        heapSize = arr.Length - 1;
        for (int i = heapSize / 2; i >= 0; i--)
        {
            Heapify(arr, i);
        }
    }

    private void Swap(int[] arr, int x, int y)//function to swap elements
    {
        int temp = arr[x];
        arr[x] = arr[y];
        arr[y] = temp;

    }
    private void Heapify(int[] arr, int index)
    {
        int left = 2 * index + 1;
        int right = 2 * index + 2;
        int largest = index;
        if (left <= heapSize && arr[left] > arr[index])
        {
            largest = left;
        }

        if (right <= heapSize && arr[right] > arr[largest])
        {
            largest = right;
        }

        if (largest != index)
        {
            Swap(arr, index, largest);
            Heapify(arr, largest);
        }
    }
    public int PerformHeapSortTest(int[] arr)
    {
        int counter = 0;
        BuildHeap(arr);
        for (int i = arr.Length - 1; i >= 0; i--)
        {
            Swap(arr, 0, i);
            heapSize--;
            Heapify(arr, 0);
        }
   DisplayArray(arr);
    }
  Private void DisplayArray(int[] arr)
    {
      for (int i = 0; i < arr.Length; i++)
         {Console.Write("{0}\n", arr[i])}
    }

I want to count the comparisons and don't understand how to implement this using this heap sort algorithm which is in a separate class which I call from the main. I have looked around online and can't find anything. Could some one show me how to implement comparisons to this algorithm?

A: You need to implement your comparisons using Compare method instead of using operators. Please see full answer here (answer post): how to count heapsort key comparisons


text:
Q: Just learned to scrape data and store it in my DB but it only scrapes one object First I am a novice, I'm still new to python and Django and I've just recently experimented with scraping my data and storing it in My database. I've got it to work kind of. It only scrapes one object and stores it. not multiple objects. Right now I am developing locally and trying to figure it out. I have it in a view like this
def practice(request):
    world = get_world_too()

    for entry in world:
        post = Post()
        post.title = entry['text']
        post.image_url = entry['src']
        post.save()

        template = "blog/post/noindex.html"
        context = {
        }
        return render(request, template, context)

and this is the function
        def get_world_too():
        url = 'http://www.example.org'
        html = requests.get(url, headers=headers)
        soup = BeautifulSoup(html.text, 'html5lib')

        titles = soup.find_all('section', 'box')[:9]
        entries = [{'href': url + box.a.get('href'),
                    'src': box.img.get('src'),
                    'text': box.strong.a.text,
                    } for box in titles]
        return entries

it only scrapes and stores multiple objects If I refresh the page. But my function is set to 9, so I thought this would at least have nine objects stored in my database. and in the view I have a loop
for entry in world:
        post = Post()
        post.title = entry['text']
        post.image_url = entry['src']
        post.save()

so shouldn't the loop get all nine of the objects? Also I no this isn't the professional way to do this. As I sid I am just practicing with it. Ultimately I want to set up this as an heroku cron job to run a couple of times throughout the day. But for right now How can I get this to scrape more than one of the objects in one shot and save it to my db.

A: It only goes through the loop once because of this line:
return render(request, template, context)
return returns out of the whole function altogether the first time it gets ran (in the first loop). If you want to go through each loop then return, move the return out of the loop like:
def practice(request):
    world = get_world_too()

    for entry in world:
        post = Post()
        post.title = entry['text']
        post.image_url = entry['src']
        post.save()

        template = "blog/post/noindex.html"
        context = {}

    # not in the loop anymore
    return render(request, template, context)


text:
Q: Custom font no being applyed on CSS Could someone tell me what's wrong here..? I've checked it many times and can not find the problem. Page always loads with Impact instead of Corbert font.
Also, when I check what is happening trough Firebug, 'corbert' name displays grey, and when hovering it, the miniature that Firebug shows as a font demo, is not Corvert, like if it did not find the files:

CSS code (I have also tried setting the first one to .eot)
@font-face {
font-family: 'corbert';
   src: url('corbert-regular.ttf');
   src: url('corbert-regular.eot?#iefix') format('embedded-opentype'),
        url('corbert-regular.woff') format('woff'),
        url('corbert-regular.ttf') format('truetype'),
        url('corbert-regular.svg#adlerRegular') format('svg');
  font-weight: normal;
  font-style: normal;
}
*, *:before, *:after {
  -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;
 }

body {
    overflow-x: hidden; height:100%; width:100%; margin:0; padding:0; font-family:'corbert',Fallback, impact;
}

Here you have a screen of the folder with linked fonts:

A: my fool proof @font-face code (taken from someone else's excruciating troubleshooting, but I can't remember who...):

@font-face {
        font-family: 'fontname';
  src: url('fonts/fontname.eot'); /* IE9 Compat Modes */
  src: url('fonts/fontname.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('fonts/fontname.woff') format('woff'), /* Modern Browsers */
         url('fonts/fontname.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('fonts/fontname.svg#svgFontName') format('svg'); /* Legacy iOS */
    }

note that there are two src and there are # on a couple of lines.
and the order seems to matter quite a bit
[edit: it's from here]

A: You have typographic apostrophes around the font name, so the name is actually 'corbert' rather than corbert.
Use regular apostrophes:
font-family: 'corbert';

Also, is the SVG name of the font really adlerRegular, and not something like corbertRegular?

A: I always refer to this blog post when I'm having trouble with custom fonts; Bulletproof @font-face Syntax.
In short, you should be using:
@font-face {
  font-family: 'corbert';
  src: url('corbert-regular.eot?') format('eot'),
       url('corbert-regular.woff') format('woff'),
       url('corbert-regular.ttf') format('truetype');
}


text:
Q: Using NSFetchedResultsController to get a random object I would like to fetch a random object from a fetch request that I am using NSFetchedResultsController with.  This is what I had:
int randIndex = arc4random() % [[_fetchedResultsController fetchedObjects] count];
randomObject = [_fetchedResultsController objectAtIndex:randIndex];

However, I don't think I'm doing this correctly, as it is causing crashes.  Could someone please provide me some advice?

A: Try this:
int randIndex = arc4random() % [[_fetchedResultsController fetchedObjects] count];
randomObject = [[_fetchedResultsController fetchedObjects] objectAtIndex:randIndex];

The crash is because NSFetchedResultsController doesn't respond to -objectAtIndex:.


text:
Q: Does this dbcp Exception matter? I'm using spring 3.05 + mysql, after the program running, I found a lot of Exceptions from log:
books.log.6- 09:24:45 Closing JPA EntityManager -org.springframework.orm.jpa.EntityManagerFactoryUtils
books.log.6- 09:24:45 about to close PreparedStatement (open PreparedStatements: 1, globally: 1) -org.hibernate.jdbc.AbstractBatcher
books.log.6- 09:24:45 aggressively releasing JDBC connection -org.hibernate.jdbc.ConnectionManager
books.log.6- 09:24:45 releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)] -org.hibernate.jdbc.ConnectionManager
books.log.6- 09:24:45 Cannot release connection [???] -org.hibernate.util.JDBCExceptionReporter
books.log.6: java.sql.SQLException: Already closed.
books.log.6-    at org.apache.commons.dbcp.PoolableConnection.close(PoolableConnection.java:114)
books.log.6-    at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.close(PoolingDataSource.java:191)
books.log.6-    at org.hibernate.connection.DatasourceConnectionProvider.closeConnection(DatasourceConnectionProvider.java:97)
books.log.6-    at org.hibernate.jdbc.ConnectionManager.closeConnection(ConnectionManager.java:474)
books.log.6-    at org.hibernate.jdbc.ConnectionManager.aggressiveRelease(ConnectionManager.java:429)
books.log.6-    at org.hibernate.jdbc.ConnectionManager.afterStatement(ConnectionManager.java:304)
books.log.6-    at org.hibernate.jdbc.AbstractBatcher.closePreparedStatement(AbstractBatcher.java:572)
books.log.6-    at org.hibernate.jdbc.AbstractBatcher.closeStatement(AbstractBatcher.java:291)
books.log.6-    at org.hibernate.jdbc.AbstractBatcher.closeQueryStatement(AbstractBatcher.java:307)
books.log.6-    at org.hibernate.jdbc.AbstractBatcher.closeQueryStatement(AbstractBatcher.java:234)
books.log.6-    at org.hibernate.loader.Loader.getResultSet(Loader.java:1967)
books.log.6-    at org.hibernate.loader.Loader.doQuery(Loader.java:802)
books.log.6-    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
books.log.6-    at org.hibernate.loader.Loader.doList(Loader.java:2533)
books.log.6-    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
books.log.6-    at org.hibernate.loader.Loader.list(Loader.java:2271)
books.log.6-    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:452)
books.log.6-    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363)
books.log.6-    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
books.log.6-    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268)
books.log.6-    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
books.log.6-    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:246)
books.log.6-    at com.tekelec.books.domain.BookInfo.findAllBooks_aroundBody4(BookInfo.java:238)
books.log.6-    at com.tekelec.books.domain.BookInfo.findAllBooks(BookInfo.java:1)
books.log.6-    at com.tekelec.books.web.BooksController.getBooks(BooksController.java:37)
books.log.6-    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
books.log.6-    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
books.log.6-    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
books.log.6-    at java.lang.reflect.Method.invoke(Method.java:616)
books.log.6-    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)

I know this is caused by Mysql -- after hours of idle, it initialy closed the connection while it still looks alive from dbcp side. Since Mysql is serving several database instance, so I need to make change from my application code side.
My question is, does the exception really matter? will JPA retry connection after the failure?
Thanks!

A: You should add a validation query (select 1) to your DataSource.
<Resource name="jdbc/cfmediaarchive" type="javax.sql.DataSource"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8"

    auth="Container" username="username" password="password"

    maxIdle="3" maxActive="15" maxWait="10000" logAbandoned="true" removeAbandoned="true" removeAbandonedTimeout="60"

    validationQuery="select 1" />

Config with Spring:
spring.xml
   <bean id="dataSource"
    class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="${driverClassName}" />
    <property name="url" value="${url}" />
    <property name="username" value="${username}" />
    <property name="password" value="${password}" />
    <property name="validationQuery" value="select 1"/>
</bean>

  <bean
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    id="entityManagerFactory">
    <property name="persistenceUnitName" value="persistenceUnit" />
    <property name="dataSource" ref="dataSource" />
    <!-- this is important to connect JPA and JdbcTemplate transaction control -->
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="false" />
        </bean>
    </property>
</bean>

persistence.xml
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
        <property name="hibernate.hbm2ddl.auto" value="validate" />
        <property name="hibernate.connection.charSet" value="UTF-8" />
        <property name="hibernate.show_sql" value="false" />

    </properties>
</persistence-unit>


text:
Q: rails - Dead pages on web app heroku Hello I am making a little quiz web app as a learning project. However when on my heroku server there are some dead pages, but not when I am running on my local server. Here is my heroku address: https://krisquiz.herokuapp.com/
The dead pages are when you submit a question and when you try and start a quiz. I looked at the urls and they look properly. The only thing in common that I can think of for the two pages is that I built the urls manually for the links (ex: request.base_url + '/quiz/' + quiz.id.to_s + '/start'). As I am not sure what I need to give you as information just tell me and I will try to quickly get back to you.
My heroku logs: http://pastebin.com/Tqfb4C6r


text:
Q: Ask a binomial distribution problem in the voting setup Two candidates were running for a post. The voting machines recorded
520,000 votes for the first candidate and 480,000 votes for the second one.
Afterwards it became apparent that the voting machines were defective—
they randomly and independently switched each vote for the opposite one
with probability of 45%. The losing candidate asked for a re-vote. Is there
a basis for a re-vote?
Source: Theory of probability and random processes / leonid b. koralov, yakov g. sinai. Section 2.4 Question 7
My attempt: I know p=0.45 is the parameter in the binomial distribution. But I don't know how to build such a binomial distribution. I am thinking a basis for a re-vote can be there are 2000 votes from the first candidate should belong to the second candidate. Then I am studying $P(X \geq 2000)$ where X is Binom(520000, 0.45). Is this thinking correct?

A: The defective voting machines can switch votes both ways -- a vote for candidate 1 can be switched to a vote for candidate 2, and vice versa. So the number of intended votes for candidate 2 equals the random variable $X+Y$, where $X$ is the number of recorded votes for candidate 1 that in fact were switched from candidate 2, and $Y$ is the number of recorded votes for candidate 2 that were not switched to candidate 1.  Then $X$ and $Y$ are independent binomial variables; note they have different success probabilities.
You want the probability $P(X+Y>500,000)$ since $\{X+Y>500,000\}$ is the event that candidate 2 received more intended votes than candidate 1. You should use the normal approximation to compute this probability.