text:
Q: Change MinionPro Math fonts I have installed MinionPro.sty and like the text part of the font very much for my thesis. I do not like the numbers though since they disturb readability when there are many numbers in the text. So I tried
\usepackage[onlytext]{MinionPro}
\usepackage{mathspec}
\setmathfont(Digits,Latin,Greek){Minion Pro}

My platform is Windows, MikTeX 2.9 (x64). I have also installed "Minion Pro" in C:\Windows\Fonts. When I try compiling in XeLaTeX, I get the following errors:
Undefined control sequence. \setmathfont(Digits,Latin,Greek){Minion Pro}
Missing \begin{document}. \setmathfont(Digits,Latin,Greek){Minion Pro}
Undefined control sequence. \setmathfont(Digits,Latin,Greek){Minion Pro}
Undefined control sequence. \setmathfont(Digits,Latin,Greek){Minion Pro}
Package mathspec Error: `amsmath' must be loaded earlier than 'mathspec'. \RequirePackage{amsmath}

So I compromised and tried Arno Pro for text and MinionPro for math as mentioned here in LuaLaTeX. Installed Arno Pro into Windows fonts.
\usepackage[minionint,mathlf,onlymath]{MinionPro}
\usepackage{fontspec}
\setmainfont[UprightFont=ArnoPro-Regular,
BoldFont=ArnoPro-Bold,
ItalicFont=ArnoPro-Italic,
BoldItalicFont=ArnoPro-BoldItalic,
Numbers={Proportional}]{Arno Pro}

No luck. First two errors with LuaLaTeX are
Undefined control sequence. Numbers={Proportional}]{Arno Pro}
Missing \begin{document}. Numbers={Proportional}]{Arno Pro}

EDIT: Complete main.tex file below
\newif\iflayoutversion
% \layoutversiontrue
\layoutversionfalse

\documentclass[11pt]{book}

\usepackage[dutch,english]{babel}
\usepackage{type1cm}
\usepackage{sty/fncychapleo}
\usepackage[vcentering,dvips]{geometry}

\iflayoutversion
    \geometry{papersize={170mm,240mm},total={135mm,165mm}}
    % \usepackage[a4,cam,center]{crop}
    % \crop[font=\upshape\mdseries\small\textsf]
\else
    \geometry{papersize={210mm,297mm},total={165mm,235mm}}
\fi

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
%% Now begin customising things. See the fancyhdr docs for more info.
\renewcommand{\chaptermark}[1]{\markboth{Chapter \thechapter. {#1}}{}}
\renewcommand{\sectionmark}[1]{\markright{\thesection~{#1}}{}}
\renewcommand{\headrulewidth}{0.5pt}

\usepackage{graphicx}
\DeclareGraphicsExtensions{.eps, .jpg, .jpeg, .png}

\usepackage{enumerate}
\usepackage{tabularx}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{balance}
\usepackage{subfig}
\usepackage{url}
\usepackage{psfrag}
\usepackage{todonotes}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{algorithmicx}
\usepackage{amsthm}
\usepackage{url}
\usepackage[toc,page]{appendix}

\graphicspath{{./fig/}}
\newtheorem{theorem}{Theorem}
\newtheorem{lemma}{Lemma}

\usepackage[onlytext]{MinionPro}
\usepackage{mathspec}
%\setmainfont{Minion Pro}
\setmathsfont(Digits,Greek)[Numbers={Proportional}]{Minion Pro}
%\setmathfont[range=\mathit]{Minion Pro Italic}

%\usepackage[minionint,mathlf,onlymath]{MinionPro}
%\usepackage{fontspec}
%\setmainfont{MinionPro}[
%Extension = .otf,
%Path = ./fonts/,
%UprightFont = *-Regular,
%BoldFont = *-Bold,
%ItalicFont = *-It,
%BoldItalicFont = *-BoldIt,
%Numbers={Proportional}]

\usepackage[acronym,toc]{glossaries}

\algrenewcommand{\algorithmiccomment}[1]{\hskip3em// #1}

\include{title}

\begin{document}
\input{front-matter}

\fancyhead[LE]{\thepage}
\fancyhead[RE]{\leftmark}
\fancyhead[RO]{\thepage}
\fancyhead[LO]{\rightmark}

%\fancyhead[RO]{{\footnotesize\rightmark}\hspace{2em}\thepage}

\include{chap1/chap}

\graphicspath{{./fig/chap6/}}
\include{chap6/chap}

\begin{appendices}
\include{apndx1/chap}
\end{appendices}

\bibliographystyle{IEEEtran}
\small
\bibliography{IEEEabrv,references}

\end{document}

A: You have several options to use Minion Pro in LaTeX.

*

*Use the mathspec package with XeLaTeX to load the OpenType text font as provided by Adobe Illustrator or Typekit.
\usepackage{mathspec}
\setmainfont{Minion Pro}
\setmathsfont(Digits,Greek,Latin)[Numbers={Proportional}]{Minion Pro}
\setmathrm{Minion Pro}

*Use the unicode-math package with XeLaTeX or LuaLaTeX (recommended) and load the OpenType text font as the text font and the commercial MinionMath as the math font.
\usepackage{unicode-math}
\setmainfont{Minion Pro}
\setmathfont{MinionMath-Regular.otf}

*Convert the OpenType fonts for use with pdfLaTeX following these instructions and use the package.
\usepackage[minionint,mathlf]{MinionPro}

For the sake of completeness here is the full MWE:
\documentclass{article}

%% XeLaTeX solution
\usepackage{mathspec}
\setmainfont{Minion Pro}
\setmathsfont(Digits,Greek,Latin)[Numbers={Proportional}]{Minion Pro}
\setmathrm{Minion Pro}

%% Better XeLaTeX/LuaLaTeX solution,
%% but requires commercial MinionMath
%\usepackage{unicode-math}
%\setmainfont{Minion Pro}
%\setmathfont{MinionMath-Regular.otf}

%% pdfLaTeX solution
%\usepackage[minionint,mathlf]{MinionPro}

\begin{document}
Lorem ipsum dolor sit amet
\[ \int_0^\infty e^{-\alpha x^2} \mathrm{d}x =
            \frac12\sqrt{\int_{-\infty}^\infty e^{-\alpha x^2}}
            \mathrm{d}x\int_{-\infty}^\infty e^{-\alpha y^2}\mathrm{d}y =
            \frac12\sqrt{\frac{\pi}{\alpha}} \]
\end{document}


text:
Q: How to stop ldapsearch(1) from base64 encoding userPassword and other attributes? The ldapsearch(1) command retrieves objects from an LDAP server, and prints them out as an LDIF structure, like this (not real data):
dn: mail=foo@domain.com,dc=domain,dc=com
objectclass: top
objectclass: person
mail: foo@domain.com
userPassword:: hdfy74dhn79wdhyr74hy7489fhw46789f

If an attribute contains non-ASCII data, it is Base64-encoded, indicated by a double :: after the attribute name.  In addition, it appears that any attribute called userPassword will always be so encoded, even if it is ASCII-clean.
What I want to do is to tell ldapsearch not to do this.  I have not been able to find an option flag to pass to suppress this behaviour; only recompiling the source with LDAP_PASSWD_DEBUG disabled.
Is there an undocumented option to prevent this encoding?
(Leaving aside security concerns etc. as this is for testing purposes)

A: Short of recompiling ldapsearch, there seems to be no way to do this with a simple flag.
However you can create a shell alias like this, which will have the same effect - provided you have the Perl MIME::Base64 module installed.
myldapsearch()
{
ldapsearch $* | perl -MMIME::Base64 -n -00 -e 's/\n +//g;s/(?<=:: )(\S+)/decode_base64($1)/eg;print'
}
alias ldapsearch=myldapsearch

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS3 re-size page according to screen size / display how can i get my page to align to fit into any any screen size, for example, take a look at this link for a better understanding https://dl.dropbox.com/u/8542058/Photo%20Jul%2012%2C%209%2056%2026.png
if you notice, on the link above, once the screen is adjusted, the image on the screen adjust it self and take the shape of the screen accordingly. now i want to do the same to my page, my demo page can be found on http://jsfiddle.net/529Lk/show/, and the codes are http://jsfiddle.net/529Lk/. thanks
for easy view my codes are still here:
CSS3:
body{
font-family: Arial, "MS Trebuchet", sans-serif;
color:#000;
background:#088A08;
font-weight: bold;
margin:auto;
}
/* SLIDE Start */

input[id=slideThree] {
visibility: hidden;
}

/* SLIDE THREE */
.slideThree {
width: 120px;
height: 45px;
background: #0101DF;

-webkit-border-radius: 30px;
-moz-border-radius: 30px;
border-radius: 30px;
position: relative;

-webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);
-moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);
box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);
    position:relative; left:450px;
}

.slideThree:after {
content: 'OFF';
font: 19px/26px Arial, sans-serif;
color: #fff;
position: absolute;
right: 10px;
z-index: 0;
font-weight: bold;
text-shadow: 1px 1px 0px rgba(255,255,255,.15);
}

 .slideThree:before {
content: 'ON';
font: 19px/26px Arial, sans-serif;
color: #fff;
position: absolute;
left: 10px;
z-index: 0;
font-weight: bold;
}

.slideThree label {
display: block;
width: 50px;
height: 40px;

-webkit-border-radius: 50px;
-moz-border-radius: 50px;
border-radius: 50px;

-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
-o-transition: all .4s ease;
-ms-transition: all .4s ease;
transition: all .10s ease;
cursor: pointer;
position: absolute;
top: 3px;
left: 3px;
z-index: 1;

-webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);
-moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);
box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);
background: #fcfff4;
background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4',   endColorstr='#b3bead',GradientType=0 );
}

.slideThree input[type=checkbox]:checked + label {
left: 68px;
}

.back { width:598; height:95px;  background:url('http://i1159.photobucket.com/albums/p637/Apulo_Cosmas/btn_push01c2x.png') no-repeat;      }

HTML:

<input type="checkbox" value="None" id="slideThree" name="check" />

A: If you mean If I were to shrink the browser, it would still fit? That is what you would call a fluid-width style. This can be done by using percentages on widths.
On the other hand, if you want to apply separate styles to your page depending on the screen resolution, then you can use media queries: http://webdesignerwall.com/tutorials/css3-media-queries


text:
Q: Android Переключение между фрагментами Здравствуйте.
Подскажите как сделать переключение между фрагментами. Есть 3 фрагмента. на которых размещены кнопки. Как через кнопки сделать переключение между фрагментами?
Код activity(Задаю фрагменты):
public class MainActivity extends FragmentActivity {
/** идентификатор первого фрагмента. */
public static final int FRAGMENT_ONE = 0;
/** идентификатор второго. */
public static final int FRAGMENT_TWO = 1;
/** идентификатор третего. */
public static final int FRAGMENT_THREE = 2;
/** количество фрагментов. */
public static final int FRAGMENTS = 3;
/** адаптер фрагментов. */
private FragmentPagerAdapter _fragmentPagerAdapter;
/** список фрагментов для отображения. */
private final List<Fragment> _fragments = new ArrayList<Fragment>();
/** сам ViewPager который будет все это отображать. */
private ViewPager _viewPager;

@Override
protected void onCreate(final Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // создаем фрагменты.
    _fragments.add(FRAGMENT_ONE, new FirstFragment());
    _fragments.add(FRAGMENT_TWO, new SecondFragment());
    _fragments.add(FRAGMENT_THREE, new TherdFragment());

.....
В классе фрагмента на котором расположена кнопка пишу переход на другой фрагмент:
public class SecondFragment extends android.support.v4.app.Fragment {
private Context context;

Fragment fragment1;

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //задаем разметку фрагменту
    final View view = inflater.inflate(R.layout.second, container, false);
    //ну и контекст, так как фрагменты не содержат собственного
    context = view.getContext();

    fragment1 = new FirstFragment();

    //Knopka 1
    Button button1 = (Button) view.findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.pager, fragment1);
            transaction.commit();
        }
    });

}
В итоге происходит переход на пустой фрагмент.

A: как я понял вам нужно переключать текущую страницу ViewPager. для этого у MainActivity дописываем метод
public void setPage(int page) {
    _viewPager.setCurrentItem(page, true); //второй параметр для плавного перелистывания
}

и перелистываем страницу из фрагмента:
((MainActivity) getActivity).setPage(MainActivity.FRAGMENT_ONE);


text:
Q: jQuery undocumented function? right click on an element :  ( no using plugins)
I saw an answer like this :
$('#hello').bind("contextmenu",function(e){    //contextmenu ??
   alert('Right Clickz');
   return false;
});

I've searched all jquery site and didnt find the contextmenu function.
where is it documented ?

A: the bind() method takes the name of a DOM event which is any event supported by the DOM tree jQuery is running with, including your own custom events. All events for all browsers are not documented and all events will not exist in all browsers.
See the documentation here: http://api.jquery.com/bind/
Some of the events have shortcuts and probably works in the majority of browsers.
For more possible DOM events google for "dom event list".

A: This site shows what browsers and objects the event is available on (almost all):
http://www.quirksmode.org/dom/events/contextmenu.html

The contextmenu event fires when the user calls the context menu by right-clicking.

This handy demo page shows it in action:
http://www.quirksmode.org/dom/events/tests/contextmenu.html


text:
Q: The connection to the server localhost:8080 was refused. Did you specify the right host? While installing kubectl on Ubuntu 22.04 i got this error message. Is there any solutions for this problem please !!
I tried to reinstall it


text:
Q: disable button when textfields are empty hi im a beginner to programming and have been stuck on this task for ages and seem to be getting nowhere.
basically i have several textfields that generates the input information on a different page when the user presses a button. i would like the button to be disabled until all text fields are filled with information.
so far i have this:
    - (void)textFieldDidEndEditing:(UITextField *)textField
{
    // make sure all fields are have something in them

if ((textfbookauthor.text.length  > 0)&& (textfbookedition.text.length > 0)&& (textfbookplace.text.length > 0)&& (textfbookpublisher.text.length > 0) && (textfbookpublisher.text.length > 0) && (textfbooktitle.text.length > 0)  && (textfbookyear.text.length > 0)) {
        self.submitButton.enabled = YES;
    }
    else {
        self.submitButton.enabled = NO;
    }
}

the problem is the 'submitButton' is coming up with an error, what needs to go in its place?
i tried to put my button 'bookbutton'in it instead but its not working.
this is my function for the 'generate' button
    -(IBAction)bookbutton:(id)sender;
{
    NSString* combinedString = [NSString stringWithFormat:
                                @"%@ %@ %@.%@.%@:%@.",
                                textfbookauthor.text,
                                textfbookyear.text,
                                textfbooktitle.text,
                                textfbookedition.text,
                                textfbookplace.text,
                                textfbookpublisher.text];
    BookGenerate*bookg = [[BookGenerate alloc] init];
    bookg.message = combinedString;
    bookg.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:bookg animated:YES];
    [BookGenerate release];
}

if anybody knows how i can make it work or what i need to add please help.
thanks in advance

A: If you have a button and you want to enable it only if there is a text in a textfield or textview, implement the follow method
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (textView.text.length > 1 || (text.length > 0 && ![text isEqualToString:@""]))
    {
        self.button.enabled = YES;
    }
    else
    {
        self.button.enabled = NO;
    }

    return YES;
}

A: Make an Outlet for every UITextField and create an IBAction in your .h:
IBOutlet UITextField *textField1;
IBOutlet UITextField *textField2;
IBOutlet UITextField *textField3;
IBOutlet UIButton *button

- (IBAction)editingChanged;

Connect all the outlets and connect the IBAction to every textfield with editingChanged:
 - (IBAction)editingChanged {
    if ([textfield1.text length] != 0 && [textfield2.text length] != 0 && [textfield3.text length] != 0) {
         [button setEnabled:YES];
     }
     else {
         [button setEnabled:NO];
     }
 }

Note that you can also use [textfield.text isEqualToString:@""] and put a ! in front of it (!means 'not') to recognize the empty textField, and say 'if the textField is empty do...'
And:
- (void)viewDidLoad {
    [super viewDidLoad];
    [button setEnabled:NO];
}

A: Few solutions are available on these posts as well

*

*Very Similar Query

*A different version of it
Key here is using (extending) UITextFieldDelegate class and it's associated function
//Need to have the ViewController extend UITextFieldDelegate for using this feature
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    // Find out what the text field will be after adding the current edit
    let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

    if !text.isEmpty{//Checking if the input field is not empty
        button.userInteractionEnabled = true //Enabling the button
    } else {
        button.userInteractionEnabled = false //Disabling the button
    }

    // Return true so the text field will be changed
    return true
}

A: You should use" textfield should change chracters in range" (see apple docs for uitextviewdelegate). because it updates as users type information." Textfield did end editing" only fires when the users finishes editing a textfield or hits enter. In most cases, someone will fill in the last field and leave the cursor sitting there and expect the button to become enabled...but that wont happen using "textfield did end editing" just because they entered input.
You can also do this to check the length
if([self.textfiele.text isEqualToString:@""])

A: In addition to having IBOutlets for each UITextField, it might be helpful to have an IBOutletCollection declared that contains all 3 text fields in an array.
@property (nonatomic, retain) IBOutletCollection(UITextField) NSArray *textFields;
Then in your implementation just @synthesize textFields and you can quickly loop the text fields it contains, checking for text.
- (IBAction)editingChanged
{
    BOOL buttonShouldBeEnabled = YES;

    for (UITextField *field in self.textFields)
        if (!field.text.length)
            buttonShouldBeEnabled = NO;

    button.enabled = buttonShouldBeEnabled;
}


text:
Q: ExtJS Tab panel autoLoad not executing the scripts I have a tab panel having three tabs on it and they are using a loader to load different tab contents. All are having autoLoad but only first tab content is shown and other tabs are empty. But i found that all the ajax request are done in firebug but the content won't render.
Here is the code snippet..
Ext.create('Ext.tab.Panel', {
    height: 300,
    renderTo: Ext.getBody(),
    id:'InstrumentEditWindow_tabpanel',
    items: [
      {
          title: 'Instrument details',
          id:'InstrumentEditWindow_instrumentTab',
          loader: {
                loadMask:true,
                url: '?r=instrument',
                single:true,
                autoShow: true,
                renderer: 'html',
                method:'GET',
                autoLoad: true,
                scripts: true
          },
          height:270
      },
      {
          title: 'Weighbridge details',
          id:'InstrumentEditWindow_weighbridgeTab',
          loader: {
                loadMask:true,
                url: '?r=instrument/Default/weighbridge',
                renderer: 'html',
                autoShow: true,
                method:'GET',
                single:true,
                autoLoad: true,
                scripts: true
           },
           height:270
       },
       {
           title: 'Package details',
           id:'InstrumentEditWindow_packageTab',
           loader: {
                 loadMask:true,
                 url: '?r=instrument/Default/package',
                 renderer: 'html',
                 method:'GET',
                 autoShow: true,
                 single:true,
                 autoLoad: true,
                 scripts: true
            },
            height:270
        }
    ]
})


text:
Q: R Shiny MySQL Upload actionButton I am developing a shinydashboard to upload/append some csv files i get on a regular basis to a MySQL database.
The app so far does three things.

*

*allows nominating the csv file to be uploaded.

*allows a text input of a project number that is added as new column to the data.

*an action button to initiate the upload and display the data uploaded.

PROBLEM
The first upload works fine. When I go to upload a second file by browsing or dropping the file, the App uploads the new file before i press the action button and so it will upload before I can change the project number. It will also start a new upload if I make any changes to the text input
The examples files and schema structure are simplified and shown below. Any clues on code I've missed or misused would be appreciated.
test.csv
v1,v2,v3
33,78,44
4,49,15
87,132,98
The database schema is called shiny and the table is named table1 with columns as follows:
id - primary key, auto-increment.
pn - varchar(10).
v1 - varchar(10).
v2 - varchar(10).
v3 - varchar(10).
Shiny code as follows
## app.R ##
library(shiny)
library(shinydashboard)
library(DT)
library(RMySQL)

# Database access information
user = 'root'
password = 'password'
host = 'host'
dbname='shiny'

ui <- dashboardPage(

  dashboardHeader(title = "Shiny SQL Upload App"),

  #### Main Sidebar Menu Items ####
  dashboardSidebar(width = 120,
                   sidebarMenu(
                     menuItem("Upload", tabName = "aa", icon = icon("dashboard")),
                     menuItem("Menu2", tabName = "bb", icon = icon("dashboard")),
                     menuItem("Menu3", tabName = "cc", icon = icon("dashboard")),
                     menuItem("Menu4", tabName = "dd", icon = icon("dashboard"))
                   ) # End sidebarMenu
  ), #End dashboardSidebar

  #### Main Body Content ####
  dashboardBody(
    shinyDashboardThemes(theme = "poor_mans_flatly"),
    tabItems(

      tabItem(tabName = "aa", # Start of Menu Item 1 aa
              fluidRow(
                tabBox(
                  width = 6,
                  id = "tabset1",
                  tabPanel("Up Load File", # Start of 1st subtab to first menu item
                           {
                             sidebarLayout( # Sidebar style for subtab
                               sidebarPanel( # Sidebar panel details and content
                                 width = 7,
                                 fileInput("file1", label = "File input", accept = c(".xlsx", ".xls", ".csv", ".ods")),
                                 textInput("pn", "Project Number or Name", value = "", width = NULL, placeholder = NULL),
                                 actionButton("go", "Upload")
                               ), # End of sidebarPanel
                               mainPanel( # Main panel details and content
                                 width = 3,
                                 tableOutput("contents")

                               ) # End of mainPanel
                             ) # End of sidebarLayout
                           }
                  ), # End of tabPanel

                  tabPanel("Instructions for Upload", # Start of 2nd subtab to first menu item
                           {
                             mainPanel(
                               "Insert instructions for upload here..."
                             ) # End of mainPanel
                           }
                  ) # End of tabPanel
                ) # End of tabBox
              ) # End of fluidRow
      ), # End of tabItem menu Item 1

      #secondtab contents  menu bb
      tabItem(tabName = 'bb',
              h2("Menu 2 Tab Heading"),
              "text2 text2 text2 text2 text2"
      ),

      #third tab contents  menu cc
      tabItem(tabName = "cc",
              h2("Menu 3 Tab Heading"),
              "text3 text3 text3 text3 text3"
      ),

      #third tab contents menu dd
      tabItem(tabName = "dd",
              h2("Menu 4 Tab Heading"),
              "text4 text4 text4 text4 text4"
      )
    )
  )
)

server <- function(input, output) {
  observeEvent(input$go, {
    output$contents =
      renderTable({
        inFile <- input$file1

        if (is.null(inFile))
          return(NULL)
        #connect to database
        con <- dbConnect(MySQL(),
                         user = user,
                         password = password,
                         host = host,
                         dbname = dbname)
        data = read.csv(inFile$datapath, header = TRUE) # csv file contents to data dataframe
        data = mutate(data, pn = input$pn) # add project name to dataframe
        data <- data[,c(ncol(data),1:(ncol(data)-1))]  # move last col to first col
        dbWriteTable(conn = con, name = 'table1', value = data, append = TRUE, header = TRUE, row.names=FALSE) # upload dataframe to MySQL database
        lapply(dbListConnections(MySQL()), dbDisconnect) # close database connection
        data # Show data uploaded
      }
      )
  }
  )
}

shinyApp(ui, server)

A: Try this
server <- function(input, output) {

  mydata <- eventReactive(input$go, {
    inFile <- input$file1
    if (is.null(inFile)) return(NULL)

    data = read.csv(inFile$datapath, header = TRUE) # csv file contents to data dataframe
    data = mutate(data, pn = input$pn) # add project name to dataframe
    data <- data[,c(ncol(data),1:(ncol(data)-1))]  # move last col to first col
    data
  })
  output$contents <- renderTable({
    req(mydata())
    #connect to database
    con <- dbConnect(MySQL(),
                     user = user,
                     password = password,
                     host = host,
                     dbname = dbname)
    dbWriteTable(conn = con, name = 'table1', value = mydata(), append = TRUE, header = TRUE, row.names=FALSE) # upload dataframe to MySQL database
    lapply(dbListConnections(MySQL()), dbDisconnect) # close database connection
    mydata() # Show data uploaded
  })
}


text:
Q: Ubuntu and Lazarus Today I installed Ubuntu and Lazarus IDE (Delphi style cross-platform IDE). I don't know anything about the file structure of Linux Operating Systems. Do you know some tutorials that can get me started specially with Lazarus, and does Linux have modules and API's or how does it work?

A: Some general info:
In Linux (almost) everything is implemented in libraries, have a look at dpkg -l | grep lib. All Debian packages that start with lib are library packages that install a library to /usr/lib or /lib.
Often there is a lib*-doc package for the library that contains its API documentation. Package documentation in general is installed to /usr/share/doc.
There may also be help availabe in the manpage system, try man man and in the GNU info tool.
C/C++ headers are located at /usr/include, you'll have to translate them to Pascal in order to use the libs.
Of course Lazarus and FreePascal come with there own libraries as well and you may want to look at them first.
There is also an Ubuntu specific StackExchange site here: https://askubuntu.com/

A: The best place to start with Ubuntu is at their site:

*

*https://help.ubuntu.com/
It's well documented and the community is great.
Have fun!

A: The main Free Pascal documentation can be useful too (Free Pascal is included in Lazarus as compiler):

*

*http://www.freepascal.org/docs.var
and the main Lazarus library, aka the LCL:

*

*http://lazarus-ccr.sourceforge.net/docs/lcl/

A: If you are looking for the one book describing ALL Linux APIs, it's there:
http://www.man7.org/tlpi/index.html
It just came out, and has had nothing but rave reviews so far.
(And no, I'm neither the author nor the publisher! :D )

A: Excuse me jumping in here :)
Your question is quite broad, so I will answer with some general information of my own.
First of all, the main thing that is annoying for me with programming in lazarus on ubuntu, is when you transfer your program onto windows it doesn't work... I don't know if anyone else gets this, but I have to first compile my application on a windows machine before I can use it on windows.
Also, if you are making a graphical application then make sure you have a fixed font size. I like mine at 11. Obviously make it different for titles.
Why is this a problem you ask? Well, I find, I make this incredible application that looks lovely, and then the fonts are tiny on a different machine. So make sure you're fonts are fixed!!
If you haven't already, the easiest way to install lazarus is to run...
sudo apt-get install lazarus

...in your terminal
Finally, just make a folder called projects in your home directory and you're off! Nothing really different except that lazarus is stored in usr/share/applications.
Hope this helped!
Harrison


text:
Q: Delete N nodes after M nodes of a linked list I can't figure out why my code is not working. The question is -

Delete N nodes after M nodes of a linked list
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the linked list and next M and N respectively space separated. The last line contains the elements of the linked list.
Example:
Input:
1
8
2 1
9 1 3 5 9 4 10 1

Output:
9 1 5 9 10 1

And my code is -
void linkdelete(struct Node  *head, int M, int N)
{
if(head==NULL)
return;
Node* temp=head;
while(1)
{
int m=M-1;
while(m--)
{
temp=temp->next;
if(temp==NULL)
exit;
}
int n=N;
Node* t2=temp;
while(n--)
{
t2=t2->next;
if(t2==NULL)
exit;
}
temp->next=t2->next;
temp=temp->next;
}

On compiling it's giving RUNTIME ERROR.

A: Some issues:

*

*Your code has unbalanced braces. I suppose the missing closing brace should be at the end, but since you have not indented your code, there is no way to know

*You should not exit. The function should return. In the second loop should not even even exit the function, but just break out of the loop: you still need to change temp->next.

*The iteration of the outer loop may end with temp==NULL, so when it starts the next iteration, you will have an invalid reference with temp->next. Make the condition of the outer loop temp != NULL
Here is a corrected version:
void linkdelete(struct Node *head, int M, int N) {
    if (head == NULL) return;
    Node* temp = head;
    while (temp != NULL) {
        int m = M - 1;
        while (m--) {
            temp = temp->next;
            if (temp == NULL) return; // don't exit, but return
        }
        Node* t2 = temp->next;
        int n = N;
        while (n--) {
            if (t2 == NULL) break; // don't stop yet
            t2 = t2->next;
        }
        temp->next = t2;
        temp = t2;
    }
}


text:
Q: Challenge in setting up the script which connects to multiple servers as an autosys job The purpose of the script is to login to multiple servers and execute the df -k command and to send out email containing the list similar like below :
Thu Nov  3 12:59:49 EDT 2016
Running out of space "/opt (80%)" on (a******001s02)
Running out of space "/var (83%)" on (a*******01s01)
Running out of space "/opt/IBM/ITM (98%)" on (a*******001s01)
Running out of space "/apps (80%)" on (a*********01s01)
Running out of space "/opt/wily (80%)" on (a********01s01)
My challenge is :
This script has to run as a scheduled job like autosys job . And the challenge is that, what i believe(not 100 percent sure) , the username ( ssh $username@$host)
should be a sudo user for it to run as an autosys job. But if i hardcode username as a sudo user , the ssh command wont work . As in , we cannot login to multiple servers with username as sudo.
Here I have used 'logname' , so logname will take the name of the user executing the command .But , logname doesnt seem to work if i have to make it as autosys job .
Basically what I want is to make this script run as an autosys job. Currently its working perfectly fine If I can manually run the script .I appreciate any help. Thanks in advance :)
Entire script:
#Shell script to watch disk space
#!/bin/sh

MAILTO="xxxxxxx@xxxxx.com"

# Set alert level 80% is default

ALERT=70

path=/tmp/Joshma

report=$path/report.txt

date > $report

echo >>$report

servers=$path/serversfile.txt

username=`logname`

for host in `cat $servers`

do
echo "$host"
ssh $username@$host df -k | grep -vE '^Filesystem|tmpfs|cdrom|proc' | awk '{ print $4 " " $7 }' | while read output;

do
echo " $output"

usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )

partition=$(echo $output | awk '{ print $2 }' )

if [ $usep -ge $ALERT ]
then
    echo "Running out of space \"$partition ($usep%)\" on ($host)\n" >>$report

fi

done

done

cat $report | mail -s "File System Space Check" $MAILTO

A: The job owner value in a Autosys job can be any user ID that can logon to the server (The machine value) that is executing the AutoSys job. The AutoSys agent will spawn a child process that executes the command as that user ID. Use the ID that you are using to manual run the script as the job owner if you can. If not make sure that the ID that you use has the appropriate permissions to ssh to your server and execute the commands. It is not a AutoSys requirement that the job owner value have sudo on a server.
If the script runs manually but fails in the AutoSys job using the same ID and server, start looking at the environment set in child process. By default AutoSys sources a generic profile that may not be the same as the one set when logging in manually with the ID. You may have to set the profile: value in the job to source a profile file to set the environment correctly when the child process is started.


text:
Q: change attritube value based on other attribute value on select field i have this code:
<select data-showinsummary="true" data-price="0">
     <option data-price="0" >OPTION 1</option>
     <option data-price="20">OPTION 2</option>
     <option data-price="10">OPTION 3</option>
</select>

when user select an option for example option 3 the data-price on select tag goes to 3 also.
By default on select tag, the data-showinsummary is "true" and data-price is "0" ,i can't change this.
what i'm trying to do is check if data-price on select tag is equal to "0" and if it is = 0 then i wanna change data-showinsummary from "true" to "false"
<select data-showinsummary="false" data-price="0">

i would like a solution using pure javascript or jquery.
thank you very much :D

A: Add a onchange function.On change call a function and get the attribute value
Hope this snippet will be useful & change the attribute of select tag

function updateValue() {
  if ($("#sel option:selected").data('price') == 0) {
    $("#sel").attr('data-showinsummary', false)
  } else {
    $("#sel").attr('data-showinsummary', true)
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='sel' data-showinsummary="true" data-price="0" onchange='updateValue()'>
     <option data-price="0" >OPTION 1</option>
     <option data-price="20">OPTION 2</option>
     <option data-price="10">OPTION 3</option>
</select>

A: HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect" data-showinsummary="true" data-price="0">
     <option data-price="0" >OPTION 1</option>
     <option data-price="20">OPTION 2</option>
     <option data-price="10">OPTION 3</option>
</select>

and .js
   $(function(){
  $("#mySelect").change(function(e){
      if($('#mySelect').find(":selected").data('price') == 0){
      $(e.target).data('showinsummary' , 'false');
    }
  });
});

A: give id "prices" to your select element like this:
<select id="prices" data-showinsummary="true" data-price="0">
    <option data-price="0" >OPTION 1</option>
    <option data-price="20">OPTION 2</option>
    <option data-price="10">OPTION 3</option>
</select>

and use this code for javascript part:
window.onload = function() {
    document.getElementById('prices').addEventListener('change', function() {
        var selected = this.options[this.selectedIndex];

        this.setAttribute('data-price', selected.getAttribute('data-price'));

        if (selected.getAttribute('data-price') == 0) {
            this.setAttribute('data-showinsummary', false);
        } else {
            this.setAttribute('data-showinsummary', true);
        }
    });
}


text:
Q: how is pageLoad() getting called? I simply chose an asp.net ajax web form, and I was presented with a page similar to the below mentioned one:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="AppReport.aspx.vb" Inherits="ism2_AppReport" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function pageLoad() {
            alert();
        }

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
    </div>
    </form>
</body>
</html>

I don't understand how the pageLoad executes. How to disable it?

A: pageLoad is just a short-hand of the following:
Sys.Application.add_load(function() {
    // pageload
});

It is being called by the ASP.NET AJAX framework. If you don't need it, you can just remove it.


text:
Q: Select text node by value Given the desire to use XPath to select an XML Text Node based on its value, is there a better way than:
//*[text()="foo"]/text()

I'm assuming that there's something  like:
//text()[self="foo"]

...but I don't know what to put for self.

A: In XPath the period or dot character . is the self, also known as the "context node".
This query…
//text()[.="foo"]

…will select all text nodes with the value of "foo".

A: You have generally found the right answer:
//text()[.="foo"]

However, please note the following:

*

*The XPath // pseudo-operator should be avoided as much as possible whenever the structure of the XML document is statically known, because its evaluation causes complete subtrees (in the worst case the complete document tree) to be traversed and is very inefficient. If you know that all text nodes are children of c and all c in the document can be selected by /a/b/c, then use: /a/b/c/text(). If you only know that all text nodes are descendants of c, then it is still much better to use: /a/b/c//text() than //text() or even than //c//text()

*Quite often the text nodes contain whitespace that we tend not to notice. In such cases one needs to write:
normalize-space(.) = 'foo'

rather than
. = 'foo'


text:
Q: Scroll to top of WebBrowser control How can you scroll to the top of a web broswer  control. The page I am loading has an iframe and the scroll bar is starting 20px down. It only happens in my application. I would like to auto scroll to the top.

A: Quick search yields: webBrowser1.Document.Window.ScrollTo(0, 200);

A: If what you mean is wanting to scroll the content of the iframe to the top, the following should help.
First you will need 2 things:

*

*Add reference to C:\Program Files\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll

*edit your <iframe> tag so that it has an id, eg: id="something"
Finally, the code:
HtmlElement ele = webBrowser1.Document.GetElementById("something");
mshtml.HTMLIFrameClass frame = ele.DomElement as mshtml.HTMLIFrameClass;
if (frame != null)
{
    mshtml.HTMLDocumentClass doc = frame.document as mshtml.HTMLDocumentClass;
    if (doc != null)
    {
        object i = 0;
        mshtml.HTMLWindow2Class win = doc.frames.item(ref i) as mshtml.HTMLWindow2Class;
        if(win != null)
            win.scrollTo(0, 0);
    }
}


text:
Q: Upgrading wifi card killed m.2 e key slot I tried upgrading my intel wireless-ac 7265 to a ax200ngw and only bluetooth worked. After swapping them back, still only bluetooth worked, when wifi was working before.
The wifi half of the cards do not appear in device manager in windows 10 or in the output of lspci in fatdog64, but bluetooth appears in device manager and lsusb, leading me to believe I killed my pcie (but not the usb) m.2 e key slot.
Please help me restore wifi functionality.
The computer is a Hp probook x360 11 G1 EE
I have pentium n4200, 8gb ram and touchscreen version.


text:
Q: How to fix unknown skin name 'WVGA800' error when setting up GitLab CI? I'm new to CI and I'm trying to setup CI on GitLab for Android and here is my .gitlab-ci.yml file:
image: openjdk:8-jdk

variables:
 ANDROID_COMPILE_SDK: "27"
 ANDROID_BUILD_TOOLS: "24.0.0"
 ANDROID_SDK_TOOLS: "24.4.1"

before_script:
 - apt-get --quiet update --yes
 - apt-get --quiet install --yes wget tar unzip lib32stdc++6 lib32z1
 - wget --quiet --output-document=android-sdk.tgz  https://dl.google.com/android/android-sdk_r${ANDROID_SDK_TOOLS}-   linux.tgz
 - tar --extract --gzip --file=android-sdk.tgz
 - mkdir android-sdk-linux/licenses
 - printf "8933bad161af4178b1185d1a37fbf41ea5269c55\nd56f5187479451eabf01fb78af6dfcb131a6481e" > android-sdk-linux/licenses/android-sdk-license
 - printf "84831b9409646a918e30573bab4c9c91346d8abd" > android-sdk-linux/licenses/android-sdk-preview-license
 - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter android-${ANDROID_COMPILE_SDK}
 - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter platform-tools
 - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter build-tools-${ANDROID_BUILD_TOOLS}
 - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter extra-android-m2repository
 - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter extra-google-google_play_services
 - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter extra-google-m2repository
 - export ANDROID_SDK_ROOT=$PWD/android-sdk-linux/platform-tools/
 - export ANDROID_HOME=$PWD/android-sdk-linux
 - export PATH=$PATH:$PWD/android-sdk-linux/platform-tools/
 - chmod +x ./gradlew

stages:
 - build
 - test

build:
 stage: build
 script:
 - ./gradlew assembleDebug
artifacts:
 paths:
 - app/build/outputs/

unitTests:
 stage: test
 script:
   - ./gradlew test

functionalTests:
 stage: test
 script:
  - wget --quiet --output-document=android-wait-for-emulator https://raw.githubusercontent.com/travis-ci/travis-cookbooks/0f497eb71291b52a703143c5cd63a217c8766dc9/community-cookbooks/android-sdk/files/default/android-wait-for-emulator
  - chmod +x android-wait-for-emulator
  - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter sys-img-x86-google_apis-${ANDROID_COMPILE_SDK}
  - echo no | android-sdk-linux/tools/android create avd -n avd$AVD_SDK -t android-${ANDROID_COMPILE_SDK} --abi google_apis/x86
  - android-sdk-linux/tools/emulator64-x86 -avd avd$AVD_SDK -no-window -no-audio &
  - ./android-wait-for-emulator
  - adb shell input keyevent 82 &
  - ./gradlew cAT
artifacts:
  paths:
  - app/build/reports/androidTests/

My above script builds my app but when it's running functionalTest I got this error:emulator: ERROR: unknown skin name 'WVGA800'
then I've created my AVD with -no-skin parameter and now I got this error:
$ android-sdk-linux/tools/emulator64-x86 -avd avd$AVD_SDK -no-skin -no-window -no-audio &
$ ./android-wait-for-emulator
emulator: ERROR: This AVD's configuration is missing a kernel file!!
emulator: ERROR: ANDROID_SDK_ROOT is defined (/builds/myRepo/myProject/android-sdk-linux/platform-tools/) but cannot find kernel file in /builds/myRepo/myProject/android-sdk-linux/platform-tools/system-images/ sub directories

I've followed this guide but not really helped to me. Does anyone have any ideas how I can fix this problem?


text:
Q: SQL with subquery WHERE condition is empty I am hoping someone can advise on what is wrong.
SELECT sms.id FROM sms INNER JOIN screens ON sms.screen_id = screens.id WHERE screens.experience_id = '108';

AND
SELECT id FROM sms
WHERE screen_id IN (SELECT id FROM screens WHERE experience_id = 108 )

... returns an empty row, but there are rows that should be returned.
To clarify...
SELECT id FROM sms

... returns all rows in SMS
SELECT id FROM sms
WHERE screen_id IN (SELECT id FROM screens)

... returns all rows in SMS and
SELECT id FROM screens WHERE experience_id = 108

... returns all rows from screens with that id.
SQL to make the tables...
    CREATE TABLE IF NOT EXISTS `screens` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `device_id` int(11) NOT NULL,
  `type` varchar(32) NOT NULL,
  `description` text NOT NULL,
  `position` int(11) NOT NULL,
  `experience_id` int(11) NOT NULL,
  `image` varchar(512) NOT NULL,
  `url` varchar(512) NOT NULL,
  `persona_id` int(11) NOT NULL,
  `socialPost` text NOT NULL,
  `socialLinkHeadline` varchar(512) NOT NULL,
  `socialLinkDescription` text NOT NULL,
  `socialLink` varchar(512) NOT NULL,
  `socialAction` varchar(64) NOT NULL,
  `bgcolor` varchar(16) NOT NULL DEFAULT '#fff',
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `user_id` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=472 ;

CREATE TABLE IF NOT EXISTS `sms` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `source` varchar(16) NOT NULL,
  `content` text NOT NULL,
  `position` int(11) NOT NULL,
  `screen_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;

