text:
Q: collection_select with one-to-many / many-to-many How do I use collection_select in a One-ToMany-ToOne scenario. Here is what I have
The application manages projects. Each project has a different set of languages that it supports. People can now post messages in the projects
in one of the languages that the project supports.
Simplified class structure:
class Project < ApplicationRecord
  has_many :languageprojects
  has_many :languages, through: :languageprojects
end

class Language < ApplicationRecord
  has_many :languageprojects
  has_many :projects, through: :languageprojects
  def to_s
    language
  end
end

class Languageproject < ApplicationRecord
  belongs_to :language
  belongs_to :project
end

class Projectmessage < ApplicationRecord
  belongs_to :language
  belongs_to :project
end

How to I format the collection_select in the form where the users enters a new message (Projectmessage). The user must be able to select one of the languages that the project supports.
I want to display the languages name in the native language of the user thus the languages are stored in the table LANGUAGES in the format
en
fr
ru

Then I keep the translations of these languages in the locales folder under en.yml, fr.yml, ru.yml. E.g.:
en:
  language_en: English
  language_fr: French
  language_ru: Russian

I got so far:
<%= form.collection_select :language_id, Languageproject.all, :id, :language, { include_blank: false }, { class: 'form-control' } %>

This shows the values of the table entries (i.e. en, fr, ru). How do I incorporate the language translation? I want the dropdown to show English, French, Russian
Obviously I can always code it instead of using 'collection_select' but am hoping for a 'Ruby' way of solving this.

A: Try using options_for_select
<%= f.select :language_id, options_for_select(@language_project.languages.all.map{|l| [l.language, l.id]}, @language.id), include_blank: false, class: 'form-control' %>


text:
Q: Call method in sub widget from parent I have a method in my parent widget that runs and updates a boolean. Whenever the value is changed, a method needs to be run in a child widget, using the changed value. What is the best way to trigger that action from the parent?
Both widgets are stateful widgets.

A: You could either inject the parent's method as a callback to the child or dispatch a notification from the child and then listen for it in the parent.
The latter is a cleaner and more reusable way, since it'll improve your child reusability.
You can check here for a very good guide on how to do it!

A: The answer from magicleon94 was pretty good, and would have worked if I needed to update a widget with new information. I will probably reference that for some other issues I am working on. For this issue, I needed to run a method to return markers for a mapWidget, based on data from a parent, when that data changed. I found the best way to do that was using a streamController, as outlined by this StackOverflow post. Whenever I updated the value, I called add on the stream, and then received the update in my child class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Validation Service - Unsuccessful validation for Email message I'm trying to create an Email HTML template using XHTML document.
I was trying to test the document using "Markup Validation Service" but without success. I got 2 errors and I was trying to figure it out and did some changes but it doesn't fix.
This is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Welcome</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Lato" />

              We're so happy!!!

              We founded this because we wanted to create a trustworthy app.

Extension

                     <button style="margin:33px 0 0 15px;color: black;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;
    font-size: 14px; background-color: Transparent;
    background-repeat:no-repeat;
    border: 1px solid black;
    cursor:pointer;overflow: hidden;outline:none;">GET THE EXTENSION</button>

Application

                     <button style="margin:10px 0 0 50px;color: black;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;
    font-size: 16px; background-color: Transparent;
    background-repeat:no-repeat;
    border: 1px solid black;
    cursor:pointer;overflow: hidden;outline:none;">GET THE APP</button>

              ® Copyright © 2017

What am I missing ?
Thank you.

A: The Markup Validation Service says:

Line 84, Column 70: document type does not allow element "td" here;
  assuming missing "tr" start-tag

A  must be inside of a
.

This is the HTML.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Welcome</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Lato" />

                    We're so happy!!!

 We founded this because we wanted to create a trustworthy app.

Extension

                                  <button style="margin:33px 0 0 15px;color: black;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;
    font-size: 14px; background-color: Transparent;
    background-repeat:no-repeat;
    border: 1px solid black;
    cursor:pointer;overflow: hidden;outline:none;">
                  GET THE EXTENSION
                 </button>

Application

                                  <button style="margin:10px 0 0 50px;color: black;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;
    font-size: 16px; background-color: Transparent;
    background-repeat:no-repeat;
    border: 1px solid black;
    cursor:pointer;overflow: hidden;outline:none;">
                  GET THE APP
                 </button>

                    ® Copyright © 2017


text:
Q: nth-of-type not working as expected I've got some simple markup

