text:
Q: Most simple but complete CMake example Somehow I am totally confused by how CMake works. Every time I think that I am getting closer to understanding how CMake is meant to be written, it vanishes in the next example I read. All I want to know is, how should I structure my project, so that my CMake requires the least amount of maintainance in the future. For example, I don't want to update my CMakeList.txt when I am adding a new folder in my src tree, that works exactly like all other src folders.
This is how I imagine my project's structure, but please this is only an example. If the recommended way differs, please tell me, and tell me how to do it.
myProject
    src/
        module1/
            module1.h
            module1.cpp
        module2/
            [...]
        main.cpp
    test/
        test1.cpp
    resources/
        file.png
    bin
        [execute cmake ..]

By the way, it is important that my program knows where the resources are. I would like to know the recommended way of managing resources. I do not want to access my resources with "../resources/file.png"

A: The most basic but complete example can be found in the CMake tutorial:
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
add_executable(Tutorial tutorial.cxx)

For your project example you may have:
cmake_minimum_required (VERSION 2.6)
project (MyProject)
add_executable(myexec src/module1/module1.cpp src/module2/module2.cpp src/main.cpp)
add_executable(mytest test1.cpp)

For your additional question, one way to go is again in the tutorial: create a configurable header file that you include in your code. For this, make a file configuration.h.in with the following contents:
#define RESOURCES_PATH "@RESOURCES_PATH@"

Then in your CMakeLists.txt add:
set(RESOURCES_PATH "${PROJECT_SOURCE_DIR}/resources/")
# configure a header file to pass some of the CMake settings
# to the source code
configure_file (
  "${PROJECT_SOURCE_DIR}/configuration.h.in"
  "${PROJECT_BINARY_DIR}/configuration.h"
)

# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
include_directories("${PROJECT_BINARY_DIR}")

Finally, where you need the path in your code, you can do:
#include "configuration.h"

...

string resourcePath = string(RESOURCE_PATH) + "file.png";

A: Note: This answer is long because the innocent-looking question and the multiple topics it covers are deceptively broad, and the question's intended audience is for beginners (people new to CMake). Trust me- this answer could have been a lot longer than it is.
What CMake is

Somehow I am totally confused by how CMake works. Every time I think that I am getting closer to understanding how CMake is meant to be written, it vanishes in the next example I read.

CMake is a buildsystem generator. You write a configuration to describe a buildsystem (a project and its build targets and how they should be built) (and optionally, tested, installed, and packaged). You give the CMake program that configuration and tell it what kind of buildsystem to generate, and it generates it (providing that that buildsystem is supported). Such supported buildsystems include (but are not limited to): Ninja, Unix Makefiles, Visual Studio solutions, and XCode.
The buildsystem is the thing that understands (because you instruct it on) how your project needs to be built- what source files it has, and how those source files should get compiled into object files, and how those object files should get linked together into executables or dynamic/shared or static libraries.
The advantages of using CMake should not be understated. If you want to support multiple buildsystems (which is especially common for cross-platform library authors who want to allow their users to make their own buildsystem choices and save those users the work of writing those buildsystem configurations), it is a lot less work to write one CMake configuration than N configurations for N different buildsystems in their own languages and ways of doing things.
Actually, CMake supports other programming languages and their buildsystems than just C and C++, but since you're just asking about C++, I'll leave that out.
Tricks to avoid CMake when using CMake (don't try at home, kids)

All I want to know is, how should I structure my project, so that my CMake requires the least amount of maintainance in the future. For example, I don't want to update my CMakeList.txt when I am adding a new folder in my src tree, that works exactly like all other src folders.

Contrary to what you think, a small degree of having to modify CMakeLists.txt files whenever you add new source files is a very small cost in return for all the benefits of what CMake can provide, and trying to circumvent that cost has its own costs that become problems at scale. That's why those circumvention techniques (namely, file(GLOB)) that people often use are discouraged for use by the maintainers of CMake, and by various long-time users of CMake on Stack Overflow, as seen here and here.
When you have a small project with a few files, it's not very cluttery to list out those few source files in your CMakeLists.txt files, and when you have big projects with lots of source files, you're still better off listing out the source files explicitly for the reasons previously listed in the linked resources. In short, it's for your own good and sanity. Don't try to fight it.
A basic CMake configuration

This is how I imagine my project's structure, but please this is only an example. If the recommended way differs, please tell me, and tell me how to do it.
myProject
    src/
        module1/
            module1.h
            module1.cpp
        module2/
            [...]
        main.cpp
    test/
        test1.cpp
    resources/
        file.png
    bin
        [execute cmake ..]

If you're looking for a convention to use for project filesystem layout, one well-specified layout spec is The Pitchfork Layout Convention (PFL), which was written based on conventions that emerged in the C++ community over time.
Here's what this project layout might look like following the PFL spec with split headers and split tests:
myProject/
  CMakeLists.txt
  libs/
    module1/
      CMakeLists.txt
      include/myProject_module1/
        module1.h
      src/myProject_module1/
        module1.cpp
      tests/
        CMakeLists.txt
        test1.cpp
      data/
        file.png
    module2/
      CMakeLists.txt
      src/module2
        main.cpp
      [...]
  build/

Note: it doesn't have to be include/myProject_module1/- it can just be include/, but adding the myProject_module1/ makes the #includes for each module "namespaced" so that two modules (even if one is from a separate project) can have header files of the same name, and that those headers can all be included in one source file without clashing or ambiguities, like so:
#include <myProject_module1/foo.h>
#include <myProject_module2/foo.h>
#include <yourProject_module1/foo.h>
// Look, ma! No clashing or ambiguities!

Since you allowed so in your question, for the rest of the config code examples, I will use the above PFL layout.
myProject/CMakeLists.txt:
cmake_minimum_required(VERSION 3.25)
# ^choose a CMake version to support (its own can of worms)
# see https://alexreinking.com/blog/how-to-use-cmake-without-the-agonizing-pain-part-1.html
project(example_project
  VERSION 0.1.0 # https://semver.org/spec/v0.1.0.html
  DESCRIPTION "a simple CMake example project"
  # HOMEPAGE_URL ""
  LANGUAGES CXX
)
if(EXAMPLE_PROJECT_BUILD_TESTING)
  enable_testing()
  # or alternatively, `include(CTest)`, if you want to use CDash
  # https://cmake.org/cmake/help/book/mastering-cmake/chapter/CDash.html
endif()
add_subdirectory(libs/module1)
add_subdirectory(libs/module2)
# ^I generally order these from lower to higher abstraction levels.
# Ex. if module1 uses module2, then add_subdirectory it _after_ module2.
# That allows doing target_link_libraries inside moduleN/CmakeLists.txt
# instead of here (although that's equally fine. a matter of preference).

The cmake_minimum_required() command is where you declare what version of CMake is required to parse and run your CMake configuration. The project() command is where you declare the basic project information, the enable_testing() command enables testing for the current directory and below, and each add_subdirectory command changes the "current directory", creates a new subdirectory "scope", and parses the CMakeLists.txt file found at that path.
Here are the docs for cmake_minimum_required(), project(), enable_testing() and add_subdirectory().
myProject/libs/module1/CMakeLists.txt (and similar for module2):
# if module1 is a library, use add_library() instead
add_executable(module1
  src/module1.cpp
)
target_compile_features(okiidoku PUBLIC cxx_std_20) # or whatever language standard you are using
target_include_directories(module1 PUBLIC include)
if(EXAMPLE_PROJECT_BUILD_TESTING)
  add_subdirectory(tests)
endif()

The add_executable() command is how you declare a new executable target to be built. The add_library is similar, but is how you declare a library target to be built, where the library can be linked to via the target_link_libraries() command.
The target_compile_features() command is how you tell CMake what flag to pass to the compiler to pick a C++ language standard to use, and the target_include_directories() command is how you tell CMake what include directories to specify when compiling implementation files. PUBLIC means that the target itself will need that include directory for its #includes, and that other dependent targets that link to that target will as well. If dependent targets don't need it, use PRIVATE. If only dependent targets need it, use INTERFACE. PUBLIC, PRIVATE, and INTERFACE are relevant for library targets, but I'm not aware of them having any use for executable targets (since I'm pretty sure nothing ever depends on executables linkage-wise), so either PUBLIC or PRIVATE should work when specifying include directories for executable targets.
Here are the docs for add_library(), add_executable(), target_compile_features() target_include_directories(), and target_link_libraries().
If you want to learn more about any CMake command (listed in cmake --help-command-list), just do cmake --help <command>, or google cmake command <command>.
In terms of the tests folder, you can use CMake's testing support without using any C++ testing libraries of frameworks, or use it with a testing library or framework that supports CMake. To read more about CMake and testing in general, read the chapter in the Mastering CMake book. It's too much material to cover in the form of a Stack Overflow answer.

*

*See here for GoogleTest's docs on its CMake support.

*See here for Catch2's docs on its CMake support.

*I couldn't find official Boost.Test docs for usage with CMake's test functionality, but here's CLion's Boost.Test + Cmake tutorial page, and here's a related Stack Overflow Q&A.

Installation is also its own can of worms (more on that later), so since the question didn't ask for it, I think it's better to leave out of the answer post to avoid an super long post and scope creep. Again, see the dedicated chapter in the Mastering CMake book. One thing to especially watch out for with installation is making sure you make the install package relocatable.
In terms of a very very simple project, that's all you need, although of course, there can be much more configuration to do based on your project's specific needs, but you can burn yourself on those bridges when you get there.
Compile options / flags is also its own can of worms and better covered in separate Q&A posts.
If you want to start using dependencies, I suggest reading the official "Using Dependencies" guide.
If you really have a lot of source files, and your myProject/src/module1/CMakeLists.txt file starts to get unwieldy because of all the lines of add_executable/add_library, then you can factor that out into a separate file using target_sources() and either another CmakeLists.txt file in a subdirectory included via add_subdirectory, or a sources.cmake file in the same subdirectory included via include().
To generate the buildsystem as shown in your directory tree diagram, change your current directory to .../myProject and then run cmake -S . -B build <...>, where <...> is any other configuration arguments you want to use.
As always, the CMake reference docs can be quite helpful, but overwhelming to look at the first couple of times, since they're not meant for beginners to learn from. If you want to learn more about how to use CMake, try out the official CMake tutorial, and reading relevant chapters in the Mastering CMake book. If you really want to dive deep, check out "Professional CMake"- written by Craig Scott (one of the CMake maintainers). It costs money, but having read the sample chapter, the table of contents, and other blog posts and proposals on the CMake GitLab by Craig, I have faith in its value, and new editions to the book don't cost extra.
Tricks for Resource Files

By the way, it is important that my program knows where the resources are. I would like to know the recommended way of managing resources. I do not want to access my resources with "../resources/file.png"

This response is written assuming you chose CMake to use it for all it's worth- cross-platform, flexible-toolchain builds, which not everybody uses CMake for (which is fine).
This is its own can of worms. One tricky part is the filesystem placement compared between the build folder and the install folder. The build folder is where the binaries and other ingredients like object files get built, and the install folder is anywhere you install those built binaries to. They can have very different filesystem structures, where the build folder layout is up to CMake, and it does sensible things by default, but the layout of things in the install folder is largely up to how you want it to be configured. That can be different than what CMake does in the build folder, and you'll probably want to be able to run and test your binaries from both the build folder and the install folder. So you need to find a way to support your binaries finding your resource files in both where they are at "development time" (when you're running from the build folder), and after installation (when you or your users are running the installed binaries).
There are also various different conventions on different platforms for where to place resource files for installation. There's a convention defined by the GNU Coding Standards, which CMake has a bit of integration with / support for, but of course, Microsoft Windows has another thing with \Program Files\ and \Users\...\AppData\, and MacOS has another thing with app bundles and /library/Application Support/. Things might not be as simple as you thought they were. But I don't know a lot about this (and I could be wrong), but it seems to me that this is big enough of a topic to have its own question, or several of its own questions here on Stack Overflow.
For other related CMake bits, see:

