text:
Q: How to return a PartialView from Core 2 RazorPage ViewModel Handler In Asp.Net MVC, you can easily return a partial view by doing the following:
return PartialView("ModelName", Model);
How is this done on a RazorPage ViewModel Handler?

A: Thanks alot to TechFisher for figuring it out, here is a bit cleaner example.
public IActionResult OnGetTestPartial()
{
    return new PartialViewResult()
    {
        ViewName = "Test",
        ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
        {
            Model = new TestPartialData { Data = "inputhere" },
        }
    };
}

Partial view in a file name "Test.cshtml" in the same folder as the above class.
@using YourNamespace
@model TestPartialData

Hello, model value: @Model.Data

Load it async with jquery
$("#someHtmlElementId").load("Your/Path/TestPartial");

A: I figured this out.  It is not nearly as straight forward as it is in MVC.  You have to create an empty ViewDataDictionary() and then set its Model property to the partial's populated model.
View Model / Handler
public async Task<IActionResult> OnGetAsyncUpdateSearchResults(DateTime startDate, DateTime endDate, string selectedTypes)
{
    int[] types = selectedTypes.Split(",").Select(x => int.Parse(x)).ToArray();

    var inventory = await _itemService.GetFiltered(types, null, null, null, null, null, null, startDate, endDate.ToUniversalTime(), null, null, null, null, null, null, null);

    if (inventory != null)
    {
        SearchResultsGridPartialModel = new SearchResultsGridPartialModel();
        SearchResultsGridPartialModel.TotalCount = inventory.TotalCount;
        SearchResultsGridPartialModel.TotalPages = inventory.TotalPages;
        SearchResultsGridPartialModel.PageNumber = inventory.PageNumber;
        SearchResultsGridPartialModel.Items = inventory.Items;
    }

    var myViewData = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()) { { "SearchResultsGridPartialModel", SearchResultsGridPartialModel } };
    myViewData.Model = SearchResultsGridPartialModel;

    PartialViewResult result = new PartialViewResult()
    {
        ViewName = "SearchResultsGridPartial",
        ViewData = myViewData,
    };

    return result;
}

I can now call this handler via ajax GET and have it return the partial's HTML.  I can then set the partial's div and the partial refreshes as expected.
Here is the AJAX call I'm making:
var jsonData = { "startDate": startDate, "endDate": endDate, "selectedTypes": selectedTypesAsString };

$.ajax({
    type: 'GET',
    url: "searchresults/?handler=AsyncUpdateSearchResults",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    contentType: 'application/json; charset=utf-8"',
    data: jsonData,
    success: function (result) {
        $("#searchResultsGrid").html(result);
    },
    error: function (error) {
        console.log(error);
    }
});


text:
Q: About Laguerre's method, what is $n$? I am trying to understand Laguerre's method for finding complex roots of polynomials. I don't know what the value of $n$ should be in the equation. I have seen some people say I should always set it to $2$, however, this hasn't worked for me.

A: $n$ is the degree of the polynomial you are trying to find the root of.  It comes in because we assume there are $n$ roots, one close and the rest an equal distance away.  See Wikipedia.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extjs Date picker display issue I wrote code of ExtJS for date picker, and include it in two different HTML file. Height of text box is different in the first HTML file than in the other. My code is :
Ext.create('Ext.form.Panel', {
    height: '15%',
    width: $("#MainWindow_Right_Panel").width() - 20,
    renderTo: 'FilterControl',
    id: 'DatePicker_Panel',
    border: 0,
    items: [
        {
            xtype: 'datefield',
            fieldLabel: 'To',
            name: 'to_date',
            style: 'float: right',
            id: 'todate',
            padding: 5,
            width: 130,
            labelWidth: 30,
            value: todate,
            maxValue: today,
            format: "d.m.Y",
            layout: 'form',
            listeners: {
                select: function(combo, value) {
                     todate=value;

                }
            }
        },
        {
            xtype: 'datefield',
            fieldLabel: 'From',
            style: 'float: right',
            labelWidth: 50,
            width: 150,
            name: '_fromdate',
            padding: 5,
            id: 'fromdate',
            value:fromdate,
            maxValue: today,
            format: "d.m.Y",
            layout: 'form',
            listeners: {
                select: function(combo, value) {
                   fromdate=value;
                }
            }

        },
    ]
});

output in first HTML:

in the second:

A: you have to add cls:'x-border-box, x-border-box',
after add cls you code should be like this :
 Ext.create('Ext.form.Panel', {
    height: '15%',
    width: $("#MainWindow_Right_Panel").width() - 20,
    renderTo: 'FilterControl',
    id: 'DatePicker_Panel',
    border: 0,
    items: [
        {
            xtype: 'datefield',
            fieldLabel: 'To',
            name: 'to_date',
            style: 'float: right',
            **cls:'x-border-box, x-border-box',**
            id: 'todate',
            padding: 5,
            width: 130,
            labelWidth: 30,
            value: todate,
            maxValue: today,
            format: "d.m.Y",
            layout: 'form',
            listeners: {
                select: function(combo, value) {
                     todate=value;

                }
            }
        },
        {
            xtype: 'datefield',
            fieldLabel: 'From',
            style: 'float: right',
            **cls:'x-border-box, x-border-box',**
            labelWidth: 50,
            width: 150,
            name: '_fromdate',
            padding: 5,
            id: 'fromdate',
            value:fromdate,
            maxValue: today,
            format: "d.m.Y",
            layout: 'form',
            listeners: {
                select: function(combo, value) {
                   fromdate=value;
                }
            }

        },
    ]
});


text:
Q: using js/jquery to populate google adsense I am trying to incorporate my own advertisement module for my website, if their are no ads to be displayed it defaults to google adesense ad
I currently have
if(this.ad_found)
//run code to display ad
else {
    google_ad_client = "ca-pub-";
    /* Name */
    google_ad_slot = "-----";
    google_ad_width = ---;
    google_ad_height = ---;

    var head = document.getElementById('id_from_display_page')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//pagead2.googlesyndication.com/pagead/show_ads.js';
    $("#id_from_display_page").html(script);
}

as you can tell I have no idea how to populate id 'id_from_display_page' to display the google adsense stuff
The display page:

I want to populate this div with google adsense