And I'm using the following CSS to try and target the .11 and .12
div div:nth-of-type(1) { // some rules for the first div }
div div:nth-of-type(2) { // some rules for the second div }

However, it seems that div .121 is being targeted by the first rule. Is there a reason for this?
How would i target .11 in the first rule and .12 in the second only?

A: It's because div.121 is the first div-type child of div.12.
To exclude it, qualify your div.1's class and add the child combinator >, which will only match children of div.1 rather than any element inside it (this answer illustrates another example):
div.1 > div:nth-of-type(1)
div.1 > div:nth-of-type(2)

A: Because div.121 is also the first div that is a child of a div, and is therefore matched by the same selector.


text: Q: Criterion for vanishing of Hom sheaf Let $X$ be a scheme and $\mathcal{F}$ be an $\mathcal{O}_X$-module which is supported in a proper subscheme $Y$ of $X$ in the sense that $Y$ is of codimension at least $1$ in $X$. We know that if $\mathcal{O}_X$ is torsion free then the $\mathcal{H}om$-sheaf $\mathcal{H}om_X(\mathcal{F},\mathcal{O}_X)$ is zero. Is there any alternative condition on $\mathcal{O}_X$ under which the vanishing of the $\mathcal{H}om$ sheaf still holds?


text:
Q: Dont want to add header rows when i have looped through first file What am i trying to do
Basically im looping through all my folders to catch if there is a .txt document.
When i have loop through this i want to add the headers and rows from this document to a DataTable. My columns are always the same from each file.
The code i used so far
DataTable csvData = new DataTable();

string[] fullpath = Directory.GetFiles(@"D:\Stack", "*.txt", System.IO.SearchOption.AllDirectories);

            foreach(string s in fullpath)
            {

                DataTable eachfile = new DataTable();

            using (TextFieldParser csvReader = new TextFieldParser(s))
            {

                        csvReader.SetDelimiters(new string[] { ";" });
                        csvReader.HasFieldsEnclosedInQuotes = false;
                        string[] colFields = csvReader.ReadFields();
                        foreach (string column in colFields)
                        {
                            DataColumn datecolumn = new DataColumn(column);
                            datecolumn.AllowDBNull = true;
                        eachfile.Columns.Add(datecolumn);
                        }

                    eachfile.Columns.Add("SalesNo");
                    eachfile.Columns.Add("Date");

                    while (!csvReader.EndOfData)
                    {

                        csvReader.SetDelimiters(new string[] { "," });

                        string[] fieldData = csvReader.ReadFields();
                        //Making empty value as null
                        for (int i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                        }

                        Match conum = Regex.Match(s, @"SalesNo\d+");
                        Match cycle = Regex.Match(s, @"Date\d{8}");

                        DataRow row = eachfile.NewRow();

                        //Alternativ
                        //row["FirstName"] = fieldData[0];
                        row[0] = fieldData[0];
                        row[1] = fieldData[1];
                        row[2] = conum;
                        row[3] = cycle;

                        eachfile.Rows.Add(row);

                        csvData = eachfile.Copy();
                    }

                }
            }
        }

What is my issue
Well in my code i try to add data to a DataTable called eachfile. However i cannot add this to my main DataTable csvData, since it will be overwritten eachtime. What I really wanted to is to collect all my data into one DataTable csvData but only add the HeaderRows once (from first file i loop through)
What do i need
I need to re-write the code i think so when i loop through first file, it uses the code here which adds my header to the csvData DataTable
 csvReader.SetDelimiters(new string[] { ";" });
                        csvReader.HasFieldsEnclosedInQuotes = false;
                        string[] colFields = csvReader.ReadFields();
                        foreach (string column in colFields)
                        {
                            DataColumn datecolumn = new DataColumn(column);
                            datecolumn.AllowDBNull = true;
                        eachfile.Columns.Add(datecolumn);
                        }

                    eachfile.Columns.Add("CoNum");
                    eachfile.Columns.Add("CycleDate");

When this is done and i have inserted data from the first file, i do not want to add the header rows again for the next file, since it will fail due to duplicate names. But only add the data to the already existing csvData (and not overwriting the previous added data)
What do i think i can do?
I think i need to count if it is the first file, and do something like this
where i count the number of fullpath and if that is 1 i go through the headers else i go to my else where i readline first so i wont get first row?
 if (fullpath.Count() == 1)
                    {

                        csvReader.SetDelimiters(new string[] { ";" });
                        csvReader.HasFieldsEnclosedInQuotes = false;
                        string[] colFields = csvReader.ReadFields();
                        foreach (string column in colFields)
                        {
                            DataColumn datecolumn = new DataColumn(column);
                            datecolumn.AllowDBNull = true;
                            csvData.Columns.Add(datecolumn);
                        }

                        csvData.Columns.Add("CoNum");
                        csvData.Columns.Add("CycleDate");

                        while (!csvReader.EndOfData)
                        {

                            csvReader.SetDelimiters(new string[] { "," });

                            string[] fieldData = csvReader.ReadFields();
                            //Making empty value as null
                            for (int i = 0; i < fieldData.Length; i++)
                            {
                                if (fieldData[i] == "")
                                {
                                    fieldData[i] = null;
                                }
                            }

                            Match conum = Regex.Match(s, @"CoNum\d+");
                            Match cycle = Regex.Match(s, @"CycleDate\d{8}");

                            DataRow row = csvData.NewRow();

                            //Alternativ
                            //row["FirstName"] = fieldData[0];
                            row[0] = fieldData[0];
                            row[1] = fieldData[1];
                            row[2] = conum;
                            row[3] = cycle;

                            csvData.Rows.Add(row);
                        }
                    }
                    else
                    {
                        csvReader.ReadLine();
                        while (!csvReader.EndOfData)
                        {

                            csvReader.SetDelimiters(new string[] { "," });

                            string[] fieldData = csvReader.ReadFields();
                            //Making empty value as null
                            for (int i = 0; i < fieldData.Length; i++)
                            {
                                if (fieldData[i] == "")
                                {
                                    fieldData[i] = null;
                                }
                            }

                            Match conum = Regex.Match(s, @"CoNum\d+");
                            Match cycle = Regex.Match(s, @"CycleDate\d{8}");

                            DataRow row = csvData.NewRow();

                            //Alternativ
                            //row["FirstName"] = fieldData[0];
                            row[0] = fieldData[0];
                            row[1] = fieldData[1];
                            row[2] = conum;
                            row[3] = cycle;

                            csvData.Rows.Add(row);
                        }

                    }

Thanks in advance !

A: Your problem seems to be related to the detection of the first iteration of a  foreach loop. All the other building blocks, as adding the columns and adding the data rows, look fine and will work.
There are many options. One is to use a for loop instead, and add the columns only when the loop counter has its start value. One is to add a flag that ensures that the columns are added only in the first iteration:
var isfirstfile = true;
foreach(var file in files)
{
    if(isfirstfile)
    {
        /* add the columns */

        isfirstfile = false;
    }
    else
    {
        /* skip the first row of the current input file */
    }
    /* add the data rows */

}

Of course this assumes that all files have the same number and types of columns, in the same order.


text:
Q: Android - How to implement parcelable for List and List? I need to send an object of this class to an activity; but I could not properly implement the reading and writing of weeks and weeklyPosts attributes.
I've tried to do with the answer to this question: How to implement parcelable for List<Long>
and this: Using an ArrayList<String> with a class that extends Parcelable,  but does not work.
Thanks in advance.
import java.util.ArrayList;
import java.util.List;

import android.os.Parcel;
import android.os.Parcelable;

public class Statistics implements Parcelable{

    private String forumName;
    private List<String> weeks = new ArrayList<String>();
    private List<Long> weeklyPosts = new ArrayList<Long>();

    public Statistics(){

    }

    public Statistics (Parcel in){
        readFromParcel(in);
    }

    public static final Parcelable.Creator<Statistics> CREATOR
    = new Parcelable.Creator<Statistics>() {
        public Statistics createFromParcel(Parcel in) {
            return new Statistics(in);
        }

        public Statistics[] newArray(int size) {
            return new Statistics[size];
        }
    };

    @Override
    public void writeToParcel(Parcel dest, int flags) {

        dest.writeString(forumName);
                               //How to write the weeks List<String> ?
                               //How to write the weeklyPosts List<Long> ?
    }

    private void readFromParcel(Parcel in) {

        forumName = in.readString();
                               //How to read the weeks List<String> ?
                               //How to read the weeklyPosts List<Long> ?

    }

    @Override
    public int describeContents() {
        return 0;
    }
}

A: You can convert your the Lists to arrays (Long[] and String[]), and then use
dest.writeLongArray(weeksArray);
dest.writeStringArray(weeklyPostsArray);

in.readLongArray();
in.readStringArray();

For the String list, you can also use:
dest.writeStringList(weeks);

and
 in.readStringList();


text:
Q: OutOfMemory Java heap space when running on maven even though the memory has been increased I am writing some JUnit tests which retrieve 200,000 records from MySQL. When I try to run the tests via eclipse, it went out of memory.
I have increased the heap space via the VM arguments to -Xmx8G and it solved the problem. However, when I try to run this on maven by calling mvn test, it is still saying it is out of memory even though I have added it to the pom.xml
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
    <reuseForks>true</reuseForks>
    <forkCount>2</forkCount>
    <argLine>-Xmx10000m -XX:+HeapDumpOnOutOfMemoryError </argLine>
</configuration>

[INFO] Running ABCTechRecords.TestCountUniqueRecord
Nov 03, 2019 6:46:44 PM
ABCTechRecords.TestCountUniqueRecord init
INFO:  Starting test TestA
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 585.821 s <<< FAILURE! - in ABCTechRecords.TestCountUniqueRecord
[ERROR]
TestA(ABCTechRecords.TestCountUniqueRecord )  Time elapsed: 585.801 s  <<< ERROR!
java.lang.OutOfMemoryError: Java heap space at ABCTechRecords.TestCountUniqueRecord.init(TestA.java:28)

A: Please try the following configuration into the pom.xml file.
<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
    <configuration>
        <argLine>-Xmx4096m</argLine>
    </configuration>
  </plugin>
</plugins>


text:
Q: curses-like library for cross-platform console app in python I'm looking into developing a console application in python which should be able to run under Windows as well as Linux. For this, I'd really like to use a high-level console library like curses. However, as far as I know, curses is not available on Windows.
What other options do I have? Unfortunately, using cygwin under Windows is not an option...
Thanks for your help!

A: There is a wcurses.  I've never tried it but it may meet your needs.  It sounds like it doesn't have full curses compatibility, but may be close enough.  Also it might not be using the DOS terminal, but opening a GUI window and drawing monospaced text inside.
Other windows text mode options are:

*

*The console module;

*wconio -- based on Borland's C conio library.

I believe both are windows only.

A: I recently hit this issue for a package I was putting together (https://github.com/peterbrittain/asciimatics). I wasn't very happy with the solutions that required you to install (or worse) build separate binary executables like PDCurses or cygwin, so I created a unified API that provides console colours, cursor positioning and keyboard & mouse input for Windows, OSX and UNIX platforms.
This is now live and has been tested on CentOS 6/7 and Windows 7/8/10 and OSX 10.11.  You can install it from PYPI using pip and then use the Screen class to control your console.  As you can see from the project gallery, it should provide all your console needs, but if you need some extra features, please post an enhancement request on GitHub and I'll see what I can do.

A: I don't know why people answer in question comments, but debustad is right, there is a prebuilt curses for Windows:

*

*http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses
Note lots of other helpful libraries there too.  After doing so, install pip and the (lesser known but excellent) bpython interactive interpreter to try it out immediately:
pip install bpython

I also recommend the Urwid library for something higher-level.  Never tried it on Windows, but it should be possible with one of the curses packages.

A: PDCurses works on Windows, but I don't know any Python wrapper.
I wonder whether the curses module could be implemented on Windows with PDCurses?

A: develop two interfaces for your program, a text console ui and a graphical ui. Make the console one work only on linux. Nobody on windows uses text console apps.


text:
Q: Proving Lagrange Form of Remainder for Taylor Polynomial So I got to the infamous "the proof is left to you as an exercise" of the book when I tried to look up how to get the Lagrange form of the remainder for a Taylor polynomial. Is this right?
Given
$R_{n}(x)=\frac{1}{n!}\int_{0}^{x}f^{n+1}(t)(x-t)^{n}dt$,
find out why
$R_{n}(x)=\frac{1}{(n+1)!}f^{n+1}(c)x^{n+1}$ for some $c\in [0,x]$
According to FTC,
$\int_{0}^{x}f'(t)dt = f(x) - f(0)$
Also, according to the Mean Value Theorem, there exists a $c$ such that
$f'(c)(x-0)=f(x)-f(0)$
so
$\int_{0}^{x}f'(t)dt = f'(c)(x-0)$
finding the derivative of both sides with respect to $x$:
$f'(x) = f'(c)$
so
$f^{n+1}(x) = f^{n+1}(c)$
Going back to the integral form of the remainder:
$R_{n}(x)=\frac{1}{n!}\int_{0}^{x}f^{n+1}(t)(x-t)^{n}dt$,
I replace $f^{n+1}(x)$ with $f^{n+1}(c)$ (This is the step I am most unsure of)
Since $f'(c)$ is a constant, I pull it out of the integral and integrate what's left under the integral, giving me
$R_{n}(x)=\frac{1}{(n+1)!}f^{n+1}(c)x^{n+1}$ for some $c\in [0,x]$
If this is right, then does it mean that $f'(c)$ is the average value of $f'(x)$  from $0$ to $x$?
Sorry if my LaTeX/wording/proof is off. I'd appreciate any corrections/answers to be as simple (notation-wise) as possible please - 1st year undergrad here...

A: No, it is not right.
$$f'(c) (x-0) = f(x) - f(0)$$ is true, but $c$ depends on $x$.
So it is something like
$$f'(c_x) (x-0) = f(x) - f(0)$$
So derivative of $f'(c) x $ is not really $f'(c)$.
And the step from
$f'(x) = f'(c)$ to $f^{n+1}(x) = f^{n+1}(c)$ is also wrong. If $c$ is constant (according to your proof), then the derivative on the right side becomes $0$.


text:
Q: Change Class value using Greasemonkey? What method changes a class value using Greasemonkey? For instance, I'd like to change:
<a id="Test" class="button_primary button_left_padding tlignore disabled" role="button"

to:
<a id="Test" class="button_primary button_left_padding tlignore enabled" role="button"

A: For a simple static page and assuming that id="Test" is unique and stable, code like the following will work:
var targNode    = document.getElementById ("Test");
targNode.classList.remove ("disabled");
targNode.classList.add ("enabled");

For AJAX-driven pages, this complete script would work:
// ==UserScript==
// @name     _Flip CSS classes
// @match    http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

waitForKeyElements ("#Test", swapClass);

function swapClass (jNode) {
    jNode.removeClass ("disabled").addClass ("enabled");
}


text:
Q: CPP printf giving no output on VS2012 I am using Microsoft Visual Studio 2012 Professional. I have a simple CPP code:
#include "stdio.h"

int main () {
int a = 0, b = 0, c = 0;
printf("\nEnter two numbers:\n");
scanf("%d %d", &a, &b);

c = a+b;
printf("\nc = %d", c);
return 0;
}

The problem I am facing is that the first printf statement is getting printed but the second one is not. The code is exiting without printing anything. However when I debug using breakpoints, the value of c is getting stored in it.

A: I'll take a wild guess and say you run this from your IDE.
It does print the output. But the program then ends. And it ends so fast, you cannot see the output. If you want your program to wait for you to see it, you will need to find a way to make it wait. For example with another scanf line.
As there is no standard, environment agnostic way to say "Press any key to continue", have a look here for some alternatives.

A: Add \n to the end of the last printf. It is implementation-defined whether the last line of output to stdout actually gets flushed , if it doesn't end in a newline.

A: When you use

scanf("%d %d", &a, &b);

then you should give 2 inputs separated by space or enter

scanf("%d,%d", &a, &b);

then you should give 2 input separated by comma(,).
and at last use

printf("Press any key to continue.."); getche(); instead of return;


text:
Q: skipping loop in foreach with if statement I have this strange issue and I'm not sure how to title the question - suggestions?
Anyway, have an array that I'm looping over.
<?php

$array =  array(
   0 => array (
        'id' => '3'
        //etc
   ),
   1 => array (
        'id' => '4'
        //etc
   ),
   2 => array (
        'id' => '5'
        //etc
   ), //etc
);

$numbers = '1,2,3,4';

foreach ($array as $arr) {

  if (! check_array($arr['id'], explode(',', $numbers)) ) {
    continue;
  }

  echo 'My ID is: '.$arr['id'];
  // output should only contain 3 and 4 since the rest didn't match

}

function check_array($id, $numbers) {
    if(in_array($id, $numbers)) {
        return true;
    }
}

The idea is to skip the current iterations if $arr['id'] does NOT matches with a value in the $numbers array.
It almost works fine except, because check_array() returns true or returns '1', for some reason it adds a 1 to my array of numbers.
This means that my array would now be 1,2,3,41. I had to explode() the $numbers array because in_array() expects parameter two to be an array, however, all I have is a comma separated string - so it must be converted to an array first.
Why does it add it on to the end? I essentially only want to extract $arr if it's id is equal to any of the numbers within $numbers.

A: From OP's comment below,

I don't need just the ID's of the matched $arr's, I need every key that $arr has. I simply want to extract certain arrays within $array based on my $numbers var.

If you want to extract matched inner arrays from $array based on the $numbers ids, the solution would be like this:
$numberIds = explode(',', $numbers);
$resultArr = array();
foreach($array as $arr){
    if(in_array($arr['id'], $numberIds)){
        $resultArr[] = $arr;
    }
}

// display $resultArr array
var_dump($resultArr);

Here's the live demo


text:
Q: Nasm assembler x64 compare input string Compare the user input string with some values.

In this case i want to compare the input string with the '2' and jump to the CvrtMInus if the input is '2'

but nothing happends any idea?

For example the user put :
nasm -f elf64 -g inputCompare.asm
gcc -o inputCompare inputCompare.o
 ./inputCompare 2

sys_Exit       equ     1 ;id codigos del sistema
extern printf

section .data
formatoChar: db '%c', 0AH,0
formatoDec: dq '%d', 0AH,0
formatoStr: db '%s', 0AH, 0
mayus: db "Convert MAYUS", 0AH,0
minus: db "Convert MINUS", 0AH,0
tipoCnvs: db "2",0x0A

section .bss

section .text
global  main

_exit:
mov     rax,    1       ; exit
mov     rbx,    0       ; exit status
int     80h

main:
;Get the input data

 mov rcx, rdi     ; argc
 mov r8, 0     ; offset
 add r8, 8 ; apunta al siguiente argumento
 mov rdx, qword [rsi+r8] ; argv

 mov [tipoCnvs],rdx;Store value in variable
   ;print input
   ;mov rdi, formatoStr ; first parameter for printf
   ;mov rsi, rdx ; second parameter for printf
   ;mov rax, 0 ; no floating point register used
   ;call printf  ; call to printf

;Print input value

 mov rdi,formatoStr
 mov rsi,[tipoCnvs]
 mov rax, 0; no floating point register used
 call printf

; This is the Comparison part that I'm interested in

 cmp byte [tipoCnvs], '2'
 je CvrtMinus

 ;Convierte a Mayusculas
 CvrtMayus:
 mov rdi,mayus
 mov rax,0; no floating point register used
 call printf
 jmp _exit

 ;Convierte a Minusculas
 CvrtMinus:
 mov rdi,minus
 mov rax,0; no floating point register used
 call printf
 jmp _exit

A: The problem is that tipoCnvs contains a pointer to the string, so cmp byte [tipoCnvs], '2' compares the first byte of the pointer and not the string. You need to load it into a register because you need another level of indirection. Example:
mov rsi, [tipoCnvs]
cmp byte [rsi], '2'

The usual advice applies: learn to use a debugger so you can fix your own mistakes.
PS: When using the C library you should not invoke the exit system call directly. Normally you'd just return from main, or if you really need to then call exit from the C library. The system call terminates the program immediately, without letting the C library shut down properly. For example, you might lose some output that has not been flushed from internal buffers yet.


text:
Q: change checkbox label background size in html I'd like to know if it's possible to change the size of an html checkbox label background (mines have quite a broad vertical range around the text), or is that irremediably linked to font size ?
Any help will be gladly received,
Regards

A: Try this
html

    <input type="checkbox" name="Test" id="test1">Test_button

CSS
.checkboxes label {
    font-family:Arial Black;
    font-size: 12px;
    color: #666;
    border-radius: 10px 10px 10px 10px;
    background: #f0f0f0;
    padding: 100px 4px;
    text-align: left;
}

input[type=checkbox]:checked + label {
    color: white;
    background: #F2B611;
                                       }


text:
Q: where does Ubuntu save user permission of a file? i don't know the reason why but Linux user permissions is not working on NTFS file system... anyway, if a file was copied from windows to Ubuntu, Ubuntu  has to give them an ownership and a user permission as well.. so where does Ubuntu save user permission of a file?
the thing is, moving a file from Linux distro to another doesn't change  permissions. so it  should be inside of the file for sure.
does Ubuntu rewrite each and every file?

A: Linux uses NTFS via software called NTFS3G (google for details if interested). Linux and NTFS have totally different concepts of users, groups and file permissions. This means it's not simple to translate permissions between systems.
To adjust NTFS permissions into Linux form NTFS3G has 2 possibilities: (a) just ignore what NTFS has and set all files and all directories to the same umasks; or (b) provided that user mapping was done, it attempts to guess what meaning of Linux permission are resulted from NTFS permissions of a paricular file/dir.
In case (a) Linux-supplied permissions are not stored anywhere and any attempts to change them are ignored. Case (b) reads and stores file permissions in NTFS.

A: In the ext filesystem, which is used in Linux, inodes are used to describe stored files. An inode contains attributes of a file as well as its data block locations (these are the blocks that contain the actual contents of the file). The following is briefly what is stored in an inode:
Inode number
File access, modify and changed timestamps
File size
Permissions
Owner
Group
Data Block Locations
So to answer your question, Unix stores the permissions of a file in its inode, which is in the filesystem, for example ext4.
If you want to see the inode information of a file, you can use the stat command:
$ stat /bin/bash
  File: '/bin/bash'
  Size: 635933          Blocks: 624        IO Block: 65536  regular file
Device: 2e208854h/773883988d    Inode: 281474976901122  Links: 1
Access: (0755/-rwxr-xr-x)  Uid: ( 1000/    Alaa)   Gid: (  513/    None)
Access: 2014-10-18 13:45:13.375853300 -0400
Modify: 2014-10-08 16:54:16.000000000 -0400
Change: 2014-10-18 13:45:13.438253400 -0400
 Birth: 2014-10-18 13:45:13.375853300 -0400

To point out something in your question: by default, when you copy a file from a Linux distribution to another, the permissions are not copied. What happens is that the data blocks (the actual contents) are copied, but all the other attributes are not. So for example, if you are copying files from your internal to your external hard drive (both formatted as ext4), the owner of the copied data on the external hard drive becomes (I think) the user that did the copy command. If you wanted to preserve the permissions (and other attributes) of a file, you would have to use an extra flag, such as -p (or --preserve) in the cp command:
   -p     same as --preserve=mode,ownership,timestamps

   --preserve[=ATTR_LIST]
      preserve   the   specified   attributes   (default:  mode,owner-
      ship,timestamps), if possible  additional  attributes:  context,
      links, xattr, all

Where mode is the permissions. Using options like the -p copies over those inode attributes to the new file.
Windows uses the FAT32 or NTFS which are completely different filesystems that don't understand inodes. That's why, when you copy something from Linux (ext4) into Windows (NTFS or FAT32), Windows applies its own attributes to the file.
When you mount an NTFS filesystem in Ubuntu, it sets permissions on everything in the partition using the umask command (or options fmask and dmask in fstab). When you copy something over to that mounted partition, those files take whatever the umask command entails, and the permissions cannot be changed unless you remount the whole partition with new options.
For more information, read the manpage of ntfs-3g here: http://linux.die.net/man/8/ntfs-3g.


text:
Q: How to get the EOMONTH(End of month) of the current date using Python3 I have a SQL server stored procedure and I am trying to replicate it using python. One of the things I am trying to replicate is the following function:
DECLARE @Anchor_DT as DATE =EOMONTH(Getdate(),-1);

Here is what I have tried in Python3:
import datetime
datetime.date (2000, 3, 1) - datetime.timedelta (days = 1)

Output:
datetime.date(2000, 2, 29)

The thing is, I have to enter the date (200,3,1). I want to be able to pick up the current date and output the End of month. Here is what I tried but to no avail:
import datetime
datetime.date.now() - datetime.timedelta (days = 1)

Any suggestions or recommended solutions?

A: What about:
import datetime

now = datetime.datetime.today()
print(datetime.datetime((now.year + (now.month // 12)), (now.month + 1) % 12, 1) - datetime.timedelta(days = 1))

Or, you could use the calendar.monthrange method:
import calendar
import datetime

now = datetime.datetime.today()
_, lastday = calendar.monthrange(now.year, now.month)
print(datetime.datetime(now.year, now.month, lastday))


text:
Q: Twitter Api library? + retweeing I am looking at the twitter api page https://dev.twitter.com/ and I noticed that they have already built libraries that are wrappers against the twitter api. So I am thinking this is the best way to go but I am unsure which C# library I should use.
Does anyone have any suggestions?
What I am trying to do is make some simple service or cmd line application that will help me automate retweeting.
So I am looking for a library that will allow me to get posts from other twitter accounts and then retweet them from another account.
I am not sure if the library can do this or not. Otherwise I was thinking of getting the RSS feed from the twiter account I want to get the twitters from parse out the new ones and use a library to retweet them on my own account.
I have not used twitter much so I am hopping someone can shed some light on this.

A: Looking at the list I'd the first appears to be most comprehensive. However the linq 2 Twitter seems to be promising for the reading stuff.

A: I am currently in the process of expanding the new re-write of Twitterizer (http://code.google.com/p/twitterizer), once the proper methods have been added to the new version, you should be able to do this in a fairly straight forward way.

*

*Get the user timeline of the user you want to retweet.

*Locate the tweet (aka status).

*Call the retweet method.

Here are the raw API calls you'll probably need:

*

*https://dev.twitter.com/docs/api/1/get/statuses/user_timeline

*(step 2 doesn't have an API call)

*https://dev.twitter.com/docs/api/1/get/statuses/retweets/%3Aid
If you're in a time crunch, I can probably get those particular methods created quite quickly, as the underpinnings of our library is ready to go. Just let me know.
No matter what direction you choose, be absolutely sure to use OAuth for user authorization. (That's what we just re-wrote Twitterizer) Basic authentication will cease to function sometime in June. (Details here: http://groups.google.com/group/twitter-api-announce/browse_thread/thread/c2c4963061422f28?hl=en)


text:
Q: Laravel perdí configuración Storage::url Perdí un proyecto por un problema en mi PC. Al descargar de Github el proyecto tuve que re configurar todo pero no lo logro recuperar la funcionalidad para las imágenes. Las imágenes las tenía resguardadas por lo que copie las mismas a la carpeta Storage y no funcionan.
De hecho si cargo nuevas imágenes tampoco funciona.
Error:
Imágenes vacías

Al verificar las URL en el inspector de elementos veo:

La estructura de carpetas:
MiSitio/storage/...

En las vistas las imágenes las muestro de la siguiente forma:
<img src="{{ Storage::url($image->url) }}" />

Volví a ejecutar el comando:
php artisan storage:link

Y no resolvió mi problema.
Si accedo a la url de cualquier imagen del sistema me indica:
404 not found
y la url: http://localhost:8000/storage/posts/7Vl8bNpHp7emLKxUl52S90rOIAlSa62uP1r5aC1U.png
Si busco en la carpeta storage de imágenes la encuentro en la siguiente dirección:
MiSitio\storage\app\public\posts

A: Buen día,
Es posible que la ruta del storage esté mal configurada
Intenta lo siguiente:

*

*Abre config/filesystems.php

*Modifica la parte que dice public de la siguiente manera:

'public' => [
        'driver' => 'local',
        'root' => storage_path(),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ]

*Borra el folder storage de tu carpeta public si ya existe

*Ejecuta php artisan storage:link
Si no funciona intenta nuevamente pero en el paso 2 donde dice 'root' pon lo siguiente  'root' => storage_path('app/public')


text:
Q: Trying to create array of arrays: data.map is not a function I have some data, that looks like this mock data:
const mockData = [
  {
    "1": [
      {
        val1: 0.9323809524,
        val2: 5789.12,
        val3: 84.467,
        val4: 189.12,
        val5: 8,
        bins: 1,
      },
      {
        val1: 10.7328571429,
        val2: 5478.43,
        val3: 84.467,
        val4: -121.57,
        val5: 9,
        bins: 1,
      },
      {
        val1: 1.4457142857,
        val2: 5647.59,
        val3: 84.467,
        val4: 47.59,
        val5: 10,
        bins: 1,
      },
    ],
    "2": [
      {
        val1: 0.9323809524,
        val2: 5289.12,
        val3: 84.467,
        val4: 189.12,
        val5: 8,
        bins: 2,
      },
      {
        val1: 10.7328571429,
        val2: 5178.43,
        val3: 84.467,
        val4: -121.57,
        val5: 9,
        bins: 2,
      },
      {
        val1: 1.4457142857,
        val2: 5547.59,
        val3: 84.467,
        val4: 47.59,
        val5: 10,
        bins: 2,
      }
    ],
    "3": [
      {
        val1: 0.9323809524,
        val2: 5089.12,
        val3: 84.467,
        val4: 189.12,
        val5: 8,
        bins: 3,
      },
      {
        val1: 10.7328571429,
        val2: 5178.43,
        val3: 84.467,
        val4: -121.57,
        val5: 9,
        bins: 3,
      },
      {
        val1: 1.4457142857,
        val2: 5247.59,
        val3: 84.467,
        val4: 47.59,
        val5: 10,
        bins: 3,
      },
    ],
  },
];

So using useState I just set that to:
const [data, setData] = useState(mockData)

What I want to do is iterate through this data to get 3 arrays with the values of e.g. val2. So basically the result should be something like:
const newData = [
    [5789.12, 5478.43, 5647.59],
    [5289.12, 5178.43, 5547.59],
    [5089.12, 5178.43, 5247.59]
]

Now, if I try to do it a bit manually, like:
console.log(Object.keys(data[1].map((x) => x.val2)).map((val) => data[1].map((x) => x.val2)[val]));

Then I get an array for the first entry. But if I try to iterate through it, to actually create a new array of arrays, e.g.:
const [newData, setNewData] = useState([]);

setNewData(
    data.map((y, i) => ({
      Object.keys(y.map((x) => x.val2)).map((val) => y.map((x) => x.val2)[val]),
    }))
  );

I just get the error Uncaught TypeError: y.map is not a function. I've tried to just Object.keys a few places, without luck, but I may just be confused to why it doesn't work.
So what am I missing here?

A: {
   Object.keys(y.map((x) => x.val2)).map((val) => y.map((x) => x.val2)[val]),
}

Your map does not return values properly because of an extra pair of brackets {}. You can check the logic below

const data = [
  {
    "1": [
      {
        val1: 0.9323809524,
        val2: 5789.12,
        val3: 84.467,
        val4: 189.12,
        val5: 8,
        bins: 1,
      },
      {
        val1: 10.7328571429,
        val2: 5478.43,
        val3: 84.467,
        val4: -121.57,
        val5: 9,
        bins: 1,
      },
      {
        val1: 1.4457142857,
        val2: 5647.59,
        val3: 84.467,
        val4: 47.59,
        val5: 10,
        bins: 1,
      },
    ],
    "2": [
      {
        val1: 0.9323809524,
        val2: 5289.12,
        val3: 84.467,
        val4: 189.12,
        val5: 8,
        bins: 2,
      },
      {
        val1: 10.7328571429,
        val2: 5178.43,
        val3: 84.467,
        val4: -121.57,
        val5: 9,
        bins: 2,
      },
      {
        val1: 1.4457142857,
        val2: 5547.59,
        val3: 84.467,
        val4: 47.59,
        val5: 10,
        bins: 2,
      }
    ],
    "3": [
      {
        val1: 0.9323809524,
        val2: 5089.12,
        val3: 84.467,
        val4: 189.12,
        val5: 8,
        bins: 3,
      },
      {
        val1: 10.7328571429,
        val2: 5178.43,
        val3: 84.467,
        val4: -121.57,
        val5: 9,
        bins: 3,
      },
      {
        val1: 1.4457142857,
        val2: 5247.59,
        val3: 84.467,
        val4: 47.59,
        val5: 10,
        bins: 3,
      },
    ],
  },
];

const results = data.map((item) => Object.keys(item).map(key => item[key].map((value) => value.val2))).flat();

console.log(results)


text:
Q: Single thread executor with a cached thread I am looking to perform a particular set of operations with one thread only.
However, I cannot get Executors.newSingleThreadExecutor to work with a cached thread from a map.
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class ThreadTest {
    private final Callable<Boolean> task = new Callable() {
        @Override
        public Boolean call() {
            System.out.println("Ran");
            return Boolean.TRUE;
        }
    };

    //this prints the Callable output "Ran"
    @Test
    public void testVanilla() throws InterruptedException {
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.submit(task);
        Thread.sleep(10);
    }

    //this does not print the Callable output "Ran"
    @Test
    public void testCached() throws InterruptedException {
        Map<String, Thread> map = new HashMap<>();
        Thread thread = new Thread("WORKER");
        thread.setDaemon(false);
        map.put("uniq", thread);
        ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return map.get("WORKER");
            }
        });

        service.submit(task);
        Thread.sleep(10);
    }
}

Is there something obviously wrong? I'm wondering why the executor did not work in case #2

A: Your Thread has no Runable to invoke the callable. This Code works fine for me
    @Test
    public void testCached() throws InterruptedException {
        Map<String, Thread> map = new HashMap<>();
        ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {

                if (!map.containsKey("WORKER")) {
                    Thread thread = new Thread(r, "WORKER");
                    thread.setDaemon(false);
                    map.put("WORKER", thread);
                }

                return map.get("WORKER");
            }
        });

        service.submit(task);
        Thread.sleep(10);
    }


text:
Q: How to programmatically read a MS Access (.mdb) file in java? I am giving maintenance on an old, decentralized, and local application that each of our Clients uses, with each app having its own independent .mdb (MS Access) file as a database. We are developing a new, centralized SpringBoot Web application that uses MySQL as a database. The problem is that we can't just throw away the data on the already existing Access databases, therefore, one of the pre-requisites for the new application is to add a function to migrate all the old data from those .mdb files into the new database.
In detail, using an HTTP call, our client should be able to send a .mdb file through a SpringBoot controller. The Server should then read the tables and its contents, validate a few pieces of information, and insert the data read on the new MySQL database.
A few notes:
The most recent version of the database structure -the MySQL- is, of course, already known, but the structures of the older Access databases may vary, as not all of the Clients have the most up to date version of the old App/MS Access. That's why, if possible, the reading process should be dinamic and independent of a pre-determined structure. The good news is that, in general, the newer versions only add new tables and fields (no deletions nor editions), therefore when migrating a very old .mdb, a few tables and fields could be missing (shouldn't be a problem, except it's 'NOT NULL'), but at least there will be no "new", unknown or extra field.
The HTTP Controller, the validation, and insertion of the data are OK, but I couldn't find how to programmatically and dynamically read the .mdb file. Any help would be appreciated. Thanks in advance!


text:
Q: Reaching into object from array in javascript? How can I reach into a object using an array and set a value - preferably without using eval, doing something like object[eval(["key", "deepkey"].split("")) = "newvalue"?
Doing it manually, I would just do object.key.deepkey = "newvalue", but again, I need to do this using an array to reach into the right property.
The object for reference:
object = {
  key: {
    deepKey: "value"
  }
}

A: You can write array type syntax as. jsfiddle
object = {
  key: {
    deepKey: "value"
  }
}

object['key']['deepkey']='newvalue'

if you have keys in array you can do this
var keys = ['key','deepkey'];
var obj = object;
for(var k =0; k <keys.length-1; k++){
   obj= obj[keys[k]];
}
obj[keys[k]] = 'newvalue'

A: You can use a recursive function to step through each level of the array (or object) like so:
function val(array, indices) {
    if(indices.length > 1) {
        var idx = indices.shift();
        return val(array[idx], indices);
    }
    else {
        return array[indices.shift()];
    }
}

var obj = { a: { b: 'c' } };

//result is 'c'
var result = val(obj, ['a', 'b']);

If you want to get an object reference, simply specify the second arg only up to that:
var obj = {
    a: {
        b: {
            c: 'foo'
        }
    }
};

var ref = val(obj, ['a', 'b']);

//ref is now obj.a.b, so you can do something like...
ref.x = 'bar';

console.dir(ref); //outputs something like { c: 'foo', x: 'bar' }

A: You can take the function from this question and rework it to access properties of an object.
http://jsfiddle.net/jbabey/Mu4rP/
var getPropByName = function (propName, context) {
    var namespaces = propName.split('.');

    for(var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
    }

    return context;
};

var myObject = {
    someKey: {
        deepKey: "value"
    }
};

myObject.someKey.deepKey; // "value"
getPropByName('someKey.deepKey', myObject); "value"

A: An alternative could be using Array.map this way:
function deepkey(obj,keys,set){
  var i=1
     ,kys = keys.split('.')
     ,exist = kys.map( function(k){
          var prev = this[i-1], isobj = prev.constructor === Object;
          this.push( isobj && k in prev ? prev[k] : prev);
          return (i++,this[i-1]);},
          [obj]
        )
     ,x = exist[exist.length-2];
  if (x && x.constructor === Object && set){
    x[kys[kys.length-1]] = set;
  }
  return x[kys.pop()] || null;
}
// usage
var obj = { a:{ b:{ c:1, cc:{ d:{ e:{ a:1,b:2,c:3 } } } } } };
// assign [1,2,3,4,5] to obj.a.b.cc.d.e.b
console.log(deepkey(obj,'a.b.cc.d.e.b',[1,2,3,4,5])); //=> [1,2,3,4,5]
// get obj.a.b.cc.d.e.b[2]
console.log(deepkey(obj,'a.b.cc.d.e.b')[2]); //=> 3
// get non existing path obj.a.b.c.d.e.b
console.log(deepkey(obj,'a.b.c.d.e.b')); //=> null


text:
Q: Read iso_3166_2.js using rjson package in R I need to read js in R to download iso_3166_2 data. How I can use rjson to read?
library("rjson")
json_file <- "https://raw.githubusercontent.com/oodavid/iso-3166-2/master/iso_3166_2.js"
lines <- readLines(json_file)

A: Packages like rjson and jsonlite expect to read properly formatted JSON data, not arbitrary javascript files. You can verify something is in JSON format with a JSON validator. In this you are lucky that it's pretty close to a proper JSON file, you just need to clean a few things up. you just need to clean up the first and last lines
json_file <- "https://raw.githubusercontent.com/oodavid/iso-3166-2/master/iso_3166_2.js"
lines <- readLines(json_file)
lines[1] <- gsub(".*(?={)", "", lines[1], perl=TRUE)
lines[length(lines)] <- gsub(";.*$", "", lines[length(lines)], perl=TRUE)
mydata <- jsonlite::fromJSON(paste(lines, collapse="\n"))

Here I used jsonlite rather than rjson because it more easily allows vectors for input and doesn't seem to get tripped up on quote encoding.


text:
Q: Azure Function Python Environment Variables I hope somebody can help to clarify this issue.
I have an azure function running some python code. The function itself is pretty simple, as I just need to loop over resource groups and list all the storage accounts inside each resource group.
Locally as python code is running just fine and I can access the resources with my service principle.
So I decided to automate this in an azure function as follow:
def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    if mytimer.past_due:
        logging.info('The timer is past due!')
    credentials = DefaultAzureCredential()
    logging.info('Python timer trigger function ran at %s', utc_timestamp)
    KeyVault_Url = f'KeyVault connection String'

    client_keyvault = SecretClient(vault_url=KeyVault_Url, credential=credentials)
    subscription_id = client_keyvault.get_secret("subscribed").value
    resource_client = ResourceManagementClient(credentials, subscription_id)
    storage_client = StorageManagementClient(credentials, subscription_id)
    logging.info('This should run')

    for resource_group in resource_client.resource_groups.list():
        logging.info(resource_group.name)
        for storage in storage_client.storage_accounts.list_by_resource_group(resource_group.name):
            logging.info(f"Storage Account is: {storage.name}")
            print(f"\tStorage Account: {storage.name}")

When I trigger manually this function, it run successfully but in the logs, I don't see the last 2 line of code. it seems that the forloop is not reached.
I checked the output of the function, and I found bizarre this:
Request URL: 'https://management.azure.com/subscriptions/subscription/resourcegroups?api-version=REDACTED' Request method: 'GET' Request headers: 'Accept': 'application/json' 'x-ms-client-request-id': 'id' 'User-Agent': 'azsdk-python-azure-mgmt-resource/21.1.0 Python/3.9.12 (Linux-5.4.81-microsoft-standard-x86_64-with-glibc2.31)' 'Authorization': 'REDACTED' No body was attached to the request

The redacted is not really clear to me what it means and if that is the cause why the for loop is not running.
Here is my question to overcome this.
I have a service principle that has the right permission to run this task, and I would like to configure this credential in a json file in the function project, so after the deployment I can just set those variables in the configuration blade of the azure function itself.
At the root folder of the project I have a file called local.settings.json with a set of configuration to run the function locally. And as far as I know in c# you can have a upsetting.[environemt].json and you can configure specific variables to be used in specific environments. Can anyone help understand how to solve this?
Basically I want to have appsettings.staging.json file with specific variables, like:
client_id: "client_id"
tenant_id: "tenant_id"

and set the values in the azure function configuration in the portal.
Is there a way to do this in python function?
I hope I explained my problem well, and please if I didn't do not hesitate to ask more details.
Thank you so much for any help or hint that you can provide me with.

A: We use Azure Keyvault to store the environment-specific variables and query based on each Environment.
{
    "AZURE_CLIENT_ID": "***",
    "AZURE_TENANT_ID": "***",
    "AZURE_CLIENT_SECRET": "***",
}


text:
Q: How Music player work when we kill (swipe) the recent app When I play the music and come on home the music is running, but when I kill the app music is restart. I want to run the music when I kill the app instead of it restarting.
Please help me.
My code is:----
MainActivity.java
public class MainActivity extends ActionBarActivity {

Context context;
private Button mPlay, mStop;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mPlay = (Button) findViewById(R.id.button1);
    mStop = (Button) findViewById(R.id.button2);
    mPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent service = new Intent(MainActivity.this, Myservice.class);
            startService(service);
        }
    });
    mStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent name = new Intent(MainActivity.this, Myservice.class);
            stopService(name);
        }
    });
}

}
And my service class is:---
public class Myservice extends Service implements
MediaPlayer.OnErrorListener{

private final IBinder mBinder = new ServiceBinder();
    MediaPlayer mPlayer;
    private int length = 0;

    public Myservice() { }

    public class ServiceBinder extends Binder {
        Myservice getService()
         {
            return Myservice.this;
         }
    }

    @Override
    public IBinder onBind(Intent arg0){return mBinder;}

    @Override
    public void onCreate (){
      super.onCreate();

       mPlayer = MediaPlayer.create(this, R.raw.follow);
       mPlayer.setOnErrorListener(this);

       if(mPlayer!= null)
        {
            mPlayer.setLooping(true);
            mPlayer.setVolume(100,100);
        }

        mPlayer.setOnErrorListener(new OnErrorListener() {

      public boolean onError(MediaPlayer mp, int what, int
          extra){

            onError(mPlayer, what, extra);
            return true;
        }
          });
    }

    @Override
    public int onStartCommand (Intent intent, int flags, int startId)

    {
         mPlayer.start();
         return START_STICKY;

    }

    public void pauseMusic()
    {
        if(mPlayer.isPlaying())
        {
            mPlayer.pause();
            length=mPlayer.getCurrentPosition();

        }
    }

    public void resumeMusic()
    {
        if(mPlayer.isPlaying()==false)
        {
            mPlayer.seekTo(length);
            mPlayer.start();
        }
    }

    public void stopMusic()
    {
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }

    @Override
    public void onDestroy ()

    {
        super.onDestroy();
        if(mPlayer != null)
        {
        try{
         /*mPlayer.stop();
         mPlayer.release();*/
            Toast.makeText(getApplicationContext(), "ondestroy", 2000).show();
            }finally {
                mPlayer = null;
            }
        }

    }

    public boolean onError(MediaPlayer mp, int what, int extra) {

        Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
        if(mPlayer != null)
        {
            try{
                mPlayer.stop();
                mPlayer.release();
            }finally {
                mPlayer = null;
            }
        }
        return false;
    }

}

