text:
Q: Short story where Earth is given a racist governor who likes species of a certain color I'm trying to identify a science fiction short story I read many years ago.
In it, Earth receives an emissary from the Galactic Government, who informs us that (our sense of self-importance notwithstanding) Earth is in a remote backwater and has only recently come to the attention of the Galactic Empire, which has assigned us a governor who is exceedingly and unpleasantly oppressive.
Worse yet, this Governor is notoriously color-prejudiced, strongly preferring beings who are green, or perhaps blue... Really, there are no humans who look like that? Oh, dear. That is really quite bad...

A: "Down the River." A short story written by Mack Reynolds. First published in Startling Stories (September 1950). I first encountered it in the anthology Galactic Empires, Volume 2, edited by Brian Aldiss.
A little Googling found portions of the text for me on Google Books, part of a collection called The Second Mack Reynolds Megapack: 21 Classic Tales of Science Fiction, which is available via Amazon (in a Kindle e-book edition) for a mere $0.99 in U.S. money.
It appears that for a long time, Earth has basically been primitive territory under the silent protection of "the Gabon of Carthis." However, some recent high-level negotiations among the great Galactic powers have led to a transfer of this territory to "the Gabon of Wharis," who is the ruler of the Wharis Empire. A new Graff (sort of like a provincial governor) will soon be sent out to represent that empire, and Wharis is not so laissez-faire about primitive native tribes as the rulers of Carthis have traditionally been. We can look forward to having our natural resources plundered for the benefit of more advanced worlds.
The old Graff, who is explaining this to leaders of the human nations before he leaves our solar system forever, draws an explicit comparison to the Louisiana Purchase, when France sold a huge chunk of North America to the USA, with none of the Native American tribes in that territory even being consulted in the matter, since their opinions simply didn't count!
And of course the story's title refers to the pre-Civil War tradition, in the USA, of selling a slave "down the river," which was understood in such places as Missouri (one of the northernmost slave states in those days, and located along the Mississippi River) to mean the slave would probably end up far worse off than he was before. (As a child, I think I first learned that meaning of "sold down the river" when I read Mark Twain's novel Pudd'nhead Wilson.)
The last paragraphs of Reynolds's story are visible on Google Books. I will quote them to show that this is definitely the same thing you were remembering. The old Graff, the one about to leave, is the person speaking first. The President of the United States is the other participant in this conversation.

"There is one thing I can suggest that might help you considerably in
your dealings with Belde Kelden Forty-eight L. I hope that in telling
you of it, I don't hurt your feelings."
"Of course not," the President said hurriedly and hopefully. "The fate
of the whole world is at stake. Anything that will help--"
"Well, then, I might say that I consider myself completely without
prejudice. It means nothing to me if a person has a green skin, a
yellow one, or is white, brown, black, or red. Some of my best friends
are unfortunately colored.
"However, well, don't you have any races on
this planet with a green complexion? Graff Belde Kelden Forty-eight L
is known to be extremely prejudiced against races of different colors.
If you had some green representatives to meet him--"
The President, who was from Mississippi, stared at him dumbly.
The Graff was distressed. "You mean you have no races at all on Earth
of green complexion?--or, at very least, blue?"

(Frankly, for a long time I've been thinking that the human race's best bet might be to use some Hollywood makeup artists to make certain people look green-skinned, and then send them out to be as charming as possible in representing us to the new Graff so that he would go comparatively easy on the rest of us. It might not work, but it could scarcely make things worse!)


text:
Q: move_uploaded_file two or more different image names moves only one i am trying to move five different files in one form at the same time but only one image moves. I have five columns for each filename in my database table. The uploaded image names saves in the database column but the only problem is only one file is moved instead of all the files uploaded. Below is code:
 //form isValid...
 $post = $form2->getData();

            $imageonetmp = $post["imageone"]["tmp_name"];
            $imageonename = $post["imageone"]["name"];

            $imagetwotmp = $post["imagetwo"]["tmp_name"];
            $imagetwoname = $post["imagetwo"]["name"];

            $imagethreetmp = $post["imagethree"]["tmp_name"];
            $imagethreename = $post["imagethree"]["name"];

            $imagefourtmp = $post["imagefour"]["tmp_name"];
            $imagefourname = $post["imagefour"]["name"];

            $imagefivetmp = $post["imagefive"]["tmp_name"];
            $imagefivename = $post["imagefive"]["name"];

            $filepath = $this->_dir.$imageonename;
            $filepath = $this->_dir.$imagetwoname;
            $filepath = $this->_dir.$imagethreename;
            $filepath = $this->_dir.$imagefourname;
            $filepath = $this->_dir.$imagefivename;

            move_uploaded_file($imageonetmp, $filepath);
            move_uploaded_file($imagetwotmp, $filepath);
            move_uploaded_file($imagethreetmp, $filepath);
            move_uploaded_file($imagefourtmp, $filepath);
            move_uploaded_file ($imagefivetmp, $filepath);

 /*set image names to db here*/
 $entityManager->persist($autos);
            $entityManager->flush();

Hope someone can help.

A: You are using the same variable name $filepath to write the files.  Meaning you are moving each file but overwriting the previous move.
You should use different variable names e.g. $filepath1, $filepath2, etc...
Or
$filepath = file location...
Move file...
And repeat.

redpajama_set_name: RedPajamaStackExchange