*

*The RESOURCE target property (for macOS and iOS)

*How to use Resource Files (.rc) in CMake?
For examples of shortcomings with simple/naive approaches, the answer by sgvd works for the build directory, but will not work wherever the project is installed to, and even if it's made to somehow work on the builder's machine, the fact that it uses an absolute path makes it unlikely to work when distributed to other machines or platforms with different conventions.
If you're using CMake but only want to support a specific platform, then consider yourself lucky and find or write a question here on Stack Overflow about how to do that.
See also this related question (which at the time of this writing still has no answers): How to specify asset paths that work across builds.
Send-off

Welcome to the world of CMake! Just wait 'till you get to generator expressions! Then you'll really start having fun :D

A: After some research, I have now my own version of the most simple but complete CMake example. Here it is, and it tries to cover most of the basics, including resources and packaging.
One thing it does non-standard is resource handling. By default CMake wants to put them in /usr/share/, /usr/local/share/ and something equivalent on Windows. I wanted to have a simple zip/tar.gz file that you can extract anywhere and run. Therefore resources are loaded relative to the executable.
The basic rule to understand CMake commands is the following syntax:
<function-name>(<arg1> [<arg2> ...]) without comma or semicolon. Each argument is a string. foobar(3.0) and foobar("3.0") is the same. You can set lists/variables with set(args arg1 arg2). With this variable set foobar(${args})  and foobar(arg1 arg2) are effectively the same. A nonexistent variable is equivalent to an empty list. A list is internally just a string with semicolons to separate the elements. Therefore a list with just one element is by definition just that element, no boxing takes place.
Variables are global. Built-in functions offer some form of named arguments by the fact that they expect some ids, like PUBLIC or DESTINATION, in their argument list, to group the arguments. But that's not a language feature; those ids are also just strings, and parsed by the function implementation.
You can clone everything from GitHub.
cmake_minimum_required(VERSION 3.0)
project(example_project)

###############################################################################
## file globbing ##############################################################
###############################################################################

