text:
Q: kivy - textinput from kv to py - import data I'm trying to get the data from a simple textinput that is in my kv file and use the information in my python file.
but i keep getting the same error.
this error happens when i press a button and the function try to run looks like its trying to get the information from the text_location widget
thank you in advance.
class ScatterTextWidget(BoxLayout):

    def initialize_request(self):
         ''' Initial analysis and control flow of the class '''

         location = self.ids.input_location
         date = S.ids.input_date
         time_raw = ScatterTextWidget.ids.input_time
         print(f'{location} - {date} - {time_raw}')

class HistoricalApp(App):
     def build(self):
         return ScatterTextWidget()

if __name__ == "__main__":

    HistoricalApp().run()

the kivy file called "historical.kv"
i reduce it because is kind of long
<ScatterTextWidget>:
    BoxLayout:
        canvas.before:
            Color:
                rgb: utils.get_color_from_hex('#01183f')
            Rectangle:
                pos: self.pos
                size: self.size
        size_hint_y: None
        height: 40
        valign: 'middle'

        TextInput:
            id:text_location
            width: 200
            id: input2
            font_size: 15
            size_hint_y: None
            height:40
        TextInput:
            id:input_date
            width: 200
            id: input1
            font_size: 15
            size_hint_y: None
            height: 40
        TextInput:
            id:input_time
            width: 200
            id: input1
            font_size: 15
            size_hint_y: None
            height: 40

the error i receive is
File "kivy\properties.pyx", line 838, in
 kivy.properties.ObservableDict.__getattr__
 KeyError: 'text_location'

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "C:/Users/IBKCo/Desktop/Git Programs/TimeStationHistoricalRecords/MainGui.py", line 77, in <module>
     HistoricalApp().run()
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\app.py", line 826, in run
     runTouchApp()
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\base.py", line 502, in runTouchApp
     EventLoop.window.mainloop()
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\core\window\window_sdl2.py", line 727, in mainloop
     self._mainloop()
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\core\window\window_sdl2.py", line 460, in _mainloop
     EventLoop.idle()
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\base.py", line 340, in idle
     self.dispatch_input()
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\base.py", line 325, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\base.py", line 291, in post_dispatch_input
     wid.dispatch('on_touch_up', me)
   File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
     self.dispatch('on_release')
   File "kivy\_event.pyx", line 703, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1214, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1098, in kivy._event.EventObservers._dispatch
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\pdEnv\lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Users\IBKCo\Desktop\Git Programs\TimeStationHistoricalRecords\historical.kv", line 127, in <module>
     on_release: root.initialize_request()
   File "C:/Users/IBKCo/Desktop/Git Programs/TimeStationHistoricalRecords/MainGui.py", line 31, in initialize_request
     location = self.ids.text_location
   File "kivy\properties.pyx", line 841, in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

thank you in advance
best,

A: First, you need to remove both of the id:input1 lines and the id:input2 line. Then change your initialize_request method to:
def initialize_request(self):
     ''' Initial analysis and control flow of the class '''

     location = self.ids.text_location.text
     date = self.ids.input_date.text
     time_raw = self.ids.input_time.text
     print(f'{location} - {date} - {time_raw}')

Note that self.ids.text_location is a reference to the TextInput widget, so you have to add .text to get its text. Same for the other TextInput widgets.


text:
Q: Binding datepicker with an Angular Directive So, I have created a JSFiddle that actually works for this:
Working example
var datePicker = angular.module('JBenchApp', []);

datePicker.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'DD, d  MM, yy',
                onSelect: function (date) {
                    scope.date = date;
                    scope.$apply();
                }
            });
        }
    };
});

But when I move this into my application it doesn't work with the exact same code.
Some background:

*

*I have an ng-app="JBenchApp" in my HTML tag.

*I have declared my links to JQuery, JQuery-UI, and Angular in the head of my index.html file

*I have a calendar.html file that is a partial that gets displayed using the angular routing and the ng-view directive. This has the tag:

All gets displayed properly and onLoad I can see that the directive is bound. I then click on the datepicker and nothing happens. No errors appear in the console either.
Everything in the JSFiddle above works. I have copied it exactly as is into my code and it just doesn't work. What am I doing wrong?
EDIT TO INCLUDE WHAT'S IN THE HEAD:
 <link href="css/bootstrap.css" rel="stylesheet" />
    <link href="css/styles.css" rel="stylesheet" />
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="js/jquery-2.1.4.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-route.min.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/directives.js"></script>
    <script src="js/app.js"></script>
    <script src="js/bootstrap.js"></script>

A: Well, after staring at this code and staring at this code, it struck me. The directive is named jqdatepicker and the call to the directive is jdatepicker (no "q"). Doh!

redpajama_set_name: RedPajamaStackExchange


text:
Q: tfs force rebase from parent to child branch I have looked all over for a way to force a rebase when merging in TFS.  I am looking for a way to force developers to get latest of the parent branch and merge it down into their own branch before merging back up to the parent.  Most results now are coming back with GIT articles but we are using TFVC.

A: There is no out-of-tge-box way to 'force' developers to do this.
Professional developers should always make sure they have an up to date workspace and have completed a build and run unit tests before checkin in. This is a discipline issue.
You could create a checkin policy that checks for this. But that would be over kill.
..


text:
Q: jQuery.on() does not work in WordPress admin panel I'm writing my own WordPress(4.1.4) plugin which uses some JavaScript code in admin panel.
The first issue is $ object is undefined, so I use jQuery instead.
Now, I want to handle click on the button using jQuery:
jQuery(function(){
    jQuery(".my-button").on("click", function(){
        alert("OK");
    });
});

Unfortunately, this simple code does not work, but if I try to use this:
jQuery(function(){
    jQuery(".my-button").click(function(){
        alert("OK");
    });
});

it works fine.
At first, I thought that jQuery version is too old, but when I checked it, I got 1.11.1.
So I don't understand why the jQuery.on() does not work in my case.

A: Make sure you code is running at the end of the document by running <?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>, then setting the $in_footer argument to true. Then the on function should work as expected. I've tested in WP version 4.2.1, but it should still work in your 4.1.4 environment. This code will also allow you to use the $.
(function($){
    $(".my-button").on("click", function(e){
        e.preventDefault();
        alert("OK");
    });
}(jQuery));

A: I had same problem :/
my code:
(function ($) {
    "use strict";

    jQuery('.theme_data_sync').click(function (e) {
        jQuery('.theme_data_sync').addClass('xxx')
    })

})(jQuery);

at first, i thought there is jquery problem! but at the end after half an hour Checking my codes, 'wp_enqueue_script' was the cause!
i put the 'true' at the end of 'wp_enqueue_script' for loading scripts in footer; it worked for me


text:
Q: WSO2 custom authenticator for Outh2 token api I want to implement a custom authenticator for /oauth2/token,
Where along with grant_type, username, password, and scope will pass one more parameter OTP and that will be validated with custom logic.
Is there any way of verifying additional parameters with external custom logic?
I can see in WSO2 docs, Writing a Custom OAuth 2.0 Grant Type but that will verify the additional params internally.


text:
Q: iPhone Case Manufactuerer - Unlabelled but have logo A family member has a really old iphone case that is pretty nice and I'm trying to find the company behind it. Unfortunately the case did not come with packaging (as far as we can remember), it was sold in the Apple Store at the time, and it doesn't have the company name on the case itself, just a logo:

I tried a google reverse image look up and it found nothing, so I'm hoping that someone here recognizes it.

A: I found out another way that this is Best Buy's house brand for phone accessories called RocketFish. Most of the phone items under this brand are now discontinued.


text:
Q: sendmail on linux not working I have tried everything I can possibly find on the interwebs and nothing I do makes any difference at all. I am trying to send out email with sendmail on my linux box. The larger picture is I need to send off emails when a process fails or crashes on a node server, my company does not have smtp by choice, so I am looking into using sendmail through nodemailer. Needless to say it isn't working correctly. I am not getting an error, but the mail never goes through, so I decided to go more basic and just test sendmail through the terminal, and I can't get any mail to send at all. I have gone into the /etc/mail directory and edited both the sendmail.mc and submit.mc files to get a fully qualified domain name, I found a quick tutorial online that said to add the following to the sendmail.mc file...
Dmbar.com
define('confDOMAIN_NAME', '$w.$m')dnl

So I added that and then ran the 'sendmailconfig' command to update the app, then just to be safe I ran the '/etc/init.d/sendmail restart' command to restart the sendmail daemon.
Then I run the sendmail command to test send an email like so...
sendmail -t < email.txt

Where the contents of email.txt are simply...
to:realemail@gmail.com
from:myemail@mydomain.com
subject: Test email

test test etst

yes the "realemail@gmail.com' is not where it was sent, there is a real email in that line, and the 'myemail@mydomain.com' is not what is in the file either, that is replaced with an actual email address.
Still no mail goes through. When I bring up the 'sendmail -bp' command I get things like...
 u4KJaAJF030710readqf*  -1   Fri May 20 12:36  <****@***********>
             (Deferred: Connection refused by alt4.gmail-smtp-in.l.google.)
                 <realemail@gmail.com>

yes I replaced the sender with *****, but safe to say it is using computeruser@computername and not the from in the mail file, nor the DOMAIN_NAME that has been defined in the .mc file.
I am really lost here, nothing I do seems to matter, I can't get this to send an email and I really need this running. I have been scouring the internet all day and everything I find is either, add that define line in to the sendmail.mc file, or just simple commands on how to actually send the mail, I can't find anything that would help as to why this isn't sending any emails. I can, however, hop into a PHP page and successfully send an email with the "mail" PHP function just fine, so I know my system is able to send emails correctly.
I am begging for any help at all, email is not my strong suit, so any help is greatly appreciated. Thank you.

A: Found the issue finally. It turns out that Comcast does not allow any communications on port 25, so all of my emails are getting blocked. Pain in the ...!


text:
Q: .htaccess rewrite url don't do it I'm new with htaccess configurations and I need your help.
I have this url:
http://www.mypage.com/page/web/controller/index.php
and I don't want to show the
page/web/controller/index.php
please how can I do this?
this is my actual .htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^mypage.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.mypage.com$
RewriteCond %{REQUEST_URI} !mypage/web/
RewriteRule (.*) /page/web/$1 [R=301,L]
RewriteRule ^page/web/(.*)$ $1 [R=301,L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php
RewriteCond  %{HTTP_HOST} ^mypage.com$[OR]
RewriteCond %{HTTP_HOST}  ^www.mypage.com$
RewriteRule  (.*) "http\:\/\/mypage\.com\/page\/web\/" [R=301,L]

A: You can redirect from http://www.mypage.com/page/web/controller/index.php to http://www.mypage.com
just add header("location: http://www.mypage.com") to the top of ../web/controller/index.php and add an index.php to root directory this will redirect you to http://www.mypage.com/index.php.
This is not the solution you are looking for but could be an alternative solution.
And this link may help
Thank you :)


text:
Q: Angular issue in IntelliJ I am facing following issue while working on an angular component in IntelliJ.

Why do I face it and how to solve it?

A: You need to make sure that your component is added to an NgModule, and that this module has either CommonModule or BrowserModule imported. Either directly, or through a common module import.
Make sure to only import the BrowserModule once in your app though


