text:
Q: Xamarin Forms, I am trying to add a dynamic stack of buttons, but my app crashes when trying to launch on IOS, throwing an exception I am trying to add a stack of dynamically added buttons.
I am trying to build an app where you can scroll through a page to find a recipe you like and click the button in order to open another page that includes the ingredients and cooking instructions.
I followed this guide: How to create a dynamic list of buttons on MainPage in Xamarin.Forms? However whenever I try to launch the app on my iphone11, I get this
I am really frustrated right now, as I don't know what to do. I am new to xamarin forms, so please explain to me as if I have the IQ of an orangutan.
Here is my code:
recipeList.cs:
using System;
using System.Collections.Generic;

namespace CUapp
{
    public class recipeList
{
    public static List<recipeModel> list;

    public recipeList()
    {
        list.Add(new recipeModel { title = "spag. Meatball", id = "1"});
        list.Add(new recipeModel { title = "page1", id = "2" });
        list.Add(new recipeModel { title = "page2", id = "3" });
    }

}
}

recipeModel.cs:
using System;
namespace CUapp
{
    public class recipeModel
    {
        public string title { get; set; }
        public string id { get; set; }
    }
}

Recipes.xaml:
<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="CUapp.Recipes"
    Title="Recipes"
    BackgroundColor="WhiteSmoke"
    xmlns:rv="clr-namespace:Sharpnado.MaterialFrame;assembly=Sharpnado.MaterialFrame">

        <ScrollView >
            <StackLayout x:Name="buttons" HorizontalOptions="Center" Margin="10">
                <!--<rv:MaterialFrame x:Name="button" AcrylicGlowColor="Gray" LightThemeBackgroundColor="brown" WidthRequest="800" Style="{StaticResource AcrylicFrame}">
                <Button
                    Text="Spag. Meatballs"
                    FontSize="Medium"
                    Clicked="Button_Clicked"
                ></Button>
                </rv:MaterialFrame>-->

            </StackLayout>
        </ScrollView>

</ContentPage>

Recipes.xaml.cs:
using System;
using System.Collections.Generic;

using Xamarin.Forms;

namespace CUapp
{
    public partial class Recipes : ContentPage
    {
        public Recipes()
        {
            InitializeComponent();
            double w = Application.Current.MainPage.Width;

            buttons.Children.Clear();
            foreach (var item in recipeList.list)
            {
                var btn = new Button()
                {
                    Text = item.title,
                    StyleId = item.id
                    };
                btn.Clicked += OnDynamicBtnClicked;
                buttons.Children.Add(btn);
            }
        }

        private async void OnDynamicBtnClicked(object sender, EventArgs e)
        {
            var myBtn = sender as Button;
            // who called me?
            var myId = myBtn.StyleId; //this was set during dynamic creation

            //do you stuff upon is
            switch (myId)
            {
                case "1":
                    await Navigation.PushAsync(new SpaghettiMeatball());
                    break;

                case "2":
                    await Navigation.PushAsync(new Page_1());
                    break;

                case "3":
                    await Navigation.PushAsync(new Page_2());
                    break;
            }

        }

        private async void Button_Clicked(System.Object sender, System.EventArgs e)
        {
            await Navigation.PushAsync(new SpaghettiMeatball());
        }
    }
}

thank you so much guys!
EDIT:
Here is the "exception thrown page"
exception thrown page

A: You can achieve the effect you want by using CollectionView. When the CollectionView is clicked, the clicked item information is obtained, and then sent to Page1 for display, so that there is no need to create multiple pages.
Here is the xaml code for the Recipes:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="dddd.Recipes"
Title="collectionViewTest">

   <StackLayout>
     <CollectionView  x:Name="Mycll" SelectionMode="Single" SelectionChanged="Mycll_SelectionChanged">
         <CollectionView.ItemTemplate>
             <DataTemplate>
                 <Label Text="{Binding title}"></Label>
             </DataTemplate>
         </CollectionView.ItemTemplate>
     </CollectionView>
   </StackLayout>
</ContentPage>

Here is the c# code for the Recipes:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Recipes : ContentPage
{
    public ObservableCollection<recipeModel> myC { get; set; }
    public Recipes()
    {
        InitializeComponent();
        recipeList re = new recipeList();
        myC = new ObservableCollection<recipeModel>(re.list);
        Mycll.ItemsSource = myC;
    }
    public void Mycll_SelectionChanged(System.Object sender, Xamarin.Forms.SelectionChangedEventArgs e)
    {
        a = e.CurrentSelection.FirstOrDefault() as recipeModel;
        Navigation.PushAsync(new Page1(a));
    }
}

Here is the xaml code for the Page1(Details page):
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="dddd.Page1">

    <StackLayout>
        <Label x:Name="xid">
        </Label>
        <Label x:Name="xtitle">
        </Label>
    </StackLayout>
</ContentPage>

Here is the c# code for the Page1:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page1 : ContentPage
{
    public Page1(recipeModel recipeModel)
    {
        InitializeComponent();
        BindingContext = this;
        xid.Text = recipeModel.id;
        xtitle.Text = recipeModel.title;
    }
}

Here is the c# code for the recipeList:
public class recipeList
{
    public ObservableCollection<recipeModel> list;
    public recipeList()
    {
        list = new ObservableCollection<recipeModel>
        {
            new recipeModel { title = "spag. Meatball", id = "1" },
            new recipeModel { title = "page1", id = "2" },
            new recipeModel { title = "page2", id = "3" },
        };
    }
}

Here is the screenshot:

A: You should give us more information (for example the exception message you're getting).
By the way, I can give you some hints that I think you should consider:

*

*In your code you're calling double w = Application.Current.MainPage.Width; without using it. If current main page is null (because the main page is Recipes and your just inside its constructor) you will receive a null reference exception. You are not using the width value, so why don't you remove it?

*You should rewrite your static list class like this in order to have some valid values:
 public class recipeList
 {
     public static List<recipeModel> list = new List<recipeModel> {
         new recipeModel { title = "spag. Meatball", id = "1" },
         new recipeModel { title = "page1", id = "2" },
         new recipeModel { title = "page2", id = "3" }
     };
 }

*Be sure you have set the MainPage inside a NavigationPage before calling Navigation.PushAsync() method.
In your App.cs you should have: MainPage = new NavigationPage(new MainPage());

A: *

*Use ObservableCollection instead of List as it has INotifyPropertyChanged implemented (this will update your UI when you populate the collection)

*Use a ListView or CollectionView in your XAML and bind your ObservableCollection to it. Check docs on which one is better for your purpose: CollectionView and ListView differences. You can also create the buttons in the List- or CollectionView then.

A: thanks so much for your detailed answers.
Thankfully I have found a solution to my problem.
I have searched on youtube for an observableCollection tutorial which I have followed: https://www.youtube.com/watch?v=41NiKhFxYb0
And I used Classid instead of styleid, as I have learned that styleid is not bindable.
This was the first time I had ever asked a question on stack overflow, and I am impressed by the number of helpful answers you guys provided. Thanks so much for being such a helpful community :) <3


text:
Q: Delete all Visual Composer Shortcodes saving content I'm trying to import 200 posts from an older wordpress, with a lot of visual composer shortcodes in the content.
Is there any way to delete all shortcodes and save the content?

A: Programmatically this can be done with visual composer activated and resaved content like this:
for each all posts
   post->post_content = do_shortcode(post->post_content)
   save(post)
endforeach

What I mean - all shortcodes need to be rendered to get it HTML and save it as new post content. This will allow to "strip" all shortcodes but save the markup generated with visual composer. But note that you will need to manually enqueue styles/css for visual composer elements.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding CCS, Javascripts and PHP files into Joomla websites I am quite new to Joomla and have come across a problem that annoys me as a programmer alot!
Now Ive been watching several tutorials on-line and all of them state "Its so easy for non programmers to create a website with Joomla"
While that's fine and all there seem to be few tutorials that actually show what "powers" you do have if you infact have programmering experience.
Here is my problem:
I want to be able to add PHP, Javascripts CSS and HTML to my site i have stumbled across JUMI but as far as i know it only allows me to add scripts to articles and modules.
Here is an example of what i want to achieve:
I will buy and use a template at Themeforest Then i want to create a search bar using HTML and PHP, when using the search option the site will run my script and load the result into a table using a combination of JQuery and HTML.
Other than that i wish to create a session so that when user for example tries to purches items on my site will be saved and so that my site actually remembers the users choices.
Now i do not except you guys to have all the answers but a simple redirect to a tutorial, paper or any other place where i can learn about how to make this work would make me very gratefull.
Question update
So i think my question is abit hard to understand i ive made this update:
Maybe i have misunderstood some things but say for instance one of you guys download a template how do you go on from there? how do you manipulate the modules so that when you search for something the search is done in another database table than the default one? how do you create a login for users to use and add your own costum scripts?
These are only a few examples but i hope you get the idea.

A: Read more abou Joomla modules. They allow to add bits of your own custom functionality to your websites :
http://docs.joomla.org/Module
[update]
If you need to create more self-contained bits of functionalites that operate on their own db tables ect then you most likely need to build component (the tutorial below is quite hands-on):
http://docs.joomla.org/J2.5:Developing_a_MVC_Component/Developing_a_Basic_Component
I realize the Joomla docs are not great. I myself learned most by studying code of core templates and components

A: Search bar is a full integrated feature to frameworks like
Joomla
Drupal
Wordpress

and so on..
If you want sessions and some more advanced security mechanism you might want to think about buying a ssl certificate and do most of the interaction to the server by SSL encryption.
Also you sholud look at:
http://www.opencart.org
is that answer your problem?

A: I think you are working on a joomla 2.5. I don't know if you are able to build a new template (copy of Themeforest) and override that.
For the adds you got many solutions. You can override your template, build modules or componments that you gonna put in different postion, or you can try some plugin like sourcerer, module anywhere...All that depends on the type of your site, sometimes that doesn't feet.
For the session I think you still have several choices, build it from scratch or search for a module.
Hope that helps.
I would create a module. I'm sure there are several ways to do that but that's what I would do. From scratch or with blank_module (joomla module).
You got some doc here : http://docs.joomla.org/J2.5:Creating_a_simple_module/Developing_a_Basic_Module
Here for the output ovveride (other database for example) : http://docs.joomla.org/Understanding_Output_Overrides


text:
Q: Does the OS (Ubuntu LTS vs CentOS) has a significant impact on the performance of a MySQL Server In the following scenario:

*

*same hardware

*same mysql version

*same configuration settings

*same load

*using latest stable version of the OS

Does the OS has an impact on MySQL overall performance?
The customer's IT staff is advising on chaning Ubuntu LTS with CentOS to improve performance.
Am I missing something?
I would undestand the impact of a distro like Gentoo or Arch Linux, but not really CentOS.

A: Benchmark it and test for yourself...
You will find that the different operating systems may have different application-level defaults. So examine configuration files closely before deeming that everything has the "same config".
The kernels are also different and have different OS-level default settings. Think about sysctl.conf settings, for instance.
Or think about how RHEL/CentOS 6 and newer systems have the tuned-adm framework to set server performance profiles...