# these instructions search the directory tree when CMake is
# invoked and put all files that match the pattern in the variables
# `sources` and `data`
file(GLOB_RECURSE sources      src/main/*.cpp src/main/*.h)
file(GLOB_RECURSE sources_test src/test/*.cpp)
file(GLOB_RECURSE data resources/*)
# you can use set(sources src/main.cpp) etc if you don't want to
# use globbing to find files automatically

###############################################################################
## target definitions #########################################################
###############################################################################

# add the data to the target, so it becomes visible in some IDE
add_executable(example ${sources} ${data})

# just for example add some compiler flags
target_compile_options(example PUBLIC -std=c++1y -Wall -Wfloat-conversion)

# this lets me include files relative to the root source directory with a <> pair
target_include_directories(example PUBLIC src/main)

# this copies all resource files in the build directory
# we need this, because we want to work with paths relative to the executable
file(COPY ${data} DESTINATION resources)

###############################################################################
## dependencies ###############################################################
###############################################################################

# this defines the variables Boost_LIBRARIES that contain all library names
# that we need to link to
find_package(Boost 1.36.0 COMPONENTS filesystem system REQUIRED)

target_link_libraries(example PUBLIC
  ${Boost_LIBRARIES}
  # here you can add any library dependencies
)

###############################################################################
## testing ####################################################################
###############################################################################

# this is for our testing framework
# we don't add REQUIRED because it's just for testing
find_package(GTest)

if(GTEST_FOUND)
  add_executable(unit_tests ${sources_test} ${sources})

  # we add this define to prevent collision with the main
  # this might be better solved by not adding the source with the main to the
  # testing target
  target_compile_definitions(unit_tests PUBLIC UNIT_TESTS)

  # this allows us to use our executable as a link library
  # therefore we can inherit all compiler options and library dependencies
  set_target_properties(example PROPERTIES ENABLE_EXPORTS on)

  target_link_libraries(unit_tests PUBLIC
    ${GTEST_BOTH_LIBRARIES}
    example
  )

  target_include_directories(unit_tests PUBLIC
    ${GTEST_INCLUDE_DIRS} # doesn't do anything on Linux
  )
endif()

###############################################################################
## packaging ##################################################################
###############################################################################

# all install commands get the same destination. this allows us to use paths
# relative to the executable.
install(TARGETS example DESTINATION example_destination)
# this is basically a repeat of the file copy instruction that copies the
# resources in the build directory, but here we tell CMake that we want it
# in the package
install(DIRECTORY resources DESTINATION example_destination)

# now comes everything we need, to create a package
# there are a lot more variables you can set, and some
# you need to set for some package types, but we want to
# be minimal here
set(CPACK_PACKAGE_NAME "MyExample")
set(CPACK_PACKAGE_VERSION "1.0.0")

# we don't want to split our program up into several things
set(CPACK_MONOLITHIC_INSTALL 1)

# This must be last
include(CPack)

Note: While the above usage of file(GLOB) is appropriate here, where the question specifically asks for a technique to minimize the frequency of edits to CMakeLists.txt files with the addition of new source files, this technique is discouraged in the official documentation, and in the answers to these dedicated questions: #1, #2.


text:
Q: Event for input type=number I am a bit new to Angularjs. In Chrome, for number type input fields, pressing on up and down key arrow increases/decreases the entered value. It needs to be disabled. Any ideas or help in how it can be done?
I tried using jQuery: $(":input").bind('keyup mouseup', function () but the ng-model binding is not updating. Might be because the angular js doesn't recognize the change made with jQuery.

A: If you need to disable it permanently better do it another way, use regular text input but restrict other chars than numbers.
<input type="text" ng-pattern="/^[0-9]*$/" />

Check out ngPattern docs

A: You can use ng-model directive to access the value of input in controller, and ng-disabled directive to control an input state. Hopefully the following demo may be of some help:

var app = angular.module('demo', []);

app.controller('DemoCtrl', function($scope) {
  $scope.myNumber = 0;
  $scope.isDisabled = false;
  $scope.toggle = function() {
    $scope.isDisabled = !$scope.isDisabled;
  };
});

    <input type="number" ng-model="myNumber" ng-disabled="isDisabled"/>
    <button ng-click="toggle()">Disable/Enable</button>

A: Model won't change inside jquery event.Use ng-keypress event in angularjs

redpajama_set_name: RedPajamaStackExchange


text:
Q: When I query a partitioned table, is it possible to filter by partition column with a subquery and reduce cost at the same time? I can see from public documentation that BigQuery partition table has this limitation that if the partition column has a subquery as a filter, it won't prune the queried partition and reduce "bytes processed"(cost). I'm wondering if there is a way to workaround.
For example, this query will scan 38.67 GB, is there a way to reduce it?
WITH sub_query_that_generates_filter AS (
  SELECT DATE "2016-10-01" as month UNION ALL
  SELECT "2017-10-01" UNION ALL
  SELECT "2018-10-01"
)
SELECT block_hash, fee FROM `bigquery-public-data.crypto_bitcoin.transactions`
WHERE block_timestamp_month in
(SELECT month FROM sub_query_that_generates_filter)

A: With BigQuery scripting, there is a way to reduce the cost.
Basically, a scripting variable is defined to capture the dynamic part of a subquery. Then in subsequent query, scripting variable is used as a filter to prune the partitions to be scanned.
CREATE TEMP TABLE sub_query_that_generates_filter AS (
  SELECT DATE "2017-10-01" as month UNION ALL
  SELECT "2018-10-01" UNION ALL
  SELECT "2016-10-01"
);
BEGIN
  DECLARE month_filter ARRAY<DATE>
    DEFAULT (SELECT ARRAY_AGG(month) FROM sub_query_that_generates_filter);

  SELECT block_hash, fee FROM `bigquery-public-data.crypto_bitcoin.transactions`
    WHERE block_timestamp_month in UNNEST(month_filter);
END

It scans only 2GB of data instead of 38GB. Cheaper and faster!


text:
Q: Error message when running Rake command in Rails app I'm trying to create posts in my Rails app by pulling data from a CSV file.
When I try to run a Rake command, I get the error message below. What's wrong with this code?
SEED.RAKE FILE
require 'csv'

namespace :csv do

  desc "Import CSV Data for Michelin Star Restaurants"
  task :post => :environment do

    csv_file_path = 'db/data.csv'

    CSV.foreach(csv_file_path) do |row|
        Post.create({
          :name => row[1],
          :address => row[2],
          :city => row[3],
          :michelin_status => row[4],
          :website => row[5],
          :phone => row[6],
          :longitude => row[7],
          :latitude => row[8],
          :inthenews => row[9],
          :google_reviews => row[10],
        })
      end
    end
  end

ERROR MESSAGE FROM CONSOLE
Faisals-Air:dinner fkhalid2008$ rake csv:post
rake aborted!
ArgumentError: invalid byte sequence in UTF-8
/Users/fkhalid2008/dinner/lib/tasks/seed.rake:11:in `block (2 levels) in <top (required)>'
/Users/fkhalid2008/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `eval'
/Users/fkhalid2008/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => csv:post
(See full trace by running task with --trace)

DB MIGRATE FILE
class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :name
      t.string :inthenews
      t.string :michelin_status
      t.string :google_reviews
      t.string :address
      t.string :city
      t.string :website
      t.integer :phone
      t.integer :longitude
      t.integer :latitude

      t.timestamps null: false
    end
  end
end

CSV FILE SCREENSHOT

A: This is because somewhere in your file there are some invalid bytes.
To avoid this issue, you can use scrub method like this:
CSV.foreach(csv_file_path) do |row|
  Post.create({
                  :name => row[1].scrub,
                  :address => row[2].scrub,
                  :city => row[3].scrub,
                  :michelin_status => row[4].scrub,
                  :website => row[5].scrub,
                  :phone => row[6].scrub,
                  :longitude => row[7].scrub,
                  :latitude => row[8].scrub,
                  :inthenews => row[9].scrub,
                  :google_reviews => row[10].scrub,
              })
end

Update
Try to specify the encoding type when you read the CSV file like this:
CSV.foreach(csv_file_path, "r:ISO-8859-1") do |row|
 . . .
 . . .
end

A: You can simply convert the original csv file to utf8 with nkf.
$ nkf -w --overwrite db/data.csv


text:
Q: How to get the link to the file after uploading to Google Drive via api? I am following this guide. I am able to upload images to my google drive but I am not able to get the path to the file.
https://gist.github.com/ivanvermeyen/cc7c59c185daad9d4e7cb8c661d7b89b
// Get img that was uploaded to my server
$img = request()->file('img');

// Save that image to my google drive
Storage::disk('google')->put('img.png', fopen($img, 'r+'));

// ?? how do I get the path to the file so I can save it in my database?

A: Have you looked it up in the laravel documentation?
https://laravel.com/docs/5.5/filesystem#file-urls
For your code you should use this:
use Illuminate\Support\Facades\Storage;

$url = Storage::disk('google')->url('img.png');

dd($url);


text:
Q: get_object_or_404 while using multi-table(?) Inheritance in Django Currently working on Django 1.6, MySQL and South:
I recently starting working with inheritance and Django models.
Wondering if anyone has run into an issue where running get_object_or_404 from django.shortcuts yields 404 with the message no matches found, but writing the query normally using model.objects.get(pk=###) will yield a single answer.
I want to emphasize that the model we are inheriting is not an abstract model.
Using the code below as a sample:
from django.shortcuts import get_object_or_404

Car(models.Model):
    name = models.CharField(null=True, blank=True, default=None,)
    trunk_size = models.IntegerField(default=0)
    fleet_leader = models.ForeignKey("Car", related_name='car_fleet', null=True, default=None)
    class Meta:
        verbose_name = "Car"
        verbose_name_plural = "Cars"

Bigcar(Car):
    extra_storage_size = models.IntegerField(default=0)
    class Meta:
        verbose_name = "Car"
        verbose_name_plural = "Cars"

So if I make the query:
get_object_or_404(Car, pk=123)

Assuming that the Car data entry with row or primary key 123 exists, I would not get any results, however the entry
Car.objects.get(pk=123)

Would yield a result.
So I'm wondering if anyone knows what's going on with these queries? Am I missing some setting or code that I should implement following the inheritance being used? I've looked into the Django documentation and most of the emphasis is on abstract model inheritance usage.


text:
Q: Prestashop: Pass data from js file to controller to custom page I'm having difficulty passing the value from my personal js to the controller and recovering it on the personal tpl page.
This module will serve to customize product after some selections and fields to fill out.
The selections pass from tabs to tabs.
The problem is that I can't get the value {$ var}
I have:

*

*JS in root->modules->modulename->views->js->namejsfile.js

*CONTROLLER in root->modules->modulename->controllers->front->controllername.php

*VIEW in root->modules->modulename->views->templates->front->filename.tpl

in JS
$('#send').click(function(){
            var ciao = 'cioaa';
            var myUrl = prestashop.urls.base_url + 'index.php?fc=module&module=configuratore';
            $.ajax({
                type: 'get',
                cache:false,
                url: myUrl,
                data: {
                    ajax: true,
                    datas:ciao,
                    action: 'fromAjax',
                },
          })
          .done(function() {
            console.log('Success!');
          })
          .fail(function() {
            console.log('error');
          });
});

in PHP
class ConfiguratoreTaskModuleFrontController extends ModuleFrontController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function init()
    {
        parent::init();
    }

    public function initContent()
    {

        parent::initContent();
        $this->setTemplate('module:configuratore/views/templates/front/task.tpl');
    }
    $this->fromAjax();
}

public function fromAjax()
{
    $mVar = Tools::getValue('datas');
    return   $this->context->smarty->assign(array('var'=>$mVar));
}

in TPL
{$var}

A: <?

public function fromAjax()
{
    $mVar = Tools::getValue('datas');
    $this->context->smarty->assign(array('var'=>$mVar));
    $templateFile = 'module:configuratore/views/templates/front/task.tpl';
    $html = $this->fetch($templateFile);
    die($html); // pass to JS
}

in JS:
.done(function(html) {
        console.log(html);
      })


text:
Q: Filter dataframe in Shiny I have two filters that are used to filter a dataframe (interactively).

*

*When the first filter has a value and the second filter is empty, the dataframe is filtered based on the first filter.

*When the second filter has a value and the first filter is empty, the dataframe is filtered based on the second value.

*When the first and second filters have values, the dataframe is filtered based on the two values.

The last condition is the one that is currently not working.
Here is the code of the main app.R script :
## app.R ##
library(shiny)
library(shinydashboard)
library(DT)
library(writexl)

Mesure <- c('Mesure 1', 'Mesure 2', 'Mesure 3')
Media <- c('TV', 'Radio', 'PQ')
Variable <- c(1,2,3)
postTestsData <- data.frame(Mesure, Media, Variable)

if(interactive()){

    shinyApp(

    ui <- dashboardPage(
      dashboardHeader(
        title = "Aless' Data"
      ),

      dashboardSidebar(
        sidebarMenu(
          menuItem("Database", tabName = "database", icon = icon("fas fa-database")),
          menuItem("Post-tests", tabName = "posttests", icon = icon("fas fa-vial"), menuSubItem('Table of data', tabName = 'datapost'), menuSubItem('Graphs', tabName = 'graphspost'))
        )
      ),

      dashboardBody(
        tabItems(
          tabItem(
            tabName = "database",
            fluidRow(
              box(
                title = "Télécharger la base de données", downloadButton("dl", "Télécharger"), solidHeader = TRUE, status = 'primary'
              ),
              box(
                title = "Filtrer la base de données",
                selectInput(
                  "variable", "Variables : ", choices = namesCol
                  , multiple = TRUE
                ), solidHeader = TRUE, status = 'primary'
              )
            ),
            fluidRow(
              box(
                dataTableOutput("data"), width = 100
              )
            )
          ),
          tabItem(
            tabName = "datapost",
            fluidPage(
              box(
                title = "Filtrer les mesures",
                selectInput("mesures", "Mesures : ", choices = namesMesure, multiple = TRUE),
                solidHeader = TRUE,
                status = 'primary'
              ),
              box(
                title = "Filtrer les médias",
                selectInput("medias", "Média : ", choices = namesMedia, multiple = TRUE),
                solidHeader = TRUE,
                status = 'primary'
              )
            ),
            fluidRow(
              box(
                dataTableOutput("posttestsdata"), width = 100
              )
            )
          ),
          tabItem(
            tabName = "graphspost",
            fluidRow(
              box(
                title = "Filter les mesures"
              )
            )
          )
        )
      )
    ),

    server <- function(input, output) {

        # Filter the post tests table
        observeEvent(input$medias,{
          vals$mesures=FALSE
          vals$medias=TRUE
        })

        observeEvent(input$mesures,{
          vals$mesures=TRUE
          vals$medias=FALSE
        })

        posttestsdata <- eventReactive(c(vals$mesures, vals$medias, input$mesures, input$medias),{
          if(vals$mesures == TRUE){
            str(vals$mesures)
            tempData <- subset(postTestsData, Mesure %in% as.character(input$mesures))
            print('step 1')
          }
          else if (vals$medias == TRUE){
            str(vals$medias)
            tempData <- subset(postTestsData, Media %in% as.character(input$medias))
            print('step 2')
          }
          else if((vals$mesures == TRUE) & (vals$medias == TRUE)) {
            tempData <- filter(postTestsData, (Media %in% as.character(input$medias)) & (Mesure == input$mesures))
            print('step 3')
          }

          return(tempData)

        })

        output$posttestsdata <- renderDataTable({
          posttestsdata()
        })

        # Select the column of the database that the user wants to see
        output$data <- DT::renderDataTable(
          data[, c("ID", input$variable), drop = FALSE],
          options = list(scrollX = TRUE),
          filter = 'top',
          rownames = FALSE
        )

        # Download database
        output$dl <- downloadHandler(
          filename = function() {"test.xlsx"},
          content = function(file) {write_xlsx(data, path = file)}
        )
      }
    )
  }

A: It might simply be down to this line:
filter(postTestsData, (Media %in% as.character(input$medias)) & (Mesure == input$mesures)

Are you trying to use the dplyr::filter? If so you can simply give the column name and the variable you want to filter on, something like this:
dplyr::filter(postTestsData, Media == !!input$medias, Mesure == !!input$mesures)

As an additional note, I don't think you really need the reactiveValues for the true/false flags as you can usually check whether an input is set via is.null.
Hope this helps.


text:
Q: How do you recursively sort a deeply nested array of objects and return the result - javascript I'm recursively sorting a deeply nested array of objects by a deeply nested obj that is keyed by id.
This function works but when I console.log while invoking the function the result is undefined.
The unsorted array of objects passed as an argument does get sorted if I console.log it before and after the call to this function, but that is not being returned from the function call - it is a mutation, which I'm looking to avoid.
A couple of things I've tried:

*

*Instead of the initial call to .map(), using .reduce(), and
adding an empty array as the accumulator, which allows the function
to return but it does not sort :/

*Returning the array I'm calling .map() on at the very end works -
but this seems like a hack, and it also encloses the result in an
array.
    I've tried carefully placing returns in different places - but what usually results is [undefined], or arrays of arrays that
contain undefined
  function sortDeepNestedArray(unsortedArray, sortedObj){unsortedArray.map((obj) => {
    const children = obj.Children;
    const Id = obj.Id
    if (children && children.every(o => !o.Children)) {
      Object.keys(sortedObj).map(key => {
        if (Id === key) {
          return children.sort((a, b) => {
            a = sortedObj[key].Children[a.Id]
            b = sortedObj[key].Children[b.Id]
            return a - b
          });
        }
      });
    }

    Object.keys(sortedObj).map(key => {
      const isNotBaseCase = children &&
      children.every(o => o.Children) &&
      Id === key &&
      sortedObj[key] &&
      sortedObj[key].Children

      if (isNotBaseCase) {
        sortDeepNestedArray(children, sortedObj[key].Children);
      }
    });
  });
}


text:
Q: How to remove the numbers of the chapter and the section/subsection before their names? I used the titlesec package like this:
\documentclass{report}
\usepackage{titlesec}

\titleformat{\chapter}{\normalfont\huge}{\thechapter.}{20pt}{\huge\it}

\begin{document}

\chapter{Name of Chapter}
\section{Name of Section}
\subsection{Subsection}

\end{document}

How I can remove tHe number before the chapter name? and how I can put the chapter's name in the center of the line? Also I want to make sections and subsections without numbers.
What I want is:
Name of Chapter
Name of Section
Subsection
without any numbers.

A: To have chapters, sections, etc., without numbers put:
\setcounter{secnumdepth}{-1}

in your preamble.
(To have chapters and above numbered use \setcounter{secnumdepth}{0} and to have sections and above numbered \setcounter{secnumdepth}{1} and so forth.)

A: Add \centering into the format parameter of \titleformat.
To omit numbering just add star to the chapter command.
\documentclass{report}
\usepackage{titlesec}

\titleformat{\chapter}{\normalfont\huge\centering}{\thechapter.}{20pt}{\huge\it}

\begin{document}

\chapter*{Name of Chapter}
\section*{Name of Section}
\subsection*{Subsection}

\end{document}

A: You can use this:
\titleformat{\chapter}{\normalfont\huge}{}{0pt}{\filcenter\itshape}

However you might have problems with the  table of contents.


text:
Q: Can I fetch subtasks of a JIRA issue via XMLRPC (and if so, how to do this)? I have an xmlrpc interface running and am able to fetch issues by ID.
For example, the issue as returned by getIssue('PROJECT-701') contains the fields:
affectsVersions .. : [releaseDate,sequence,released,archived,...]
assignee ......... : '...'
components ....... : ...
created .......... : '2011-06-01 16:14:21.217'
customFieldValues  : ...
description ...... : '...'
fixVersions ...... : #()
id ............... : '28602'
key .............. : 'PROJECT-701'
project .......... : 'PROJECT'
reporter ......... : '...'
status ........... : '10032'
summary .......... : '...'
type ............. : '18'
updated .......... : '2011-06-07 12:49:51.363'
votes ............ : '0'

now I need to fetch the issue's subtasks. From the html-browser interface, I know that 3 subtasks with IDs 702, 703,...) are present. I am able to fetch the subtasks (as issues) by their issue ID, if those IDs are known (i.e. a getIssue('PROJECT-703') gives the correct return with subtask as issuetype.
However, how do I get those subtask-ids via xmlrpc from the issue ??
I find no parent-issue-id in the subtask nor any subtask-ids in the parent.
Is this simply missing from the XMLRPC interface (and I need to use SOAP), or is there a clever trick (text or other special search) to get the info?
If possible, I want to stay with and use XMLRPC instead of SOAP, but a definite confirmation that it is NOT possible in XMLRPC would also be helpful, so I won't waste time trying to get an incomplete xml-rpc interface working...
Additional info:
I am talking to a JIRA 3.13.5 and a getServerInfo request returns:
baseUrl .... : ...
buildDate .. : 'Tue Jul 07 00:00:00 CEST 2009'
buildNumber  : '360'
edition .... : 'Enterprise'
serverTime . : '...'
version .... : '3.13.5'

Thanks for any hint.

A: edit: (Sorry misread your question, my answer is for SOAP. With luck the XML-RPC will also have this method).
Unfortunately I'm using version 4.2, so I don't know if this method is available for your version; a quick search of the 3.x documentation suggests it might be.
The only way I've been able to get the substasks for an issue is by using the getIssuesFromJqlSearch method:
$jira.getIssuesFromJqlSearch($token, 'parent = "PROJECT-703"', 100)
This returns all the subtasks for PROJECT-703


text: Q: How to create an instance of Element/VariableElement/TypeElement in Java Is there any way to create an instance of the VariableElement without resorting to manually overriding all the methods, but rather via some standard library utility class?


text:
Q: What is the value of segment registers in 8086? I have just started to read about intel 8086 and have a question concerning its memory.
I read that the address bus is 20-bit wide, which means the address space is 1MB, and this space is divided into segments.
the question is:

*

*the four segment registers, CS, DS, SS and ES, are they read only or I can set their values, and which are their default values?

*I saw the following assembly tutorial:
ORG 100h
MOV AX, 0B800h ; set AX = B800h (VGA memory).
MOV DS, AX ; copy value of AX to DS.
MOV CL, 'A' ; CL = 41h (ASCII code).
MOV CH, 01011111b ; CL = color attribute.
MOV BX, 15Eh ; BX = position on screen.
MOV [BX], CX ; w.[0B800h:015Eh] = CX.
RET

Concerning the first line, does that mean this code will exist in address 0x100 in code segment space or in the whole address space
and the line:
MOV [BX], CX

Does that mean every time I reference an address in the MOV instruction, the address should be estimated from the start address of the data segment? (as he wrote that the destination is the value + the value in the data segment reg)

A: First, I feel compelled to point out that you appear to be talking here about 8086 "real mode" addressing, which is a very old way of doing things which almost nothing uses anymore.  Pretty much all modern operating systems operate in "protected mode", which supports many enhancements (such as flat 32- and 64-bit memory space addressing, virtual memory, etc.) which changes how all of this works substantially.
As far as I know, most operating systems nowadays don't even have any way to run code such as this (in real mode) anymore, so if you're interested in learning assembly for the purposes of programming modern PCs, you might want to find some more recent sources to learn from.
That having been said, assuming you do have some reason to want to do this (such as working with certain embedded processors), or are just curious for historical purposes:

*

*Yes, the 8086 real-mode segment registers can be modified.  The instructions and options for doing this are a bit more limited than modifying the more general-purpose registers (for example, there's no instruction to just load a value directly into a segment register, which is why in the code you quoted, the value is first loaded into AX, and then AX is loaded into DS), and can also vary depending on which segment register you're working with.
In general, you would never want to modify CS (the "code segment") register directly, as that would result in immediately changing what code the processor is running (probably in a way you really don't want).  The usual way to modify CS is with a "long jump" or "long call" instruction, which will update both CS and IP (the instruction pointer) at the same time.  Likewise, SS (the "stack segment") is usually set at the beginning of program execution and never changed (but it technically could be if you had some really compelling reason to do so).
DS and ES are general-purpose data segment registers and it was fairly common for programs to change these however they wanted to best access the memory they wanted to work with (as your example code above demonstrates).
As for the initial values for these registers, those were typically determined by the operating system prior to calling the program's code.  Traditionally, in MS-DOS, there were two ways to write programs, as .COM files or as .EXE files.  (The ORG 100h line in the code above suggests that it was intended to be run as a COM program.)  In the COM case, MS-DOS would initially set all of the segment registers to be the same as CS (that is, they'd all point to wherever DOS had decided to load the program in memory) before invoking the program.  The EXE file format was somewhat more sophisticated, and allowed specifying a separate "data segment", in which case the OS would set DS and ES to point to that segment before starting the program instead.  In EXE programs, DOS would also typically set up a separate stack segment (SS) for them as well.

*The ORG 100h line tells the assembler "assume that the following code will be loaded at address 100h".  In real-mode code, addresses such as this are always relative to CS (so the program could actually be loaded many places in memory, as long as CS is set to the correct value to make the code be at 100h relative to CS).

*Most addresses for data operations (such as MOV) will be calculated relative to DS by default (for some instructions, you can change that by explicitly specifying a different segment to use, but whether and how you can do that depends on the opcode and the way you're using it).  There are, however, a few instructions which are designed to use other segments by default.  In summary, it's really best to read the docs for each opcode you want to know about to determine how it uses which segment registers.

A: Get an intel 8088/86 manual.  this is all explained in there.
yes you can change them, you would have to be able to change them for them to be useful.  The obvious segments are used by default (code for code, data for data), but there are places where you can specify other segments on a data instruction.
The org 0x100 means this code (or data that follows an org directive) starts at address 0x100 within the segment.


text:
Q: Problems upgrading React Native from 0.66.5 to 0.71.0: > Task :app:createBundleReleaseJsAndAssets FAILED I'm facing some problems doing the update of ReactNative from 0.66.5 to 0.71.0. Well, you need to solve some issues that I did little by little but now I am stuck with one related to this Gradle task, that I am not able to solve.
> Task :app:createBundleReleaseJsAndAssets FAILED
Execution optimizations have been disabled for task ':app:createBundleReleaseJsAndAssets' to ensure correctness due to the following reasons:
  - Gradle detected a problem with the following location: '<whatever>/app/build/generated/res/react/release'. Reason: Task ':app:lintVitalAnalyzeRelease' uses this output of task ':app:createBundleReleaseJsAndAssets' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.5.1/userguide/validation_problems.html#implicit_dependency for more details about this problem.

I think the key is in
Reason: Task ':app:lintVitalAnalyzeRelease' uses this output of task ':app:createBundleReleaseJsAndAssets' without declaring an explicit or implicit dependency but I am not being able to find the solution to it.
The fail summary:
* What went wrong:
Execution failed for task ':app:createBundleReleaseJsAndAssets'.

> Process 'command 'node'' finished with non-zero exit value 1

I think it is related to Hermes, seeing the trace:
at com.facebook.react.tasks.BundleHermesCTask.runCommand(BundleHermesCTask.kt:129)
        at com.facebook.react.tasks.BundleHermesCTask.run(BundleHermesCTask.kt:89)

A: For some reason, in our structure of subprojects, we needed to have react-native and react in the root folder as dependencies installed to be able to run all phases of the build correctly.
  ...
  "dependencies": {
    "react": "18.2.0",
    "react-native": "0.71.1"
  }
  ...


text:
Q: Insert link to attached document in Outlook 365 I have a macro that had been working until I updated to Office 365.
I could attach a file or files and create a link in the body so that when the user clicks the link, it opens the attachment. This is very helpful if you have more than one attachment and need to write your email and keep the user in context of what you need to open. Instead of having to write the name of the attachment you can simply add a link (e.g. [ LINK ]) as a shortcut.
This was working in 2013:
Set MyAttachment= item.Attachments.item(i)

MyAttachment.PropertyAccessor.SetProperty "http://schemas.microsoft.com/mapi/proptag/0x3712001E", CStr(AttachRef)

Where AttachRef is the name of the attachment (string).
I then write the link in the email body with the address:
"cid:" & CStr(AttachRef)

And a description (string) the can be seen simply as:
[LINK]

Using:
Set Inspector = Application.ActiveInspector()
Set wdDoc = Inspector.WordEditor wdDoc.Hyperlinks.Add Selection.Range, Address:=iAddress, TextToDisplay:=iTextToDisplay

When you try to open the link, MS Office does not recognize the file and I get:

"Microsoft Office has identified a potential security concern. This location may be unsafe. cid:NAME"


text:
Q: Error "no such element: Unable to locate element" I am on this page
https://login.alibaba.com/?spm=a2700.8293689.0.0.NdeZUw&tracelog=hd_signin
And trying to access Email field by following web element code:
public static WebElement Email_Field(WebDriver driver) throws InterruptedException {

        //element = (new WebDriverWait(driver, 10)).until(ExpectedConditions
                //.visibilityOfElementLocated(By.xpath("//input[@id='fm-login-id']")));

        element = driver.findElement(By
                .xpath("//input[@id='fm-login-id']"));

        while (!isDisplayed(element)) {
            Thread.sleep(3000);
            System.out.println("Element is not visible yet");
        }

        return element;
    }

public static boolean isDisplayed(WebElement element) {
        try {
            if(element.isDisplayed())
                return element.isDisplayed();
            }catch (NoSuchElementException ex) {
            return false;
        }
        return false;
    }

But getting the following exception:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='fm-login-id']"}
  (Session info: chrome=59.0.3071.115)

A: The email field is inside the frame. Before access any element in the frame, you have to switch. please try following code.
public static WebElement Email_Field(WebDriver driver) throws InterruptedException {

    WebElement element;

    (new WebDriverWait(driver, 30)).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("alibaba-login-box"));

    element = driver.findElement(By.xpath("//input[@id='fm-login-id']"));

    while (!isDisplayed(element)) {
        Thread.sleep(3000);
        System.out.println("Element is not visible yet");
    }

    return element;
}


text:
Q: whl file installation using command prompt I'm using IDLE(3.6.0) 32 bit and I've tried installing some packages using
pip install pocketsphinx-0.1.3-cp35-cp35m-win32.whl

but i keep on getting an error saying:

pocketsphinx-0.1.3-cp35-cp35m-win32.whl is not a supported wheel on this platform.

Am I installing the right file?

A: You're using Python 3.6.0 and trying to install a wheel for Python 3.5. Synchronise versions — either use Python 3.5 or download a wheel for Python 3.6.


text:
Q: How to define an optional entry point into custom Mac OS X framework / dynamic library? In Windows there is a DllMain and DLL_PROCESS_ATTACH / DLL_PROCESS_DETACH flags, which allow to initialize / free resources after DLL is attached to a process... So how can I specify an entry point in case of OS X? As always, I can't find anything useful in Apple documentation :(

A: The Dynamic Library Programming Topics document on Apple's Web site shows the use of
__attribute__((constructor))

and
__attribute__((destructor))

to implement initialisers and finalizers in dynamic libraries.

A: Wouldn't that work?
__attribute__((constructor)) void DllMain()
{
  // code
}

A: I think malkia (upvoted) and Bavarious have the right answer, but since I already looked it up: One way to do this is to set your init routine. Look for the "Initialization Routine" in your Xcode build settings for your library. Prefix the function name with an underscore. I.e. if your init routine is called DllMain, enter "_DllMain".
Also, I have previously done some initialization using obj-c++ doing something like this:
class LibraryInit
{
    public LibraryInit()
    {
        // do some init stuff here
    }
} ;
static LibraryInit sLibraryInit();

A: My main application statically links to a static library A with a function ABC and my dynamic library xyz.dylib also statically links to the same static library A which has the same function ABC.
Now when the main application Loads xyz.dylib using dlopen on runtime. The initializer gets called where i have called ABC function. This function ABC is getting called from main application's address space. This is really strange and i do not know, what is going wrong? Though it should have called ABC function from the dylib.


text:
Q: How do I validate a drop down list in Laravel PHP? The Situation:
Under models, I've a user.php which handles all validation regarding adding a user to a website.
This is (part of) the code:
public static $add_rules = array(
   'last_name'             => 'required',
   'first_name'            => 'required',
   'email'                 => 'required|unique:users,email',
   'username'              => 'required|alpha_num|min: 5|unique:users,username',
   'password'              => 'required|min: 4|same:password_confirmation',
   'password_confirmation' => 'required',
   'user_role'             => 'required|not_in:-- Choose User Type --'
);

user_role is the ID of the dropdown list, seen here:
<select name="user_type_id" class="form-control" id="user_role">
<option value="0">-- Choose User Type --</option>
@if(Session::get("user_type") == "superuser")
     {
     @foreach($user_types as $ut)
         <option value="{{$ut['id']}}">
             {{ ucwords($ut["user_type"]) }}
         </option>
     @endforeach
     }
@else{
     <option value="Regular">Regular</option>
}@endif
</select>

Basically, what happens up there is that the drop down list is filled with user types, whatever they are. But it always has the first 'option' of -- Choose User Type --.
The Problem:
Problem is, the user can go with that option and add a user. I have a javascript code that blocks this and outputs an error message in a pop-up window, but it's ugly, and not consistent with the rest of the website's error messages.
So I added it to the rules. It needs to be validated such that it will only accept anything other than the default -- Choose User Type -- option.
What I Tried:
not_in did not work, unfortunately.
Can I get some help on this?
Thanks.

A: You have your select named "user_type_id" but you are trying to validate a field named "user_role"

A: You're not using not_in the right way. You're supposed to pass in the values that are not allowed, not the representation of those values.
'user_role' => 'required|not_in:0'

A: I think this situation calls for using:   Validator::extend()
http://laravel.com/docs/validation#custom-validation-rules
This would probably be a handy gist. Make a rule that validates whatever string the coder provides.


text:
Q: Problems with creating a Yarn lock for nuxt because of a symlink missing? I'm not able to install a project with yarn anymore due to an error I get. It's preventing my local machine to create a lock file. I've been googling for half a day now and I'm getting desperate.
This is the response I get in the terminal:

When I install the project via NPM install and then run command Yarn dev/build/generate everything seems to be working fine.
I'm a total noob with Yarn so please bear with me.


text:
Q: pentaho PDI passing uservariable in command line I am trying to run a Transformation/Job by passing a user variable in command line.
I have tried by passing variable value as below.
sh pan.sh -file='test.ktr' '-param:input_directory=/path/to/directory' -level=basic
where input_directory is variable in transformation and i mentioned it as ${input_directory}
But when I do this, the pan is unable to find the variable value. It is throwing error as below
Could not list the contents of "file:///home/user1/pdi8.1/data-integration8.1/${input_directory}" because it is not a folder.
can someone help me on this. Thank you

A: To pass named parameters to your job or transformation, the parameters need to be defined in the properties window, shown here for a transformation. The default value is not needed, but works well for testing. Pay attention to capitalization.

So the pieces of the puzzle are:

*

*From the command line, pass the parameter like -param:yourparam=yourvalue

*Define this same parameter in the highest-level job or transformation

*Use it as you would use any variable, with ${yourparam}

A: i think the parameter names to be used in job should be ${PARAM_NAME1}
using command line i follow the below convention
call "{Replace with kitchen.bat File Path}" /file:"{Replace with JOB File Path}"  "-param:PARAM_NAME1=PARAM_VALUE1" "-param:PARAM_NAME2=PARAM_VALUE2"


text:
Q: Need to create a function for a casino game I have a Project for my programming class, and its requiring me to set up the main functionality for the casino using functions.
First, I needed to seed the random number generator which I think I did right.
void seedRand(int seed)
{
srand(time(0));
}

Second, was to continue to set up functions. So I set the next one to print out numbers to the second decimal place.
void printMoney(double money)
{
std::cout << std::setprecision(2) << std::fixed;
}

The next one, and the one I'm not understanding, is to have the user pay, and have the casino receive the money.
Sorry if i didn't put enough information, if something is missing please ask. I'm still new to understanding everything. Any help would be appreciated. Thanks.
void payMoney(double & wallet, double amount)
{

}

A:
which I think I did right.

No you didn't, it should rather look like
void seedRand(int seed) {
    srand(seed == 0?time(0):seed);
}

If there's a parameter passed, it's probably meant to be actually used. I've chosen zero as a convention, when seed() should be called with a randomly time based value.

So I set the next one to print out numbers to the second decimal place.

Your second function sets up the output stream state well, but misses to output the value, it should look like
void printMoney(double money) {
    std::cout << std::setprecision(2) << std::fixed << money << std:: endl;
                                                    // ^^^^^
}

And at least your last function is probably supposed to be implemented as
void payMoney(double & wallet, double amount) {
    wallet -= amount;
}

All in all it's hard to answer what you're supposed to do with this task.
But since you tagged this question c++, I'd rather recommend to go putting these functions in context of classes like class Casino and class Player.
class Casino;
class Player {
    double wallet;
public:
    void payMoney(Casino& Casino, double amount);
};

class Casino {
public:
    void addToBank(double money) {
        bank += money;
    }
private:
    double bank;
};

void Player::payMoney(Casino& casino, double amount) {
    wallet -= amount;
    casino.addToBank(amount);
}


text:
Q: CSS flex fill blank I have the following HTML and CSS, on a page I would like to look like a blog page so using flex I would like it to look something like https://calpoint.com/techpipe/2016/06/02/free-divi-blog-extension-gives-the-divi-blog-module-a-brand-new-look/

article {
  width: 100%;
  display: -webkit-flex;
  display: flex;
  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  flex-flow: wrap;
  -webkit-align-content: flex-end;
  align-content: flex-end;
}

article div {
  flex-grow: 1;
  width: 32%;
  padding: 0;
  background-color: whitesmoke;
  float: left;
  margin-bottom: 1%;
  margin-left: 1%;
  overflow: auto;
  border-radius: 25px;
  padding-bottom: 1%;
  text-align: center;
}

1

Proin finibus augue auctor ipsum varius tempus. Nam mollis odio ac mauris pulvinar, sed porta lorem auctor. Sed elit odio, aliquam vitae sollicitudin quis, imperdiet eget nisl. Proin mattis elementum orci, nec consequat augue luctus vel.

2

Proin finibus augue auctor ipsum varius tempus. Nam mollis odio ac mauris pulvinar, sed porta lorem auctor.

3

Proin finibus augue auctor ipsum varius tempus. Nam mollis odio ac mauris pulvinar, sed porta lorem auctor. Sed elit odio, aliquam vitae sollicitudin quis, imperdiet eget nisl. Proin mattis elementum orci, nec consequat augue luctus vel.

4

Proin finibus augue auctor ipsum varius tempus. Nam mollis odio ac mauris pulvinar, sed porta lorem auctor. Sed elit odio, aliquam vitae sollicitudin quis, imperdiet eget nisl. Proin mattis elementum orci, nec consequat augue luctus vel.

5

Proin finibus augue auctor ipsum varius tempus. Nam mollis odio ac mauris pulvinar, sed porta lorem auctor. Sed elit odio, aliquam vitae sollicitudin quis, imperdiet eget nisl. Proin mattis elementum orci, nec consequat augue luctus vel.

6

Proin finibus augue auctor ipsum varius tempus. Nam mollis odio ac mauris pulvinar, sed porta lorem auctor. Sed elit odio, aliquam vitae sollicitudin quis, imperdiet eget nisl. Proin mattis elementum orci, nec consequat augue luctus vel.

My question is how do I line boxes 1,2.3 so they all start at the same height on the page, then move 5 box up to fill the space  in the top row?
Hope this makes sense.
Thanks
Peter


text:
Q: Generating DEM Generation in LPS? I have a Cartosat 2.5 m Imagery and Block files along with DSM Data. I wanted to generate DEM using Leica Photogrammetry Suite Software. Does anyone know the steps of generating same?
I  have to edit the existing DSM by augmenting with more breaklines / masspoints and editing of existing points to the exact ground surface as visualized on the stereo data supplied.
Also is DSM also in black/white color or is there a way to change bands and update the colors?
How can I perform the same on LPS Software?

A: You want to edit DSM (vector format:ltfx, tin.pro) file in 3D stereo environment,
where you can change the color of your mass point, break line and create new to final convert into DEM (DTM).
You can enhance the B/W cartosat image for enhanced clear view.
Any issue in setting up your machine environment, 3D editing and let me know.


text:
Q: How do I give "#ffff" string color to setBackgroundColor() as parameter? I want to give color to relative layout as setBackgroundColor() and the color value is like "#ffffff" and setBackgroundColor() dosent accept string value

A:
You can Use the below code:-

Relativelayout.setBackgroundColor(Color.parseColor("#ffffff"))


text:
Q: Copying data from table without primary key to a table with a pk I have two tables foo and bar in Postgres with the same structure except that bar is empty and has a primary key called id, while foo is populated and has a column called id with unique values (but it does not have a  primary key).
When I attempt to copy data from foo to bar using this command:
INSERT INTO bar
SELECT id, timestamp, updated_at
FROM foo

I get an error:

ERROR:  duplicate key value violates unique constraint "bar_pkey"
DETAIL:  Key (id)=(1) already exists.

How is this error possible when the table bar is compltely empty?  What is the correct procedure in postgres to perform a data copy from one table without a primary key to a table with one?

A: Validate that bar is really empty:
select count(*)
from bar;

If that is not the problem, then foo has duplicates:
select id
from foo
group by id
having count(*) > 1;

There are other arcane possibilities such as misnamed constraints (so the issue isn't really id) or triggers.  However, I am discounting those possibilities.
If you want one arbitrary row per foo, you can use distinct on:
select distinct on (id) id, timestamp, updated_at
from foo
order by id;


text:
Q: How can I send fax using Express.js I found interfax in the npm. But not sure is it that I need. Can someone help me to find a right way for sending faxes using node+express?

A: If you will take a look at source code of the interfax library, you can see that this library is using native node.js module https. You can read more about it here.
So you do not need express at all. Just go ahead with the documentation in the readme file.
But if you want to send fax after some endpoint call, you can do something like this:
const express = require('express');
const app = express();
const InterFAX = require('interfax');

// Initialize using parameters
const interfax = new InterFAX({
  username: '...',
  password: '...'
});

app.get('/sendFax', (req, res) => {
  // Send test file
 interfax.outbound.deliver({
   faxNumber: '+11111111112',
   file: 'folder/fax.txt'
 })
 .then(fax => {
   res.send('Fax sended');
 })
 .catch(error => {
   res.send('Error: ', error);
 });
});

app.listen(3000);


text:
Q: Nativescript 5.0 - displaying react/angular webapp read from local path inside WebView component on Android It is possible to display an react/angular web application on WebView component ?
I build angular(angular cli) and react application in prod mode.
Next, prepared files I put inside ./assets folder.
After changes inside webpack.config.js and run
tns run android --bundle than nothing is shown beside of static texts.
home.component.tns.html
 <GridLayout>
     <WebView src="~/assets/seatmap/index.html"></WebView>
 </GridLayout>

home.component.tns.html
 <!doctype html>

 <meta charset="utf-8">
 <title>t</title>
 <base href="/">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="icon" type="image/x-icon" href="favicon.ico">
 <link rel="stylesheet" href="styles.x.css">

      // not displayed
      // displayed
     <app-root></app-root> // nothing is displayed
     This text is displayed

Javascript files are loaded. There is no problem with path.
When I change src to any external web site (src="http://facebook.com") everything is ok.

A: Duplicate of NativeScript WebView loading local resources in src document
It's known issue with iOS, please refer my answer there which includes possible workarounds.


text:
Q: Why am i getting Error: $injector:unpr Unknown Provider? I am fairly new to angular and i am trying to replace some scope data structure with a factory but the dependency injection is causing an issue. Help please
https://jsfiddle.net/bennacer860/k8js1o4m/1/
angular.module('flapperNews', [])
  .factory('posts', [function() {
    var o = {
      posts: []
    };
    return o;
  }]);

angular.module('flapperNews', [])
  .service('myService', function() { /* ... */ })
  .controller('MyController', ['myService', function(myService) {
    // Do something with myService
    console.log("test");
  }]);