text:
Q: Add an auto fill search box on a sharepoint list I don't have any experience with custom code and needed some help to upgrade a site.
I have a list [coreitemslookup] with three columns:
Title,
Description &
Related keywords
This list is on a SharePoint site added as a webpart.
I wanted to add a custom search (using script editor) on the site. It needs to have an auto-fill capability so that when you search, it gives suggestions, and displays matching keywords found in any of the columns in the list.
Would appreciate all the help I can get.
P.S I am using Sharepoint online on a modern page.


text:
Q: Jupyter Notebook Python Project: Stock Analysis Using Plotly-Dash I am working on Stock Analysis using Dash and Plotly Project in Jupyter Notebook (Python = 3.7.6).
I have taken 3 stock markets i.e Hang Shang of Honk Kong, S&P500 of USA and Nifty500 of India. I am getting the outputs of first two markets like Live Predictions Graphs but in India's case, nothing's showing up.
Could anyone help to get the Indian market forecast charts as well?
Thank You :)
Code:
import pandas as pd
from jupyter_plotly_dash import JupyterDash
import re
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import yfinance

app = dash.Dash()

app.layout = html.Div([
    dcc.Tabs(id='dashboard-tabs', value='price-tab',children=[
        dcc.Tab(label='Stock Price', value='price-tab',children=[
            html.Div([html.H2(id='tab1-stock-name',
                           style={'width':'30%','display':'inline-block'}),
                      html.H4(id='tab1-ticker',
                           style={'width':'10%','display':'inline-block'})],
                      style={'width':'90%','margin':'auto'}),

            html.Div(get_tab1_info_box(),
                     style={'width':'90%','margin':'auto'}),
            # Position 1, Info and dropdown
            html.Div(get_stats_graph_layout('tab1'),
                     style={'width':'90%','margin':'auto'})
            # Position 2, Table of stats and graph
            ]), # Tab 1, End price-tab
        dcc.Tab(label='Stock/Index Growth', value='change-tab',children=[
            html.Div([html.H2('Stock Price Growth vs. Index Growth')],
                     style={'width':'90%','margin':'auto',
                            'text-align':'center'}),
            # Position 0, Title
            html.Div(get_tab2_info_box(),
                     style={'width':'90%','margin':'auto'}),
            # Position 1, Info and dropdown
            html.Div(get_stats_graph_layout('tab2'),
                     style={'width':'90%','margin':'auto'})
            # Position 2, Table of stats and graph
            ]) # Tab 2, End change-tab
        ]) # End Tabs
    ]) # End base Div

def verify_ticker(ticker, mkt):
    if mkt == 'hk':
        tick = re.findall('^\d{1,5}$', ticker)
        if len(tick)>0:
            tick = str(tick[0])[::-1]
            while(len(tick)<4):
                tick += '0'
            tick = tick[::-1]
            tick += '.HK'
            return True, tick
        else:
            return False, None
    elif mkt == 'us':
        tick = re.findall('^[A-Za-z]{1,4}$', ticker)
        if len(tick)>0:
            return True, tick[0].upper()
    elif mkt == 'ind':
        tick = re.findall('^[A-Za-z]{1,4}$', ticker)
        if len(tick)>0:
            return True, tick[0].upper()
        else:
            return False, None
    return False, None

# Obtain 50- ,100- and 200-day moving average
def getMA(stock, time, date_list):
    if 'mo' in time or time=='ytd' or time=='1y':
        df = stock.history(period='2y')
    elif time=='2y' or time=='3y' or time=='4y':
        df = stock.history(period='5y')
    else:
        df = stock.history(period='10y')
    df = df.reset_index()[['Date','Open','Low','High','Close']]
    df['MA50'] = df.Close.rolling(50).mean()
    df['MA100'] = df.Close.rolling(100).mean()
    df['MA200'] = df.Close.rolling(200).mean()

    df = df.loc[(df['Date']>=date_list.min()) & (df['Date']<=date_list.max())]
    return df

# Generate stock price and graph on Tab 1
@app.callback([Output('tab1-stock-name','children'), # Stock Name
               Output('tab1-ticker','children'), # Ticker
               Output('tab1-stock-price','children'), # Current Stock Price
               Output('tab1-stock-price-change','children'), # Price Change
               Output('tab1-stock-price-change','style'),
               # Price Change font colour
               Output('tab1-stock-price-percentchange','children'),
               # Price Percent Change
               Output('tab1-stock-price-percentchange','style'),
               # Price Precent Change font colour
               Output('tab1-error-message','children'), # Error Message
               Output('tab1-vis','figure'), # Stock Price Chart
               Output('tab1-table','children')], # Table of Stock Stats
              [Input('tab1-submit','n_clicks'), # Button
               Input('tab1-time-interval','value')], # Time interval
              [State('tab1-ticker-input','value'), # Ticker textbox input
               State('tab1-market-dropdown', 'value')]) # Market Dropdown input
def get_ticker(n_clicks, time, ticker, mkt):
    # For default setting
    if ticker == '':
        return 'Please Enter a Stock Ticker', \
               '','','',{'width':'20%', 'display':'inline-block'},'', \
               {'width':'20%', 'display':'inline-block'},'', \
               {'data':None}, None
    # Verify ticker format in respective to stock market
    stockFormat, ticker = verify_ticker(ticker, mkt)
    # Catch incorrect
    if stockFormat is False:
        return 'Wrong Ticker', '#######', '$##.##', '##.##', \
               {'width':'20%', 'display':'inline-block'}, '##.##%', \
               {'width':'20%', 'display':'inline-block'}, \
               'Error! Please try again.', {'data':None}, None
    # Obtain stock price and stats
    stock = yfinance.Ticker(ticker)
    # Catch if stock exists
    if stock.history(period='ytd').shape[0] == 0:
        return 'Wrong Ticker', '#######', '$##.##', '##.##', \
               {'width':'20%', 'display':'inline-block'}, '##.##%', \
               {'width':'20%', 'display':'inline-block'}, \
               'Error! Please try again.', {'data':None}, None
    ### Stock Stats for Info Box ###
    try:
        # Name and price
        stock_name = stock.info['longName']
        price_list = stock.history(period=time)['Close'].tolist()
        price = f'${price_list[-1]:.2f}'
        # Price Change
        price_change = price_list[-1] - price_list[-2]
        price_percent_change = (price_list[-1]/price_list[-2])-1
        if price_change > 0:
            price_change_colour = {'color':'green'}
        else:
            price_change_colour = {'color':'red'}
        price_change_colour['display']= 'inline-block'
        price_change_colour['width']= '20%'
        price_change_colour['font-size'] = '150%'
        price_change = f'{price_change:.2f}'
        price_percent_change = f'{price_percent_change*100:,.2f}%'

        df = getMA(stock, time,
                   stock.history(period=time).reset_index()['Date'])

        fig = getCandlestick(df)
        table = getTab1Table(stock.history(period=time).reset_index(),
                             stock.info)

    except:
        return 'Sorry! Company Not Available', '#######', '$##.##', '##.##', \
               {'width':'20%', 'display':'inline-block'}, '##.##%', \
               {'width':'20%', 'display':'inline-block'}, \
               'Error! Please try again another Company.', {'data':None}, None

    return stock_name, ticker, price, price_change, price_change_colour, \
           price_percent_change, price_change_colour, '', fig, table

@app.callback([Output('tab2-stock-include','options'),
               Output('tab2-stock-include','value')],
               [Input('tab2-index-choice','value')])
def generate_dropdown_stocknames(mkt):
    if mkt == 'hsi':
        stock_list = pd.read_csv('C:\\Users\\Pranav Jaswal\\Desktop\\StockAnalytics-master\\IndexComponents\\HengSengStockList.csv',
                     dtype=str)
        stock_list = stock_list.sort_values('Ticker')
        stock_list['label'] = stock_list['Ticker'].astype(str) + '\t' + \
                              stock_list['Company']
        opts = [{'label': label, 'value': ticker} for label, ticker in
                zip(stock_list['label'].tolist(),
                    stock_list['Ticker'].tolist())]
        return opts, []
    elif mkt == 'sp500':
        stock_list = pd.read_csv('C:\\Users\\Pranav Jaswal\Desktop\\StockAnalytics-master\\IndexComponents\\SP500StockList.csv',
                                 engine='python')
        stock_list = stock_list.sort_values('Ticker')
        stock_list['label'] = stock_list['Ticker']
        opts = [{'label': label, 'value': ticker} for label, ticker in
                zip(stock_list['label'].tolist(),
                    stock_list['Ticker'].tolist())]
        return opts, []
    elif mkt == 'nifty500':
        stock_list = pd.read_csv('C:\\Users\\Pranav Jaswal\\Desktop\\StockAnalytics-master\\IndexComponents\\ind_nifty500list.csv',
                                 engine='python')
        stock_list = stock_list.sort_values('Ticker')
        stock_list['label'] = stock_list['Ticker']
        opts = [{'label': label, 'value': ticker} for label, ticker in
                zip(stock_list['label'].tolist(),
                    stock_list['Ticker'].tolist())]
        return opts, []
    return [], []

@app.callback([Output('tab2-table','children'),
               Output('tab2-vis','figure')],
              [Input('tab2-index-choice','value'),
               Input('tab2-stock-include','value'),
               Input('tab2-time-interval','value')])
def generate_tab2_graph(mkt,stocks,time):
    # Function to calculate price change relative to the first day
    def get_price_change(price_list):
        base_price = price_list[0]
        return [(price/base_price)-1 for price in price_list]

    df_stocks = []
    if len(stocks) > 0:
        for stock in stocks:
            if mkt=='hsi':
                stock = stock[1:] + '.HK'
            stock_df = yfinance.Ticker(stock).history(period=time)
            stock_df = stock_df.reset_index()[['Date','Close']]
            stock_df.columns = ['Date',stock]
            df_stocks.append(stock_df)

    y_ticker = None
    index_col = None
    if mkt == 'hsi':
        y_ticker = '^HSI'
        index_col = 'Heng Seng Index'

    elif mkt == 'sp500':
        y_ticker = '^GSPC'
        index_col = 'S&P 500'
    elif mkt == 'nifty500':
        y_ticker = '^NSEI'
        index_col = 'Nifty 50'
    else:
        return html.Table(), {'data': None}

    # Prepare the data set to plot the line chart
    index = yfinance.Ticker(y_ticker)
    df_index = index.history(period=time).reset_index()[['Date','Close']]
    df_index.columns = ['Date', index_col]
    # To take out duplicated columns, ie, Date, while concat
    if len(stocks) > 0:
        for df_temp in df_stocks:
            df_index = pd.merge(df_index, df_temp, how='left',on='Date')
        # In case there are NA's, fill with last observation
        df_index = df_index.fillna(method='backfill', axis=1)
        # Drop duplicated columns in case there are
        df_index = df_index.loc[:,~df_index.columns.duplicated()]

    # Convert from price to percent change relative to Day 1 of the period
    for col in df_index.columns:
        if col != 'Date':
            df_index[col] = get_price_change(df_index[col].tolist())
    fig = getLinePlot(df_index, 2)

    # Prepare the data set to list the summary on the table
    last_close = df_index[index_col].tolist()[-1]*100
    df_index_period = index.history(period=time).reset_index()
    df_index_52weeks = index.history(period='1y').reset_index()
    range_period = (round(df_index_period['Close'].min(),2),
                    round(df_index_period['Close'].max(),2))
    range_52weeks = (round(df_index_52weeks['Close'].min(),2),
                     round(df_index_52weeks['Close'].max(),2))
    volume = (index.history(period=time).reset_index()['Volume'].tolist()[-1],
              index.history(period=time).reset_index()['Volume'].mean())
    # Generate a table of summary
    table = getTab2Table(index_col, last_close, range_period, range_52weeks)

    return table, fig