A: EDITS:
This time, we're going to wrap all of this in a self-executing function.  Also, we'll make new elements and stick em in the body at the end.  Here's the cheat sheet:
Javascript:
(function (window, document) {
    if (ad_found) {
        //run code to display ad
    } else {
        google_ad_client = "ca-pub-";
        /* Name */
        google_ad_slot = "-----";
        google_ad_width = "---";
        google_ad_height = "---";

        var head = document.createElement('div');
        head.id = "id_from_display_page";
        var script = '


text:
Q: Writing direction of String Scenario: The user can change the Keyboard language dynamically and enter text into UITextView.
Issue: If the user changes the keyboard language to Arabic and enters text, the text is in Right to Left direction.
Is there a way in which I can determine the writing Direction. Either from
UITextView or
The Entered Text or
Some magic from the Keyboard
Please help me solve this.
Thanks,
Roshit
PS: The TextAllignment of UITextView doesnot do the magic..
EDIT:
I also convert the NSString from the Textfield into an NSAttributedString and draw Using CoreText. Can I by any chance get the writing direction in this scenario (NSAttributedString or CoreText)

A: Take a look at the baseWritingDirectionForPosition:inDirection: method of the UITextInput protocol.
Both UITextView and UITextField implement the UITextInput protocol.

A: Thanks to @rob, this is what I came up with:
UITextPosition *aPosition;
UITextWritingDirection aDirection = [aTextView baseWritingDirectionForPosition:aPosition inDirection:UITextStorageDirectionForward];

switch (aDirection) {
    case UITextWritingDirectionNatural:
        NSLog(@"Natural");
        break;

    case UITextWritingDirectionLeftToRight:
        NSLog(@"L-R");
        break;

    case UITextWritingDirectionRightToLeft:
        NSLog(@"R-L");
        break;

    default:
        break;
}

It worked perfectly fine.
Just out of curiosity..
I used : UITextPosition *aPosition; I have not initialized it and set a position to it. Then how did this work.
@rob- Any help on this ?

A: A quick, and thus in-linable, option is to use the Locale like this:
[NSLocale lineDirectionForLanguage:[[NSLocale currentLocale]languageCode]]

Use it for things like Tab Stops like this:
NSTextTab* tab = [[NSTextTab alloc]initWithTextAlignment:(([NSLocale lineDirectionForLanguage:[[NSLocale currentLocale]languageCode]]==kCFLocaleLanguageDirectionRightToLeft)?NSTextAlignmentRight:NSTextAlignmentLeft) location:100.0f options:@{}];


text:
Q: How MDM install application on device without user interaction? I am working on one assignment, I need to implement silent apk installation on android phone.I checked many posts and find out that it is possible to install apk only if hone is rooted. But MDM(Mobile Device Management) tools are capable to install apk without user interaction and remotely.Can any body explain me how MDM are capable to do so?

A: On Android, the MDM companies such as AirWatch must have an os-level app signature for their service app.  For example, for Samsung there is this:
https://play.google.com/store/apps/details?id=com.airwatch.admin.samsung&hl=en
Once that service is installed, the OS allows AirWatch to do silent installs because the service is trusted as if it were part of the operating system.

A: Yes you can install an application silently without user interaction:
To do that your app must be system signed. Secondly you must have the apk of the application you want to install and then you need to run a command pm install which you can do programmatically something like this:
private boolean installApk(String apkPath)
{

    Command installEvent = new Command(getCommandList("pm install "
        + apkPath));

    return installEvent.executeCommandList();

}

This works for me.


text:
Q: Gap under sticky footer My sticky footer works on the "Our Story" page and Hurricane Shutters pages in Safari, but there is a white gap in Firefox and Chrome. Any help is appreciated. the link is www. sloanhp.com.

A: You have an unnecessary extra

 in your footer whose margin and padding is causing the gap.

A: Set the css of your footer to:
.footer {
position:fixed;
bottom:0;
}

That's saying you meant your really want a sticky footer.  Right now, it is just at the end of your content.
The blank paragraph tags won't matter as it is a child of the main .footer class which has a black background.


text:
Q: print a Class::Method() when a method is called Is there some easy way so that I when a method is called to get class and the method name printed on the screen.. something like this :
> class1:method()
> class1:method4()
> class3:method2()
....

in a sense insert a "cout" in the beginning of every method w/o actually doing the typing ?


text:
Q: FFMPEG Windows Batch - Recursive Convert based and settings based on Frame Height So I'm trying to make a batch file to use FFMPEG to convert around ~1000 MP4 video files.
I want to recursively go through these folders, possibly use ffprobe to discover the frame height, and then based on the frame height options (360, 480, 720, or 1080 frame height) give them individually different ffmpeg commands.
I've been reading up on various approaches to this just as far as batch processing goes.
So far I'm at this stage:
for %%a in ("*.*") do C:\ffinstall\local64\bin-video\ffmpeg -i "%%a"  -c:v libx264 -crf 18 -preset veryslow -tune film -refs 8 -bf 6 -aq-mode 2 -filter_complex "[0:v][1:v]overlay=30:main_h-overlay_h-30,subtitles='D:\add.ass'" -c:a copy "encoded\%%~na.mp4"

pause
Code to discover the frame height:
ffprobe -v error -show_entries stream=height -of default=noprint_wrappers=1 inputfile.mp4

Trying to figure out conditionals and how their syntax is.  Also I'm getting a  Unable to parse option value "add.ass" as image size error. Which I believe is due to not being to see the subtitle file.
Any suggestions on where I can start? Thanks for any help.


text:
Q: Pushing dynamic state update in a child component to a parent component Context: I am building a timer app, and I have two components, App.js (parent) and Configuration.js (child).
I want to take a state in Configuration.js, which is initially set as timerSecond: this.props.timerSecond (being pulled from App.js through props) and update the same state in the parent component as it is being updated in the child component.
Here is a segment of my App.js:
class App extends React.Component {

  constructor() {
    super();
    this.state = {
      breakLength: 5,
      sessionLength: 25,
      timerMinute: 25,
      timerSecond: 0,
      isPlay: false
    }

And my Configuration.js:
class Configuration extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isSession: true,
            timerSecond: this.props.timerSecond,
            intervalId: 0
        };

        this.playTimer = this.playTimer.bind(this);
        this.decreaseTimer = this.decreaseTimer.bind(this);
    }

        // PLAY
        playTimer() {
            let intervalId = setInterval(this.decreaseTimer, 1000);
            this.props.onPlayStopTimer(true);
            this.setState({
                intervalId: intervalId
            })
        }

        // Decrease seconds
        decreaseTimer() {
            switch(this.state.timerSecond) {
                case 0:
                    if(this.props.timerMinute === 0) {
                        if(this.state.isSession) {
                            this.setState({
                                isSession: false
                            });
                            this.props.toggleInterval(this.state.isSession);
                        } else {
                            this.setState({
                                isSession: true
                            });
                            this.props.toggleInterval(this.state.isSession);
                        }
                    } else {
                        this.props.updateTimerMinute()
                        this.setState({
                            timerSecond: 59
                        })
                    }
                    break;
                default:
                    this.setState((prevState) => {
                        return {
                            timerSecond: prevState.timerSecond - 1,
                        }
                    })
                    break;
            }
        }

Essentially- Every time seconds incrementally decrease from 59, the state timerSecond successfully changes in Configuration.js, but I'm not sure how to push that update to the parent level (App.js). I need it to dynamically update in App.js, because I have another component pulling from the same state (timerSecond) and displaying the timer tick on the page.
I've read about lifecycle methods like componentDidUpdate(), but I'm not sure how to use it in this context? Every time I try, I keep getting an infinite loop error message. I also came across this code
componentDidUpdate(prevProps, prevState){
if(prevState.searchTerm !== this.state.searchTerm) {
   this.props.onSearchChange(this.state.searchTerm)
  }
}

on this posting, but I'm not sure this would help / apply to the dynamic aspect of my timer app?

A: all you need, is to pass down a function from app.js to configuration.js
App extends React.Component {
constructor() {
    super();
    this.state = {
        breakLength: 5,
        sessionLength: 25,
        timerMinute: 25,
        timerSecond: 0,
        isPlay: false
    }
}
render() {
    const updateState = (newState) => {
        this.setState({
            ...this.state,
            newState
        })
    }

    return(
        <Configuration {...this.state} updateState={updateState}/>
    )
}
}

now updateState function is passed down as props to Configuration.js


text:
Q: iOS : Call a method just one time Hi I was wondering how can I call a method just for one time in application life ... My application should download some files from server and I need do it just for one time; I mean  mean just one time per installation
here is my method
//Download some images from server and save it into directory

- (void) downloadCovers {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    [self saveFile:@"mag1" ofType:@"png" fromURL:@"http://myweb.com/mag1.png" inDirectory:documentsDirectory];

}

and this method set images as UIButton BG :
  - (void)buttonsBGImage {

       UIImage * bgMag1 = [self loadImage:@"mag1" ofType:@"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];

        [mag1 setBackgroundImage:bgMag1 forState:UIControlStateNormal];
         NSLog(@"BG IS SET");

    }

A: why not just testing if the file is exist or not in local storage!
//Download some images from server and save it into directory

- (void) downloadCovers {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pathToImg = [NSString stringWithFormat:@"%@/mag1.png",documentsDirectory];
    BOOL isExist = [[NSFileManager defaultManager]fileExistsAtPath:pathToImg];
    if (!isExist) {
        [self saveFile:@"mag1" ofType:@"png" fromURL:@"http://myweb.com/mag1.png" inDirectory:documentsDirectory];
    }

}

A: You can't do it for a method, but you can do it for a function using pthread_once:
static pthread_once_t once = PTHREAD_ONCE_INIT;
pthread_once(& once, SomeFunction);

or you can execute a block once using dispatch_once (the most natural choice for your current implementation).
In some cases (not this one), you may also prefer to do your work in +initialize.
EDIT: Question was clarified
Just check for the file's existence, or use a preference if you want this to persist across multiple launches.

A: Set a flag as a NSUserDefaults key and check for this NSUserDefault value in your downloadCovers method. If it is already set, do nothing, else download files and set the flag to true.
Like so:
-(void) downloadCovers {
BOOL downloaded = [[NSUserDefaults standardUserDefaults] boolForKey: @"downloaded"];
if (!downloaded) {
     //download code here
      [[NSUserDefaults standardUserDefaults] setBool:YES forKey: @"downloaded"];
    }
}

Cheers

A:  - (void)buttonsBGImage {

        if (!mag1.backgroundImage){
             UIImage * bgMag1 = [self loadImage:@"mag1" ofType:@"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];

               [mag1 setBackgroundImage:bgMag1 forState:UIControlStateNormal];
               NSLog(@"BG IS SET");
        }

    }


text:
Q: add gdb package to riscv image using yocto i am new to yocto, trying to add gdb to the resulting image using IMAGE_INSTALL_append="gdb" in local.conf.
I got the following error:
ERROR: Nothing RPROVIDES 'python-compilegdb' (but /home/osdev/riscv-poky/build/../meta-riscv/recipes-core/images/core-image-riscv.bb RDEPENDS on or otherwise requires it)

NOTE: Runtime target 'python-compilegdb' is unbuildable, removing...

Missing or unbuildable dependency chain was: ['python-compilegdb']
ERROR: Required build target 'core-image-riscv' has no buildable providers.

Missing or unbuildable dependency chain was: ['core-image-riscv', 'python-compilegdb']

How can I resolve this error?
Thanks!

A: The override-style append you used literally only appends the string you give to the variable value: this means you need to add a prepending space yourself:
IMAGE_INSTALL_append = " gdb"


text:
Q: Have a clickable button on top of a combobox in WPF I can get a button to appear and be clickable in the drop down list of a combo box, but I cannot get the selected combo box item (the drop list is closed) to have the button be clickable. It always skips the button click and just opens the drop down list. I basically want the Button_Click event handler that I setup to be called once it is clicked. Here is my sample combo box that shows the button but is not clickable once it is in the selected item:
<ComboBox x:Name="MyCombo" Width="200" Height="30" ItemsSource="{Binding ListCombo}">
        <ComboBox.Resources>
            <DataTemplate DataType="{x:Type local:ComboItemClass}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=SampleText}" Width="120" />
                    <Button Width="20" Content="..." Click="Button_Click"/>
                </StackPanel>
            </DataTemplate>
        </ComboBox.Resources>
    </ComboBox>

A: Putting buttons inside comboboxes is one of those really cool features that we now CAN do in WPF that we (me included) get really excited about, before we stop to consider if we SHOULD do this.
Having a button inside a combobox makes it very easy to confuse the heck out of your user.  I would recommend that you bind the data from your comobox listitems to a button outside of the combobox, where your user will expect it.  That way, you can still change the end result of the button being pressed by selecting an item from the combobox.
EDIT:
If you have the space for it, a listbox would work perfectly for what you want to do.
    <ListBox>
        <ListBoxItem>
            <StackPanel Height="34" HorizontalAlignment="Left" Margin="12,16,0,0"  VerticalAlignment="Top" Width="430" Orientation="Horizontal">
                <Button Content="Edit"  />
                <Button Content="Delete"  />
                <TextBlock Text="Port Information here" VerticalAlignment="Center" Margin="20,0" />
            </StackPanel>

        </ListBoxItem>
        <ListBoxItem>
            <StackPanel Height="34" HorizontalAlignment="Left" Margin="12,16,0,0"  VerticalAlignment="Top" Width="430" Orientation="Horizontal">
                <Button Content="Edit"  />
                <Button Content="Delete"  />
                <TextBlock Text="Port Information here" VerticalAlignment="Center" Margin="20,0" />
            </StackPanel>

        </ListBoxItem>
        <ListBoxItem>
            <StackPanel  Height="34" HorizontalAlignment="Left" Margin="12,16,0,0"  VerticalAlignment="Top" Width="430" Orientation="Horizontal">
                <Button Content="Edit"  />
                <Button Content="Delete"  />
                <TextBlock Text="Port Information here" VerticalAlignment="Center" Margin="20,0" />
            </StackPanel>

        </ListBoxItem>


text: Q: Calculating the two outer Bezier Curves of a thick Bezier curve I'm creating a Bezier curve using 4 control points (left photo). If the same curve was 100px thick (right photo) is it possible to calculate the control points needed to create the 2 red curves using the original points? Where can I learn more about this? Thanks!


text:
Q: javascript string length compare I want to check the size of the string entered in a text box.
what am I missing?
var com = document.getElementById("comment").value;
if(com.lenght <= 100){
 alert("good");
} else {
 alert("bad");
}

A: misspelled lenght - should be length

A: It is written length not lenght.

A: Mis-spelling:
if(com.lenght <= 100){

use this:
if(com.length <= 100){

A: Try changing lenght to length.


text:
Q: Handling namespaces in the XML when using XSLT I have the following XML with name, say, "screen.xml":
    <tc:transform xmlns:tc="http://www.w2.prg/1999/XSL/Transform" version="1.0">
<tc:blockTemplate blockTitle="Court/Agency">
<link flush="true" href="./customimages/customBlockStylesheet.css" rel="stylesheet" type="text/css"/>

     <tc:label category="DISP" name="CoreDocketNumber"/>:

     **<tc:field category="DISP" name="CoreDocketNumber"/>**

     <tc:label category="DISP" name="CoreCourt"/>:

     **<tc:field category="DISP" name="CoreCourt"/>**

</tc:blockTemplate>
</tc:transform>

I am trying to write an XSL that will mostly ignore the html tags and only look at the tags with name "tc:field" and give me the following:

screen.xml

DISP.CoreDocketNumber

DISP.CoreCourt

The DISP is the value of the category attribute of the tc:field tag and CoreDocketNumber is the value of the name attribute.
Here's my attempt at the XSL
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:tc="http://www/w2.prg/1999/XSL/Tansform" xmlns="http://www.w3.org/1999/xhtml">
    <xsl:output method="html" indent="yes"/>
      <xsl:template match="@*|node()">

            <xsl:apply-templates select="tc:field"/>

      </xsl:template>

      <xsl:template match="tc:field">

<xsl:value-of select="@category"/>.<xsl:value-of select="@name"/>

      </xsl:template>
</xsl:stylesheet>

I only get the following output when I apply the xsl to the xml:

I am not sure I am handling the tc namespace correctly. Any guidance would be greatly appreciated.

A: Try something like:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:tc="http://www.w2.prg/1999/XSL/Transform"
exclude-result-prefixes="tc">

<xsl:template match="/">

screen.xml

                <xsl:apply-templates select="//tc:field"/>

</xsl:template>

<xsl:template match="tc:field">

        <xsl:value-of select="@category"/>
        <xsl:text>.</xsl:text>
        <xsl:value-of select="@name"/>

</xsl:template>

</xsl:stylesheet>


text:
Q: Getting error while inserting radio button values to oracle database from python Linked to my previous question.
I am working on a project which will basically ask 3 questions to users and answers will be available in form of radio buttons with 2 options. Once clicked on submit after selecting the options i need the values to be inserted into oracle database. Now when i am trying to add some variables which i set already, i am getting error as cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number
I have created a table in oracle database called "Survey" which have below fields
1) STAFFID
2) MACHINE
3) CURRENT_TIME
4) DAY
5) MOOD
6) WORK
I am looking help on
1) How do i insert variables as values in to the database? (staffid, machine, date_str are the values i am trying to insert in the database fields STAFFID, MACHINE, CURRENT_TIME )
2) How do i insert the radio button values day_selected, mood_selected and work_selected  into database fields DAY, MOOD, WORK
below is my code.
from tkinter import *
import tkinter.messagebox
import getpass
import socket
from datetime import datetime

