text:
Q: How not to use ObjectManager in phtml from template First a bit of context, and at the end, my question

I added an EAV attribute to my customer. It's an attribute with multiple values, and I want to add it to the account information (for reasons).
I've made a module, added a source for my select element, observer, etc...
It's working ok.
Let's say it's in
app/code/MyCompany/MyEAVAttributeModule
I've got a custom theme, made by another team, in
app/design/frontend/ThemeTeam/ThemeInUse
To add my attribute to the register and edit form, I've added on the custom theme
app/design/frontend/ThemeTeam/ThemeInUse/Magento_Customer/templates/form/register.phtml
and
app/design/frontend/ThemeTeam/ThemeInUse/Magento_Customer/templates/form/edit.phtml
which are copies from
/vendor/magento/module-customer/view/frontend/templates/form/register.phtml and edit.phtml
And to get all my values to add a select element, I've added in the phtml
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$my_attributes = $objectManager->create('Magento\Eav\Model\Config')->getAttribute('customer', 'my_attribute');

if ($my_attributes->getSource()) {
    $my_attribute_list = $my_attributes->getSource()->getAllOptions();
}

and then a <select> and a foreach
It works, my attribute is shown, the value is saved.

Now, for my question :-)
To get all the values, I get an instance of ObjectManager at the begining of my phtml
I know it's wrong to do that, but I couldn't find another way.
So how to do it ?
I know I should make a function and use a Helper (which I read is not recommended) or perhaps use it in the Block ?
But where ? In the theme ? In my module ? Somewhere else ?
Thanks if you can guide me on this one !

A: You should create a view model and inject it via DI. You can access the view model instance from within the template.
customer_account_edit.xml:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="customer_edit">
            <arguments>
                <argument name="view_model" xsi:type="object">Vendor\Package\ViewModel\YourEavAttribute</argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

EavAttribute.php:
<?php
/**
 * YourEavAttribute.php
 */
declare(strict_types=1);

namespace Vendor\Package\ViewModel;

use Magento\Eav\Model\Config;
use Magento\Framework\View\Element\Block\ArgumentInterface;

class YourEavAttribute implements ArgumentInterface
{
    /** @property Config $config */
    protected $config;

    /**
     * @param Config $config
     * @return void
     */
    public function __construct(
        Config $config
    ) {
        $this->config = $config;
    }

    /**
     * @return Config
     */
    public function getConfig(): Config
    {
        return $this->config;
    }
}

From inside your template:
$viewModel = $block->getViewModel();
$config = $viewModel->getConfig();


text:
Q: Why does the debugger show only one element from my array pointer? First off: I know that new is the C++ way of doing this. I am simply showing that there is more than one way to reproduce this error, and both are incredibly frustrating.
I have two forms of this source file. I'm trying to debug yet another programming assignment, but I'm not asking for help on that. Basically, I'm trying to re-implement set as a class with fields for size and a pointer to an int array. Here's the code using new:
testnew.cpp
int main()
{
    int size = 1;
    int *elements = new int[size];
    elements[0] = 0;
    size++;
    int * temp = new int[size];
    for (int i = 0; i < (size - 1); i++)
    {
        temp[i] = elements[i];
    }
    delete[] elements;
    temp[size] = size;
    elements = temp;
    elements[1] = 1;
    delete[] elements;
}

and again, using the less-preferable alloc functions:
testalloc.cpp
int main()
{
    int size = 1;
    int * elements = (int *) malloc(sizeof(int) * size);
    elements[0] = 0;
    size++;
    elements =(int *) realloc(elements,size * sizeof(int));
    elements[1] = 1;
    free(elements);
}

In both cases, my goal is to create an array, and then append to it. However, in both cases, after building and running it in Visual Studio 2010, the array is not grown at all, and only has 1 "slot" for my items to go into. In VS's debugger, I have watches on the elements array pointer; attached is a screenshot. It is the same for both versions of the code.

-- the breakpoint is at the delete[]/free() call.
Seriously, what am I doing wrong? This has to be a logic error, and I've combed through a quarter dozen examples of both malloc/realloc and new, and read and re-read my textbook, and I can't see what's wrong!
I feel like I should have a line that splits the allocated memory into an array, but doesn't the new int[] call do that?

A: Besides any other issues with the code, you must either do what JoeG mentions and have multiple watches, or set a watch like this:
elements,5

will result in:

I don't know if there is an updated list for VS2010, but this still works:
Symbols for Watch Variables
And:
View array in Visual Studio debugger?

A: Other answers have pointed out the bug in your code (temp[size] = size;), however your confusion is coming from the fact that you're misreading the debugger's output.
As far as the type system and debugger are concerned, elements isn't an array,  it's a pointer. The debugger has no way of knowing whether or not it's a pointer to the first element in an array or a pointer to a single element.
If you want to see the value of elements[x] in your debugger, use the expression *(elements+x).

A: In the first example, this is wrong:
temp[size] = size;

This will translate to:
temp[2] = 2;

And since arrays are zero-indexed you are writing outside your allocated area.

A: The file testnew.cpp allocates memory for size elements in temp but then sets temp[size], which is the size+1 element.  Perhaps this should be
temp[i] = size;

The file testalloc.cpp commits the common error of reassigning memory to the same variable without verifying that thte call to realloc succeeds:
elements =(int *) realloc(elements,size * sizeof(int));

If realloc fails, elements will be set to null, and its original memory will be orphaned.

A: First of all C++ is 0 indexed, so temp[size] = size; is an off by one error. And to answer your question, the type of elements is int*. That it's actually an array is not knowledge which is available to VS without code analysis. So, what you need to do is either use for example std::vector<>, boost::array or make sure that your array never detoriates to int*.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selenium and Facebook Post Button: How to click facebook post button in java using selenium? driver.get("https://www.facebook.com/sachin.aryal");
driver.findElement(By.name("xhpc_message_text")).sendKeys("Testing Java and Selenium");
driver.findElement(By.xpath("//*[@id='u_0_1a']/div/div[6]/div/ul/li[2]/button")).click();

The last line of the code is not working. How do I set the XPath of the Post button on facebook?

A: I know you already marked your own answer but it's not the proper way to do this. There are ways built into Selenium to do waits, e.g. wait for an element to be clickable. This method is the proper and more efficient way to do this.
driver.get("https://www.facebook.com/sachin-aryal/");
driver.findElement(By.name("xhpc_message_text")).sendKeys("Testing Java and Selenium");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button/span[.=\"Post\"]"))).click();

A: I noticed it works when you first scroll into view the button, try adding before the click on post the:
     ((JavascriptExecutor)driver).executeScript("window.scrollBy(0,259)","");

A: Try the below code .. it must work for you..
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Facebook_login {

    public static void main(String[] args) throws InterruptedException {
        String user_name = "facebook_user_name";
        String pwd = "facebook_password";
        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get("https://www.facebook.com");
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.findElement(By.name("email")).clear();
        driver.findElement(By.name("email")).sendKeys(user_name);
        driver.findElement(By.name("pass")).clear();
        driver.findElement(By.name("pass")).sendKeys(pwd);
        driver.findElement(By.xpath("//input[contains(@value,'Log In')]")).click();
        Thread.sleep(10000);
        System.out.println("logged in successfully");
        WebElement notification = driver.findElement(By.xpath("//a[contains(@action,'cancel')]"));
        if(notification.isDisplayed()) {
            System.out.println("Notification is present");
            notification.click();
        }
        WebElement status =driver.findElement(By.xpath("//textarea[@name='xhpc_message']"));
        status.sendKeys("Hello");
        Thread.sleep(3000);
        WebDriverWait wait = new WebDriverWait(driver,30);
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Post']"))).click();

    }
}