if __name__ == '__main__':
    app.run_server(debug=False, port=8000)


text:
Q: Can TextEdit save as plain text? When I try to save a new file in TextEdit, I always get a popup saying I can't save with ".txt" at the end of the file name.
I want to save a plaintext file, but TextEdit insists on saving as .rtf instead. It also lists .doc, .odt, .html, and some others.
How can I save a TextEdit document as plain text?

A: The format menu has a toggle to switch things for you.
Pressing shift + command + T will toggle the document to plain text mode.

You can also set the default format in the preference pane for the app.


text:
Q: Select a tag nested in layers of divs all!
I am having a problem with selecting the
s separately from each other. I want to style the first
 differently than the second
.
It would be much easier (and wouldn't need to be asked here) to assign a class/id to those
s but I cannot do that because I am using a WordPress theme.

Thank you!

A: What about this:

.wrapper > div:first-child p.a {
  color:red;
}
.wrapper > div:last-child p.a {
  color:blue;
}

aa

bb

aa

bb

A: Just select it with nth-of-type and the direct descendant selector.
nth-child works too if this is the exact structure and not any different element besides
 in that

.wrapper > div:first-of-type p.a {
  color:blue;
}
.wrapper > div:nth-of-type(2) p.a {
  color:pink;
}

aa

bb

aa

bb


text:
Q: Java EE declarative security, acquiring reference to a secured bean from application client On 2 questions I would like to consult you.
Background: I have written a test, Java EE application and added declarative security. The application is deployed on Glassfish 3.1. For unit testing I used JUnit with the embedded container for all beans with local interface. For the entry point of the appliaction, the SessionFacde bean, which has the only remote interface, I wrote a simple client which acquires reference to the SessionFace bean. Security annotations I applied for the SessionFacade bean only.
(Question 1: What is the recommended unit testing strategy with security? Is it all right if I utilize a simple application client for the sessionFacade? (The other (local) beans are not affected as no security annotations are applied there.))
Question 2: How should I access the SessionFacde form the appliaction client? I would really appriciate if you could copy here some code samples for the application-client.xml and acquiring a reference to the JNDI service. This would spare me a lot of time. The question is similar to the one under Java EE 6 Application Client login but I found an explanation (http://docs.oracle.com/cd/E18930_01/html/821-2418/beacm.html) that it is not really recommended as it loads the burden of security back to the developer instead of the framework. See the below text:

"[...]Programmatic login allows the application developer to bypass
  the GlassFish Server-supported authentication mechanisms and feed
  authentication data directly to the security service. While flexible,
  this capability should not be used without some understanding of
  security issues.
Since this mechanism bypasses the container-managed authentication
  process and sequence, the application developer must be very careful
  in making sure that authentication is established before accessing any
  restricted resources or methods. It is also the application
  developer's responsibility to verify the status of the login attempt
  and to alter the behavior of the application accordingly.
The programmatic login state does not necessarily persist in sessions
  or participate in single sign-on.[...]"

Thank you that you have read it so far.
Kind regards,
Tamas
Remark: As there has been no response since I wrote the original post, I would say it would be enough to answer the second question. It would help me to go on. Thanks, Tamas


text:
Q: Accessing the content database directly - SharePoint Is accessing a content database is not a 'best practice/advisable' or it 'should' not be done as Microsoft does not support it? I just want to know if it 'can' be done in the worst case or it 'should not be done' at all.

A: For worst case scenario or any normal scenario till the time you are making readonly request to content database its fine. the only risk associated with this is since microsoft does not recommends the same they can change thier internal DB structure any time during  hotfix or SP release. Be causious in accessing the data so that you do not cause any lock or dead lock type situations

A: You should not access a ContentDB directly. The access to any SharePoint DBs can void your support for the farm, and yes, this includes READING from the DB.
See: http://support.microsoft.com/kb/841057/en-us
[...]
Examples of such database changes include, but are not limited to, the following: Reading from the database, manually or programmatically Adding database triggers:
Adding database triggers
Adding new indexes or changing existing indexes within tables
Adding, changing, or deleting any primary or foreign key relationships
Changing or deleting existing stored procedures
Calling existing stored procedures directly
Adding new stored procedures
Adding, changing, or deleting any data in any table of any of the databases for the products that are listed in the "Applies to" section
Adding, changing, or deleting any columns in any table of any of the databases for the products that are listed in the "Applies to" section
Making any modification to the database schema
Adding tables to any of the databases for the products that are listed in the "Applies to" section
Changing the database collation
Running DBCC_CHECKDB WITH REPAIR_ALLOW_DATA_LOSS (However, running DBCC_CHECKDB WITH REPAIR_FAST and REPAIR_REBUILD is supported, as these commands only update the indexes of the associated database.)

A: Well, I wish I could give you a firm answer BUT I can say this; if you are looking for a "worst case senario" then hook your SharePoint list up to an Access db and pull it all down via a link table.  That way you can copy into a 'real' table.
That is if that is what you're looking to get to.
If you're looking to just do reporting on it, then TOTALY use link tables in Access and report off of them.  It'll be safe and it will be real-time.


text:
Q: I have to design a bootloader for Kinetis E series controller. What are the prerequisites to write a general bootloader code ? To write a C code, the priori knowledge about main function, function declaration and definition, variable declaration and initialization is required, similarly to write a bootloader code what all priori knowledge is required.Say that code should toggle an LED when system starts booting.

A: For reference a bootloader on a microprocessor is a small app that is resident on the microprocessor that can be used to download larger 'main' apps into the program memory.
What you need to know in order to implement a bootloader depends very much on the processor you are targeting, but the following list is a start:

*

*Details of processor memory map - in particular are any parts of your memory reserved or protected for use by the bootloader. Will you need to run the bootloader from RAM while the main program memory is erased?

*Details of interrupt vectors and how these will be directed / redirected to your user application.

*How you will implement a recovery strategy if something goes wrong during download of new main app.

*How to erase and write the 'user' parts of your program memory.

*How to configure your processor at power up - set input /output directions, crystal dividers, peripheral initialisations and so on

*What communication mechanism and protocol (eg serial, USB, Ethernet) you will use to communicate and receive the main application from a remote system

*How your processor will (re)enter bootloader mode. After you have downloaded your main app how will you return to the bootloader?

*How your bootloader process will synchronise with software on remote system.


text:
Q: Login page not redirect to target location in PHP? Hi everyone please help i have developed my first website www.ncrwallpaper.com its under testing.
My problem is that whenever i login on from login page.
1st its not redirect to target page
2nd its already logged in but in current page its not showing..
here is my code
<?php
session_start();
include('dbfunctions.php');
include_once('top.php');

if(isset($_POST['login'])) {
    $a=$mysqli->real_escape_string($_POST['email']);
    $b=$mysqli->real_escape_string($_POST['pass']);
    $c=$mysqli->query("select * from users where email='$a' and pass='$b'");
    $count=$c->num_rows;

    if($count==1){
        $f=$c->fetch_object();

        //value assign in session_id
        $_SESSION["id"]=$f->id;
        $_SESSION["email"]=$f->email;
        $_SESSION["name"]=$f->name;
        $_SESSION["contact"]=$f->contact;

        if(isset($_SESSION['url'])) $url = $_SESSION['url']; // holds url for last page visited.
            else $url = "index.php";

        header("Location: $url");
    } else echo "Please enter valid email id and password";
}

?>

this code is already working on localhost
<form action="#" method="post" enctype="multipart/form-data">
    <input type="email" name="email" placeholder="E-Mail Address" id="input-email" class="form-control" required autofocus/>
    <input type="password" name="pass" placeholder="Password" id="input-password" class="form-control" required/>
    <input type="submit" value="Login" class="btn btn-primary" name="login" />
</form>

A: You can't use header after you output something which will be the css in the top.php you have 3 options you use  javascript , output buffering or a meta refresh to redirect
echo '<meta http-equiv="refresh" content="0; URL=' . $url . '">';

the 0 is the delay how long the site should be shown till it refreshes

A: You could use ob_start() & ob_end_clean()
<?php
ob_start();
session_start();
include('dbfunctions.php');
include_once('top.php');

if(isset($_POST['login'])) {
    $a=$mysqli->real_escape_string($_POST['email']);
    $b=$mysqli->real_escape_string($_POST['pass']);
    $c=$mysqli->query("select * from users where email='$a' and pass='$b'");
    $count=$c->num_rows;

    if($count==1){
        $f=$c->fetch_object();

        //value assign in session_id
        $_SESSION["id"]=$f->id;
        $_SESSION["email"]=$f->email;
        $_SESSION["name"]=$f->name;
        $_SESSION["contact"]=$f->contact;

        if(isset($_SESSION['url'])) $url = $_SESSION['url']; // holds url for last page visited.
            else $url = "index.php";

        $output = ob_get_contents();
        ob_end_clean();
        header("Location: $url");
    } else echo "Please enter valid email id and password";
}

?>

A: try this in place of your header
<script type="text/javascript">
window.location.assign('your desired location');
</script>

Note:close php before script tag and open php after closing script tag

A: <?php
session_start();
include('dbfunctions.php');
?>
<?php include_once('top.php'); ?>
<?php
if(isset($_POST['login']))
{
$a=$mysqli->real_escape_string($_POST['email']);
$b=$mysqli->real_escape_string($_POST['pass']);
$c=$mysqli->query("select * from users where email='$a' and pass='$b'");
$count=$c->num_rows;
if($count==1){
$f=$c->fetch_object();
//value assign in session_id
$_SESSION["id"]=$f->id;
$_SESSION["email"]=$f->email;
$_SESSION["name"]=$f->name;
$_SESSION["contact"]=$f->contact;
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php";

echo " <script type=\"text/javascript\">
window.location.assign('blaahh.php');
</script> ";
}
else{
echo "Please enter valid email id and password";
}

}

?>

A: You will need some JS. Just put this code in your header:
 ?> // close php
<script type="text/javascript">
window.location.assign('location');
</script>
<?php // open php again

A: PHP:
header("Location: yourpage.php");
exit;

You have to use exit or die after header in order to stop execution of your code. Also, the code has to be executed before any output.


text:
Q: Promise from check login method is not returning the promise to canActivate() I have the following login method:
login(username, password)
  {
    let headerOptions = new HttpHeaders();
    // headerOptions.append('Access-Control-Allow-Origin', '*');
    // headerOptions.append('Access-Control-Request-Headers', '*');
    // headerOptions.append('Content-Type', 'application/json');
    // headerOptions.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
    headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

    this.credentials = {user: username, pass: password};
    const httpParams = new HttpParams()
      .set('username', username)
      .set('password', password);

    //console.log("hi "+ this.credentials);
    return this.http.post('http://dev.local/scripts/login.php', httpParams,  {
      headers: headerOptions,
    })
}

And when a user is successfully logged in, a JWT array is returned into local storage, so we can check the role, and if it's still logged.
There is a component where only admins has the right to access it, so when a user click on the route:
{
    path: 'forgot',
    component: ForgotPasswordComponent,
    canActivate: [AuthGuardService]
},

An authGuard will run using the canActivate() guard.
canActivate(_route: ActivatedRouteSnapshot,
              _state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean
  {
    if(this.authApi.checkIsLogin())
    {
      return true;
    }
    else
    {
      return false;
    }
}

Now to check the checkIsLogin(), the following script a executed to return a promise:
checkLoggedInAdmin()
  {
    //Get the JWT token from local storage
    let jwt = localStorage.getItem('jwt');
    let httpParams = new HttpParams().set('jwt', jwt);
    let headerOptions = new HttpHeaders();
    headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

    const promise = new Promise(
      (resolve, reject)=>{
        if(jwt!="" || jwt!=null || jwt!=undefined)
        {
          this.http.post('http://dev.local/scripts/checkLoginAdmin.php', httpParams, {
            headers: headerOptions
          }).subscribe(
            (data)=>{
              if(data==true)
              {
                this.loggedIn=true;
              }
              else{
                this.loggedIn = false;
              }
            }
          )
        }
        else
        {
         this.loggedIn=false;
        }

        resolve(this.loggedIn),
        reject(this.loggedIn)
      }
    )
}

Where loggedIn is defined as boolean on top of the class.
And here is the function checkIsLogin():
checkIsLogin(){
    return this.loggedIn
}

When a user logged in, a jwt is returned, with all necessary details. But if it's an admin, and when clicking on the desired route, nothing happened, and no code is executed, with no errors at the console.


text:
Q: Multiple imputation for non-parametric tests on small sample? I am new to multiple imputation, so apologies if the question is naive. I have been exploring multiple imputation for use on a small data set where there are just a couple of data points. I would like to run Wilcoxon signed-rank tests using the pooled imputations. However, SPSS doesn't provide pooled test statistics for non-parametrics because "Rubin's rules... don't address nonparametric tests". Consequently, SPSS calculates the statistics for each imputation, but not as a group. So I was wondering how useable this output is (e.g., should I report the statistic range) or is this indicative of a fundamental issue in trying to use multiple imputation with non-parametric tests. Because of these complexities and the small amount of missing data, I considered mean substitution instead but I appreciate that this approach is not optimal - although the overall findings remain the same either way.
Any advice would be greatly appreciated.

A: Not a naive question at all. I'm not an expert, but I think this is actually a rather difficult question.
As you may be aware, Rubin's Rules assume that the full-data estimate, $\hat{\theta}_{full}$, would be normally distributed. Then from the $M$ imputed estimates, $\hat{\theta}_{1}, \ldots, \hat{\theta}_{M}$, we average them to find the point estimate $\hat{\theta}_{imp}$ and also combine the within- and between- variances to estimate the variance of $\hat{\theta}_{imp}$, $\hat{\text{V}}[\hat{\theta}_{imp}]$. Then we can use traditional methods for normally distributed values to find confidence intervals and perform tests. If the estimates $\hat{\theta}_{i}$ are not normally distributed then this will not work.
My understanding is that the Wilcoxon signed-rank test statistic, $W$, is asymptotically normally distributed. So in contrast to the SPSS manual, I think you could pool the estimates if you had a large sample. Although if it isn't supported by SPSS you'd probably have to program the calculations yourself.
But, it sounds like your sample isn't nearly large enough to consider this. $W$ is not close to normally distributed in small samples. An alternative you could consider would be pooling the p-values from the imputed datasets themselves. I don't know enough to offer guidance on it, but you can read about the procedure in section 5.3.2 of Flexible Imputation of Missing Data, https://stefvanbuuren.name/fimd/sec-multiparameter.html#sec:chi. The basic idea is to transform the imputed p-values to be approximately normally distributed, pool those transformed values, then transform back to find the final p-value. You can see some sample code in this answer, How to get pooled p-values on tests done in multiple imputed datasets?
Of course, if the amount of missing data is very small, you could consider using a complete-case analysis instead. The results would probably be very similar.


text:
Q: Lowest common ancestor in igraph Suppose we have a tree in igraph:
library(igraph)

g <- make_tree(14, children = 3)
plot(g, layout = layout_as_tree)

Created on 2019-12-21 by the reprex package (v0.3.0)
How do we find the lowest common ancestor (LCA) of an arbitrary collection of nodes? That is, in the above example

*

*The LCA of 7 and 14 is 2.

*The LCA of 6, 9, 12, and 14 is 1.

*The LCA of 1 and 8 is 1.

*The LCA of any node is itself.

And so on.
It feels like there ought to be an elegant way of doing this in igraph, but I haven't managed to find it. I played around with intersections of calls to all_simple_paths, but since I don't have a good way to get the levels of each node, this didn't help.
I am aware that many of the phylogenetics packages implement this for other data structures, but I would rather avoid the interconversion if there is a reasonable solution on the graph. (I'm perfectly happy with a tidygraph solution, however.)

A: For a tree, you can get the paths from a node to the root. Then find the highest index for the intersection beteen the paths:
lca <- function(graph, ...) {
  dots = c(...)
  path = ego(graph, order=length(V(graph)), nodes=dots, mode="in")
  max(Reduce(intersect, path))
  }

lca(g, 7, 14)
lca(g, 10, 8)

A: At least for modest size graphs, you can do this from the distance matrix between points. x is an ancestor of y if and only if there is a path from x to y. Also, if the index of x > index of y,  x is no higher than y in the tree.
DM = distances(g, V(g), mode="out")
LCA = function(NodeList) {
    max(which(rowSums(is.infinite(DM[,NodeList])) == 0))
}
LCA(c(7,14))
2
LCA(c(6,9,12,14))
1


text:
Q: Open a Colorbox within a div block instead of whole page I am currently building a Jquery interactive game and I'm using the jQuery Colorbox plugin to show messages to user.
The thing is, all the game is inside a div and I need that Colorbox to open inside that div (that container div is overflow:hidden).
I want Colorbox to work the same way it does by default, centered, but in a div block instead of the whole body.
I tried to change this line in colorbox.js:
$(document.body).append($overlay, $box.append($wrap, $loadingBay));

Into this:
$("#game").append($overlay, $box.append($wrap, $loadingBay));

But it isn't working. Do you have any idea?
Thank you so much!

A: A little late on this answer...
Im looking at line 300 of jquery.colorbox.js.
Change:
$window = $(window);
TO:
$window = $(".Class");


text:
Q: Show output on Tkinter gui, in real time(dynamically) I am working on a python program that generates output continuosly, Depending upon the user input. I am unable to show this output on Tkinter gui. Without tkinter it just works perfectly on terminal. Could you please suggest some code that will show the output on thr gui.
Here is my python code: Program 1:-
print "Enter a file name:",
filename = raw_input()
print filename

This program is executed with gui using second program. Program 2:-
import os
from Tkinter
import * root = Tk()
t = Text(root)
t.pack()
def go():
    p = os.popen("python hello.py")
    for l in p.xreadlines():
    t.insert(END, '%s\n' % l.rstrip())
    t.see(END)
    t.update_idletasks()

Button(root, text='Go', command=go).pack()
root.mainloop()

Now I want the output to be shown inside tkinter GUI.


text:
Q: (Python) locate certain field of image from image I want to extract certain part from the image
I am running Python 3.9.12 with CV2 4.6.0 on Ubuntu 22.04.1 LTS
(From) The original pic:
https://ibb.co/RcZ7ntL
(then) The pic want to locate(I want to extract the red part only):
https://ibb.co/dGBfqXx
(the desire pic/output) : https://ibb.co/j5h501f
I've tried searching for a solution on StackOverflow, but I didn't find anything remotely similar. And I search that most of the tutorial is teaching finding the same image in image.
In case someone doesn't want to load too many pics, I put them as link instead.
so my main issue is that not sure how to cut them into the picture I want

this is after I manual cut to the part I want, then I can do OCR recognize image to text
the desire pic/output : https://ibb.co/j5h501f
the pic I success detect the image to text:  https://ibb.co/mv9WTpW

I come up a idea [solution A]

*

*that using openCV bounding box cut every sticker separated https://ibb.co/1Q9DnLJ

*cause every line is fixed distance (ex: CA74C8), then give cv the correct scale to cut

how to make [solution A] step 1 work? I have tried for half of a day but still stock on this, I need a hand thanks

A: You can do the reverse task:
run your OCR first, since it will find all texts in the image for you.
If you you tesseract, it will send you all the text AND the locations/boxes where the text is found.
like here:


text:
Q: Why two if statement working like if and else statement
My problems is kinda confusing, you dont have to read the whole code
  just check the function showOrder()

What  i am trying to do in the showOrder is simply this, that when ever person click on the edit button, it should display  the form, which is fine, but as soon as click on the edit button, its not displaying me the item, please read below what i am trying to say,
like lets say i have theese two items, and this is my first out put
Cook Dinner
Eat Dinner

so now lets say i click on the Cook Dinner 4 items, so my out put look like this
Cook Dinner
4 Cook Dinner [Edit Button]
Eat Dinner

Up untill now every thing is fine, but now what i want to happen is this, that when i click on Edit Button, it should leave  4 Cook Dinner as it is, and below it should display me the form, to leave notes, basically i want my output to like this
Cook Dinner
4 Cook Dinner [Edit Button] //Please read the notes below as well
//Display the form, to leave the notes,
Eat Dinner

Notes for above output : It displaying me the form, but it removing the 4 Cook Dinner line
and i am kinda confuse, because to acheive it, i am using, showOrder() function with two if statement,
First if statement basically saying if orderEditing is true display the form,
and Second if statement is basically saying if quantity greater than zero, display the quantity and task
But instead displaying both of them, these two working like if and else statement, can some body explain me why??,
The only logical explanation is this, that one function can only have one statement, but still not clear to me any confusion please let me know.
import React from 'react'
const order = [];

export default class Header extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            quantity:0,
            editing:false,
            orderEditing:false,
            order
        }
    }

    displayMenu ()
    {
        return (

        {this.props.task}

        <button onClick={this.onEdit.bind(this)}>Edit</button>

        );
    }
    onEdit()
    {
        this.setState({editing:true})
    }

    handleMenu()
    {
        this.setState({quantity:this.state.quantity+1});

    }

    showOrder()
    {

        if(this.state.orderEditing==true )//***First if statement
        {
            console.log(this.state.orderEditing) /* OutPut -- False*/
            console.log(this.state.quantity)    /* OutPut -- 4*/
            return (
            <form>
            <input type='text' defaultValue={this.state.quantity} size='1'/>
            <input type='text' placeholder='Notes'/>
            </form>
            );
        }//closing of first if statement

        if(this.state.quantity>0)//*** Second if statement
        {
            console.log(this.state.orderEditing)    /* OutPut -- true*/
            console.log(this.state.quantity)        /* OutPut -- 4*/
            return (

            {this.state.quantity } {this.props.task}
            <button onClick={this.editOrder.bind(this)}>Edit</button>

            );
        }
    }//closing of second if statement.

editOrder()
{
    this.setState({orderEditing:true})
}

    render(){

        return (

        {this.displayMenu()}
            {this.showOrder()}

        );
    }
}

A: When you return within your function, the code after the return block will not execute. That is why if the first condition is true, the second one will not render. If you wanted to display both individually, you could always put them into two separate functions that have their own returns.

A: In React, components can be expressed as regular JavaScript functions and as functions, they behave exactly the same way.
As soon as any condition is met your showOrder function returns with the result of one of those branches and no other code is executed. The first condition that passes the test takes it all. Your example can be reduced to:
function f() {
    if (condition1) return a;
    if (condition2) return b;
}

In order to render (return) multiple results, you must wrap your result with some container element, most likely a div. Then you can conditionally render components using logical AND (&&) operator. React doesn't render some falsy values (null, false, undefined).
Fixed showOrder function may look like this:
showOrder() {
    return (

            {this.state.orderEditing && <form>Render form here</form>}
            {this.state.quantity > 0 &&
Render edit button here
}

    );
}


text:
Q: R converts dates into a wrong format (year to a 5 digit number) I have loaded a txt dataset into R. A part of it can be seen below:
date    rf
1   19620102 0.011
2   19620103 0.011
3   19620104 0.011
4   19620105 0.011
5   19620108 0.011

I have tried to convert the dates using the following code:
df$date <- format(as.Date(df$date), "%Y-%m-%d")

This gives the following results, that are not what I wanted:
date    rf
1   55688-01-06 0.011
2   55688-01-07 0.011
3   55688-01-08 0.011
4   55688-01-09 0.011
5   55688-01-12 0.011

I wanted to convert the dates into the format as seen below:
date    rf
1   1962-01-02 0.011
2   1962-01-03 0.011
3   1962-01-04 0.011
4   1962-01-05 0.011
5   1962-01-08 0.011

Does anyone know how I can get the results that I want?

A: This works
as.Date("19620102", "%Y%m%d")
#> [1] "1962-01-02"

Created on 2021-02-06 by the reprex package (v0.3.0)
So just do
as.Date(as.character(df$date), "%Y%m%d")

A: We could also use ymd from lubridate
library(lubridate)
ymd(19620102)
#[1] "1962-01-02"


text:
Q: jqGrid: double clicking a row twice needs to be disabled I have a jqgrid named: grid2.
When I click on a row it starts editing it and adds some small editing icons aside.
But if I double click once again (or hundreds again) in that editing input, it appends over and over the icons causing a mess.
ondblClickRow: function(id){
$("#grid2").editRow(id);
displayEditIcons('grid2', id, 'id');
},

I need either to suprime the twice double clicking event or remove the dbclick event handler for the input.
One clue would be to add this line inside jqGrid event:
$("#grid2 input").bind('dblclick',function(e){$(this).attr('disabled', 'disabled');});

but I need: 1. not to disable the input but the handler 2. It only works on the third click. 3. It should be working on all active row fields.
ps. I found the fix I found the fix in case someone is interested.
$("#grid2 input").bind('dblclick',function(e){ return false; });


text:
Q: Setting paths in Fish like in Bash? I've got this in my bash_profile, and I can't figure out the equivalent in Fish:
export PATH=$PATH:~/Dev/ark/bin
export PATH=$PATH:~/bin/
export PATH=$PATH:~/i386-elf/bin/
export GOPATH=~/Dev/gocode/
export PATH=$PATH:$GOPATH/bin

How do I do that in my fish configuration file? I've tried
set PATH $PATH:$GOPATH/bin

But that doesn't seem to work.
EDIT: I fixed my fish config to be
set -x GOPATH ~/Dev/gocode
set -U fish_user_paths $fish_user_paths ~/Dev/ark/bin ~/bin/ ~/i386-elf/bin $GOPATH/bin

But I dunno if you want to close the question or if anyone wants to submit an answer or...?

A: To set a custom environmental variable it appears that you use -x and then the path. For a persistent environmental variable, you have to set the fish_user_paths, which will append the given paths to your $PATH.
pathpathpathpath
set -x GOPATH ~/Dev/gocode
set -U fish_user_paths $fish_user_paths ~/Dev/ark/bin ~/bin/ ~/i386-elf/bin $GOPATH/bin


text:
Q: File Upload after a pre-selection of sub-folder via dropdown menu In this example, I'd like to realise a fileupload center where you could firstly choose a a output subfolder via a dropdown-select!
Second, you could choose a file which you want to uplaod via drag&drop function or browse-button and finally, you get further passed on to the target folder with its subfolders where you can watch all the entries!
Hereby, the problem is that the new url after the dropdown select (with attached sub-folder value to the url - eg.In the console, I can see that it correctly turns the original url: './DisplayDirectoryContents/uploads/' into './DisplayDirectoryContents/uploads/Kooperationen/'after choosing the subfolder 'Kooperationen' in the dropdown select) will not be passed on to the upload.php file and therefore the file doesn't get uploaded into the target folder!Instead of the target subfolder "Kooperationen" the file gets just uploaded into the "DisplayDirectoryContents"-folder - 2 levels down from where it's supposed to land!
Hierarchy of folders:

*

*DisplayDirectoryContents (here are the php-files)

*uploads with subfolders:

*Kontaktlisten, Kooperationen, Vorsorge

I've already tried to work with different approaches but the url string of the "move2folder" variable obviously is not passed on to the second php-file called upload.php!
If I try it with a fixed url value like: $moved2folder = './DisplayDirectoryContentss/uploads/Kooperationen/' it works fine! But, I'd like to solve it for the automated passed on choice of a subfolder out of the dropdown select!
Please, could anyone provide me with some hints to solve this issue? Which kind of code do I have to add to the upload.php in order to get the move2folder-url passed on and the file uploaded to the before chosen subfolder?

*

*fancy_fileupload.php (relevant parts)
enter code here

<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">

FileUpload Center

Select Output Folder

  <select class="fileupload" id="foldername" name="folder" onchange="weiterleitung();" style="color: #fff; background: #007a96; border-radius:0.3em; height:33px; font-size:0.9em; " enctype="multipart/forn-data">
            <option value=""> Select Folder ...</option>
            <option value="Kontaktlisten"> Kontaktlisten </option>
            <option value="Kooperationen"> Kooperationen </option>
            <option value="Vorsorge"> Vorsorge </option>
            <option value="cityviews"> cityviews </option>
            </select>

 Select Your File

                Drop Here

                Browse
<input type="file" name="upl" multiple>

 Find your fileuploads here

 </form>

*upload.php
enter code here
<?php

require 'fancy_fileupload.php';
$move2folder = $_POST['move2folder'];

// A list of permitted file extensions
$allowed = array('png', 'jpg', 'jpeg', 'svg', 'gif', 'ico', 'zip', 'xlsx', 'docx', 'pdf', 'mp4', 'avi', 'txt', 'mp3');

if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){

    $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
    $file_tmp = $_FILES['upl']['tmp_name'];
    $file_name = $_FILES['upl']['name'];
    /*$move2folder = "./DisplayDirectoryContents/uploads/Kooperationen/";*/

    if(!in_array(strtolower($extension), $allowed)){
        echo '{"status":"error"}';
        exit;
    }

    if(move_uploaded_file($file_tmp, $move2folder .$file_name)) {
        /*echo "The file was successfully uploaded!";*/
        echo '{"status":"success"}';
        exit;
    }

    }