A GIF of me running these queries to verify is here: https://ibb.co/gzPFsd
I am at a loss and can see that people can't replicate, thanks!

A: I don't get what's wrong in your query but you can do that using join as well.
SELECT sms.id FROM sms INNER JOIN screens ON sms.screen_id = screens.id WHERE screens.experience_id = '108';

A: Your query works fine , here's the proof.
DROP TABLE IF EXISTS SMS,SCREENS;
CREATE TABLE SMS(ID INT, SCREEN_ID INT);
CREATE TABLE SCREENS(ID INT, EXPERIENCE_ID INT);

INSERT INTO SMS VALUES (1,1),(2,2);
INSERT INTO SCREENS VALUES(1,108),(2,100);

SELECT id FROM sms
WHERE screen_id IN (SELECT id FROM screens WHERE experience_id = 108 );

+------+
| id   |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

Assuming that my data model and yours are the same.


text:
Q: Python: Looping through a dictionary (created from JSON) to create row(s) So, I'm attempting to import Dynatrace data through an api call which returns JSON.  I have the JSON imported as a dictionary of dictionaries and lists (multiple nests).
What I'm trying to do is end up with rows that I can later use to write to a csv.
I think it'll make more sense with examples.
Example of imported JSON (cut short for space, but I left 3 "sections" of what I need):
dtrace_results = json.loads(http_response.content)