text:
Q: input range onChangeComplate event I try to implement input range in my react app. But can`t find way how to trigger function when drag is over. Implementation must work on Chrome.
      <input
        className="slider"
        onChange={this.handleMinProbabilitySlideChange}
        onMouseUp={this.handleDragEnd} // not working
        onBlur={this.handleDragEnd}    // not working
        value={minProbability}
        type="range"
        min="0"
        max="100"
        step="1"
      />


text:
Q: Defaulting locale if locale missing in Rails I have my web app translated into english and croatian. English being set as default locale in my config/application.rb and enabled all fallbacks:
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :en
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
I18n.enforce_available_locales = true
config.i18n.fallbacks = true
config.i18n.fallbacks = [:en]
config.i18n.fallbacks = {'es' => 'en', 'fr' => 'en', 'de' => 'en'}

My config/routes.rb are defined like this:
scope "(:locale)", :locale => /en|hr/ do
  root :to => 'static_pages#home'
  match 'signin', to: 'sessions#new', via: 'get'
  match 'signout', to: 'sessions#destroy', via: 'delete'
  match '/signup', to: 'users#new', via: 'get'
  match '/about',   to: 'static_pages#about',   via: 'get'
  resources :sessions, only: [:new, :create, :destroy]
  resources :relationships, only: [:create, :destroy]

  resources :users do
    member do
      get :following, :followers
    end
  end

end

Everything works perfect when a user is using the app and switches between the languages, but if a user goes to the url and types in for example "es" instead of "en" or "hr" I get a routing error page with the error description: No route matches [GET] "/es/signin"
How can I make it fallback to english locale, if the whole .yml file in the locales folder is missing?

A: Add es or any other locale to your regex in config/routes.rb: :locale => /en|hr|es/. Anything except those values will cause routing error.


text:
Q: How do I build a single js file for AWS Lambda nodejs runtime We are working on a project/framework that aids in deploying and maintaining code in AWS Lambda. I want to build/bundle all node.js code for a lambda function into one js file because:

*

*Smaller codebases help with lambda cold start issues

*Lambda has code zip size limit of 50MB

We don't want to create a custom bundler to do this because there are many options already out there (systemjs,browserify,webpack etc). HOWEVER we are concerned with issues with some node modules not playing well with bundlers/builders.
Specifically aws-sdk has known issues with webpack, says it has browserify support but I've talked to people who have had issues with browserify'ing aws-sdk
We want to pick an existing bundler (or 2), but we want to make sure it works for as many modules/code as possible. We are trying to create a plugin ecosystem for JAWS, so getting this right is important (don't want to turn people off because module X they use wont bundle).
Questions:

*

*How would I go about bundling/building to satisfy these constraints?

*Is there any guidelines we can give to consumers of our product to ensure the code they write/use will bundle? Ex: Dynamic require()s cause issues AFAIK.

A: I prefer not to use single file solution, but to upload zip file with all my code packed. I use gulp for this. The code below only uploads production dependencies, excluding development ones and zip archive from previous upload. You may also exclude your test folder or any other file using parameters of gulp.src.
Just to mention, aws-sdk library is in my development dependencies as AWS Lambda already has a copy ;)
var gulp = require('gulp');
var lambda = require('gulp-awslambda');
var zip = require('gulp-zip');
var settings = require('./settings');
var argv = require('yargs').argv;
var p = require('./package.json');

gulp.task('default', function () {
    var profile = argv.profile;
    var src = ['**', '!*.zip', '!node_modules/aws-sdk{,/**}'];
    var i;
    for (i in p.devDependencies) {
        src.push("!node_modules/" + i + "{,/**}");
    }
    if (!profile) {
        profile = settings.aws.defaultProfile;
    }
    return gulp.src(src)
        .pipe(zip('archive.zip'))
        .pipe(lambda(settings.aws.lambda, {
            region: settings.aws.region,
            profile: profile
        }))
        .pipe(gulp.dest('.'));
});

A: This doesn't directly answer your question, but the serverless project might be exactly what someone in this situation needs.
It allows you to build projects in a normal webpack-style multi-file architecture, then uses a CLI utility to build your project(s) into Lambda-optimized files.
The CLI also handles function initialization, deployment, and a litany of other functions I've not yet even needed.  It will even create/configure your triggers (e.g., s3 object creation or setting up a new REST API thru AWS API service).
I only have a few Lambda functions, but even maintaining those was a pain until I started using serverless.
(this is a fawning post, but to be clear I'm not affiliated w/ the project)

A: aws-sdk-js now officially supports browserify. You can why this is a great thing on my blog.
I have created a serverless plugin called serverless-plugin-browserify that will do all the heavy lifting with very minimal configuration.
To answer the question specifically, I solved the problem with this browserify config:
{
  disable: false, //Not an official option, used as internal option to skip browserify
  exclude: [],    //Not an option, but will use for setting browserify.exclude() if defined in yml
  ignore:  [],    //Not an option, but will use for setting browserify.ignore() if defined in yml

  basedir:          this.serverless.config.servicePath,
  entries:          [],
  standalone:       'lambda',
  browserField:     false,  // Setup for node app (copy logic of --node in bin/args.js)
  builtins:         false,
  commondir:        false,
  ignoreMissing:    true,  // Do not fail on missing optional dependencies
  detectGlobals:    true,  // We don't care if its slower, we want more mods to work
  insertGlobalVars: {      // Handle process https://github.com/substack/node-browserify/issues/1277
    //__filename: insertGlobals.lets.__filename,
    //__dirname: insertGlobals.lets.__dirname,
    process: function() {
    },
  },
  debug:            false,
}

You can see my full code here with a complete example here

A: Possible answer might be making the function behave like a bootloader. Make the function download packaged code from S3, unpack it and run it.
Having to touch the code the way you're proposing seems like a bad idea that could result in unpredictable and hard to debug bugs.


text:
Q: Few extremely large values when using RDTSCP in C I am using the following function to measure clock cycles taken by a simple operation:
uint64_t rdtscp(void) {
  uint32_t lo, hi;
  __asm__ volatile ("rdtscp"
      : /* outputs */ "=a" (lo), "=d" (hi)
      : /* no inputs */
      : /* clobbers */ "%rcx");
  return (uint64_t)lo | (((uint64_t)hi) << 32);
}

To avoid taking into account possible delay due to interrupts, I parsed /proc/interrupts file in the read_intr() function and considered the value only if there were no new interrupts on CPU 0.
These functions are used to measure the cycles taken by the operation in a loop:
for (i = 0; i < 1000; i++)
{
    for (j = 0; j < 256; j++)
    {
        rnd1 = rand() % 256;

        intr1 = read_intr();
        start = rdtscp();
        rnd1 + 1;  // Operation
        end = rdtscp();
        intr2 = read_intr();

        if (intr1 == intr2)
        {
            printf("%lu\n", end - start);
            fflush(stdout);
        }
    }
}

I then ran the above program using:
$ sudo schedtool -F -p 99 -e taskset 0x1 ./a.out > output

That is, the program is scheduled using SCHED_FIFO with 99 priority and forced to run on CPU 0.
I analyzed the output counter values to obtain the following statistical parameters about the execution cycles taken:
Mean = 36.49
Median = 33

However, when the output is sorted in descending order the first few values are:
32593
29081
28878
1113
1065
612

What is the reason for these (very few) extremely high counter readings even after interrupts are being considered? Also, given that the first three sorted readings are much higher than the following three (shown), could this be because of different reasons?
Edit: Based on gudok's comment, I turned off hyper-threading and also automatic power management from the BIOS settings, but still find a discrepancy as mentioned below.


text:
Q: contradiction proof on divides Suppose a,b ∈ Z. If 4 | $(a^2 + b^2)$ then a and b are not both odd.
So, assuming that 4 | $(a^2 + b^2)$  and $a$ and $b$ are odd
this gives $4k=(2l+1)^2+(2u+1)^2$ for some $k,l,u\in z$
eventually leading to $4k=4(l^2+l+u)+2(u^2+1)$
The RHS is not a multiple of 4 when $u=2$ contradiction.
Is this valid, thanks.

A: It's not yet valid, because you haven't shown why the RHS cannot be a multiple of $4$. You cannot simply set $u=2$, because the $u$ you have is already determined by $b$, since $b=2u+1$.

To correct your proof, re-think how you got from
$$4k=(2l+1)^2 + (2u+1)^2$$
to
$$4k = 4(l^2+l+u) + 2(u^2+1)$$
because I think you were a bit sloppy here.

A: This is invalid. You have done a mistake in calculation.
RHS will be $4(l^2+u^2+l+u)+2$, which is not divisible by 4.
Hope it helps:)

A: If you multiply correctly, the RHS leaves a rest of 2 modulo 4. So your idea was correct, you just need to recalculate.


text:
Q: Sharing folders revokes user permission I am currently trying to move files from server A to server B.
Server A is currently hosting a website, and server is suppose to host it in the future.
Server A has a severe firewall, connection through port 445 has been opened, but that still does not allow files to be shared across the servers using fileshare,
The only way, we've been able to move files som A to B, is by right clickking each folder -> enable share -> and give our users read/write permission.
A problem with doing this, is that enabling sharing of folders seem to revoke users that are in the permission list => thereby causing havoc on server A, and on the content it is hosting.
Is there a way to enable share, without revoking users permission given to the folder, or subfolders?

A: Your question is not quit clear.
What is the purpose to share a folder if you do not give permissions?
Either you can give permission to everyone,group or a user, this is how folder sharing is working.
What i'm suggesting is to arrange all folders under 1 generic folder and share the generic one, this way you can handle only 1 folder and not share one folder by one.


text:
Q: How to convert a Delimited List of Mixed Strings to an array for powershell script I'm looking to solve a problem where I have a long file of comma-delimitted ordered 8-digit numbers and ranges (with leading zeros), as below:
00001253,00001257-00001268,00001288,...,02154320,02154321,02154323-02154327,...

I want to
(a) store any values that aren't ranges as tokens in a PowerShell array while retaining leading zeros
and
(b) expand ranges to all of their corresponding values and store the tokens in the same array. Here's the PowerShell "script" I threw together for my purpose so far:
$refids = @(ARRAY_DERIVED_FROM_ABOVE_LIST)

foreach ($refid in $refids) {
New-Item c:\scripts\$refid.txt -type file -force -value "KEY:$refid"
}

Any ideas on how to proceed? Thanks in advance for any assistance

A: You can start with this, maybe:
$string = '00001253,00001257-00001268,00001288,02154320,02154321,02154323-02154327'

$string.split(',') |
foreach {
  if ($_.Contains('-'))
    {
     invoke-expression ($_.replace('-','..')) |
     foreach {'{0:D8}' -f $_}
    }

  else {$_}
 }

00001253
00001257
00001258
00001259
00001260
00001261
00001262
00001263
00001264
00001265
00001266
00001267
00001268
00001288
02154320
02154321
02154323
02154324
02154325
02154326
02154327

A: Mjolinor's answer is very good. Some people refrain from using Invoke-Expression. Here is another example that accomplishes the same thing while showing a slightly different approach.
$string = '00001253,00001257-00001268,00001288,02154320,02154321,02154323-02154327'

$string.split(',') | ForEach-Object {
    If($_.Contains('-')){
        $_.Split("-")[0]..$_.Split("-")[1]
    } Else {
        $_
    }
} | ForEach-Object{ Write-Output ([string]$_).PadLeft(8,"0")}


text:
Q: Generating histograms of multiple fields using ArcPy? I have a large shapefile and I'm trying to automate a process to generate histograms of several fields with the MakeGraph tool, but I'm receiving the following error.

class 'arcgisscripting.ExecuteError'>: Failed to execute. Parameters
  are not valid. ERROR 001020: Input series error. Incompatible
  parameter list. Click 'Always reset parameters...' check-box to reset
  parameters. Failed to execute (MakeGraph).

Any idea why this is happening? My inputs are as follows...

*

*input table = shapefile,

*fieldList is generated by input,

*workspace = output folder,

*input_template = a .grf or .tee (tried both),

*run is just a boolean true or false

Here's my code:
# Import arcpy module
import arcpy

# Check out any necessary licenses
arcpy.CheckOutExtension("spatial")

input_table = arcpy.GetParameterAsText(0)

fieldList = arcpy.GetParameterAsText(1)

workspace = arcpy.GetParameterAsText(2)
arcpy.env.workspace = workspace

input_template = arcpy.GetParameterAsText(3)

run = arcpy.GetParameterAsText(4)

countBin = 10

# Boolean selection
if run == 'true':

    # Iterate over selected field names
    for fieldName in fieldList.split(';'):

        out_graph_name = "histogram"
        out_graph_jpg = fieldName + "_histogram.jpg"

        # Create the graph
        graph = arcpy.Graph()

        # Add a histogram series to the graph
        graph.addSeriesHistogram(input_table, fieldName, countBin)

        # Specify the title of the left axis
        graph.graphAxis[0].title = "Count"

        # Specify the title of the bottom axis
        graph.graphAxis[2].title = fieldName

        # Specify the title of the Graph
        graph.graphPropsGeneral.title = fieldName + " Histogram"

        # Output a graph, which is created in-memory
        arcpy.MakeGraph_management(input_template, graph, out_graph_name)

        # Save the graph as an image
        arcpy.SaveGraph_management(out_graph_name, out_graph_jpg, "MAINTAIN_ASPECT_RATIO", 600, 375)

else:
    print "done"

A: Your issue is here I believe:
graph.addSeriesHistogram(input_table, fieldName, countBin)

Specifically, with the variable fieldName. For addSeriesHistogram, fieldNameneeds to be a layer object. Instead, it is a string in your code.
To access the layer object, you'll need to use arcpy.ListLayers.
Try this code:
#Create map object
mxd = arcpy.mapping.MapDocument("CURRENT")

#iterate through layer objects in map object
for lyr in arcpy.mapping.ListLayers(mxd):

    #Find layer with name 'fieldName'
    if lyr.name == fieldName:
        graph.addSeriesHistogram(input_table, lyr, countBin)


text:
Q: Magento How to add custom field into Role Creation Form and save its value into database I have a requirement to add an extra field on to the Role Creation form.
I was able to do by 2 ways
 - Using Event Observer
 - Or by rewriting blocks
But I want to save this field into the data base and want to populate this value on edit role page.
I tried -
$fieldset = $form->addFieldset('navigator_information', array(
            'legend' => 'Navigator Information',
            'class' => 'fieldset-wide'
                )
          );

      $options = array();
      $options['client'] = 'client';
      $options['report'] = 'report';

          //add new field
          $fieldset->addField('navigator_role', 'select',
            array(
                'name'  => 'navigator_role',
                'label' => Mage::helper('adminhtml')->__('Navigator Roles'),
                'id'    => 'navigator_role',
                'class' => 'required-entry',
        'values' => $options,
                'required' => true,
              )
          );

and it shows me the new fieldset and new field but How to store this value
into db?
Any help would be appreciated.
I have uploaded screen shot that shows new field


text:
Q: Which function in compiler is responsible for accepting returned value from main () This is a curious question i got from my sir. He said if we don't put return type before main() it will return a garbage value. He said that this garbage value is returned to a function in the C compiler.

*

*Which compiler function is responsible for that?

*What will happen if this compiler functions parameter is a garbage value?

e.g. :
main()
{

 printf("Hello world");

} //will return a garbage value since no return type

A: There isn't necessarily a name for the function that calls main() and arranges to exit the program with the value returned by main().  The object file often has a name such as crt0.o and is responsible for calling main() and calling exit() with the returned value.
The code main() { …; /* No return */ } is invalid in C99 and C11; you must specify a return type (of int — see What should main() return in C and C++?).  In the C89/C90 standard, you could write main() without a return type, but you were then obliged to return a value explicitly from main() or you would, indeed, get garbage returned.
However (in what some people consider a mistake, though it is compatible with C++), C99 legislated that if you don't explicitly return a value from int main(void) { …; /* No return */ }, the compiler effectively inserts return 0; for you.
Thus, the code shown is C89/C90 (or pre-standard) C and should have a return.

A: I don't believe there is any convention for the name of such function, but it is responsible to use the return value of main() to set the ERROR LEVEL value recorded by the O/S. One can normally check that value (usually in batch file processing) to determine if the program completed successfully (0) vs. an error indication, with possible meaning to the different non zero values.

A: In standard C (and C++), main must have the return type int.  If there is no return type, perhaps some random four bytes of memory will be returned.  And in fact, only one byte will be used on many systems (like Unix and Linux) because return values from programs are always in [0,255].  If you return a garbage value, most systems will interpret zero as success and non-zero as failure, so invocations of your program may appear to "fail" from the outside caller's perspective.
On the other hand, some systems may tolerate this sort of misstep, because lots of legacy code does it, and simply return 0 for you.
There is some "startup" code which is run before main() usually.  This is platform-dependent, but somehow it needs to communicate the parameters and return value of main from and to the operating system.

A: If you add the -v flag to your invocation, i.e. g++ -std=c89 -x c -O2 -Wall -pedantic -pthread -v main.cpp, you'll notice that gcc adds some object files to your linker, i.e. crtbegin.o, crtend.o, crti.o and crtn.o, as well as crt1.o or crt0.o (it could be either.) The latter contains the entry point function (i.e., _start) that initializes the process and calls exit(main(argc, argv)).
Note this is actually implementation and operating system dependent (but gcc on linux was used as an example.)

In C89, if you don't specify a return value for main, the value returned is undefined.
2.1.2.2 Hosted environment

A return from the initial call to the main function is equivalent to
  calling the exit function with the value returned by the main function
  as its argument. If the main function executes a return that specifies
  no value, the termination status returned to the host environment is
  undefined.

In C99, you cannot declare a function without a return type (the implicit int rule is removed.) Compared to C89, C99 is explicit about the return type of main:

It shall be defined with a return type of int and with no parameters:
  [...] or in some other implementation-defined manner.

It also removed the undefined return value:
5.1.2.2.3

1 If the return type of the main function is a type compatible with
  int, a return from the initial call to the main function is equivalent
  to calling the exit function with the value returned by the main
  function as its argument;10) reaching the } that terminates
  the main function returns a value of 0. If the return type is not
  compatible with int, the termination status returned to the host
  environment is unspecified.

A:
Which compiler function is responsible for that?

None.  The value is returned to the environment.  In an operating system environment that value may be used to determine the status of the program execution.  By convention zero is success, non-zero an error.  The value can be used by shell scripts or other programs that launch processes - The make utility for example uses it to determine whether a build step has failed.
When a C program is run, it is loaded and started by the OS, then start-up code included by the linker performs tasks such as setting the stack pointer, initialising static data, initialising the library, then calling main().  When main() returns, this came code may perform some clean-up before the OS unloads the code and performs its own clean-up.

What will happen if this compiler functions parameter is a garbage value?

A non-zero value may be interpreted as an error condition, but only is something s explicitly checking it and interpreting it that way - such as a shell script, batch file or make for example.  The OS does nothing with it other than setting an environment variable ERRORLEVEL, so the value can be interrogated after the event.


text:
Q: PyQt6: Keep child of checkable QGroupBox active when Box is unchecked Is there a way in PyQt6 to keep the children of an unchecked QGroupBox active?
In detail I have a checkable QGroupBox where I use a QLable in the position of the original title of this box to allow linking to a webpage with the description of this box. As long as the box is active this link works as expected. However, as soon as it is unchecked the link is as well. Is there any way to prevent this? As my code is quite complex, I want to avoid assigning the parent of the groupbox as parent to the lable if possible.
Here are the likely relevant lines:
self.PerlFilePathBox = QtW.QGroupBox(parent=self.ConfigTab)
self.PerlFilePathBox.setTitle(" ")
self.PerlFilePathBox.setCheckable(True)
self.PerlFilePathBox.setChecked(False) # as soon as this is checked in the running program, the link becomes active
self.PerlFilePathBox.setGeometry(rel_pos(30, 140, 800, 120))

self.PerlFilePathBoxTitle = QtW.QLabel(self.PerlFilePathBox)
self.PerlFilePathBoxTitle.setText("Link.")
self.PerlFilePathBoxTitle.setOpenExternalLinks(True)
self.PerlFilePathBoxTitle.setGeometry(rel_pos(50, 5, 600, 25))

Is there any simple way to achieve this (like setting a particular property of QLabel) or would this require excessive sub-classing of the QGroupBox etc.?


text:
Q: Why does 00.0 cause a syntax error? This is weird.  This is what happens at the JavaScript console in Chrome (version 42.0.2311.135, 64-bit).
> 0
< 0
> 00
< 0
> 0.0
< 0
> 00.0
X Uncaught > SyntaxError: Unexpected number

Firefox 37.0.2 does the same, although its error message is:
SyntaxError: missing ; before statement

There's probably some technical explanation regarding the way JavaScript parses numbers, and perhaps it can only happen when tinkering at the console prompt, but it still seems wrong.
Why does it do that?

A: The expressions 0.0 and 00.0 are parsed differently.

*

*0.0 is parsed as a numeric literal 1

*00.0 is parsed as:

*

*00 – octal numeric literal 2

*. – property accessor

*0 – identifier name

Your code throws syntax error because 0 is not a valid JavaScript identifier. The following example works since toString is a valid identifier:
00.toString

1 Section 7.8.3 – Leading 0 can be followed by decimal separator or ExponentPart
2 Section B.1.1 – Leading 0 can be followed by OctalDigits

A: 00 is evaluated as an octal number and .0 is evaluated as accessing that number's property. But since integers are not allowed to be used as property accessors, the error is thrown.
You get the same error for any other object:
'string'.0 // Syntax error: unexpected number
({}).0 // Syntax error: unexpected number

You can find related information about property accessors on MDN.


text:
Q: How to fit the Histogram inside the node of tikzpicture I want to fix the x-axis label position and I also want to know how to reposition the histogram inside the rectangle like margin center or other feasible solution
\documentclass{article}
\usepackage[dvipsnames]{xcolor}
\usepackage{tikz}
\usetikzlibrary{positioning,calc}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\tikzset{myblock/.style = {rectangle, draw, minimum height=3cm}
}
  \begin{tikzpicture}
    \node (foo)[myblock]{
       \begin{tikzpicture}
       \begin{axis}[
       ybar=-0.10cm,
       axis x line*=bottom,
       axis y line*=left,
       height=3.5cm, width=3.4cm,
       bar width=0.1cm,
       symbolic x coords={topic1,topic2,topic3},
       %xtick={topic1,topic2,topic3},
       label style={font=\tiny},
       tick label style={font=\tiny}]
    \addplot[BlueGreen,fill] coordinates {(topic1,0.4)};
    \addplot[Cyan,fill] coordinates {(topic2,0.5)};
    \addplot[ForestGreen,fill] coordinates {(topic3,0.1)};

    \end{axis}
    \end{tikzpicture}
};
\node (bar)[myblock,right of=foo,xshift=5cm]{bar};
\draw[->] ($(foo.north east)!0.25!(foo.south east)$) -- node[below] {arrow text} ($(bar.north west)!0.25!(bar.south west)$);
\draw[->] ($(foo.north east)!0.5!(foo.south east)$) -- node[below] {arrow text} ($(bar.north west)!0.5!(bar.south west)$);
\draw[->] ($(foo.north east)!0.75!(foo.south east)$) -- node[below] {arrow text} ($(bar.north west)!0.75!(bar.south west)$);
% more arrows here
\end{tikzpicture}
\newpage
\end{document}

A:
\documentclass{article}
\usepackage[dvipsnames]{xcolor}
\usepackage{tikz}
\usetikzlibrary{positioning,calc, fit}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
    \tikzset{myblock/.style = {rectangle, draw, minimum height=3cm}
    }
    \begin{tikzpicture}
%       \node (foo)[myblock]{
%           \begin{tikzpicture}
                \begin{axis}[
                    ybar=-0.10cm,
                    axis x line*=bottom,
                    axis y line*=left,
                    height=3.5cm, width=3.4cm,
                    bar width=0.1cm,
                    symbolic x coords={topic1,topic2,topic3},
                    %xtick={topic1,topic2,topic3},
                    label style={font=\tiny},
                    tick label style={font=\tiny}]
                    \addplot[BlueGreen,fill] coordinates {(topic1,0.4)};
                    \addplot[Cyan,fill] coordinates {(topic2,0.5)};
                    \addplot[ForestGreen,fill] coordinates {(topic3,0.1)};

                \end{axis}
            (bounding box)
            \node[draw=red, fit=(current bounding box)]{};
            \draw(current bounding box.east)--++(2,0);
%           \end{tikzpicture}
%       };
%       \node (bar)[myblock,right of=foo,xshift=5cm]{bar};
%       \draw[->] ($(foo.north east)!0.25!(foo.south east)$) -- node[below] {arrow text} ($(bar.north west)!0.25!(bar.south west)$);
%       \draw[->] ($(foo.north east)!0.5!(foo.south east)$) -- node[below] {arrow text} ($(bar.north west)!0.5!(bar.south west)$);
%       \draw[->] ($(foo.north east)!0.75!(foo.south east)$) -- node[below] {arrow text} ($(bar.north west)!0.75!(bar.south west)$);
        % more arrows here
    \end{tikzpicture}
%   \newpage
\end{document}


text:
Q: What happens when you update an Windows store app? What happens when a developer updates an app? Does the user that updates the said app download a whole new app or is the windows app store smart enough like play store to just download the changes?Can anyone give logical explanation how it works in windows store?

A: >>Does the user that updates the said app download a whole new app or is the windows app store smart enough like play store to just download the changes?
When the developers created package for their project, and chose generate app bundle always, the user can download faster with an app bundle, because they only download the assets that they need. Then they don't need to download a whole new app to update. If the developers didn't choose this, the user may need to download a whole new app.
>>Can anyone give logical explanation how it works in windows store?
For example, if you create a app, then you choose generate app bundle always when packaging your app and publish this in the Windows Store. The customer need to download 100MB to require this app. After a period of time, you update this app, the customer just download the assets that they need to update our app, maybe just download 10MB.


text:
Q: How to simply add a column level to a pandas dataframe let say I have a dataframe that looks like this:
df = pd.DataFrame(index=list('abcde'), data={'A': range(5), 'B': range(5)})
 df
Out[92]:
   A  B
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4

Asumming that this dataframe already exist, how can I simply add a level 'C' to the column index so I get this:
 df
Out[92]:
   A  B
   C  C
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4

I saw SO anwser like this python/pandas: how to combine two dataframes into one with hierarchical column index? but this concat different dataframe instead of adding a column level to an already existing dataframe.
-

A: You could just assign the columns like:
>>> df.columns = [df.columns, ['C', 'C']]
>>> df
   A  B
   C  C
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4
>>>

Or for unknown length of columns:
>>> df.columns = [df.columns.get_level_values(0), np.repeat('C', df.shape[1])]
>>> df
   A  B
   C  C
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4
>>>

A: Another way for MultiIndex (appanding 'E'):
df.columns = pd.MultiIndex.from_tuples(map(lambda x: (x[0], 'E', x[1]), df.columns))

   A  B
   E  E
   C  D
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4

A: option 1
set_index and T
df.T.set_index(np.repeat('C', df.shape[1]), append=True).T

option 2
pd.concat, keys, and swaplevel
pd.concat([df], axis=1, keys=['C']).swaplevel(0, 1, 1)

A: I like it explicit (using MultiIndex) and chain-friendly (.set_axis):
df.set_axis(pd.MultiIndex.from_product([df.columns, ['C']]), axis=1)

This is particularly convenient when merging DataFrames with different column level numbers, where Pandas (1.4.2) raises a FutureWarning (FutureWarning: merging between different levels is deprecated and will be removed ... ):
import pandas as pd

df1 = pd.DataFrame(index=list('abcde'), data={'A': range(5), 'B': range(5)})
df2 = pd.DataFrame(index=list('abcde'), data=range(10, 15), columns=pd.MultiIndex.from_tuples([("C", "x")]))

# df1:
   A  B
a  0  0
b  1  1

# df2:
    C
    x
a  10
b  11

# merge while giving df1 another column level:
pd.merge(df1.set_axis(pd.MultiIndex.from_product([df1.columns, ['']]), axis=1),
         df2,
         left_index=True, right_index=True)

# result:
   A  B   C
          x
a  0  0  10
b  1  1  11

A: A solution which adds a name to the new level and is easier on the eyes than other answers already presented:
df['newlevel'] = 'C'
df = df.set_index('newlevel', append=True).unstack('newlevel')

print(df)
#           A  B
# newlevel  C  C
# a         0  0
# b         1  1
# c         2  2
# d         3  3
# e         4  4

A: As suggested by @StevenG himself, a better answer:
df.columns = pd.MultiIndex.from_product([df.columns, ['C']])

print(df)
#    A  B
#    C  C
# a  0  0
# b  1  1
# c  2  2
# d  3  3
# e  4  4

A: Another method, but using a list comprehension of tuples as the arg to pandas.MultiIndex.from_tuples():
df.columns = pd.MultiIndex.from_tuples([(col, 'C') for col in df.columns])

df
   A  B
   C  C
a  0  0
b  1  1
c  2  2
d  3  3
e  4  4


text:
Q: set a property's value with unknown depth within an object in javascript var params = {
    search: {
        make: "",
        model: ""
    }
}

function setVariable() {
    var value = "BMW";
    var key = "search.make";
    var arr = key.split(".");    //eg. ["search", "make"]
    params[arr[0]][arr[1]] = value;   // this works, but how do you
                                      // do it with unknown arr[] length?
}

How do I do this with an unknown arr[] length?
I have surmised that I probably need to do a recursive call, maybe passing something like arr.slice(1) within the function, but I have not been able to figure out what that should look like.

A: var params = {
    search: {
        make: "",
        model: "",
        whatever: {
            foo: {
                bar: {
                    moo: 123,
                    meow: 'xyz'
                }
            }
        }
    }
};

function updatePath(obj, path, value) {
    var parts = path.split('.');
    var i, tmp;
    for(i = 0; i < parts.length; i++) {
        tmp = obj[parts[i]];
        if(value !== undefined && i == parts.length - 1) {
            tmp = obj[parts[i]] = value;
        }
        else if(tmp === undefined) {
            tmp = obj[parts[i]] = {};
        }
        obj = tmp;
    }
    return obj;
}

Demo:
> updatePath(params, 'search.whatever.foo.bar')
{ moo: 123, meow: 'xyz' }
> updatePath(params, 'search.whatever.foo.bar.moo')
123
> updatePath(params, 'search.whatever.foo.bar.moo', 'test')
'test'
> updatePath(params, 'search.whatever.foo.bar.moo')
'test'
> updatePath(params, 'search.whatever.foo.bar')
{ moo: 'test', meow: 'xyz' }
> updatePath(params, 'search.whatever.foo.bar.x.y.z', 'hi')
'hi'
> updatePath(params, 'search.whatever.foo.bar.x')
{ y: { z: 'hi' } }
> updatePath(params, 'search.whatever.foo.bar')
{ moo: 'test',
  meow: 'xyz',
  x: { y: { z: 'hi' } } }
>

A: The following code traverses your params object until the given key is found. It assumes that key.split(".") returns a proper array of keys (so you might need to sanitize your inputs here further.
var params = {
    search: {
        make: "",
        model: ""
    }
}

function setVariable() {
    var value = "BMW";
    var key = "search.make";
    var arr = key.split(".");    //eg. ["search", "make"]

    var runner = params;
    for( var i=0, max=arr.length-1; i<max; ++i ) {
       // make sure the key exists
       runner[ arr[i] ] = runner[ arr[i] ] || {};
       // move one level deeper
       runner = runner[ arr[i] ];
    }

    // set the value in the last level
    runner[ arr[arr.length-1] ] = value;
}

EDIT: wrt to the comment of Felix Kling: It assumes that you want previously not existant keys to be generated. Else you would have to put a a further check into the for loop and leave the function, if the key does not exist, instead of creating it.


text:
Q: What do we mean by "controllable actions" in a POMDP? I have some questions related to POMDPs.

*

*What do we mean by controllable actions in a partially observable Markov decision process? Or no controllable actions in hidden Markov states?

*When computing policies through value or policy iteration, could we say that the POMDP is an expert system (because we model the environment)? While, when using Q-learning, it is a more flexible system in terms of intelligence or adaptability to a changing environment?

A: Actions
Controllable actions are the results of choices that the decision maker makes. In the classic POMDP tiger problem, there is a tiger hidden behind one of two doors. At each time step, the decision maker can choose to listen or to open one of the doors. The actions in this scenario are {listen, open left door, open right door}. The transition function from one state to another depends on both the previous state and the action chosen.
In a hidden Markov model (HMM), there are no actions for the decision maker. In the tiger problem context, this means the participant can only listen without opening doors. In this case, the transition function only depends on the previous state, since there are no actions.
For more details on the tiger problem, see Kaelbling Littman and Cassandra's 1998 POMDP paper, Section 5.1. There's also a more introductory walk-through available in this tutorial.
Adaptability
The basic intuition in your question is correct, but can be refined. POMDPs are a class of models, whereas Q-learning is a solution technique. The basic difference in your question is between model-based and model-free approaches. POMDPs are model-based, although the partial observability allows for additional uncertainty. Reinforcement learning can be applied in a model-free context, with Q-learning. The model-free approach will be more flexible for non-stationary problems. That being said, depending on the complexity of the problem, you could incorporate the non-stationarity into the model itself and treat it as an MDP.
There's a very thorough discussion on these non-stationary modelling trade-offs in the answer to this question.
Lastly, it is correct that POMDP's can be considered expert systems. Mazumdar et al (2017) have suggested treating Markov decision processes (MDPs) as expert systems.


text:
Q: Change Virtualbox disk type from AHCI to RAID I made have an image that was made on a Dell computer. This Dell had "RAID mode" set in the bios. If I load and then boot the image on any other computer set to AHCI or AHCI/RAID, I get BSOD. Same happens in Virtualbox.
On a physical machine, I can just go to the bios and switch it. How can I do this in Virtualbox?

A: Add the virtual disk to the Virtualbox VM as an IDE drive and set the IDE controller type to ICH6.

A: You need to install the AHCI driver for the operating system before you switch it in the BIOS.  You can do this from Device Manager by updating the IDE bus device driver to the revelant AHCI bus driver for your computer.


text:
Q: Background with opacity set is solid and not transparent in Chrome and Opera I have a div with text and background which after scrolling down is going over the home slider.I want to have some transparency. Everything is ok in Firefox where that layer is transparent with some opacity set. But in chrome and opera it is solid and slider is not visible under. I use:
  background:rgba(255,255,255,0.5);

i event tried to use transparent PNG but it also is solid.Problem preview
How can i make a background transparent in Chrome and Opera?

A: I know it is an old question but searching for the same problem this poped up on top for me.
So I had the same problem - working perfectly in Firefox but on Chrome no opaciy at all.
What I did and its working perfectly (at least for now) it to change from RGBA colors to HSLA colors.
In my  case changed the following :
background-color: rgba(0, 0, 0, 0.75);

to
background-color: hsla(0, 0%, 0%, 0.75);

I have no idea why chrome prefers the HSL colors and opacity.
Also a good point to consider, HSL colors are supported in newer browser versions.


text:
Q: On the two definition of weakly convergence of measures, which one is true? Let $X$ be a metric space and $\mu, \mu_1,\mu_2,\ldots$ Borel probability mesures on $X$. I met the following two definitions of the weakly convergence of $\{\mu_n\}$:
1. We call $\{\mu_n\}$ converges weakly to $\mu$ if $\int f d\mu_n\to \int fd\mu$ for any $f\in C(X)$, where $C(X)=\{f:X\to R: \text{$f$ is continuous and bounded}\}$;
2. We call $\{\mu_n\}$ converges weakly to $\mu$ if $\int f d\mu_n\to \int fd\mu$ for any $f\in C_c(X)$, where $C_c(X)=\{f:X\to R: \text{$f$ is continous and has compact support}\}$.
But, generally speaking, $C_c(X)$ and $C(X)$ are not necessarily equal on a metric space. So, which one is true? Or, these are actually two different definitions with the same name?

A: These are not equivalent. In K L Chung's book the second one is called vague convergence. The first definition is the standard one.


text:
Q: Why does my `train_test_split()` returns same samples Why does my sklearn.model_selection.train_test_split() returns same samples of X_train, X_test, y_train, y_test each time I run the code, even though I have kept shuffle=True, and I have not manually defined the seed value?
I am printing the samples like this:
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 100, shuffle=True)

print (y_test)

A: The train_test_split random_state controls the state of the sample (https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html):

Controls the shuffling applied to the data before applying the split. Pass an int for reproducible output across multiple function calls

To get different results, simply remove the parameter.


text:
Q: MySQL - Unable to load slow_log table We've had slow-log enabled for years:
slow-query-log=1
log-output=TABLE
Never had any problems retrieving the records from the table to review the results. About a week ago, I tried to retrieve the results with a SELECT statement. That attempt timed out. So, I tried to just "open the table" using HeidiSQL and SQLyog. HeidiSQL never completes the load (locks up the IDE), SQLyog fails with a MySQL error:
Executed SQL statement: select * from mysql.slow_log limit 0, 1000
Error number: 2000
Error message: Unknown MySQL error
I've tried under my own user account and as root, from both my own machine and on the server directly (localhost).
I tried TRUNCATING the table. That commands succeeds, but takes a very long time. I thought the table was maybe filling with too many records, but SQLyog indicates there are only 30 records right now.
What could be causing this and how do I fix it? We've made no server changes (MySQL versions or my.ini changes).
This MySQL server is a replicated master. I enabled slow-log on the slave, as the slave is used for some read-only tasks. I can access the slow-log table just fine on the slave. Don't know that that means anything, but in case it's helpful.
FYI, we run MySQL Server on Windows machines (Server 2012 R2).

A: I did some googling, and it's practically un-findable, but I did found this:

I had the same error. The solution was to fix permissions of log
  directory & files:
sudo chown -Rv mysql /var/log/mysql The update/reinstall helped you
  probably because the mysql install script fixed the permissions for
  you.

Quote


text:
Q: How to estimate a multiple regression function that has interactions between the independent variables and is potentially non-linear? I understand how linear regression is used on a sample to produce a model of how each independent variable affects the dependent variable. What I would like to do is something similar, except where the model can also represent interactions between the independent variables. Also, I would like the model to be nonlinear if possible. With preference given to simpler solutions, what is the range of available solutions to such a problem?
EDIT
To be more specific, the following are the details of my problem. I'm developing a neural network algorithm that has 11 continuous covariates that control it's behavior. These include size of different layers, learning rate, and a number of other things. I'm trying to understand how different values for the covariates produce different performance levels and why. Intuition and preliminary analysis (based on Monte Carlo sampling) tell me that there are interactions among some covariates and that effects are not likely to be linear in all cases. However, it's not obvious to me what the type of the relationships are (e.g. polynomial, exponential, etc.). Also, for efficiency, as I add more covariates and apply the algorithm to different contexts, I would like to have a method of regression in place that doesn't assume linearity and isn't dependent on foreknowledge of the type of relationship between the covariates and the performance (dependent variable).

A: The part about interaction terms in the linear model is easy to answer .  If you have variables $X_1$ and $X_2$ that you think interact in the model add the term $X_1$ multiplied by $X_2$ and test to see if the coefficient is significantly different from 0.  That term is your interaction term. Regarding a nonlinear model, why do you think you need a model that is nonlinear in the parameters.  There are many options for nonlinear models and the choice should be dictated by how the regression parameters are connected to the covariate in a nonlinear fashion. Should the coefficients be exponents for the covariates (for example)?


text:
Q: creating a search bar using Django I have a list of markdown pages displayed on the index page. I want to make a search bar using django that displays the searched items of the list so I have written this code in order to make the search bar get a certain query
in views.py:
def index(request):
    x = util.list_entries()
    for entryy in x:
        if 'q' in request.GET:
            q = request.GET['q']
            data = x.entryy.filter(entryy__icontains = q)
        else:
            data = x
    return render(request, "encyclopedia/index.html", {
        "entries": data
    })

in urls.py:
urlpatterns = [
    path("", views.index, name="index")]

in layout.html:
  <form action="{% url 'index' %}" method = "get">
                    {% csrf_token %}
                    <input class="search" type="search" name="q" placeholder="Search Encyclopedia">
                </form>

util.list_entries() fuction:
def list_entries():
    """
    Returns a list of all names of encyclopedia entries.
    """
    _, filenames = default_storage.listdir("entries")
    return list(sorted(re.sub(r"\.md$", "", filename)
                for filename in filenames if filename.endswith(".md")))

when I enter anything in the search bar this appears
to me :
enter image description here
so what is the problem??

A: Your model class fields are your attributes, filter function is trying to reach the attribute that doesn't exist.
if your model is called Entry and model field - title, you can import Entry to your views, and filter through its title fields using __contains.
models.py:
class Entry(models.Model):
    title = models.CharField(null=False, blank=False)

views.py:
from myApp.models import Entry
...

def list_entries():
    ...
    data = Entry.objects.filter(title__contains = q)


text:
Q: Flat nested set to nested structs in Go Maybe its just late in the day and this is making my brain melt.
I'm trying to convert a flat list of nested sets into a multi-dimensional nested array.
I have a bunch of structured CMS entries as follows:
entries := []TreeEntry{
        {
            Slug:  "about-us",
            Title: "About us",
            Left:  2,
            Right: 11,
            Level: 1,
        },
        {
            Slug:  "more-about-us",
            Title: "More about us",
            Left:  3,
            Right: 6,
            Level: 2,
        },
        {
            Slug:  "even-more-about-us",
            Title: "Even more about us",
            Left:  4,
            Right: 5,
            Level: 3,
        },
        {
            Slug:  "contact-us",
            Title: "Contact us",
            Left:  2,
            Right: 7,
            Level: 1,
        },
    }

And I want to unflatten them as follows:
entries := []TreeEntry{
        {
            Slug:  "about-us",
            Title: "About us",
            Left:  2,
            Right: 11,
            Level: 1,
            Children: []TreeEntry{
                {
                    Slug:  "more-about-us",
                    Title: "More about us",
                    Left:  3,
                    Right: 6,
                    Level: 2,
                    Children: []TreeEntry{
                        {
                            Slug:  "even-more-about-us",
                            Title: "Even more about us",
                            Left:  4,
                            Right: 5,
                            Level: 3,
                        },
                    },
                },
            },
        },
        {
            Slug:  "contact-us",
            Title: "Contact us",
            Left:  2,
            Right: 7,
            Level: 1,
        },
    }

The aim here is ultimately to return a menu structure with the slugs contact'ed together as appropriate, but some reason, I just cannot get my head around achieving this in Go.
Can anybody point me in the correct direction?
Edit: Added non-working example of what I've attempted:
https://play.golang.org/p/oKWo21lu__7
The results never add below the first level.
Thanks,
J

A: As it turns out, I needed to use pointers to hold the child entries. The following setup works:
type TreeEntry struct {
    Id       int64        `db:"elementId" json:"id"`
    Slug     string       `db:"slug" json:"slug"`
    Title    string       `db:"title" json:"title"`
    Left     int          `db:"lft" json:"-"`
    Right    int          `db:"rgt" json:"-"`
    Level    int          `db:"level" json:"-"`
    Children []*TreeEntry `json:"children"`
}

func (t *TreeEntry) AddNestedChild(newEntry TreeEntry) {
    // If this child is one level below the current node, just add it here for now
    if newEntry.Level == t.Level+1 {
        t.Children = append(t.Children, &newEntry)
    } else {
        // Loop through the children and see if it fits anywhere
        for _, child := range t.Children {
            if newEntry.Left > child.Left && newEntry.Right < child.Right {
                child.AddNestedChild(newEntry)
                break
            }
        }
    }
}


text:
Q: What is the difference between Shrink and Compact in SQL Server CE? I have a method that is run periodically to optimise my application's SQL Server Compact Edition (3.5) database. The existing code uses the Shrink() method:
        SqlCeEngine engine = new SqlCeEngine(dbConnectionString);
        engine.Shrink();

Today I noticed that there's also a Compact() method. Which is preferable for periodic maintenance?

A: From the SQL Server Compact Team Blog:

The difference between these two is
  much similar to Internal and External
  Memory Fragmentation.

  From SqlCeEngine.Shrink documentation,
Reclaims wasted space in the database
  by moving empty and unallocated pages
  to the end of the file, and then
  truncating the file.  You can
  configure a database to automatically
  shrink by setting the autoshrink
  threshold option in connection string.
  Shrink does not create a temporary
  database file.
From SqlCeEngine.Compact documentation,
Reclaims wasted space in the database
  by creating a new database file from
  the existing file.  By creating a new
  database means, it reclaims the free
  space between rows.

  To be more clear, Shrink claims the
  pages which are entirely free or
  unallocated; where as, Compact claims
  the wasted space with in the page too.
  Hence Compact requires creating a new
  database file.


text:
Q: Looping through badly formatted HTML Tables Code jQuery So I have an html table that is being generated by my client. I have zero interest in changing how they generate this code at this time it and neither do they.

                Chef's Selections for Tuesday, April 25, 2017

                SPRING FLING! Please ask us about our Bell's Beer Pairing! May 22nd!

                Soups

                Beef Vegetable

                Cream of Tomato

                Lunch Selections

                Butterflied Hot Dog

                all beef butterflied hot dog, grilled, American cheese, mustard, bacon, pickle spear, French

                fries $6.50

                Pulled BBQ Pork Sliders

                Two tender smoked pulled pork sliders, barbeque sauce, Cheddar cheese, house made coleslaw,

                French fries $8

                Grilled Chicken Avocado Club Sandwich

                Boneless chicken breast char-grilled, avocado, Swiss cheese, bacon, lettuce, tomato, mayonnaise,

                house made macaroni salad $10.50

                Desserts

                Chocolate Oreo Cream Cake | Kentucky Bourbon Pecan Pie

                Double Chocolate Peppermint Brownie w/ Mint Chocolate Chip Ice Cream & Hot Fudge+

                Brownie Bottom Sundae | Hot Fudge Cream Puff

                Crème Brulee+ | Vanilla Cheesecake

                Key Lime Pie | Coconut Macaroon w/ Sorbet++

                + Gluten Free ++ Gluten and Dairy Free

                *

                * These items are cooked to order and the consumption of raw or undercooked meats, fish or shellfish

                may increase your risk of food borne illness.

                Drink Specials

                House Made SANGRIA $6 Glass |  $16 Carafe

                Rotating Wine

                The Prisoner Red Blend, Napa Valley, CA '15 | $66 Btl

                Balletto Pinor Noir, Sonoma, '13 | 8 oz. $15 | Btl $46

                Red Diamond Malbec, Mendoza-Argentina, '12 | 8 oz. $9 | Btl $28

I have another part of this project that I have a form for and I have the values being stored via JSON. With that being said, I would like a way to be able to loop through the table and store the items into arrays and then combine the arrays into one JSON file at the end so that I can use that and compare elsewhere within this project. Here is the code I have for getting this HTML table file and then parsing it partially, but I am stuck in trying to figure out the loop. Here is that code:
$.get('/specials/lunch_klm.html', function(data) {
  var rows = jQuery($.parseHTML(data)).find("tr");
  var results = [];
  var category = [];
  var apps = [];
  var soups = [];
  var entrees = [];
  var desserts = [];
  rows.each(function(i) {
    thiz = jQuery(this);
    var markup = thiz.html();
    var text = $.trim(thiz.text());
    if( text == 'Soups') {
      results.push(text);
    }
  })
  console.log(soups);
}, 'html');

I would like to loop until I hit the text value Soups, then put the next few rows values into the soups array, until I get to "Lunch Selections", and then store just the titles of the entrees, not the descriptions. Any help would be appreciated.

A: table contains rows[], which themselves contain cells[]. You can't get the cells[] directly from the table.
You could use table.getElementsByTagName('td') as a shortcut, provided there are no nested tables.
Otherwise, you should loop through each of the rows[] and in that loop you can loop through the cells[].

var tables = document.getElementsByTagName('table'),
  i;
for (i = 0; i < tables.length; i++) {
  var table = tables[i],
    rows = table.rows,
    rowcount = rows.length,
    r,
    cells, cellcount, c, cell;
  for (r = 0; r < rowcount; r++) {
    cells = rows[r].cells;
    cellcount = cells.length;
    for (c = 0; c < cellcount; c++) {
      cell = cells[c];
      console.log(cell.textContent);
    }
  }
}

      Chef's Selections for Tuesday, April 25, 2017

      SPRING FLING! Please ask us about our Bell's Beer Pairing! May 22nd!

      Soups

      Beef Vegetable

      Cream of Tomato

      Lunch Selections

      Butterflied Hot Dog

      all beef butterflied hot dog, grilled, American cheese, mustard, bacon, pickle spear, French

      fries $6.50

      Pulled BBQ Pork Sliders

      Two tender smoked pulled pork sliders, barbeque sauce, Cheddar cheese, house made coleslaw,

      French fries $8

      Grilled Chicken Avocado Club Sandwich

      Boneless chicken breast char-grilled, avocado, Swiss cheese, bacon, lettuce, tomato, mayonnaise,

      house made macaroni salad $10.50

      Desserts

      Chocolate Oreo Cream Cake | Kentucky Bourbon Pecan Pie

      Double Chocolate Peppermint Brownie w/ Mint Chocolate Chip Ice Cream & Hot Fudge+

      Brownie Bottom Sundae | Hot Fudge Cream Puff

      Crème Brulee+ | Vanilla Cheesecake

      Key Lime Pie | Coconut Macaroon w/ Sorbet++

      + Gluten Free ++ Gluten and Dairy Free

      *

      * These items are cooked to order and the consumption of raw or undercooked meats, fish or shellfish

      may increase your risk of food borne illness.

      Drink Specials

      House Made SANGRIA $6 Glass |  $16 Carafe

      Rotating Wine

      The Prisoner Red Blend, Napa Valley, CA '15 | $66 Btl

      Balletto Pinor Noir, Sonoma, '13 | 8 oz. $15 | Btl $46

      Red Diamond Malbec, Mendoza-Argentina, '12 | 8 oz. $9 | Btl $28

A: You would probably need a piece of logic like this:
var str = "

            Chef's Selections for Tuesday, April 25, 2017

            SPRING FLING! Please ask us about our Bell's Beer Pairing! May 22nd!

            Soups

            Beef Vegetable

            Cream of Tomato

            Lunch Selections

            Butterflied Hot Dog

",
  html = $.parseHTML( str ),
  results = [],
  soups = [],
  entrees = [];

var currentArr = results;

$.each( html, function( i, el ) {
  var t = $(el).find("font").text();

  if ("Soups" == t) {
    results.push("
" + t + "
");
    currentArr = soups;
  }
  else if ("Lunch Selections" == t) {
    results.push("
" + t + "
");
    currentArr = entrees;
  }
  // you may need another if condition here to switch currentArr back to results
  else {
    currentArr.push("
" + t + "
");
  }

});

Please refer to this to see how it runs in action. Hope that can help.

A: This would get you started. It is difficult however to separate items from descriptions of items without some sort of classes added to the rows. I started filtering these descriptions by using an array of ignoreText which works on a few descriptions for now
If it was feasible to have classes added in back end it would greatly simplify problem

// predefine the categories in array
// if needed could generate these by inspecting `font-size`
var cats = ['Soups', 'Lunch Selections', 'Desserts', 'Drink Specials','Rotating Wine'],
  ignoreText = ['*', 'may increase'],
  currCat = null,
  // create object with cats as keys and empty arrays to push data to
  items = cats.reduce(function(a, c) {
    a[c] = [];
    return a;
  }, {});

// would be what you receive in your ajax, used helper function for demo
var ajaxData = get_data()

$(ajaxData).filter('table').each(function() {
  var txt = $(this).text().trim(),
    isCatHeading = cats.indexOf(txt) > -1;

  if (isCatHeading) {
    currCat = txt
  }

  if (currCat && !isCatHeading) {
    // see if start of txt is in the "ignore" array
    var isIgnoreText = ignoreText.filter(function(reg) {
      return txt.indexOf(reg) === 0;
    }).length;

    if (!isIgnoreText) {
      items[currCat].push(txt)
    }
  }
});
// display data in demo
$('pre').text(JSON.stringify(items, null, 4));

//helper function for demo
function get_data(){
  return `

        Chef's Selections for Tuesday, April 25, 2017

        SPRING FLING! Please ask us about our Bell's Beer Pairing! May 22nd!

        Soups

        Beef Vegetable

        Cream of Tomato

        Lunch Selections

        Butterflied Hot Dog

        all beef butterflied hot dog, grilled, American cheese, mustard, bacon, pickle spear, French

        fries $6.50

        Pulled BBQ Pork Sliders

        Two tender smoked pulled pork sliders, barbeque sauce, Cheddar cheese, house made coleslaw,

        French fries $8

        Grilled Chicken Avocado Club Sandwich

        Boneless chicken breast char-grilled, avocado, Swiss cheese, bacon, lettuce, tomato, mayonnaise,

        house made macaroni salad $10.50

        Desserts

        Chocolate Oreo Cream Cake | Kentucky Bourbon Pecan Pie

        Double Chocolate Peppermint Brownie w/ Mint Chocolate Chip Ice Cream & Hot Fudge+

        Brownie Bottom Sundae | Hot Fudge Cream Puff

        Crème Brulee+ | Vanilla Cheesecake

        Key Lime Pie | Coconut Macaroon w/ Sorbet++

        + Gluten Free ++ Gluten and Dairy Free

        *

        * These items are cooked to order and the consumption of raw or undercooked meats, fish or shellfish

        may increase your risk of food borne illness.

        Drink Specials

        House Made SANGRIA $6 Glass |  $16 Carafe

        Rotating Wine

        The Prisoner Red Blend, Napa Valley, CA '15 | $66 Btl

        Balletto Pinor Noir, Sonoma, '13 | 8 oz. $15 | Btl $46

        Red Diamond Malbec, Mendoza-Argentina, '12 | 8 oz. $9 | Btl $28