/*echo '{"status":"error"}';*/
echo "Unfortunately. the file was not uploaded properly!";
exit;

?>

´´´


text:
Q: How to add legend on a bar chart? I have the following Bar chart:
Code to create it:
names = {'a', 'b',.....}
b = bar(cell2mat(data_plot'));
legend(b,names,'Location', 'eastoutside');
ylabel('Teest');

So, I want to add a legend to it, but not from each of the bars (blue, yellow, orange) but for the groups of bars(1, 2, 3 ,4 ...)
In names are saved all the names for the 12 groups, but I dont know how to set them as values for the legend. Instead I get other values that are describing each of the bars?
UPDATE: To be more clear, I don't want to change the values on the x-aches (1,2,..) with values from names. I want the (1,2..) to stay where they are and how they are, but instead I want to change the table on the right where I have a legend for the Blue, Orange and Yellow bars with values that would correspond to the (1,2,3..) with the ones from names.
Example: 1 are data from 'USA' so the first value in names is 'USA'. This means on the table on the right I want sth like 1: 'USA'

A: You can't do what you want directly, you need to plot each group at a time, see this related post on MATLAB Answers and this question on SO. Here's a workaround based on this, but the bars in each group have to be the same colour:
Y = rand(5,3);
names = {'a';'b';'c';'d';'e'};
colours = {'g';'r';'b';'y';'c'};
h = zeros(size(Y));
for k = 1:size(Y,1)
  h(k,:) = bar(3*k-2,Y(k,:),colours{k});
  hold on
end

xlim([0 15]);
set(gca,'XTick',[1 4 7 10 13]);
set(gca,'XTickLabel',{'1';'2';'3';'4';'5'});
ylabel('Test');

legend(h(:,1),names,'location','northeastoutside')

which produces the following:

A: EDIT: Leaving for Legacy's sake. Ignore. I misunderstood the problem and jumped to an answer I thought of instead of taking the time to read and test a solution.
Try set(gca, 'xticklabel', names);
Also be sure to check out the following on why:

*

*Video on how to change xtick marks

*Matlab Set Documenation

*Matlab GCA Documentation


text:
Q: Button spacing coming as different in Chrome, firefox and IE11 Since browse button(input control) looked different in these three browsers, I tried to make it look similar by making its opacity 0 and put a dummy button under it and make it look like user is clicking the dummy button(even made sure that browse control is of the same size of that of the dummy button) and it worked fine for IE 11.
When I tested the page in chrome and firefox, there were some spacing issues and also in Firefox, the width I have set for the input control is not working.
<input id="Browse" type="file" value="button" style="z-index:12; position:relative; left:0px;opacity:0; width:63px; display:inline-block">
     <asp:button ID="btnBrowse" runat="server" text="Browse" style="z-index:1;        position:absolute;left:595px; height:21.5px"/>
</input>

This is what I did. Can some one help me out here!?

A: If you want them to look the same, or at least close, apply a reset style to the button element.
Reset CSS
input{
    display: inline-block; /* allows margins and padding, but floats like text */
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0; /* removes the outline when you click a form element */
}

Styling CSS
input{
    height: 1.5rem;
    width: auto;
    padding: 0.75rem 1.5rem;
    line-height: 1.5rem; /* same as height - centers vertically */
    color: black;
    background: gray;
}

I was styling input fields recently and this should give you a good start.


text:
Q: i want to read the content of html and i need to change it with the required text

<!DOCTYPE html>

  <meta charset="ISO-8859-1">
  <title id="title1">Amazon Home</title>

Hello World

  <form action="Translate" method="post">
    UserName<input type="text" name="uid">

    Password<input type="password" name="pwd">

    <input type="submit" value="submit" id="sub">
  </form>

Some text here

how to get the content( say Amazon Home,Hello World,UserName,Password,submit,some text here) of above html to servlet or to jsp.... and in my database im having the equivalent text of content in another language as shown below . so if i get those strings from html to any layer then i have to replace the content with another strings(which are in my database).
(with out using javascript like document.getElementById("l1").innerHTML="Nom d'utilisateur";)
-----+-------------+-------------------+
| id | f_key       | f_value           |
+----+-------------+-------------------+
|  1 | Hello_World | Bonjour le monde  |
|  2 | UserName    | Nom d'utilisateur |
|  3 | Password    | mot de passe      |
|  4 | submit      | soumettre         |
|  5 | Amazon_Home | Amazon Accueil    |
+----+-------------+-------------------+

A: use Resource bundle in jsp to change the text depending on your case


text:
Q: Must HEAD point to a branch? Must HEAD point to a branch, or can it point directly to a commit node? Is it possible to move HEAD to point to an arbitrary commit node even if no branch is referencing this node?

A:
Must HEAD point to a branch, or can it point directly to a commit?

HEAD is just a pointer to a commit. It is possible that no branch points to that commit.

Is it possible to move HEAD to point to an arbitrary commit even if no branch is referencing this commit?

Yes, it is.
Just do:
git checkout <commit-sha>

and you will check out that commit in a detached head state. That basically means that you are currently not on a branch.

A: Read this full answer:
How to move HEAD back to a previous location? (Detached head)
HEAD can be point to any commit, If HEAD is not pointing to a the latest commit in the branch you are in a detached HEAD.
Read the above answer to get the full detailed what is it and how to "fix" it.


text:
Q: Loading config file from DLL mixed with COM Interop I'm having trouble loading configuration settings in .NET whilst using an assembly over COM interop.
Background:
We use lots of VBScript scripts on some servers, that perform various tasks.  Commonly, they perform functions such as sending Emails.  To facilitate this, I wanted to create a COM object that was creatable from the VBScript, which would help with some of these common featuresets.
Thus, I'm trying to create a .NET assembly that exposes some COM interfaces via interop.  I managed to get this working, but then wanted to externalise (rather than hard code) some of the configuration settings.
I'm using this line to retrieve the configuration:
ConfigurationManager.OpenExeConfiguration(this.GetType().Assembly.Location)

This seems to work without issue when I'm testing it from a test project, and referencing it as a .NET project, but if I test it as a COM object, it fails.
The reason for the failure is that in my config file, I have a custom section:
<section name="CustomSection" type="COMObjects.CustomSection, COMObject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e9e8071519bd2f04"/>

However when it tries to load the custom section, it fails to load the assembly "COMObject".  To me, this makes sense, as I haven't placed the assembly in the GAC (nor do I want to), so it's struggling to locate it.
Is there a way to help the .NET framework locate the assembly referenced in the config file for a scenario such as this?
Below is the fuslogvw.exe output for the binding:

The operation failed.
Bind result: hr = 0x80070002. The system cannot find the file specified.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll
Running under executable  C:\Windows\SysWOW64\cscript.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: User = My-MACHINE\ME
LOG: DisplayName = COMObject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e9e8071519bd2f03
 (Fully-specified)
LOG: Appbase = file:///C:/Windows/SysWOW64/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = NULL
Calling assembly : System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.

LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: The same bind was seen before, and was failed with hr = 0x80070002.
ERR: Unrecoverable error occurred during pre-download check (hr = 0x80070002).

Thanks

A:
Running under executable  C:\Windows\SysWOW64\cscript.exe

This code is activated by the 32-bit version of the script interpreter.  Where the CLR will look for assemblies is affected by the startup EXE location.  It sets the value of AppBase which inevitably point to the Windows directory because that's where cscript.exe is stored.  The only way it could find your assembly is by you copying it into c:\Windows\SysWow64.  That's not a reasonable thing to do, this directory is owned by the operating system.
The private path can be configured by a app.exe.config file, <probing> element.  It is limited, you can only select a subdirectory of the AppBase.  Creating a subdirectory in c:\Windows\SysWOW64 is not a reasonable thing to do.  Creating a script.exe.config file is going to affect all scripts that are executed by cscript.  That's not a reasonable thing to do.
The .NET framework offers a very reasonable alternative to assembly resolution problems like this.  You already know it, it is the thing you don't want to do.  This assembly belongs in the GAC.


text:
Q: Are there any Samsung Artik libraries/header files for connecting to AWS IoT? I bought the Artik 053/055s modules to try and create an IoT project. Given that the Artik cloud and all other support is being removed, i am trying to connect the Artik to the AWS IoT service and use MQTT/HTTPS to push data to a DynamoDB instance.
I have tried looking for solutions to this on multiple sites including Samasung's Artik guides, forums etc., but I'm unable to find good resources/tutorials/samples for the same. If there are any resources for Artik<->AWS libraries or even sample codes it will be very helpful


text:
Q: Bazel, python3 and python interpreter options I have a large and diverse codebase, much of which is python(3), which I am trying to organise with bazel.
I would ideally like (in approximate order of importance):

*

*To default to python3 (ideally a specific version, but I can live with just using whatever's in /usr/bin/python3)

*To send options to the python interpreter, ideally in a per-target manner

*The option to override the python interpreter and other options for specific targets

Right now I have a partial solution and I would like some advice on whether it is idiomatic and where it might be improved.
In /BUILD I have
genrule(
  name = "python3_interpreter",
  outs = ["python"],
  cmd = "echo '#!/bin/bash\n/usr/bin/python3 -OO \"$$@\"\n' > $@",
  executable = True,
)
py_runtime(
  name = "python3",
  visibility = ["//visibility:public"],
  interpreter = ":python3_interpreter",
  files = []
)

to create a man-in-the-middle python interpreter, where I can add options  to the python interpreter (-OO in this case).
In /.bazelrc I have
build --python_top=//:python3
run --python_top=//:python3

To default to that interpreter.
I could probably use a macro around the genrule to make adding interpreter options more ergonomic (and perhaps search for python3 in a more structured way), but it still feels a lot like a hack.
I could also use an external repository to download and build a specific python version from source, more effort but also more hermitic.
None of these options seem particularly satisfying  and none allow me to override things per-target.
Any advice or constructive criticism would be welcome. I'm already using rules_python to manage pip dependencies. I'm also thinking of using rules_pyz, which looks like it might be easier to edit to support other features I need from python (e.g. py_library that depends on cc_library).


text:
Q: Add vertical space before a \minipage Is it possible to use a minipage with the a new line space before it in a single command?
Sample code here

\begin{minipage}[]{\linewidth}
\begin{minted}[linenos, frame=single]{java}
class Main {
    public static void main(String[] args) {
        /* code */
    }
}
\end{minted}
\end{minipage}

If I don't use minipage I get the expected result
Sample code here

\begin{minted}[linenos, frame=single]{java}
class Main {
    public static void main(String[] args) {
        /* code */
    }
}
\end{minted}

I would like to renew the minipage command (if it's possible) to add the new line before the minipage section. I'd prefer not to use \\ after "Sample code here" if possible.


text:
Q: Function in excel to search an array of strings for two different sub strings I am having trouble at the moment finding a function to search through an array of cells in excel in order to count the amount of times a cell contains two words.
e.g. The functions I have tried so far:
    =COUNTIF([array],AND("text1","text2"))

and
    =COUNT(IF(ISNUMBER(SEARCH("text1",[array])*SEARCH("text2",[array])),1,0))

or
    =SUM(IF(ISNUMBER(SEARCH("text1", [array])*SEARCH("text2",[array])),1,0))

So I was hoping for feedback if there is a different/easier way to do this or if there are errors in constructing my excel functions.

A: Try COUNTIFS with wildcards, I.e
=COUNTIFS(A:A,"*text1*",A:A,"*text2*")

A: As a side note:
For those of us who still hang around with ancient Excel versions: the following will work even with Excel 2003:
=MMULT(TRANSPOSE(IF(ISNUMBER(FIND("text2";A1:A200));1;0));IF(ISNUMBER(FIND("text1";A1:A200));1;0))

You have to confirm the formula input with <cntrl><shift><return> for it to become a matrix formula, otherwise it will not work.


text:
Q: How to create your own "transactions" dataset to be used for visualisation of Market Basket analysis I am playing around with market basket visualisations. Using the following code I get a dataset that I can use for some nice visualisations.
library("arules")
library("arulesViz")

data("Groceries")
summary(Groceries)

This all works fine but the thing is that I would like to tweak the data a little.
I see that the data is defined like this:
class(Groceries)
[1] "transactions"
attr(,"package")
[1] "arules"

Any ideas on how I can create my own dataset like this?

A: To quote the help file ?arules::transactions, here's one way:
library(arules)

## example 1: creating transactions form a list
a_list <- list(
      c("a","b","c"),
      c("a","b"),
      c("a","b","d"),
      c("c","e"),
      c("a","b","d","e")
      )

## set transaction names
names(a_list) <- paste("Tr",c(1:5), sep = "")
a_list

## coerce into transactions
trans1 <- as(a_list, "transactions")
trans1
# transactions in sparse format with
#  5 transactions (rows) and
#  5 items (columns)


text:
Q: In spark, how do I fold my RDD into pairs? Suppose I have an RDD of integers that looks like this:
(1,2,3,4,5,6,7,8)

(ie there are eight items on the RDD)
and I want to fold the RDD into pairs so it looks like this:
((1,2),(3,4),(5,6),(7,8)

(ie there are four items on the RDD).
I thought that there might be a partition or aggregate function but there doesn't seem to be one.
My question is: In spark, how do I fold my RDD into pairs?

A: This is what exactly sliding function does which available in mllib Library
// Import the mllib library
scala> import org.apache.spark.mllib.rdd.RDDFunctions._
import org.apache.spark.mllib.rdd.RDDFunctions._

scala> val rdd = spark.sparkContext.parallelize(Seq(1,2,3,4,5,6,7,8))
rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[10] at parallelize at
 <console>:29

scala> rdd.sliding(2,2).map(x => (x(0), x(1))).foreach(println)
(1,2)
(5,6)
(3,4)
(7,8)

Or better
rdd.sliding(2,2).map{case Array(x,y) => (x,y) }.foreach(println)

Hope this helped!


text:
Q: How to write state changing routine, similar to Redux? How can I write a really super, simple state changing routine? I need something like Redux, but way simpler, don't need all the bells & whistles.
I was thinking of a global object i.e. myState = {}, that is changed via setMyState() / getMyState().
I'm using JavaScript, and wondering if this would be done via a timer that polls say every 10ms, or so.
So in my JavaScript client app (I'm using ReactJS), a call to my getMyState("show-menu") inside a render() would update the Component's state just like using this.state..
The reason I want this is:
1) Wanna know how to write it for learning purposes.
2) Need something simpler that Redux, simple like Meteor's Session vars, so don't have to pass this.Refs. down to child compnents which setState on parent components.
3) Redux is a mouthful, there is still lots to digest and learn to use Redux.

A: Seems like you could do this pretty simply with a constructor.
function State () {
   this._state = {};
...
}

State.prototype.get = function () {
    return this._state;
};

State.prototype.set = function (state) {
    return this._state = state;
};

var STATE = new State();

But then you have to do the polling you mentioned in your post. Alternatively, you can look at eventEmitter libraries for javascript, for example https://github.com/facebook/emitter, and turn the State object into an event emitter.

A: Update
Not sure if this is what you're looking for, at all, but it's simpler.
function makeStore () {
  var state = { };
  return {
    set (key, value) { state[key] = value; },
    get (key) { return state[key]; }
  };
}

const store = makeStore();

store.set("counter", 1);
store.get("counter"); // 1

Believe it or not, there's really not a lot to Redux.
There's, perhaps, a lot to think about, and it's extra work to keep everything untied from your store...
But have a quick look:
function reducer (state, action) {
  state = state || { count: 0 };
  const direction = (action.type === "INCREASE") ? 1 : (action.type === "DECREASE") ? -1 : 0;
  return {
    count: (state.count + direction)
  };
}

function announceState () {
  console.log(store.getState());
}

function updateView () {
  const count = store.getState().count;
  document.querySelector("#Output").value = count || 0;

}
function increase () {
  store.dispatch({ type: "INCREASE" });
}
function decrease () {
  store.dispatch({ type: "DECREASE" });
}

const store = createStore(reducer, { count: 0 });
store.subscribe(announceState)
     .subscribe(updateView);

document.querySelector("#Increment").onclick = increase;
document.querySelector("#Decrement").onclick = decrease;
updateView();

This is the code I intend to use.
Looking at it, I'm pretty much just creating a store (with a function to run every time there's an event), there's the subscription to have a listener run, after the store has updated, there's a line where I fire an action, and...  ...well, that's it.

function createStore (reduce, initialState) {
  var state = initialState;
  var listeners = [];

  function notifyAll () {
    listeners.forEach(update => update());
  }

  function dispatch (event) {
    const newState = reduce(state, event);
    state = newState;
    notifyAll();
    return store;
  }

  function subscribe (listener) {
    listeners.push(listener);
    return store;
  }

  function getState () {
    return state;
  }

  const store = {
    getState, subscribe, dispatch
  };

  return store;
}

// THIS IS MY APPLICATION CODE
function reducer (state, action) {
  state = state || { count: 0 };
  const direction = (action.type === "INCREASE") ? 1 : (action.type === "DECREASE") ? -1 : 0;
  return {
    count: (state.count + direction)
  };
}

function announceState () {
  console.log(store.getState());
}

function updateView () {
  const count = store.getState().count;
  document.querySelector("#Output").value = count || 0;

}
function increase () {
  store.dispatch({ type: "INCREASE" });
}
function decrease () {
  store.dispatch({ type: "DECREASE" });
}

const store = createStore(reducer, { count: 0 });
store.subscribe(announceState)
     .subscribe(updateView);

document.querySelector("#Increment").onclick = increase;
document.querySelector("#Decrement").onclick = decrease;
updateView();
<button id="Decrement">-</button>
<output id="Output"></output>
<button id="Increment">+</button>

The very tiny, very easy implementation of a store (note that the real thing is more complex) is above. dispatch and subscribe are very useful, here.


text:
Q: I need help starting my computer I followed a YouTube video that told me how to uninstall Ubuntu after restarting the computer I received this message
Error: file not found.
grub rescue>

I have heard that you can reboot using a live CD, but mine is in a buddy's house and I have also heard that if you type 1s it will do something. I have tried this and all I receive is:
 Unknown command '1s'

A: First of all, that is a video on how to destroy your Ubuntu installation, not remove it.
If you want to completely remove Ubuntu and switch to Windows, boot into a liveCD when you get one, read up on how to install Gparted, delete your primary Ubuntu partition(s), boot into a Windows OEM cd and use the command prompt to restore the NT bootloader grub replaced.
As for:

Error: file not found. Grub rescue>

Grub is something called a bootloader. Bootloaders are used to bootstrap (initialize) Linux so that Ubuntu can run. Since Grub is a rather feature-rich bootloader, it holds most of it's code in your Ubuntu install. Since you destroyed your ubuntu install, grub can't find the rest of itself to load, and falls back to emergency console mode...
Also, since your tiny stage-1 grub install on the MBR most likely does not come with built-in NTFS support, you're out of luck if you want to boot back to windows without some sort of Rescue OS. Sorry :(


text:
Q: Excluded Source File Name causes pod header file not found There is an Objective-c framework in the project, the framework does not support running on simulator. It's not good for developing, so I excluded the file in Build Settings --> Excluded Source File Name, but this causes errors xxxx.h file not found. in Bridge-Header.h.
I also tried to set Validate workspace = yes, again, the framework seemed to be excluded, but it causes the errors.
How can I exclude framework correctly? and why the errors above happens?
Thanks.

A: This cause errors because Xcode can't find the files in the framework!You should find out all the files that have referred to any file of the framework. After you find them out, you'd better disable the functions provided by the framework, and remove all the reference in all the files. The errors will disappear after you remove all the reference
Don't delete or mess up the code, you need them when running on a real device after all.


text:
Q: Can we control the distance between the empirical and theoretical mean on the whole trajectory any better than using Hoeffding and a union bound? Suppose $X,X_1,X_2,X_3\dots$ is a $\mathbb{P}$-i.i.d. family of $[-1,1]$-valued random variables with $\mathbb{E}[X] = 0$.
Hoeffding's inequality implies that
\begin{equation*}
    \forall T \in \mathbb{N}, \forall \varepsilon > 0, \qquad \mathbb{P}\bigg[\frac{1}{T} \sum_{s=1}^T X_s \ge \varepsilon\bigg] \le \exp\Big(-\frac{T}{2}\varepsilon^2\Big),
\end{equation*}
from which it follows that
\begin{equation*}
    \forall T \in \mathbb{N}, \forall \delta \in (0,1), \qquad \mathbb{P}\bigg[\frac{1}{T} \sum_{s=1}^T X_s \ge \sqrt{\frac{2}{T}\log\Big(\frac{1}{\delta}\Big)}\bigg] \le \delta.
\end{equation*}
Basically, this result states that the trajectory of the process $Y_t := \frac{1}{t}\sum_{s=1}^t X_s$ is below the threshold $\sqrt{\frac{2}{T}\log\Big(\frac{1}{\delta}\Big)}$ with probability at least $1-\delta$, at any prescribed time $T$.
Instead, suppose that we wanted the whole trajectory $Y_1, Y_2,\dots,Y_T$ under the thresholds $\sqrt{\frac{2}{1}\log\Big(\frac{1}{\delta}\Big)}, \sqrt{\frac{2}{2}\log\Big(\frac{1}{\delta}\Big)}, \dots, \sqrt{\frac{2}{T}\log\Big(\frac{1}{\delta}\Big)}$, where $T \in \mathbb{N}$ is fixed. Can we do any better than using the following union bound
\begin{equation*}
    \mathbb{P}\bigg[\bigcup_{t\in\{1,\dots,T\}} \bigg\{\frac{1}{t} \sum_{s=1}^t X_s \ge \sqrt{\frac{2}{t}\log\Big(\frac{1}{\delta}\Big)}\bigg\}\bigg] \le \sum_{t=1}^T \mathbb{P}\bigg[\frac{1}{t} \sum_{s=1}^t X_s \ge \sqrt{\frac{2}{t}\log\Big(\frac{1}{\delta}\Big)}\bigg] \le \delta\cdot T ?
\end{equation*}
The problem with this last inequality is that a multiplicative factor $T$ appears in the bound, and I feel that maybe, due to something in the spirit of maximal martingale inequalities, we can do much better.
Any suggestion or pointer to the literature is very welcome.
EDIT: I tried to perform some simulations. Taking $X_1,X_2,\dots$ as a $\mathbb{P}$-i.i.d. family of Rademacher random variables seems to suggest that at least something of the form
\begin{equation*}
    \forall T \in \mathbb{N}, \forall \delta \in \Big(0,\frac{1}{10}\Big), \qquad \mathbb{P}\bigg[\bigcup_{t\in\{1,\dots,T\}} \bigg\{\frac{1}{t} \sum_{s=1}^t X_s \ge \sqrt{\frac{2}{t}\log\Big(\frac{1}{\delta}\Big)}\bigg\}\bigg] \le \delta\cdot \log(T)
\end{equation*}
holds, and even something better than this (maybe, even an upper bound of the form $O(\delta \cdot \log\log T)$).

A: The dependence on $T$ is logarithmic, see $(4)$ below. I could not find a precise reference, so I give an argument below, making sure to get explicit constants. The argument is adapted from the standard proof of the law of the iterated logarithm, that can be found, e.g., in the textbook by Durrett, Probability Theory and examples, and in [1].
Let $S_t:=\sum_{j=1}^t X_j$ and $\lambda:=\sqrt{2\log (1/\delta)}$, so that $e^{-\lambda^2/2}=\delta$.   The goal is to estimate
$\mathbb{P}(A)$ , where
$$A:=\bigcup_{t\in\{1,\dots,T\}} \bigg\{S_t \ge \lambda\sqrt{t}  \bigg\} \,.$$
We will assume that $\lambda^2 \ge 2e$, otherwise $\mathbb{P}(A)$ will be close to $1$. We first prove an upper bound.
Fix  $q=e^\beta>1$ and let
$$\tau_n:=\inf\left\{ t \in [q^n, q^{n+1}] :\, S_t\geq \lambda   q^{n/2} \right\},$$
with the convention that the infimum of the empty set is $\infty$.
Observe that
$$A \subset \bigcup_{n=0}^{N-1} \{\tau_n \le q^{n+1}\}\,, \quad \text{where}\quad N=\Bigl\lceil\frac{\log T}{\log q}\Bigr\rceil \,. \tag{1}$$
Next, apply the Azuma-Hoeffding inequality to the martingale $M_t=S_{t\wedge\tau_n}$, to infer that
$$\mathbb{P}(\tau_n \le q^{n+1})=
\mathbb{P}\Bigl(M_{q^{n+1}} \ge \lambda   q^{n/2} \Bigr) \le
\exp\Bigl(-\frac{\lambda^2}{2q}\Bigr) \,.$$
Recalling that $q=e^\beta$, we deduce from $(1)$ that
$$ \mathbb{P}(A) \le \Bigl\lceil\frac{\log T}{\beta}\Bigr\rceil \cdot
\exp\Bigl(-\frac{\lambda^2}{2e^\beta}\Bigr) \,. \tag{2}$$
To minimize the right-hand side, we take
$\beta \in (0,1]$ that satisfies
$$ {e^\beta}/{\beta}=\lambda^2/2=\log(1/\delta) \,.\tag{3}$$
To get a concrete bound, we note that $(3)$ gives
$$ \lambda^2/2 <  {1}/{\beta}+2 \,, \quad \text{so}$$
$$\exp\bigl(- {1}/{ \beta}\bigr) < \exp( -\lambda^2/2+2) =e^2\delta \,.$$
Thus $(2)$ yields that
$$ \mathbb{P}(A) \le  \bigl(1+   \frac{\lambda^2}{2}  \log T \bigr) \cdot
\exp\Bigl(-\frac{1}{ \beta}\Bigr) < e^2\delta  \log(e/\delta) \cdot \log T  \,. \tag{4}$$
$ \quad$
To show that the dependence on $T$ is indeed logarithmic (and not $f(\delta)\log \log T$ ), we give a rough lower bound in the special case  that $X_i$ are independent Rademacher variables (i.e., take values $\pm 1$), although it works more generally if they satisfy a CLT. We also assume that $1<\lambda<T^{1/8}$, although this can be relaxed as well.
Fix any $\epsilon>0$ and an integer $r>1$. Consider the independent  events
$$D_n=\left\{ S_{r^n} -S_{r^{n-1}}  >  \lambda r^{n/2} \right\}.$$
If $r^n >\sqrt{T}$, then by a version of the central limit theorem (That can be found e.g. in the book by Feller) and a lower tail bound for the Gaussian,
$$\mathbb{P}(D_n) >\exp\Bigl(-\frac{\lambda^2 r}{2r-3}\Bigr)>\delta^{1+\epsilon} \,,$$
provided that $r$ is large enough so that  $r/(r-3)<1+\epsilon$.  Let
$$N_0=\Bigl\lceil\frac{\log T}{2\log r}\Bigr\rceil \,.$$
If $\delta^{1+\epsilon} N_0<1$, then
$$ \mathbb{P}\Bigl(\bigcup_{n=N_0}^{2N_0-2} D_n \Bigr) \ge 1-(1-\delta^{1+\epsilon})^{N_0-1} > (N_0-1)\delta^{1+\epsilon}/2 \,.$$
If $\sigma$ is the last $n \in [N_0,2N_0-2]$ such that $D_n$ holds,
(which is well defined if the union in last display is nonempty), then $A$ will hold provided $S_{r^{\sigma-1}} \ge 0$, and the latter event has probability at least $1/2$ even conditional on $\sigma$. Thus we conclude that
$$\mathbb{P}(A) \ge (N_0-1)\delta^{1+\epsilon}/4 \,.$$
[1] Brownian motion, by Peter Mörters and Yuval Peres. Cambridge University Press, 2010. https://yuvalperes.com/brownian-motion/

A: I'm not sure whether the following counts as better, but it's easy to get a bound of $O\left(\delta\sqrt{\log(1/\delta)}\cdot \sqrt{T}\right)$.
We have, for any $1 \le t \le T$, $$\mathbb{P}\left[\frac{1}{t}\sum_{s=1}^t X_s \ge \sqrt{\frac{2}{t}\log\left(\frac{1}{10\delta}\right)}\right] \le 10\delta.$$ Note $$\sqrt{\frac{2}{t}\log\left(\frac{1}{\delta}\right)}-\sqrt{\frac{2}{t}\log\left(\frac{1}{10\delta}\right)} = \frac{\frac{2}{t}\log 10}{\sqrt{\frac{2}{t}\log(\frac{1}{\delta})}+\sqrt{\frac{2}{t}\log(\frac{1}{10\delta})}} \sim \frac{c}{\sqrt{t\log(1/\delta)}},$$ (where $c = \sqrt{2}\log 10$, I think). Therefore, if $$\frac{1}{t}\sum_{s=1}^t X_s \ge \sqrt{\frac{2}{t}\log\left(\frac{1}{10\delta}\right)}$$ for some $t \in [T]$, then $$\frac{1}{t'}\sum_{s=1}^{t'} X_s \ge \sqrt{\frac{2}{t'}\log\left(\frac{1}{\delta}\right)}$$ for all $t' \in \left[t,t+\frac{c\sqrt{t}}{\sqrt{\log(1/\delta)}}\right]$. There are $m := C\sqrt{T\log(1/\delta)}$ values of $t$, say $t_1,\dots,t_m$, for which $[T] = \cup_{j=1}^m \left[t_j,t_j+\frac{c\sqrt{t_j}}{\sqrt{\log(1/\delta)}}\right]$. Therefore, \begin{align*}
\mathbb{P}\bigg[\bigcup_{t\in\{1,\dots,T\}} \bigg\{\frac{1}{t}\sum_{s=1}^t X_s \ge \sqrt{\frac{2}{t}\log\Big(\frac{1}{\delta}\Big)}\bigg\}\bigg] &\le \mathbb{P}\bigg[\bigcup_{j=1}^m \bigg\{\frac{1}{t_j}\sum_{s=1}^{t_j} X_s \ge \sqrt{\frac{2}{t_j}\log\Big(\frac{1}{10\delta}\Big)}\bigg\}\bigg] \\ &\le m\cdot 10\delta \\ &= O\left(\delta\sqrt{\log(1/\delta)}\cdot \sqrt{T}\right).
\end{align*}


text:
Q: How to hide an iPhone App from the iPad's AppStore I noticed that WhatsApp Messenger [1] isn't available for iPad anymore.
Apple states that "iPad runs nearly all applications, or apps, designed for iPhone and iPod Touch" [2]
Now, I must have missed a memo since I knew that any iPhone App could be downloaded on iPad too.
So we finally get to my question: How to hide an iPhone App from the iPad's AppStore?
Thanks.
[1] https://itunes.apple.com/it/app/whatsapp-messenger/id310633997?mt=8
[2] http://support.apple.com/kb/ht4082

A: As far as I know, WhatsApp has never been available for download on the iPad. This is because they listed telephony as one of the Required Device Capabilities in their info.plist.
That's the only way that you can get an iPhone app not to install on an iPad. Apple doesn't provide any other way as they want all (most) of the iPhone apps to be compatible on iPads (if the app is not universal it'll just run in the iPhone scaled mode).
Please note that if you require telephony to achieve this, but that's not an actual requirement for your app, it will most likely be rejected on the App review process as Apple don't allow artificial hardware requirements used for limiting device types.


text:
Q: Why is App Access Token different to AppID|Secret now? In the facebook docs, it says we can specify:
AppID|Secret
As the application access_token
However, when going to https://developers.facebook.com/tools/access_token/  the App Token is different. This is in the form AppID|Randomnumber
Which should we be using? The PHP SDK uses the 'Secret' version - do we need to adjust this?

A: The app token is not APP_ID|APP_SECRET. The FB docs says that the app token may be obtained using the APP_ID and the APP_SECRET. You can achieve this by hitting this URL:
https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials

A: AppID|AppSecret works and I use it outside of PHP.  It is the only way to publish to a users stream after their access token expires and you haven't prompted for offline_access.  The appId|randomnumber they show you on that page expire like regular access tokens where appid|appsecret do not expire.


text:
Q: Why is my form marked dirty when manually set a control to pristine in Angular? I have created this directive:
app.directive("date", ['$filter', function ($filter) {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attributes, controller) {
            scope.$watch(function () {
                return controller.$modelValue;
            },
            function (newVal, oldVal) {
                if (newVal !== oldVal && newVal) {
                    var format = attributes.date || "dd-MM-yyyy";
                    var parsedDate = new Date(newVal);

                    parsedDate = $filter('date')(newVal, format);

                    controller.$setViewValue(parsedDate);
                    controller.$setPristine();
                    controller.$render();
                }
            });
        }
    }
}])

I this directive like this:
<form name='myForm'>
    Date: <input type="text" data-ng-model="contract.StartDate" name="StartDate" date />
</form>

In my scope I have a function which determines the state of the save button:
scope.canSave = function () {
    return scope.contractForm.$valid && scope.contractForm.$dirty;
}

As you can see in the code snippet of the date directive, I set controller.$setPristine(), however this action is not seen by the form controller, because form.$dirty is set to true, but when I check form.StartDate.$dirty it is set to false.
How is this possible and how can I make sure / force that form sees that StartDate is not dirty?

A: I finally find a solution in the form of parsers and formatters:
app.directive("date", ['$filter', function ($filter) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attributes, controller) {
            controller.$parsers.unshift(function (value) {
                if (!value) {
                    return;
                }

                var format = attributes.date || "dd-MM-yyyy";
                return $filter('date')(value, format);
            })

            controller.$formatters.unshift(function (value) {
                if (!value) return;

                var format = attributes.date || "dd-MM-yyyy";
                return $filter('date')(value, format);
            })
        }
    }
}])