A: Add the below method in your service and call the method when media starts playing. Foreground service are high priority service which are not killed by android system often, starting a foreground service needs a notification. you can manually stop foreground service by calling stopForeground(true). Please watch for basics of Media Playback State of Media Playback (Android Dev Summit 2015)
private static final String NOTIFICATION_ID = 91;

    private void runAsForeground(){
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
                notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

        Notification notification=new NotificationCompat.Builder(this)
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .setContentText("Media is playing")
                                    .setContentIntent(pendingIntent).build();

        startForeground(NOTIFICATION_ID, notification);

    }


text:
Q: SharePoint FBA: Membership email vs. "People and Groups" email I have a WSS 3.0 site with FBA and a custom user management web part. To track user email address, I have been using the Email property of the MembershipUser object. I just realized today that if you go into People and Groups and look at the email address for a user, the email address is blank, and can be edited there independent of the MembershipUser value. It seems that the alerts system uses the email address that is stored in People and Groups.
I have not gotten into recoding yet because I want to make sure I'm not missing anything first. I assume I could switch from MembershipUser.Email and story my information in SPUser.Email instead. But I seem to remember that on a different project I used MembershipUser.Email with no problems and the alerts went out fine (although that was MOSS).
So I guess I have two questions:

*

*Is there a way to tell People and Groups or the Alerts system to use MembershipUser.Email?