which looks like:
{'totalCount': 41, 'nextPageKey': None,
 'result': [{'metricId': 'builtin:service.response.time',
             'data': [{'dimensions': ['SERVICE-039D18D190DF8EE1'],
                       'dimensionMap': {'dt.entity.service': 'SERVICE-039D18D190DF8EE1'},
                       'timestamps': [1641491760000, 1641491820000, 1641491880000],
                       'values': [733, None, 724]},
                      {'dimensions': ['SERVICE-CF6C91BB030BB3AC'],
                       'dimensionMap': {'dt.entity.service': 'SERVICE-CF6C91BB030BB3AC'},
                       'timestamps': [1641491760000, 1641491820000, 1641491880000],
                       'values': [60951.354609929076, 56788.070796460175, 57866.69565217391]},
                      {'dimensions': ['SERVICE-BF03689183860CA9'],
                       'dimensionMap': {'dt.entity.service': 'SERVICE-BF03689183860CA9'},
                       'timestamps': [1641491760000, 1641491820000, 1641491880000],
                       'values': [69, 74, 78.5]}
                     ]}]}

After some manipulation to get it closer to where i want it:
for row in dtrace_results['result'][0]['data']:
    row.pop('dimensions')

results of printing the above: (bullets added for clarity)

*

*{'dimensionMap': {'dt.entity.service': 'SERVICE-039D18D190DF8EE1'}, 'timestamps': [1641492060000, 1641492120000, 1641492180000, 1641492240000], 'values': [None, 1495.3333333333333, 1451.5, None]}