text:
Q: Convergence of a sequence with natural logs Let $c>1$ be an integer constant.
Edit: I am wondering if the sequence
$$
cn\left[\frac{1}{\ln\left(n\right)} - \frac{1}{\ln\left(c n\right)}\right]
\qquad
\mbox{converges as}\quad n \to \infty.
$$
My first guess is that it should go to $0$, but simulation results show otherwise.

A: Response to the updated question....
Notice that
\begin{align}
cn \left(\frac 1 {\log n} - \frac 1 {\log cn}\right)
&= \frac{cn \log c}{(\log n)(\log n + \log c)}.
\end{align}
Now $\log(n)^2$ is far smaller than $n$ once $n$ is large enough, so this tends to infinity. This almost grows linearly in $n$.


text:
Q: Error in my sql I am facing problem which is mentioned as follows.
ERROR: Could not able to execute
INSERT INTO user_db (Name,UserId,Ip_addr) VALUES ('jayesh vyas', 'jay', ::1).
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near '::1)' at line 1.

My code is mentioned as below.
<?php
$link = mysqli_connect("localhost", "root", "", "apptitude");
$ip_user = $_SERVER['REMOTE_ADDR'];
// Check connection
if($link == false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$uname = mysqli_real_escape_string($link, $_REQUEST['uname']);
$username = mysqli_real_escape_string($link, $_REQUEST['username']);

// attempt insert query execution
$sql = "INSERT INTO user_db (Name,UserId,Ip_addr) VALUES ('$uname', '$username', " . $ip_user . ")";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// close connection
mysqli_close($link);
?>

can anyone please help me to understand that why it is happened???
Thanks in advance.

A: Your SQL statement is missing single quotes around the IP address.
So as you did it for $user and $username, just use it again on $_SERVER['REMOTE_ADDR'] (after connecting to the MySQL server): $ip_user = mysqli_real_escape_string($link, $_SERVER['REMOTE_ADDR']);.
And as tadman said, please use prepared statements.
Btw. $_SERVER['REMOTE_ADDR'] must not the clients IP address. Take a look at this Post.


text:
Q: Maxwell's Equations in Terms of the de Rham complex I am trying to phrase Maxwell's differential equations in terms of the de Rham complex. The equations are
$$ \nabla \cdot E = \frac{\rho}{\epsilon_0}$$
$$ \nabla \cdot B = 0$$
$$ \nabla \times E = - \frac{\partial B}{\partial t}$$
$$ \nabla \times B = - \mu_0 \left( J + \epsilon_0 \frac{\partial E}{\partial t} \right) $$
I am confused, because the first equation (Gauss's law) suggests that the electric field $E$ is a $2$ form and $\nabla \cdot E = dE$ is a $3$-form. But the third equation (the Maxwell-Faraday equation) suggests that $E$ is a $1$ form, and that $\nabla \times E$, the curl, is $d E$. I was thinking the hodge-star operation must be involved here somehow, since it turns $1$ forms into $2$ forms here and vice versa.
Can someone point me to a source which phrases things this way?
Thanks so much!