*Is it best practice to use SPUser.Email for email storage, rather than MembershipUser.Email?

A: This post goes in-depth in getting SharePoint to sync the user profiles in your FBA store by naming all properties sharepoint should know about in the web.config and create those properties in your ProfileProvider. Not sure if it is what you are looking for exactly though. FBA user profile mapping does not work as clean as AD user profile mapping does out of the box.
Also, check out the User Profile Import Tool on CodePlex. It's for MOSS but might provide some pointers.


text:
Q: why garbage collection, closure and lambda disabling prism event aggregator subscription? I have a simple event defined using PRISM event aggregator pattern
 public class TestEvent : PubSubEvent
    {
    }
    public static class PrismEvents
    {
        public static readonly IEventAggregator EventAggregator = new EventAggregator();
        public static readonly TestEvent EventTest = EventAggregator.GetEvent<TestEvent>();
    }

I have a subscriber class where this event is subscribed using a lambda.Note the usage of a local variable(i) inside the subscription code
public class SubScriber
    {
        public SubScriber()
        {
            int i = 5;
            PrismEvents.EventTest.Subscribe(() =>
            {
                Console.WriteLine("Event Fired");//not getting called
                i = 10; //commenting this line will execute the subscription code
            });
        }

    }

In the publisher side Subscriber is created, then  GC is called then event publised.
Subscription code is not getting executed!
 class Program
    {
        static void Main(string[] args)
        {
            new SubScriber();
            GC.Collect(); //commenting this line will execute the subscription code
            PrismEvents.EventTest.Publish();
            Console.ReadKey();
        }

    }