root=Tk()
root.title("Survey")
root.geometry("225x225")
root.config(bg="antique white")
root.resizable(width="false", height="false")

day_selected = IntVar()
mood_selected = IntVar()
work_selected = IntVar()

# creating values for entry

staffid = getpass.getuser()
machine = socket.gethostname()
now = datetime.now()
date_str = now.strftime("%Y/%m/%d %H:%M:%S")
day_sel = day_selected.get()

def done():
    print(staffid)
    print(machine)
    print(date_str)
    print(day_sel)
    print("Good" if day_selected.get()==1 else "BAD")
    print("Good" if mood_selected.get()==3 else "BAD")
    print("Good" if work_selected.get()==5 else "BAD")
    dsn_tns = cx_Oracle.makedsn('server', 'port', service_name='XXXX.XX.XXXX')
    conn = cx_Oracle.connect(user=r'XXXX', password='XXXX', dsn=dsn_tns)
    cur = conn.cursor()
    cur.execute("INSERT INTO SURVEY (STAFF_ID, HOST_NAME, CURRENT_TIME, DAY, MOOD, WORK) VALUES (%s, %s, %s, %s, %s, %s)",
                (staffid, machine))
    conn.commit()
    cur.close()
    conn.close()
    tkinter.messagebox.showinfo("Thank you", "Thank you for completing the survey !!!")

lab1 = Label(root, text="  How Was ?", font=("calibri", 20, "bold"), bg="antique white", fg="brown").pack()
lab2 = Label(root, text="Day", font=("calibri", 14, "bold"),bg="antique white")
lab2.place(x=8, y=50)
r1=Radiobutton(root,text="Good", font=("calibri",12), variable=day_selected, value=1,bg="antique white").place(x=110,y=52)
r2=Radiobutton(root,text="Bad",font=("calibri",12), variable=day_selected, value=2,bg="antique white").place(x=170,y=52)
lab3 = Label(root, text="Mood", font=("calibri", 14, "bold"),bg="antique white")
lab3.place(x=8, y=100)
r3=Radiobutton(root,text="Good", font=("calibri",12), variable=mood_selected, value=3,bg="antique white").place(x=110,y=102)
r4=Radiobutton(root,text="Bad",font=("calibri",12), variable=mood_selected, value=4,bg="antique white").place(x=170,y=102)
lab4 = Label(root, text="Work", font=("calibri", 14, "bold"),bg="antique white")
lab4.place(x=8, y=150)
r5=Radiobutton(root,text="Good", font=("calibri",12), variable=work_selected, value=5,bg="antique white").place(x=110,y=152)
r6=Radiobutton(root,text="Bad",font=("calibri",12), variable=work_selected, value=6,bg="antique white").place(x=170,y=152)

sub_bt=Button(root, text="Submit",font=("calibri",12, "bold"), command=done, bg="brown", fg="white").pack(side=BOTTOM)

root.mainloop()


text:
Q: How many "elementary" characterizations of twisted SU(2) representation varieties are known? If $\Sigma_g$ is a genus-$g$ surface, $g \geq 2$, then let $\mathcal{M}(\Sigma_g)$ be its twisted SU(2) representation variety, i.e. $$\mathcal{M}(\Sigma_g) := \{ (A_1, B_1, \ldots, A_g, B_g) \in SU(2)^{2g} \:|\: [A_1,B_1]\cdots[A_g,B_g] = -I \}/SO(3),$$ where $SO(3) = SU(2)/\{\pm 1\}$ acts on these tuples by conjugating each component.  Then $\mathcal{M}(\Sigma_g)$ is a smooth, compact $(6g-6)$-dimensional symplectic manifold, and it's symplectomorphic to the moduli space of stable bundles over a genus-$g$ Riemann surface with rank $2$ and determinant equal to some fixed line bundle of odd degree (this moduli space is a Kaehler manifold).
In his 1968 paper "Stable bundles of rank 2 and odd degree over a curve of genus 2", Peter Newstead showed that $\mathcal{M}(\Sigma_2)$ is isomorphic to the intersection of two generic quadric hypersurfaces in $\mathbb{P}^5$.  In a recent paper, Ivan Smith used this characterization to get a lot of information about the Fukaya category of $\mathcal{M}(\Sigma_2)$ in terms of the Fukaya category of $\Sigma_2$.  (My impression is that people care a lot about the Lagrangian intersection theory of $\mathcal{M}(\Sigma_g)$ because if you understand that, you understand the instanton Floer homology of 3-manifolds.)  My question is:

are there any similarly elementary characterizations of $\mathcal{M}(\Sigma_g)$ for $g \geq 3$?

I know that bits and pieces about $\mathcal{M}(\Sigma_g)$ are known, e.g. its symplectic volume and characteristic classes (maybe even its cohomology?); I would really like to know about more elementary things that are known to be isomorphic to it as symplectic/Kaehler manifolds.

A: I think Nate might know this by now, but in case anyone else is curious, there is a generalization of the intersection-of-quadrics-in-$\mathbb{P}^5$ picture to general genus, proved first in this paper, I believe

Classification of Vector Bundles of
  Rank 2 on Hyperelliptic Curves, U.V.
  Desale and S. Ramanan, Inventiones

The story is that $\mathcal{M}_g$ is homeomorphic (in fact, symplectomorphic), to the space of $g-2$ dimensional linear subspaces in the intersection of two quadrics in $\mathbb{P}^{2g+1}$.


text:
Q: JQuery ajax not working for specific input string parameter "" I'm making a JQuery ajax call with a string input parameter as below. But whenever the input parameter value is "<?", the ajax call fails without even hitting the controller method in the service layer.
But this works fine, for all input values like "<", "?", "<*" etc.. This is breaking only for this input "<?".
In the controller service method, if i hard code the input parameter value to "<?", this provides me the expected result. Only when i pass this value from JQuery ajax this is breaking.
$.ajax({
                url: '/Profile/ValidateAccountName',
                type: 'GET',
                dataType: 'json',
                async: false,
                data: {
                    accountName: $('#account-name').val()
                },
                cache: false,
                success: function (result) {
                    if (!result) {
                        isValid = false;
                        errMsg = "Account name has invalid characters";
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    console.error("Service call failed during ValidateAccountName() execution. ")
                }
            });

Please let me know what am i missing here.

A: ? is a special character and is a marker for starting a new URL parameter. You need to use encodeURIComponent method to send such special characters like below,
$.ajax({
                url: '/Profile/ValidateAccountName',
                type: 'GET',
                dataType: 'json',
                async: false,
                data: {
                    accountName: encodeURIComponent($('#account-name').val())
                },
                cache: false,
                success: function (result) {
                    if (!result) {
                        isValid = false;
                        errMsg = "Account name has invalid characters";
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    console.error("Service call failed during ValidateAccountName() execution. ")
                }
            });


text:
Q: Overlay Layout crashes in Android O I use this code to show the overlay layout in my app. In android 8.0 "Oreo" it crashes
WindowManager.LayoutParams playerParams = new WindowManager.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT,
        WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
        WindowManager.LayoutParams.FLAG_FULLSCREEN,
        PixelFormat.TRANSLUCENT);

I found that this TYPE_SYSTEM_ERROR is deprecated in O. Is there any other way to show the layout.

A: I was also facing the same issue the TYPE_SYSTEM_ERROR is Deprecated in oreo So if we have to use that we need to do this
WindowManager.LayoutParams params;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            PixelFormat.TRANSLUCENT);
} else {
    params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            PixelFormat.TRANSLUCENT);
}

You can try this out.


text:
Q: How to embed tweets in asp.net application I want to embed tweets in an asp.net application/page. Something akin to the wordpress feature where all one has to do is paste the url for tweet in the editor and WP automagically embeds the tweet. Or maybe some sort of shortcode like [tweet:numeric_String_here] and then this becomes a nicely formatted tweet. After much googling i have found a couple of potential solutions. One is clients side - EmbedTweet which i i just tried but does not work. I know twitter uses OAuth so this script may use their legacy api. The other solution is to work with OEmbed based on what i rad at twitter's dev section. So before I start heading a potential blind alley I'd like a little direction on what i should i look at to embed tweets with asp.net, Could be a client side solution too. I'd rather use use a pre-built solution but if i have to roll my own i can. Does Linq to Twitter or Twitterizer support embeding tweets? Or should I use JSON.net to get the tweet info via JSON?