text:
Q: Difference between "lady" and "woman"? Are there differences between "lady" and "woman" ?
Google say lady is a polite social woman. But we don't use them just as this. Do we? English isn't my native language so I am better clarifying myself.

A: An analogy should illustrate the difference well:

Lady : woman :: gentleman : man.

That is, "lady" and "gentleman" typically occur in the same contexts, as do "woman" and "man". Examples:

"Ladies and gentlemen" as a term of address in public speaking.
Women and Men, the title of a novel by Joseph McElroy.

A: "Lady" can be used to refer to someone of higher or lower social rank. When it's spelled with a capital letter, it is the title of a woman with the equivalent rank of a Lord, or a woman who is married to a Lord. As "just a word", though, it usually refers to somebody who is of a different social rank from yours. You would use the terms "cleaning lady" and "bag lady" just as much (and probably more in these less-formal times) as you would "lady of the house" and other sorts of "you are more important than me" phrases.
One needs to watch the use of "lady" these days. Because it has been as much a word that comes automatically with marriage as one that may be earned, it is sometimes felt as belittling, dismissive or condescending; something like calling Jane, who is married to John Smith, Mrs. John Smith. The word itself isn't a bad one, and can be used in very positive ways, but many of its uses—uses that once would have been the height of proper manners—are very much unwelcome these days.

A: Both user3820386 and Stan Rogers answers are correct, but there is more to the question. There has been a generational shift in the meaning and implications of "lady", at least in the US. For instance, my father (born 1913) used to tell the joke, "What's the difference between a diplomat and a lady?"

If a diplomat say yes he means maybe, if he says maybe he means no, and
  if he says no he's no diplomat.
If a lady say no she means maybe, if she says maybe she means yes, and if she says yes she's no lady.

In the 1950s, the animated Disney movie "The Lady and the Tramp" http://movies.disney.com/lady-and-the-tramp was a popular family movie, but it included a play on words with the juxtaposition of "lady" and "tramp", with the latter meaning a sexually promiscuous woman.
At the same time, "lady of the evening" was a euphemism for prostitute.
With the advent of the Sexual Revolution, the aspect of compulsory chastity is no longer part of the definition of lady. As far as I know.

A: A lady was a woman with an higher rank in society.
Nowadays lady and woman means the same (but lady is more complimentary than woman).


text:
Q: Rstudio to mysql arabic data corrupted I have a simple rscript to save the data from rstudio to mysql by calling a mysql stored procedure,
mysql is installed at linux server.
code snippet for saving is below
mydata<- levels(as.factor(datatable$ID[1]))
apply(ExportTable, 1, function(row) sqlQuery(mysqldb, sprintf("CALL spsavetoMysql('%s', '%s', %s, '%s', '%s', %s, '%s', '%s', '%s')", pid, rid, row[1], gsub("'", "''", row[3]), row[2], row[4], sid, gsub("'", "''", row[6]), gsub("'", "''", row[5]) )))

But when i use arabic character it corrupt data like

when data is being sent from rstudio data are correct,
when manually calling sp in mysql, data inserts successfully,
it corrupt data on the way calling mysql sp from r script.
please advise.
Thanks


text:
Q: Kibana Server Not Ready 7.10 I followed this video https://www.youtube.com/watch?v=gZb7HpVOges&lc=UgytpC8Evhfmld7YeBV4AaABAg.9GmQvwXZKJC9GmSBBrUcxY
to the T on my virtual box instance of Ubuntu 20.
Elastic appears to run fine however when I try to run kibana I receive "Kibana Server Not Ready" Error.
Both elastic and kibana are 7.10
When I run a journalctl -u kibana.serviceI receive:
Dec 03 14:04:25 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:25Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:27 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:27Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:30 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:30Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:32 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:32Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:35 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:35Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:37 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:37Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:40 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:40Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:42 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:42Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:45 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:45Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:47 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:47Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:50 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:50Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}
Dec 03 14:04:52 elk kibana[647]: {"type":"log","@timestamp":"2020-12-03T14:04:52Z","tags":["error","elasticsearch","data"],"pid":647,"message":"[ConnectionError]: connect ECONNREFUSED 127.0.0.1:9200"}

Elastic Yml
cluster.name: lab

node.name: lab1

path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch

bootstrap.memory_lock: true

network.host: 0.0.0.0
http.port: 9200

discovery.type: 'single-node'

indices.query.bool.max_clause_count: 8192
search.max_buckets: 250000

action.destructive_requires_name: 'true'

reindex.remote.whitelist: '*:*'

xpack.monitoring.enabled: 'true'
xpack.monitoring.collection.enabled: 'true'
xpack.monitoring.collection.interval: 30s

xpack.security.enabled: 'true'
xpack.security.audit.enabled: 'false'

node.ml: 'false'
xpack.ml.enabled: 'false'

xpack.watcher.enabled: 'false'

xpack.ilm.enabled: 'true'

xpack.sql.enabled: 'true'

Kibana Yml
server.name: 'lab1'
server.host: '0.0.0.0'
server.port: 5601

server.maxPayloadBytes: 8388608

elasticsearch.hosts: ['http://127.0.0.1:9200']
elasticsearch.username: 'kibana'
elasticsearch.password: 'changeme'

elasticsearch.requestTimeout: 132000
elasticsearch.shardTimeout: 120000

kibana.index: '.kibana'

#kibana.defaultAppId: 'dashboard/<dashboard_id>'

#logging.quiet: true
#logging.timezone: 'UTC'

vega.enableExternalUrls: true

console.enabled: true

xpack.security.enabled: true
xpack.security.audit.enabled: false

xpack.monitoring.enabled: true
xpack.monitoring.kibana.collection.enabled: true
xpack.monitoring.kibana.collection.interval: 30000

xpack.monitoring.ui.enabled: true
xpack.monitoring.min_interval_seconds: 30
#xpack.monitoring.ui.container.elasticsearch.enabled: 'false'

#xpack.apm.enabled: true
#xpack.apm.ui.enabled: true

xpack.grokdebugger.enabled: true


text:
Q: App disappeared from developer account After adding a test user, my app disappeared from my list in the developer account. I can still access the app:
https://developers.facebook.com/apps/337746716318749
but it is gone from my settings.


text:
Q: Open a blog post in a pop-up modal with wordpress like instagram does as the question already says I am looking for a way to open a wordpress blog as a modal. For easier understanding, I want to recreate/customize the Instagram page for my purposes. So it's from the home page layout like Instagram and the modal pop-up should also open like there. Is there any way whether as code or plugin that I can dynamically play out the content from each blog item for each post in a modal?
For the implementation of the project, I use the Avada theme, maybe this is still a helpful information :)
Example image attached...
Thanks a lot for your help,
Greetings Alex
Overview
Modal-Popup
So far I have only tried to open the modal as a pop-up at all, however not even that has worked so far. I look forward to your support, thank you.


text:
Q: Https call with client certificate from smartcard How can I programmatically call https endpoint from c# that requires client certificate from smart-card?
Can I use store certificate or do I need to export required certificate to file?
I can access the endpoint without any problems from a browser, but when i do that from c# or node I get 401 unauthorized and I tried both options using store or importing certificate from file but that doesn't work for me.
Here's sample code:
const string url = "https://somesite.com/url";

var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
var certs = store.Certificates;

//var cert = new[] { X509Certificate.CreateFromCertFile("./m102044.cer") };     from cert exported from chrome

var request = (HttpWebRequest)WebRequest.Create(url);
request.ClientCertificates = certs;

var response = request.GetResponse();  // 401 unauthorized


text:
Q: Batch file and CHOICE command for multiple files Having a Windows program that does wipe files and folders from the context menu too even with no confirmation at all then I created a batch file with the following content
@ECHO OFF
CHOICE /M "Do you want to Wipe Files"
IF ERRORLEVEL 2 GOTO QUIT
IF ERRORLEVEL 1 GOTO RUN
:RUN
START "" "C:\Program Files\MyProgram\myexec.exe" /wipe "%~1"
EXIT
:QUIT
EXIT

and a registry key with the following entry
[HKEY_CLASSES_ROOT\*\shell\wipefiles\command]
@="\"C:\\Program Files\\MyProgram\\myexec-start.cmd\" \"%1\""

just to get a safety chance before to wipe the file or the folder and it does work.
However if multiple files are selected then it prompts you to answer Y or N for the times as far as the number of files is and furthermore the cmd window remains open until you hit Y or N the times as far as the number of selected files is.
Is there a way in order to answer a single time Y or N (closing the cmd screen) regardless of the number of selected files?

A: There seems to be no simple way to do what you request from the context menu, since a separate process is opened for each selected file.
But it can be done easily from the send to menu:
Create a shortcut in the SendTo folder for your script, and now you can send as many files or folders as you want.
The script reads as follows:
@ECHO OFF
CHOICE / M "Do you want to Wipe Files"
IF ERRORLEVEL 2 GOTO QUIT

:: If your software enables file processing in a chain, such as myexec.exe /wipe filename1 filename2 ..., use this syntax:
START "" "C:\Program Files\MyProgram\myexec.exe" /wipe %*
:: If not, use the for loop:
for %%f in (%*) do START "" "C:\Program Files\MyProgram\myexec.exe" /wipe %%f

: QUIT