Couple of points

*

*Commenting the usage of local variable(i=10) will fix the
issue.Subscription code will execute as expected

*Commenting GC.collect will fix the issue. Subscription code will
    execute as expected
What is the reason for this behavior?

A: Good questions.
I don't have all the answers, but Prism uses WeakReference.
Subscribe create a WeakReference on the delegate (action) use in argument.
To be precise, the WeakReference is made on the Target of the delegate.
Here some code to understand better what happens :
    public class SubScriber
    {
        public SubScriber()
        {
            int i = 5;
            Action action1 = () =>
            {
                Console.WriteLine("Event Fired action1");//not getting called
                i = 11; //commenting this line will execute the subscription code
            };

            Action action2 = () =>
            {
                Console.WriteLine("Event Fired action2");//will be called
            };

            Console.WriteLine("Target 1 = "+ action1.Target);
            Console.WriteLine("Target 2 = " + action2.Target);
            PrismEvents.EventTest.Subscribe(action1);
            PrismEvents.EventTest.Subscribe(action2);
        }

        ~SubScriber()
        {
            Console.WriteLine("SubScriber destructed");
        }
    }

    static void Main(string[] args)
    {
        new SubScriber();
        GC.Collect(); //commenting this line will execute the subscription code
        GC.WaitForPendingFinalizers(); // or Thread.Sleep(2000);
        Console.WriteLine("Publish");
        PrismEvents.EventTest.Publish();
        Console.WriteLine("Press a key to finish");
        Console.ReadKey();
    }