angular.module('flapperNews', [])
  .controller('MainCtrl', ['$scope', 'posts', function($scope, posts) {
    $scope.test = 'Hello world!';
    // $scope.posts = [
    //   {title: 'post 1', upvotes: 5},
    //   {title: 'post 2', upvotes: 2},
    //   {title: 'post 3', upvotes: 15},
    //   {title: 'post 4', upvotes: 9},
    //   {title: 'post 5', upvotes: 4}
    // ];
    $scope.posts = posts.posts;

    $scope.addPost = function() {
      if (!$scope.title || $scope.title === '') {
        return;
      }
      $scope.posts.push({
        title: $scope.title,
        link: $scope.link,
        upvotes: 0
      });
      $scope.title = '';
      $scope.link = '';
    };

    $scope.incrementUpvotes = function(post) {
      post.upvotes += 1;
    };
  }]);

A: Eliminate the [] in each angular.module('flapperNews', []) after the first.
Passing an argument there tells angular to create a new instance of your module and therefore destroys any previous instances.


text:
Q: Unable to read messages from HornetQ queue in springboot application I am trying to setting up consumer with springboot but getting a difficulty. I have seen an example configuration of JMS Consumer setup and did the same but somehow consumer is not setting up properly and on Jconsole Queue is showing 0 consumer. Here is my springboot setup:
@Configuration
@EnableJms
@EnableAutoConfiguration
public class MongoConfiguration {
@Bean
    public ConnectionFactory connectionFactory() {
        final Map<String, Object> properties = new HashMap<>();
        properties.put("host", tcpServerURL);
        properties.put("port", tcpServerPort);
        final org.hornetq.api.core.TransportConfiguration configuration =
                new org.hornetq.api.core.TransportConfiguration("org.hornetq.core.remoting.impl.netty.NettyConnectorFactory", properties);
        return new org.hornetq.jms.client.HornetQJMSConnectionFactory(false, configuration);
    }