A: Twitter has a statuses/oembed.json endpoint that I implemented in LINQ to Twitter. Here's an example of how you might use it:
    static void OEmbedStatusDemo(TwitterContext twitterCtx)
    {
        var embeddedStatus =
            (from tweet in twitterCtx.Status
             where tweet.Type == StatusType.Oembed &&
                   tweet.ID == "305050067973312514"
             select tweet.EmbeddedStatus)
            .SingleOrDefault();

        Console.WriteLine("Embedded Status Html: " + embeddedStatus.Html);
    }


text:
Q: Wrong colors extracted from TBitmap.Palette I am trying to extract colors from 8 bit bitmap with the usage of TBitmap.Palette. My colors are messed up and I don't know why. I've created a simple visual test to compare results:

Code that I am using:
procedure TForm36.FormCreate(Sender: TObject);
var
  LBitmap1, LBitmap2: TBitmap;
  LPaletteEntries: TMaxLogPalette;
  P1: PByteArray;
  P2: PRGBTriple;
  X,Y: Integer;
begin
  {$POINTERMATH ON}
  LBitmap1 := TBitmap.Create;
  LBitmap1.LoadFromFile('E:\3x2x8.bmp');
  img1.Picture.Assign(LBitmap1);

  LBitmap2 := TBitmap.Create;
  LBitmap2.Width := LBitmap1.Width;
  LBitmap2.Height := LBitmap1.Height;
  LBitmap2.PixelFormat := pf24bit;

  GetPaletteEntries(LBitmap1.Palette, 0, 256, LPaletteEntries);
  for Y := 0 to LBitmap1.Height - 1 do
  begin
    P1 := LBitmap1.ScanLine[Y];
    P2 := LBitmap2.ScanLine[Y];
    for X := 0 to LBitmap1.Width - 1 do
    begin
      P2[X].rgbtBlue := LPaletteEntries.palPalEntry[P1[X]].peBlue;
      P2[X].rgbtGreen := LPaletteEntries.palPalEntry[P1[X]].peGreen;
      P2[X].rgbtRed := LPaletteEntries.palPalEntry[P1[X]].peRed;
    end;
  end;
  img2.Picture.Assign(LBitmap2);
end;

Any idea what I am doing wrong? Thanks.

A: I was passing a wrong structure to GetPaletteEntries.
I should pass palPalEntry: array [0..255] of TPaletteEntry; and not TMaxLogPalette.


text:
Q: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. while testing javascript code having defer() i have the following code  in FormService.js
service.retriveFields = function (Id,UniqueIds) {

        var deferred = $q.defer();

        function success(successResponse) {
            // valid response received
            if (successResponse.data) {
                deferred.resolve(successResponse.data);

            } else {
                // TODO: show error message
                console.log("error");

                deferred.reject(response);
            }
        }

        function error(errorResponse) {
            console.log(errorResponse);
            deferred.reject(errorResponse);
            // TODO: show error message
        }

        // service call
        SomeFactory.retriveFields(Id, UniqueIds)
            .then(success, error);

        return deferred.promise;
    };

I have written the following  test case
describe('retriveFields ()', function () {
    it('tests function call', function (done) {

        var response = {data: {}};
        var deferred = $q.defer();
        var promise = deferred.promise;
        promise.then(function () {
            resolve(response);
        });

        var Id = "5b7d86e60bf5e5bc21b4309f";
        var UniqueIds = ["5b7d71b822fc4e102c0875d3", "5b7d71ad2d4914162cb12ec6"];

        sinon.stub(SomeFactory, 'retriveFields')
            .returns($q.when(response));

        var promise = FormService.retriveFields (Id,UniqueIds);
        promise.then(function (result) {
            expect(result).toEqual({data :{}});
        })
    });
});

however i got the following error
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
I am not understanding as to why the timeout is happening . Am i testing incorrectly ?
if yes please help me as to how can i test defer

A: Looks like you aren't calling done() to let Jasmine know to stop waiting for your test to complete.


text:
Q: How can I disable an audio HDMI device? powertop reports that Intel CougarPoint HDMI is 100% active and there are reports that this device consumes a lot of power. If that is so, I would like to disable it as I never use it. Is there a way I can disable it?
I am using Ubuntu 11.10

A: I had the same issue when I updated to Ubuntu 19.10.

*

*Open PulseAudio Volume Control. I believe it's already installed by default.

*Click the Configuration tab.

*Find your HDMI device and set the Profile to Off.

If it's not install, you can install the PulseAudio control panel using:
sudo apt install pavucontrol

A: *

*Click on the speaker icon, top right. Choose 'Sound Settings...'

*Click on the Hardware tab

*Select the HDMI device and choose 'Off' from the pull-down menu.

A: As per other answer:
Off mode in pavucontrol lives it's own life and is not persistent.
Using load-module module-switch-on-port-available in /etc/pulse/default.pa does not look like a desired solution.

Another approach:

*

*Sudo Edit: /etc/modprobe.d/blacklist.conf

*Add: blacklist snd_hda_codec_hdmi

*Run: pulseaudio -k to restart pulseaudio.

Downside: even with it blacklisted it re-appear if it is on a device that is attached after boot. E.g: I have 6 monitors where one have HDMI-audio. If I de-activate the HDMI monitor and then activate it the HDMI-audio for it is activated. Have not investigate why.

A: To disable the audio device (not just mute) run in terminal
sudo alsa force-unload

alsa options are
unload|reload|force-unload|force-reload|suspend|resume

In case you require the audio device at a later stage.


text:
Q: AVPlayerViewController did exit full screen I'm trying to know when an AVPlayerViewController was dismissed or exited full screen in order to change its parent view controller layout but I'm having no luck finding a delegate method that tells me when it happens.
I've tried adding an observer on the view controller like so:
player = AVPlayer(URL: NSURL(fileURLWithPath: videoPath))
playerController = AVPlayerViewController()
playerController?.delegate = self
playerController!.player = player

playerController?.contentOverlayView?.addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions.New, context: nil)
addChildViewController(playerController!)

but it's never triggered.
I just want to know when playerControlleris being dismissed or user exited full screen.

A: You can handle it in the parent view controller's viewWillAppear: method.
func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let playerController = playerController {
        // handle exit of playerController here...
    }
}

A: If you want track user exit fullscreen or state of video, you can use MPMoviePlayerController.


text:
Q: the series $\sum_{n=1}^{\infty}f_n(x)$ converges uniformly Choose the correct option let  $f :\mathbb{R} \rightarrow  \mathbb{R}$ be  non zero function such that $|f(x)| \le \frac{1}{1+2x^2}$  for all $x \in \mathbb{R}$ .Define real value  function $f_n$  on $\mathbb{R}$  for all $n \in \mathbb{N}$ by $f_n(x) = f(x +n)$.
Then ,the series  $\sum_{n=1}^{\infty}f_n(x)$  converges  uniformly
Choose the correct option
$a)$ on $[0,1]$
$b)$ on $[-1,0]$
$c)$ on $[-1,1]$
$d)$  None of these
I thinks  option $a) ,b)$ and $c)$  will correct  because derivative of $f$  is  bounded
Is its  True??

A: HINT:
We are not given that $f$ is differentiable.
So, note that for $x\in [-1,1]$
$$|f_n(x)|=|f(x+n)|\le \frac{1}{1+2(x+n)^2}\le \frac1{1+2(n-1)^2}$$
Appeal to the Weierstrass M-Test.  Can you finish?


text:
Q: Bucket password in Couchbase I am creating a demo project for reative programming with springboot and Couchbase.
I have set the below properties in application.properties file:
spring.couchbase.bootstrap-hosts=localhost
spring.couchbase.bucket.name=vanquish
spring.couchbase.bucket.password=
spring.data.couchbase.repositories.type=auto

As I don't have any bucket level password while creating it. Still, service is not able to start because of below exception:
Caused by: com.couchbase.client.java.error.InvalidPasswordException: Passwords for bucket "vanquish" do not match.
    at com.couchbase.client.java.CouchbaseAsyncCluster$OpenBucketErrorHandler.call(CouchbaseAsyncCluster.java:651) ~[java-client-2.5.9.jar:na]
    at com.couchbase.client.java.CouchbaseAsyncCluster$OpenBucketErrorHandler.call(CouchbaseAsyncCluster.java:634) ~[java-client-2.5.9.jar:na]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:140) ~[rxjava-1.3.8.jar:1.3.8]
    at rx.internal.operators.OnSubscribeMap$MapSubscriber.onError(OnSubscribeMap.java:88) ~[rxjava-1.3.8.jar:1.3.8]
    at rx.observers.Subscribers$5.onError(Subscribers.java:230) ~[rxjava-1.3.8.jar:1.3.8]
    at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.checkTerminated(OperatorObserveOn.java:273) ~[rxjava-1.3.8.jar:1.3.8]
    at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:216) ~[rxjava-1.3.8.jar:1.3.8]
    at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55) ~[rxjava-1.3.8.jar:1.3.8]

I tried searching all properties but not able to find any relevant property to set username and password or setting the password in couchbase for the bucket.

A: Assuming that you're using a couchBase version 5.x:
According to the couchBase documentation:

To access cluster-resources, Couchbase Server users — administrators
  and applications — must specify a username and password.

Steps to follow:

*

*Open your couchBase admin console: http://<couchBase-host>:8091/ui/index.html#!/overview

*Click on 'Security'

*click on 'Add user'

In the 'Add user' form add these parameters:
User Name: This must be the bucket name, in your case vanquish.
Password: Set the password that you want, this must be the value set in spring.couchbase.bucket.password.
Roles: Go to Roles -> Bucket Roles -> Bucket Admin and select your bucket, in your case vanquish.
Click on 'Save'.
After doing this and set the password in spring.couchbase.bucket.password it should work.


text:
Q: How to override the default image loaded by a facet of orderingList richfaces component I'm trying to change the image loaded by default in the facets of orderingList richfaces component.
The default image is being loaded from DATB folder so i'm trying to override the loading and make from a local folder in my project.
enter image description here
So, i'm trying to override the image used for first button and use mine instead.
For example, the generated img tag for topControlDisabled facet is :
<img style="margin:0px;padding:0px;border:0px;" width="15" height="15"
     border="0" alt="topControlDisabled" src="/XXXX/faces/a4j_3_1_6.SR1org.richfaces.renderkit.html.images.OrderingListIconTopDisabled/DATB/eAE7Pynr9d75nz59BgAgIgbq">