We saw that the "SubScriber destructed" is displayed before "Publish".
What is interesting is also to use ILSpy to see what is generated :
public class SubScriber
    {
        [CompilerGenerated]
        private sealed class <>c__DisplayClass0_0
        {
            public int i;

            internal void ctor>b__0()
            {
                Console.WriteLine("Event Fired action1");
                this.i = 11;
            }
        }

        [CompilerGenerated]
        [Serializable]
        private sealed class <>c
        {
            public static readonly Program.SubScriber.<>c <>9 = new Program.SubScriber.<>c();

            public static Action <>9__0_1;

            internal void ctor>b__0_1()
            {
                Console.WriteLine("Event Fired action2");
            }
        }

        public SubScriber()
        {
            Program.SubScriber.<>c__DisplayClass0_0 <>c__DisplayClass0_ = new Program.SubScriber.<>c__DisplayClass0_0();
            <>c__DisplayClass0_.i = 5;
            Action action = new Action(<>c__DisplayClass0_.<.ctor>b__0);
            Action arg_41_0;
            if ((arg_41_0 = Program.SubScriber.<>c.<>9__0_1) == null)
            {
                arg_41_0 = (Program.SubScriber.<>c.<>9__0_1 = new Action(Program.SubScriber.<>c.<>9.<.ctor>b__0_1));
            }
            Action action2 = arg_41_0;
            string arg_59_0 = "Target 1 = ";
            object expr_4D = action.Target;
            Console.WriteLine(arg_59_0 + ((expr_4D != null) ? expr_4D.ToString() : null));
            string arg_7B_0 = "Target 2 = ";
            object expr_6F = action2.Target;
            Console.WriteLine(arg_7B_0 + ((expr_6F != null) ? expr_6F.ToString() : null));
            Program.PrismEvents.EventTest.Subscribe(action);
            Program.PrismEvents.EventTest.Subscribe(action2);
        }

        ~SubScriber()
        {
            Console.WriteLine("SubScriber destructed");
        }
    }

The difference I saw is that the 2nd action has a static readonly field that hold an instance on the delegate...
Regards,
Sybaris


text:
Q: Drop unused levels in facet_wrap in ggplot2 I am needing to drop unused levels in facet_wrap (ggplot2), but can't figure out how to do it. The initial question was posted here, but thought this would be better as a separate question.
Here is some example code:
group1 = c(rep("A",4),rep("B",4),rep("C",3))
group2 = c(rep(c("param1","param2","param3","param4"),2),c("param1","param2","param3"))
est = rnorm(length(group2),mean = 0, sd = 1)
lwr = est - sd(est)
upr = est + sd(est)

df = data.frame(group1,group2,est,lwr,upr)

# Swapped the x axis to use group1
figure.gg = ggplot(data = df, aes(x = group1, y = est, ymin = lwr, ymax = upr)) +
  geom_point(position = position_dodge(width = 0.5)) +
  geom_errorbar(position = position_dodge(width = 0.5), width = 0.1) +
  coord_flip() +
  # Facet wrapped with one column using group 2s
  facet_wrap(~group2, ncol = 1, strip.position = "right") +
  ylab("estimate")

figure.gg

Group1 (C) does not have a param4, but it is included in the figure. However, adding drop = TRUE to facet_wrap() does not change the behavior. I can solve with scales = "free_x", but I really don't want to float the facets; I want them to all be aligned.

A: Specify scales = "free_y"
figure.gg = ggplot(data = df, aes(x = group1, y = est, ymin = lwr, ymax = upr)) +
  geom_point(position = position_dodge(width = 0.5)) +
  geom_errorbar(position = position_dodge(width = 0.5), width = 0.1) +
  coord_flip() +
  # Facet wrapped with one column using group 2s
  facet_wrap(~group2, ncol = 1, strip.position = "right", scales = "free_y") +
  ylab("estimate")

figure.gg


text:
Q: Horizontally sizing Bootstrap 3 media object body I need to equally size the .media-body elements so they can grow up to the left limit of the page no matter the text they wrap.

Lorem ipsum dolor sit amet, consectetur dipiscing elit. Duis pharetra varius quam sit amet vulputate. Quisque mauris augue, molestie tincidunt condimentum vitae, gravida a libero.

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra varius quam sit amet vulputate. Quisque mauris augue, molestie tincidunt condimentum vitae, gravida a libero.

Here's the snippet

A: This seems to work...


text:
Q: Mulitple preprocessor directives on shared project I have a shared database model in a seperate project, that is shared with another solution, however i want to use a different Identity mapping, so i wanted to know if it possible to use preprocessor directives.
Inside sharedProject example:
#if setup1
    public  virtual int Id { get; protected set; }

#elif setup2
    public  virtual Guid Id { get; protected set; }
#endif
    public virtual string Name { get; set; }

I know you can add preprocessor directives to the project, but not entirely sure how that works, only used it for debug.
In:
Project -> Properties -> build -> Conditional preprocessor symbols

Should i do something like this:
StartupProject1 -> properties -> Conditional preprocossor symbols = setup1
StartupProject2 -> properties -> Conditional preprocossor symbols = setup2
sharedProject -> properties -> Conditional preprocossor symbols = setup1,setup2

A: Find out how to do it
I ended up using configuration mananger, and create multiple configurations, based, on those configurations, i just added the only needed preprocsessor symbol
SharedProject Setup1 Configuration
SharedProject -> properties -> Conditional preprocossor symbols = setup1

SharedProject Setup2 Configuration
SharedProject -> properties -> Conditional preprocossor symbols = setup2

And in configuration manager on the solution, i just chose the needed setup for the shared project


text:
Q: How to perform an action depending on various checkbox status? I want to call a JavaScript function depending on the check boxes status.
For example if only checkbox 1 is active, I want to call the function genPDF()
If all checkboxes are active I want to invoke the function gen4PDF() once I press the generate report button, etc.
As far as I know I can do something like that: (and it works)
 DOWNLOAD PDF
But I want a more 'smart' link/button. How can I do it?
My code skeleton:
<!DOCTYPE>

    <title>System Overview Report</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <input type="checkbox" name="basic">I want basic report

    <input type="checkbox" name="network">I want network report

    <input type="checkbox" name="suggestions">I want suggestions report

    <input type="checkbox" name="complete">I want a complete report

     GENERATE PDF REPORT

A:  var checkBoxes=document.getElementsByClassName('pdf');
for(var i=0; i<4;i++){
    checkBoxes[i].onclick=function(){
        var checkedNum=0;
        for(var j=0; j<4;j++){
            if(checkBoxes[j].checked){
                checkedNum++
            }
        }

        switch (checkedNum){

            case 1:
                genPDF();
                break;
            case 2:
                gen2PDF();
                break;
            case 3:
                gen3PDF();
                break;
            case 4:
                gen4PDF();
                break
        }
    }
}

A: You can get all checkbox states like this:
var options = {}
$('input[type="checkbox"]').each(function() {
  options[this.name] = this.checked
})

You can check against single or multiple options to figure out what to do.

genPDF = function() {
  var options = {}
  $('input[type="checkbox"]').each(function() {
    options[this.name] = this.checked
  })

  if (options.basic && !options.network) {
    // etc
  } else if () {
    // etc
  }
}

    <input type="checkbox" name="basic">I want basic report

    <input type="checkbox" name="network">I want network report

    <input type="checkbox" name="suggestions">I want suggestions report

    <input type="checkbox" name="complete">I want a complete report

     GENERATE PDF REPORT

A: the code for two cases first checkbox and all checkboxes:

function genPDF() {
  console.log('genPDF');
}

function gen2PDF() {
  console.log('gen2PDF');
}

function gen3PDF() {
  console.log('gen3PDF');
}

function gen4PDF() {
  console.log('gen4PDF');
}
function generate() {
  var basic = document.querySelector('[name="basic"]').checked;
  var network = document.querySelector('[name="network"]').checked;
  var suggestions = document.querySelector('[name="suggestions"]').checked;
  var complete = document.querySelector('[name="complete"]').checked;
  if (basic && !network && !suggestions && !complete) {
    genPDF();
  } else if (basic && network && suggestions && complete) {
    gen4PDF();
  }
}
<input type="checkbox" name="basic">I want basic report

<input type="checkbox" name="network">I want network report

<input type="checkbox" name="suggestions">I want suggestions report

<input type="checkbox" name="complete">I want a complete report

 GENERATE PDF REPORT


text:
Q: Years not displaying correctly in line graph I am trying to make a line graph for annual observations. The X-axis is not displaying the years correctly; they come out as 2,008 / 2,009 etc.
Here is the code I used:
\begin{figure}[h!]
\centering
\begin{tikzpicture}
\begin{axis}[
xlabel=Year,
ylabel=Number of certificates,
legend pos=north east,
legend entries={Eco,Private},
]
  \addplot table [x=Year,y=Eco] {data.txt};
  \addplot table [x=Year,y=Private] {data.txt};
\end{axis}
\end{tikzpicture}
\end{figure}

The table is in a separate file, data.tex, in the following format:
X Year  Private  Eco
1 2007  5877    nan
2 2008  921253  nan
3 2009  6131    nan
4 2010  6953    nan
5 2011  37184   nan
6 2012  61179   nan
7 2013  374902  18
8 2014  565200  12918
9 2015  137686  227964
10 2016 55295   204323

this is what the output looks like:

How can I get the values on the X axis to display as years?

A: Like this. SORRY, most likely I misread your question.
\documentclass[border=3.14mm,tikz]{standalone}
\usepackage{filecontents}
\begin{filecontents*}{data.txt}
X Year  Private  Eco
1 2007  5877    nan
2 2008  921253  nan
3 2009  6131    nan
4 2010  6953    nan
5 2011  37184   nan
6 2012  61179   nan
7 2013  374902  18
8 2014  565200  12918
9 2015  137686  227964
10 2016 55295   204323
\end{filecontents*}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xlabel=Year,
ylabel=Number of certificates,
legend pos=north east,
legend entries={Eco,Private},
xticklabel style={/pgf/number format/1000 sep={}
}
]
  \addplot table [x=Year,y=Eco] {data.txt};
  \addplot table [x=Year,y=Private] {data.txt};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: How to determine if an associative array is a subset of another associative array I have a question about determining whether a PHP associative array, which contains indices to another array, is a subset of another similarly constructed associative array, namely one that contains indices to another array.