    @Bean
    public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
                                                    DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        configurer.configure(factory, connectionFactory);

        return factory;
    }
}

listener with queue destination
  @Component
    public class TrackerJmsListener {
        @JmsListener(destination = "trackerRec",containerFactory = "myFactory")
        public void handleMessage(String message) {//implicit message type conversion
            System.out.println("received: " + message);
        }
    }

Here is a jconsole of local running hornetq Mbean

I am confuse as there is no error showing on console and nothing is reading by consumer. If i change jms port or queue name then after starting of springboot app i see error message on console so my basic configuration seems to be right.
Basic setup of hornetq in server.
hornetq-configuration.xml
<?xml version="1.0"?>
<configuration xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hornetq">
    <connectors>
        <connector name="netty-connector">
            <factory-class>org.hornetq.integration.transports.netty.NettyConnectorFactory
            </factory-class>
        </connector>
    </connectors>
    <acceptors>
        <acceptor name="netty-acceptor">
            <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory
            </factory-class>
        </acceptor>
    </acceptors>
    <security-enabled>false</security-enabled>
</configuration>

hornetq-jms.xml
<?xml version="1.0"?>
<configuration xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hornetq">
    <!--the connection factory used by the example -->
    <connection-factory name="ConnectionFactory">
        <connectors>
            <connector-ref connector-name="netty-connector" />
        </connectors>
        <entries>
            <entry name="ConnectionFactory" />
        </entries>
        <consumer-window-size>0</consumer-window-size>
        <connection-ttl>-1</connection-ttl>
    </connection-factory>
    <queue name="trackerRec">
        <entry name="trackerRec" />
    </queue>