How i can override the src attribute to make the facet use my image link ?

A: You can customize the controls, e.g.
<rich:orderingList … >
    <f:facet name="topControl">
        <!-- your code here -->
    </f:facet>
    …

This will replace the "First" button, the other facet names are upControl, downControl and bottomControl. See the docs.


text:
Q: Multiselection of recycler view inner containers
This is my recyclerview adapter. I am inflating views. Now I want to select the containers in each view. They are working fine but when I scroll down to the list the selection gone missing. Please help me to store the selection containers on each view. Thanks

Here is my onBind Method of recyclerviewAdapter;
@Override
    public void onBindViewHolder(final NewProductsView holder, final int position) {
        final int posi = position;
        final Product product = products.get(position);
        if (positiono.contains(position)) {
            holder.cat_con.setVisibility(View.VISIBLE);
            int i = positiono.indexOf(position);
            holder.cat.setText(categories.get(i).getName());
        } else {
            holder.cat_con.setVisibility(View.GONE);
        }

        holder.product_name.setText(product.getName());
        holder.price1.setText("SAR " + product.getSwDrycleanPrice());
        holder.price2.setText("SAR " + product.getSwWashingPrice());
        holder.price3.setText("SAR " + product.getSwPress());
        holder.checkBox.setChecked(product.isSelected());
        holder.checkBox.setTag(product);

        if (product.isSelected()) {
            holder.checkBox.setSelected(product.isSelected());
        } else {
            holder.checkBox.setSelected(!product.isSelected());
        }

        if (product.isSeriver1()) {
            setColored(posi, holder);
        }else {
            setColorTransparent(holder);
        }

        if (product.isSeriver2()) {
            setColored(posi, holder);
        }else {
            setColorTransparent(holder);
        }

        if (product.isSeriver3()) {
            setColored(posi, holder);
        }else {
            setColorTransparent(holder);
        }

        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                CheckBox cb = (CheckBox) v;
                Product emp = (Product) cb.getTag();

                emp.setSelected(cb.isChecked());
                products.get(posi).setSelected(cb.isChecked());

                Toast.makeText(
                        v.getContext(),
                        "Selected Employees: " + cb.getText() + " is "
                                + cb.isChecked(), Toast.LENGTH_LONG).show();
            }
        });

        holder.service_con1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!holder.isFav) {
                    product.setSeriver1(true);
                    products.get(posi).setSeriver1(true);
                    products.get(posi).setSeriver2(false);
                    products.get(posi).setSeriver3(false);
                    setColor(holder, 0);
                    holder.isFav = true;
                } else {
                    holder.isFav = false;
                }
            }
        });

        holder.service_con2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!holder.isFav) {
                    product.setSeriver2(true);
                    products.get(posi).setSeriver1(false);
                    products.get(posi).setSeriver2(true);
                    products.get(posi).setSeriver3(false);
                    setColor(holder, 1);
                    holder.isFav = true;
                } else {
                    holder.isFav = false;
                }
            }

        });

        holder.service_con3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!holder.isFav) {
                    product.setSeriver3(true);
                    products.get(posi).setSeriver1(false);
                    products.get(posi).setSeriver2(false);
                    products.get(posi).setSeriver3(true);
                    setColor(holder, 2);
                    holder.isFav = true;
                } else {
                    holder.isFav = false;
                }
            }
        });

    }

this is the setColor method:
public void setColor(NewProductsView holder, int i) {
        switch (i) {
            case 0:
                holder.service1.setTextColor(activity.getResources().getColor(R.color.white));
                holder.price1.setTextColor(activity.getResources().getColor(R.color.white));
                holder.service_con1.setBackgroundColor(activity.getResources().getColor(R.color.colorPrimary));

                holder.service2.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.price2.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.service_con2.setBackgroundColor(activity.getResources().getColor(R.color.transparent));

                holder.service3.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.price3.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.service_con3.setBackgroundColor(activity.getResources().getColor(R.color.transparent));

                break;
            case 1:
                holder.service1.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.price1.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.service_con1.setBackgroundColor(activity.getResources().getColor(R.color.transparent));

                holder.service2.setTextColor(activity.getResources().getColor(R.color.white));
                holder.price2.setTextColor(activity.getResources().getColor(R.color.white));
                holder.service_con2.setBackgroundColor(activity.getResources().getColor(R.color.colorPrimary));

                holder.service3.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.price3.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.service_con3.setBackgroundColor(activity.getResources().getColor(R.color.transparent));

                break;
            case 2:
                holder.service1.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.price1.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.service_con1.setBackgroundColor(activity.getResources().getColor(R.color.transparent));

                holder.service2.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.price2.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
                holder.service_con2.setBackgroundColor(activity.getResources().getColor(R.color.transparent));

                holder.service3.setTextColor(activity.getResources().getColor(R.color.white));
                holder.price3.setTextColor(activity.getResources().getColor(R.color.white));
                holder.service_con3.setBackgroundColor(activity.getResources().getColor(R.color.colorPrimary));
                break;
        }
    }

A: Instead of doing directly setTextColor on any view, you should update that in the arraylist that is bound to the adapter.
after changing any value , user notifyDataSetChanged(); and it will work correct.
Reason: Always when you scroll a recyclerview , it recycle the views every time when they come into focus.
Example:
Whenever you set a new color using setColor() method, save that color in arraylist too and set that dynamically in onBindViewHolder method.
Let me know if i misunderstood.


text:
Q: How to use PHP to Redirect to an url after the base_url I'm trying to use PHP to redirect to a page 5 secs after an action is done. I've searched up how to use header for this but want to get more info on incorporating base_url() into the code, so I won't need to change this script multiple times on different servers.
Code:
$url=base_url().'page_I_want_to_go_to'
header('Refresh: X; URL=$url');

This does redirect me to a link, but the url is not the url I was indicating with base and page I want to go to.

A: Edit to:
$url=base_url().'page_I_want_to_go_to'
header('Refresh: 5; URL=' . $url);

Do you have something configured inside the config file. Check the configuration of the framework that uses. For example, in codeigniter the configuration file is in /application/config/config.php
$config['base_url'] = 'my_page';

A: Change the bottom line to "double quotes", PHP wont substitute variables that are in single quotes.
$url=base_url().'page_I_want_to_go_to'
header("Refresh: X; URL=$url");


text:
Q: Comparing user input I want to write simple application in c# that help me learning touch typing. Right now I'm making method to compare chars from text and user input. I have problem because I made some method to look for text change :
private void tb_write_TextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox t =(TextBox)sender;

        if (Words.WordCompare(tb_text.Text.ToCharArray(), t.Text.ToCharArray()))
        {

            l_words.Content =("OK");

        }
        else
        {
            l_words.Content = ("Not ok");
        }

    }