Assuming that I have two arrays, one named dogs and another named legged-animals.
<?php
$dogs = array(0 => array('height' => 100, 'weight' => 100),
              1 => array('height' => 50, 'weight' => 50));

$legged-animals = array(0 => array('height' => 200, 'weight' => 500),
                        1 => array('height' => 220, 'weight' => 500),
                        2 => array('height' => 100, 'weight' => 100),
                        3 => array('height' => 50, 'weight' => 50));
?>

So the question is, how can I determine that dogs is a subset of legged-animals?
EDIT:
Here's my attempt at finding out whether one is the subset of the other:
function filter($largeSets, $subSets)
{
    $result = array();

    $count = count($subSets);
    foreach ($largeSets as $individualSet)
    {
        foreach ($subSets as $set)
        {
            $intersection = array_intersect($individualSet, $set);

            if (!empty($intersection) && isset($intersection['height']) && isset($intersection['weight']))
            {
                $result['array'][] = $individualSet;
                $count--;
                break;
            }
        }
    }

    $result['result'] = ($count == 0);

    return $result;
}

UPDATED:
This is a somewhat easier solution that I think will solve the problem. The idea is to go through the multidimensional array, serialize the arrays, and then use array_intersect.
$dogs = array(0 => array('height' => 100, 'weight' => 100),
              1 => array('height' => 50, 'weight' => 50),
              2 => array('height' => 10, 'weight' => 25) );

$legged_animals = array(0 => array('height' => 200, 'weight' => 500),
                        1 => array('height' => 220, 'weight' => 500),
                        2 => array('height' => 100, 'weight' => 100),
                        3 => array('height' => 50, 'weight' => 50));

foreach ($dogs as $dog)
{
    $arr[] = serialize($dog);
}

foreach ($legged_animals as $animal)
{
    $arr2[]  = serialize($animal);
}
$intersection = array_intersect($arr, $arr2);
print_r($intersection);

At this point, the intersection would print out a serialized form of the intersection. To get the initial results back, you'd have to unserialize the arrays.
Is there an easier way of doing this?

A: How about this long-winded method:
// borrowed from giosh at http://php.net/manual/en/function.array-diff-assoc.php
function array_diff_assoc_recursive($array1, $array2) {
    $difference=array();
    foreach($array1 as $key => $value) {
        if( is_array($value) ) {
            if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
                $difference[$key] = $value;
            } else {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if( !empty($new_diff) )
                    $difference[$key] = $new_diff;
            }
        } else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) {
            $difference[$key] = $value;
        }
    }
    return $difference;
}

function array_is_sub($needle,$haystack)
{
  foreach ($needle as $n)
  {
    $matched=false;
    foreach ($haystack as $h)
    {
      if (empty(array_diff_assoc_recursive($n, $h)))
      {
         $matched=true;
         break;
      }
    }
    if (!$matched) return false;
  }
  return true;
}

$dogs = array(0 => array('height' => 100, 'weight' => 100),
              1 => array('height' => 50, 'weight' => 50));

$legged_animals = array(0 => array('height' => 200, 'weight' => 500),
                        1 => array('height' => 220, 'weight' => 500),
                        2 => array('height' => 100, 'weight' => 100),
                        3 => array('height' => 50, 'weight' => 50));

if (array_is_sub($dogs,$legged_animals)) {
  echo "Dogs is a subset of Legged_Animals.";
} else {
  echo "Dogs is NOT a subset of Legged_Animals.";
}

Should work.

A: This solution works perfectly fine for what I need:
// takes two multidimensional arrays, $arr1 and $arr2
// and returns the intersection of the two
// @return an array that is the intersection of the two
function findIntersection($arr1, $arr2)
{
    $retArray = array();
    $firstArray = array();
    $secondArray = array();
    $intersection = array();

    foreach ($arr1 as $set)
    {
        $firstArray[] = serialize($set);
    }

    foreach ($arr2 as $set)
    {
        $secondArray[] = serialize($set);
    }

    $intersection = array_intersect($firstArray, $secondArray);

    if (!empty($intersection))
    {
        foreach ($intersection as $serializedArray)
        {
            $retArray[] = unserialize($serializedArray);
        }
    }

    return $retArray;
}