</configuration>

A: Your JConsole screenshot is showing the attributes for the trackerRec core queue. However, that is not the core queue which corresponds with the trackerRec JMS queue which your application will be using. You need to look at the jms.queue.trackerRec core queue or look at the trackerRec JMS queue in the JMS tree.
Also, it's worth noting that the HornetQ code-base was donated to the Apache ActiveMQ project over three years ago now and that code-base lives on as the Apache ActiveMQ Artemis broker. I strongly encourage you to move from HornetQ to ActiveMQ Artemis. There's been a ton of improvements, new features, bug fixes, etc. since the last HornetQ release. Also, since ActiveMQ Artemis 2.0 there is no longer an arbitrary separation between core addresses & queues and JMS queues & topics. The addressing model is more intuitive and powerful.


text:
Q: Generate days in month based on month I'm wondering if anyone has an elegant solution for generating days based on a month selected for use in a dropdown. What i'm wanting to do is for the user to select the month, then populate a dropdown for days for that month. So for example if the user selected january you would have a dropdown list with values 1 - 31. The only bit i think might be tricky will be to do with leap years, so it may need to pass in year as well. Any ideas would be most appreciated :)

A: Enumerable.Range(1, System.DateTime.DaysInMonth(int year, int month));

A: You would need to create cascading dropdowns, where the user selects the year and the month and you generate a third dropdown based on that combination.
But a much easier solution would be to use a jQuery date picker: http://docs.jquery.com/UI/Datepicker
This does the hard work for you!