Maybe it's a bit of a deviation from the theme, but you can do it in VBScript like this:
Set Shell = CreateObject("WScript.Shell")
if MsgBox("Do you want to Wipe Files?", vbQuestion + vbYesNo, "wipefiles") = vbYes then
  for each Arg in WScript.Arguments
    Shell.Run """C:\Program Files\MyProgram\myexec.exe"" /wipe " & """" & Arg & """",0,True
  Next
end if

It will display a graphical message box asking the user to confirm the deletion, without any terminal window.


text:
Q: How to disable gae python to check for updates every time I start a server in eclipse? I just hate seeing this for 20sec every time I run my server: appcfg.py:393] Checking for updates to the SDK.

A: For anyone else looking for the answer, appcfg.py now has a command line switch:
--skip_sdk_update_check

happy coding!

A: Create or edit the file .appcfg_nag in your home directory. Edit the first line to be:
opt_in: false

A: @Nick Jognson and @Joe answers both for me did not worked but here is how i fixed it for ENTERPRISES where user names get deleted and user profile gets deleted on every reboot.
#!/usr/bin/env python
from subprocess import Popen, PIPE
cmd = Popen('python.exe script.py', stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = cmd.communicate("sendNOnENTER\nsendNOnENTER\n")
print out
print err

Here script.py is executed and if it was asked to type Y or n you can use communicate method or second method is little bit nonsense but also works:
import os
from subprocess import Popen
google_app_engine_update = 'c:/Python27/.appcfg_nag'
if os.path.exists(google_app_engine_update):
  target = open(google_app_engine_update, 'r+')
else:
  target = open(google_app_engine_update, 'w')

line1 = 'opt_in: false'
target.write(line1)
target.close()
Popen(['c:/Python27/python.exe', 'C:/google/devscript.py', arg1, arg2], shell=False)


text:
Q: Failed to link math library with intel mkl using g++ I tried to compile with intel mkl 11.1 using g++:
g++ -m32 test.c -lmkl_intel -lmkl_intel_thread -lmkl_core -liomp5 -lpthread -lm

The error says:
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `logf'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `atan2'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `sin'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `fabs'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `exp'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `cos'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `sqrt'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_intel_thread.so: undefined reference to `log'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `pow'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `log10'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `ceil'
/opt/intel/composer_xe_2013_sp1.0.080/mkl/lib/ia32/libmkl_core.so: undefined reference to `expf'

But, if I compile with
g++ -m32 test.c -lmkl_intel -lmkl_intel_thread -lmkl_core -lm -liomp5 -lpthread -lm

There will be no error. I don't understand why added a -lm after the -lmkl_core will help, by the way
gcc -m32 test.c -lmkl_intel -lmkl_intel_thread -lmkl_core -liomp5 -lpthread -lm

Turns out to be ok, I also don't understand what's the difference here.
Below is my test code.
/* C source code is found in dgemm_example.c */

#define min(x,y) (((x) < (y)) ? (x) : (y))

#include <stdio.h>
#include <stdlib.h>
#include "mkl.h"

int main()
{
    double *A, *B, *C;
    int m, n, k, i, j;
    double alpha, beta;

    printf ("\n This example computes real matrix C=alpha*A*B+beta*C using \n"
            " Intel(R) MKL function dgemm, where A, B, and  C are matrices and \n"
            " alpha and beta are double precision scalars\n\n");

    m = 2000, k = 200, n = 1000;
    printf (" Initializing data for matrix multiplication C=A*B for matrix \n"
            " A(%ix%i) and matrix B(%ix%i)\n\n", m, k, k, n);
    alpha = 1.0; beta = 0.0;

    printf (" Allocating memory for matrices aligned on 64-byte boundary for better \n"
            " performance \n\n");
    A = (double *)mkl_malloc( m*k*sizeof( double ), 64 );
    B = (double *)mkl_malloc( k*n*sizeof( double ), 64 );
    C = (double *)mkl_malloc( m*n*sizeof( double ), 64 );
    if (A == NULL || B == NULL || C == NULL) {
        printf( "\n ERROR: Can't allocate memory for matrices. Aborting... \n\n");
        mkl_free(A);
        mkl_free(B);
        mkl_free(C);
        return 1;
    }

    printf (" Intializing matrix data \n\n");
    for (i = 0; i < (m*k); i++) {
        A[i] = (double)(i+1);
    }

    for (i = 0; i < (k*n); i++) {
        B[i] = (double)(-i-1);
    }

    for (i = 0; i < (m*n); i++) {
        C[i] = 0.0;
    }

    printf (" Computing matrix product using Intel(R) MKL dgemm function via CBLAS interface \n\n");
    cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
            m, n, k, alpha, A, k, B, n, beta, C, n);
    printf ("\n Computations completed.\n\n");

    printf (" Top left corner of matrix A: \n");
    for (i=0; i<min(m,6); i++) {
        for (j=0; j<min(k,6); j++) {
            printf ("%12.0f", A[j+i*k]);
        }
        printf ("\n");
    }

    printf ("\n Top left corner of matrix B: \n");
    for (i=0; i<min(k,6); i++) {
        for (j=0; j<min(n,6); j++) {
            printf ("%12.0f", B[j+i*n]);
        }
        printf ("\n");
    }

    printf ("\n Top left corner of matrix C: \n");
    for (i=0; i<min(m,6); i++) {
        for (j=0; j<min(n,6); j++) {
            printf ("%12.5G", C[j+i*n]);
        }
        printf ("\n");
    }

    printf ("\n Deallocating memory \n\n");
    mkl_free(A);
    mkl_free(B);
    mkl_free(C);

    printf (" Example completed. \n\n");
    return 0;
}

A: I'm working on Debian and I follow the steps below to successfully run and compile one of the example programs in mkl:

*

*I use script.sh to automatically install the necessary packages (need to use sudo)

*Run one of example programs (this one for example) as following:
(ref)

*

*$ export MKLROOT=/opt/intel/compilers_and_libraries_2018.2.199/linux/mkl

*$ cc -fopenmp -m64 -I${MKLROOT}/include test.c -Wl,--no-as-needed -L${MKLROOT}/lib/intel64 -lmkl_intel_lp64 -lmkl_core -lmkl_gnu_thread -lpthread -lm -ldl

*$ ./a.out


text:
Q: Delete Row if Columns K:R all contain blanks VBA Excel Bit of a background: I'm trying to copy a table from "Create Form" N2:AE14
Set r = Sheets("Create Form").Range("COPYTABLEB")
Selection.Copy

Set dest = Sheets("Sample Data").Range("B1").End(xlDown).Offset(1, 0)
r.Copy
dest.PasteSpecial Paste:=xlPasteValues

I want it to copy only the cells that have values and not blanks but unfortunately it's picking up the formulas and pasting them as blanks. So when I go to paste the next section in, it sees the blanks as data.
So instead I'm trying to figure out a way of deleting an entire Row in "Sample Data" if Columns K:R all contain blanks once its been copied across.
I currently have a loop that does it for column B being blank but it takes far too long.
Lastrow = Range("B" & Rows.Count).End(xlUp).Row
MsgBox (Lastrow)
For i = Lastrow To 2 Step -1
If Trim(Range("B" & i).Value) = "" And Trim(Range("B" & i).Value) = "" Then
Range("B" & i).EntireRow.Select
Selection.Delete

End If

Next i

Could someone please help me either:
a.) copy and paste the values across minus all the blanks
b.) or help me with a quicker way of deleting the rows?

A: assuming

*

*you want to delete

"an entire Row in "Sample Data" if Columns K:R all contain blanks"

you could try this:
Sub CopyValuesAndDeleteRowsWithBlankKRColumns()
    Dim pasteArea As Range
    Dim iRow As Long

    With Sheets("Create Form").Range("COPYTABLEB")
        Set pasteArea = Sheets("Sample Data").Range("B" & Rows.count).End(xlUp).Offset(1, 0).Resize(.Rows.count, .Columns.count)
        pasteArea.Value = .Value
    End With
    With Intersect(pasteArea, Sheets("Sample Data").Range("K:R"))
        For iRow = .Rows.count To 1 Step -1
            MsgBox WorksheetFunction.CountBlank(.Rows(iRow)) & " - " & WorksheetFunction.CountBlank(.Rows(iRow)) Mod 8
            If WorksheetFunction.CountBlank(.Rows(iRow)) Mod 8 = 0 Then .Rows(iRow).EntireRow.Delete
        Next
    End With
End Sub


text:
Q: TFS 2008 Cube Report between two points in time In TFS 2008, I'd like to be able to create a pivot table/chart to show the difference in a specific field between two given points in time. The reason is we put our initial estimates in at the beginning and then update it to the total number of hours we did against the item when we finish. An obvious answer to this, would be two separate fields, one for initial and one for final, but that isn't how it was set up, so the only way I can pull the data is querying against the history of the work item.
I am up for writing a custom SQL query or updating the cube with a new perspective if necessary, but ideally, I'd like to just pull it together with the TFS cube into excel 2007. I was looking at the Work Item History perspective, but I'm just not seeing anything close enough in there.

A: The Work Item history in the TFS cube indeed exposes the state of the work item fields over time. You can just select the start and end point in the pivot table connected to the cube datasource as the row or column. On the other axis, select the field you want to display. The values in the table will show the values for the fields in both points in time.


text:
Q: '~' operator in Numpy used for general condition? I recently came across this operator in a data analysis book that I should have read a long time ago. It is used for general conditions but I don't understand it.

A: When applied to a numpy array with boolean dtype, it is the logical_not operator:
In [607]: np.array([True, False, True])
Out[607]: array([ True, False,  True])
In [608]: ~np.array([True, False, True])
Out[608]: array([False,  True, False])
In [611]: np.logical_not(np.array([True, False, True]))
Out[611]: array([False,  True, False])

That's not the case with Python booleans:
In [613]: ~True
Out[613]: -2
In [614]: not True
Out[614]: False


text:
Q: Mail attachments not attaching I am writing a simple email helper class that will be called by a Windows service. When I test though the email attachment is not sending with the rest of the email.
mailAttachmentFilePath is an ArrayList (just for clarification) and mail represents MailMessage class.
if (mailAttachmentFilePath.Count > 0)
        {
            foreach (string file in mailAttachmentFilePath)
            {
                Attachment data = new Attachment(file);
                mail.Attachments.Add(data);
                data.Dispose();
            }
        }

I am certain I am missing something but, I don't know what it is...

A: Do the data.Dispose() AFTER you send the email :D.

A: Remove the data.Dispose(). The attachments are being added by reference so when you call dispose it's actually releasing the attached file. You also don't really need the if statement. Try this:
    foreach (string file in mailAttachmentFilePath)
    {
        Attachment data = new Attachment(file);
        mail.Attachments.Add(data);
    }


text:
Q: CSS transition issue on Chrome with Flexslider I'm using flexslider to display a list of elements which are quite complex.
Basically each item has:

*

*a background image in position: absolute

*a foreground containing text and images

I have the following issue (only in Chrome): the foreground goes to the back during sliding transition and then comes back to front when the transition is finished.
Do you have any idea of investigation paths for this issue?

A: After reading https://github.com/woothemes/FlexSlider/issues/179 I solved the issue by using the following option at slider creation:
useCSS: false


text:
Q: How to subtract x from every number in a listbox So I have a list box of numbers and I want to subtract an integer from every single number of a list box. Here is an example:
1
2
3
4
5

I want to get the absolute value of the difference
Math.Abs(2 - 1)
Math.Abs(2 - 2)
Math.Abs(2 - 3)
Math.Abs(2 - 4)
Math.Abs(2 - 5)

And put them in a list box.
I've tried:
while (i < listBox1.Items.Count)
{
    result -= Convert.ToInt32(listBox1.Items[i++]);
    int result1 = Convert.ToInt32(result)
    int sub = Math.abs(result1)
}

A: Would this work :
I am using Select(x => {return x;}) notation of linq to do an operation on the array element, and return a value. In this case, the operation is Math.abs of each element of the array and a given number. _absDiffs will be an IEnumerable<int>, which you could call .ToArray() on to turn it into int[].
int[] _nums = {1,2,3,4,5};
int _number = 2;

var _absDiffs = _nums.Select(num=> { return Math.abs(_number - num);});


text:
Q: Determine how to evaluate missing data variables properly in a function that uses '{{' I'm attempting to build a function to produce box plots via highcharter. Once upon a time a function existed in highcharter called hcboxplot which has since been deprecated and which also uses deprecated tidy functions at this point.
Therefore, I'm now using highcharter::data_to_boxplot which creates a data.frame with list columns where each list includes boxplot.stats points. In an effort to simplify things for my team and I; I want to write a wrapper function for data_to_boxplot that builds out a basic boxplot.
Since data_to_boxplot uses data variables I need to embrace -> {{}} my arguments in order to evaluate them in the right context. Maybe there's another way? I'm very new to tidy evaluation as I mainly work with data.table and am having difficulty with handling optional parameters.
Example output:
library(data.table)
library(highcharter)
library(tidyr)

# dummy data
tmp = data.table(
  x1 = runif(30) * 10,
  grp = rep(c("a","b","c"),10),
  grp2 = rep(c("d","e"),15)
)

# transformed for hc
stat = data_to_boxplot(tmp, x1, grp, grp2)

# sample plot
highchart(type = "chart") %>%
  hc_add_series_list(stat)

Issue - when using a wrapper:
hc_boxplot = function(data, x, var = NULL, var2 = NULL, outliers = FALSE, ...) {
  arggs = list(...)

  d = data_to_boxplot(data = data, variable = {{x}}, group_var = {{var}}, group_var2 = {{var2}}, add_outliers = outliers, arggs)

  # basic chart
  highchart(type = "chart") %>%
    hc_add_series_list(d)
}

hc_boxplot(data = tmp, x = x1, var = grp, name = "test")
# Error in setnames(x, value) : - This refers to the excluded var2 arg
# Can't assign 1 names to a 0 column data.table

This works for the most part when all arguments are used but if I omit var2 or var & var2. Those args are still evaluated using {{}} even though to my understanding they should be missing. Below is a snippet from the data_to_boxplot code where the wrong portion of the if statement is evaluated. Since data_to_boxplot doesn't treat var2 as missing.
# where var2 == group_var2
# evaluates to TRUE instead of FALSE and proceeds to build an empty table
  if (!missing(group_var2)) {
    dg2 <- data %>% select({
      {
        group_var2
      }
    })
  }
  else {
    dg2 <- data.frame(rep(NA, nrow(dx)))
  }

Since the arguments are not environment variables, I'm wondering how I can signal to data_to_boxplot in my wrapper that the omitted arguments are in fact missing.

Additionally, I'm having trouble passing in named arguments via (...) to data_to_boxplot. In my example above I use name = "test" which should name the series but am getting an undesired result. Where a new column is added named "arggs" with "test" in it instead of updated the column titled "name".
# A tibble: 2 × 5
  name  data       id    type    arggs
  <chr> <list>     <chr> <chr>   <named list>
1 d     <list [3]> d     boxplot <chr [1]>
2 e     <list [3]> e     boxplot <chr [1]>

Appreciate any help on this as I'm sufficiently stuck.

A: This is a bug in highcharter. They are currently using this pattern in data_to_boxplot():
if (!missing(group_var)) {
  dg <- data %>% select({{ group_var }})
}

But using missing() on arguments that might contain {{ doesn't work. What they should do instead:
# Defuse `group_var` into a quosure so we can inspect it
group_var <- enquo(group_var)

# Inspect the defused quosure with `quo_is_missing()`
if (!quo_is_missing(group_var)) {
  # Inject it back into the data-masking expression
  dg <- data %>% select(!!group_var)
}

Until this is fixed upstream, you can work around. This is not so trivial because missing values are involved:
hc_boxplot = function(data, x, var, var2, outliers = FALSE, ...) {
  arggs = list(...)

  # Capture defused expressions so we can inspect them and remove
  # missing values
  defused_args = enquos(
    variable = x,
    group_var = var,
    group_var2 = var2
  )

  # Remove any missing arguments
  defused_args = Filter(\(x) !rlang::quo_is_missing(x), defused_args)

  # We'll inject the compacted list of defused expressions with `!!!`
  # back into `data_to_boxplot()`. This is equivalent to using
  # `do.call()` for a list of arguments.  In data-masking functions,
  # only `...` supports `!!!` automatically. To use it on named
  # arguments like `variable` and `group_var1`, we need to explicitly
  # enable `!!!` with `inject()`.
  d = inject(
    data_to_boxplot(
      data,
      !!!defused_args,
      add_outliers = outliers,
      !!!arggs
    )
  )

  # basic chart
  highchart(type = "chart") %>%
    hc_add_series_list(d)
}


text:
Q: How can I pass command line arguments to a program in a Windows batch file? I'm trying to do this :
cd C:\Users\Public
%1 /s

Where %1 is the name of and executable that changes based on a where it's being executed, but is otherwise identical. The issue is that the /s is being seen as a command or program and not an argument to the executable passed in %1. Is what I'm trying to do possible? If so, what's the syntax?

A: If you save what you have as testit.bat and then when you go to run it add the parameter after your batch file name: "testit dir" it will run the dir command with the /s switch.

A: Next example could help.  Note:

*

*" double quotes using: If a single parameter contains spaces, you can still pass it as one item by surrounding in "quotes" - this works well for long filenames: Syntax : Escape Characters, Delimiters and Quotes;

*%*in a batch script refers to all the arguments (e.g. %1 %2 %3 %4 %5 ... %255) but only arguments %1 to %9 may be referenced by number: Command Line arguments (Parameters)
The cliparsearg.bat script prints all command line arguments:
==>type cliparsearg.bat
@echo OFF >NUL
set /A "ii=0"
:loopfor
    echo param %%%ii% = %0
    SHIFT
    set /A "ii+=1"
if not [%0]==[] goto :loopfor
echo   all %%* = %*
goto :eof

==>cliparsearg.bat withoutspaces /S 3rdPar
param %0 = cliparsearg.bat
param %1 = withoutspaces
param %2 = /S
param %3 = 3rdPar
  all %* = withoutspaces /S 3rdPar

==>cliparsearg.bat with 2 spaces /S 3rdPar
param %0 = cliparsearg.bat
param %1 = with
param %2 = 2
param %3 = spaces
param %4 = /S
param %5 = 3rdPar
  all %* = with 2 spaces /S 3rdPar

==>cliparsearg.bat "with 2 spaces" /S 3rdPar
param %0 = cliparsearg.bat
param %1 = "with 2 spaces"
param %2 = /S
param %3 = 3rdPar
  all %* = "with 2 spaces" /S 3rdPar

Resources (basic required reading for Windows batch scripters):

*

*An A-Z Index of the Windows CMD command line

*Windows CMD Shell Command Line Syntax

A: Thanks for all your help guys. I looked at the documentation and your comments and, though I'm still completely unsure of how this is actually supposed to work, I got it working sensibly. Here's the solution I came up with:
"%~1" /s


text:
Q: How to remove a parent div based on the symbol it has inside? It is possible to remove the item which has (x) symbol including parent div.

            Item 1

Content 1

             (x)Item 1.1.1

Title 2

            Content 2

After removing it must be

            Item 1

Content 1

I wrote this regex
@"
(.*?)\(x\)(.*?)(.*?)
"

but it removes the first div also.
I have the id -663241532 accessible if it can help.

A: As suggested regexes are not the best tool for xml document manipulation. Example solution using Linq to XML:
var xDoc = XDocument.Parse(html);
var spansToRemove = xDoc.Descendants("span")
                        .Where(s => s.Value.StartsWith("(x)")).ToArray();
foreach (var toRemove in spansToRemove)
{
    var element = toRemove;
    while (element != null && element.Name != "div")
        element = element.Parent;
    if (element != null)
        element.Remove();
}

A: I suggest you to use HtmlAgilityPack (available from NuGet) for working with HTML:
HtmlDocument doc = new HtmlDocument();
doc.Load("index.html");
var spans = doc.DocumentNode.SelectNodes("//span[contains(., '(x)')]");
foreach (var span in spans)
{
    HtmlNode parent = span.ParentNode;
    while (parent != null)
    {
        if (parent.Name == "div")
        {
            parent.Remove();
            break;
        }

        parent = parent.ParentNode;
    }
}

XPath above selects all span nodes which contain (x) text. Then in loop we search nearest div parent of each selected span and remove it.


text:
Q: How to use dangerouslySetInnerHTML I have html script data.
I want to put it in div. but when I do that It just shows "}" this and that's it.
I wonder what I did wrong.
When I log newDataHTML, I can get html string.
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {

  const getData = () => {
    axios
      .get('/api/data')
      .then( (data) => {
        // get new Data
        const newDataHTML = data.data[0].rule;

        return {__html: newDataHTML};
      })
      .catch( err => console.log(err));
  }

  return (

      <Tabs defaultTab="data" onChange={(tabId) => { console.log(tabId) }}>
        <TabList>
          <Tab tabFor="data">New Data</Tab>
        </TabList>
        <TabPanel tabId="data">

;
        </TabPanel>
      </Tabs>

  );
}

export default App;

A: It is not working because you can't return outside .then method and also you will encounter rerender loop... You can put the method in useEffect hook so it runs once and also put the return data in useState...
const [data, setData] = useState();
useEffect(() => {
   const getData = () => {
      axios.get('/api/data').then((res) => {
        const newDataHTML = res.data[0].rule;
        setData({__html: newDataHTML})
      }).catch( err => console.log(err));
   }
   getData();
}, [])

you can now use the data variable in your jsx instead of calling the function in your jsx.
It will also be nice to use packages like DomPurify to avoid xss attacks.
https://www.npmjs.com/package/dompurify


text:
Q: Counting the number of data occurrences in each pandas column I have the following dataframe:
import pandas as pd
df = pd.DataFrame({"E": ["X", "Y", "X", "X", "Y", "X"], "F": ["Y", "Y", "X", "Y", "X","Y"], "G": ["Y", "X", "X", "X", "Y", "X"], "I": ["A", "B", "B", "B", "A", "A"]})
df.set_index("I", drop = True, inplace = True)

print(df)
   E  F  G
I
A  X  Y  Y
B  Y  Y  X
B  X  X  X
B  X  Y  X
A  Y  X  Y
A  X  Y  X

I want to count now the occurrence of each combination A-X, A-Y, B-X, B-Y for each column E, F, G, so the expected output would be:
       E     F     G
       X  Y  X  Y  X  Y
I
A      2  1  1  2  1  2
B      2  1  1  2  3  0

I know that I can do it for one column with pd.crosstab. So I could iterate through the columns and concatenate the dataframes:
for i, column in enumerate(df.columns):
    if i == 0:
        df1 = pd.crosstab(df.index, df[column])
    else:
        df1 = pd.concat([df1, pd.crosstab(df.index, df[column])], axis = 1)

But apart from the fact that iteration feels unpandaish and I expect there is a better solution, the index also lost the information regarding the initial columns:
       X  Y  X  Y  X  Y
row_0
A      2  1  1  2  1  2
B      2  1  1  2  3  0

What would be a way to achieve the correct output?

A: you can use get_dummies on df and then groupby on the indexes and use sum:
df1 = pd.get_dummies(df).groupby(level=0).sum()

and you get:
   E_X  E_Y  F_X  F_Y  G_X  G_Y
I
A    2    1    1    2    1    2
B    2    1    1    2    3    0

if you want a multiindex level for the column, you can do:
df1.columns = pd.MultiIndex.from_tuples([col.split('_') for col in df1.columns])

and you get as your expected output


text:
Q: Установить selenium webdriver chromedriver на linux, используя python Я на стадии настройки Selenium на Ubuntu. Хочу использовать python 3.5 и chrome browser. Я установила pip3 и python 3.5. Скачала selenium и chromedriver через терминал и pip3. Сейчас я ничего не могу запустить, потому что получаю ошибку при загрузке webdriver:

Полагаю, проблема в версии pip. Похоже, используется pip вместо pip3 - но как заставить работать pip3?

A: Проблема была не в pip и не в версиях питона, а в том что на моей ubuntu стоял хром не последней версии. А хромдрайвер я естесственно скачала последний. Только после апдейта хрома все заработало.

A: Думаю, что у Вас просто не установлен pip3. Для того, чтобы его установить, нужно сделать apt-get. Предварительно, право, обновите его:
sudo apt-get update

Далее можете ставить pip3:
sudo apt-get install python3-pip

Если же вдруг окажется, что pip3 поставлен, то в любом случае, попробуйте его переустановить:
sudo apt-get remove python3-pip

Что касается pip и pip3. Первый объект, как правило относится к python2.7. Второй -- к python3.5. Часто бывает так, что при установке версии 2.7 pip устанавливается сразу. С pip3 обычно больше косяков. Его нужно подтянуть apt-get, как я указал выше. Но нужно понимать, что по неведомым мне причинам при установке пакетов для 3 версии, проблем возникает гораздо больше, чем при работе со 2 версией.
Что касается selenium и webDriver, то устанавливать Вам нужно именно selenium. По крайней мере, на 2 питоне вместе с ним в комплекте идёт и webdriver для большого кол-ва браузеров. Сделать это можно, очевидно, так:
sudo pip3 install selenium

После проделанных операций, по идее, всё будет более или менее ставиться из PyCharm, в котором Вы работаете.


text:
Q: managedObjectContext is null if I set it as using property, but non-null if I set it as chained controller If I use the following code in order to set AppDelegate's managedObjectContext to the firstViewController, which is just a subclass of UITableViewController in AppDelegate.m's application: didFinishLaunchingWithOptions method,

    rootTabBarController *rootabbarcontroller = (rootTabBarController *)self.window.rootViewController;

    UINavigationController *navigationController = [[rootabbarcontroller viewControllers] objectAtIndex:0];
    FirstViewController *firstViewController = [[navigationController viewControllers] objectAtIndex:0];

    firstViewController.managedObjectContext = self.managedObjectContext;

and then run the simulator, the value of managedObjectContext is set to non-null within FirstViewController.m's viewDidLoad method, and hence the Core Data works as expected.
However, when I tried to write the following code in the application: didFinishLaunchingWithOptions: method:

_firstViewController.managedObjectContext = self.managedObjectContext;

and run the simulator, the resultant managedObjectProperty value within FirstViewController.m's viewDidLoad method is set to null.
So I wonder why the first implementation, which is chained from the root UITabBarController to root UINavigationController to FirstViewController works within its viewDidLoad: method, but the latter (just directly set to its property) doesn't.
It's worth noting that I declared @property (nonatomic, strong) FirstViewController *firstViewController; in AppDelegate.h when I tried to implement in the latter way. Also set its class to the appropriate view controller in storyboard.
I've read some blogs to take the latter approach (links are not handy, sorry), so it would be possible to take the latter route to set its managedObjectContext value correctly and synthesize Core Data with UITableView.
So what am I missing? And is it feasible to just take the latter approach (which saves me of a lot of coding and potential unexpected bugs)? And finally, which is the better way to take?
I use Xcode 5 and iOS 7, thanks.
[updated]
If I tried to add the following line as suggested by Almas in the answer below,
self.firstViewController = firstViewController;

then I got an compile error since firstViewController isn't defined there.
And so I added the initialization of the firstViewController, by adding the following line just above the above line.
FirstViewController *firstViewController = [[FirstViewController alloc] init];

but then the AppDelegate.m looks like working correctly, but this time, an error occurred in viewDidLoad method of the FirstViewController.m, which is the same as my first reported one.

A: Did you set your local variable firstViewController to ivar/property before setting managed object context to it?
add:
self.firstViewController = firstViewController;
// or
_firstViewController = firstViewController;

before:
_firstViewController.managedObjectContext = self.managedObjectContext;


text:
Q: retrieve output logfile value from logger i try to use python logging module to create a timed rotating handler to some sort cache to a file.
eventually i need to know what is the cache file name.
i cannot find any property in logger to retrieve it.
so i create kind of monkey job to overload the logger for later retrieve.
anybody know a better solution?
    def srvcacheconfig(**kwargs):
        srv_name = kwargs['server_name']
    #     cache_path = CACHEPATH
    #     ans=dict()
        cache_filename = srv_name+CACHE_EXT
        cache_logger = logging.getLogger(srv_name)
        cache_logger.propagate = False

        #monkey job
        cache_logger.cache_name = cache_filename

        cache_format = logging.Formatter("%(message)s")
    #     cache_handlers = logging.handlers.TimedRotatingFileHandler(cache_filename, when = 'midnight', backupCount = 366)
        cache_handlers = logging.handlers.TimedRotatingFileHandler(cache_filename, when = 'M', interval = 1, backupCount = 200)

        cache_handlers.setFormatter(cache_format)
        cache_logger.addHandler(cache_handlers)

#       consoleHandler = logging.StreamHandler()
#        cache_logger.addHandler(consoleHandler)

        cache_logger.setLevel(logging.DEBUG)
        return cache_logger

thank you very much

A: The TimedRotatingFileHandler has a property named baseFilename, which holds the name of the logfile. However, this is not documented and may therefore change without further notice.
From this property you can get the logfile's name:
import logging
from logging.handlers import TimedRotatingFileHandler

my_logger = logging.getLogger('my_logger')
my_handler = TimedRotatingFileHandler('logfile.log')
my_logger.addHandler(my_handler)

def get_filename(some_logger):
    return [some_handler.baseFilename
            for some_handler in some_logger.handlers
            if isinstance(some_handler, TimedRotatingFileHandler)]

print(get_filename(my_logger))  # ['/home/finwood/temp/so/logfile.log']


text:
Q: Does an arbitrary function preserve arbitrary intersections? Let $S,T$ be sets and let $\Lambda$ be an index-set. Let $f:S\to T$ and $\{A_\lambda\}_{\lambda\in\Lambda}$ be a collection of subsets in $S$ (i.e. $A\lambda\subset S$ for all $\lambda\in\Lambda$). Does $f$ satisfy $$f\left[\bigcap_{\lambda\in\Lambda} A_\lambda\right]\subset\bigcap_{\lambda\in\Lambda} f[A_\lambda]\text{ and }f\left[\bigcup_{\lambda\in\Lambda} A_\lambda\right]=\bigcup_{\lambda\in\Lambda} f[A_\lambda]?$$

A: Sure; the arguments are exactly the same as for the finite case.
Suppose that $x\in\bigcap_{\lambda\in\Lambda}A_\lambda$; then $x\in A_\lambda$ for each $\lambda\in\Lambda$, so $f(x)\in f[A_\lambda]$ for each $\lambda\in\Lambda$, and therefore $f(x)\in\bigcap_{\lambda\in\Lambda}f[A_\lambda]$. It follows immediately that
$$f\left[\bigcap_{\lambda\in\Lambda}A_\lambda\right]\subseteq\bigcap_{\lambda\in\Lambda}f[A_\lambda]\;.$$
Now suppose that $x\in\bigcup_{\lambda\in\Lambda}A_\lambda$; then there is some $\lambda_0\in\Lambda$ such that $x\in A_{\lambda_0}$. Clearly $f(x)\in f[A_{\lambda_0}]\subseteq\bigcup_{\lambda\in\Lambda}A_\lambda$, so
$$f\left[\bigcup_{\lambda\in\Lambda}A_\lambda\right]\subseteq\bigcup_{\lambda\in\Lambda}f[A_\lambda]\;.$$
Conversely, if $y\in\bigcup_{\lambda\in\Lambda}f[A_\lambda]$, then $y\in f[A_{\lambda_0}]$ for some $\lambda_0\in\Lambda$, and therefore there is an $x\in A_{\lambda_0}$ such that $f(x)=y$. Clearly $x\in\bigcup_{\lambda\in\Lambda}A_\lambda$, so $f(x)\in f\left[\bigcup_{\lambda\in\Lambda}A_\lambda\right]$, and it follows that
$$f\left[\bigcup_{\lambda\in\Lambda}A_\lambda\right]\supseteq\bigcup_{\lambda\in\Lambda}f[A_\lambda]$$ and hence that
$$f\left[\bigcup_{\lambda\in\Lambda}A_\lambda\right]=\bigcup_{\lambda\in\Lambda}f[A_\lambda]\;.$$

A: We can do some element-chasing and show this is indeed true:
Suppose $y\in f\left[\bigcap A_\lambda\right]$, then there is some $x\in\bigcap A_\lambda$ such that $f(x)=y$. This means that for all $\lambda$, $x\in A_\lambda$ so $y\in f\left[A_\lambda\right]$ for all $\lambda$, and thus the inclusion holds.
For the union, let $y\in f\left[\bigcup A_\lambda\right]$, then there is some $\lambda$ and $x\in A_\lambda$ such that $y=f(x)$, therefore $y\in f\left[A_\lambda\right]$ and therefore $y\in\bigcup f\left[A_\lambda\right]$. The other direction is similar.

A: The first holds since $f\left(\bigcap_\lambda A_\lambda\right) \subseteq f(A_\lambda)$
for all $\lambda\in\Lambda$.  This inequality can be strict.
The second is easy to prove. It is true.


text:
Q: How to run custom SQL queries in Moodle? I found the predefined query functions in Moodle are not very handy when the query is getting complex. Most predefined functions can be found here: https://docs.moodle.org/dev/Data_manipulation_API
I am wondering if there is a function in Moodle that allows me to run any custom SQL queries so that I can do whatever I need to the Moodle DB (i.e. like using php query() function to run custom queries).
One example would be, I was trying to get last row from the table 'trigger_message', I know in php I can do
$sql=("
      SELECT Trigger_id
      FROM trigger_message
      ORDER BY trigger_Id
      DESC limit 1
     ");

$id = $DB->query($sql);

But in moodle I have no clue how to do it, could anybody advise please?

A: Every one of the Moodle DB functions has an _sql variant that accepts SQL + params - see the docs here: https://docs.moodle.org/dev/Data_manipulation_API
So, from your example, you will probably want something like:
$id = $DB->get_field_sql("SELECT MAX(trigger_id) FROM {trigger_message}");

(which will sort out the correct prefix for the trigger_message table - usually mdl_trigger_message).
However, for the example you have given, you probably want to write:
$id = $DB->get_field('trigger_message', 'MAX(trigger_id)');


text:
Q: Crear botones verticales fijos de la A a la Z en una página Quiero realizar unos botones de manera vertical, que queden fijos a la izquierda de la página y que siempre estén visibles. Lo botones son todo el abecedario quedando por ejemplo así:
A
B
C
D
E
.
.
.
.
Y
Z

Sé que puede quedar muy largo en mi página, pero quizás le pueda poner una especie de barra o flechas (hacia arriba o hacia abajo) para acortar el abecedario y de esta manera se mueva haciendoles clic.
Claro que no voy a poner uno por uno los botones hasta llegar a la "Z" (seria tedioso y mucho "código"), la idea es hacer una especie de for para recorrer e ir poniendo en cada botón la letra.
El funcionamiento del mismo es que luego cuando se hace clic en una letra, por ejemplo la "E", me tiene que llevar a donde este todo el contenido que empieza con dicha letra (en la página estoy mostrando diferentes palabras ordenadas alfabéticamente).
Me gustaría saber cómo podría realizar esto. En CSS hay que poner position: fixed y display: block, eso esta bien. El problema es que no sé como hacer la parte de crear estos botones desde JavaScript o JQuery con un for (desde la A a la Z) e ir creando los elementos (por ejemplo para una lista), algo como

...
Espero me puedan dar una idea.

A: Este ejemplo crea los elementos
 de una lista
. Si lo abres en el inspector verás que dentro de cada
 hay un elemento  cuyo href="#${letra}". O sea: tus fragmentos de contenido tendrán que llevar un id Por ejemplo lo de la letra a tendrá id="a"

let abc = ""
for(let i=97; i <= 122; i++){
let letra = String.fromCharCode(i);
abc+= `<li><a href="#${letra}">${letra}</a></li>`
}

alfabeto.innerHTML = abc;

A continuación un ejemplo básico de como quedaría con los articulos que tienen un id

let abc = "";//el alfabeto
let art = "";// los articulos

for(let i=97; i <= 122; i++){
let letra = String.fromCharCode(i);
//crea los elementos li
abc+= `<li><a href="#${letra}">${letra}</a></li>`
//crea los articulos cun su id y un elemento a que apunta hacia arriba
art+= `

${letra}${letra}${letra}${letra}

`
}

alfabeto.innerHTML = abc;
articulos.innerHTML = art;
#wrap{display:flex}
section article{padding:1em;display:block;height:10em}


text:
Q: Show attached image after upload trough SonataAdmin I have a Product entity mapped as follow:
class Product
{

    use IdentifiedAutogeneratedEntityTrait;
    use BaseEntityTrait;

    ......

    /**
     * @ORM\ManyToOne(targetEntity="\Application\Sonata\MediaBundle\Entity\Media")
     * @ORM\JoinColumn(name="product_image", referencedColumnName="id")
     */
    protected $image;

   ......

    public function setImage(\Application\Sonata\MediaBundle\Entity\Media $image)
    {
        $this->image = $image;
    }
}

Then in my admin form I have this:
protected function configureFormFields(FormMapper $form)
{
    $form
            ->add('product_name', null)
            ->add('product_description', null)
            ->add('image', 'sonata_type_admin');
}

When I add a new product I can upload a image and yes it works but I can see the image on the page where I'm creating the product, how I can do that?

A: I think you have to use sonata_type_model_list and not sonata_type_admin.
protected function configureFormFields(FormMapper $form)
{
    $form
            ->add('product_name', null)
            ->add('product_description', null)
            ->add('image', 'sonata_type_model_list');
}


text:
Q: How to change Nvidia graphic resolution in Ubuntu 12.04? I ran this command in the terminal:
sudo service lightdm stop

After that the only resolution that I have is 640*480! My screen's resolution is 1366*768 in windows. How can I set the resolution to 1366*768??

A: if you simply want to change resolution manually go to system settings/displays and apply desired one.
if you got messed up with nvidia configuration do the following:
press Ctrl + Alt + F1 and run:
sudo /etc/init.d/lightdm stop

sudo dpkg-reconfigure xserver-xorg

sudo /etc/init.d/lightdm start

if you need to configure new installation of nvidia run in terminal Ctrl + Alt + T:
sudo nvidia-xconfig

gksudo nvidia-settings


text:
Q: Handlebars - output a value inside curly braces My output needs to look somewhat like:
{foo} bar

The problem is the value foo comes from either a field or a helper. I could make the helper include the brackets {foo} but that doesn't seem a perfect solution. On the other hand if I try:
{{{foo_field}}} {{bar_field}}

That doesn't work as tripple braces also render the field in a slightly different manner.

A: Solution copied from Simple way to escape curly braces?
{ {{~foo_field~}} } {{bar_field}}


text:
Q: How to bind angular property to model as array? My component is
import { Component } from '@angular/core';

export class LocationModel {
  name: string;
  position: {
    center: any[]
  }
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  model: LocationModel = new LocationModel();

  onSubmit() {
    console.log(this.model);
  }
}

And HTML component template is:
<form (ngSubmit)="onSubmit(f)">
 Location name:
 <input
   type="text"
   [(ngModel)]="model.name"
   name="firstName">

lon:
 <input
   type="text"
   [(ngModel)]="model.positon.center[1]"
   name="lon">

lat:
 <input
   type="text"
   [(ngModel)]="model.positon.center[0]"
   name="lat">

 <input type="submit" value="Submit">
</form>

{{model|json}}

But I could not create a json template like following:
{ "name": "some name", "position": { "center": [ 30.6067, 490.5563189 ] } }

A: Can you please try like this,
Assigning initial value to center
export class LocationModel {
  name: string;
  position: {
    center: ["",""]
  }
}

Html:
<form (ngSubmit)="onSubmit(f)">
 Location name:
 <input
   type="text"
   [(ngModel)]="model.name"
   name="firstName">

lon:
 <input
   type="text"
   [(ngModel)]="model.positon.center[1]"
   name="lon">

lat:
 <input
   type="text"
   [(ngModel)]="model.positon.center[0]"
   name="lat">

 <input type="submit" value="Submit">
</form>

{{model|json}}


text:
Q: vector output for if_else or alternative I'm struggling to find an answer to the following problem.
I want to search a column in a data.frame by a vector.  Upon finding a match I then wish to utilise the element of the 'search vector' to create a new element of a new column.  See the reproducible example below please.
colour <- c('red', 'yellow')

a <- c('violet', 'red', 'taupe', 'blue', 'yellow_a', 'yellow_b', 'blue_a', 'red_c')
b <- c('non', 'prim', 'non', 'prim', 'prim', 'prim', 'prim', 'prim')
c <- c(1, 2, 3, 4, 5, 6, 7, 8)

df <- data.frame(a, b, c)

I've tried the following:
df_clean <- df %>% mutate(d = if_else(str_detect(a, colour), colour, NA_character_))

The Output:
Problem:  Looking at help files I'm unable to output greater than 1 from an 'if_else', I'm receiving the following:

Error: Problem with mutate() column d. ℹ d = if_else(rep(str_detect(a, colour), length(colour)), colour, NA_character_). x true must be length 16 (length of condition) or
one, not 2.

I'm looking to achieve:
a <- c('violet', 'red', 'taupe', 'blue', 'yellow_a', 'yellow_b', 'blue_a', 'red_c')
b <- c('non', 'prim', 'non', 'prim', 'prim', 'prim', 'prim', 'prim')
c <- c(1, 2, 3, 4, 5, 6, 7, 8)
d <- c(NA_character_, 'red', NA_character_, NA_character_, 'yellow', 'yellow', NA_character_, 'red')

df_clean <- data.frame(a, b, c, d)

Requirements:
If you could help me fix this or find an alternative solution I would be most grateful, I'm unable to bridge the gap.  I'm missing something potentially obvious?
Any help would be greatly appreciated!
Many Thanks

A: Potential solution with str_extract from the stringr package.
colour <- c('red', 'yellow')

a <- c('violet', 'red', 'taupe', 'blue', 'yellow_a', 'yellow_b', 'blue_a', 'red_c')
b <- c('non', 'prim', 'non', 'prim', 'prim', 'prim', 'prim', 'prim')
c <- c(1, 2, 3, 4, 5, 6, 7, 8)

df <- data.frame(a, b, c)

colour_str <- paste(colour, collapse='|')

df |>
  mutate(d = str_extract(a, colour_str))

Output:
         a    b c      d
1   violet  non 1   <NA>
2      red prim 2    red
3    taupe  non 3   <NA>
4     blue prim 4   <NA>
5 yellow_a prim 5 yellow
6 yellow_b prim 6 yellow
7   blue_a prim 7   <NA>
8    red_c prim 8    red

A: You were very close from the solution :
a <- c('violet', 'red', 'taupe', 'blue', 'yellow_a', 'yellow_b', 'blue_a', 'red_c')
b <- c('non', 'prim', 'non', 'prim', 'prim', 'prim', 'prim', 'prim')
c <- c(1, 2, 3, 4, 5, 6, 7, 8)
d <- c(NA_character_, 'red', NA_character_, NA_character_, 'yellow', 'yellow', NA_character_, 'red')

my_df <- data.frame(a, b, c, d)
pattern <- "red|yellow"
my_df$test <- ifelse(test = str_detect(string = my_df$a, pattern = pattern) == TRUE, yes = str_extract(string = my_df$a, pattern = pattern), no = NA)


text:
Q: Does graphene-django dynamically create an API documentation? I'm considering using GraphQL with a Django backend service but I couldn't find much information regarding the API documentation. I need some solution to dynamically generate the documentation, perhaps like npm's graphql-docs with a result similar to GitHub's API docs.
Is it feasible to accomplish with graphene-django? If not, what's a good alternative for a python environment?

A: Yes, it's very easy to do by using GraphiQL, which is embedded in to Graphene.
The instructions on how to integrate this with Graphene are here in the graphene-python documentation. --- basically you need to add the parameter graphiql=True when setting up the API route in your urls.py file.
After it is set up, if go to your API endpoint in your browser, you'll see a nice interface for sending API calls, getting API responses, and reading documentation for both queries and mutations.  The documentation is initially hidden on the right until you click on the "< Docs" link.


text:
Q: How to make a Symfony2 Bundle Live on a Website Sorry if this is a dumb question, but I have been looking around for a bit with no luck finding an answer. I am new to Symfony2 and spent the last couple weeks installing it on my website's server, making a bundle and building all the pages, and testing it out with its app_dev.php urls. I'm now ready to make it public on my site, but I'm not sure how to go about doing this. Basically, I want to activate the bundles so instead of having to go to website/symfony/web/app_dev.php/Page, I can just go to website/Page. Thanks!

A: Ok, so thats not really a Symfony issues and it depends very much on your environment (mostly what webserver you are using). What you have to do is make the web folder of the symfony project your root folder (aka, where right now is the symfony folder) and move all other folder within symfony folder one level up. So lets say you have your httpdocs or www folder as your root folder, you have to copy the contents of symfony/web in that folder and move everything else from symfony folder one level above httpdocs folder. That being said, probably there is a lot more configuration that goes on into it. Here are a couple of resources to get you started:
http://symfony.com/doc/current/cookbook/deployment-tools.html
Symfony2: How to deploy in subdirectory (Apache)
Remember that in live mode you should be accessing app.php and not app_dev.php...

A: I tend to do it by adding those lines to an .htaccess file on the root:
<IfModule mod_rewrite.c>
RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ web/$1 [QSA,L]
</IfModule>

Then the original .htaccess file in the web directory takes care of the rest.


text:
Q: Polymorph design when filling a map container in C++ I'm not good at OOP design, but I need to demonstrate my knowledge to potential employer.
The situation is following:
I've got a file with parameters of key-value type, called parameters.txt.
I've got a map <string, CommonParamValue> as a container. I need to fill it with elements, using the file with parameters. The key is always a std::string parameter, the CommonParamValue can be represented with int, double, string and a standard function call. To implement this, the CommonParamValue is a base class with virtual methods. It has childs - StringParamValue, DoubleParamValue, CurTimeParamValue. The base class and every child have a method virtual string GetValue() that returns a string representation of inner data; virtual void SetValue(string) to set the value.
The question is how to fill the container map <string, CommonParamValue> with appropriate data in runtime using polymorphism? Now I've got such situation:
parameters.txt
*user_name=Jane
*order_number=1325
current_date=

Routine for filling map
ifstream in(fileParamsPath);
    if (! in)
    {
        cout << "Cannot open file with parameters, program is terminating." << endl;
        cin.get();
        exit(-1);
    }
    string key = "", value = "";
    while(in)
    {
        getline(in, key, '=');
        getline(in, value, '\n');

        // put key and value into the container
        // right here we need to analyze the data type and choose appropriate container.
        // CommonParamValue *paramValue = new DoubleParamValue(); or
        // CommonParamValue *paramValue = new CurTimeParamValue(); or
        // CommonParamValue *paramValue = new StringParamValue();

        paramValue->SetValue(value);
        params.insert(make_pair(key, *paramValue)); // params is a map <string, CommonParamValue>
        delete paramValue;
    }
    in.close();

There's an idea to keep the type of value-parameter in file parameters.txt and analyze it when filling map <string, CommonParamValue>
parameters.txt
*user_name=Jane
string

*order_number=1325
int

current_date=
function

And modify routine for filling map <string, CommonParamValue> this way:
string key = "", value = "", type = "";
    while(in)
    {
        getline(in, key, '=');
        getline(in, value, '\n');
        getline(in, type, '\n');
        in.get(); // got the dividing empty string
        // put key and value into the container
        // right here we need to analyze the data type and choose appropriate container.
        if(type == "int")
        {
            CommonParamValue *paramValue = new IntParamValue();
        }
        else if(type == "function")
        {
            CommonParamValue *paramValue = new CurTimeParamValue();
        }
        else if(type == "string")
        {
            CommonParamValue *paramValue = new StringParamValue();
        }
        else
        {
            // error
            exit(1);
        }

        paramValue->SetValue(value);
        params.insert(make_pair(key, *paramValue)); // params is a map <string, CommonParamValue>
        delete paramValue;
    }

Is that a good decision or bad? Maybe my potential employer wanted me to implement it in other way, but I have only this decision. Is there any better one for a junior C++ programmer?

A: The most classic design applicable is that of a factory method design.
CommonParamValue* createParamValue( const std::string &value );

The createParamValue method takes the responsibility of creating the appropriate derived ParamValue and return it as a CommonParamValue.
You can avoid pumping additional strings for "type" into parameters.txt by inferring the type, inside createParamValue, using the value string. A regular expression sounds like the most elegant for int, double and CurTime. Boost regex is an example library lets you do this in c++. But of course if you're looking for a quick solution, then writing your own 30-line decision tree should not be a problem for these simple grammars.

A: The if statements in client code looks a bit iffy to me. Could try a factory class?
Have a Base Class IParamValue
IntParamValue : public IParamValue { }

static IParamValue * Create(string selection);

IParamValue * IParamValue::Create(string selection)
{
    if (selection == "int") return new IntParamValue();
    ...
}

Client code:
IParamValue* param = IParamValue::Create ("something");


text:
Q: Does a subsequence need to be continuous I am new to Dynamic Programming and was reading on the Longest Increasing Subsequence(LIS) problem.
The solution stated that the sequence need not be continuous as in the original array. Elements can be skipped in between; but I was under another impression.
Could you please help clarify this confusion.
Say for example:
a = {10,22,9,33,55,66,12,90}
the LIS is {10,22,33,55,66,90} => 6
However, I thought it would be {33,55,66}
Thanks

A: Subsequence doesn't need to be continous. A Subsequence is formed by deleting zero or more elements from an array. A subaaray on the other hand is always continous. Lets's take your example:
a = {10,22,9,33,55,66,12,90}

Here,{10,22,33,55,66,90} is the longest increasing subsequence and {33,55,66} is the longest increasing subarray.
So, what you are basically answering is a solution to the longest increasing subarray problem.


text:
Q: Show that x'X'y=y'Xx Can anyone prove the following
x'X'y = y'Xx
Where x,y is a column vector and X is a (n x k) matrix.

I mean its obvious when the above is a quadratic form, but less so when it is a bivariate function.

A: Hint: $A = x'X'y$ is a $1 \times 1$ matrix, so $A = A'$.


text: Q: Download events and reports from Trend Micro DSM Is there a way to download events and reports like IP events or IM events or single reports like Alert/attack reports from Trend using API by coding. If there isn't can a module for this be made?


text:
Q: replacing img src attribute w/ jQuery not working I'm trying to create simple slideshow where if I click the image it will turn into the next image. So far I have four images in a subfolder, named 1-4 (ex: 1.jpg, 2.jpg, 3.jpg, 4.jpg).
I've set up a counter (the variable imgcounter) so that if it is greater than 4 it will reset to 1, and I use this counter to easily change the src name of the img element.
The simple version:
$(document).ready(function() {
var imgcounter = 1;
$('#slide img').each(function() {
    $(this).click(function() {
        if(imgcounter <= 4 ) {
            imgcounter++;
            $(this).attr('src', 'images/' + imgcounter + '.JPG');
        } // end if
        else {
            var imgcounter = 1;
            $(this).attr('src', 'images/' + imgcounter + '.JPG');
        } // end else
    }); // end click
}); // end each
});  // end ready

In this version the image will not even change if I click it.
I've also tried this more complicated method where I put a variable to define what I want to replace source with. I'm not sure if I'm using the replace() function right, especially at the part where I used double apostrophes '' to indicate I want to replace the entire src. I'm also not sure if I wrote out the second part of the replace() function legitimately -- the 'images/' + imgcounter + '.JPG'.
$(document).ready(function() {
var imgcounter = 1;
$('#slide img').each(function() {
    var imgFile = $(this).attr('src');
    var preloadImg = new Image();
    $(this).click(function() {
        if(imgcounter <= 4 ) {
            imgcounter++;
            preloadImg.src = imgFile.replace('', 'images/' + imgcounter + '.JPG');
            $(this).attr('src', preloadImg.src);
        } // end if
        else {
            var imgcounter = 1;
            preloadImg.src = imgFile.replace('', 'images/' + imgcounter + '.JPG');
            $(this).attr('src', preloadImg.src);
        } // end else
    }); // end click
}); // end each
});  // end ready

In this version the image changed but I get a broken image symbol and the error console reads:
Failed to load resource file:///..(took out full path)../images/1.JPGimages/1.JPG
I'm not sure why it's failing to replace the entire source and instead it just seems to append a copy of the source name at the end...
Thanks for any help in advance!

A: I'd do something like:
var imgcounter = 1;

$("#slide img").click(function(e){
    if(imgcounter < 4){
        imgcounter++;
    }else{
        imgcounter = 1;
    }
    $(this).attr("src", "images/"+imgcounter+".jpg");
});

It adds the handler to each img inside #slide anyway, so no need for the each() function, and it looks a lot cleaner.
Also, removed the redundant call to $(this).attr().


text:
Q: can we cache count query before request hits django I have home page which lists from a very large table. It is paginated by PageNumberPagination. The loading time of this page is affected because of the count(*) query of the paginator. I resolved slowness for all other requests by installing django-cachalot. However the first request still takes up a lot of time. I tried to create a fake request in AppConfig.ready() so that the count(*) query gets cached every time when the project loads up. But it didn't work.
Is there a clean hack for caching the count(*) query before the first request is made?

A: Clean Hack? Not really! :)
However, you may play around with a custom class of your own inheriting from PageNumberPagination. Then try to reimplement de count function on the parent Paginator class:
@cached_property
def count(self):
  """Return the total number of objects, across all pages."""
  c = getattr(self.object_list, "count", None)
  if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c):
    return c()
  return len(self.object_list)

Even though that function says @cached_property it will create a new instance of Paginator class for every request, so, not so much cached.
So, you may implement your own caching solution over this function.


text:
Q: Android WebChromeClient integration with javaScript gives Unexpected Illegal token Home.java
public void updatePhoto(Bitmap bitmap) {
   String bitmapStr = BitMapToString(bitmap);
   Home.currentBmp = bitmap;

   String parameter = "data:image/jpeg;base64," + bitmapStr;

   webView1.loadUrl("javascript:var script = document.createElement('script');" +
      "script.type='text/javascript';script.src='form.js';" +
      "script.onload=" + "processImage('" + parameter + "');" +
      //"script.onload=" + "processImage(':/;//');" +
      "document.getElementsByTagName('head').item(0).appendChild(script);");
   Log.v(parameter, "QWERTY");
   Log.v("QWERTY", parameter);
}

form.js
function processImage(img) {
   alert('process image end');
}

this function converts the Bitmap object into a base64 String, then executes an external javascript function (form.js -> processImage(var)). However it doesn't execute processImage and gives an Uncaught SyntaxError: Unexpected token ILLEGAL. However when i uncomment the
//"script.onload=" + "processImage(':/;//');" +

line and comment in
"script.onload=" + "processImage('" + parameter + "');" +

it seems that the function is working well. The possible value for parameter variable would be
data:image/jpeg;base64,iVBORw0KgoAAAANSHUEgAAA......

What I am asking is how am I gonna make the javaScript function work with the parameter? Thanks!


text:
Q: How to Disable SharePoint form field in forms through designer How can I Disable input fields in forms through SharePoint Designer.

A: Open the form in SharePoint Designer and go to the Code view.
On your Mentor Name field change the ControlMode attributes from "Edit" to 'Display".  There should be 2 occurrences:
<SharePoint:FormField runat="server" id="ff1{$Pos}" ControlMode="Display" FieldName="Title" __designer:bind="{ddwrt:DataBind('u',concat('ff1',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Title')}"/>

<SharePoint:FieldDescription runat="server" id="ff1description{$Pos}" FieldName="Title" ControlMode="Display"/>

A: Using ControlMode="Display" does not work when the ControlMode for this form is "new"; if that is the case then using jquery in this manner will do the same:
$('selector').attr('disabled','disabled')

A: Lost in Alabama's solution works in SP2010 for new forms as well as edit forms; you shouldn't need jQuery for this.
You will, however, need to create a new New Item form and then edit in code view, replacing ControlMode="New" with ControlMode="Display".  And of course these shouldn't be required fields.
Here is a New Item form example for an entire row:

            <nobr>Supplier</nobr>

        <SharePoint:FormField runat="server" id="ff16{$Pos}" ControlMode="Display" FieldName="Supplier" __designer:bind="{ddwrt:DataBind('i',concat('ff16',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Supplier')}"/>
        <SharePoint:FieldDescription runat="server" id="ff16description{$Pos}" FieldName="Supplier" ControlMode="Display"/>

Result:

If you want to hide the field you can simply change the class to "ms-hidden" for both class fields, example:

            <nobr>Supplier</nobr>

        <SharePoint:FormField runat="server" id="ff16{$Pos}" ControlMode="New" FieldName="Supplier" __designer:bind="{ddwrt:DataBind('i',concat('ff16',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Supplier')}"/>
        <SharePoint:FieldDescription runat="server" id="ff16description{$Pos}" FieldName="Supplier" ControlMode="New"/>

Result:


text:
Q: Python Pandas - Day and Month mix up I have a 'myfile.csv' file which has a 'timestamp' column which starts at
(01/05/2015  11:51:00)
and finishes at
(07/05/2015  23:22:00)
A total span of 9,727 minutes
'myfile.csv' also has a column named 'A' which is some numerical value, there are values are multiple values for 'A' within each minute, each with a  unique timestamp to the nearest second.
I have code as follows
df = pd.read_csv('myfile.csv')
df = df.set_index('timestamp')
df.index = df.index.to_datetime()
df.sort_index(inplace=True)
df = df['A'].resample('1Min').mean()
df.index = (df.index.map(lambda t: t.strftime('%Y-%m-%d %H:%M')))

My problem is that python seems to think 'timestamp' starts at
(01/05/2015  11:51:00)
-> 5th January
and finishes at
(07/05/2015  23:22:00)
-> 5th July
But really 'timestamp' starts at the
1st May
and finishes at the
7th of May
So the above code produces a dataframe with 261,332 rows, OMG, when it should really only have 9,727 rows.
Somehow Python is mixing up the month with the day, misinterpreting the dates, how do I sort this out?

A: There are many arguments within csv_read that can help you parse dates from a csv straight into your pandas DataFrame. Here we can set parse_dates with the columns you want as dates and then use dayfirst. This is defaulted to false so the following should do what you want, assuming the dates are in the first column.
df = pd.read_csv('myfile.csv', parse_dates=[0], dayfirst=True)

If the dates column is not the first row, just change the 0 to the column number.

A: The format of dates that you have included in your question don't seem to match your strftime filter. Take a look at this to fix your string parameter.
It looks to me that it should be something in the lines of:
'%d/%m/%Y %H:%M:%S'


text:
Q: Where do I need to place the routing for a (post) function in nodejs with express application? I have made a few websites with Pug in a Nodejs with express application.
On the websites there is also a contact form which people can fill in to ask questions.
My question is; where do I need to place the routing for the mail function?
Let's say that there is only a console.log(123) in that function to keep it easy?!
See below the structure (of the most necessary files):
- site
  - config
      - assets
          default.js
          development.js
      - env
          default.js
          development.js
      - lib
          app.js
          express.js
          logger.js
          pug-routes.js
          socket.io.js
      config.js
  - modules
      - core
          - client
              - app
                  config.js
                  init.js
              - config
                  core.client.route-filter.js
                  core.client.routes.js
                  core-admin.client.routes.js
              - controllers
                  header.client.controller.js
                  home.client.controller.js
              - css
              - directives
              - services
              - views
          - server
              - controllers
                  core.server.controller.js
              - routes
                  core.server.routes.js
              - views
                  layout.server.view.html
      - website
          - client
              - css
              - img
              - js
          - server
              contact.pug
  - node_modules
  - public
  - scripts
  package.json
  server.js

Server.js:
/* eslint no-mixed-spaces-and-tabs: "error" */
/* eslint indent: ["error", 4] */
'use strict';

/**
 * Module dependencies.
 */

var app = require('./config/lib/app');
var server = app.start();

module.exports = app;

App.js
/* eslint no-mixed-spaces-and-tabs: "error" */
/* eslint indent: ["error", 4] */
'use strict';

/**
 * Module dependencies.
 */
var config = require('../config'),
    mongoose = require('./mongoose'),
    express = require('./express'),
    chalk = require('chalk'),
    seed = require('./seed'),
    Mollie = require('mollie-api-node');

function seedDB() {
    if (config.seedDB && config.seedDB.seed) {
        console.log(chalk.bold.red('Warning:  Database seeding is turned on'));
        seed.start();
    }
}

// Initialize Models
mongoose.loadModels(seedDB);

module.exports.init = function init(callback) {
    mongoose.connect(function (db) {
        // Initialize express
        var app = express.init(db);
        if (callback) callback(app, db, config);
    });
};

module.exports.start = function start(callback) {
    var _this = this;
    _this.init(function (app, db, config) {
        // Start the app by listening on <port> at <host>
        app.listen(config.port, config.host, function () {
            // Create server URL
            const proto = process.env.NODE_ENV === 'secure' ? 'https' : 'http';
            var server = `${proto}://${config.host}:${config.port}`;

            // Logging initialization
            console.log('--');
            console.log(chalk.green(config.app.title));
            console.log();
            console.log(chalk.green('Environment:     ' + process.env.NODE_ENV));
            console.log(chalk.green('Server:          ' + server));
            console.log(chalk.green('Database:        ' + config.db.uri));
            console.log(chalk.green('App version:     ' + config.meanjs.version));
            if (config.meanjs['meanjs-version']) {
                console.log(chalk.green('MEAN.JS version: '
                                        + config.meanjs['meanjs-version']));
            }
            console.log('--');

            if (callback) callback(app, db, config);
        });
    });
};

Contact form:
form(method="POST" action="/mail")
        case (type)
            when 'slider'
                block
                .row
                    .col-md-8
                        .QapTcha
                            .bgSlider
                                .Slider.ui-draggable.ui-draggable-handle.e-resize.absolute
                                    .text-center.text-white(style='cursor:e-resize')
                                        i.fa.fa-chevron-right.btn-m-t-QapTcha.align-middle
                        input.d-none.submit(type='submit' name='submit' id=options.id submit=options.submit load=options.load)
                        div(style='fonts-size:11px')!=options.text
            when 'button'
                .row
                    .col-sm-12
                        .panel.panel-info
                            .panel-body
                                block
                .panel-footer
                    .form-group
                        button.btn.btn-primary.btn-lg.btn-block.submit(id=options.inputId submit=options.submit load=options.load type='submit')!=options.text
            default
                +createForm(options, 'slider')
        .feedback

I am familiar with node/pug/express, but i am not an expert.

A: You can add in init() function of App.js,
// Initialize express
var app = express.init(db);

app.post('/mail', (req, res) => {
    // Do your stuff
})

Just make sure you add this before starting app.


text:
Q: Performance of sequential and parallel computing with low cost tasks i have a List of Objects "Cell" which represent a current status.
List<Cell> currentCells = new ArrayList<Cell>();
I want to update the current status in a loop by calculating a future status (a new List of Cells) an then do replacing by "current status = future status" and so on. For that every Cell has a method which returns a new Cell Object representing its future. This method has simple math operations. There are no dependencies to other calculations. So, in theory, future Cells could be computet in parallel Threads.
My Problem is to find the fastet way of computing the future status cause the "List cells" is a very large ArrayList(4000000) and i want to reach up to 25 loops /second.
If i compute it sequentially my loop repeats 3 times / second. If i do high parallelisation by making each Cell a callable and putting them in an ExecuterService my loop repeats only with 0.5 per second.
List<Future<Cell>> futures = taskExecutor.invokeAll(cells);
I know that solving a problem in parallel always needs an overhead. In this case it speeds down my loop. What method can you recommend to speed up my loop?

A: There seems to be no difference in speed anyway if i change numberOfThreads from 1 up to 12 (i have maximum of 12 processors). The code of my loop is:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import view.ConsolePrinter;

public class Engine implements Runnable {

    private int numberOfThreads = 8;
    private boolean shouldRun = false;
    private ExecutorService taskExecutor;
    private Thread loopThread;
    private List<Cell> cells;
    private World world;
    private int numberOfRunningTimeSteps = 0;
    private int FPS = 30;
    private double averageFPS;

    public Engine(List<Cell> cells, World world) {
        this.cells = cells;
        taskExecutor = Executors.newFixedThreadPool(numberOfThreads);
        this.world = world;
    }

    @Override
    public void run() {

        world.resetTime();
        shouldRun = true;

        long startTime;
        long estimatedTimeMillis;
        long waitTime;
        long totalTime = 0;
        long targetTime = 1000 / FPS;

        int frameCount = 0;
        int maxFrameCount = 1;

        while (shouldRun) {

            startTime = System.nanoTime();

            try {
                List<Future<Cell>> futures = taskExecutor.invokeAll(cells);
                List<Cell> futureCells = new ArrayList<Cell>();

                futures.forEach((future) -> {
                    try {
                        futureCells.add(future.get());
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }

                });

                world.setCells(futureCells);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            world.timeProceeded();

            if (numberOfRunningTimeSteps != 0 && world.getTime() == numberOfRunningTimeSteps) {
                shouldRun = false;
            }

            estimatedTimeMillis = (System.nanoTime() - startTime) / 1000000;
            waitTime = targetTime - estimatedTimeMillis;
            try {
                if (waitTime > 0.0) {
                    Thread.sleep(waitTime);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            totalTime += System.nanoTime() - startTime;
            frameCount++;
            if (frameCount == maxFrameCount) {
                averageFPS = 1000.0 / ((totalTime / frameCount) / 1000000);

                frameCount = 0;
                totalTime = 0;
            }
        }

    }

    public void start(int n) {
        loopThread = new Thread(this);
        loopThread.start();
        numberOfRunningTimeSteps = n;
    }

    public void stop() {
        shouldRun = false;

    }

}


text:
Q: Place to unzip files in Android Because of apk maximum size 50MB, i decided to make apk expansion file. I know that I can get any file (inputstream) from  this package but I am working in LibGDX, and this doesn't have option to load textures/music from inputstream.
So, I must extract files, load texture/music and then I can delete file.
I think that i need max 50MB space and i have two options:
UNZIP TO:

*

*ContextWrapper.getFilesDir()  - it returns internal file, but I can't know how many files can I unzip there, because this storage is shared with all apps.

*getExternalStorageDirectory() - it returns external file, but according to website (developer.android.com) "This directory may not currently be accessible"
Which directory will be best to unpack and always avaliable?

A: If, as you tell us, here there are big quantities of data, so in order to improve user experience (not all phones have huge memory and using internal storage may cause your app is uninstalled) you should use external storage.
You have to care about couple of things:

*

*Add permissions to read / write

*Check file availability starting app

Adding permissions:
<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    ...
</manifest>

Checking file availability
And starting the app, be careful and check if external storage is available, and show message otherwise in order to avoid exceptions:

Caution: External storage can become unavailable if the user mounts the external storage on a computer or removes the media, and there's no security enforced upon files you save to the external storage. All applications can read and write files placed on the external storage and the user can remove them.

A: Use Context.getCacheDir() to get access to a private directory where you can extract files. This should be considered as a cache directory, so you should check for the file on startup and extract it again if it is missing.
This method doesn't require any additional permissions and is more secure. Also, the directory is guaranteed to exist by the Android APIs.