*{'dimensionMap': {'dt.entity.service': 'SERVICE-CF6C91BB030BB3AC'},
'timestamps': [1641492060000, 1641492120000, 1641492180000,
1641492240000], 'values': [70568.0193548387, 64320.80487804878,55929.954545454544, 57868.15151515151]}

*{'dimensionMap': {'dt.entity.service': 'SERVICE-BF03689183860CA9'}, 'timestamps': [1641492060000, 1641492120000, 1641492180000, 1641492240000], 'values': [132, 101, 81, 77]}

what I'm trying to get from the above is basically, in this example 4 rows for each row above, like this (numbers added just for clarity, not needed in results):

*

*SERVICE-039D18D190DF8EE1,1641492060000,None

*SERVICE-039D18D190DF8EE1,1641492120000,1495.3333333333333

*SERVICE-039D18D190DF8EE1,1641492180000,1451.5

*SERVICE-039D18D190DF8EE1,1641492240000,None

*...followed by additional rows

Thanks in advance for any help.

A: Using zip and csv will get you there I think.
Given your data like:
data = {
    'totalCount': 41,
    'nextPageKey': None,
    'result': [
        {
            'metricId': 'builtin:service.response.time',
            'data': [
                {
                    'dimensions': ['SERVICE-039D18D190DF8EE1'],
                    'dimensionMap': {'dt.entity.service': 'SERVICE-039D18D190DF8EE1'},
                    'timestamps': [1641491760000, 1641491820000, 1641491880000],
                    'values': [733, None, 724]
                },
                {
                    'dimensions': ['SERVICE-CF6C91BB030BB3AC'],
                    'dimensionMap': {'dt.entity.service': 'SERVICE-CF6C91BB030BB3AC'},
                    'timestamps': [1641491760000, 1641491820000, 1641491880000],
                    'values': [60951.354609929076, 56788.070796460175, 57866.69565217391]
                },
                {
                    'dimensions': ['SERVICE-BF03689183860CA9'],
                    'dimensionMap': {'dt.entity.service': 'SERVICE-BF03689183860CA9'},
                    'timestamps': [1641491760000, 1641491820000, 1641491880000],
                    'values': [69, 74, 78.5]
                },
                ## many more
            ]
        }
    ]
}