A: Do this to populate your days dropdownlist:
System.DateTime.DaysInMonth(int year, int month);


text:
Q: C: When to return by value or pass reference Although the subject is discussed many times, I haven't found any satisfying answer so far. When to return data from a function by return or to pass a reference to change the data on address? The classic answer is to pass a variable as reference to a function when it becomes large (to avoid stack copying). This looks true for anything like a structure or array. However returning a pointer from a function is not uncommon. In fact some functions from the C library to the exact thing. For example:
char *strcat(char *dst, const char *src);

Always returns a pointer to destination even in case of an error. In this case we can just use the passed variable and leave the return for what it is (as most do).
When looking at structures I see the same thing happening. I often return pointers when functions only need to be used in variable initialization.
char *p = func(int i, const char *s);

Then there is the argument that stack coping variables is expensive, and so to use pointers instead. But as mentioned here some compilers are able to decide this themselves (assuming this goes for C as well). Is there a general rule, or at least some unwritten convention when to use one or the other? I value performance above design.

A: Start by deciding which approach makes the most sense at the logical level, irrespective of what you think the performance implications might be.  If returning a struct by value most clearly conveys the intent of the code, then do that.
This isn't the 1980s anymore.  Compilers have gotten a lot smarter since then and do a really good job of optimizing code, especially code that's written in a clear, straightforward manner.  Similarly, parameter passing and value return conventions have become fairly sophisticated as well.  The simplistic stack-based model doesn't really reflect the reality of modern hardware.
If the resulting application doesn't meet your performance criteria, then run it through a profiler to find the bottlenecks.  If it turns out that returning that struct by value is causing a problem, then you can experiment with passing by reference to the function.
Unless you're working in a highly constrained, embedded environment, you really don't have to count every byte and CPU cycle.  You don't want to be needlessly wasteful, but by that same token you don't want to obsess over how things work at the low level unless a) you have really strict performance requirements and b) you are intimately familiar with the details of your particular platform (meaning that you not only know your platform's function calling conventions inside and out, you know how your compiler uses those conventions as well).  Otherwise, you're just guessing.  Let the compiler do the hard work for you.  That's what it's there for.

A: Rules of thumb:

*

*If sizeof(return type) is bigger than sizeof(int), you should probably pass it by pointer to avoid the copy overhead. This is a performance issue. There's some penalty for dereferencing the pointer, so there are some exceptions to this rule.

*If the return type is complex (containing pointer members), pass it by pointer. Copying the local return value to the stack will not copy dynamic memory, for example.

*If you want the function to allocate the memory, it should return a pointer to the newly allocated memory. It's called the factory design pattern.

*If you have more than one thing you want to return from a function - return one by value, and pass the rest by pointers.

*If you have a complex/big data type which is both input and output, pass it by pointer.


text:
Q: Model: Apply condition on join statements I want to add some conditions on a model's join.
this is what I tried and nothing changed on the result:
    Members::find('all', [
        'fields' => ['name', 'Count(Orders.id)'],
        'with' => 'Orders',
        // 'joins' => [
        //  'Orders' => 'Orders.status = delivered'
        // ]
    ]);

this is my working example query:
SELECT name, COUNT(orders.id) FROM members
LEFT JOIN orders ON orders.member_id = members.id AND orders.status = 'delivered'
GROUP BY member_id

Edit:
I also tried this approach based on this answer
$joins = array();
$joins[] = new \lithium\data\model\Query(array(
     'source' => 'orders',
     'type' => 'LEFT',
     'constraint' => array('Orders.status' => 'delivered'),
));

Members::find('all', [
    'fields' => ['name', 'Count(Orders.id)'],
    'with' => 'Orders',
    'joins' => $joins
]);

but the created query doesn't contain defined joins parameters ('Orders.status' => 'delivered')

A: What you are trying to do is conceptually wrong. Please try to put the status = 'delivered' in the where clause of the query. For more info, read below:
Although the query you are writing makes sense when read, and (might) yield the same results, you are mixing the join clause and the where clause.

*

*Join clause should contain conditions that are required to "join" two records together (i.e. same name, same first_name and last_name, same make and model, etc.)

*Where clause should contain conditions that are necessary to return only those records that satisfy the conditions. These records can be from a single table (usually) or from multiple tables (in case of joins).


text:
Q: OpenCV - findContours on generated image doesn't work I have an image of a graph. I perform some preprocessing functions on the image in order to extract the graph line (which works). I then, however, try to find the contour of the graph line that is found and saved as a separate image. When I do this, however, I do not get the desired results.
Graph line extracted
Contour found of the above image
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread("/Users/2020shatgiskessell/Desktop/graph_extracting/Test_Graphs/Graph2.jpg")
h,w = img.shape[:2]
mask = np.zeros((h,w), np.uint8)
mask2 = mask = np.zeros((h,w), np.uint8)

def find_contours(image):
    # Transform to gray colorspace and threshold the image
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

    # erod then dialate image (for denoising)
    kernel = np.ones((2,2),np.uint8)
    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)

    #Find contours in order of hiarchy
    #CHAIN_APPROX_NONE gives all the points on the contour
    _, contours, hierarchy = cv2.findContours(opening,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    return contours

#---------------------------------------------------------------
#CLEAN UP IMAGE AND JUST EXTRACT LINE
#get the biggest contour
cnt = max(find_contours(img), key=cv2.contourArea)
cv2.drawContours(mask, [cnt], 0, 255, -1)

# Perform a bitwise operation

res = cv2.bitwise_and(img, img, mask=mask)

# Threshold the image again
gray = cv2.cvtColor(res,cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# Find all non white pixels of image
non_zero = cv2.findNonZero(thresh)

# Transform all other pixels in non_white to white
for i in range(0, len(non_zero)):
    first_x = non_zero[i][0][0]
    first_y = non_zero[i][0][1]
    first = res[first_y, first_x]
    res[first_y, first_x] = 255

# Display the image
cv2.imwrite("extractedline.png", res)
#-------------------------------------------------------
#GET CONTOUR OF EXTRACTED LINE - NOT WORKING
i = 0
#Display contours
for contour in find_contours(res):
    #approximate the contour shape
    cv2.drawContours(mask2, [contour], 0, 255, -1)
    res2 = cv2.bitwise_and(res,res,mask=mask2)
    i = i+1
    print (i)

cv2.imshow('after', mask2)


text:
Q: Debugging Android project in Eclipse suddenly doesn't work anymore I am developing on Windows machine.
I was working quite well until yesterday, when I saw the the update prompt and updated my ADT plugin.
Today when I tried debugging my test project, I experienced either one the following cases:
1) Logcat stops forever on the message "sending wait chunk".
The console reads:
[2010-08-15 19:05:58 - TestProject] Project dependency found, installing: Project
[2010-08-15 19:05:58 - Project] Uploading Project.apk onto device 'emulator-5554'
[2010-08-15 19:05:58 - Project] Installing Project.apk...
[2010-08-15 19:06:08 - Project] Success!
[2010-08-15 19:06:08 - ProjectTest] Launching instrumentation  android.test.InstrumentationTestRunner on device emulator-5554
[2010-08-15 19:06:08 - ProjectTest] Collecting test information
[2010-08-15 19:06:14 - ProjectTest] Sending test information to Eclipse
[2010-08-15 19:06:14 - ProjectTest] Running tests...

And Logcat reads:
D/ActivityManager(   84): Uninstalling process com.mat.project
I/ActivityManager(   84): Start proc com.mat.project for added application com.mat.project: pid=341 uid=10029 gids={3003, 1015}
I/System.out(  341): Sending WAIT chunk

I have to terminate the AVM manually. This is the most frequent case.
2) Logcat shows the following message, and test project fails:
[2010-08-15 18:42:40 - (My project)] Test launch failed: Could not connect to:  : 51154
[2010-08-15 18:42:40 - (My project)] Connect to Eclipse test result listener failed

3) Eclipse stops responding.
The above cases happens even when the test unit contains nothing.
Also it just doesn't not work in debug. The test case runs successfully if it is not in debug mode (But there are still some glitches, like Logcat sometimes won't emit debug messages).
I have tried the followings, but still no luck:

*

*Reinstall the Android SDK

*Download the latest version of Eclipse and download the ADT plugin again

*Running Eclipse with -clean switch

*Clean the test and test target projects and build again

*Switched to a new workspace and configure my projects again

*Clear user data while start debugging in the AVM

*Configure a new AVM

It would be grateful if anyone can shed a light on me.
Thanks in advance!

A: [2012-09-18 18:03:57 - NotePadTest] Test launch failed: Could not connect to:  : 52122
[2012-09-18 18:03:57 - NotePadTest] Connect to Eclipse test result listener failed

or
Launch error: Failed to connect to remote VM

I'v met the same problem and I solved it as below:
Preferences-General-Network Connections-Direct
Hope this helps.

A: I determined to resolve this issue last weekend. The trials are quite frustrating but it seems to be finally working. Below is what I did:

*

*The machine I am using for development is Windows 7 Ultimate (64-bit).

*I decided to start over again by reinstalling all the components.

*Firstly the latest Java Runtime. I decided to use 32-bit Java (hoping) for better compatibility.

*Then I followed the step-by-step tutorial in the Android SDK page. To my surprise on the Eclipse ADT page I suddenly saw the following message:

Caution: There are known issues with
  the ADT plugin running with Eclipse
  3.6. Please stay on 3.5 until further notice.notice.

*

*Not sure I overlooked this message or not, by anyway. So Helios is not guaranteed, I downloaded Galileo and install the ADT plugin (which turns out my decision to install 32-bit Java was correct, as Galileo only offers x86 build)

Unfortunately, this still won't work. But after some trial and error I found a way to kick the test case working, which is:

*

*First, start the application to be tested in Debug mode. The DVM should boot, and the debugger should attach successfully.

*Do NOT close the DVM. Go select the test case and click the debug run button.

This way the DVM won't stuck at the Sending WAIT chunk message, and test cases can be run.
Hope this helps.