text:
Q: Passing Firebase Cloud Messaging data to n screens above the current screen and across the app in Flutter I've got an app in Flutter that's pulling a lot of data in the parent screen. The parent screen gets divided into a few child screens and those go to a few more child screens.
Now, in order to make sure this isn't pulling data all the time from the API, I'm only pulling it once in the root screen - which is fine 90% of the time.
All the subsequent updates are broadcasted throughout the app via firebase cloud messaging
If I'm on screen 3, I need to update data in screen 1 which should also update data which will eventually be displayed on screen 2. I'm currently using this method to pass my data around (https://flutter.io/cookbook/navigation/passing-data/)
For example, screen 1 contains three projects. Each project has its own screen.
Screen 2.1 is for project 1, screen 2.2 is for project 2 and so on.
In screen 2.1, there are n to do lists.
Now if I open the to do list, I reach screen 3 with the data of the first to do list of project 1.
In a firebase cloud messaging data notification, I receive the new information of this todo list and something from the todo list of project 2 todo list 1.
How do I maintain consistency and update the data across the board?
Do I need to change my architecture and use Redux or something along those lines?

A: This question is actually related to maintaining state across app. Flutter supports various methods for maintaining state. It depends on what you are building.

*

*Inherited Widget: It is the simplest way but it have drawbacks when state has to maintained deeep into widget tree.

*Scoped Model: This package is useful for maintaining state across its descendants.

*Streams(BLoC): It is the best way to maintain state across the app. Flutter uses similar process for maintaining state in app widget tree. In flutter everything is essentially a stream.
More resources for BLoC implementations. Flutter Show BloC Pattern implementation

A: Very good question!
You will need a central "data service" that acts as a single source of truth.
It loads the initial data and stores it inside of it, it also updates the data when a cloud message arrives, and notifies all widgets that depend on the data that the data has changed.
The screens never store a mutable copy of the data, instead they query the data service to get the latest data.
Depending on the complexity of your app, there are different solutions which work either with or without streams.
InheritedWidget is a basic solution Flutter comes with. You would usually have a StatefulWidget with a State that wraps your MaterialApp with an InheritedWidget to broadcast the State to your screens.
scoped_model is thin wrapper around InheritedWidget, but basically offers the same feature. Again, the model provider must wrap your MaterialApp to make it available on all screens.
BLoC and flutter_redux are more advanced solutions.


text:
Q: Failed to build gem native extension. + rake failed, exit code 1 I got multiple errors when trying to install the gems in a rails application cloned from remote repo, here's a screenshot of the error knowing that I'm still junior with RoR, knowing that I tried many answers but nothing worked
elta3lab@elta3lab-Inspiron-N5110:~/raye7-api$ bundle install
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32`.
Fetching gem metadata from http://rubygems.org/.............
Fetching gem metadata from http://rubygems.org/..
Resolving dependencies...........................................................................
Using rake 12.3.1
Fetching concurrent-ruby 1.1.3

Your user account isn't allowed to install to the system RubyGems.
  You can cancel this installation and run:

      bundle install --path vendor/bundle

  to install the gems into ./vendor/bundle/, or you can enter your password
  and install the bundled gems to RubyGems using sudo.

  Password:

Your user account isn't allowed to install to the system RubyGems.
  You can cancel this installation and run:

      bundle install --path vendor/bundle

  to install the gems into ./vendor/bundle/, or you can enter your password
  and install the bundled gems to RubyGems using sudo.

  Password:
Installing concurrent-ruby 1.1.3
Using i18n 0.9.5
Using minitest 5.11.3
Using thread_safe 0.3.6
Using tzinfo 1.2.5
Fetching activesupport 4.2.11
Installing activesupport 4.2.11
Using builder 3.2.3
Using erubis 2.7.0
Using mini_portile2 2.3.0
Fetching nokogiri 1.8.5
Installing nokogiri 1.8.5 with native extensions
Using rails-deprecated_sanitizer 1.0.3
Using rails-dom-testing 1.0.9
Fetching crass 1.0.4
Installing crass 1.0.4
Fetching loofah 2.2.3
Installing loofah 2.2.3
Using rails-html-sanitizer 1.0.4
Fetching actionview 4.2.11
Installing actionview 4.2.11
Fetching rack 1.6.11
Installing rack 1.6.11
Using rack-test 0.6.3
Fetching actionpack 4.2.11
Installing actionpack 4.2.11
Using globalid 0.4.1
Fetching activejob 4.2.11
Installing activejob 4.2.11
Fetching mini_mime 1.0.1
Installing mini_mime 1.0.1
Fetching mail 2.7.1
Installing mail 2.7.1
Fetching actionmailer 4.2.11
Installing actionmailer 4.2.11
Fetching activemodel 4.2.11
Installing activemodel 4.2.11
Using arel 6.0.4
Fetching activerecord 4.2.11
Installing activerecord 4.2.11
Using activerecord-import 0.20.2
Fetching public_suffix 3.0.3
Installing public_suffix 3.0.3
Using addressable 2.5.2
Using bundler 1.16.1
Using thor 0.19.4
Fetching railties 4.2.11
Installing railties 4.2.11
Using hike 1.2.3
Using multi_json 1.13.1
Using tilt 1.4.1
Fetching sprockets 2.12.5
Installing sprockets 2.12.5
Using sprockets-rails 2.3.3
Fetching rails 4.2.11
Installing rails 4.2.11
Fetching apipie-rails 0.5.14
Installing apipie-rails 0.5.14
Using ast 2.4.0
Using execjs 2.7.0
Fetching autoprefixer-rails 9.4.2
Installing autoprefixer-rails 9.4.2
Fetching aws-sigv4 1.0.3
Installing aws-sigv4 1.0.3
Fetching jmespath 1.4.0
Installing jmespath 1.4.0
Fetching aws-sdk-core 2.11.184
Installing aws-sdk-core 2.11.184
Fetching aws-sdk-resources 2.11.184
Installing aws-sdk-resources 2.11.184
Fetching aws-sdk 2.11.184
Installing aws-sdk 2.11.184
Fetching bcrypt 3.1.12
Installing bcrypt 3.1.12 with native extensions
Using bootstrap-datepicker-rails 1.7.1.1
Using sass 3.2.19
Using bootstrap-sass 3.3.5
Using momentjs-rails 2.17.1
Using bootstrap3-datetimepicker-rails 3.1.3
Using bugsnag 6.9.0
Using uniform_notifier 1.10.0
Using bullet 5.6.1
Using byebug 9.1.0
Using cancancan 1.17.0
Using xpath 2.1.0
Using capybara 2.15.4
Using capybara-email 2.5.0
Fetching mime-types-data 3.2018.0812
Installing mime-types-data 3.2018.0812
Fetching mime-types 3.2.2
Installing mime-types 3.2.2
Fetching carrierwave 1.2.3
Installing carrierwave 1.2.3
Using carrierwave-aws 1.2.0
Using carrierwave-base64 2.6.1
Using chartkick 2.2.5
Using coffee-script-source 1.12.2
Using coffee-script 2.4.1
Using coffee-rails 4.0.1
Using sass-rails 4.0.5
Using chosen-rails 1.5.2
Using chronic 0.10.2
Using coderay 1.1.2
Fetching connection_pool 2.2.2
Installing connection_pool 2.2.2
Using cookiejar 0.3.3
Using daemons 1.2.6
Using data_migrate 3.2.2
Using database_cleaner 1.6.2
Fetching delayed_job 4.1.5
Installing delayed_job 4.1.5
Fetching delayed_job_active_record 4.1.3
Installing delayed_job_active_record 4.1.3
Using orm_adapter 0.5.0
Using responders 2.4.0
Using warden 1.2.7
Using devise 4.3.0
Using devise_token_auth 0.1.43
Using diff-lcs 1.3
Using docile 1.1.5
Using unf_ext 0.0.7.5
Using unf 0.1.4
Fetching domain_name 0.5.20180417
Installing domain_name 0.5.20180417
Using eventmachine 1.0.9.1
Using em-socksify 0.3.2
Using http_parser.rb 0.6.0
Using em-http-request 1.1.5
Using email_check 1.0.1
Using erubi 1.7.1
Fetching factory_bot 4.11.1
Installing factory_bot 4.11.1
Fetching factory_bot_rails 4.11.1
Installing factory_bot_rails 4.11.1
Using faker 1.8.7
Using multipart-post 2.0.0
Fetching faraday 0.15.4
Installing faraday 0.15.4
Using faraday_middleware 0.12.2
Using websocket-extensions 0.1.3
Using websocket-driver 0.7.0
Using faye-websocket 0.10.7
Using faye 1.1.2
Using faye-rails 2.0.3
Using multi_xml 0.6.0
Using httparty 0.15.7
Fetching fcm 0.0.6
Installing fcm 0.0.6
Fetching ffi 1.9.25
Installing ffi 1.9.25 with native extensions
Using file_validators 2.1.0
Fetching font-awesome-rails 4.7.0.4
Installing font-awesome-rails 4.7.0.4
Using font-awesome-sass 4.7.0
Using foreman 0.84.0
Using formatador 0.2.5
Using formtastic 3.1.5
Fetching geocoder 1.4.9
Installing geocoder 1.4.9
Fetching geokit 1.13.1
Installing geokit 1.13.1
Fetching geokit-rails 2.3.1
Installing geokit-rails 2.3.1
Using rb-fsevent 0.10.3
Using rb-inotify 0.9.10
Using ruby_dep 1.5.0
Using listen 3.1.5
Fetching lumberjack 1.0.13
Installing lumberjack 1.0.13
Using nenv 0.3.0
Using shellany 0.0.1
Using notiffany 0.1.1
Fetching method_source 0.9.2
Installing method_source 0.9.2
Using pry 0.11.3
Fetching guard 2.15.0
Installing guard 2.15.0
Using guard-compat 1.2.1
Using rspec-support 3.7.1
Using rspec-core 3.7.1
Using rspec-expectations 3.7.0
Using rspec-mocks 3.7.0
Using rspec 3.7.0
Using guard-rspec 4.7.3
Using haml 4.0.7
Using hash-deep-merge 0.1.1
Using hashie 3.5.7
Fetching highline 2.0.0
Installing highline 2.0.0
Using http-cookie 1.0.3
Using json 1.8.6
Fetching hypertrack 0.1.6
Installing hypertrack 0.1.6
Fetching parser 2.5.3.0
Installing parser 2.5.3.0
Fetching rails-i18n 4.0.9
Installing rails-i18n 4.0.9
Fetching rainbow 2.2.2
Installing rainbow 2.2.2 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /tmp/bundler20181204-31799-okhy3brainbow-2.2.2/gems/rainbow-2.2.2/ext
/usr/bin/ruby2.5 mkrf_conf.rb

current directory: /tmp/bundler20181204-31799-okhy3brainbow-2.2.2/gems/rainbow-2.2.2/ext
/usr/bin/ruby2.5 -rrubygems /usr/share/rubygems-integration/all/gems/rake-12.3.1/exe/rake
RUBYARCHDIR=/tmp/bundler20181204-31799-okhy3brainbow-2.2.2/extensions/x86_64-linux/2.5.0/rainbow-2.2.2
RUBYLIBDIR=/tmp/bundler20181204-31799-okhy3brainbow-2.2.2/extensions/x86_64-linux/2.5.0/rainbow-2.2.2
/usr/bin/ruby2.5: No such file or directory -- /usr/share/rubygems-integration/all/gems/rake-12.3.1/exe/rake (LoadError)

rake failed, exit code 1

Gem files will remain installed in /tmp/bundler20181204-31799-okhy3brainbow-2.2.2/gems/rainbow-2.2.2 for inspection.
Results logged to /tmp/bundler20181204-31799-okhy3brainbow-2.2.2/extensions/x86_64-linux/2.5.0/rainbow-2.2.2/gem_make.out

An error occurred while installing rainbow (2.2.2), and Bundler cannot continue.
Make sure that `gem install rainbow -v '2.2.2'` succeeds before bundling.

In Gemfile:
  i18n-tasks was resolved to 0.9.28, which depends on
    rainbowMake sure that `gem install rainbow -v '2.2.2'` succeeds before bundling.

In Gemfile:
  i18n-tasks was resolved to 0.9.28, which depends on
    rainbow

and when trying to install rainbow, either with or without sudo, I got this error
Building native extensions. This could take a while...
ERROR:  Error installing rainbow:
    ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.5.0/gems/rainbow-2.2.2/ext
/usr/bin/ruby2.5 mkrf_conf.rb

current directory: /var/lib/gems/2.5.0/gems/rainbow-2.2.2/ext
/usr/bin/ruby2.5 -rrubygems /usr/share/rubygems-integration/all/gems/rake-12.3.1/exe/rake RUBYARCHDIR=/var/lib/gems/2.5.0/extensions/x86_64-linux/2.5.0/rainbow-2.2.2 RUBYLIBDIR=/var/lib/gems/2.5.0/extensions/x86_64-linux/2.5.0/rainbow-2.2.2
/usr/bin/ruby2.5: No such file or directory -- /usr/share/rubygems-integration/all/gems/rake-12.3.1/exe/rake (LoadError)

rake failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.5.0/gems/rainbow-2.2.2 for inspection.
Results logged to /var/lib/gems/2.5.0/extensions/x86_64-linux/2.5.0/rainbow-2.2.2/gem_make.out

A: solved using
sudo gem install rake
sudo gem install rainbow -v '2.2.2'
sudo bundle install


text:
Q: Play a mp3 file in ios I'm quite new to iPhone(From PHP). I just completed a simple app in iPhone.
What i need is to play a sound in loop from the moment one open my app until he suspends it.
Hope some one will come up with a clue.
Thanks


text:
Q: how to use webpack to load CDN or external vendor javascript lib in js file, not in html file I am using react starter kit for client side programming. It uses react and webpack. No index.html or any html to edit, all js files. My question is if I want to load a vendor js lib from cloud, how to do I do that?
It would be easy to do that in a html file. <script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>
However, in js file, it only uses npm installed packages. How can I import the above lib with no html file? I tried import and require, they only work for local files.
update 10/21/15
So far I tried two directions, neither is ideal.

*

*@minheq yes there is a html file sort of for react start kit. It is html.js under src/components/Html. I can put cloud lib and all its dependencies there like this:

        <div id="app" dangerouslySetInnerHTML={{__html: this.props.body}} />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>
        <script src="/app.js"></script>
        <script dangerouslySetInnerHTML={this.trackingCode()} />
    </body>

Good news is it works, I don't need do anything else in js file, no import or require. However, now I have two jquery libs loaded in different ways. One in here, the other through npm and webpack. I wonder it will give me trouble later. The react-routing I use give me 'undefined variable' error if I type a none home path in browser window due to the server side loading I guess. So this solution is not very good.

*Use webpack externals feature. This is documented as: link. "You can use the externals options for applications too, when you want to import an existing API into the bundle. I.e. you want to use jquery from CDN (separate  tag) and still want to require("jquery") in your bundle. Just specify it as external: { externals: { jquery: "jQuery" } }."
However, the documentation I found a few places are all fussy about how to do this exactly. So far I have no idea how to use it to replace <script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script> in html.

A: You can create a script tag in your JS as
$("body").append($("<script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>"))

A: externals is not intended to let you do this. It means "don't compile this resource into the final bundle because I will include it myself"
What you need is a script loader implementation such as script.js. I also wrote a simple app to compare different script loader implementations: link.

A: There is one html file that is definitely being used to serve to users with  your js bundle attached. Probably you could attach the script tag into that html file

A: var $script = require("scriptjs");
$script("//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js", function() {
  $('body').html('It works!')
});

A: Use webpack's externals:

externals allows you to specify dependencies for your library that are
  not resolved by webpack, but become dependencies of the output. This
  means they are imported from the environment during runtime.

A: I have looked around for a solution and most of all proposals were based on externals, which is not valid in my case.
In this other post, I have posted my solution: https://stackoverflow.com/a/62603539/8650621
In other words, I finished using a separate JS file which is responsible for downloading the desired file into a local directory. Then WebPack scans this directory and bundles the downloaded files together with the application.


text:
Q: Representación gráfica en Python de datos en formato JSON provenientes del puerto serial (Arduino) En python debo generar la representación gráfica de valores, provenientes del puerto serial en formato JSON, en tiempo real.
Ya logré la graficación de 2 valores pero tengo un problema con la escala creada.
Esta es la cadena de datos enviada por mi arduino:
{"LightSensor":754.00,"IR":28.00,"Visible":10.00,"UV":0.01,"CurrentSensor":-0.07,"VoltageDivider":1.2}

Este es el código en python que estoy utilizando:
from socket import timeout
import matplotlib.pyplot as plt
import serial
import json
from itertools import count
from matplotlib.animation import FuncAnimation

#initialize serial port
arduinoData = serial.Serial('COM11', 9600, timeout = 10)

plt.style.use('fivethirtyeight')
fig,ax1 = plt.subplots()

x_values = []
y_values = []
z_values = []

index = count()

def animate(i):
    data = arduinoData.readline().decode("utf-8")
    dict_json = json.loads(data)

    color1 = 'tab:blue'
    color2 = 'tab:red'

    x_values.append(next(index))
    y_values.append(dict_json.get("VoltageDivider"))
    z_values.append(dict_json.get("LightSensor"))

    ax1.plot(x_values, y_values, color1)
    ax1.set_ylabel("Tension")

    plt.cla()

    ax2 = ax1.twinx()
    ax2.plot(x_values, z_values, color2)
    ax2.set_ylabel("Luminosité")

ani = FuncAnimation(plt.gcf(), animate, 1000)

plt.tight_layout()
plt.show()

Y esto es lo que genera:

La escala generada del lado izquierdo de las y, es correcta y concuerda con los valores recibidos en VoltageDivider. Sin embargo, del lado derecho se generan dos escalas, la correcta es la que va de 0-700. No logro comprender por qué se crea la que va de 0-1.0
Apreciaría su ayuda...


text:
Q: DFA which accepts either even number of 1s or odd number of 0s. ex- 0,11,10,01,110,011,000,101 etc DFA which accepts either even number of 1s or odd number of 0s. ex- 0,11,10,01,110,011,000,101 etc

A: we can make four different cases that are

and corresponding the table we will have three final states that are acceptable cases. let the states be:

*

*q0 for even even

*q1 for odd even

*q2 for even odd

*and q3 for odd odd

so the transition graph would be given by

A: i think below DFA will full fill requirements...i made in paint so,not looking pretty.

A:             State           O               1
           ->q0*            q1              q2
             q1*            q0              q3
             q2             q3              q0
             q3*            q2              q1

q0 is the initial state and q0,q1,q3 are the final states.

A: Create 4 states like below
      +-------------+
      |  0s  |  1s  |
+-------------------+
| q0* | even | even |
+-------------------+
| q1  | even | odd  |
+-------------------+
| q2* | odd  | even |
+-------------------+
| q3* | odd  | odd  |
+-------------------+

See that your accepting states are q0, q2 and q3
Your state transition table will be like this
      +----+----+
      | 0  | 1  |
+---------------+
| q0* | q2 | q1 |
+---------------+
| q1  | q3 | q0 |
+---------------+
| q2* | q0 | q3 |
+---------------+
| q3* | q1 | q4 |
+-----+----+----+


text:
Q: Run a bash script at instance startup but not at reboot For some instance types in AWS, there is instance store 0 available which you can select during launch instance wizard at 'add storage'. I found that this instance store 0 needs to be reformatted and remounted every time instance starts. However, once mounted, the mount remains intact after a reboot but not for instance start. I execute following code via /etc/rc.local which basically serves the purpose.
#!/usr/bin/bash

FSTYPE=xfs
DEVICE=/dev/xvdb

mkfs -t $FSTYPE $DEVICE
umount -f /mnt > /dev/null 2>&1
mount $DEVICE /mnt
chmod 777 /mnt
chmod +t /mnt
exit

But rc.local gets executed at reboot as well as during startup. Is there an elaborate way in Centos 7 wherein this script runs only during instance startup and not during reboots?


text:
Q: Making select and update in one query is there a query where I can do both querys in one?
This is the first
$q = "select c.id as campaignId,c.priceFactor,
              o.cid,o.bloggerPrice,o.state as state,o.customerPrice,o.id as orderId,o.listPrice,o.basicPrice
              from campaign c, orders o
              where c.id={$campaignId}
              and c.id = o.cid
              and o.state in (8,9)";

And this is the second
  foreach($orders as $order)
        {
             $listPrice      = $order->priceFactor * $order->basicPrice;

             if($order->bloggerPrice < $listPrice || $order->customerPrice < $listPrice)
             {
                $order->bloggerPrice  = $listPrice;
                $order->customerPrice = $listPrice;
             }

             $qUpdate       = "update orders set
                               listPrice = {$listPrice},bloggerPrice={$order->bloggerPrice},
                               customerPrice ={$order->customerPrice}
                               where id=$order->orderId and cid={$order->cid}";

            // $this->db->q($qUpdate);
        }

My question is: Can I do it the above without a PHP code just pure SQL?

A: In MySQL, you can use a join right after UPDATE.  In your example, this might look something like:
update Orders o
inner join Campaign c on c.id = o.cid
set
    listPrice = o.priceFactor * order.basicPrice
,   bloggerPrice = case
        when o.bloggerPrice < o.priceFactor * order.basicPrice
            then o.priceFactor * order.basicPrice
            else bloggerPrice
        end
,   listPrice = case
        when o.customerPrice < o.priceFactor * order.basicPrice
            then o.priceFactor * order.basicPrice
            else listPrice
        end
where o.state in (8,9)
and c.id = {$campaignId}


text:
Q: Foundation 5 - Dropdowns not working properly having some more issues with Foundation 5.
the dropdown menus: http://foundation.zurb.com/docs/components/dropdown.html
even when using there download and copy pasting the code from their site, the drop down bar when refreshing the page or first load, shows the content already dropped down, and only disappears when you spam click it a few times and move the mouse away. is something broken with it, i assumed it was supposed to have the drop down content hidden on initial load.
code is:
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Foundation | Welcome</title>
    <link rel="stylesheet" href="css/foundation.css" />

        Link Dropdown »

This is a link

This is another

Yet another

I have tried using the scripts at the top and bottom of the page, same thing.

also is it possible instead of clicking to have it just display on mouse hover?
Thanks.

A: I know this is a super-old question, but I got here via Google and wanted to answer it in case anyone else does.
At least one of your problems is this line
class="[tiny small medium large content]f-dropdown"

You're not supposed to literally put [tiny small medium large content]. You're supposed to choose one of those options (if desired). Like this:
class="tiny f-dropdown"


text:
Q: Combine vendor javascripts in angular 2 I'm using Angular 2 and I'd like to know how can I combine my vendor javascript files.
for example, I have these files:

*

*jquery.min.js

*slick.min.js

*bootstrap.min.js

I want to output them as vendor.js.
Is it possible do to this?

Edit 1
In Laravel There's a service called Elixir, It does exactly what I wish to do with my Angular app.

A: You can use Grunt / Gulp.
With grunt, you write something like concat:
concat: {
    options: {
        stripBanners: true,
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %> */'
    },
    js_libs: {
        src: ["jquery.js", "bootstrap.js"],
        dest: 'vendor.js'
    },
}

Or if you also want to uglify:
uglify: {
    options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
    },
    js_libs: {
        src: ["jquery.js", "bootstrap.js"],
        dest: 'vendor.min.js'
    }
},


text:
Q: JQuery stopPropagation on .live() when handlers already exist I'm aware that live calls bubble up through the doccument and that is why I'm having issues.
Unfortunately I'm using third party libraries that bind event handlers to elements and would like to create a case in which a click event isn't bubbled up to those elements.
using .click() in combination with eventStopPropagation() works just fine, however due to the dynamic nature of the content I need to use either live,on,delegate,etc...
Here's a fidddle of my issue. I need to prevent "middle" click from firing when clicking the "inner" div. I can not change the "middle" handler (it is best if you consider I don't even have access to it).
Thanks in advance for your help!! And sorry for the repeat, I thought it would be tidier this way.
http://jsfiddle.net/99zQM/9/
HTML:

    outer non dynamic element

        middle dynamic

            inner dynamic

Javascript:
$("#middle").bind('click',function(e){
    //is rebound when content is loaded
   alert("middle clicked");
});
$('#inner').live('click',function(e){
    alert("inner clicked");
});

A: You would use .on for binding click event. For each binding to #outer, #middle and #inner.
Use stopPropagation to prevent bubble up event.
$("#outer").on('click', function(e){
    e.stopPropagation();
    alert("outer clicked");
});

$("#outer").on('click', '#middle', function(e){
    e.stopPropagation();
    alert("middle clicked");
});

$("#outer #middle").on('click', '#inner', function(e){
    e.stopPropagation();
    alert("inner clicked");
});

jsFiddle example : http://jsfiddle.net/99zQM/11/

A: Use this code
$(document).bind('click',function(e) {
    if (e.target)
        target = e.target;
    else if (e.srcElement)
        target = e.srcElement;
    else
        target = e.currentTarget;

    if (target.id == 'middle')
    {
    alert("middle clicked");
    }

       else if (target.id == 'inner')
       {
       alert("inner clicked");
       }
});

http://jsfiddle.net/99zQM/12/

A: You may try to capture the click handler and dynamically wrap it in another handler which tests for event bubbling like this :
// Your code does not change

    $("#middle").bind('click',function(e){
        //is rebound when content is loaded
       alert("middle clicked");
    });

    $('#inner').live('click',function(e){
        alert("inner clicked");
    });

// capture the click handler on #middle and wrap it inside a test for bubbling
var handler = $._data($("#middle")[0], "events")["click"][0].handler;
$('#middle').unbind('click');

$("#middle").bind('click',(function(handlerVar){return function(e){
    if(e.target===this) // test for bubbling
    {
        handlerVar(e);
    }
}})(handler));

see : http://jsfiddle.net/99zQM/13/
Hope this will help


text:
Q: How to filter rows according to the bigger value in another column? I have a data frame like below
d1<-c('a','b','c','d','e','f','g','h','i','j','k','l')

d2<-c(1,5,1,2,13,2,32,2,1,2,4,5)

df1<-data.frame(d1,d2)

Which looks like the data table in this picture

My goal is to filter the rows based on which value of d2 in every 3 rows is biggest. So it would look like this:

Thank you!

A: We may use rollmax from zoo to filter the rows
library(dplyr)
library(zoo)
df1 %>%
  filter(d2 == na.locf0(rollmax(d2, k = 3, fill = NA)))
  d1 d2
1  b  5
2  e 13
3  g 32
4  l  5

A: You can create a grouping variable that puts observations into groups of 3. I have first created a sequence from 1 to the total number of rows, incremented by 3. And then repeated each number of this sequence 3 times and subset the result to get a vector the same length of the data, incase the number of observations is not perfectly divisible by 3. Then simply filter rows based by the largest number of each group in d2 column.
library(dplyr)

df1 %>%
  mutate(group = rep(seq(1, n(), by = 3), each = 3)[1:n()]) %>%
  group_by(group) %>%
  filter(d2 == max(d2))

# A tibble: 4 x 3
# Groups:   group [4]
#  d1       d2 group
#  <chr> <dbl> <dbl>
# 1 b         5     1
# 2 e        13     4
# 3 g        32     7
# 4 l         5    10

A: Yet another solution:
library(tidyverse)

d1<-c('a','b','c','d','e','f','g','h','i','j','k','l')
d2<-c(1,5,1,2,13,2,32,2,1,2,4,5)

df1<-data.frame(d1,d2)

df1 %>%
  mutate(id = rep(1:(n()/3), each=3)) %>%
  group_by(id) %>%
  slice_max(d2) %>%
  ungroup %>% select(-id)

#> # A tibble: 4 × 2
#>   d1       d2
#>   <chr> <dbl>
#> 1 b         5
#> 2 e        13
#> 3 g        32
#> 4 l         5


text:
Q: Relative error plot I was plotting the relative error of the $e^{11/12 -n}n^{n+1/2}$ approximation to $n!$ as $n$ gets larger and larger, and at some very large value of $n$ Mathematica gives this plot:

Can somebody explain what exactly the plot means? Of course, I understand that, for larger and larger $n$, the relative error tends to a limit, but I am not sure how to interpret this plot. In particular, I don't understand how the error can show greater variation as $n$ grows large.
Thanks.
Edit: I want to add that when $n$ is an order of magnitude less what I get is something like this:

A: Looks like numerical error, try increasing the WorkingPrecision
Plot[Abs[(Exp[11/12 - n] n^(n + 1/2) - n!)/n!]
   ,{n, 10, 10^7}
   ,WorkingPrecision -> 100]

WorkingPrecision is an option for various numerical operations that specifies how many digits of precision should be maintained in internal computations.
Edit You might also find Limit interesting
Limit[(Exp[11/12 - n] n^(n + 1/2) - n!)/n!, n -> Infinity]
N[%,50]
(* -1 + E^(11/12)/Sqrt[2 \[Pi]] *)
(* -0.0022692878024401615486447545367879811325821284314703  *)


text:
Q: Reading sub-level JSON data using Pandas I am stuck while reading sublevel data using Pandas.
Background:
I used NYT Archive API to download series of data, I stored it in a JSON file which actually has list of JSON objects in it.
Procedure:
I read the JSON file using read_json method.
pandas_df = pd.read_json("data.json")
When I see sample result using head, it looks like below:
 pandas_df.head()
    copyright  \
0  Copyright (c) 2013 The New York Times Company....
1  Copyright (c) 2013 The New York Times Company....
2  Copyright (c) 2013 The New York Times Company....
3  Copyright (c) 2013 The New York Times Company....
4  Copyright (c) 2013 The New York Times Company....

                                            response
0  {'docs': [{'subsection_name': None, 'slideshow...
1  {'docs': [{'subsection_name': None, 'slideshow...
2  {'docs': [{'subsection_name': None, 'slideshow...
3  {'docs': [{'subsection_name': None, 'slideshow...
4  {'docs': [{'subsection_name': None, 'slideshow...

I only need information in the response. So when I change the code like below:
print(pandas_df["response"].head())
0    {'docs': [{'subsection_name': None, 'slideshow...
1    {'docs': [{'subsection_name': None, 'slideshow...
2    {'docs': [{'subsection_name': None, 'slideshow...
3    {'docs': [{'subsection_name': None, 'slideshow...
4    {'docs': [{'subsection_name': None, 'slideshow...
Name: response, dtype: object

Question:
How can I fetch data using elements inside docs? Like subsection, slideshow etc. Can I see it in a tabular format, like a data frame?
Please let me know if any more information is required.
Thanks.
EDIT 1:
Adding first element from the JSON file. This file is too big around 1GB.
{
  "copyright": "Copyright (c) 2013 The New York Times Company.  All Rights Reserved.",
  "response": {
    "meta": {
      "hits": 7652
    },
    "docs": [
      {
        "web_url": "http://www.nytimes.com/interactive/2016/technology/personaltech/cord-cutting-guide.html",
        "snippet": "We teamed up with The Wirecutter to come up with cord-cutter bundles for movie buffs, sports addicts, fans of premium TV shows, binge watchers and families with children.",
        "lead_paragraph": "We teamed up with The Wirecutter to come up with cord-cutter bundles for movie buffs, sports addicts, fans of premium TV shows, binge watchers and families with children.",
        "abstract": null,
        "print_page": null,
        "blog": [],
        "source": "The New York Times",
        "multimedia": [
          {
            "width": 190,
            "url": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbWide.jpg",
            "height": 126,
            "subtype": "wide",
            "legacy": {
              "wide": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbWide.jpg",
              "wideheight": "126",
              "widewidth": "190"
            },
            "type": "image"
          },
          {
            "width": 600,
            "url": "images/2016/10/13/business/13TECHFIX/06TECHFIX-articleLarge.jpg",
            "height": 346,
            "subtype": "xlarge",
            "legacy": {
              "xlargewidth": "600",
              "xlarge": "images/2016/10/13/business/13TECHFIX/06TECHFIX-articleLarge.jpg",
              "xlargeheight": "346"
            },
            "type": "image"
          },
          {
            "width": 75,
            "url": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbStandard.jpg",
            "height": 75,
            "subtype": "thumbnail",
            "legacy": {
              "thumbnailheight": "75",
              "thumbnail": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbStandard.jpg",
              "thumbnailwidth": "75"
            },
            "type": "image"
          }
        ],
        "headline": {
          "main": "The Definitive Guide to Cord-Cutting in 2016, Based on Your Habits",
          "kicker": "Tech Fix"
        },
        "keywords": [
          {
            "rank": "1",
            "is_major": "N",
            "name": "subject",
            "value": "Video Recordings, Downloads and Streaming"
          },
          {
            "rank": "2",
            "is_major": "N",
            "name": "subject",
            "value": "Television Sets and Media Devices"
          },
          {
            "rank": "1",
            "is_major": "Y",
            "name": "subject",
            "value": "Television"
          }
        ],
        "pub_date": "2016-01-01T05:00:00Z",
        "document_type": "multimedia",
        "news_desk": "Technology / Personal Tech",
        "section_name": "Technology",
        "subsection_name": "Personal Tech",
        "byline": {
          "person": [
            {
              "firstname": "Brian",
              "middlename": "X.",
              "lastname": "CHEN",
              "rank": 1,
              "role": "reported",
              "organization": ""
            }
          ],
          "original": "By BRIAN X. CHEN"
        },
        "type_of_material": "Interactive Feature",
        "_id": "57fdfb9895d0e022439c2b57",
        "word_count": null,
        "slideshow_credits": null
      }]}}

A: You should be able to extract all the elements under the docs list which is nested in the response dictionary into a DataFrame.
import json
with open('data.json') as f:
    data = json.load(f)
df = pd.DataFrame(data['response']['docs'])


text:
Q: Downloading GUI for a wpf desktop application I am developer of an wpf application which will be deployed among various locations in my city. My applications GUI will change with respect to the season. I am planning to write the application using MEF/MVVM so that i can isolate the GUI part to  a seperate dll and  download the new version when available. Recently, I came to know about XAP. Is it possible to put the GUI files in XAP and download it when needed? Is it possible to  have a silverlight plugin inside a WPF application?

A:
Is it possible to put the GUI files in XAP and download it when
  needed?

Surely, you can. I'd recommend reading about Prism for information about how to build modular apps in WPF. Basic idea is to dynamically load needed assemblies, reference their resources and put their content  onto the page. MEF is used to import declarations of components/user controls.

Is it possible to have a silverlight plugin inside a WPF application?

Sure, you can do that. One of the ways is to integrate webBrowser control onto your page and set its location to XAP file, though it looks like an overkill.


text:
Q: MVC Redirect from one project to another in one solution How can i redirect from one MVC project to another in the same solution and then passing parameters without passing them throw url ?
Thanks in advance,

A: Once the application is deployed there are no longer notions such as solutions or projects. You can only make a redirect to either a relative or absolute url. A relative url would be part of the same web application so you could redirect to the corresponding controller action:
return RedirectToAction("SomeAction", "SomeController");

If you need to redirect to another application you need should use an absolute url:
return Redirect("http://localhost:1234/SomeController/SoneAction");

Obviously for this to work the other application need to be started and hosted in a webserver.
As far as passing parameters is concerned the standard way defined by the HTTP protocol when making a GET request is to pass them as key value pairs in the query string. Assuming that the other application is hosted on the same domain as the source application you could also set a cookie whose value can be read by the target application.
Here's an example of how you can set a cookie before redirecting:
var cookie = new HttpCookie("cookieName", "someValue")
cookie.Domain = ".example.com";
Response.SetCookie(cookie);
return Redirect("http://example.com/SomeController/SoneAction");


text:
Q: taylor series for two variables The theorem I have been given for this is $$f(x,y)=f(a+u,b+v)=f(a,b)+\sum \limits_{k=1}^{\infty} \frac1{k!} \bigg(u\frac{\partial}{\partial x}+v\frac{\partial}{\partial y}\bigg)^kf(a,b)$$ where $u=x-a$ and $v=y-b$.
Find Taylor series for $f(x,y)=\sin x \sin y$ near origin up to the square terms.
I don't understand why this isn't just zero because $f(a,b)=f(0,0)=0$. The solution says it is $xy+...$

A: For second order we get $f(a+u,b+v)=f(a,b)+\sum_{k=1}^2\frac{1}{k!}(u\frac{\partial}{\partial x}+v\frac{\partial}{\partial y})^kf(a,b)$ and $f=\sin(x)\sin(y)$, so $$\partial_xf=\cos(x)\sin(y),\partial_yf=\sin(x)\cos(x)$$
$$\partial_{xy}f=cos(x)\cos(y),\partial_{xx}f=\partial_{yy}f=-f$$
so at $(0,0):\partial_xf=\partial_yf=\partial_{xx}f=\partial_{yy}f=0$ and $\partial_{xy}f=1$, so we get $f(x,y)=xy+remainder$

A: Perhaps this is your misunderstanding.  When they wrote
$$
\bigg(u\frac{\partial}{\partial x}+v\frac{\partial}{\partial y}\bigg)^kf(a,b)
$$
they do not mean some operation applied to $f(a,b)$, which is $0$ in your case.  Instead they mean the derivative
$$
\bigg(u\frac{\partial}{\partial x}+v\frac{\partial}{\partial y}\bigg)^kf
$$
of $f$, evaluated at the point $(a,b)$.


text:
Q: CSS property background-clip:text is not working for me in chrome or safari I don't get why the background-clip property is not working in chrome and safari.
i try to put the prefix -webkit but it doesn't help.
The page is located here http://pierredebroux.be/charleroi/
the code is mainly:

OBSERVER CHARLEROI

     .image2 {
     position: fixed;
        width:100%;
        height: 100%;
        background: url(img/a.jpg) 50% 50%;
        background-size: cover;
        background-clip:text;
        color:transparent;
        opacity: 0;
        filter:blur(2px)
    }

   h1 {
     font-size: 190px;
    line-height: 180px;
  }

Thanks,
Pierre

A: I guess the minute error in your code is opacity:0;.
It will set the background invisible. try removing it. Also -webkit- prefix is required for background-clip:text;.
I have attached a code pen for reference.


text:
Q: R Function Query Write a function called "query". It takes five inputs

*

*"age_low": default value = 1

*"age_high": default value = 100

*"keyword":  default value = ""

*"rating_low":  default value = 1

*"rating_high":  default value = 5

and returns a data frame which contains the rows of df where the reviewer's age is between "age_low" and "age_high" (inclusive),the review text contains "keyword" (case insensitive), and the rating is  between "rating_low" and "rating_high" (inclusive).
Save the output of query(age_low=20, age_high=50) in df1
Save the output of query(rating_high=3) in df2
Save the output of query(age_low=20, age_high=50, keyword="price", rating_low=4, rating_high=5) in df3
query <- function(age_low=1, age_high=100, keyword="", rating_low=1, rating_high=5) {
  return(df$Age>= age_low and df$Age<=age_high,
         tolower(df$`Review Text` == tolower(keyword)),
         df$Rating>=rating_low and df$Rating<=rating_high)
}

df1 <- query(age_low=20, age_high=50)
df2 <- query(rating_high=3)
df3 <- query(age_low=20, age_high=50, keyword="price", rating_low=4, rating_high=5)

A: Except for the criteria, you should also put df as an input for your function as a good habit.
query <- function(df=df, age_low=1, age_high=100, keyword="", rating_low=1, rating_high=5) {
  # first filter
  out_df <- df[df$Age>=age_low & df$Age<=age_high, ]

  # second filter
  out_df <- out_df[tolower(out_df$`Review Text`) == tolower(keyword), ]

  # third filter
  out_df <- out_df[out_df$Rating>=rating_low & out_df$Rating<=rating_high, ]

  return(out_df)
}

df1 <- query(age_low=20, age_high=50)
df2 <- query(rating_high=3)
df3 <- query(age_low=20, age_high=50, keyword="price", rating_low=4, rating_high=5)


text:
Q: Changing focus from Button in ListView row to list item I have a ListView with list items that have a Button on them.  You can no longer select the list item, only the Button on the list item.  How do you change the focus back to the list item?

A: For the Button in your list row layout add the attribute:
android:focusable="false"


text:
Q: AS3- Reading the first element from XML I loaded XML in AS3.
In that XML, I make that flash will retrieving a value of an attribute and traced it.
the output was:
test1,test2,test3,test4

But I want that flash will output only the first element from that output (test1 only). I searched in Google and I didn't find an answer.
Sample of my XML content :
<data>
    <myXML typesId="test1,test2,test3,test4"/>
</data>

A: You can extract the first word (test1) from the typesId parameter using String.substr() function :
var xml:XML = <data>
    <myXML typesId="test1,test2,test3,test4"/>
</data>;

var types:String = xml.myXML.@typesId;

trace(types.substr(0, types.indexOf(',')));     // gives : test1

Hope that can help.

A: Another solution with Regular Expression:
var data:XML =
<data>
    <myXML typesId="test1,test2,test3,test4"/>
</data>;

var word:String = data.myXML.@typesId.toString().replace(/^([^,]+).*$/, "$1");

The value of the word will be test1.


text:
Q: How can I do to load all the resources when starting the app? Java loads the resources as they are needed. This make my tiny small desktop application to be very slow when opening a window.
How can I do to load all the resources when starting the app? Is something related to classloaders?
EDIT: does this code work if the files are inside a jar?
EDIT2: Note that the aim is not to reduce the startup time, but to reduce the time of new windows opening after the app is started. I want all resources to go to the memory and stay "ready for use", so after loaded the app will run faster the user's commands.

A:
Java loads the resources as they are needed.

Actually, it is more complicated than that.  If you have a class A that statically depends on a class B that statically depends on a class C, then loading A will trigger eager loading of B and C and so on.  But some libraries (and I think AWT and Swing do this) internally use the Class.forName(...) method to lazily load implementation classes.  This reduces the number of classes that are loaded initially, and (ideally) avoids loading code that your application will never use.

How can I do to load all the resources when starting the app?

I suppose that you could create explicit static dependencies to defeat the laziness above, but that probably won't make your application's initial window appear more quickly.  A better strategy would be to try to use more lazy loading to reduce the amount of code that needs to be loaded to get the initial window visible.  But this needs to be done judiciously.  If you lazyily load classes that are needed for the initial window, you may actually make startup slower.
Compiling to native code (using GCJ for example) is another alternative, but this has various downsides; e.g. larger binaries, more native library dependencies, portability issues, (possibly) slower execution speed for a long running application.
Re your EDIT: I think that code will "work", but I don't see how it could possibly speed up your application's startup.

A: The problem is harder: The code is initialized if it is used, which can be seen even on the method level. So you have to run it to load it.
The only other possibility is to buy Excelsior Jet, which does the compile step for you (and returns a nice .exe as a side effect).
EDIT: You can reduce your runtime by Class.forName()ing all your classes during startup, and having everything loaded when its needed. Please note that for having everything really fast, the code must have been run, so maybe you can open, but hidden, all windows, the close them, and then really show the main window from which all other windows are opened. Sadly this will make your app startup really slow. But it can even be done in background, while the user decides what to do next.

A: If you mean also other resources than classfiles then you could use the proxy pattern to delay loading (lazy loading) until you really need the resources.

A: On Windows 7 and had a similar issue with Java Applications Client Side. Anything that extended any Gui (Frame, JFrame, etc...) would start to take over a minute to run and load from only taking a few seconds.
Traced it down to IIS running in the background (after an update?).
Stopping its service from Control Panel\Programs\Programs and Features - Turn Windows features on and off.
And now the Java Applications are loading in a couple of seconds again.
Hope other people find this helpful. :-)


text:
Q: How to Copy from Windows Application which doesnt support clipboard I have a windows application which has a text area but I cannot copy using Ctrl+C. The text is readable and selectable but I cannot copy it. Is there any software or addon to enable the copy to clipboard.

A: It may depend on the version of windows you are using but GetWindowText
can help you.
I haven't used it though.Please let me know if it works.

A: Try to add Clipboarder trow Desktop Gadgets. That Clipboard tracks everything you copy. Maybe you Clipboard gets cleared after coping, but with the gadget you can select it afterwords


text:
Q: .click does not fire client-side validation in IE8 So I have a Create page with an MVC Html.BeginForm with input controls and a submit button (id = "myButton") inside. This form is loaded inside an iframe (id = "myFrame") of my Edit page. The edit page has a modal popup with the iframe. When I click a button in the modal popup of the edit page, I call $("#myFrame").contents().find("#myButton").click() in my javascript file.
My question is, when I call .click() of the button, why doesn't it fire my client-side validations in IE8? I tried it on chrome and it works fine.
I've already wasted 3 days searching for an answer but so far I came up with nothing. Help would be very much appreciated.

A: Events can get tricky and behave differently in different browsers. Try this one:
$("#myButton").trigger("click");

or
jQuery.event.trigger("click", button);


text:
Q: Groovy module is not loaded when creating Elasticsearch 5 Node in Java code I'm currently trying to migrate an application from using ES 1.7 to ES 5.4. While the migration of the actual application is pretty smooth, the tests are a pain. The problem are lots of Groovy scripts in the aggregations. To test those, an Elasticsearch Node is constructed via Java code. That works fine for ES 1.7, but throws exceptions for ES 5.4. The node is constructed like this:
final Settings.Builder elasticsearchSettings = Settings.builder()
            .put("transport.type", "local")
            .put("http.enabled", "false")
            .put("cluster.name", "integration-test-cluster")
            .put("path.home", DEFAULT_ES_DIRECTORY)
            .put("path.data", DEFAULT_DATA_DIRECTORY)
            .put("path.logs", DEFAULT_LOGS_DIRECTORY)
            .put("script.inline", "true")
            .put("script.file", "true")
            .put("script.legacy.default_lang", "groovy")
return new Node(elasticsearchSettings.build()).start();

I added groovy-lang (2.4.5) as dependency as well as groovy-all. But when I then pass a Groovy script in an aggregation, the test fails with an exception:
Caused by: java.lang.IllegalArgumentException: script_lang not supported [groovy]
at org.elasticsearch.script.ScriptService.getScriptEngineServiceForLang(ScriptService.java:187)
at org.elasticsearch.script.ScriptService.compile(ScriptService.java:259)
at org.elasticsearch.index.query.QueryShardContext.getLazySearchScript(QueryShardContext.java:353)

When I turn on logging for this Elasticsearch node, I see that the Groovy module is not even loaded:
[INFO ] 2017-05-23 16:39:42.857 [main] PluginsService - no modules loaded
[INFO ] 2017-05-23 16:39:42.857 [main] PluginsService - no plugins loaded

I tried to force the loading of that module by adding a "modules" file in the directory Elasticsearch will run (the one defined in DEFAULT_ES_DIRECTORY) with just "lang-groovy" in it, but that just results in a different exception:
java.lang.IllegalStateException: Unable to initialize modules
at sun.nio.fs.UnixFileSystemProvider.newDirectoryStream(UnixFileSystemProvider.java:426)
at java.nio.file.Files.newDirectoryStream(Files.java:457)
at org.elasticsearch.plugins.PluginsService.getModuleBundles(PluginsService.java:270)
at org.elasticsearch.plugins.PluginsService.<init>(PluginsService.java:116)
at org.elasticsearch.node.Node.<init>(Node.java:309)
at org.elasticsearch.node.Node.<init>(Node.java:242)

I tried to use the constructor that uses the classpathPlugins as parameters and pass the GroovyPlugin.class from groovy-lang, but, as you might have guessed, all I get is an exception:
java.lang.VerifyError: class org.elasticsearch.script.groovy.GroovyPlugin overrides final method onModule.(Lorg/elasticsearch/script/ScriptModule;)V
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

So how can I activate Groovy scripts for that node?


text:
Q: Motivation of this multiplication method I have pondered this question for a while while drinking some Chai spice tea (yes the double use of the word "while" makes sense):
Suppose $x = 5678$ and $y = 1234$. Now let us label each of the parts of the numbers as follows: $$x = \underbrace{56}_{a} \underbrace{78}_{b}$$ $$y = \underbrace{12}_{c} \underbrace{34}_{d}$$
Write $x= 10^{n/2}a+b$ and $y = 10^{n/2}c+d$. Then $$xy = 10^{n}ac+10^{n/2}(ad+bc)+bd$$
Where does recursion play a role in this? For recursion to work, we would need a base case. Also is possible to represent this in matrix form, e.g.:
$$ \begin{bmatrix}a & b \\ c & d \end{bmatrix} = \begin{bmatrix} 56 & 78 \\ 12 & 34 \end{bmatrix}$$
The $ad+bc$ term reminded me of the matrix determinant for a $2 \times 2$ matrix except the terms are added.

How do we compute the terms $ac, ad, bc$ and $ad+bc$ using recursion?

A: Your algorithm computes the product of $x$ and $y$, both $n$-digit numbers. You divide each of $x$ and $y$ into four $n/2$-digit numbers  $a, b, c, d$ and find you need to find the products $ac,ad,bc,ad+bc$. Each of these is a product of $n/2$-digit numbers, so you can use your multiplication algorithm recursively to compute these numbers.
In other words, start with two $n$-digit numbers (pad with zeros to make $n$ a power of two), then that product will require $4$ products of $n/2$-digit numbers, each of which will require $4$ products of $n/4$-digit numbers, and so on. Obviously, you'll stop the recurrence when you get down to numbers that can be computed directly, so for instance you could always stop the recursion when $n=1$. Just counting the multiplications (since the additions and shifts will take less time than the multiplications), we have the recurrence for the time this will take,
$$
T(n)=\begin{cases}
       1 & \text{if $n=1$}\\
       4T(n/2) & \text{if $n>1$}
     \end{cases}
$$
Which, unfortunately, has the solution $T(n)=n^2$, which is no faster than if we'd just used naive multiplication.
The real key to this multiplication algorithm is that you actually only need to perform three products. Since
$$(a+c)(b+d) = ab+ad+bc+cd
$$
we can compute
$$P_1=ab,\quad P_2 = cd,\quad P_3 =(a+c)(b+d)
$$
and then
$$
ad+bc=P_3-P_2-P-1
$$
This means that if we do this recursively we'll only need $3$ multiplcations of $n/2$-digit numbers and this will have running time about $n^{\log_2 3}\approx n^{1.585}$ which is asymptotically much better than $n^2$.
As a side note, you can do even better by splitting your numbers in groups of three, rather than 2, using seven products rather than three, though now the computational overhead starts to eat into the running time so this is only time-saving on really long numbers. There are, by the way, even faster ways to multiply.


text:
Q: PHPUnit. Протестировать ветку кода, которая зависит от настроек php.ini, неизменяемых в runtime Предыстория
На некоторых "не_очень_хороших" хостингах любят безальтернативно отключать некоторые функции через php.ini. В частности иногда полезную parse_ini_file. В своем проекте (легковесный скелет api) обошел таким образом:
if (function_exists('parse_ini_file')) {
    self::$settings = parse_ini_file(PROPERTIES);
    return;
}
$content = preg_grep("/^[\w .]+=.*/", explode(PHP_EOL, file_get_contents(PROPERTIES)));
foreach ($content as $row) {
    $row                    = strstr($row . ';', ';', true);
    $key                    = trim(strstr($row, '=', true), " \n\r");
    $value                  = trim(strstr($row, '=', false), " \"=\n\r");
    self::$settings[ $key ] = $value;
}

Вопрос
Как мне теперь прикрутить PHPUnit для тестирования куска кода с рукописным парсером?
Идеально было бы задисейблить ее в рантайме, но можно ли это сделать я как-то инфы не нашел.
PS Собственно я нахожусь в самом начале изучения PHPUnit и, возможно, есть true way, которого просто не знаю.

A: Зашел с черного хода.
Вынес самописный парсер в отдельный приватный метод
private static function loadSettings() {
    self::$settings = function_exists('parse_ini_file')
        ? parse_ini_file(PROPERTIES)
        : self::loadSettingsHard();
}

private static function loadSettingsHard() {
    $settings = [];
    $content  = preg_grep("/^[\w .]+=.*/", explode("\n", file_get_contents(PROPERTIES)));
    foreach ($content as $row) {
        $row              = strstr($row . ';', ';', true);
        $key              = trim(strstr($row, '=', true), " \n\r");
        $settings[ $key ] = trim(strstr($row, '=', false), " \"=\n\r");
    }

    return $settings;
}

В тестовом методе применил грязный хак с Reflection
public function testGetConfigValueHard() {
    $method = new ReflectionMethod(
        Config::class, 'loadSettingsHard'
    );
    $method->setAccessible(true);
    $method->invoke(Config::class);
    $this->assertEquals(
        'localhost',
        Config::get('db_host')
    );
}

В общем и целом, эта задача позволила меня посмотреть на тестирование с неожиданной стороны. Для покрытия тестами данного функционал я был вынужден уменьшить цикломатическую сложность своего кода (по факту применил принцип единственной ответственности), что является одним из столпов хорошей архитектуры приложения.
Что же до ответа на вопрос, то удалить функцию в рантайме можно с помощью функции runkit_function_remove, которая входит в PECL расширение runkit. По многим причинам такой подход нежелателен.


text:
Q: Getting CodeIgniter Active Record's current SQL code for example, i want to convert this;
$this->db->get('table');

to this;
'SELECT * FROM table'

is there any function for this? i searched on the user guide of CI but didnt find any solution.

A: You can also use $this->db->get_compiled_select(). The difference between get_compiled_select() and last_query() is that get_compiled_select() gives the query string generated even if you don't run the query against the database.

A: Try
echo $this->db->last_query();

after you run your Active Record Query and it'll spit out the raw SQL it ran for you. I use it often.


text:
Q: Trigger jquery script from PHP I am trying to do the following:
1: Load an XML file (with a list devices that has a static name, and a changing value and note) - this works
2: Load the XML (t=0) into varaiables for easy use in the HTML - this works
3: Load XML again (t=200ms) - this works (I think)
4: Check if any values have changed between the two XML's
5: If TRUE then update one or more

Task 1: I guess I need to have the loadxml script run again whenever it is done or say every 200 ms
Task 2: I need to write and call a script that can update the

I have made my code with only two parameters for easy understanding and put in comments where I guess I need to have something.
If this is a crazy overall architecture, please give me a direction to look to.
<?php

loadxml() ;

function loadxml() {
$feed_url = "demoxml.xml";
$xml = file_get_contents($feed_url);
$array = json_decode(json_encode((array)simplexml_load_string($xml)),1);

for ($id=1; $id<=157; $id++) {

//dynamic
$generation='new';
$hs3device_note[$id][$generation]= $array['device'][$id]['@attributes']['note'] ;
if ($hs3device_note[$id]['current'] != $hs3device_note[$id]['new']) { ;
$hs3device_note[$id]['current'] = $hs3device_note[$id]['new'] ;
//CALL SCRIPT (like ReplaceContentInContainer) TO UPDATE
 WITH CONTENT $hs3device_note[$id]['new'])
} ;
$hs3device_value[$id][$generation]= $array['device'][$id]['@attributes']['value'] ;
if ($hs3device_value[$id]['current'] != $hs3device_value[$id]['new']) { ;
$hs3device_value[$id]['current'] = $hs3device_value[$id]['new'] ;
//CALL SCRIPT (like ReplaceContentInContainer) TO UPDATE
 WITH CONTENT $hs3device_note[$id]['new'])
} ;

}
//MAKE loadxml() call it self or restart in 200 ms
} ;

...

...

A: AJAX or Asynchronous JavaScript and XML is a method of sending requests to a server from JavaScript asynchronously (hence the name), with your question it would mean you can send a request to the server (at a specified interval) to see if some data has changed and if the PHP script evaluates true (ie it has) then it is sent back to the HTML page to replace the existing data that is being displayed.
function myXMLRequest() {
    var request = $.ajax({
        url: "script.php",
        type: "POST",
        data: { action:'testmyxml' },
        dataType: "html"
    });

    request.done(function( msg ) {
        setTimeout(function() {
            myXMLRequest();
        }, 5000);
        if(msg != "") {
            $( "#mydiv" ).html( msg );
        }
    });

    request.fail(function( jqXHR, textStatus ) {
        alert( "Request failed: " + textStatus );
    });
}

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

Reference: JQuery API documentation.

http://api.jquery.com/jquery.ajax/

the script.php is your php script that does all the logic, data is sent back using PHP's 'echo' command, if not don't echo anything... (you can test if msg is empty client side). msg will hold all the information that has been echoed by PHP in script.php and can be put into a div as shown in my example.


text:
Q: Find all primes $p,q$ such that $p^q + q^p$ is perfect square Just a hint for a solution? I tried to separate the cases when one of the primes is $2$, so it would be $2^p + p^2 = k^2$ for some $k$. Since $2^p$ is even, and $p^2$ is odd, it implies that $k^2$ is odd and therefore must be in form $4k+1$... but don't know what to do next.

A: For the case you are investigating, we have $k-p$ and $k+p$ are both powers of $2$, say $2^a$ and $2^b$. That gives $p=\frac{2^b-2^a}{2}$. Not many possibilities for $a$!


text:
Q: Unable to catch SQLAlchemy IntegrityError If I try to commit a record to my database and it already exists then I want to use a try/except block to handle it:
from sqlalchemy.exc import IntegrityError

try:
    session.commit()
except IntegrityError:
    # do something else

However, I can't seem to catch the error. Here's a typical error that occurs on session.commit():
Exception has occurred: IntegrityError
(mysql.connector.errors.IntegrityError) 1062 (23000): Duplicate entry '88306-1' for key 'match_feat.idx_match_feat__composite'

I wondered if I was trying to catch the wrong error so I tried using:
from mysql.connector.errors import IntegrityError

But I get the same error message.
The answers to the question here focus on adding session.rollback() to the except: block however this doesn't help me (or the OP?) as I'm getting the error in the try: block and so the except: block isn't ever triggered.

A: Worked this out. The answers to the question here were correct. A rollback() is needed at the start of the except block. I'm not sure on the exact mechanics but the error was being caught on the first iteration of the code however if the transaction wasn't then rolled back then the second time through the error occurred in the try block and wasn't caught. This solved the issue:
try:
    session.commit()
except IntegrityError:
    session.rollback()
    # do something else

A: I assume that the pass statement was used in the except block to tell Python to do nothing, for example:
try:
    session.commit()
except IntegrityError:
    pass

As the example in the question would result in an IndentationError being raised.
Based on your answer, it seems that the IntegrityError is being raised elsewhere in the code and not by session.commit() inside the try block. I suggest reviewing the stack trace generated when the exception is raised to find out where in your code this exception is being raised. The Python debugger can also be used to step through the code line-by-line.


text:
Q: OneTone WP Theme - Adjust Background Vide Size I'm using the "OneTone" theme from MageeWP on Wordpress. I'm trying to alter the CSS code to change the video background from full screen to half screen.
I did the following:
#tubular-container{
     height: 550px !important;  /* My edit */
   position:absolute!important;
 }

This is a decent work around, it pulls up the second section so it COVERS half the video, I was wondering if anyone knows the exact CSS section to actually CHANGE the video size. THANKS!!
Code is too big to paste but this is a very very popular FREE theme on Wordpress. Link to the site is here: https://wordpress.org/themes/onetone/


text:
Q: Add A Gallery - Android How can I dynamically add a gallery to an android app, I have:
Gallery gallery = new Gallery(this);

But it doesnt work.

A: set the Layout parameters of gallery, ie size then take a Layout and add into it
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
gallery.setLayoutParams(layoutParams);

LinearLayout mLinearLayout=(LinearLayout) findViewByID(R.id....);
mLinearLayout.addView(gallery);


text:
Q: Pipes, how do data flow in a pipeline? I don't understand how the data flows in the pipeline and hope someone could clarify what is going on there.
I thought a pipeline of commands processes files (text, arrays of strings) in line by line manner. (If each command itself works line by line.) Each line of text passes through the pipeline, commands don't wait for the previous to finish processing whole input.
But it seems it is not so.
Here is a test example. There are some lines of text. I uppercase them and repeat each line twice. I do so with cat text | tr '[:lower:]' '[:upper:]' | sed 'p'.
To follow the process we can run it "interactively" -- skip the input filename in cat. Each part of the pipeline runs line by line:
$ cat | tr '[:lower:]' '[:upper:]'
alkjsd
ALKJSD
sdkj
SDKJ
$ cat | sed 'p'
line1
line1
line1
line 2
line 2
line 2

But the complete pipeline does wait for me to finish the input with EOF and only then prints the result:
$ cat | tr '[:lower:]' '[:upper:]' | sed 'p'
I am writing...
keep writing...
now ctrl-D
I AM WRITING...
I AM WRITING...
KEEP WRITING...
KEEP WRITING...
NOW CTRL-D
NOW CTRL-D

Is it supposed to be so? Why isn't it line-by-line?

A: This actually took me some thought to understand and even more to answer. Great question (I'll upvote it next).
You neglected to try tr | sed in your debugging items above:
>tr '[:lower:]' '[:upper:]' | sed 'p'
i am writing
still writing
now ctrl-d
I AM WRITING
I AM WRITING
STILL WRITING
STILL WRITING
NOW CTRL-D
NOW CTRL-D
>

So evidently tr buffers. Learn something new everyday!
EDIT:
As I think this over, we have isolated the cause, but not provided an explanation. If you cat | tr, it writes right away, if you cat | sed, it writes right away, but if you tr | sed, it waits for EOF. I would suggest the answer might be buried in tr or sed source code then, and not be a pipe issue.
EDIT:
I see Wumpus provided the explanation while I was typing the last edit. Thanks!

A: There's a general buffering rule followed by the C standard I/O library (stdio) that most unix programs use. If output is going to a terminal, it is flushed at the end of each line; otherwise it is flushed only when the buffer (8K on my Linux/amd64 system; could be different on yours) is full.
If all your utilities were following the general rule, you would see output delayed in all of your examples (cat|sed, cat|tr, and cat|tr|sed). But there's an exception: GNU cat never buffers its output. It either doesn't use stdio or it changes the default stdio buffering policy.
I can be fairly sure you're using GNU cat and not some other unix cat because the others wouldn't behave this way. Traditional unix cat has a -u option to request unbuffered output. GNU cat ignores the -u option because its output is always unbuffered.
So whenever you have a pipe with a cat on the left, in the GNU system, the passage of data through the pipe will not be delayed. The cat isn't even going line by line - your terminal is doing that. While you're typing input for cat, your terminal is in "canonical" mode - line-based, with editing keys like backspace and ctrl-U offering you the chance to edit the line you have typed before sending it with Enter.
In the cat|tr|sed example, tr is still receiving data from cat as soon as you press Enter, but tr is following the stdio default policy: its output is going to a pipe, so it doesn't flush after each line. It writes to the second pipe when the buffer is full, or when an EOF is received, whichever comes first.
sed is also following the stdio default policy, but its output is going to a terminal so it will write each line as soon as it has finished with it. This has an effect on how much you must type before something shows up on the other end of the pipeline - if sed was block-buffering its output, you'd have to type twice as much (to fill tr's output buffer and sed's output buffer).
GNU sed has -u option so if you reversed the order and used cat|sed -u|tr you would see the output appear instantly again. (The sed -u option might be available elsewhere but I don't think it's an ancient unix tradition like cat -u) As far as I can tell there's no equivalent option for tr.
There is a utility called stdbuf which lets you alter the buffering mode of any command that uses the stdio defaults. It's a bit fragile since it uses LD_PRELOAD to accomplish something the C library wasn't designed to support, but in this case it seems to work:
cat | stdbuf -o 0 tr '[:lower:]' '[:upper:]' | sed 'p'


text:
Q: NSManagedObject and categories/subclasses I'm working on an app where there are two different NSManagedObject types that might point to a user-taken video via an NSURL.  My thought was to create another NSManagedObject (video) to hold the URL reference, and when no other objects point to the video object, call the file system to remove the file pointed to by the NSURL.
Relative cocoa newbie question: what is the appropriate cocoa idiom for this?  Coming from C++, I'd subclass video to override the delete function (which Apple's documentation seems to suggest is not ideal).  I could imagine writing a category of video which has some extra functionality but this would need to be explicitly called?
Thanks for any ideas.

A: You can override the prepareForDeletion method in your custom NSManagedObject subclass to delete the underlying file when the object is about to be deleted. It's designed for exactly this purpose.


text:
Q: web service written in java but called in c# I am trying to import a web service from another application into a custom asp.net application. However, it's throwing an error at the moment. Have you seen the following error before (see below)?

Custom tool error: Unable to import
  WebService/Schema. Unable to import
  binding 'AuthenticateSoapBinding' from
  namespace
  'http://site:80/LiveTime/WebObjects/LiveTime.woa/ws/Authenticate'.
  Unable to import operation 'connect'.
  Types must be declared at the top
  level in the schema. Please review
  schema type 'Map' from namespace
  'http://xml.apache.org/xml-soap':
  element 'item' is using anonymous type
  declaration, anonymous types are not
  supported with encoded SOAP.

Some initial research in google shows the following:
Java .Net Interop. Axis java.util.Map
http://wiki.apache.org/ws/FrontPage/Axis/DotNetInteropMapInfo
Which mentioned that the web service need to be changed. However, I don't think this is going to happened. Any idea on how to get around this?
The following is the web service XML that I get the information from:
<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://server:80/LiveTime/WebObjects/LiveTime.woa/ws/Authenticate" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://server:80/LiveTime/WebObjects/LiveTime.woa/ws/Authenticate" xmlns:intf="http://server:80/LiveTime/WebObjects/LiveTime.woa/ws/Authenticate" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><wsdl:types><schema targetNamespace="http://xml.apache.org/xml-soap" xmlns="http://www.w3.org/2001/XMLSchema"><import namespace="http://schemas.xmlsoap.org/soap/encoding/"/><complexType name="Map"><sequence><element maxOccurs="unbounded" minOccurs="0" name="item"><complexType><all><element name="key" type="xsd:anyType"/><element name="value" type="xsd:anyType"/></all></complexType></element></sequence></complexType></schema></wsdl:types>
  <message name="keepAliveResponse">
    <part name="keepAliveReturn" type="apachesoap:Map"/>
  </message>
  <message name="connectResponse">
    <part name="connectReturn" type="apachesoap:Map"/>
  </message>
  <message name="connectRequest">
    <part name="username" type="xsd:string"/>
    <part name="password" type="xsd:string"/>
  </message>
  <message name="disconnectRequest">
  </message>
  <message name="disconnectResponse">
    <part name="disconnectReturn" type="apachesoap:Map"/>
  </message>
  <message name="keepAliveRequest">
  </message>
  <portType name="Authenticate">
    <operation name="connect" parameterOrder="username password">
      <input message="impl:connectRequest" name="connectRequest"/>
      <output message="impl:connectResponse" name="connectResponse"/>
    </operation>
    <operation name="keepAlive">
      <input message="impl:keepAliveRequest" name="keepAliveRequest"/>
      <output message="impl:keepAliveResponse" name="keepAliveResponse"/>
    </operation>
    <operation name="disconnect">
      <input message="impl:disconnectRequest" name="disconnectRequest"/>
      <output message="impl:disconnectResponse" name="disconnectResponse"/>
    </operation>
  </portType>
  <binding name="AuthenticateSoapBinding" type="impl:Authenticate">
    <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="connect">
      <wsdlsoap:operation soapAction=""/>
      <input name="connectRequest">
        <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://ws.livetime.com" use="encoded"/>
      </input>
      <output name="connectResponse">
        <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://server:80/LiveTime/WebObjects/LiveTime.woa/ws/Authenticate" use="encoded"/>
      </output>
    </operation>
    <operation name="keepAlive">
      <wsdlsoap:operation soapAction=""/>
      <input name="keepAliveRequest">
        <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://ws.livetime.com" use="encoded"/>
      </input>
      <output name="keepAliveResponse">
        <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://server:80/LiveTime/WebObjects/LiveTime.woa/ws/Authenticate" use="encoded"/>
      </output>
    </operation>
    <operation name="disconnect">
      <wsdlsoap:operation soapAction=""/>
      <input name="disconnectRequest">
        <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://ws.livetime.com" use="encoded"/>
      </input>
      <output name="disconnectResponse">
        <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://server:80/LiveTime/WebObjects/LiveTime.woa/ws/Authenticate" use="encoded"/>
      </output>
    </operation>
  </binding>
  <service name="Authenticate">
    <port binding="impl:AuthenticateSoapBinding" name="Authenticate">
      <wsdlsoap:address location="http://server:80/LiveTime/WebObjects/LiveTime.woa/ws/Authenticate"/>
    </port>
  </service>
</definitions>


text:
Q: $(document).ready() firing before partial view is loaded I have a page that has a partial view withing it.
MyMainView.cshtml

    @Html.Partial("MyPartial")

@section pagespecific {

}

MyPartial.cshtml

    @Html.HiddenFor(x => x.MyModelField)

The value of MyModelField in the model is True, however, I get the following output into the browser console:
Value is: undefined

Why isn't this picking up the field? Shouldn't the partial view have been added to the DOM before this fires?
If I change the $(document).ready() to $(window).load() it works as expected.
How can I achieve the desired behavior?

A: Yes it is true, the reason is whenever your dom is ready .ready is fired. So your page is loaded first and it fires the jquery .ready function() , while the sequentially execution partial view also execute at server side.
Both are different in the usability.
To stop or you want to execute after some time.

*

*Either you can do this in partial view

or

*

*Give the delay time of your duration
$(document).ready(function(){
    console.log('Value is: ' + $('#MyModelField').val());
    setTimeout("$('#buttonid').click()", DelayDuration);
});

//DelayDuration means give milisecond value, 1000 milisecond = 1 sec
The same question asked here
JQuery events don't work with ASP.NET MVC Partial Views
Is it possible to kick off a javascript function after a partial view renders in MVC Asp.net?

A: $(document).ready doesn't fire before partial is rendered because partial view is rendered on server-side. You're using wrong ID in jquery because @Html.HiddenFor(x => x.MyModelField) won't create element with ID="MyModelField". Element will have ID with prefix which is dependent on you model class name.
Inspect element's id in browser tools (F12) and determine the real ID.
Example:
If you model name is User class. The generated id will look like User_MyModelField


text:
Q: How does this code work(simple java recursion)? I am having trouble understanding recursion. I understand the theory. Like when a function calls itself, needs a base case to end the recursion and all that but when it comes to using it in a program, I get really confused. For example, I have posted some code below. When I call print function before the recursive function..it prints the numbers in reverse order (54321) and when I call it after the recursion, it prints it as 12345. Why is that?
public class Main {

    public static void main(String[] args) {

        printNumbers(5);
    }

    public static void printNumbers(int num){
        if(num==0) {
            return;
        }
       System.out.println(num); // this prints 54321

        printNumbers(num-1);
       System.out.println(num);//this prints 12345

    }
}

A: This is where something like a "desk check" (pen and paper) will come in very handy so you can step through the code and describe the state at each step.
Essentially, the second print statement won't get called until the printNumbers method returns, meaning that your execution looks something like...
printNumber(5)
    num = 5
    num == 0 = false
    print num (5)
    printNumbers(num - 1)
        num = 4
        num == 0 = false
        print num (4)
        printNumbers(num - 1)
            num = 3
            num == 0 = false
            print num (3)
            printNumbers(num - 1)
                num = 2
                num == 0 = false
                print num (2)
                printNumbers(num - 1)
                    num = 1
                    num == 0 = false
                    print num (1)
                    printNumbers(num - 1)
                        num = 0
                        num == 0 = true (return)
                    print num (1)
                print num (2)
            print num (3)
        print num (4)
    print num (5)


text:
Q: SwiftUI Text being truncated unexpectedly I have an HStack with three elements, as such:
HStack(alignment: .firstTextBaseline) {
    Text(title.uppercased())
        .lineLimit(1)
    Rectangle()
        .frame(height: 1)
        .foregroundColor(Color(.tertiaryLabel))
    Text(value)
        .lineLimit(1)
}

The first text element is being truncated in favor of the rectangle, which seems odd to me since the rectangle seems like it should compress as much as needed to accommodate the surrounding text.

I found that adding .fixedSize() to my Text objects fixes this issue, but is that the best/proper solution?

A: I assume you look for layoutPriority modifier, like
HStack(alignment: .firstTextBaseline) {
    Text(title.uppercased())
        .lineLimit(1)
        .layoutPriority(1)        // << here !!
    Rectangle()
        .frame(height: 1)
        .foregroundColor(Color(.tertiaryLabel))
    Text(value)
        .lineLimit(1)
}


text:
Q: gengetopt: Multiple arguments split with space, not comma When specifying an option as
option "foo" f "" string optional multiple(1-)

gengetopt correctly builds up the array foo_args when called as:
./a.out -f A -f B -f C        # {"A", "B", "C"}
./a.out -f A,B,C              # {"A", "B", "C"}

But this only grabs the first "A", and considers "B" and "C" to be unnamed
./a.out -f A B C              # {"A"}

I'm not using --unnamed-opts, because I don't have any unnamed arguments. I'd like to support that style, because it seems more common… is that easily possible?

A: You might try puting quotes around the space separated list items, like so: -f "A B C" and do an extra parsing.


text:
Q: Firebird DB size do not change I'm using the Firebird DB and I did the following. I create a DB, fill it with a lot of records (size of the DB file 113MB). Then I delete all the records but the size remains the same. Is there any way to "shrink" or to "pack" the DB file?

A: The page at Re: Firebird and vacuum? claims that you need to use gbak to rebuild the database for that.  Note that the file will not grow when you insert records until the total amount of data hits 113MB again, so you might just want to leave the file at that size.


text:
Q: Jackson MyCustomDeserializer super.deserialize(parser, dc, intoValue); not working I'm running Spring Boot with Jackson 2.10.3.
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.10.3</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.10.3</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.10.3</version>
</dependency>

My input value is a json representation of an serialized object, in my case FC.java
When creating the Mapper a new CustomerFCDeserializer is registered.
  mapper = new ObjectMapper();
  SimpleModule module = new SimpleModule();
  module.addDeserializer(FC.class, new CustomFCDeserializer(fcFactory));
  mapper.registerModule(module);

The CustomFCDeserializer is inteded to initialize an FC object the serialized object should be deserialized into.
fc = super.deserialize(parser, dc, fc);
Normally i would just deserialize it, but in this specific case the default constructor can't be called, instead the object needs some other initializiation as done by FcFactory. This way also serialized fields will be set in the object returned by the factory.
public class CustomFCDeserializer extends StdDeserializer<FC> {
    private final FCFactory fcFactory;

    public CustomFCDeserializer(FCFactory fcFactory) {
        super(FC.class);
        this.fcFactory = fcFactory;
    }

    @Override
    public FC deserialize(JsonParser parser, DeserializationContext dc) throws IOException, JsonProcessingException {
        ObjectCodec codec = parser.getCodec();
        JsonNode node = codec.readTree(parser);
        JsonNode idNode = node.get("id");
        long id = idNode.asLong(0);
        FC fc = fcFactory.getFCById(id); //<!--- create my object
        //set values on prev created fc object
        fc = super.deserialize(parser, dc, fc); //<!-- pollute it
        return fc;
    }
}

Running this example will recursivly call deserialize, super.deserialize and finally deserialize again which fails as structure changed.
java.lang.NullPointerException: null
    at objectMapper.CustomFcDeserializer.deserialize(CustomFcDeserializer.java:38) ~[classes/:na]
    at objectMapper.CustomFcDeserializer.deserialize(CustomFcDeserializer.java:16) ~[classes/:na]
    at com.fasterxml.jackson.databind.JsonDeserializer.deserialize(JsonDeserializer.java:129) ~[jackson-databind-2.9.0.jar:2.9.0]
    at objectMapper.CustomFcDeserializer.deserialize(CustomFcDeserializer.java:51) ~[classes/:na]
    at objectMapper.CustomFcDeserializer.deserialize(CustomFcDeserializer.java:16) ~[classes/:na]
[...]

Is there a better way than handeling this issue by a bunch of if statements?
Or is the a more intelligent way to pollute and existing object?
deserialize(JsonParser p, DeserializationContext ctxt, T intoValue) seems be fine as it takes an intoValue, but im deserializing an object, not a collection nor map. Btw and my object isn't and doesnt have immutable members.
com.fasterxml.jackson.databind.JsonDeserializer
public T deserialize(JsonParser p, DeserializationContext ctxt, T intoValue) throws IOException
Alternate deserialization method (compared to the most commonly used, deserialize(JsonParser, DeserializationContext)), which takes in initialized value instance, to be configured and/or populated by deserializer. Method is not necessarily used (or supported) by all types (it will not work for immutable types, for obvious reasons): most commonly it is used for Collections and Maps. It may be used both with "updating readers" (for POJOs) and when Collections and Maps use "getter as setter".
Throws: IOException

A: went to deep into overwriting mapper and deserializer,
simply do
Map<String, Object> fcInput = dfe.getArgument("fcInput");
FC fcInput = mapper.convertValue(fcInput, FC.class);
String fcString = mapper.writeValueAsString(fcInput);

long fcId = fcInput.getId();
FC existingFc = fcFactory.getFC(fcId);

ObjectMapper om = new ObjectMapper();
ObjectReader or = om.readerForUpdating(existingFc);
FC updatedFc = or.readValue(fcString);


text:
Q: Cannot open database "C:\PROGRAM FILES\X\Y\Z.MDF" requested by the login. The login failed. Login failed for user 'DESKTOP-xxxxx'' I have created a windows form application. I have included a local dabase named Z.mdf.  In the app.config the connection string is like below:
<connectionStrings>
    <add name="ZConnectionString"
        connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Z.mdf;Integrated Security=false;Connect Timeout=30"
        providerName="System.Data.SqlClient" />
</connectionStrings>

When I run the application from visual studio,it works fine. But when I deploy the application with advanced installer, it gives the following error:

Cannot open database "C:\PROGRAM FILES\X\Y\Z.MDF" requested by the login. The login failed. Login failed for user 'DESKTOP-xxxxx''

How can I resolve this problem?

A: Your connection string specifies Integrated Security=false; so the login isn't using your Windows user account.
You need to either use Integrated Security=true or you need to specify a user id and password on your connection string:
<connectionStrings>
<add name="ZConnectionString"
    connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Z.mdf;
    Integrated Security=false; user id=xyz; password=abc;Connect Timeout=30"
    providerName="System.Data.SqlClient" />
</connectionStrings>


text:
Q: Celery chain results from task to map to another I have a celery application
@task
def step_one(items):
    items.sort()
    for i in range(len(items), 100):
        yield items[i:i + 100]

@task
def step_two(batch):
    for item in batch:
        print(item)

if __name__ == '__main__':
    celery.chain(step_one.s([i for i in range 100000]), step_two.map().s()).delay()

This does not work because step_two is expecting an iterator, but I want it to take the results from the previous step, what is the correct way to go about this? It would also be nice if tasks could start at the yield rather than after the whole list is sorted and chunked.
I have seen this question Best way to map a generated list to a task in celery but I feel that it should not be necessary to create an intermediate step to map the results to another task. Additionally, calling step_two.map.s() gives me an error function object has no attribute s


text:
Q: How to function return a selectbox with foreach? I am writing some code for a plugin in joomla. I need to return a html select populated with a foreach with data from an array. I got stuch in commas.... Something like this, but populated with foreach:
return '<select id="'.$this->id.'" name="'.$this->name.'">'.
           '<option value="1" >New York</option>'.
           '<option value="2" >Chicago</option>'.
           '<option value="3" >San Francisco</option>'.
           '</select>';

A: Writing a foreach loop is kinda simple:
$result = '<select id="'.$this->id.'" name="'.$this->name.'">';
foreach (array(1 => 'New York', 2 => 'Chicago') as $k => $v) {
    $result .= '<option value="' . $k .'" >' . $v . '</option>';
}
$result .= '</select>';
return $result;