We might try:
results = []
for item in data["result"][0]["data"]:
    dimension = item["dimensions"][0]
    for timestamp, value in zip(item["timestamps"], item["values"]):
        results.append({
            "ID": dimension,
            "timestamp": timestamp,
            "value": value if value else "None"
        })

this would allow us to do:
print(results)

giving:
[
    {'ID': 'SERVICE-039D18D190DF8EE1', 'timestamp': 1641491760000, 'value': 733},
    {'ID': 'SERVICE-039D18D190DF8EE1', 'timestamp': 1641491820000, 'value': 'None'},
    {'ID': 'SERVICE-039D18D190DF8EE1', 'timestamp': 1641491880000, 'value': 724},
    {'ID': 'SERVICE-CF6C91BB030BB3AC', 'timestamp': 1641491760000, 'value': 60951.354609929076},
    {'ID': 'SERVICE-CF6C91BB030BB3AC', 'timestamp': 1641491820000, 'value': 56788.070796460175},
    {'ID': 'SERVICE-CF6C91BB030BB3AC', 'timestamp': 1641491880000, 'value': 57866.69565217391},
    {'ID': 'SERVICE-BF03689183860CA9', 'timestamp': 1641491760000, 'value': 69},
    {'ID': 'SERVICE-BF03689183860CA9', 'timestamp': 1641491820000, 'value': 74},
    {'ID': 'SERVICE-BF03689183860CA9', 'timestamp': 1641491880000, 'value': 78.5}
]

Turning results into a csv is then straightforward.
import csv
with open("results.csv", "w", encoding="utf-8", newline="") as file_out:
    writer = csv.DictWriter(file_out, fieldnames=results[0].keys())
    writer.writeheader()
    writer.writerows(results)

giving a csv that looks like:
ID,timestamp,value
SERVICE-039D18D190DF8EE1,1641491760000,733
SERVICE-039D18D190DF8EE1,1641491820000,None
SERVICE-039D18D190DF8EE1,1641491880000,724
SERVICE-CF6C91BB030BB3AC,1641491760000,60951.354609929076
SERVICE-CF6C91BB030BB3AC,1641491820000,56788.070796460175
SERVICE-CF6C91BB030BB3AC,1641491880000,57866.69565217391
SERVICE-BF03689183860CA9,1641491760000,69
SERVICE-BF03689183860CA9,1641491820000,74
SERVICE-BF03689183860CA9,1641491880000,78.5