A: I've just been running into this problem. It was driving me crazy.
As a last resort, I tried running the tests on my NexusOne device, instead of the emulator. They did run through completion.
I then tried on the emulator again and, to my surprise, they worked.
Not very confidence inspiring, I know, but worth a try.
Good luck!

A: Try issuing the following commands in a CMD window:
%ADB_DIR%\adb kill-server
%ADB_DIR%\adb start-server
Hope this helps.

A: Try this; run configuration, check whether launce default activity is selected, and in target tab check "always prompt to pick device"


text:
Q: Is it okay to put partial answers? So let's say someone asks a question and you know an integral part of the answer, but not the whole thing. An example of one is this person was trying to make a scalable div with some styling. I knew how to do the javascript tidbit, but not the CSS. Would it be wrong of me to post my answer for the javascript but not the CSS? Technically I'm not solving his problem because the CSS portion that he wants to understand is not being answered much in my answer, but at the same time I don't want this to be a barrier for me to contribute something that I can help with.
Any thoughts are most appreciated.
EDIT: Also are there any thoughts on posting unfinished answers? Maybe you're posting part of an answer you want to finish later?

A: In my opinion it's OK and I will explain why.

*

*Assuming you answer is good and correct, it has value for other people, even if not answering the whole original question.

*The question author does not have to mark it accepted, he can upvote and comment "true, but I still need this and that"

*Assuming other answer give the missing stuff without what you said, the OP can post his own answer combining both and accept it making it community wiki so that he won't gain reputation for contents not his own.

A: I think it is perfectly fine to post partial answers. It may be possible to figure out the rest on your own, someone else may post the second part of the answer or you can go back to complete your answer later on.


text:
Q: Can you call a C# DLL from a C DLL? I've built a DLL in C#. Now I want to use the R Environment to call functions in that DLL. The R environment supports calling unmanaged C/C++ DLL's but not into .NET DLL's. So my question is, can I call functions in a C# DLL from a C/C++ DLL? If so, do you have a link to info about how to do this?

A: The most straight forward way of doing this is to expose one of the C# classes in your C# DLL as a COM object, and then create an instance of it from your C/C++ DLL. If that isn't an acceptable option, you'd need to create a mixed-mode C++ DLL (which contains both managed and unmanaged code). Your C/C++ DLL can call exported functions in your mixed-mode DLL, which can in turn forward the calls on to your C# class.

A: This article might help you out:
CLR Hosting APIs (MSDN)
Updated: There's a tool called mergebin that ships with the .NET SQLite wrapper you can use to create a mixed mode native/managed DLL. Grab the source code from:
SQLite for ADO.NET 2.0 (SourceForge)
You'll find the exe in the bin\tools folder.
Kev

A: It is actually pretty easy.  Just use NuGet to add the "UnmanagedExports" package to your .Net project.  See https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports for details.
You can then export directly, without having to do a COM layer.  Here is the sample C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using RGiesecke.DllExport;

class Test
{
    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
    public static int TestExport(int left, int right)
    {
        return left + right;
    }
}

R should be able to load TextExport just like a regular C dll.


text:
Q: strange space issue when adding Kal as subview There's too much black space between the Kalendar and the navigation bar. Here's a picture of what I'm talking about:

I'm calling the code from ViewDidLoad of a ViewController that I have in my storyboard:
- (void) viewDidLoad {
    KalViewController *calendar = [[KalViewController alloc] init];
    [self.view addSubview:calendar.view];
}

I'm just learning to use Kal.  Maybe I'm going about incorporating it in the wrong way.  I sure do like using the storyboard to link up my views so my viewcontroller includes "Kal.h" and I instantiate as shown in the code above.  I tried to make the viewcontroller a subclass of KalViewController but that didn't work.
Maybe there's a more elegant way of incorporating Kal into a hierarchy of storyboarded view controllers?

A: Just add the following:
[[self navigationController] initWithRootViewController:calendar];
[[calendar navigationItem] setHidesBackButton:YES];

and it should do the trick. The second line is being used to hide the "Back" button that otherwise becomes visible, but for me it's a single screen app, you may or may not want to use it.

A: I used the exact same code as you initially did ACB, had the exact same problem but I also had included [self addChildViewController:calendar]; after the creation of the calendar view.
What does this code do? [self addChildViewController:calendar];
I understand it "adds a child view controller" but what is REALLY going on.... and should I need this? Apparently not because you didn't, and I just compiled my code without it and there was no difference.
Overall code:
KalViewController *calendar = [[KalViewController alloc] init];

[self.view addSubview:calendar.view];

//[self addChildViewController:calendar];


text:
Q: Why might Internet explorer return different results when running as a windows service? I have a Windows Service that is calling a Web Page via the ShDocVw object (IE8) with a URL. It then checks the page and if it gets a certain result, it reads the data and then returns a result.
When I run this in debug and as my ordinary domain user, it all works happily. When I run it as an ordinary domain user as a Windows Service, it gives me back a completely different web page. I have checked the calling URL and the response URL from the web page and in debug or in production and they are exactly the same! Strangely, the web page being sent back in debug is different to the one being sent back in production. The one in debug gives me the information that I am looking for, but the production version (running as a Windows Service) responds with an error.
The original URL seems to be redirecting to another web page, which is why I am using ShDocVw and IE for the process (unless someone tells me otherwise). I did try using a different object, but I cannot remember what that was now.
What is really weird is that the process works perfectly for 3 different URLs in debug and in the Windows Service, but the fourth URL varies it's returned web page (but has the same URL)!
The code is something like:
        InternetExplorer objIE = new InternetExplorer();
        objIE.Navigate(sService, ref objEmpty, ref objEmpty, ref objEmpty, ref objEmpty);
        while (objIE.Busy || (objIE.ReadyState.ToString() != "READYSTATE_COMPLETE"))
        {
            System.Threading.Thread.Sleep(1000);
            if (i == I_TIMEOUT)
            {
                break;
            }
            i++;
        }
        mshtml.HTMLDocument objDocument = (mshtml.HTMLDocument)objIE.Document;

Does anyone know how to find out what the problem is or know what I might be doing wrong?

A: The answer to the problem was that the USER that the Windows Service was running under had never been logged on, so it did not have an IE profile. Once I logged onto the computer as the user and fire up and close IE, the Windows Service started to work and the correct request then resulted in the correct response for the previously errant request.
Thanks for your answers.


text:
Q: Calling a WCF service with jQuery ajax I created a WCF service with a method declared as follows
[OperationContract]
[WebInvoke(UriTemplate="getDashBoard", Method="POST", BodyStyle=WebMessageBodyStyle.WrappedRequest, RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
getDashBoard object (string strGroups);

which returns a
List<Dictionary String, Object> rows = new List<Dictionary String, Object>();

serialized by JavaScriptSerializer
serializer.Serialize ( rows) ;

client-side i call the webservice method in this way
$.ajax ({
    type: " POST" ,
    url: url ,
    headers : {" Access -Control- Allow- Origin" , " *", " Access -Control- Request- Method" , " POST "},
    dataType : " json " ,
    contentType : "application / json ; charset = utf -8" ,
    date : ' {" strGroups ": " ISPB "} ' ,
    success : function ( data) {
        var content = JSON.parse ( data);
        $.each(content, function(i, item) {
            console.log(i) ;
        });
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(" getDashBoard " + textStatus) ;
    }
});

with Firefox the call to the WS returns this error " NetworkError : 405 Method Not Allowed . Locked request multiorigine (cross- origin) : the criterion of the origin does not allow the reading of the remote resource http:// .... You can solve the problem ... by moving the resource on the same domain or activating CORS . "
with the debugger IE return data appear correctly formatted and the object "content" has all the correct values ; but the cycle doesn't work: it returns "Character is not valid"
help meeeeee !
i'm desperate :o
Thanks Cinzia

A: try this :
$.ajax ({
type: " POST" ,
url: url ,
crossDomain : true,
dataType : " json " ,
date : ' {" strGroups ": " ISPB "} ' ,
success : function ( data) {
    var content = JSON.parse ( data);
    $.each(content, function(i, item) {
        console.log(i) ;
    });
},
error: function (jqXHR, textStatus, errorThrown) {
    alert(" getDashBoard " + textStatus) ;
}

});

A: You must activate CORS on your WCF Service on the server-site. CORS is used to get arround the same-origin-policy. Here is a good resource about this.
Basically you first have to add a message inspector and later on you have to add the CORS-Heder to the response:
requiredHeaders.Add("Access-Control-Allow-Origin", "*");
requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
requiredHeaders.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");

endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));

The differed behavior in IE and FF comes from the preflighted OPTIONS call from FF (description). If you enable CORS on your WCF-Service (like descried above), it should work in both browsers.
As an alternative you can run your service call on the same domain, but this depends on your requirements.

A: Thank you very much for your answer.
The problem is that even if i work on the SAME DOMAIN i have the same error "SCRIPT1014: Invalid character" on
$.each(content, function(i, item) {
        console.log(i) ;
    });

if i delete the rows code about the cycle, IE shows me the data return as below:
[{"Descr":"Altro","percValore":0.003},{"Descr":"altro 2","percValore":0.100}]
it seems correct!!! FireFox doesn't show nothing!
Maybe the problem is not the cross domain but the response?
Thank you Cinzia


text:
Q: Fetch result from Many to Many Relation I have two entity with Many to Many relation like below..
@Entity
@Table(name = "MEMBER")
public class Member implements Serializable {
    @Id
    private Long id;

    private String name;

    @OneToMany(fetch = FetchType.LAZY)
    @Fetch(value = FetchMode.SELECT)
    @JoinTable(name = "MEMBER_BADGE",
            joinColumns = {@JoinColumn(name = "member_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "badge_id", referencedColumnName = "id")})
    private List<Badge> badgeList = new ArrayList<>(0);

    // Getter & Setters

}

And
@Entity
@Table(name = "BADGE")
public class Badge implements Serializable{
    @Id
    private Long id;

    private String name;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "badgeList")
    @Fetch(FetchMode.SELECT)
    private List<Member> memberList = new ArrayList<>(0);

    // Getter & Setters
}

Badge name examples... "Teacher", "Doctor", "Engineer" etc.
How to get all the "List<Member>" who have "Teacher" badge by Hibernate Criteria/Query.
session.createCriteria(Member.class).add(Restrictions.eq(---What ?---)).list();
session.createQuery("select mem from Member where ???? ").list();

A: It has been solved using alias like...
session.createCriteria(Member.class)
       .createAlias("badgeList", "badge")
       .add(Restrictions.eq("badge.name", "Teacher"))
       .list();