`

}

Data

Test


text:
Q: Cast Button not showing up I am trying to create a ChomeCast sender app with Android Studio.  I have implemented all code need to be able to Add the Cast Button but it's not available
Here is my Code.
build.gradle
    apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.3"

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.+'
    compile 'com.google.android.gms:play-services:4.3.+'
    compile 'com.android.support:mediarouter-v7:19.+'

}

res/menu/main.xml
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.castbuttontest.app.MainActivity" >

    <item
        android:id="@+id/media_route_menu_item"
        android:title="@string/media_route_menu_title"
        app:actionProviderClass="android.support.v7.app.MediaRouteActionProvider"
        app:showAsAction="always"/>
</menu>

MainActivity.java
    package com.example.castbuttontest.app;

    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.support.v7.app.MediaRouteActionProvider;
    import android.support.v7.media.MediaRouteSelector;
    import android.support.v7.media.MediaRouter;
    import android.view.Menu;
    import android.view.MenuItem;

import com.google.android.gms.cast.Cast;
import com.google.android.gms.cast.CastDevice;
import com.google.android.gms.cast.CastMediaControlIntent;
import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends ActionBarActivity {

    MediaRouter mediaRouter;
    MediaRouteSelector mediaRouteSelector;
    MediaRouter.Callback myMediaRouterCallBack = new MediaRouter.Callback() {
        @Override
        public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo route) {
            CastDevice device = CastDevice.getFromBundle(route.getExtras());

        }

        @Override
        public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo route) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        String APP_ID = "F6D3E50B";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mediaRouter = MediaRouter.getInstance(this);
        mediaRouteSelector = new MediaRouteSelector.Builder()
                //.addControlCategory(CastMediaControlIntent.categoryForCast(APP_ID))
                .addControlCategory(CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID)
                .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mediaRouter.addCallback(mediaRouteSelector, myMediaRouterCallBack,MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
    }

    @Override
    protected void onStop() {
        mediaRouter.removeCallback(myMediaRouterCallBack);
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem mediaRouterItem = menu.findItem(R.id.media_route_menu_item);
        MediaRouteActionProvider provider = (MediaRouteActionProvider) MenuItemCompat.getActionProvider(mediaRouterItem);
        provider.setRouteSelector(mediaRouteSelector);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        return super.onOptionsItemSelected(item);
    }

}

Can you tell where the problem is located?
Thanks in Advance
EDIT:
I have finally solved the problem .I have created a new Empty project and re-written the code by following the Sender App tutorial (Link):
MainActivity.java
    /*
   Copyright 2014 Charles-Eugene LOUBAO

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package cf.charly1811.android.sample.MediaRouteProvider;

import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.MediaRouteActionProvider;
import android.support.v7.media.MediaRouteSelector;
import android.support.v7.media.MediaRouter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.cast.CastDevice;
import com.google.android.gms.cast.CastMediaControlIntent;

public class MainActivity extends ActionBarActivity {
    /**
     * This sample shows how to add the Cast Button to the action bar using MediaRouterProvider
     * @see "https://developers.google.com/cast/docs/android_sender"
     */
    public static final String TAG = MainActivity.class.getSimpleName();
    String APP_ID = "F6D3E50B";

    MediaRouter mediaRouter;
    MediaRouteSelector mediaRouteSelector;
    MediaRouter.Callback mMediaRouterCallback;
    CastDevice mCastDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaRouter = MediaRouter.getInstance(this);
        mediaRouteSelector = new MediaRouteSelector.Builder()
                .addControlCategory(CastMediaControlIntent.categoryForCast(APP_ID))
                .build();

        mMediaRouterCallback = new MediaRouter.Callback() {
            @Override
            public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo route) {
                super.onRouteSelected(router, route);
                Log.d(TAG, "Connected to "+ route.getName());
                mCastDevice = CastDevice.getFromBundle(route.getExtras());
                Toast.makeText(getApplicationContext(), "Connected to "+route.getName(),Toast.LENGTH_LONG).show();
            }

            @Override
            public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo route) {
                super.onRouteUnselected(router, route);
                mCastDevice = null;
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        mediaRouter.addCallback(mediaRouteSelector,mMediaRouterCallback,MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
        if(isFinishing())
        {
            mediaRouter.removeCallback(mMediaRouterCallback);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem media_route_menu_item = menu.findItem(R.id.media_route_menu_item);
        MediaRouteActionProvider provider = (MediaRouteActionProvider) MenuItemCompat.getActionProvider(media_route_menu_item);
        provider.setRouteSelector(mediaRouteSelector);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        /*
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        */
        return super.onOptionsItemSelected(item);
    }
}

And now it works properly. The Icon is now available and I can connect to my Chromecast. I am not sure but I think the problem was about the Instance of MediaRouter.Callback;
PS: I have uploaded the full code on GitHub . You can check it out. (Link)

A: Rewriting it all from beginning doesn't actually show anyone where the problem was...
You have
.addControlCategory(CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID)
instead of
.addControlCategory(CastMediaControlIntent.categoryForCast(CastMediaControlIntent.DEFAULT_MEDIA_RECEIVER_APPLICATION_ID))
You were passing APP_ID directly into category. I guess category has special format and APP_ID isn't exactly that. I did the same mistake. :)

A: I have finally solved the problem .I have created a new Empty project and re-written the code by following the Sender App tutorial (Link):
MainActivity.java
    /*
   Copyright 2014 Charles-Eugene LOUBAO

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package cf.charly1811.android.sample.MediaRouteProvider;

import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.MediaRouteActionProvider;
import android.support.v7.media.MediaRouteSelector;
import android.support.v7.media.MediaRouter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.cast.CastDevice;
import com.google.android.gms.cast.CastMediaControlIntent;

public class MainActivity extends ActionBarActivity {
    /**
     * This sample shows how to add the Cast Button to the action bar using MediaRouterProvider
     * @see "https://developers.google.com/cast/docs/android_sender"
     */
    public static final String TAG = MainActivity.class.getSimpleName();
    String APP_ID = "F6D3E50B";

    MediaRouter mediaRouter;
    MediaRouteSelector mediaRouteSelector;
    MediaRouter.Callback mMediaRouterCallback;
    CastDevice mCastDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaRouter = MediaRouter.getInstance(this);
        mediaRouteSelector = new MediaRouteSelector.Builder()
                .addControlCategory(CastMediaControlIntent.categoryForCast(APP_ID))
                .build();

        mMediaRouterCallback = new MediaRouter.Callback() {
            @Override
            public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo route) {
                super.onRouteSelected(router, route);
                Log.d(TAG, "Connected to "+ route.getName());
                mCastDevice = CastDevice.getFromBundle(route.getExtras());
                Toast.makeText(getApplicationContext(), "Connected to "+route.getName(),Toast.LENGTH_LONG).show();
            }

            @Override
            public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo route) {
                super.onRouteUnselected(router, route);
                mCastDevice = null;
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        mediaRouter.addCallback(mediaRouteSelector,mMediaRouterCallback,MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
        if(isFinishing())
        {
            mediaRouter.removeCallback(mMediaRouterCallback);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem media_route_menu_item = menu.findItem(R.id.media_route_menu_item);
        MediaRouteActionProvider provider = (MediaRouteActionProvider) MenuItemCompat.getActionProvider(media_route_menu_item);
        provider.setRouteSelector(mediaRouteSelector);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        /*
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        */
        return super.onOptionsItemSelected(item);
    }
}

And now it works properly. The Icon is now available and I can connect to my Chromecast. I am not sure but I think the problem was about the Instance of MediaRouter.Callback;
PS: I have uploaded the full code on GitHub . You can check it out. (Link)

A: I have struggled to find a solution to this, and nothing I found helped. Until I eventually found this link

A   Unavailable: While Cast receivers are not available, the Cast button does not appear

Check if you have any devices to CAST TO in your vicinity. I didn't, so the button was hidden by design. You can easily just check, go to youtube app, and there's no cast button there either when there's not a receiver app present. Hope this saves someone some time cause I had a hard time trying to see why it isn't appearing.


text:
Q: Basic Cloud Firestore security rules setup I am currently using this default code to secure my Cloud Firestore database:
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

This code works fine and the simulation is fine.
I tried to update the code and use the new default code I find in every guide:
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

But this code fails every time, the access is not granted.
In the simulation, I just try to read a document in a Collection named "parameters".
Am I missing something here? My plan is to harden the security access afterwards.

A: Ok my bad, I actually realised that the database access rules and the storage access rules have their own and separate security panels.
I was trying to update the storage rules with the default database rules...


text:
Q: Get number from dial in Android? I am working on an application in which I have to make call from my application using my PHP server.
I have a condition in which, whenever user presses the Green call button of Android Device and after dialing number, I have to give user an option to call from my App or normal SIM. I have done that too.
Now I want to get the number which I have dialed on the dialer before switching to the application.
Means if User selects my application to call then I must have number dialed on the phone Dial.
I am using the below code to generate the pop up to use my application for calling. The code is written as Intent filter in my manifest inside the specific activity.
<activity
            android:name="com.tv.longdistcall.PlaceLongDistCall"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.CALL_BUTTON" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.CALL_PRIVILEGED" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:scheme="tel" />
            </intent-filter>
        </activity>

Please suggest me, how to get the number dialed on the dialer before switching to the activity.

A: You need to create a new BroadcastReceiver with NEW_OUTGOING_CALL intent filter. This receiver intercepts every call to CALL_PRIVILEGED or CALL actions on the device regardless of what app is the one targeted.
The destination number can be found on the receiver's intent extras in Intent.EXTRA_PHONE_NUMBER.


text:
Q: What is Mathematical formulation of Holographic principle? What is Mathematical formulation of Holographic principle

The holographic principle is a property of quantum gravity and string theories which states that the description of a volume of space can be thought of as encoded on a boundary to the region—preferably a light-like boundary like a gravitational horizon.

A: It is maybe an underappreciated fact that the old relation between the 2d Wess-Zumino-Witten model on a Lie group $G$ and the 3d $G$-Chern-Simons theory is an example of the holographic principle. See for instance

*

*Sergei Gukov, Emil Martinec, Gregory Moore, Andrew Strominger, Chern-Simons Gauge Theory and the AdS(3)/CFT(2) Correspondence (arXiv:hep-th/0403225)

and see on the nLab at AdS3-CFT2 and CS-WZW correspondence for more pointers.
Now the 2dWZW/3dCS correspondence is, to a considerable degree of detail, a mathematical theorem. At the heart this says that the geometric quantization (which is the mathematically precise formulation of quantization) of 3d CS over a (punctured) surface $\Sigma$ yields the spaces of states of 3d CS over $\Sigma$ for each choice of polarization of the theory as a projectively flat bundle -- the Hitchin connection -- over the moduli space of conformal structures on $\Sigma$, and that this are the spaces of conformal blocks of the 2d WZW model with worldvolume $\Sigma$.
For a review of what exactly this means a good place to start is around p. 30 of

*

*Krzysztof Gawędzki, Conformal field theory: a case study (arXiv:hep-th/9904145)

Another maybe underappreciated fact is that in

*

*Edward Witten, AdS/CFT Correspondence And Topological Field Theory JHEP 9812:012, 1998, (arXiv:hep-th/9812012)

it is argued that also AdS5-CFT4 holography as well as AdS7-CFT6 holography, at least, are all controled by just the higher Chern-Simons term on the gravity side, at least as far as the conformal blocks on the CFT side are concerned.
Notably this means by AdS7-CFT6 holography that the 6d (2,0)-superconformal QFT on the M5-brane is determined by the 7d Chern-Simons theory inside the 11d Chern-Simons term of 11-dimensional supergravity after KK-reduction on a 4-sphere.
Indeed, this is how Witten proposed to capture the M5-brane theory in

*

*Edward Witten, Five-Brane Effective Action In M-Theory J. Geom. Phys.22:103-133,1997 (arXiv:hep-th/9610234)

(there for the simple special case of the abelian theory on a single M5): one can formalize what it means to apply geometric quantization in codimension 1 to the 7d Chern-Simons theory to obtain its space of states, and according to Witten's argument this is, holographically, the space of conformal blocks of the 6d conformal field theory on the 5-brane.
It was the desire to give a fully mathematically precise formulation of this "holographic quantization" of the single M5-brane that led to the seminal article

*

*Mike Hopkins, Isadore Singer, Quadratic Functions in Geometry, Topology, and M-Theory, J. Differential Geom. Volume 70, Number 3 (2005), 329-452

maybe one of the high points of deep mathematics motivated by or found in string/M-theory.
(Incidentally, the abelian 7d Chern-Simons term that Witten considered in the above article is well known to receive quantum corrections from a Green-Schwarz mechanism in 11d sugra and from the "flux quantization condition". The full 7d Chern-Simons term in 11d sugram KK-reduced on the 4-sphere is that of a nonabelian Chern-Simons theory. We wrote that out as an extended prequantum field theory in the articles here. It is natural to expect that the holographic dual of this complete nonabelian Chern-Simons term of 11d sugra is the 6d-theory on the 5-brane with its nonabelian 2-form field. But this remains to be analyzed.)
In order to find more instances of mathematically precise aspects of holography, it also serves to go down in dimension from WZW2/CS3 to the holographic relation between point particle quantum mechanics and the 2d topological string.
A semi-formalization of this is Kontsevich's formal deformation quantization of any Poisson manifold, which was later understood in

*

*Alberto Cattaneo, Giovanni Felder, Poisson sigma models and deformation quantization, Mod. Phys. Lett. A 16, 179–190 (2001) (hep-th/0102208)

to be secretly the 3-point function of the open topological string propagating on the Poisson manifold as given by the Poisson sigma-model.
Now Kontsevich's formula is rigorous mathematics, and the interpretation by Cattaneo-Felder in terms of BV-quantization is written at the level of rigour at least of mathematical physics. Therefore I would regard this as one more mathematically precise incarnation of the holographic principle.
Notice that there is a slight variant of this holographic quantization of 1d quantum mechanics in terms of 2d topological string given by Gukov-Witten's quantization via the A-model, where the particle with phase space a symplectic manifold is quantized as the boundary theory of the topological A-model string (a limit of the topological Poisson model string).
Recently my student Joost Nuiten has described a rigorous non-perturbative version of this holographic quantization of particles with phase space a Poisson manifold as the boundary theory of the non-perturbative Poisson sigma-model. This is described in the examples section of

*

*Joost Nuiten, Cohomological quantization of local prequantum boundary field theory, thesis, Utrecht 2013

He also describes other rigorous instances of holographic quantization. For instance he indicates how the heterotic string is quantized as the boundary theory of the M2-brane ending on an "M9-brane" heterotic boundary spacetime of an 11d Hořava-Witten spacetime. A survey of this is also in the examples-section in the nLab entry on motivic quantization.
The mechanism described there I suspect gives a general mathematical rigorous formalization of holography. But this needs to be further explored.


text:
Q: ¿como aumentar los dias de un input date sin contar los domingos? Tengo un input date donde pongo una fecha y otro input date donde aparece N dias despues del dia que llene en el primer input date, pero quiero los N dias no cuenten a los domingos.
Lo que hice hasta ahora que es facil es aumentar los N dias pero contando con domingo
CODIGO

function myFunction() {

       document.getElementById("myDate1").value=document.getElementById("myDate").value;
       document.getElementById("myDate1").stepUp(5);
    }
    Date: <input type="date" id="myDate" >

Click the button to increment the value of the date field by 5 days (each time you click).

    <button onclick="myFunction()">Try it</button>
    <input type="date" id="myDate1" >

Note: The stepUp() method is not supported by Internet Explorer.

Note: input elements with type="date" do not show as any date field/calendar in Firefox or in IE 11 and earlier versions.

A: Puedes usar una librería llamada moment.js que te facilita el trabajo con fechas, usar el método day() que te proporciona dicha librería para conocer que día de la semana es y usar un condicional para filtrar según sea necesario.
A continuación te expongo un ejemplo de su uso:

var campoFecha = document.getElementById("fecha");
var campoDiaSemana = document.getElementById("dia-semana");

campoFecha.value = moment().format("YYYY-MM-DD");

campoFecha.addEventListener("input", function() {
  var fecha = moment(campoFecha.value);
  campoDiaSemana.value = fecha.day();
});
<!doctype html>

        <meta charset="UTF-8">
        <title>Trabajando fechas con moments</title>

        Edita este campo
        <input type="date" id="fecha">

        Dia de la semana
        <input id="dia-semana" disabled>

A: Aqui tienes un ejemplo en JS.

var startDate = "9-DEC-2011";
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "", noOfDaysToAdd = 13, count = 0;
while(count < noOfDaysToAdd){
    endDate = new Date(startDate.setDate(startDate.getDate() + 1));
    if(endDate.getDay() != 0 && endDate.getDay() != 6){
       //Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
       count++;
    }
}
alert(endDate);//You can format this date as per your requirement

el Demo del JS


text:
Q: Nodejs: managing distributed transactions like java ee One of the things that the Java enterprise platform facilitates is transaction management, and more so, distributed transaction management when multiple XA resources (database, message queues, resource adapters, etc)  are in play.
Allowing for transactions to be rolled back should any particular participant fail for some reason.
Is there anything of that nature available for Nodejs?
I have searched but the only results that I have found thusfar has been related to database transactions and even then it seems to be more a case of letting the database handle the transaction management rather than at an application level.

A: Java EE is great choice for the requirements you have: distributed transactions management mechanism using multiple XA resources (database, message queues). Node is not (and in my opinion will never be) suitable for this.
Good example could be LevelDB database: you start with really basic functionality - just key-value storage, and you deliberately add functionality which you need, and not more. So the way is:

from initial minimum -> to target solution (by adding, implementing)

In Java EE - you have huge all-in-one solution, and just pick what you need.
The way is:

from initial all-in-one solution -> to target one (by removing, ignoring)

Neither of choices is a silver bullet, it just depends on your requirements.


text:
Q: Page Control Navigation Symbol? Could someone point me in the right direction on how you get your Page Controller to show the navigation symbol like this?

I couldn't really describe it well, and couldn't find much relevant information on the internet. Anything would be great, thanks!

A: This is most likely a custom UIPageController.
Or you might be able to add a UIImageView to the left of the page control and when you try to swipe, set that image view to highlighted and you'll get the same effect.
Here's a custom page control, DDPageControl
https://github.com/ddeville/DDPageControl


text:
Q: If Else not allowing color change? I would like to have 3 If/Else If statements that change the color of a background depending on the value received. So Far my code is:
/////Activity Response Selection/////
@IBAction func ActivityAction(sender: AnyObject) {

    if(ActivitySeg.selectedSegmentIndex == 0)
    {
    ActivityVal.text = "Absent"
    ActivityNum.text = "0"
    }
    else if(ActivitySeg.selectedSegmentIndex == 1)
    {
    ActivityVal.text = "Arms/Legs Flexed"
    ActivityNum.text = "1"
    }
    else if(ActivitySeg.selectedSegmentIndex == 2)
    {
    ActivityVal.text = "Active Movement"
    ActivityNum.text = "2"
    }

let ActivityIn = Double(ActivityNum.text!)
let PulseIn = Double(PulseNum.text!)
let GrimIn = Double(GrimNum.text!)
let AppIn = Double(AppNum.text!)
let RespIn = Double(RespNum.text!)

let product = ActivityIn! + PulseIn! + GrimIn! + AppIn! + RespIn!

TotalVal.text = "\(product)"
TotalVal.text = NSString(format: "APGAR Score: %2.0f", product)as String

if product >= 7.0 {
    TotalVal.backgroundColor = UIColor.greenColor()
}
else if product <= 6.0{
    TotalVal.backgroundColor = UIColor.yellowColor()
}
else if product <= 3.0 {
    TotalVal.backgroundColor = UIColor.redColor()
}

}
Where I have any value greater/equal to 7 as free.
Equal/Less than 6 is a yellow background.
Equal/Less than 3 is a red background.
My problem lies that the applications will only utilize the Green and Yellow colors, completely ignoring the red. How can I active the red?

A: The problem is your last else if statement.
Your red (<= 3) will also be smaller than 6, so all red ones will be caught in the first else if, never made into the second.
To correct it, you can simply swap the two else if brackets around. Check red first, then yellow.
Or to keep consistency, change it to:
if product >= 7.0 {
    TotalVal.backgroundColor = UIColor.greenColor()
} else if product > 3.0 {
    TotalVal.backgroundColor = UIColor.yellowColor()
} else {
    TotalVal.backgroundColor = UIColor.redColor()
}

Its always a good idea to check for the same inequality signs to avoid this kind of bugs.


text:
Q: Crunching numbers according to user-defined formulas: best approach? I have been trying different solutions to this problem, including a completely custom data processing module; now I feel like I've run out of options and was wondering what people thought was the best approach. Here's what I am trying to do:

*

*There is a Windows service that collects data from a fairly obscure accounting system. Reads a fairly large CSV and puts that into SQL Server.

*What gets written out to the server are raw data. So in essence, we have daily account balances that are captured and persisted (the records are simple, consisting of an account name, balance and time stamp).

*To process these data, we have a series of datapoints, each of which have a formula (ie. datapoint "farm widget sales" would have a formula like "123 + 456 + 789 - 978 - 654 - 321" where each of these numbers represent account numbers). We want to be able to apply different time dimensions to each of the datapoints, such as "Today", "MTD", "Q2 2011", etc.

This solution will ultimately be using PerformancePoint Services for its presentation layer.
What I am trying to figure out is what is the best approach to crunching these numbers, other than doing it myself in code. I've looked at PowerPivot and using SQL Server facilities for this but I don't know that they are capable of doing what I need.
The data processing would have to run through all of the raw data, and evaluate the formulae against the different time dimensions required. I have tried using a PowerPivot measure for this but I think the logic is too complicated for DAX (basically I would have to look at the formula column for a specific datapoint, figure out all the accounts I have to fetch, perform a sum based on time dimension, and then finally compute the formula itself).
Have any of you had any experience with a similar problem where you were able to leverage any of the many features of SharePoint?

A: I'd reckon you're better building an OLAP cube out of the raw data using SQL Server Analysis Services, then surfacing that through PerformancePoint or PowerPivot.
Within the OLAP cube you could build calculated measures written in MDX to apply the algorithm you need.

A: You gave your own answer when you said "dimensions":
Build a Cube in SSAS (SQL Server Analysis Services) that uses your raw data as it's datasource.
P.S. (the actual word used in SSAS describing a way of looking at data / filtering data is: a "dimension" :-D)
Excel (2010) in combination with this cube and Powerpivot, or SP2010 + Perf. Point (and PowerPivot) can then be used to build some pretty amazing KPI's, Dashboards etc.!


text:
Q: Is it safe to use .Result in a task that IsCompleted? Consider the following code:
Task<bool> task = SomeAsyncOperation();

// Some more code in which the task might be awaited

return task.IsCompleted && !task.IsFaulted && task.Result;

Using .Result in an async method is generally discouraged, since it may lead to a deadlock. However, since here it will only be called if the task IsCompleted, I'd say it's safe to do it. Am I right?