A: If you're trying create a list of lists given in bullet points, you're almost there. Simply iterate over dtrace_results['result'][0]['data'] (since it's a list of dictionaries) and get the relevant values via another iteration by zipping the 3 lists. Note that since row['dimensionMap']['dt.entity.service'] is not a list, we'll have to make it a list.
out = []
for row in dtrace_results['result'][0]['data']:

    ts = row['timestamps']
    # we need to make 'service' a list of the same length as the other lists
    service = [row['dimensionMap']['dt.entity.service']]*len(ts)
    vals = row['values']

    for zipped in zip(service, ts, vals):
        out.append(list(zipped))

Output:
[['SERVICE-039D18D190DF8EE1', 1641491760000, 733],
 ['SERVICE-039D18D190DF8EE1', 1641491820000, None],
 ['SERVICE-039D18D190DF8EE1', 1641491880000, 724],
 ['SERVICE-CF6C91BB030BB3AC', 1641491760000, 60951.354609929076],
 ['SERVICE-CF6C91BB030BB3AC', 1641491820000, 56788.070796460175],
 ['SERVICE-CF6C91BB030BB3AC', 1641491880000, 57866.69565217391],
 ['SERVICE-BF03689183860CA9', 1641491760000, 69],
 ['SERVICE-BF03689183860CA9', 1641491820000, 74],
 ['SERVICE-BF03689183860CA9', 1641491880000, 78.5]]


text:
Q: comparing growth of nth derivative of $f(x)=\sqrt {{x^2} + {c^2}}$ and $(n-1)!$ I want to compare the growth of nth derivative of $f(x)=\sqrt {{x^2} + {c^2}}$ and $(n-1)!$ as n goes to infinity. by using mathematica, numerically,
I know that when $c$ is greater than 1, $\frac{{{f^n}(x)}}{{(n - 1)!}}\xrightarrow{{n \to \infty }}0$ but I can't prove it analitically.

A: Rewrite your statement
$$\frac{f^{(n)}(x)}{(n-1)!}1^{n-1} \rightarrow 0$$
Introduce new variable $g=f'$:
$$\frac{g^{(n-1)}(x)}{(n-1)!}1^{n-1} \rightarrow 0$$
But this is equivalent to the statement, that the Taylor expansion of $g$ around $x$, evaluated at $(x+1)$, has terms decreasing to zero.
But for Taylor series, we actually know more: it is convergent within its radius of convergence. Now all you need to prove is that radius of convergence is at least 1 no matter where your starting point is. Additionally, differentiation or integration do not change the radius of convergence, so the proof for $g$ also proves the same statement for $f$.
The radius of convergence for Taylor series equals the distance to the first singularity in the complex plane: usually a pole (e.g. $1/(1+z)$ has a pole at $z=-1$), or a branch point ($\log z$ at $z=0$), in this case, a branch point is where the root argument is zero, so at $x=\pm i c$. The singularities are therefore on the imaginary axis: the smallest radius of convergence is, when you are closest to it, at $x=0$, where it equals $c$. For other $x$, the radius is bigger (equal to $\sqrt{c^2+x^2}$ actually).
This is not a rigorous proof, but for radius of convergence, you can use standard procedures (browse methods under "theoretical radius").


text:
Q: String cannot be input and skip to next prompt The problem lies in the output. I get the expected output upto the contact number after that the inputed part(from keyboard) of the address skip and jump to the email part. I have attach the output in the bottom. I would be thankful if someone figure out my problem
import java.util.Scanner;

public class PhoneLibrary {
    Scanner input = new Scanner(System.in);

    String contactName;
    double contactNumber;
    String contactAddress;
    String contactEmail;
    String description;
    boolean favourite;

    void fillForm() {
        System.out.print("Name: ");
        contactName = input.nextLine();

        System.out.print("Number: ");
        contactNumber = input.nextDouble();

        System.out.print("Address: ");
        contactAddress = input.nextLine();

        System.out.print("E-mail: ");
        contactEmail= input.nextLine();
    }

    public static void main(String[] args) {
        PhoneLibrary contact = new PhoneLibrary();
        contact.fillForm();
    }

}

Output
Name: Vector
Number: 9854425655
Address: E-mail: Vector@gmaail.com

A: Add input.nextLine() after this likes:
System.out.print("Number: ");
contactNumber = input.nextDouble();

A: Simply use this before taking input of address.
input= new Scanner(System.in);

Your code:
System.out.print("Name: ");
contactName = input.nextLine();

System.out.print("Number: ");
contactNumber = input.nextDouble();

System.out.print("Address: ");
input= new Scanner(System.in);
contactAddress = input.nextLine();

System.out.print("E-mail: ");
contactEmail= input.nextLine();

A: try this
System.out.print("Name: ");
contactName = input.nextLine();

System.out.print("Number: ");
contactNumber = Double.parseDouble(input.nextLine());

System.out.print("Address: ");
contactAddress = input.nextLine();

System.out.print("E-mail: ");
contactEmail= input.nextLine();

new line was taken in contactAddress in your code as you used nextDouble

A: use
input.nextLine();
after
contactNumber = input.nextDouble();
Because nextDouble method does not get return (\r) from console so adress varialble gets the return char and flows to email input

A: nextDouble() is a method of the class Scanner that returns the next scanned double.
have you tried?
    void fillForm() {
        System.out.print("Name: ");
        contactName = input.nextLine();

        System.out.print("Number: ");
    try{
        contactNumber = Integer.parseInt(input.nextLine());
    }catch(ParseException e){
      throw new ParseException();
    }
        System.out.print("Address: ");
        contactAddress = input.nextLine();

        System.out.print("E-mail: ");
        contactEmail= input.nextLine();
    }

    public static void main(String[] args) {
        PhoneLibrary contact = new PhoneLibrary();
        contact.fillForm();
    }


text:
Q: Mobx update a single property in an object I have created an observable property in my store as follows
class Store {
  @observable values = { id: '', name: '' }
}

This observable object is used in a form, how can I reset these values after the form is submitted?

A: You could use extendObservable and implement a reset method on your class:
const initValues = { id: '', name: '' };

class Store {
  @observable values = {};
  constructor() {
    extendObservable(this.values, initValues);
  }

  reset() {
    extendObservable(this.values, initValues);
  }
}

A: @Tholle's solution is good if you don't extend properties to the this.values observable. if you do, the reset() method will not clear newly extended properties.
Here's my solution to this:
class Store {
    const initValues = {id: '', name: ''};
    @observable values = {};
    @action resetValues() {
        Object.keys(this.values).forEach(key => delete this.values[key]);
        extendObservable(this.values, initValues);
    }
    constructor() {
        This.resetValues();
    }
}

or even better, to use observable map instead:
class Store {
    const initValues = {id: '', name: ''};
    @observable values = new Map();
    @action resetValues() {
        this.values.replace(initValues);
    }
    constructor() {
        this.resetValues()
    }
}


text:
Q: Como crear un WebMethod a partir de dos métodos donde uno de ellos no es static Hola amigos otra vez de vuelta con una nueva pregunta espero me puedan ayudar de antemano gracias.
Tengo dos métodos para leer un excel con epplus. Todo funciona de maravilla pero por ahora quiero programar un WebMethod con estos dos métodos para enviarlos por ajax y mostrar la información en un Grid(jqxGrid).
Mi pregunta seria ¿Como programar este WebMethod? ¿Como tendria que ser mi ajax?
Este es mi codigo para obtener el archivo con FileUpload
public string ruta() //Como se puede ver no es de tipo static
    {
        string fileName="";
        string fileExtension="";
        string fileLocation="";
        if (fuImportarArchivo.HasFile)
        {
            fileName = Path.GetFileName(fuImportarArchivo.FileName);
            fileExtension = Path.GetExtension(fuImportarArchivo.FileName);
            fileLocation = Server.MapPath("~/Excel/" + fileName);
            fuImportarArchivo.SaveAs(fileLocation);

        }
        return fileLocation;

    }

Este es mi otro método donde le paso como parámetro la ruta o resultado del método anterior
   public static DataTable ExcelToDataTable(string path)
    {
        using (var pck = new OfficeOpenXml.ExcelPackage())
        {
            using (var stream = File.OpenRead(path))
            {
                pck.Load(stream);
            }
            var ws = pck.Workbook.Worksheets.First();
            DataTable tbl = new DataTable();
            bool hasHeader = true;
            foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
            {
                tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
            }
            var startRow = hasHeader ? 2 : 1;
            for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
            {
                var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
                var row = tbl.NewRow();
                foreach (var cell in wsRow)
                {
                    row[cell.Start.Column - 1] = cell.Text;
                }
                tbl.Rows.Add(row);
            }
            return tbl;

        }
    }

Aqui es donde trato de crear mi WebMethod
 [WebMethod]
    public static string Importar_Excel()
    {
        string dir_archivo = ruta(); //Aqui me muestra error mi metodo ---> Se requiere una referencia de objeto para el campo, metodo o propiedad no estaticos.
        DataTable dt = new DataTable();
        dt = ExcelToDataTable(dir_archivo);
        string datos = JsonConvert.SerializeObject(dt, Formatting.Indented);
        return datos;
    }

A: La unica forma que se me ocurre es desacoplando las acciones
Por un lado tienes el upload del archivo que se realiza en el submit del form, imagino en algun eventos
public void btnUpload_Click(...)
{
    //resto codigo
    string fileLocation = ruta();

    Session["fileLocation"] = fileLocation;
}

Entonces conservas la ruta en Session para usarla en el tro paso
[WebMethod]
public static string Importar_Excel()
{
    if(HttpContext.Current.Session["fileLocation"] == null)
    {
        //aqui deberias devolver algun mensaje
        return "";
    }

    string dir_archivo = HttpContext.Current.Session["fileLocation"].ToString();

    DataTable dt = new DataTable();
    dt = ExcelToDataTable(dir_archivo);
    string datos = JsonConvert.SerializeObject(dt, Formatting.Indented);
    return datos;
}

Es alli donde lo recuperas accediendo al HttpContext.Current tomando la ruta donde se dejo el archivo
Para subir un archivo sin refrescar la pagina se podria aplicar esta tecnica
Upload File without Form Submit (PostBack) using jQuery AJAX in ASP.Net


text:
Q: AJAX request data fields "undefined" from web form submission I'm setting up a webpage that will store user responses from a form in a google sheets document. Upon form submission, an AJAX request is made and altered as to populate fields in a google script. The data fields in the request show up as undefined in both the google sheet and in curl response generated.
I know that the connection is made successfully because "undefined" values populate the google sheets cells.
The js is shown below.

  <form autocomplete=off action="javascript:;" id="resetForm" onsubmit="insert_value()">
    ID : <input type="text" class="id" name="id">
 First name: <input type="text" class="name" name="name">

    <input type="submit" value="Send form data!">
  </form>

Here is the curl generated for the request:
"https://script.google.com/macros/s/AKfycbzfVIP99UG7NK9kD94zptKJeEBhP9qWDsuFVfrOAerK6Hg-EUw-/exec?callback=ctrlq^&name=undefined^&id=undefined^&action=insert" -H "Accept: application/json, text/javascript, /; q=0.01" -H "Origin: null" -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36" --compressed
I'm not sure why they are undefined as the values are explicitly passed into the url by the js.

A:

  <form autocomplete=off action="javascript:;" id="resetForm" onsubmit="insert_value()">
    ID :
    <input type="text" id="id" name="id">

    First name:
    <input type="text" id="name" name="name">

    <input type="submit" value="Send form data!">
  </form>

Instead of giving class names to the input elements, give Id. Id is nothing but a unique attribute for each element. It must be unique.
Also, I have changed the class attribute to id. Now it must work as expected.

A: Hello you can't say my connection is successfull because I get undefined values > it's false, as you will get undefined values anyway.
What you have missed here, is to send your request once your form has been updated, not on initialization (it's what you are doing here)
You have to encapsulate your function within a kind of jquery document ready function https://learn.jquery.com/using-jquery-core/document-ready/
Or simply make sure your variable are up to date before sending them ;)


text:
Q: Runtime error on upgrading resteasy-jaxrs from 3.0.26.Final to 3.12.0.Final After Upgrading to resteasy-jaxrs.3.12.0.Final
On debugging mode, API request not landing in path method.  If revert upgrade of resteasy jar, web service request property can be debug.
Error:
19:29:32,280 ERROR [io.undertow.request] (default task-1) UT005023: Exception handling request to /vrisk/vcheck-ws/scan-service/scan: java.lang.NoSuchMethodError: org.jboss.resteasy.core.ResourceMethodInvoker.isSse()Z
    at org.jboss.resteasy.plugins.providers.sse.SseEventSinkInterceptor.filter(SseEventSinkInterceptor.java:30)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:263)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:249)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:236)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:406)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:213)
    at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:228)
    at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
    at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:53)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:59)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:326)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:812)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