Then I have my WordCompare method:
class Words
{
  public static bool WordCompare(char[] input, char[] output)
    {
        List<char> used = new List<char>();

        foreach(char ch_out in output)
        {
            foreach (char ch_in in input)
            {
                if (ch_out == ch_in)
                {
                    used.Add(ch_in);
                    return true;
                }
            }
        }
        return false;
    }

Main problem is that if user input is ok (I mean that user write every character right) method works fine, but it checks only first character,no matter what I write then and always return true. Moreover it return true when any letter from text and user input is the same, no on what postion it is. I wanted to add "used" character to list to track them, but it makes new list every time when method is called. Could you help me with this problem, or maybe there is another way of solving it?

A: class Words
{
  public static bool WordCompare(char[] input, char[] output)
    {
        List<char> used = new List<char>();
        bool flag = true;

        if(input.Length!=output.Length) {return false;}

        for(int i=0;i<input.Length;++i)
        {
                if (input[i]==output[i])
                {
                    used.Add(ch_in);
                }
               else
                {
                     flag = false;
                     break;
                }
        }
        return flag;
    }

Besides what I wanna say is: you don't need to compare when type each character but just compare the whole string by letting a client's clicking on another new button, in which button's event click just use your foreach to do comparation.


text:
Q: How to correctly scope a dataframe in R to use with a formula in a function After some digging (1, 2, 3), there appears to be a few posts about using formulas within functions causing scoping issues if I am understanding them correctly. Some suggests to use an environment, assign, or <<- to get around the issue, but I've been stumped how to use them (and confused why there's an issue in the first place).
Let's try this toy code:
library(survival)
library(survminer)
set.seed(1)

give_p_val <- function() {
  df <- data.frame('OS' = ovarian[, 'futime'], 'Survival_event' = ovarian[, 'fustat'])
  subgroup <- sample(nrow(df), nrow(df)/2)
  df$Class <- 'A'
  df$Class[subgroup] <- 'B'

  fit2 <- survfit(Surv(OS, Survival_event) ~ Class, data=df)
  return(surv_pvalue(fit2))
}
give_p_val( )

It doesn't work, unless you run it directly, which hints at a scoping issue.
This code will work to return a fitted object:
survfit(Surv(futime, fustat) ~ rx, data=ovarian)

So why does the function break if we copy a dataframe within the scope?
testit<-function(){
  ovarian2 <- ovarian
  fit2 <- survfit(Surv(futime, fustat) ~ rx, data=ovarian2)
  return(surv_pvalue(fit2))
}

testit()

Ultimately, how do I generate a dataframe within a function to be handled correctly by the formula being used?
Thanks!

A: This is a known issue in the survminer package and how surv_pvalue interacts with survfit objects. If you change survfit to  the survminer package's version, surv_fit, your function will work just fine.
give_p_val <- function() {
  df <- data.frame('OS' = ovarian[, 'futime'], 'Survival_event' = ovarian[, 'fustat'])
  subgroup <- sample(nrow(df), nrow(df)/2)
  df$Class <- 'A'
  df$Class[subgroup] <- 'B'
  fit2 <- surv_fit(Surv(OS, Survival_event) ~ Class, data=df)
  surv_pvalue(fit2, data = df)
}
give_p_val( )
#   variable      pval   method pval.txt
# 1    Class 0.2615363 Log-rank p = 0.26


text:
Q: Pyinstaller No module named msvc I am using Pyinstaller on Ubuntu to create a binary executable for my Python code. This code has a bunch of files and dependencies. One of them is tensorflow. The executable is getting created correctly but when I try to run it, I get the following error:
Traceback (most recent call last):
  File "detection_init.py", line 14, in <module>
    import lib.tensorboxDetector as tensorboxDetector
  File "/tmp/pip-build-EuLWEf/pyinstaller/PyInstaller/loader/pyimod03_importers.py", line 389, in load_module
  File "lib/tensorboxDetector.py", line 20, in <module>
    import tensorflow as tf
  File "/tmp/pip-build-EuLWEf/pyinstaller/PyInstaller/loader/pyimod03_importers.py", line 389, in load_module
  File "tensorflow/__init__.py", line 24, in <module>
  File "/tmp/pip-build-EuLWEf/pyinstaller/PyInstaller/loader/pyimod03_importers.py", line 389, in load_module
  File "tensorflow/python/__init__.py", line 104, in <module>
  File "/tmp/pip-build-EuLWEf/pyinstaller/PyInstaller/loader/pyimod03_importers.py", line 389, in load_module
  File "tensorflow/python/platform/test.py", line 57, in <module>
  File "/tmp/pip-build-EuLWEf/pyinstaller/PyInstaller/loader/pyimod03_importers.py", line 389, in load_module
  File "mock/__init__.py", line 2, in <module>
  File "/tmp/pip-build-EuLWEf/pyinstaller/PyInstaller/loader/pyimod03_importers.py", line 389, in load_module
  File "mock/mock.py", line 71, in <module>
  File "pbr/version.py", line 461, in semantic_version
  File "pbr/version.py", line 447, in _get_version_from_pkg_resources
  File "/tmp/pip-build-EuLWEf/pyinstaller/PyInstaller/loader/pyimod03_importers.py", line 389, in load_module
  File "pbr/packaging.py", line 32, in <module>
  File "/tmp/pip-build-EuLWEf/pyinstaller/PyInstaller/loader/pyimod03_importers.py", line 389, in load_module
  File "setuptools/__init__.py", line 160, in <module>
  File "setuptools/monkey.py", line 104, in patch_all
  File "setuptools/monkey.py", line 156, in patch_for_msvc_specialized_compiler
  File "importlib/__init__.py", line 37, in import_module
ImportError: No module named msvc

How can I resolve this error and run the file correctly?

A: I added msvc to the hidden imports. I'm still battling imports, but seem to be past this one.
{
    a = Analysis(['/Users/Ben/Documents/DeepMeerkat/DeepMeerkat/main.py'],
                 pathex=['/Users/ben/Documents/DeepMeerkat/DeepMeerkat/'],
                 binaries=[],
                 datas=[],
                 hiddenimports=['setuptools.msvc'],
                 hookspath=[],
                 runtime_hooks=[],
                 excludes=[ 'enchant', 'twisted'],
                 win_no_prefer_redirects=False,
                 win_private_assemblies=False,
                 cipher=block_cipher)
}

A: This problem was solved by using the dev version of Pyinstaller. More details here: https://github.com/pyinstaller/pyinstaller/issues/2824


text:
Q: Are mysql_query commands executed in a top->bottom fashion as a .php file is executed? I am attempting to build a progress bar loaded for a long running page (yes indexes are obvious solution but currently the dataset/schema prohibits partitioning/proper indexing) so I plan to use a GUID/uniqueID within the query comment to track progess with SHOW_FULL_PROCESSLIST via ajax - but the key to this rests on if the sequential queries are executed in order by php, does anyone know?

A: MySQL as a database server uses multiple threads to handle multiple running queries. It allocates a thread as and when it received a query from a client i.e. a PHP connection or ODBC connection etc.
However, since you mentioned mysql_query I think there can be 2 things in your mind:

*

*if you call mysql_query() multiple times to pass various commands, then MySQL will be passed each query after the previous query is completely executed and the result returned to PHP. So, of course MySQL will seem to then work sequentially although it is actually PHP that is waiting to send MySQL a query till one query is finished.

*In MySQL5 and PHP5 there is a function called  (mysqli_multi_query()) using which you can pass multiple queries at once to MySQL without PHP waiting for 1 query to end. The function will return all results at once in the same result object. MySQL will actually run all the queries at once using multiple threads and the wait time in this case is substantially less and you also tend to use the server resources available much better as all the queries will run as separate threads.

A: As Babbage once said, "I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question." Calls to mysql_query, like calls to any other function, execute in the order that they are reached in program flow.

A: Order in the file is mostly irrelevant. It's order of execution that matters.
<?php

    myCmdFour();
    myCmdTwo();
    myCmdThree();
    myCmdTwo();

    function myCmdTwo() {
        mysql_query(...);
    }

    function myCmdThree() {
        mysql_query(...);
    }

    function myCmdFour() {
        mysql_query(...);
    }