A: array_intersect() does the trick (don't use a dash in your array name):
$dogs = array(0 => array('height' => 100, 'weight' => 100),
              1 => array('height' => 50, 'weight' => 50));

$leggedanimals = array(0 => array('height' => 200, 'weight' => 500),
                        1 => array('height' => 220, 'weight' => 500),
                        2 => array('height' => 100, 'weight' => 100),
                        3 => array('height' => 50, 'weight' => 50));

print_r( array_intersect( $dogs, $leggedanimals ) );
// Array ( [0] => Array ( [height] => 100 [weight] => 100 ) [1] => Array ( [height] => 50 [weight] => 50 ) )


text:
Q: Delete first occurrence duplicate row in postgres I have the following table
ID   VALUE1  VALUE2
1    aaa     bbb
1    aaa     bbb

Sadly, my table has no primmary keys and I want to create it. But first I need to delete only the first occurrance of duplicated rows. I don't have any unique identifier, the rows are exactly equal.
I know that I can use something like this if I have an unique identifier:
DELETE FROM
    table
WHERE
    table.id < table.id

But, what is the best approach to this if I don't have a unique identifier?
My table has 500 million lines, about 100k are duplicated.

A: If I understand the question correctly, you can proceed using Row_Number():
with dataset as (select 1 as ID, 'aaa' as VALUE1, 'bbb' as VALUE2
     union all select 1, 'aaa', 'bbb'
     union all select 2, 'ccc', 'ddd'
     union all select 2, 'ccc', 'ddd')

select *, row_number() over (partition by id, value1, value2) from dataset;

This will create the following column row_number:
 id | value1 | value2 | row_number
----+--------+--------+------------
  1 | aaa    | bbb    |          1
  1 | aaa    | bbb    |          2
  2 | ccc    | ddd    |          1
  2 | ccc    | ddd    |          2

and then you can delete * where row_number = 1;


text:
Q: position a div on top of a video  in HTML CSS im struggling how to position a
 on top of a video <object>.
the blue border is my . behind the video is my
some text
 that i wanted to be on top of the video and position it at the bottom right.

CSS and HTML

some text

this is the object inside my owlvid.html
<OBJECT classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"
   codebase="http://downloads.videolan.org/pub/videolan/vlc/latest/win32/axvlc.cab"
    width="480" height="300" id="vlc" events="True">

   <param name="Src" value="owl-vid-path-source" />
   <param name="ShowDisplay" value="True" />
   <param name="AutoLoop" value="False" />
   <param name="AutoPlay" value="True" />
   <param name="wmode" value="transparent" />

   <embed id="vlcEmb"  type="application/x-google-vlc-plugin" version="VideoLAN.VLCPlugin.2" autoplay="yes" loop="no" width="480" height="300"
     target="owl-vid-path-source" ></embed>

</OBJECT>

A: Try this:

some text


text:
Q: Realm Swift iOS using shouldIncludeInDefaultSchema in Object class crashes app I write and maintain an xcframework that uses Realm. As well, apps that use our framework would like to use Realm. Therefore, I want to exclude our Object subclasses from the default.realm schema. I have read postings that tout the use of:
public override class func shouldIncludeInDefaultSchema() -> Bool { return false}
in an Object subclass. When I do this I consistently get a crash like this:
2023-01-10 12:18:28.008097-0800 AppIngo *** Terminating app due to uncaught exception 'RLMException', reason: 'Object type 'SomeEntity' not managed by the Realm'
So my questions are:

*

*Is this a supported mechanism for keeping Object subclasses out of the default.realm? If so, is there anything thing we need to do make this work and not crash?

*Is there any other strategy/mechanism to achieve what we are looking for.


text:
Q: Как работает шум Перлина? Объясните пожалуйста как работает шум Перлина в двумерном пространстве. На русском ничего понятного не нашёл. Есть много статей с описанием этого шума, но половина из них, как оказалось, говорит не о шуме Перлина, а принцип работы остальных мне понять не удалось. На этом сайте вообще ничего по шуму Перлина нет.
Я бы хотел привести в пример свои попытки реализации данного алгоритма, но у меня ничего нет, я не могу понять как он работает и следовательно не могу ничего написать.
Скажем есть двумерный массив, каждый элемент которого — пиксель. В случае с фрактальным шумом всё понятно: Каждый пиксель каким-то образом рассчитывается на основе предыдущих. Как работает градиентный шум?
Я понял, что: Каждому пикселю нужно высчитать вектора на основе чистого рандома, затем эти вектора нужно каким-то образом преобразовать в значение, которое уже присваивается пикселю.
Где логика? Где зависимость одного пикселя от другого (как в случае с фрактальным шумом)? Прошу объяснить максимально доступно.
Шум планирую использовать для генерации текстур.

A: Случайные вектора строятся не для каждого пикселя, а для узловых точек.
Значение конкретных пикселей рассчитывается как интерполяция тех узловых точек, между которых этот пиксель находится.
Соответственно, прямой зависимости пикселей друг от друга нет. Но значения соседних пикселей рассчитываются на основе тех же опорных точек с близкими коэффициентами. За счёт этого значения близких пикселей получаются похожими.
Достаточно понятно это объяснено тут:
https://habrahabr.ru/post/265775/
Странно, если вы не нашли эту статью, она легко гуглится по "Шум Перлина"


text:
Q: mongodb sort unpopulated subdocument I'm trying to sort unbinded subdocuments. This is the collection:
[
    {
        otherFields: {},
        visites: ["58d46ffbf1c383862cf5de4a", "58d46ffbf1c383862cf5de49"]
    }
]

And this is the aggregate:
db.exps.aggregate([
    { "$match": {} },
    { "$project": { "visites": 1 } },
    { "$unwind": "$visites" },
    { "$sort": { "visites.formVersion": 1 } },
    { "$group": { "_id": null, "count": { "$sum": 1 }, "data": { "$push": "$visites" } } }
])

I've realized that it has no sense to sort with a subfield, as the visites field is just an array of id's. Is it possible to populate them inside aggregate, so they can be sorted?
The results after nodejs population are these ones:
{
    "count": 50,
    "data": [
        {
            "_id": "58d46ffbf1c383862cf5de4a",
            "formVersion": 4,
            "start": "2017-06-04T07:30:00.000Z",
            "end": "2017-06-04T08:30:00.000Z",
            "type": "assessor",
            "expedient": "58d46ffaf1c383862cf5de41",
            "user": "58d46ff8f1c383862cf5de3a",
            "__v": 0,
            "isDeleted": false,
            "lastModified": "2017-03-24T01:01:47.343Z",
            "created": "2017-03-24T01:01:47.330Z"
        },
        {
            "_id": "58d46ffbf1c383862cf5de49",
            "formVersion": 3,
            "start": "2017-06-03T07:30:00.000Z",
            "end": "2017-06-03T08:30:00.000Z",
            "type": "assessor",
            "expedient": "58d46ffaf1c383862cf5de41",
            "user": "58d46ff8f1c383862cf5de3a",
            "__v": 0,
            "isDeleted": false,
            "lastModified": "2017-03-24T01:01:47.341Z",
            "created": "2017-03-24T01:01:47.328Z"
        },

A: Assuming two collections coll1 and coll2:
> db.coll1.find()

{
 "_id": ObjectId("58eecf2a11b7af6f560666d8"),
  "otherFields": {

 },
 "visites": [
   "58d46ffbf1c383862cf5de4a",
   "58d46ffbf1c383862cf5de49"
  ]
}
> db.coll2.find()
{
  "_id": "58d46ffbf1c383862cf5de4a",
  "formVersion": 4,
  "start": "2017-06-04T07:30:00.000Z",
  "end": "2017-06-04T08:30:00.000Z",
  "type": "assessor",
  "expedient": "58d46ffaf1c383862cf5de41",
  "user": "58d46ff8f1c383862cf5de3a",
  "__v": 0,
  "isDeleted": false,
  "lastModified": "2017-03-24T01:01:47.343Z",
  "created": "2017-03-24T01:01:47.330Z"
}
{
  "_id": "58d46ffbf1c383862cf5de49",
  "formVersion": 3,
  "start": "2017-06-03T07:30:00.000Z",
  "end": "2017-06-03T08:30:00.000Z",
  "type": "assessor",
  "expedient": "58d46ffaf1c383862cf5de41",
  "user": "58d46ff8f1c383862cf5de3a",
  "__v": 0,
  "isDeleted": false,
  "lastModified": "2017-03-24T01:01:47.341Z",
  "created": "2017-03-24T01:01:47.328Z"
}

If you're looking to sort by e.g. the formVersion field, one possible aggregate pipeline solution could be:
db.coll1.aggregate([
// left outer join from coll2 to coll1
{$lookup:{
    from:"coll2",
    localField:"visites",
    foreignField:"_id",
    as:"data"
}},

// unwind the resulting array
{$unwind:"$data"},

// sort the unwinded documents using the formVersion field
{$sort:{"_id":1 ,"data.formVersion": 1}},

// collect the results into an array
{$group:{"_id":null, data:{$push:"$data"}}}
])

The result of the pipeline is:
 {
  "_id": null,
  "data": [
    {
      "_id": "58d46ffbf1c383862cf5de49",
      "formVersion": 3,
      "start": "2017-06-03T07:30:00.000Z",
      "end": "2017-06-03T08:30:00.000Z",
      "type": "assessor",
      "expedient": "58d46ffaf1c383862cf5de41",
      "user": "58d46ff8f1c383862cf5de3a",
      "__v": 0,
      "isDeleted": false,
      "lastModified": "2017-03-24T01:01:47.341Z",
      "created": "2017-03-24T01:01:47.328Z"
    },
    {
      "_id": "58d46ffbf1c383862cf5de4a",
      "formVersion": 4,
      "start": "2017-06-04T07:30:00.000Z",
      "end": "2017-06-04T08:30:00.000Z",
      "type": "assessor",
      "expedient": "58d46ffaf1c383862cf5de41",
      "user": "58d46ff8f1c383862cf5de3a",
      "__v": 0,
      "isDeleted": false,
      "lastModified": "2017-03-24T01:01:47.343Z",
      "created": "2017-03-24T01:01:47.330Z"
    }
  ]
}

Please note that as of MongoDB 3.4, there are certain limitations in the $lookup stage; such as the two collections must be in the same database, and the from parameter cannot be a sharded collection. For more details, please see https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
Also please note that the last $group stage would result in a single document, which will be bound by MongoDB's 16 MB document size limit. If you prefer, you can remove the $group stage and iterate on the cursor returned by the $sort stage instead.


text:
Q: Write a program that asks a user to enters pairs of numbers until they enter "quit". add the numbers using a function "Write a program that asks a user to enters pairs of numbers until they enter "quit". As each pair of numbers is entered and validated, add the numbers using a function. The function will have two parameters for the pair of numbers and will return the sum. After the user enters "quit", output all the pairs of numbers and their sums."
This is my function below
function evaluatingUserInput() {

    // Variable declaration.
    var numberOne;
    var numberTwo;
    var total = 0;

    // While user input is not the string "quit" prompt the user again.
    while(numberOne != "quit"){

        numberOne = prompt("Please enter a number or quit to stop.");
        numberTwo = prompt("please enter a second number or quit to stop.");

        numberOne = Number(numberOne);
        numberTwo = Number(numberTwo);
        total = numberOne + numberTwo;

        document.write(numberOne + " + ");
        document.write(numberTwo + " = ");
        document.write(total);
        document.write("<br />");
    }
}

A: I'm not too sure what you are trying to achieve, but I'll try to do my best to help you. I don't want to give you any false information.
First, instead of using while(), I would use setInterval().
setInterval(function(){
 if (numberOne != "quit") {
  //the code you had inside while()
 }
}, 1);

Also, document.write will overwrite everything that you have on the document. So instead of doing that I would use this:
var number = document.createElement("P")
number.innerHTML = numberOne + " + " + numberTwo + " = " + total;
document.body.appendChild(number)


text:
Q: How to make ul padding-right being respected by list items when dynamically set (inside a timeout) The problem I am facing is when trying to set the padding-right property of a  element, inside a code running in a setTimeout, the li elements inside it are not properly resized.
The problem does not occur (or at least very seldom) when I am not inside a setTimeout.
Can someone confirm this is a webkit bug or otherwise point to a solution?
I was able to reproduce it in Chrome and Safari.
I have created 3 scenarios (please use Chrome and Safari to test):

*

*The ul with padding-right in static css - obviously works http://jsbin.com/ufifos/5/edit

*The ul with padding-right set in js code not inside setTimeout - works (most of the times) see jsbin.com/ekazow/1/edit

*The ul with padding-right set in js code inside a setTimeout - NOT WORKING properly http://jsbin.com/uzorux/1/edit
The padding-right is set, but the li elements are not repainted correctly. A browser resize (or a few resizes) fixes it.
Basically the code is
setTimeout(function(){

    document.getElementById('container').style.paddingRight = '20px';

}, 2000);

A: The problem is with this rule:
li {
   width: 100%;
}

It is not in the first "working" test.  Remove it and it should work fine.  You might need to set display: block on the li as well.


text:
Q: Term for a particular type of specious argument
Is there a name for the debating technique of trying to advance a
  specious argument by passing off an fallacious assumption as an
  accepted truth?

The context for this was in a communication that I recently received from a colleague rebutting a theoretical paper he had read regarding biomolecular interactions and networks. You do not need to understand the subject matter to follow this, which I have abbreviated and simplified, and set out in a way to make the structure clear:

*

*Smith and Jones propose that this network of interactions is an
important buffer against mutations…

*…but it is well known that anything can interact with anything
else…

*…therefore the original proposal is patently incorrect.

i.e.

*

*Argument to be rebutted

*Fallacious assumption (It is not true that "anything can interact
with anything else", at least in this context.)

*Erroneous conclusion

I emphasize that it is a name for the debating technique that I am after, not adjectives describing it or its components. I seem to remember there was as series in the Financial Times (London) on different techniques of rhetoric, all of which seemed to have Greek names. However none of those listed on pages such as this  seem to fit the bill.

A: I'm going to provide an answer, but I'm not sure if this shouldn't actually be asked at Philosophy.SE instead.

From the "Logical Fallacies Handlist", it seems similar to this:

Irrelevant Conclusion (Ignorantio Elenchi): This fallacy occurs when a rhetorician adapts an argument purporting to establish a particular conclusion and directs it to prove a different conclusion. For example, when a particular proposal for housing legislation is under consideration, a legislator may argue that decent housing for all people is desirable. Everyone, presumably, will agree. However, the question at hand concerns a particular measure. The question really isn't, "Is it good to have decent housing?" The question really is, "Will this particular measure actually provide it or is there a better alternative?" This type of fallacy is a common one in student papers when students use a shared assumption--such as the fact that decent housing is a desirable thing to have--and then spend the bulk of their essays focused on that fact rather than the real question at issue.

The final statement about this type of fallacy says that it's similar to begging the question, a type of fallacy that means something different than the popularized English phrase of the same words.

In this specific case:
Hypothesis:
      Smith and Jones propose a specific interaction.
Misleading Argument:
      But surely you know that anything can interact with something else.
Faulty Conclusion:
      Therefore, there's nothing unusual (important) about this interaction.

In an analogous case:
Hypothesis:
      The defendant is guilty.
Misleading Argument:
      But surely you know that everybody's guilty of something.
Faulty Conclusion:
      Therefore, the defendant is guilty.


text:
Q: ValueError: Found array with 0 feature(s) (shape=(16, 0)) while a minimum of 1 is required.? I was just trying to learn about machine learning, and I tried this script but I got an error. Can anyone explain to me what is wrong with this particular code?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn
dataset = pd.read_csv('sales_data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, :1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,
                                               y,
                                               test_size = 0.2,
                                               random_state = 0)
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train) #this line 15 generates the error message
y_pred = regressor.predict(X_test)
plt.scatter(dataku.BiayaPromo, dataku.NilaiPenjualan)
plt.xlabel("Biaya Promosi")
plt.ylabel("Nilai Penjualan")
plt.title("Grafik Nilai Penjualan VS Biaya Promosi")
plt.show()

return eror :
the eror is in line 15
    ValueError: Found array with 0 feature(s) (shape=(16, 0)) while a minimum of 1 is required.


text:
Q: Unable to add or copy gas-preprocessor.pl in usr/bin on macOS Sierra Im trying to add gas-preprocessor.pl to usr/bin. Adding it to usr/local/bin does not work.
I tried switching to root user and performing the action. The operation to copy or add this file is still not permitted.
Thanks for help in advance.

A: Since creating a soft link doesnt work for me, this link helped for the work around. http://tips.tutorialhorizon.com/2016/07/30/docker-usrlocalbindocker-machine-permission-denied/
Command: sudo chown -R $(whoami) /usr/local/bin

A: sudo ln -s gaspreprocessor/path /usr/bin/local/gaspreprocessor

Be sure gaspp is executable