and also used resteasy-spring.3.5.0.CR1. Compilation and deployement success on jboss.
I could not guess why this error explode on runtime only .


text:
Q: click on color button and write in textarea with that color font I want to do as follows:
* click a "red" button
* write in textarea with red color font
* click "blue" button
* write in textarea with blue color font

Isn't this possible in flash 10 using AS3 ??????
I tried using setTextFormat but the problem is i have to have text before inserting format on that.
This is what i want:
* start writing in textarea with WHITE COLOR (eg: "abc")
* click BLUE COLOR BUTTON
* start writing in textarea with BLUE COLOR (eg: "abcdef" - abc in white and def in blue)
* click RED COLOR BUTTON
* start writing in textarea with RED COLOR (eg: "abcdefxyz" - abc in white and def in blue and xyz in red)

Please somebody tell me how to do this?

A: the documentation states that if you want to change the format of the text prior to writing anything in the text field to assign a new defaultTextFormat.  otherwise, setting a new format will change the current selection.
the solution below works by maintaining the focus on the text field, so when the buttons are clicked the text field still has focus.  if there is a current selection, the selection will change either blue or red, depending on which button is pressed.  if there is no selection, a new defaultTextFormat is applied, without changing previous defaultTextFormats, since the text field still had focus when the new format was applied.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import flash.events.FocusEvent;

public class ChangeTextColor extends Sprite
{
private var field:TextField;
private var redButton:Sprite;
private var blueButton:Sprite;

public function ChangeTextColor()
    {
    init();
    }

//Initialize
private function init():void
    {
    //Create Text Field
    field = new TextField();
    field.type = TextFieldType.INPUT;
    field.border = true;
    field.x = field.y = 10;
    addChild(field);

    //Retain Focus On TextField
    field.addEventListener(FocusEvent.FOCUS_OUT, fieldFocusOutHandler);

    //Create Button
    redButton = createButton(10, 120, 200, 20, 0xFF0000);
    blueButton = createButton(10, 150, 200, 20, 0x0000FF);
    }

//Create Button Method
private function createButton(x:uint, y:uint, width:uint, height:uint, color:uint):Sprite
    {
    var resultSprite:Sprite = new Sprite();

    resultSprite.graphics.beginFill(color);
    resultSprite.graphics.drawRect(0, 0, width, height);
    resultSprite.graphics.endFill();

    resultSprite.addEventListener(MouseEvent.CLICK, mouseClickEventHandler);

    resultSprite.x = x;
    resultSprite.y = y;
    addChild(resultSprite);

    return resultSprite;
    }

//Apply Text Format
private function changeTextFormatColor(color:uint):void
    {
    var format:TextFormat = new TextFormat();
    format.color = color;

    //Change Format Of Selection Or Set Default Format
    if  (field.selectionBeginIndex != field.selectionEndIndex)
        field.setTextFormat(format, field.selectionBeginIndex, field.selectionEndIndex);
        else
        field.defaultTextFormat = format;
    }

//Maintain Focus Of TextField When Color buttons Are Clicked
private function fieldFocusOutHandler(evt:FocusEvent):void
    {
    stage.focus = evt.currentTarget as TextField;
    }

//Button Click Event Handler
private function mouseClickEventHandler(evt:MouseEvent):void
    {
    switch  (evt.currentTarget)
            {
            case redButton:     trace("red clicked");
                                changeTextFormatColor(0xFF0000);
                                break;

            case blueButton:    trace("blue clicked");
                                changeTextFormatColor(0x0000FF);
            }
    }
}
}

alternatively, if you have other buttons in your program that do not relate to the text field and should make the text field lose focus when clicked, just remove the fieldFocusOutHandler function and place stage.focus = field; inside the buttonClickHandler method.  you could also keep and tailor the fieldFocusOutHandler function if this is an issue.

A: Here is the solution for anyone who is looking around (thanks to those who solved my problem)
Use following in changehandler of textfield:
textfield.setTextFormat(default_format, textfield.caretIndex-1, textfield.caretIndex);

Use following in clickhandler of button:
default_format.color = getColor("red");
    stage.focus = textfield;

Regards


text:
Q: How to remove single quotes from string in the List in python? I want to generate excel pivot automatically as below.
table = pd.pivot_table(df,index=["Manager","Status"],columns=["Product"],values=["Quantity","Price"],
               aggfunc={"Quantity":len,"Price":[np.sum,np.mean]},fill_value=0)
details on : reference site
I get this from my program
{'sales_qty': ['sum'], 'buyer_cnt': ['count,sum']}

But I want
{'sales_qty': [sum], 'buyer_cnt': [count,sum]}

Sum and count,sum are dynamically allocation.
I will try to this variable
    {'sales_qty': [sum], 'buyer_cnt': [count,sum]}
to aggfunc
(ex. aggfunc= {'sales_qty': [sum], 'buyer_cnt': [count,sum]})
How can I remove single quotes from list string?
my code is here :
 my code

A: You cannot inherently remove the quotes around a Python variable. However, you can pass arguments to a function via **kwargs
import re
def my_function(**kwargs):
    the_dict = {'sales_qty': ['sum'], 'buyer_cnt': ['count,sum']}
    new_dict = {a:re.split("\W+", b[0]) for a, b in the_dict.items()}
    final_dict = {a:[kwargs[i] for i in b] for a, b in new_dict.items()}

    print(final_dict)

my_function(sum=10, count=12)

Output:
{'sales_qty': [10], 'buyer_cnt': [12, 10]}


text:
Q: Compile or not to compile .class files There is a web application, that is being ran on Windows, inside a Tomcat browser.
Application users number of .jar files as a storage for it's logic.
When I open a jar file, that I need to alter a logic of, I see a bunch of .class files. (Java compiled classes, I assume). When I try to open .class file in a text editor, I see a semi-readable gibberish.
When I feed this compiled .class to a service like showmycode.com, I can see the actual java code.
At this point I alter the code according to my need and want to put the updated .class file for application to use (put it back inside a jar).
Is it mandatory that I compile the .class file to a "semi-readable gibberish", or I can put it there as a source code file (probably not, but thought I would ask just in case).
If I have to compile the atered code, can I do it without bringing up a project in some Java IDE, and just compile it into .class via command line or something?

A: There are two main methods for editing an application you don't have the source for.
The first one, as you've discovered is decompile, edit, recompile. The advantage is that you don't have to know anything about bytecode since it's just decompiled to Java. The main disadvantage is that even the best decompilers can't guarantee producing recompileable code. And if the application has been obfuscated at all, you can forget about recompilation.
The alternative is disassemble, edit, reassemble. I'd recommend Krakatau for this (disclosure, I wrote it). One alternative is ASM, but it's designed for programatic modification, not hand editing, and it's clunkier.
The main advantage of bytecode editing is that it always works, even if the application has been obfuscated. The downside is that it obviously requires you to understand and be able to program directly in bytecode.


text:
Q: Reduce cognitive complexity of function I have this function that has a cognitive complexity of 24, but we only allow it to be maximum 15.
export function parameterValueParser<T extends Structure>(
  structure: T
): (parameterValue: Value) => Parsed<T> | null {
  return (parameterValue: Value): Parsed<T> | null => {
    if (isParameterValueNumber(structure)) {
      return parseNumber(parameterValue) as Parsed<T> | null;
    }
    if (isParameterValueStruct(structure)) {
      const parameterValueChildren = parseStruct(parameterValue);
      if (parameterValueChildren == null) {
        return null;
      }
      const result = {} as { [_: string]: Parsed<Structure> };
      for (const key in structure) {
        if (structure.hasOwnProperty(key)) {
          const child = parameterValueChildren[key];
          if (child == null) {
            return null;
          }
          const parsedChild = parameterValueParser(structure[key])(child);
          if (parsedChild == null) {
            return null;
          }
          result[key] = parsedChild;
        }
      }
      return result as Parsed<T>;
    }
    return null;
  };
}

One reason for the high cognitive complexity is the nestled ifs, and many under a for..of loop. So even if I would extract the code to a separate function, the cognitive complexity will be too high. How to reduce its complexity?

A: This might be better suited for codereview, but I'd start refactoring by
factoring out literal types
- export function parameterValueParser<T extends Structure>(structure: T): (parameterValue: Value) => Parsed<T> | null
+ type Parser<T> = (val: Value) => Parsed<T> | null;
+ export function parameterValueParser<T extends Structure>(structure: T): Parser<T>

removing all type assertions
- return parseNumber(parameterValue) as Parsed<T> | null;
+ return parseNumber(parameterValue);