    myCmdFour();
    myCmdThree();
    myCmdTwo();
    myCmdTwo();
?>

Although anyone that has PHP files that look like that, needs to seriously rethink things.


text:
Q: Gulp watch runs once then fails I have a project using Gulp and SASS and when I run gulp watch it runs the first change successfully without any issues.
The problem occurs when I make any further changes - they seem to not register and are seemingly ignored.
Here is my Gulpfile.js code:
var theme_name = 'project-theme';

var gulp    = require('gulp'),
    cleanCSS = require('gulp-clean-css'),
    sass    = require('gulp-sass'),
    concat  = require('gulp-concat'),
    uglify  = require('gulp-uglify'),
    rename  = require('gulp-rename');

var paths = {
  styles: {
    src: 'wp-content/themes/' + theme_name + '/gulp/sass/theme.scss',
    folder: 'wp-content/themes/' + theme_name + '/gulp/sass/*.scss',
    dest: 'wp-content/themes/' + theme_name + '/assets/css/'
  },
  scripts: {
    src: 'wp-content/themes/' + theme_name + '/gulp/jquery/*.js',
    dest: 'wp-content/themes/' + theme_name + '/assets/js/'
  }
};

gulp.task('styles', function() {
  return gulp
    .src(paths.styles.src, {
      sourcemaps: true
    })
    .pipe(sass())
    .pipe(cleanCSS())
    .pipe(rename({
      basename: 'main',
      suffix: '.min'
      }))
    .pipe(gulp.dest(paths.styles.dest));
});

gulp.task('scripts', function() {
  return gulp
    .src(paths.scripts.src, {
        sourcemaps: true
    })
    .pipe(uglify())
    .pipe(concat('main.min.js'))
    .pipe(gulp.dest(paths.scripts.dest));
});

gulp.task('watch', function() {
  gulp.watch(paths.scripts.src, gulp.series('scripts'));
  gulp.watch(paths.styles.folder, gulp.series('styles'));
});

gulp.task('default', gulp.parallel('styles', 'scripts', 'watch'));

I've looked at other similar questions on Stack Overflow and they've not provided me with any success. Any help will be appreciated.

A: I've found a solution. What I now understand is that Gulp does not know that the task is finished, therefore ignoring all further changes.
In order to fix this I changed Line 48 & 49 to this:
gulp.watch(paths.styles.folder).on('change',gulp.series('styles'));
gulp.watch(paths.scripts.src).on('change', gulp.series('scripts'));

All additional changes are now registered by gulp watch.
Hope this helps anyone with a similar issue.


text:
Q: ARRAY_AGG() grouped by another column's values Here's my table like below
p_no  type  name  value
------------------------
1     A     Tomy  1
1     A     Nick  2
1     B     Tomy  3
1     B     Nick  4
1     C     Tomy  5
1     C     Nick  4
2     A     Tomy  8
2     A     Nick  7
2     B     Tomy  5
2     B     Nick  4

It means each p_no represents a block that records poeple's value in both A, B, C type (might be more types).
I want to select a person with his value of all types
Given p_no=1, name=Tomy
A    B    C    D
------------------
1    3    5    ..

I have tried
SELECT p_no, t[1] A, t[2] B/*, t[3] C.....*/
FROM (
    SELECT p_no, ARRAY_AGG(type) FILTER (WHERE name='Tomy') t
    FROM type
    GROUP BY 1
    ORDER BY 1) _unused

but it cannnot make the ARRAY_AGG() include the value
I think I need something similar to ARRAY_AGG('value' GROUP BY 'type')
Is this kind of query possible or is there any better alternatives?

A: Your intuition is right. You want to aggregate value ordered by type, so:
select p_no, t[1] as "A", t[2] as "B", t[3] as "C"
from (
    select p_no, array_agg(value order by type) as t
    from my_table
    where name = 'Tomy'
    group by p_no
    ) s

db<>fiddle.


text:
Q: allowableValues From a File I might be going about this the wrong way, but is there a way to populate the allowableValues string from a json file?
Every method I've tried in reading from a file/json ends up with me having to call a method like toString(), resulting in a non-constant result.  Swagger won't allow non-constant allowableValues, but it seems silly to me that I would have to manually update this list programmatically rather than in an external file in order to add to this list.
I suspect there isn't a compile time strategy that would work here, but just thought I would ask.  Any suggestions would be greatly appreciated!
@ApiOperation(value = "Retrieve information")
@RequestMapping(value={"dothis/thing"}, method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
@Produces({"application/json", "application/xml"})
public JsonNode applicationList(HttpServletRequest request,
                                       @ApiParam(name="input_name", value="Input Name", allowableValues = LIST_OF_VALUES) @RequestParam (required = false) String input_name) throws GeneralException {


text:
Q: array_combine() merge common items I want each item as a key=>value and do not want to merge/combine common item using array_combine().
I want to combine foreach return value in key=>value and here is the result
foreach ($users_in_groups as $get_uid)
{
    $uid[] = $get_uid->user_id;
    $gnm[] = $get_uid->name;
}

Result for $uid
Array
(
    [0] => 2
    [1] => 3
    [2] => 1
    [3] => 1
    [4] => 1
    [5] => 1
)

Result for $gnm
Array
(
    [0] => member
    [1] => member
    [2] => system_admin
    [3] => admin
    [4] => TRA
    [5] => member
)

Combining as key=>value
array_combine($uid, $gnm);

Which is giving below result
Array
(
    [2] => member
    [3] => member
    [1] => member
)

Which is not what I want.
I want as below
Array
(
    [2] => member
    [3] => member
    [1] => system_admin
    [1] => admin
    [1] => TRA
    [1] => member
)

Please notice the userid as key and not combining like the current result.

A: In PHP, each array key must be a unique. This is not a valid PHP array because it has multiple keys that are the same (multiple instances of 1 as the key):
Array
(
    [2] => member
    [3] => member
    [1] => system_admin
    [1] => admin
    [1] => TRA
    [1] => member
)

You can test this by manually creating an array with multiple keys that are the same:
$c = array(
    1 => 'a',
    3 => 'b',
    3 => 'c',
);
print_r($c);

In PHP 5.5, this results in:
Array
(
    [1] => a
    [3] => c
)

What you should aim for is maybe (depending on your needs) an array like this:
array(
    2 => array('member'),
    3 => array('member'),
    1 => array('system_admin', 'admin', 'TRA', 'member'),
);

If that is what you need, you can use the following:
$uid = array(2, 3, 1, 1, 1, 1);
$gnm = array('member', 'member', 'system_admin', 'admin', 'TRA', 'member');
$result = array();
foreach($uid as $k => $u) {
    if (!isset($result[$u])) {
        $result[$u] = array();
    }
    $result[$u][] = $gnm[$k];
}
print_r($result);


text:
Q: why does listing the actual constructor of a class in javascript important I was reading on javascript garden http://bonsaiden.github.com/JavaScript-Garden/  about prototype in javascript and one of its example goes like this:
function Foo() {
    this.value = 42;
}
Foo.prototype = {
    method: function() {}
};

function Bar() {}

// Set Bar's prototype to a new instance of Foo
Bar.prototype = new Foo();
Bar.prototype.foo = 'Hello World';

// Make sure to list Bar as the actual constructor <-------------------
Bar.prototype.constructor = Bar;

Notice the line that reads Make sure to list Bar as the actual constructor. I really am lost about what this does/is. I have tried making new instances of Bar() with and without the last line. But call "value" or "method" on those instances return the exact same things. So I wonder, what's the need (I assume there must be one) of specifying the constructor?
Thank You!!!

A: Every function has a prototype property, it's assigned when the function object is created, it points to a newly created object that inherits from Object.prototype, and it has a constructor property, that simply points back to the function itself.
The purpose of the prototype property is to give a way to implement inheritance, using constructor functions. When you call a function with the new operator, it will create a new object that inherits from that constructor's prototype.
Now, the purpose of the constructor property is to have a way to refer back to the constructor that has created an object, for example:
function Foo () {}
// default value of the property:
Foo.prototype.constructor == Foo; // true

This property is inherited by the "instances" of Foo, so you can know which constructor was used to create an object:
var foo = new Foo();
foo.constructor == Foo;

If you assign a new object to the function's prototype, this relationship is lost:
function Bar () {}
Bar.prototype = { inherited: 1 };

Bar.prototype.constructor == Bar;    // false
Bar.prototype.constructor == Object; // true

And it affects also the instances of the function:
var bar = new Bar();
bar.constructor == Bar;    // false
bar.constructor == Object; // true

Another similar case is when you have two or more levels of inheritance using constructors, the most common way is used to denote the inheritance relationship between the functions, is to assign the prototype property of the second level, e.g.:
function Parent() {}

function Child () {}
Child.prototype = new Parent();

The above code has several problems, first, it executes the logic of the parent constructor to create the inheritance relationship, but that's another story, in the above example the constructor property is also affected, since we replace completely the Child.prototype object:
var child = new Child();
child.constructor == Parent; // true

If we replace replace the value of the constructor property of Child.prototype after assigning it, it will show the expected behavior:
function Child() {}
Child.prototype = new Parent();
Child.prototype.constructor = Child;

var child = new Child();
child.constructor == Child; // true

A: I believe this has to do with instantiating Bar with the new keyword. I believe using new will look for Bar.prototype.constructor. Before that line the object linked to Bar.prototype.contructor is of type Foo so when instantiated without that line it will make a Foo object instead of a Bar object.


text:
Q: VBA references in exe I recently made an Excel-tool, which makes heavy use of VBA macros.
This tool works perfectly on my pc, and on most of my colleagues pc's, but I noticed that it doesn't work on some other pc's. This is because some of the required reference files are not present on those pc's.
I would like to solve this by making an exe-file of the original Excel document, in which all the referenced files are included. I already tried this with Winrar, but I noticed that, after unpacking the exe, the reference files are unpacked in the folder in which the exe file was copied, but not in the required system folders.
How can I fix this, so that I can use the tool on whichever computer I'd like to?
Thanks in advance!
Kind regards,
Marc

A: Michael Todd's comment about licensing is something worth checking up, but assuming that's ok, you could just write a simple batch file and/or script to first unrar the files and then copy them into the relevant directories. This script would preferably be executed during installation of your excel document.
However, depending on what files they are I'd would be wary of copying them into system directories. Firstly, will you have permissions to write to those directories? Secondly, is it possible that you'll overwrite other versions of those dlls, possibly overwriting a newer version with an older version. Depending on what DLLs you're trying to copy, you might break other applications or even Windows itself by copying them in.
In general, if the solution to your problem is to copy random dlls from your machine to someone else's machine, you should look for an alternative solution. I'd suggest that the better solution might be to change your application to not reference those dlls, or if that can't be done, do a proper install of the application where those dlls come from on the machines where you have the problem .

A:
Just to be sure:
Winrar shows something like this:

and you should be selecting either "Store full paths" (better) or "Store full paths including drive letter" (worse)

A: I highly recommend you try Inno Setup.  It has a higher initial learning curve, but it is well worth it for the enhanced functionality over WinRAR (for this type of thing).  Inno-Setup creates installers from plain-text setup files, however, the "Quick Start Pack" includes a GUI front-end for making this part easier.


text:
Q: minimal initramfs (with root on LVM) Is it possible to trim the initramfs by excluding the udev hook when root is on an LVM?
LVM2 installations guide(for LVM) from arch wiki sites udev and lvm2 as the the two hooks necessary.
I have managed to trim down my mkinitcpio.conf to:
#MODULES=()

BINARIES=(fsck fsck.btrfs btrfsck)

HOOKS=(base udev lvm2)

following this guide.
If i remove either udev or lvm2 from here, it breaks, the error message is something to the line
can't find /dev/linux/arch`

which is basically a device mapper mapping path.
What i wanted to know is, can i further trim it down and remove the udev hook? is there any way that makes it possible ?  The guides i have seen/read so far are generic and (systems without LVM).
Output of lsinitcpio:
❯ lsinitcpio -a /boot/initramfs-linux-clear.img
==> Image: /boot/initramfs-linux-clear.img
==> Created with mkinitcpio 30
==> Kernel: 5.9.16-1-clear
==> Size: 47.1 MiB

==> Included modules:
  dm-bio-prison           dm-cache                dm-log                  dm-persistent-data      dm-snapshot
  dm-bufio                dm-cache-smq            dm-mirror               dm-region-hash          dm-thin-pool

==> Included binaries:
  blkid                   dmsetup                 journalctl              modprobe                sulogin                 systemd-tmpfiles
  btrfsck                 fsck                    kmod                    mount                   switch_root             udevadm
  busybox                 fsck.btrfs              lvm                     pdata_tools             systemctl               umount

Things i tried so far:

*

*Get the list necessary modules required by adding the
break=postmount boot option to the fallback image and doing
'lsmod | awk 'NF==3{print $1}'. Adding those in the MODULES array.

*Adding all the modules as listed under Included Modules from the
output of lsinitcpio (e.g  dm-bio-prison,dm-cache,dm-log etc).
NOTE: i know that the systemd hook can replace the udev hook but that's not what looking for. I want it reduced to just the base and lvm2(if necessary).


text:
Q: Spring Data JPA : externalize to a property file the @EnableJpaRepositories basePackages configuration I wanted to externalize the configuration for @EnableJPARepositories basePackages.
I have two different sample packages below

*

*com.project.ph.dao

*sample.project.jpa.repositories

I tried property externalization below (not working for multiple packages)
ProjectConfig.class
@EnableJpaRepositories(basePackages = {"${basePackages}"})

config.properties
basePackages=com.project.ph.dao,sample.project.jpa.repositories

Is there any other way to externalize this configuration for multiple packages?
Thanks!

A: No, you can't use SPEL inside the @EnableJpaRepositories annotation. Reason being that the annotation might exist on a configuration bean with additional property sources defined that could override the properties used in the annotation, so you'd have a chicken and egg scenario trying to load the beans. But you can still solve your problem using Spring's configuration mechanisms.
With Spring Boot
Instead of declaring all of the packages in a single class, create two or more @Configuration beans that are enabled based on properties using the @ConditionalOnProperty annotation from Spring Boot, e.g.:
@Configuration
@EnableJpaRepositories(basePackages = "com.project.ph.dao")
@ConditionalOnProperty("com.project.ph.dao.enabled")
public class PhProjectRepostoriesConfiguration {
}

And then another:
@Configuration
@EnableJpaRepositories(basePackages = "sample.project.jpa.repositories")
@ConditionalOnProperty("sample.project.jpa.repositories.enabled")
public class SampleProjectRepostoriesConfiguration {
}

Then in your application.properties file:
sample.project.jpa.repositories.enabled=true
com.project.ph.dao.enabled=false

Without Spring Boot
This is similar, except instead of using @ConditionalOnProperty, you'll just use @Conditional. This requires you to implement a Condition class that will check the properties instead.
Additional Notes
When using the @EnableJpaRepositories annotation, the default basePackages will be the package of the annotated class, so you could also drop these @Configuration beans into the com.project.ph.dao and sample.project.jpa.repositories packages and remove the basePackages declaration from the annotation. You'll still need the rest of the annotations, but it's one less hard-coded value to manage.
References

*

*@ConditionalOnProperty Javadoc (docs.spring.io)

*@Conditional Javadoc (docs.spring.io)

*Condition Javadoc (docs.spring.io)

*Spring Auto-Configuration Documentation (docs.spring.io)

*@EnableJpaRepositories usage documentation (docs.spring.io)

*Additional information when working with multiple DataSource objects (stackoverflow.com)


text:
Q: How to create an event stream on MySQL Given the following InnoDB table:
event_stream
+ id BIGINT PRIMARY AUTO-INCREMENT
+ event TEXT

Considering that there are several clients concurrently inserting events into this stream: What technique could we use so that this event stream could be processed in an incremental way by multiple listeners/consumers?
(edit) I.E. I would like to have multiple clients attached to this stream that can react to new events once and keep track of their position on the stream.
Considerations:

*

*Not using MySQL to store the events is not an option;

*locking the entire table is not acceptable;

*I want to keep the control of wether an event was already seem/not seem up to the consumer, there might be multiple consumers for this table;

*Creating new columns is acceptable;

*This table will grow to hundreds of millions of events;

A: "Don't queue it, just do it."  I have found that a database makes a poor queuing mechanism.  If the 'worker' threads don't take long to perform the tasks, then have the queuers simply perform the tasks; this removes the overhead of the queue, thereby possibly making the system faster and scale better.
"Hundreds of millions of events" -- and nearly all of them have been "handled"?  This suggests you have two tables -- one for handled events, one for events waiting to be handled.  The latter would rarely have more than a few dozen rows??  In that case, the processing will work better.
Have two extra columns: which worker owns the process, and when the worker grabbed it.  The time is so that you can take care of the case (yes, eventually it will happen) of a worker grabbing a task, then dying -- thereby leaving the task orphaned.  As separate job can 'reap' these orphans.
A single-SQL UPDATE can grab one row in the table.  Do this in a transaction by itself, not in any transaction(s) in the process.  Similarly 'release' the task in its own transaction.
The grab is something like this (with autocommit=ON):
UPDATE ToDo SET who = $me, when = NOW()
    WHERE who IS NULL
    LIMIT 1;   -- grab one
SELECT ... FROM ToDo WHERE who = $me;  -- get details on the task

The 'release' probably involves both tables, something like this:
BEGIN;
$stuff = SELECT ... FROM ToDo WHERE who = $me;
DELETE FROM ToDo WHERE who = $me;
INSERT ... INTO History ... VALUES (most of stuff from $stuff);
COMMIT;

In between grabbing and releasing, you have as long as you need to perform the 'task'.  You won't be tripped up by an InnoDB timeout, etc.
If you would like to give further details about your queue and tasks, I may have further refinements.
What I describe should handle any number inserters, any number of workers, and tasks lasting any length of time.
AUTO_INCREMENT is not reliable for walking through an event list.  An INSERT is multiple steps:

*

*Start transaction

*get next auto_incr id

*do the insert

*COMMIT -- only now do others see the new id

It is possible (especially in replication) for the COMMITs to be "out of order" relative to the auto_incr.


text:
Q: Am I using ThreadPool correctly & performance I have a .net windows service that works it's way through a queue of items and does some research on each one.  I'm trying to change it to a threaded model so that batches items can be researched concurrently rather than doing each item sequentially.
I know this isn't the perfect solution (it currently has to wait for the slowest item to finish being researched before moving on to the next batch).

*

*With the example below have I got the right idea with this when it comes to the threading?

*Admittedly I'm running this on a VM so it may be hampering the performance however I was expecting a bit more of a speed improvement.  Currently I'm seeing about 10% improvement and was hoping that by researching 5 or more side by side it would be lot faster than that (i.e. preferably 1/5 time but surely I should expect at least 50%?).  Besides the limitation with waiting on the slowest item to finish researching have I limited this by the way I've done the locking or something?
static object locker = new Object();
private List<string> currentItems = new List<string>();

private void researcherTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    if(Monitor.TryEnter(locker))
    {
        try
        {
            if (currentItems.Count == 0)
            {
                // get the next x items from the db and adds them to the currentItems list
                SetNextItems();
                if (currentItems.Count > 0)
                {
                    foreach (string item in currentItems)
                    {
                        ThreadPool.QueueUserWorkItem(ResearchInThread, item);
                    }
                }
            }
        }
        finally
        {
            Monitor.Exit(locker);
        }
    }
}

void ResearchInThread(object item)
{
    string currentItem = (string)item;
    try
    {
        // Research Process Here
    }
    finally
    {
        // Remove this item from the current list
        lock (locker)
        {
            currentItems.Remove(currentItem);
        }
    }
}

A: The performance gain depends much on your hardware (do you have multi core?) and on the algorithm that you are executing in parallel.
If the algorithm is close to 100% CPU bound (e.g. only doing raw calculations on data in memory) and you are running on a single core machine then, sadly, you won't see much improvement by running it in multiple threads.
On the other hand, such an algorithm would gain almost linear performance increase if you run on multiple cores.
If your algorithm is both I/O and CPU then you should see a decent performance gain by threading it even on a single core machine. How much gain depends on so many factors that I won't even put a number here :)
Regarding your code, I would recommend you create one big queue of "jobs" (your item object) and then spawn a certain number of threads that pulls jobs from this queue until it's empty. The threads would run until they see that the queue is empty. This way, you won't have to wait for the slowest worker before releasing the next batch. This should help with the overall performance gain.
Just make sure the queue is protected by a lock mechanism when dequeueing so that you don't run into race conditions.

A: A possible performance enhancement would be to use the System.Threading.Timer and the TimerCallback delegate instead as System.Timer can be affected by the system performance i.e. if the system is busy the Timer may not always trigger on time.

A: You have left out the main part of the code. How the timer function gets called "researcherTimer_Elapsed".
Under which conditions does the time elapse.
Can you please add some more code to the example to show the conditons under which the function could be called.


text:
Q: Add to cart button for Shopify Hi I have a configurable product that can come in 1000's of options. I know you can send data in a form like this to the cart:
<form action="http://your.shopify.url/cart/add" method="post">
<input type="hidden" name="id" value="VARIANT-ID" />
<input type="hidden" name="return_to" value="back" />
<input type="submit" value="BUY NOW" />
</form>

But instead of
<input type="hidden" name="id" value="VARIANT-ID" />

I would like to add the fields:
<input type="hidden" name="price" value="300" />
<input type="hidden" name="info" value="Bird fabric with black wood" />
<input type="hidden" name="image" value="imageOfProduct.png" />

and send this information to the cart. Can this be done? If not is there a way to do this?
Thanks!
Update:
May be I'm missing something or maybe my question was not clear.
I have this code (a buy button) on my web page just plain HTML:
<form action="http://your.shopify.url/cart/add" method="post">
  <input type="hidden" name="id" value="VARIANT-ID" />
  <input type="hidden" name="price" value="300" />
  <input type="hidden" name="info" value="Bird fabric with black wood" />
  <input type="hidden" name="image" value="imageOfProduct.png" />
  <input type="hidden" name="return_to" value="back" />
  <input type="submit" value="BUY NOW" />
</form>

You say to make it work I should add to the product.liquid page:
  <input type="hidden" name="properties[price]" id="price" value="300" />
  <input type="hidden" name="properties[info]" id="info" value="Bird fabric with black wood" />
  <input type="hidden" name="properties[image]" id="image" value="image.png" />

I'm fairly sure the value should not be on the product.liquid page?
Thanks for your help!

A: Open product.liquid and after <form action="http://your.shopify.url/cart/add" method="post"> but before the submit button
add
<input type="hidden" name="properties[price]" id="price" value="300" />
<input type="hidden" name="properties[info]" id="info" value="Bird fabric with black wood" />

A: This will be your button
<form action="http://yoururl.myshopify.com/cart/add" method="post" target="_parent">
  <input type="hidden" name="id" value="3569079681" />
  <input type="hidden" name="properties[URL]" value="http://" />
  <input type="hidden" name="properties[Image]" value="image.png" />
  <input type="hidden" name="properties[Fabric]" value="3569079681" />
  <input type="image" src="../img/design/cart.png" border="0" name="submit">
</form>

Then in the Shopify backend find "cart.liquid"
And paste this here: Where you place this snippet depends on your theme, but it needs to go inside the loop for cart.items and you'll likely want to place it right under the cart item's title.
{% for p in item.properties %}
  {% unless p.last == blank %}
    {{ p.first }}:
    {% if p.last contains '/uploads/' %}
    {{ p.last | split: '/' | last }}
    {% else %}
    {{ p.last }}
    {% endif %}

  {% endunless %}
{% endfor %}

For more info: https://docs.shopify.com/support/your-store/products/how-do-I-collect-additional-information-on-the-product-page-Like-for-a-monogram-engraving-or-customization


text:
Q: Do I really need to synchronize on SurfaceHolder in a rendering loop of a live wallpaper I'm implementing a rendering loop for my live wallpaper in Android. All of the examples I found on the Internet contain a rendering loop like this:
public void run() {
    while (mRunning) {
        Canvas c = null;
        try {
            c = mSurfaceHolder.lockCanvas(null);
            synchronized (mSurfaceHolder) {
                doUpdate();
                doDraw(c);
            }
        } finally {
            if (c != null) {
                mSurfaceHolder.unlockCanvasAndPost(c);
            }
        }
    }
}

Do I really need to synchronize on mSurfaceHolder object in a Live Wallpaper?
The question like this has been discussed here earlier, but no exact answer has been given. Also the answer by Jason Nichols here states:

I don't understand why your synchronizing in your rendering loop. This is bad form as it may lock up your rendering thread, causing the app to appear to freeze if it can't acquire the lock immediately for any reason. It also takes time to get acquire the lock.
If you've got your data organized in such a way that you need to get a lock in your rendering thread, you need to refactor your design.

I am really frustrated!
Update
Do I generally need any synchronization in a rendering loop? How much will it affect the rendering loop performance?

A: You don't need to synchronize on mSurfaceHolder. This code was probably taken from Lunar Lander example from SDK and changed so many times over the web that it lost its context. SurfaceHolder had been chosen as the object that provides the intrinsic lock, but as well, any other object could be used.

A: Actually this is quite simple. In most of the examples where synchronize is used, it is because there is a chance that doUpdate() and doDraw() methods would be accessed from more than one thread(Main thread and some helper thread).
However, if you can ensure that those methods will only be accessed from same thread, than there is no need to use synchronize at all.
An easy implementation (and best for performance) would be using a Handler like this:
Handler handler = new Handler(Looper.getMainLooper());

This will bind the handler to the main thread, and all the actions will be only on the main thread.
So use synchronize when you truly want to synchronize something.


text:
Q: Can a material generally score or cut itself by hand? I'm wondering if a given solid material can, in general, score or cut the same material, when applied by (at most) human muscular strength.
I've tried searching for this online, but it seems like a difficult-to-express search target. For example, the site Answers.com has a brief entry:

Q: What mineral can scratch diamonds?
A: The mineral diamond can scratch diamonds.

There's no further elaboration or justification at that site.
My question differs from prior somewhat-related questions on SE Physics, because those answers all end up addressing cases where the cutting material is accelerated to very high (possibly relativistic) speed. The present question is only about whether a limited amount of solid material, hand-held by a person, and applying only normal muscular strength, can generally visibly score or cut the same kind of material, within a few seconds to a minute of time (but assume the cutting material might be sharpened to a high degree).

*

*Is it possible to cut harder material with a less hard material?

*Can a tomato pierce a hole in a steel plate if only the tomato is travelling fast enough?
Is there any general rule for what kind of solid materials can cut themselves in this way?

A: The material quality you're looking for is hardness. The Mohs Hardness Scale is an empirical table of minerals sorted by hardness. Two materials are said to be the same harness if each can scratch the other. A homogeneous or mostly homogeneous solid, like diamond, has an identifiable hardness. A nonhomogeneous solid, like concrete, does not.
A solid-liquid mixture, like a tomato, or a solid-gas mixture, like aerogel, does not. Nonhomogeneous Solid mixtures like concrete will scratch like their hardest component and be scratched like their least hard component. Solid-liquid and solid-gas mixtures may also crush, tear, or burst, unrelated to scratching.
So: if an object has a well-defined hardness, it can scratch itself because it has the same hardness as itself. And an object has a well-defined hardness if it is a homogenous solid.