using meaningful variable names (too long names are just as bad as too short)
- const parameterValueChildren = parseStruct(parameterValue);
+ const children = parseStruct(val);

Once this is ready, you can start refactoring your logic, which will be simpler "inside-out": instead of checking the structure type in the parser, do it outside and return a specific parser for each type:
export function parameterValueParser<T extends Structure>(struct: T): Parser<T> {
    if (isParameterValueNumber(struct)) {
        return parseNumber;
    }
    if (isParameterValueStruct(struct)) {
        return structValueParser(struct);
    }
    etc....
}


text:
Q: OpenGL version to start with (as of late 2014) I know nothing about OpenGL, but it turns out it might be needed for something that I'm working on (figured this out simply because I want some visual effects that need fast drawing - hardware accelerated).
So I'm very much troubled about which version of OpenGL to start coding for as of the current date? (September 2014 for future readers).
As of now, I have read OpenGL 3.x is the most available (read as: supported) version, even on very old hardware (i.e. designed for Windows XP). But, what if I develop for OpenGL 4.x, will my application be backward-compatible with 3.x supported hardware? Or does it just break there and only run on 4.x (and future?) supported hardware?
My use of OpenGL is not for a videogame or anything similar so I might never need advanced functionality (as of now I can't name any to give you an example of what I may never use, I hope experienced OpenGL people will understand my point). However, I don't think this is going to lower in any way the driver support required, am I right?
Please note that I might have used the wrong terminology and I want to start learning OpenGL which puts me in a position not so good to understand whether I might need this or that feature and/or possible requirements - I am in the need of real advice to get started and figure my way out.

A: I'm sure this answer skips many many details and exceptions (so take with salt and if you disagree or have something to add, leave a comment :P), but... Each OpenGL version mostly just adds features, so if you start using a new features it might limit the hardware you can run your app on (and so the question attracted a downvote, when instead it should have attracted an explanation).
Basic drawing pretty much remains a constant, with one very big exception: all the stuff that was deprecated in version 3 and removed in 3.1.
Old, < GL 3:
We used to be able to do things like:
glEnable(GL_LIGHTING); //fixed-pipeline lighting. replaced with shaders
glEnable(GL_TEXTURE_2D); //fixed texturing
glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(...); //builtin matrices
glBegin(GL_TRIANGLES); glVertex3f(...) ...; glEnd(); //immediate mode with per-vertex calls
glVertexPointer(..., myArray); glDrawArrays(...); //immediate mode with client side array

But even then we still had GLSL shaders and VBOs. There's a fair amount of overlap and the GL3 deprecation didn't instantly replace everything:
glBufferData(...); //buffer mesh data to bound VBO
...
glVertexAttribPointer(...); //attach data to myCustomVar (either VBO or immediate mode local array)
...
attribute vec3 myCustomVar;
varying vec3 myVarying;
...
gl_Position = gl_ProjectionMatrix * gl_ModelviewMatrix * gl_Vertex;
...
gl_FragColor = vec4(1, 0, 0, 1);

New, >= GL 3:
The new way of drawing removes immediate mode and a lot of these in-built features so you do a lot from scratch, adds a few features and syntax changes. You have to use VBOs and shaders:
glBufferData(...); //buffer mesh data
...
glVertexAttribPointer(...); //attach VBOs, but have to set your own position etc too
...
#version 150 //set GLSL version number
out vec3 myVarying; //replaces "varying"
gl_Position = myProjection * myModelview * myPosition;
...
in vec3 myVarying;
out vec4 fragColour; //have to define your own fragment shader output
...
fragColour = vec4(1, 0, 0, 1);

To answer your question, and this is completely my opinion, I'd start learning GLES2.0 (afaik pretty much a subset of GL3) because it's so well supported right now. GL2/immediate mode certainly doesn't hurt as a learning step, and there's still quite a lot that isn't deprecated. You can always just use GL 4 features if you find you need them, but as said the basics really only changed between the above versions. Even if you use deprecated features you have to go out of your way to get a pure GL3.2 (for example) context that disallows certain calls/features. I'm not advocating it but it's entirely possible to mix very old with very new and most drivers seem to allow it.
TLDR: 1. use VBOs, 2. use shaders. Just for learning, don't bother with an explicit version context.
See Also:

*

*http://www.opengl.org/wiki/History_of_OpenGL

*http://www.opengl.org/wiki/Core_And_Compatibility_in_Contexts

*List of deprecated OpenGL functionalities


text:
Q: Python Test Loader using Nose I am a beginner at Python and the Nose framework. What I need to do is to write a Test Loader that will load tests using Nose.The results of the test has to be generated as a HTML report. Can someone give me a description about how to do this. I want to know what are the python test case files to write, what are the libraries to include. Please give me a start on this.
Thanks

A: I believe that the capability that you describe already exists in Nose.

*

*Nose discovers and loads tests.

*Nose can print output in a variety of formats, including XML (with a plug-in).

If you install Nose and the NoseXML or NoseXMLUnit plugin, I believe that you should have what you need.  If you truly need HTML instead of XML, use one of those plugins as a base to write your own. (And make sure to add it to the list of third-party plugins).


text:
Q: React - accessing selected option on button click? I have something like this
handleClick:function(){
    // click logic
},
render: function(){
  return (
    <select>
        <option value="a">A</option>
        <option value="b">B</option>
    </select>
    <button onClick={this.handleClick}>Get Selected Value</button>
  );
}

How do I get the value of the select element when I click the button?

A: You add a reference to the select
handleClick:function(){
    var value = React.findDOMNode(this.refs.mySelect).value;
},
render: function(){
  return (
    <select ref="mySelect">
        <option value="a">A</option>
        <option value="b">B</option>
    </select>
    <button onClick={this.handleClick}>Get Selected Value</button>
  );
}

A: While you can get a hold of the DOM node of the select and find out the current value, I find it simpler to use component state for this. Something like this:
var React = require('react/addons');

var App = React.createClass({
  mixins: [React.addons.LinkedStateMixin],
  getInitialState: function () {
    return {
      option: 'a'
    };
  },
  handleClick: function () {
    alert(this.state.option);
  },
  render: function () {
    return (
      <select valueLink={this.linkState('option')}>
          <option value="a">A</option>
          <option value="b">B</option>
      </select>
      <button onClick={this.handleClick}>Get Selected Value</button>
    );
  }
});

The LinkedStateMixin mixin makes sure that any changes to the select box will automatically sync that value to the components state. But also the other way around, you can update the state and LinkedStateMixin will make sure that the select box gets the new value.


text:
Q: EC2 and setting up MYSQL Replication my database size is very big around 100gb and when I restore it takes 3 days to restore. I am using amazon ec2.
My question is I want to setup a new slave to MYSQL master, can I take a snapshot of the Master and create a new instance using the snapshot and then enable replication in between.Given that I take log position before the snapshot and my.cnf changes as required. Snapshot is very fast and takes 1-2hours to create a new machine, whereas mysqldump is taking very very long.
I was just worried if replication works using above method, can anyone help please.

A: on Amazon system you can use following steps to setup replication for MySQL

*

*Choose a low/off production window

*Note Master co-ordinate using show master status

*You may consider using flush tables with read-lock, just to make sure you are sure that your co-ordinates doesn't change while you are creating snap shot

*take snap shot and restore

*Change server-id and relay log and issue change master

Hope it helps

A: I would advise you to drop mysqldump and move to Percona Xtrabackup. It will give you a filesystem level backup that can be made online. Restoring those backups will be orders of magnitude faster.


text:
Q: Why do I need an Azure On-Premises Data Gateway for my Azure Analysis Service? So I have this Azure Analysis Service where the data source of the cube points to an external (on prem) SQL Server database. For some reason it won't connect to it even when I have the proper firewall changes in place.
When processing the cube it complains that I need to install the on-premises data gateway.
So my question is: Is the on-premises data gateway mandatory for connecting to other sources outside Azure?

A: Per docs, all non-Azure data sources require the on-premises data gateway:
https://learn.microsoft.com/en-us/azure/analysis-services/analysis-services-datasource
As to why, it's unusual and not recommended that you would expose your on-premises SQL Server for direct connection from the internet.


text:
Q: How to send emails from my website domain in asp.net I want to send mail from my website domain(www.sample.com)
I have written below code. It is not returning any error. But it is not sending mail once I uploaded the pages in the server. Once click on email send, it is not getting any error, but not receiving the mail.
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("mail.sample.co.uk", 25);

smtpClient.Credentials = new System.Net.NetworkCredential("smtpuser@sample.co.uk", "pass@123");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = false;
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

//Setting From , To and CC
mail.From = new System.Net.Mail.MailAddress("smtpuser@sample.co.uk", "MyWeb Site");
mail.To.Add(new System.Net.Mail.MailAddress("myemail@gmail.com"));
mail.CC.Add(new System.Net.Mail.MailAddress("myemail1@gmail.com"));

smtpClient.Send(mail);

I am getting the "mailsend" response text in the page once calling the sending method.
Please help
Anjana

A: The following code works perfect for me. Make sure you have added a mail account on the smtp server and activated it.
private static string EMAIL_SERVER = "mailservername.mydomain.com";
    private static string EMAIL_NAME = "myMailAccount@mydomain.com";
    private static string EMAIL_PASSWORD = "complex_password123";
    private static string EMAIL_SEND_TO = "sample@mail.com";
    protected string SendMail()
    {

        try
        {

            System.Net.Mail.MailMessage objMM = new System.Net.Mail.MailMessage();
            objMM.From = new MailAddress("fromMe@mail.com", "john doe");
            objMM.To.Add(new MailAddress(EMAIL_SEND_TO));    //Note: this To a collection
            objMM.Subject = "Subject1";
            objMM.Body = "Hello world this is my text";
            objMM.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient(EMAIL_SERVER);
            smtp.Credentials = new NetworkCredential(EMAIL_NAME, EMAIL_PASSWORD);
            smtp.Send(objMM);

        }
        catch (Exception e)
        {

            return "Message can not be send couse of error: " + e.ToString();
        }

        return "Message is send.";

    }