text:
Q: React Native Image Cache Ignore the Query Params for Image URL In our react native project, we got the image url with the signing key append after the image url. Like http://my_bucket.s3.amazon.com/my_profile.jpg?signing_key=I_am_changeable_every_time.
We show the above url as following:
<ImageView source={{ uri: photo.uri }} />

We want to react native image component could handle the image cache for us. While the react native image component would load the image every time. One possible reason is that the react native image component does not really do any cache stuff.
Then we're trying to find some external react-image-cache library.
But as my understanding, almost all the image cache library would treat the whole image url as the cache key. What should we do if our image has a signing_key param which would change over time
We have thought using the image_path instead of the image_full_url or the image_id in our business context as the cache key. While we have not found any library which could give us this ability.
My question is that: How can we handle the changeable image url cache, is there any library you recommended?
Thanks!

A: Try react-native-cached-image. You can tell it to ignore the query params.
type ImageCacheManagerOptions = {
  headers: PropTypes.object,                      // an object to be used as the headers when sending the request for the url. default {}

  ttl: PropTypes.number,                          // the number of seconds each url will stay in the cache. default 2 weeks

  useQueryParamsInCacheKey: PropTypes.oneOfType([ // when handling a URL with query params, this indicates how it should be treated:
    PropTypes.bool,                               // if a bool value is given the whole query string will be used / ignored
    PropTypes.arrayOf(PropTypes.string)           // if an array of strings is given, only these keys will be taken from the query string.
  ]),                                             // default false

  cacheLocation: PropTypes.string,                // the path to the root of the cache folder. default the device cache dir

  allowSelfSignedSSL: PropTypes.bool,             // true to allow self signed SSL URLs to be downloaded. default false
};


text:
Q: HTML form PHP post not hitting Not sure why I am having this issue, I am making a edit form that will allow the users to update data.
I have an HTML form that looks like this:
<form enctype="multipart/form-data" method="post" action="updatefacility.php">
    Facility Number:
    <input type="text" id="fac_number" name="fac_number" value="<?php if (!empty($facNum)) echo $facNum; ?>" />

    Facility Name:
    <input type="text" id="fac_name" name="fac_name" value="<?php if (!empty($facName)) echo $facName; ?>" />

    Address:
    <input type="text" id="fac_address" name="fac_address" value="<?php if (!empty($facAddress)) echo $facAddress; ?>" />

    <input type="button" value="Update" name="update">
</form>

When I click my button I should be hitting updatefacility.php which looks like this:
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
    die("Connection failed: " . mysqli_connect_error());
}

 if (isset($_POST['update'])) {

     echo "test";
 }

When I am clicking my button I am expecting my form to submit and return a blank page with the word "test" on it, however nothing happens..
Am I missing something here?
Thanks

A: You need to change the input type from button to submit.
Like this:
<input type="submit" value="Update" name="update">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Initialize database without XML configuration, but using @Configuration I would like to know how to initialize a database without having to create an XML file.
I already use this kind of initialization that works fine, but in my current case I don't want to create an XML:
<jdbc:initialize-database data-source="dataSource">
  <jdbc:script location="classpath:com/foo/sql/db-schema.sql"/>
  <jdbc:script location="classpath:com/foo/sql/db-test-data.sql"/>
</jdbc:initialize-database>

I know I can create an embedded database with:
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(H2).addScript("my-schema.sql").addScript("my-test-data.sql").build();

In my case, the database and schema are created using Liquibase.
I just want to initialize it with Spring and with my customized dataset, without having to create a new XML file each time just for that.
Is it possible?

A: It certainly is possible.
If you already have an @Configuration class that is being loaded by Spring's ApplicationContext, then you simply have to create a new @Bean method that will contain the code you have there already (with an additional return statement of course).
EmbeddedDatabase implements the DataSource interface, so it can easily be used with JdbcTemplate's.
@Bean
public DataSource db() {
    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    builder.setType(H2).addScript("my-schema.sql").addScript("my-test-data.sql");
    return builder.build();
}

A: After looking at Spring classes related to EmbeddedDatabaseBuilder I found out that the DatabaseBuilder is using some code looking like this:
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
for (String sqlScript: sqlInitializationScripts ) {
  Resource sqlScriptResource = RESOURCE_LOADER.getResource(sqlScript);
  populator.addScript(sqlScriptResource);
}
DatabasePopulatorUtils.execute(populator, dataSource);

This will work fine for me, even if it will be on a @BeforeTest method and not on the Spring configuration.

A: The following lines of code inside your @Configuration class might work.
@Value("classpath:com/foo/sql/db-schema.sql")
private Resource schemaScript;

@Value("classpath:com/foo/sql/db-test-data.sql")
private Resource dataScript;

@Bean
public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
    final DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource);
    initializer.setDatabasePopulator(databasePopulator());
    return initializer;
}

private DatabasePopulator databasePopulator() {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(schemaScript);
    populator.addScript(dataScript);
    return populator;
}

A: You have to create your own schema.sql and put it in your src/main/resources-folder.
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

@Configuration
public class DataSourceInitializer {

    @Bean(name = "dataSource")
    public DataSource getDataSource(){
        DataSource dataSource = createDataSource();
        DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource);
        return dataSource;
    }

    private DatabasePopulator createDatabasePopulator() {
        ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
        databasePopulator.setContinueOnError(true);
        databasePopulator.addScript(new ClassPathResource("schema.sql"));
        return databasePopulator;
    }

    private SimpleDriverDataSource createDataSource() {
        SimpleDriverDataSource simpleDriverDataSource = new SimpleDriverDataSource();
        simpleDriverDataSource.setDriverClass(org.h2.Driver.class);
        simpleDriverDataSource.setUrl("jdbc:h2:target/database/example;AUTO_RECONNECT=TRUE");
        simpleDriverDataSource.setUsername("");
        simpleDriverDataSource.setPassword("");
        return simpleDriverDataSource;
    }
}


text:
Q: How to access a nested hash of arrays in a loop? I have data in this format
a1 1901 4
a1 1902 5
a3 1902 6
a4 1902 7
a4 1903 8
a5 1903 9

I want to calculate the cumulative score (3rd column) for each entity in the first column. So I tried to make a hash and my code looks like this:
use strict;
use warnings;

use Data::Dumper;

my $file = shift;
open (DATA, $file);

my %hash;
while ( my $line = <DATA> ) {
  chomp $line;
  my ($protein, $year, $score) = split /\s+/, $line;
  push @{ $hash{$protein}{$year} }, $score;
}

print Dumper \%hash;

close DATA:

The output looks like this
$VAR1 = {
          'a3' => {
                    '1902' => [
                                5
                              ]
                  },
          'a1' => {
                    '1902' => [
                                6
                              ],
                    '1901' => [
                                4
                              ]
                  },
          'a4' => {
                    '1903' => [
                                8
                              ],
                    '1902' => [
                                7
                              ]
                  },
          'a5' => {
                    '1903' => [
                                9
                              ]
                  }
        };

I now want to access each entity in column 1 (a1,a2,a3) and add the score, so the desired output will be something like this:
a1 1901 4
a1 1902 9    # 4+5
a3 1902 6
a4 1902 7
a4 1903 16   # 7+9
a5 1903 9

But I am unable to come up with how to access the values of the created hash in a loop in order to add the values?

A: I think
a4 1903 16   # Sum of a4 1902 and a5 1903

should be
a4 1903 15   # Sum of a4 1902 and a4 1903

If so,
my %scores_by_protein_and_year;
while (<DATA>) {
   my ($protein, $year, $score) = split;
   $scores_by_protein_and_year{$protein}{$year} = $score;
}

for my $protein (keys(%scores_by_protein_and_year)) {
   my $scores_by_year = $scores_by_protein_and_year{$protein};
   my $score = 0;
   for my $year (sort { $a <=> $b } keys(%$scores_by_year)) {
      $score += $scores_by_year->{$year};
      say "$protein $year $score";
   }
}

This works even if the data isn't grouped/sorted.

A: If the data is always sorted as you show it then you can process the data as you read it from the file:
while ( <DATA> ) {
    my ($protein, $year, $score) = split;

    $total = 0 unless $protein eq $current;
    $total += $score;

    print "$protein $year $total\n";

    $current = $protein;
}

output
a1 1901 4
a1 1902 9
a3 1902 6
a4 1902 7
a4 1903 15
a5 1903 9


text:
Q: virtual gateway interface I would like your opinion on my Linux router setup. Let's say I have default ISP (main routing table) and a specific one (routing table custom). Default ISP is on eth0 and custom one is on eth2. For default one, it's DHCP and shiny auto routes, custom one looks like this:
# echo "4999 custom" >> /etc/iproute2/rt_tables
# ip addr eth2 10.x.y.z netmask 255.255.255.0
# ip -4 route add 0.0.0.0/0 via 10.20.30.40 table custom
# iptables -t nat -A POSTROUTING -o eth2 -j MASQUERADE

So now, anything that gets routed to eth2 is going via custom ISP. It works fine. What I want, is to create a virtual interface (VETH? TAP? I don't know) with specific IP such, that I could give it to my LAN clients and get them routed via this custom ISP. I would also prefer it to be visible during a traceroute.
LAN has 172.16.1.0/24 network. What I've tried:
# ip tuntap add name tap0 mode tap
# ip addr add 172.16.1.128 dev tap0
# ip rule add iif tap0 lookup custom

However, this doesn't work. If I specify this 172.16.1.128 as a default gateway for my clients, pings don't go past it. What am I doing wrong?
UPDATE:
As for initial routing rule: LAN is at eth1, and I've used this to test custom ISP connectivity:
ip rule add iif eth1 lookup custom

I understand that I can add something like fwmark-based rule, but then it's back to iptbles doing all hard work (src nat), and that's slow and inefficient.


text:
Q: TYPO3-6.2 Extbase custom content type -> invalid value I made an extbase Extension for custom content elements. Since this is my first extension I started with a simple "hello_world_ce". This are my files:
ext_tables.php
<?php
$TCA['tt_content']['types']['hello_world_ce']['showitem'] = '--palette--;LLL:EXT:hello_world/Resources/Private/Language/locallang_mod.xlf:content_element.hello_world.general;general, --palette--;LLL:EXT:hello_world/Resources/Private/Language/locallang_mod.xlf:content_element.hello_world.header;header';

ext_localconf.php
<?php
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPageTSConfig('<INCLUDE_TYPOSCRIPT: source="FILE:EXT:'.$_EXTKEY.'/Configuration/TypoScript/ModWizards.ts">');

ModWizards.ts
mod.wizards {
    newContentElement {
        wizardItems {
            hello_world {
                header = LLL:EXT:hello_world/Resources/Private/Language/locallang_mod.xlf:content_tab_header
                elements {
                    hello_world_ce {
                        icon = gfx/c_wiz/regular_header.gif
                        title = LLL:EXT:hello_world/Resources/Private/Language/locallang_mod.xlf:content_element.hello_world
                        description = LLL:EXT:hello_world/Resources/Private/Language/locallang_mod.xlf:content_element.hello_world.description
                        tt_content_defValues {
                            CType = hello_world_ce
                        }
                    }
                }
            }
            show = *
        }
    }
}

In the TYPO3 Backend I see my content element and can add it to a page but the dropdown menu for the content type says INVALID VALUE ("hello_world_ce")
What am I missing?
EDIT: I found the missing part. I needed to add my content type to the CType array
ext_tables.php
$backupCTypeItems = $GLOBALS['TCA']['tt_content']['columns']['CType']['config']['items'];
$GLOBALS['TCA']['tt_content']['columns']['CType']['config']['items'] = array(
    array(
        'LLL:EXT:'.$_EXTKEY.'/Resources/Private/Language/locallang_mod.xlf:content_tab_header',
        '--div--'
    ),
    array(
        'LLL:EXT:'.$_EXTKEY.'/Resources/Private/Language/locallang_mod.xlf:content_element.hello_world',
        'hello_world_ce',
        'i/tt_content_header.gif'
    )
);
foreach($backupCTypeItems as $key => $value){
    $GLOBALS['TCA']['tt_content']['columns']['CType']['config']['items'][] = $value;
}

A: The question was edited, but I think there is a better way to achieve the solution.
Only to be clear about the problem:
The content element hello_world_ce was not added to the "types" dropdown by adding a new content element.
The hint in the question is correct it was not defined for the CType field.
But instead of manipulating the array you could use a core function:
 // Adds the content element to the "Type" dropdown
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPlugin(
   array(
      'LLL:EXT:your_extension_key/Resources/Private/Language/locallang_mod.xlf:content_element.hello_world',
      'hello_world_ce',
      'i/tt_content_header.gif'
   ),
   'CType',
   'your_extension_key'
);

Here is a very good example of how to add your own content element in the version TYPO3 7.6.
Note: This function is accessible in TYPO3 6.2 as well.


text:
Q: Django form for a table of checkboxes I'm trying to create a table-scheduler where people can pick the timeslots where they're free. I'm using django with a postgresql database. I have the below model:
class Person(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, unique=True)
    name = models.CharField(max_length=100)
    monday = models.mulitpleChoiceField(choices= ["12-1", "1-2", "2-3"])
    tuesday = models.mulitpleChoiceField(choices= ["12-1", "1-2", "2-3"])
    wednesday = models.mulitpleChoiceField(choices= ["12-1", "1-2", "2-3"])
    thursday = models.mulitpleChoiceField(choices= ["12-1", "1-2", "2-3"])
    friday = models.mulitpleChoiceField(choices= ["12-1", "1-2", "2-3"])
    saturday = models.mulitpleChoiceField(choices= ["12-1", "1-2", "2-3"])
    sunday = models.mulitpleChoiceField(choices= ["12-1", "1-2", "2-3"])

The question is how do I create a form using modelForm that will give me a table, with rows = days and columns = timeslots, where the user can just check a checkbox to indicate when they are free.
Currently my forms.py just looks like this:
class UserForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = [
            "name",
            "monday",
            "tuesday",
            "wednesday",
            "thursday",
            "friday",
            "saturday",
            "sunday",
        ]

I'm still pretty new to django and only pick it up a month ago. Thanks for any advice that is given.

A: I would simply use two datetime fields and the render the table with slots in the front-end with javascript. You would have to have a start_time and an end_time field.
This simplifies the model but means the model itself does not limit the time ranges (e.g Monday 12-13) and instead allows for any time to be selected. However, you could use custom validation to limit the time ranges that can be selected. I.e. so that they can only be selected in hour intervals or whatever your requirements are. I'm sure there is some online source that can help you with this but if you can't find any then let me know and I'll see if I can help.
I tried to find a javascript/jQuery library that already handles the time-picker functionality but was unable to find one. It would be fairly simple to create though. How I see it:

*

*Table of date ranges with each element having both a data-start and data-end attribute.

*On click of the time range, gather the two data attributes.

*On submit, stop propagation and submit the two date ranges to the view and save to start_time and end_time.


text:
Q: Prove inequality: $\frac{P+2004a}{P-2a}\cdot\frac{P+2004b}{P-2b}\cdot\frac{P+2004c}{P-2c}\ge2007^3.$
Let $a,b,c$ the sides of a triangle, $P$  its perimeter. Prove inequality:
  $$\frac{P+2004a}{P-2a}\cdot\frac{P+2004b}{P-2b}\cdot\frac{P+2004c}{P-2c}\ge2007^3.$$

My  attempt:
1) $P=a+b+c$. Then $\frac{P+2004a}{P-2a}=\frac{2005a+b+c}{b+c-a}$. Here $b+c-a>0 -$ triangle inequality.
2) $\sqrt[3]{xyz}\ge\frac{3}{\frac1x+\frac1y+\frac1z} \Rightarrow xyz\ge \left(\frac{3}{\frac1x+\frac1y+\frac1z}\right)^3$

A: Let
$$b+c-a=s,\quad c+a-b=t,\quad a+b-c=u$$
Then, we can have
$$a=\frac{t+u}{2},\quad b=\frac{s+u}{2},\quad c=\frac{s+t}{2}$$
So, using AM-GM inequality and letting $d=1003$,
$$\begin{align}&\frac{P+2004a}{P-2a}\cdot\frac{P+2004b}{P-2b}\cdot\frac{P+2004c}{P-2c}\\\\&=\left(1+d\frac ts+d\frac us\right)\left(1+d\frac st+d\frac ut\right)\left(1+d\frac su+d\frac tu\right)\\\\&=2d^3+3d^2+1+(d^3+d^2+d)\left(\frac su+\frac st+\frac tu+\frac ts+\frac us+\frac ut\right)+d^2\left(\frac{s^2}{tu}+\frac{t^2}{su}+\frac{u^2}{st}\right)\\\\&\ge 2d^3+3d^2+1+6(d^3+d^2+d)\sqrt[6]{1}+3d^2\sqrt[3]{1}\\\\&=(2d+1)^3\\\\&=2007^3\end{align}$$

A: I think it has to be $3\cdot 2007$ instead of $2007^3$. Since $a,b,c$ are sides of a triangle, there exist $x,y,z>0$ such that
$a=y+z$, $b=z+x$ and $c=x+y$. Hence, we have to prove:
$$
\sum_{cyc}\frac{2005(x+y)+(y+z)+(z+x)}{2(x+y+z)-2(x+y)}≥3\cdot 2007\iff\\
\sum_{cyc}\frac{2006x+2006y+2z}{2z}≥3\cdot 2007\iff\\
3+1003\sum_{sym}\frac{x}{y}≥3\cdot 2007
$$
Now with AM-GM, we have $\sum_{sym}\frac{x}{y}≥6$ and thus:
$$
3+1003\sum_{sym}\frac{x}{y}≥3+6\cdot1003=3\cdot 2007
$$
Withe equality iff $x=y=z\iff a=b=c$.


text:
Q: Intuition behind the Compensating Variation! In Economics, we can calculate the compensating variation (CV), which (to my understanding) is the amount of money we would need to give back to a consumer to keep them at the same level of Utility after a price increase:
For a standard objective function e.g. $U(x,y) = x^{1/2}y^{1/2}$ and budget line  $P_xx + P_yy = M$
Optimal $U_0 = \frac{M}{2(P_xP_y)^{1/2}}$
The formulae given to me in my book for calculating CV is as follows (I understand if it's compensating variation $∆M$ will actually be negative given how the following is constructed):
$\frac{M - ∆M}{2(P_x'P_y)^{1/2}} = U_0 = \frac{M}{2(P_xP_y)^{1/2}}$ and solve for $∆M$

*

*Where $P_x'$ is our increased price for $x$

*$U_1 = \frac{M}{2(P_x'P_y)^{1/2}}$ is the new utility with respect to the price increase.

Question 1: Why is it not $\frac{M}{2(P_x'P_y)^{1/2}} - ∆M = U_0$? This seems to be a more strait forward way of adding/subtracting the additional income to keep us on $U_0$. The original formulation seems to be more about adding/subtracting Utility? I.e. we could define a $U_1' = \frac{∆M}{2(P_x'P_y)^{1/2}}$

*

*What's the intuition here?

Question 2: Given the Utility function $U(x,y) = xy$ and the same budget constraint, we get optimal utility: $\frac{M^2}{4(P_x'P_y)}$
What would be the correct equation for compensating variation and why:

*

*$\frac{M^2 - ∆M}{4(P_x'P_y)} = U_0$

*$\frac{(M - ∆M)^2}{4(P_x'P_y)} = U_0$

*$\frac{M^2 - ∆M^2}{4(P_x'P_y)} = U_0$

*$\frac{M^2}{4(P_x'P_y)} - ∆M = U_0$
The first option works - I have worked through a numerical example and also compared the $∆M$ you get here with the $∆M$ you get from solving it in terms of the expenditure function.

*

*But i would love help on the intuition about why it's the first, and not the others (Assuming they don't work!)

Thank you!

A: First, if I knew nothing about CV, I would say that that your intuition on computing it, namely
$$\frac{M}{2(P_x'P_y)^{1/2}} - ∆M = U_0,$$
looks wrong just on the basis of units.  The second term on the left-hand side has units of dollars, while first term on the left-hand side has units of
$$ {\text{dollars}\over \sqrt{\text{dollars}^2\over (\text{unit of x})\cdot (\text{unit of y}) }}=\sqrt{(\text{unit of x})\cdot (\text{unit of y})}.$$
A quick dimensional analysis sometimes tell us a lot.

Now, I think both your questions will be cleared up with an understanding of the actual definition of CV.  First start with the indirect utility function $v(P,M)$: this is the value of the maximized utility as a function of the vector of prices $P$ and income $M$.  CV is defined as the amount a government would need to tax you after a price change to keep you just as well off as before the price change:
$$v(P_1,M-CV)=U_0=v(P_0,M).$$
In particular, assuming indirect utility decreases in prices, CV will be positive if prices fall; contrastingly, CV will be negative if prices rise (i.e. government would have to subsidize you).
Your examples are special cases of Cobb-Douglas utilities.  You can see option 2 would be the appropriate equation for your question 2.


text:
Q: How do I perform a parallel reduce operation on a recursive structure in Clojure? I'm presented with a tree data structure that I want to process or "evaluate" using a post-walk. There are two exploitable features to the problem:

*

*Disjoint subtrees can be processed independently

*Processing the same sub-tree always yields the same result, so partial results can be memoized (even between workers if possible)

One constraint is that the number of sub-trees may be quite large so I can't spawn a new thread for every sub-tree willy-nilly. Is there any library support that anticipates such a scenario?


text:
Q: Is this possible to remove a moderator status tag if I change my question? I asked this question here on MSE a while ago, as a feature-request, which later got rejected by a moderator. After doing edits to most of my questions, I thought it would be a good idea to change the original tag into a support tag and to delete the status-declined tag too.
However, when I went to edit the tags, it showed this error:

That basically meant I wasn't able to remove the moderator tag, and I had to add it back, even though I switched the whole topic of the question and all of the other tags.
How can I remove a moderator tag, do I have to ask a moderator to remove it?

A:
… wasn't able to remove the moderator tag … even though I switched the whole topic of the question

If you are completely changing the subject of your question, you should just ask a new question. Once a question has been asked and answered, it's a bit odd (and perhaps inappropriate) to try and change it to something else in-place.
Moderator tags, as their name suggests, are for moderators only. You cannot add or remove any moderator tags on any questions. But if you do have a valid reason to have a moderator tag removed, flag it for moderator attention and select the option "in need of moderator intervention" to explain the situation.


text:
Q: How do I get the value of the  from an xml doc tag in Javascript? I am successfully parsing an xml document in javascript, having read it in via an XMLHttpRequest
I now want to grab one additional piece of info. The feed I'm reading contains this tag
<opensearch:totalResults>118</opensearch:totalResults>
How do I read the value it contains?
I've used Firefox's console to examine the xml doc's contents, looking in vain for where it's mentioned.
Online searches don't help either.
Although not really relevant, the start of the heart of my code is:
    var process = function (xml) {
    var i, xmlDoc, table;
    xmlDoc = xml.responseXML;
    globXmlDoc = xmlDoc;
    var myItemAsAnObject = [];
    if (xmlDoc === null){
    feedLength = 0;
    } else {
    feedLength = xmlDoc.getElementsByTagName("item").length;
    if (feedLength == 0) { return false; }
    var x = xmlDoc.getElementsByTagName("item");

The XML is
<rss version="2.0">
<channel>
<title>victoriana: Zazzle.com Store: Matching "victoriana"</title>
<link>http://feed.zazzle.com/z.2/api/find.aspx?qs=victoriana&ft=rss&ou=%2Frss%3Fqs%3Dvictoriana</link>
<description/>
<language>en-us</language>
<pubDate>Thu, 04 Jul 2019 17:26:55 GMT</pubDate>
<ttl>60</ttl>
<opensearch:totalResults>118</opensearch:totalResults>
<opensearch:startIndex>1</opensearch:startIndex>
<opensearch:itemsPerPage>60</opensearch:itemsPerPage>
<opensearch:Query role="request" searchTerms="victoriana"/>
<item>
:
:
:

A link to the entire xml doc is:
rss feed
Note that the globxmlDoc is a global var just to let me look at it in the console.
I don't really know where to start....

A: Open this HTML doc and you will get 118 (Tested using Chrome)
<!DOCTYPE html>


text:
Q: Fixed terms in dredge function (MuMin) in GAM I am trying to use MuMIn::dredge()function to build a GAM model. I am working on fish distribution and with the aim to speed up the analysis due the size of the dataset, I want to fix two variables, for example, depth and the interaction (latitude, longitude).
I have read the package documentation and also have looked for any suggestion in this forum  but I have not been successful. The following code works,
Allmodels_Presence <- dredge(Gadiculus_Pres, rank=AIC, fixed= ~s(depth, k=4), trace=2)

for but it only has fixed one variable and I don´t know how to fix the other one s(Lon_Proj, Lat_Proj, k=20), even though I have tried several approaches (mainly following the help for subsetting in dredge() ).
Any idea or suggestions will be more than welcome. Thanks in advance.

A: From the MuMIn documentation:

fixed - optional, either a single-sided formula or a character vector
giving names of terms to be included in all models.

You need to put the names of the variables, enclosed in '', into a vector:
Allmodels_Presence <- dredge(Gadiculus_Pres, rank=AIC,
                             fixed= c('s(depth, k=4)', 's(Lon_Proj, Lat_Proj, k=20)'),
                             trace=2)


text:
Q: Как добавить к слайдеру Bootstrap 4 кнопки для переключения? Вопрос заключается в следующем: я убираю индикаторы в слайдер, делаю слайдер статичным. И нужно, чтобы переключение слайдера осуществлялось либо стрелками, либо вверху над слайдером должны быть кнопки и переключать ими. Как реализовать? Заранее спасибо.

A: Можно индикаторы просто вынести туда куда надо и  использовать их вместо кнопок. Пример на boostrap 4.

@import "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css";

#carouselExampleIndicators {
  width: 400px;
}

.carousel-indicators {
  position: relative;
  right: auto;
  bottom: auto;
  left: auto;
  margin-right: 0;
  margin-left: 0;
  list-style: none;
  background: red;
}

.carousel-indicators li {
  width: 30px;
  height: 30px;
  text-indent: 0;
  color: black;
  font-size: 14px;
  text-align: center;
  cursor: pointer;
}

1

2

3

    Previous

    Next


text:
Q: NativeScript + Angular: Code Sharing Project I followed the Nativescript steps for creating a new code sharing project here and I would like to use sass. I tried both for ones that have the NatievScript theme as well as the one that does not:
ng new -c=@nativescript/schematics no-theme-project --shared --no-theme

or
ng new -c=@nativescript/schematics sass-no-theme-project --shared --style=scss --no-theme

For this Post I chose No Theme. When it finishes creating a new project the folder is as shown:

Inside Desktop/TestProjects/sass-no-theme-project I install the node modules:
npm install

When running ng serve --o the application builds and loads up as expected in the browser. For NativeScript mobile however for Android (have not tested iOS yet) the application crashes with an error. I have tried both tns run android as well as using the NativeScript SideKick to build however they end up with the same results. I have also tried local and cloud builds.
Device Used:
Physical Samsung A5: Not emulator
Error On Mobile Device In Logs:
An uncaught Exception occurred on "main" thread.
java.lang.RuntimeException: Unable to create application com.tns.NativeScriptApplication: com.tns.NativeScriptException: Application entry point file not found. Please specify the file in package.json otherwise make sure the file index.js or bootstrap.js exists.\nIf using typescript make sure your entry point file is transpiled to javascript.
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6065)
    at android.app.ActivityThread.-wrap1(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: com.tns.NativeScriptException: Application entry point file not found. Please specify the file in package.json otherwise make sure the file index.js or bootstrap.js exists.\nIf using typescript make sure your entry point file is transpiled to javascript.
    at com.tns.Module.bootstrapApp(Module.java:311)
    at com.tns.Runtime.run(Runtime.java:544)
    at com.tns.NativeScriptApplication.onCreate(NativeScriptApplication.java:21)
    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1125)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6062)
    ... 8 more
Caused by: com.tns.NativeScriptException: Failed to find module: "./", relative to: app//
    at com.tns.Module.resolvePathHelper(Module.java:146)
    at com.tns.Module.bootstrapApp(Module.java:309)
    ... 12 more

Logs In Command Line and NativeScript Client
[18-11-10 17:43:53.724] (CLI) [./main.ns.ts] 1.22 KiB {bundle} [built]
[18-11-10 17:43:53.724] (CLI) [./package.json] 123 bytes {bundle} [optional] [built]
[18-11-10 17:43:53.724] (CLI)     + 403 hidden modules
[18-11-10 17:43:53.724] (CLI) ERROR in Patterns must be a string or an array of strings
[18-11-10 17:43:53.724] (CLI)  Webpack compilation complete.
[18-11-10 17:43:53.724] (CLI)  Executing webpack failed with exit code 2.
[18-11-10 17:43:53.724] (CLI)  # tns build android
[18-11-10 17:43:53.724] (CLI) ### Description
[18-11-10 17:43:53.724] (CLI) clean-webpack-plugin: /mnt/storage/builds/_/1bfec9e7b462a1843535f909d892c70d2010e1cf/5.0.0/5.0.0/no-sass-project/platforms/android/app/src/main/assets/app/**/* has been removed.
[18-11-10 17:43:53.724] (CLI) Executing webpack failed with exit code 2.
[18-11-10 17:43:53.724] (CLI) bc_GgX4lpDXQFHYT4ydmJ
[18-11-10 17:43:56.917] (CLI) Unable to apply changes on device: 5210ffc964ca44f3. Error is: Build failed..
[18-11-10 17:43:56.920] Error detected during LiveSync on 5210ffc964ca44f3 for C:\Users\userName\Desktop\no-sass-project. Error: Build failed.
[18-11-10 17:43:56.925] (CLI) Executing after-watch hook from C:\Users\userName\Desktop\no-sass-project\hooks\after-watch\nativescript-dev-sass.js
[18-11-10 17:43:56.925] (CLI) Executing after-watch hook from C:\Users\userName\Desktop\no-sass-project\hooks\after-watch\nativescript-dev-typescript.js
[18-11-10 17:43:56.925] (CLI) Executing after-watch hook from C:\Users\userName\Desktop\no-sass-project\hooks\after-watch\nativescript-dev-webpack.js
[18-11-10 17:43:56.925] (CLI) Stopping webpack watch

With Nativescript and Angular creating a blank new project for me I would assume it is suppose to be a HelloWorld project that works in Web, iOS, and Android right out of the gate.
UPDATE
I tried following the troubleshoot guide here such as reinstalling JDK 8 and that however the problem persists. I got it to run once, it failed and after about 4-10 minutes it rebuilt and was working. Since then I can not get it to work a second time. This leads to me believe there maybe a configuration issues somewhere such as the tsconfig json files. Taken a look in them and they seem to be fine.

A: It seems it may be difficult for the nativescript team as the packages it relies on keep changing rapidly. This is the package.json setup I used thanks @NickIliev from the nativescript team, @skopekreep, and good old debugging. If you use this setup you should be fine.
Just be wary updating the packages in the future and test before committing your package.json.
As well as the main packages I would suggest you be careful updating and ensure you test:
typescript
@types/jasmine
nativescript-dev-webpack
tns-core-modules
{
  "name": "myproject",
  "nativescript": {
  "id": "org.nativescript.myproject",
    "tns-android": {
    "version": "5.0.0"
   }
},
"version": "0.0.0",
"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e",
  "android": "tns run android --bundle",
  "ios": "tns run ios --bundle"
},
"private": true,
"dependencies": {
  "@angular/animations": "~6.1.0",
  "@angular/common": "~6.1.0",
  "@angular/compiler": "~6.1.0",
  "@angular/core": "~6.1.0",
  "@angular/forms": "~6.1.0",
  "@angular/http": "~6.1.0",
  "@angular/platform-browser": "~6.1.0",
  "@angular/platform-browser-dynamic": "~6.1.0",
  "@angular/router": "~6.1.0",
  "core-js": "^2.5.4",
  "nativescript-angular": "~6.1.0",
  "nativescript-theme-core": "~1.0.4",
  "reflect-metadata": "~0.1.8",
  "rxjs": "^6.0.0",
  "tns-core-modules": "~5.0.2",
  "zone.js": "^0.8.26"
},
"devDependencies": {
  "@angular-devkit/build-angular": "^0.8.0",
  "@angular/cli": "^6.2.0",
  "@angular/compiler-cli": "^7.0.3",
  "@nativescript/schematics": "~0.4.0",
  "@types/jasmine": "2.8.6",
  "@types/jasminewd2": "~2.0.3",
  "@types/node": "~8.9.4",
  "codelyzer": "~4.2.1",
  "jasmine-core": "~2.99.1",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~1.7.1",
  "karma-chrome-launcher": "~2.2.0",
  "karma-coverage-istanbul-reporter": "~2.0.0",
  "karma-jasmine": "~1.1.1",
  "karma-jasmine-html-reporter": "^0.2.2",
  "nativescript-dev-sass": "~1.6.0",
  "nativescript-dev-typescript": "~0.7.0",
  "nativescript-dev-webpack": "^0.17.0",
  "protractor": "~5.3.0",
  "ts-node": "~5.0.1",
  "tslint": "~5.9.1",
  "typescript": "^3.1.6"
}

}
Steps:
1. Install latest version of Node JS

*Install latest version of NPM

*npm i -g @angular/cli

*npm i -g @nativescript/schematics

*Go into the folder and Replace the package.json, ensure to change name and id to your projects name

*npm install

*tns run android --bundle

A: When you build code-sharing projects you should use the --bundle flag.
So your command should be:
tns run android --bundle or tns run ios --bundle
If you keep forgetting the --bundle flag, then you could use the scripts provided in package.json and run:
npm run android or npm run ios
Additionally, if your project uses TypeScript 2.7, then you might need to update it to 2.8
As a side note: you don't need moduleId in code-sharing projects, as webpack is taking care of this for you.


text:
Q: Changing Sine Wave frequencies in the same AVAudioPCMBuffer I've been working on getting a clean sine wave sound that can change frequencies when different notes are played.  From what I've understood, I need to resize the buffer's frameLength relative to the frequency to avoid those popping sounds caused when the frame ends on a sine's peak.
So on every iteration, I set the frameLength and then populate buffer with the signal.
AVAudioPlayerNode *audioPlayer = [[AVAudioPlayerNode alloc] init];
AVAudioPCMBuffer *buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:[audioPlayer outputFormatForBus:0] frameCapacity:44100*10];`

while(YES){
    AVAudioFrameCount frameCount = ceil(44100.0/osc.frequency);
    [buffer setFrameLength:frameCount];
    [audioPlayer scheduleBuffer:buffer atTime:0 options:AVAudioPlayerNodeBufferLoops completionHandler:nil];
    for(int i = 0; i < [buffer frameLength]; i++){
        for (int channelNumber = 0; channelNumber < channelCount ; channelNumber++) {
            float * const channelBuffer = floatChannelData[channelNumber];
            channelBuffer[i] = [self getSignalOnFrame:i];
        }
    }
}

where the signal is generated from:
(float)getSignalOnFrame:(int)i {
     float sampleRate = 44100.0;
     return [osc amplitude] * sinf([osc frequency] * i * 2.0 * M_PI / sampleRate);
}

The starting tone sounds fine and there are no popping sounds when notes change but the notes themselves sound like they're being turned into sawtooth waves or something.
Any ideas on what I might be missing here?
Or should I just create a whole new audioPlayer with a fresh buffer for each note played?
Thanks for any advice!

A: If the buffers are contiguous, then a better method to not have discontinuities in sine wave generation is to remember the phase of the sinewave at the end of one buffer, and use that phase as the starting point (angle) to generate the next buffer.
If the buffers are not contiguous, then a common way to avoid clicks is to gradually taper the first and last few milliseconds of each buffer from full gain to zero.  A linear gain taper will do, but a raised cosine taper is a slightly smoother taper.


text:
Q: Rewrite Rule Subdomain My URLs look like this
mydomain.tld/abc
de.mydomain.tld/abc

(optional there is a slash afterwards)
Now I want to rewrite all url with a subdomain, from:
de.mydomain.tld/abc (or de.mydomain.tld/abc/)

to:
de.mydomain.tld/abc.html

and all other urls should go to my ghost blog (line 5). This part works already.
my .htaccess
 1   RewriteEngine On
 2   #Rewrite my Subdomain to .html
 3   RewriteCond %{HTTP_HOST} ^de\.mydomain\.tld$
 4   RewriteRule ^(.*)/?$ $1\.html [L]

 5   RewriteRule ^(.*) http://localhost:61222/$1 [P]
 6   RewriteRule ^(.*)/$ $1 [R=301]

So far I thought it does this:
1 (line 3). If the url has the subdomain path within do the rule below.
2 (line 4) Rewrite the part before the slash (if there is one) to exactly the same with .html appended, use no more rules afterwards
Question I:
How to adjust lines 3,4 that only path which have the de. subdomain are changed to .html like described above the htaccess?
Question II:
Is the following part redirecting all www. subdomains to the original domain:
http://www.abc.de -> http://abc.de
RewriteRule ^(.*)/$ $1 [R=301]

If it is doing that do I need to move it upwards because I have the [L] in the first rule? If it is doing nothing, what would be the correct rewrite rule?


text:
Q: Can you have a subfield whose unity is different from the unity of the larger field? Suppose we have a field $F$ and a (non trivial) subring $R$ of $F$ which does not contain $1$, yet has an element $a$ such that for all $r$ in $R$, $ar = r$ and there exists $q$ in $R$ such that $rq = a$. Clearly $R$ is a field with unity $a$. Can a field have such a subring, though? If so, I'd love to see an example.

A: Hint: if $r = a r $ and $r \ne 0$, then $1 = r^{-1} r = \ldots$.

A: Assuming commutativity in the following (should I not?). Let us suppose there is such an element $a$, and let $b\in R$ be such $ab=a$ (the inverse of $a$ in $R$).
Denoting by $a^{-1}$ the inverse of $a$ in $F$, you get
$b=a^{-1}ab=a^{-1}a=1$. So $1=b\in R$, which is a contradiction.


text:
Q: What is the probability that the flight departs with empty seats? Because not all airline passengers show up for their reserved seats, an airline sells 125
tickets for a flight that holds 120 passengers. The probability that a passenger does not
show up is 0.10, and passengers behave independently.
What is the probability that the flight departs with empty seats?

A: The number of passengers showing up is a random variable $X\sim\text{Binomial}(125,0.9)$
And what you want is
$$P(X\le 119)=F_X(119)=\\=1-P(X=125)-P(X=124)-P(X=123)-P(X=122)-P(X=121)-P(X=120)$$
You may calculate it numerically with a computer program, or do a normal approximation.


text:
Q: Identify mac or local ip address I have a list of mac addresses and local ip addresses from my router.
In order to use the right ip address I need to identify which device is behind each ip address.
So my question is how can I know which device is linked to each address? Is there a way for me to find this out from my computer only?
Thanks,
Siar

A: You can obtain some information by portscanning.
sudo nmap -O $IP_ADDRESS

will return some information about the OS, you can possibly use this to identify which device is which?


text:
Q: SUBSTRING expression works in FROM clause but fails in WHERE clause In SQL Server 2019, I've got this SQL query that works. The second column returned is a hack to get the associated user name that isn't stored elsewhere in this system log. All rows with the Web_Unauthorized event type are of the form:

Unauthorized attempt from account [user name] to access [url requested]

SELECT
    SystemLog.Id AS SystemLogId,
    SUBSTRING(SystemLog.Message,
        LEN('Unauthorized attempt from account') + 2,
        PATINDEX('%to access%', SystemLog.Message) - LEN('Unauthorized attempt from account') - 3
    ) AS UserName,
    SystemLog.Timestamp AS ServerTime,
    SystemLog.Message
FROM
    SystemLog
WHERE
    EventType = 'Web_Unauthorized'

But I want to exclude rows where the user name is FOO. So I tried the following, which is identical except for the addition of a second test to the WHERE clause.
SELECT
    SystemLog.Id AS SystemLogId,
    SUBSTRING(SystemLog.Message,
        LEN('Unauthorized attempt from account') + 2,
        PATINDEX('%to access%', SystemLog.Message) - LEN('Unauthorized attempt from account') - 3
    ) AS UserName,
    SystemLog.Timestamp AS ServerTime,
    SystemLog.Message
FROM
    SystemLog
WHERE
    EventType = 'Web_Unauthorized'
    AND SUBSTRING(SystemLog.Message,
        LEN('Unauthorized attempt from account') + 2,
        PATINDEX('%to access%', SystemLog.Message) - LEN('Unauthorized attempt from account') - 3
    ) <> 'FOO'

When I execute this in SSMS, four rows are displayed before SSMS flips me to the Messages pane where it displays the error message:

Invalid length parameter passed to the LEFT or SUBSTRING function.

But the SUBSTRING call I'm making in the WHERE clause is the same one the worked in the FROM clause. Why is it failing in the WHERE clause?
I tried this as well, but with the same result:
SELECT * FROM (
SELECT
    SystemLog.Id AS SystemLogId,
    SUBSTRING(SystemLog.Message,
        LEN('Unauthorized attempt from account') + 2,
        PATINDEX('%to access%', SystemLog.Message) - LEN('Unauthorized attempt from account') - 3
    ) AS UserName,
    SystemLog.Timestamp AS ServerTime,
    SystemLog.Message
FROM
    SystemLog
WHERE
    EventType = 'Web_Unauthorized'
) Main
    WHERE Main.UserName <> 'FOO'

A: There's no guarantee that the SUBSTRING expression only evaluates rows where EventType is Web_Unauthorized.
Your extra check doesn't require the big pattern matching, so you could write this instead:
    SELECT SystemLog.Id AS SystemLogId,
    SUBSTRING(SystemLog.Message,
        LEN('Unauthorized attempt from account') + 2,
        PATINDEX('%to access%', SystemLog.Message) -
        LEN('Unauthorized attempt from account') - 3
    ) AS UserName,
    SystemLog.Timestamp AS ServerTime,
    SystemLog.Message
FROM
    SystemLog
WHERE
    EventType = 'Web_Unauthorized'
    AND SystemLog.Message NOT LIKE 'Unauthorized attempt from account _FOO_ to access%'


text:
Q: Keeping slide-out div flush with left side of window upon window resize I have a slide-out div, absolutely positioned in a relatively positioned parent,  which moves nearly off the left side of the screen upon the click of a button.
I'm animate() -ing the css left property to move it. It looks fine until you resize the window. Upon resize, the div is then either too far into the page or too far outside of the page (depending on if you are enlarging or shrinking the window).
How can I keep the div flush with the page upon resize?
Basically I want the right side of the div to always be 15px from the window border when the div is "slid out".
I was able to replicate the problem on Codepen, but not jsFiddle:
http://cdpn.io/hjnHz
Click the "<" sign on the top right of the slideout div to slide it out.

A: Simply add:
$(window).resize(function(e) { if ($("#slideout").css('left') != '0px') $("#slideout").css('left', -($("#slideout").width() - 15)); });

http://codepen.io/anon/full/rjaHD


text:
Q: what is the cyclic cover trick? What do people mean by the "cyclic cover trick"? I have found this expression a couple of times with no complete explanation, both talking about curves and surfaces...

A: The "cyclic cover trick" can refer to more than one thing.  One example is as follows.  Let $L$ be an invertible sheaf on a smooth projective scheme such that some power $L^{\otimes d}$ has a global section $s$ whose zero scheme $D$ is a smooth Cartier divisor (all of these smoothness conditions are not strictly necessary).  Let $\nu:Y\to X$ be the associated degree $d$ branched cover branched over $D$ and whose restriction over $X\setminus D$ is the $\mathbb{\mu}_d$-torsor corresponding to $L$.  More precisely, $\nu$ is affine and $\nu_*\mathcal{O}_Y$ is the  $\mathbb{Z}/d\mathbb{Z}$-graded $\mathcal{O}_X$-algebra $$\nu_*\mathcal{O}_Y = \mathcal{O}_X \oplus L^\vee \oplus \dots \oplus (L^\vee)^{\otimes (d-1)}.$$
Of course we have to say what is the multiplication rule on this algebra.  But there is a unique multiplication rule that is $\mathbb{Z}/d\mathbb{Z}$-graded and that is compatible with the multiplication rule $s:(L^\vee)^{\otimes d} \to \mathcal{O}_X$.  Now, for every $q$, $\nu_*\Omega^p_Y$ has a natural $\mathbb{Z}/d\mathbb{Z}$-grading, and the graded pieces turn out to be expressible in terms of tensor products of $\Omega^r_X$ with powers $(L^\vee)^{\otimes s}$.  Now assume that $X$ is a $\mathbb{C}$-scheme.  Then the Hodge theorem gives surjectivity of the various projections $H^r(Y^{\text{an}};\mathbb{C}) \to H^q(Y,\Omega^p_Y)$.  Both groups have a $\mathbb{\mu}_d$-action that is equivalent to a $\mathbb{Z}/d\mathbb{Z}$-grading.  In particular, vanishing of certain graded pieces of $H^r(Y^{\text{an}};\mathbb{C})$ will imply vanishing of certain cohomology groups $H^q(X,\Omega^p_X\otimes (L^\vee)^{\otimes s})$.  In this way, one can prove the Kodaira-Akizuki-Nakano vanishing theorem.
So in this case, the "covering trick" is to use a geometric result on the cyclic cover (the Hodge decomposition) combined with computation of the graded pieces to deduce a geometric result on the original scheme.  In a similar way, one can prove extensions of the Kodaira vanishing theorem, e.g., the Kawamata-Viehweg vanishing theorem.  This is discussed in detail in the book of Kollár and Mori.


text:
Q: RestKit crash -- RKManagedObjectRequestOperation.m line 873 I am getting a crash report from my app in production. The stack trace doesn't include any of my code, rather points to code in RestKit itself where it is crashing. The crash itself is hard to reproduce on my side, and seems like some user in production is hitting an edge case. Below is the stack trace:
Thread : Crashed: NSManagedObjectContext 0x1743ecd00
0  libobjc.A.dylib                0x000000019361c0b4 objc_retain + 20
1  MyApp                 0x00000001001e64c4 __78-[RKManagedObjectRequestOperation obtainPermanentObjectIDsForInsertedObjects:]_block_invoke (RKManagedObjectRequestOperation.m:873)
2  CoreData                       0x0000000181b7d218 developerSubmittedBlockToNSManagedObjectContextPerform + 200
3  libdispatch.dylib              0x0000000193c55954 _dispatch_client_callout + 16
4  libdispatch.dylib              0x0000000193c5f1e4 _dispatch_barrier_sync_f_invoke + 76
5  CoreData                       0x0000000181b7d0d8 -[NSManagedObjectContext performBlockAndWait:] + 244
6  MyApp                 0x00000001001e62d8 -[RKManagedObjectRequestOperation obtainPermanentObjectIDsForInsertedObjects:] (RKManagedObjectRequestOperation.m:870)
7  MyApp                 0x00000001001e34e4 __79-[RKManagedObjectRequestOperation performMappingOnResponseWithCompletionBlock:]_block_invoke345 (RKManagedObjectRequestOperation.m:643)
8  MyApp                 0x000000010021c31c -[RKResponseMapperOperation willFinish] (RKResponseMapperOperation.m:317)
9  MyApp                 0x000000010021c980 -[RKResponseMapperOperation main] (RKResponseMapperOperation.m:404)
10 Foundation                     0x0000000182c601cc -[__NSOperationInternal _start:] + 636
11 Foundation                     0x0000000182d21f28 __NSOQSchedule_f + 228
12 libdispatch.dylib              0x0000000193c55954 _dispatch_client_callout + 16
13 libdispatch.dylib              0x0000000193c600a4 _dispatch_queue_drain + 1448
14 libdispatch.dylib              0x0000000193c58a5c _dispatch_queue_invoke + 132
15 libdispatch.dylib              0x0000000193c62318 _dispatch_root_queue_drain + 720
16 libdispatch.dylib              0x0000000193c63c4c _dispatch_worker_thread3 + 108
17 libsystem_pthread.dylib        0x0000000193e3522c _pthread_wqthread + 816
18 libsystem_pthread.dylib        0x0000000193e34ef0 start_wqthread + 4

The crash message itself is:

Crashed: NSManagedObjectContext 0x17198900
  EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0x915da43f

Any hints/directions as to how I can go about debugging this issue?
Thanks.

A: Ran into this, had setup the core data stack twice on accident, removing the second initialization fixed the issue.


text:
Q: Is using .. as parent directory cross platform? More as a curiosity, if I want to prevent some code from looking at the parent directory (contained in a list of files/directories) and I do something along the lines of (e.g. Perl) next if /^.+$/ to exclude . and .. , is this sufficiently cross-platform? If not, which platforms are different and how might one prevent accessing the parent in that case?

A: It will work in most modern platforms.  (It will also exclude Unix hidden files/directories, but this is probably a good thing given the context.)  Windows has a special case at the root of a drive, but it's not so much "different syntax" as "not there in any syntax"; if you have any intention of using platforms such as OpenVMS or Z/OS, it won't work at all.
Note that Perl and Python ship with cross-platform path utilities that you should use instead.  I couldn't tell you about PHP or Ruby but I presume both also do so.

A: Doesn't work in ZX Spectrum. :)
Seriously, pretty much all platforms in current wide use (i.e. MSDOS, Windows, *NIX including Linux) conform to that. Be aware you will also be excluding hidden directories in UNIX-like systems.


text:
Q: Select multiple cardview and remove the position on unselect in recyclerview adapter enter image description hereHello there! i am working on recyclerview in android. in recyclerview i am selecting multiple cardview. But i want when i select cardviews then their position should be concatenated
as 1,2,3,4,5
and when i unselect the cardview then their postions should be removed. Suppose I unselect the cardview at position 5 then concatenated string will be
1,2,3,4
like this
here is my adapter code:
if (!brand.isSelected()) {
    brand.setSelected(!brand.isSelected());
    name.setTextColor(Color.WHITE);
    Log.e("boolean",String.valueOf(!brand.isSelected()));
    cardView.setBackgroundColor(Color.parseColor("#fe8d00"));
} else {
    brand.setSelected(!brand.isSelected());
    name.setTextColor(Color.BLACK);
    cardView.setBackgroundColor(Color.WHITE);
}

if (brands.get(position).isSelected()) {
    String selecName = brand.getBrandName();
    finalName = selecName + " " + finalName;
    Toast.makeText(context,finalName,Toast.LENGTH_SHORT).show();

and here is my model:
public void setSelected(boolean selected) {
    isSelected = selected;
}
public boolean isSelected() {
    return isSelected;
}

and here is image of selecting the cardview


text:
Q: how to set geometry of an element in css in qt5 I am using qt5-creator designer and iam using css for customizing QPushButtons in a frame
i want to set geometry of buttons with css
i tried this but this is not working for me
.col-1-row-2 { position: fixed; top: 500 px; left: 500 px; }

i replaced fixed with absolute and relative but nothing changed.
how can i set or change default geometry of each element in its css class?
and frames geometry?
i use this function to apply the css to the project
void MainWindow::loadCss()
{
int rows = 7, mrows = 4;
int btnWidth = width() / 5,
    btnHeight = height() / (rows + 1);

QString css = "", temp = ".col-%1-row-%2 { top: %3 px; %4: %5 px; }";
for (int i = 1 ; i <= mrows ; ++i)
{
    css += temp.arg(1).arg(i).arg((rows - mrows + i - 1) * btnHeight).arg("left").arg(40);
    css += temp.arg(2).arg(i).arg((rows - mrows + i - 1) * btnHeight).arg("right").arg(40);
}

QFile file(":/css.qss");
file.open(QFile::ReadOnly);
qApp->setStyleSheet(QString::fromLatin1(file.readAll())
                    .replace("${fullWidth}", QString::number(width()))
                    .replace("${fullHeight}", QString::number(height()))
                    .replace("${btnHeight}", QString::number(btnHeight))
                    .replace("${btnWidth}", QString::number(btnWidth))
                    + css
                    );
file.close();
}

qss file
* {
font-size: 40px;
/* qproperty-alignment: AlignCenter; */
background-color: none;
}

QFrame {
position: fixed;
top: 0;
left: 0;
min-width: ${fullWidth} px;
min-height: ${fullHeight} px;
max-width: ${fullWidth} px;
max-height: ${fullHeight} px;
}

QPushButton {
min-width: ${btnWidth} px;
min-height: ${btnHeight} px;
}

#MainWindow {
border-image: url(:/images/sky.jpg) 0 0 0 0 stretch stretch;
border-width: 0px;
}

QFrame css does not working either.

A: I'm successfully using qproperty- syntax
QPushButton#Key_0{
   qproperty-geometry: rect(0 0 160 84);
}
QPushButton#Key_1{
   qproperty-geometry: rect(160 0 160 84);
}

As described in Qt documentation

A: It's not supported. Use layouts or manual positioning for that.
Qt implements a self-contained subset of CSS. If something is not documented as supported, it isn't supported. Referring to the list of supported properties: CSS-based geometry management is not supported.
If you insist on styling position using CSS, it would be maybe 10-20 lines to add this functionality to Qt source code.


text:
Q: "A link to the server could not be established" to my database in PHP I Found this Warning:

Successful database connection, happy coding Raj2!!!
Warning: mysql_query(): Access denied for user 'root'@'localhost' (using password: NO) in /home/u590617868/public_html/action.php on line 4 Warning: mysql_query(): A link to the server could not be established in /home/u590617868/public_html/action.php on line 4.
not sucsessful

my code is:
<?php
      include_once "DB_connect.php";
      $uName = $_POST['username'];
      $sql = mysql_query("INSERT INTO members('username') VALUES('$uName')");
      if ( $sql )
      {
         echo "sucsessful";
      }
      else
      {
         echo "not sucsessful";
      }
?>

A: You've no database connection or it is not included/closed. Please post your complete code.

A: Please structure your code a little better. Just a tip.
The syntax should go something like this:
$query="INSERT INTO members (username) VALUES ('$uName')";
if(mysql_query($query)){
     echo "Success";
}else{
     echo "Fail";
}

It doesn't seem like that's the issue at hand. You have a permissions issue. Post the pseudo-content of your DB_connect.php file (change address,username, and password if you feel the need to)


text:
Q: Building list for capital city As the title says. Is there any list of buildings available to build in the capital city? Everything included decorations, random chest drops, workshops etc.

A: There isn't an official one that I am aware of but here is the result of a concerted community effort to list every city building in the game. Hope this helps answer your question.


text:
Q: jquery: read inside each div, span and input I'm creating a project in ASP.NET MVC and jQuery. When a user click on addSentence button, I want to duplicate a div called copythis with all events and insert it in another div called myform.
in copythis I have two div: in the first there is a span called sentence where I insert the text in the input in the second the user can add more then one field with different text.
When the user clicks the button called save I want to read all copythis in myform and create a structure to send to a webapi.
I have a problem is the javascript because I can read properly each div.

        $("#addSentence").on("click", function (event) {
            if ($("#inputSentence").val() == "")
                alert("Sentence must have a value");
            else {
                event.preventDefault();
                var theContainer = $("#copythis");
                if (theContainer != null) {
                    var clonedSection = $(theContainer).clone(true);
                    if (clonedSection != null) {
                        $(clonedSection).find("#sentence")
                                        .text($("#inputSentence").val());
                        $(clonedSection).appendTo("#myform");
                    }
                }
            }
    });

    $("#save").on("click", function (event) {
        $("#myform #copythis").children().each(function (index, element) {
            var elm = $(this);
            var sentence = elm.find('.row span#sentence').val();
            if (sentence != '') {
                console.log('Sentence: ' + sentence);
                $("input").children().each(function (m, l) {
                    var txt = $(this).val();
                    if (txt != '') {
                        console.log('Example: ' + txt);
                    }
                });
            }
        });
    });

    function makeRepeater(sectionsSelector, addClass, removeClass, AYSMsg) {
        $(sectionsSelector + " " + addClass + "," + sectionsSelector +
          " " + removeClass).on("click", function (event) {
            // Avoiding the link to do the default behavior.
            event.preventDefault();

            // Get the container to be removed/cloned
            var theContainer = $(this).parents(sectionsSelector);
            if ($(this).is(addClass)) {

                // Cloning the container with events
                var clonedSection = $(theContainer).clone(true);

                // And appending it just after the current container
                $(clonedSection).insertAfter(theContainer);
            } else {
                // If the user confirm the "Are You Sure" message
                // we can remove the current container
                if (confirm(AYSMsg)) {

                    // Making fade out, hide and remove element a sequence
                    // to provide a nice UX when removing element.
                    $(theContainer).fadeOut('normal',
                        function () {
                            $(this).hide('fast',
                                function () { $(this).remove(); }
                            );
                        }
                    );
                }
            }
        });
    }

    makeRepeater(
        '.my-repeated-section-form',   /* The container selector */
        '.addform',                   /* The add action selector */
        '.removeform',                /* The remove action selector */
        'Are you sure you want to remove this section?' /* The AYS message. */
    );

                <input id="inputSentence" type="text"
                       class="form-control" placeholder="Sentence...">

                    <button class="btn btn-secondary"
                            type="button" id="addSentence">Add</button>

                                     +
                                     -

                                    <input type="text" />

                                         +
                                         -

<button id="save">Save</button>


text:
Q: Number of times a button pressed, should be multiply with variable(recipeTotal) value I'm working on the Angular 8 application. I want to multiply the numbers of times the button pressed with the existing value of (recipetotal). But it didn't give me correct result.
The result should be => 8*3=24
But the result I'm getting is => 48
Can someone please help me with this.
My TS Code
  quantityControl(flag) {

    if (flag == '+') {
      this.quantity = this.quantity + 1;
      if (this.filteredRecipe.RecipePrice === 0) {
        this.recipeTotal = this.recipeTotal * this.quantity;
        console.log('The price is:'+ this.recipeTotal);
      }
    } else {
      if (this.quantity != 1) {
        this.quantity = this.quantity - 1;
        if (this.filteredRecipe.RecipePrice === 0) {
          this.recipeTotal = this.recipeTotal * this.quantity;
        }
      }
    }
  }

My HTML Code

Quantity

            <button (click)="quantityControl('-')" class="minus-btn" type="button" name="button">

            </button>

          <input type="text" class="text-center" [(ngModel)]="quantity" name="quantity" value="1" style="font-size: 18px; font-weight: bold;">

            <button (click)="quantityControl('+')" class="plus-btn" type="button" name="button">
            </button>

A: Probably the mistake is in this function evaluating
if (this.filteredRecipe.RecipePrice === 0)

Past it code or check it by yourself.


text:
Q: Make sendmail not log "did not issue MAIL/EXPN/VRFY/ETRN" messages? We have sendmail servers behind an F5 load balancer.  The load balancer is constantly opening/closing a connection to each mail server to see if it is answering.  This means our syslog files are overflowing with lines like:

Sep 19 11:13:29 mailserver-X sm-mta[12643]: w8JGDTmi012643: lb5a [10.11.12.13] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
Sep 19 11:13:29 mailserver-X sm-mta[12819]: w8JGDSLk0012819: lb5b [10.11.12.14] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA

Is there a way to make sendmail just quietly ignore these?
Currently running sendmail-8.14.5 but would update if needed to fix this issue.

A: Load balancers usually have fairly minimal scripted protocol tests, just enough to confirm probable correct operation, but frequently omit protocol niceties, or don't perform any useful operation, which is what sendmail is complaining about. The SMTP default is to just send HELO then QUIT (checking the response codes for each).
This is a LogLevel > 5 message, the default is LogLevel 9, so you could either recreate your .cf after adding to the .mc:
define(`confLOG_level',`5')

or temporarily override it by adding -O LogLevel=5 on the sendmail command line. The downside being many other (~140) messages over levels 6-9 will also be suppressed.
There is only one documented scenario where that specific message is suppressed — when a connection is going to be rejected anyway via configuration (access map or TCP wrappers). However every scenario I can think of involves logging a rejection error instead... (and worse, some may return an error to the HELO greeting which would cause the F5 to mark the service down).
There is no configurable item in the standard SMTP_monitor, but as a workaround you could set up an alternate SMTP monitor script, this example on F5's devcentral (registration required to view source) shows how it's done using Expect:
https://devcentral.f5.com/codeshare/smtp-scripted-monitor
That example sends an email on each probe which you almost certainly don't want ;-)
Instead try something like this:
expect "220"                 ;# must wait for SMTP banner
send "HELO mydomain.com\r\n" ;# EHLO is better
expect "250"
send "VRFY postmaster\r\n"   ;# some non-NOP command
expect "250"
send "QUIT\r\n"              ;# clean exit
expect "221"

and adjust as required. If your sendmail is fussy (PrivacyOptions might block VRFY/EXPN/ETRN) then either amend the expected code, or use MAIL then RSET:
 ....
 send "MAIL from:<postmaster@domain.com>\r\n"
 expect "250"
 send "RSET\r\n"
 expect "250"
 send "QUIT\r\n"
 expect "221"


text:
Q: Global Variable getting nulled | VUE JS | Laravel I need help in checking the issue with the Global variable where it is getting null on assigning it to a local variable.
For Example
A = array('a','b');
let B = A
I am using the B variable but the Global Variable A is getting Empty.
I am attaching the VUE JS script for reference.
Please check if anyone can help. It will be really appreciated.
createBoxes(spec = '') {
        let speci = []
        if (spec == '') {
            speci = this.tabs_specifications
        } else {
            speci = spec
        }
        let box = []
        for (var j = 1; j <= this.tab_cut; j++) {
            for (var i = 0; i < speci.length; i++) {
                if (speci[i].tab_position == j) {
                    box.push(speci[i]);
                    speci.splice(i, 1)
                    this.total_boxes = this.total_boxes+1
                    break;
                }
            }
        }
        this.proof_boxes.push(box)
        let spicify = speci
        if (speci.length > 0) {
            this.createBoxes(spicify)
        } else {
            this.customize_tab.proof_boxes = this.proof_boxes
            // window.localStorage.setItem('customizeTab', JSON.stringify(this.$store.state.customize_tab));
        }
    }


text:
Q: USB CDC: STM32F103RBT6 Cant get USB Device to show up I got an Olimexino-STM32 with an STM32F103RBT6. I used STM32 Workbench 2.6 on Windows 10 x64 and STMCubeXM 4.27.0.
I choosed in CubeMX

*

*STM32F103RBT6

*RCC HSE

*USB

*USB Device Communication Device Class

*Debug Line: JTAG 4 pin

*Fix clock speeds

*Add LED1 on PA5 as GPIO Out

*Add LED2 on PA1 as GPIO Out

*Toolchain SW4STM

*Stack size

In main.c in the while loop
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
      HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, GPIO_PIN_SET);
      HAL_Delay(500);
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */
      HAL_GPIO_WritePin(LED2_GPIO_Port, LED2_Pin, GPIO_PIN_RESET);
      HAL_Delay(500);

        uint8_t HiMsg[] = "hello\r\n";
        CDC_Transmit_FS(HiMsg, strlen(HiMsg));
  }
  /* USER CODE END 3 */

in usb_cdc_if.c
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
  /* USER CODE BEGIN 6 */
    if (Buf[0]=='1')
    {
        HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_SET);
    }
    else
    {
        HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_RESET);
    }
  USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
  USBD_CDC_ReceivePacket(&hUsbDeviceFS);
  return (USBD_OK);
  /* USER CODE END 6 */
}

Generate, compile and flash to Board. I can see the LED blinking in the main loop. The speed seems also correct but i just cant get a device registered on windows. I can flash the board with an example hex file from the  distributor with the bootloader active. There i can get the COM port registered. So i can see the USB Port is ok but somehow the generated code doesnt register the COM port.
Any Ideas?
https://www.olimex.com/Products/Duino/STM32/OLIMEXINO-STM32/
Here is the test1.ioc file
#MicroXplorer Configuration settings - do not modify
File.Version=6
KeepUserPlacement=false
Mcu.Family=STM32F1
Mcu.IP0=NVIC
Mcu.IP1=RCC
Mcu.IP2=SYS
Mcu.IP3=USB
Mcu.IP4=USB_DEVICE
Mcu.IPNb=5
Mcu.Name=STM32F103R(8-B)Tx
Mcu.Package=LQFP64
Mcu.Pin0=PD0-OSC_IN
Mcu.Pin1=PD1-OSC_OUT
Mcu.Pin2=PA5
Mcu.Pin3=PA11
Mcu.Pin4=PA12
Mcu.Pin5=VP_SYS_VS_ND
Mcu.Pin6=VP_SYS_VS_Systick
Mcu.Pin7=VP_USB_DEVICE_VS_USB_DEVICE_CDC_FS
Mcu.PinsNb=8
Mcu.ThirdPartyNb=0
Mcu.UserConstants=
Mcu.UserName=STM32F103RBTx
MxCube.Version=4.27.0
MxDb.Version=DB.4.0.270
NVIC.BusFault_IRQn=true\:0\:0\:false\:false\:true\:false
NVIC.DebugMonitor_IRQn=true\:0\:0\:false\:false\:true\:false
NVIC.HardFault_IRQn=true\:0\:0\:false\:false\:true\:false
NVIC.MemoryManagement_IRQn=true\:0\:0\:false\:false\:true\:false
NVIC.NonMaskableInt_IRQn=true\:0\:0\:false\:false\:true\:false
NVIC.PendSV_IRQn=true\:0\:0\:false\:false\:true\:false
NVIC.PriorityGroup=NVIC_PRIORITYGROUP_4
NVIC.SVCall_IRQn=true\:0\:0\:false\:false\:true\:false
NVIC.SysTick_IRQn=true\:0\:0\:false\:false\:true\:false
NVIC.USB_LP_CAN1_RX0_IRQn=true\:0\:0\:false\:false\:true\:false
NVIC.UsageFault_IRQn=true\:0\:0\:false\:false\:true\:false
PA11.Mode=Device
PA11.Signal=USB_DM
PA12.Mode=Device
PA12.Signal=USB_DP
PA5.GPIOParameters=GPIO_Label
PA5.GPIO_Label=LED1
PA5.Locked=true
PA5.Signal=GPIO_Output
PCC.Checker=false
PCC.Line=STM32F103
PCC.MCU=STM32F103R(8-B)Tx
PCC.PartNumber=STM32F103RBTx
PCC.Seq0=0
PCC.Series=STM32F1
PCC.Temperature=25
PCC.Vdd=3.3
PD0-OSC_IN.Mode=HSE-External-Oscillator
PD0-OSC_IN.Signal=RCC_OSC_IN
PD1-OSC_OUT.Mode=HSE-External-Oscillator
PD1-OSC_OUT.Signal=RCC_OSC_OUT
PinOutPanel.RotationAngle=0
RCC.ADCFreqValue=36000000
RCC.AHBFreq_Value=72000000
RCC.APB1CLKDivider=RCC_HCLK_DIV2
RCC.APB1Freq_Value=36000000
RCC.APB1TimFreq_Value=72000000
RCC.APB2Freq_Value=72000000
RCC.APB2TimFreq_Value=72000000
RCC.FCLKCortexFreq_Value=72000000
RCC.FamilyName=M
RCC.HCLKFreq_Value=72000000
RCC.IPParameters=ADCFreqValue,AHBFreq_Value,APB1CLKDivider,APB1Freq_Value,APB1TimFreq_Value,APB2Freq_Value,APB2TimFreq_Value,FCLKCortexFreq_Value,FamilyName,HCLKFreq_Value,MCOFreq_Value,PLLCLKFreq_Value,PLLMCOFreq_Value,PLLMUL,SYSCLKFreq_VALUE,SYSCLKSource,TimSysFreq_Value,USBFreq_Value,USBPrescaler,VCOOutput2Freq_Value
RCC.MCOFreq_Value=72000000
RCC.PLLCLKFreq_Value=72000000
RCC.PLLMCOFreq_Value=36000000
RCC.PLLMUL=RCC_PLL_MUL9
RCC.SYSCLKFreq_VALUE=72000000
RCC.SYSCLKSource=RCC_SYSCLKSOURCE_PLLCLK
RCC.TimSysFreq_Value=72000000
RCC.USBFreq_Value=48000000
RCC.USBPrescaler=RCC_USBCLKSOURCE_PLL_DIV1_5
RCC.VCOOutput2Freq_Value=8000000
USB_DEVICE.CLASS_NAME_FS=CDC
USB_DEVICE.IPParameters=VirtualMode,VirtualModeFS,CLASS_NAME_FS
USB_DEVICE.VirtualMode=Cdc
USB_DEVICE.VirtualModeFS=Cdc_FS
VP_SYS_VS_ND.Mode=No_Debug
VP_SYS_VS_ND.Signal=SYS_VS_ND
VP_SYS_VS_Systick.Mode=SysTick
VP_SYS_VS_Systick.Signal=SYS_VS_Systick
VP_USB_DEVICE_VS_USB_DEVICE_CDC_FS.Mode=CDC_FS
VP_USB_DEVICE_VS_USB_DEVICE_CDC_FS.Signal=USB_DEVICE_VS_USB_DEVICE_CDC_FS
board=custom

A: Problem solved: The Olimexino-STM32 has an output to connect and disconnect the USB. I had not configured that output pin.


text:
Q: Incomple text while saving seaborn figures I have the following data frame:

For which I'm plotting a varchar using Seaborn:
ax = sns.barplot(x='Numero de respuestas', y='Carrera' ,

data=carrera_sum)
fig = ax.set_xlabel('Numero de respuestas')

On the notebook, it looks fine but when I try to save it:
fig = ax.get_figure()
fig.savefig(join(figuras,'carreras_comunes_latam.png'))

I get an incomplete image:


text:
Q: ajax keep posting also previous requests Working with Bootstrap framework 3.3.7
I have a code like this:
$('#field_submit').click(function() {
       //omitted part not relevant
       if (counter == 0) {
           //non ho riscontrato errori, quindi posso inviare il form
           data = $('#new_field').serialize();
           $.ajax({
           //omitted part not relevant
           }).done(function(data) {
            //aggiungo il campo creato alla lista dei campi sulla sinistra
            if(data.status==200){
                //omitted part not relevant
            }else{
              //non sono riuscito a caricare i dati
              $('#modal-text').html('
'+data.message+'
Dati per il debug (saranno inviati in automatico nella mail):
');
              var risposta = data;
              $("#modal-text").append(JSON.stringify(data));
              $('#message').modal('show');
              $('.segnalazione').click(function(){
                if($(this).attr('id')=='error_submit'){
                  mail= true;
                }
                //effettuo il caricamento
                $.ajax({
                  url: 'segnalazione.php',
                  method: 'post',
                  data: {form:'new_field', valori:risposta, mail: mail},
                  dataType: 'json'
                });
              });
            }
          });
       }
   });

As you can see if the main ajax call returns a status different from 200 then I open a modal, display some informations and on click of any of the two buttons (class="segnalazione") I send some data to the second ajax call.
Modal code:

Crea un nuovo campo

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-secondary segnalazione" data-dismiss="modal">Chiudi</button>
        <button type="button" class="btn btn-primary segnalazione" id="error_submit" data-dismiss="modal">Invia mail</button>

Consider this case: I open the page, run the first ajax, display the modal and send the data. This works fine.
Then, without reloading the page I do it again, show again the modal and send the data. This time I see two requests, the first with the data from the previous call, the second with the correct data.
If I do it again, I will see three calls, first with first data, second with second data and third with the correct one.
So, after three times in the second page in the db I will have three times the first data, two times the second and once the third.
I tried to use stopPropagation but it will prevent the modal to be closed on click of the button (usind data-dismiss method).

A: Make sure you are not keeping reference to first "data" via your second "data" because you are using same variable name. By naming you second variable "data" you will change your first one.
Suggest calling it "json" or something else. This way you avoid name collision.
JS Object reference is tied to variable name, not to data inside. By updating 2nd variable - in reality you update first one.
More info here: https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0


text:
Q: Rotating on a fixed point OpenGL I want to simulate like a chest opening which is made up of 2 main parts, the lid and the base.
In order to rotate on the x axis, do I need to move the lid to the origin so that:
a) any corner of the lid is at (0, 0, 0) or;
b) the centre of the lid must be on the origin?
so my code looks like this:
- draw the chest base
- translate to origin
- rotate
- translate to original position
- draw the lid

A: You should position the lid so that it's pivot point is on the origin. The pivot point is the point on which it rotates, in this case it would be the hinge of your lid.
As for the order of your code:
- draw the chest base
- translate so pivot point of lid is on origin
- rotate
- draw the lid
- translate and rotate to original position


text:
Q: Problem in defining a module in omnetpp Hi
    I'm writing a project in omnet, but I'm stuck on defining my own module. On https://github.com/lbedogni/Basic-Broadcast-Simulation there is the full code. The problem is that i get the following error message:
<!> Error in module (cCompoundModule) scenario.host[0] (id=4) at event
\#1, t=0: Class "basic::Flooding" not found -- perhaps its code was not
linked in, or the class wasn't registered with Register_Class(), or in
the case of modules and channels, with
Define_Module()/Define_Channel().

But I defined it via Define_Module().
I think it could possibly be a package related problem, but didn't find a solution. Any idea?
Thanks

A: I am not familiar with it, but from package.ned
// designate the NED package of this folder
package basic;
// namespace of module C++ classes
@namespace(basic);
@license(LGPL);
you need to be in namespace basic I guess?
And you flooding class is not defined within namespace basic?


text:
Q: Why does the linux man page have descriptions of C code? Why does the Linux man pages have information for C functions, that are not part of the kernel's API? For instance, strsep
Sure, it's useful to provide this functionality, but from a modular perspective, it seems like this should be managed/imported from ANSI.

A: The Linux, Unix, and POSIX manual pages document the Linux, Unix, and POSIX systems. A system is a set of things (in these cases, many things) that work together. They do not just document the kernel part of the operating system. They document commands for users, commands for programmers, utilities for system administrators, routines in libraries for programs, system calls for making requests of the operating system, and other features of the entire system.
When the manual pages were started, there was no C standard from ANSI, ISO, or IEC, and so it would not have been possible to defer to those organizations. Further, many of the routines provided by these systems specify behaviors beyond those of the same routines in the C standard library.


text:
Q: What does John Conway and Simon Kochen's "Free Will" Theorem mean? The way it is sometimes stated is that

if we have a certain amount of "free will", then, subject to certain assumptions, so must some elementary particles."(Wikipedia)

That is confusing to me, but it seems to be an amazing theorem. It has been interpreted as ruling out hidden variable theories, but there is still some dissent. Lubos has a good discussion of it on his blog in the birthday blog for John Horton Conway.   I assume it means that the outcomes of microscopic measurements are not deterministic.
What does the theorem assume and what does it prove?

A: I shall attempt here to give an explanation of the meaning of the theorem with a limited background. Issues such as the validity of the proof I shall leave aside.
The Free Will Theorem (assuming SPIN, TWIN, and FIN)].
"If the choice of directions in which to perform spin 1 experiments is not a
function of the information accessible to the experimenters, then the responses
of the particles are equally not functions of the information accessible to them."
This theorem is a combination of ingredients which explain the hypotheses: The EPR setup of two particles (the SPIN  and TWIN axioms); special relativity in a limited form (the FIN (later MIN) axiom); the Kochen-Specker "non-existence of a function" theorem/paradox.
So loosely we can imagine the typical EPR setup with two spacelike separated Observers making independent "choices" as to which of several axes to measure spin in two correlated particles: A and B, say. Let A's measurement be at time $t_A$. Then the conclusion is that no function of past properties (past light cone to $t_A$) predicts the outcome for A.
So the key phrase is "no function".
This theorem was primarily motivated to further exclude a fully deterministic interpretation of QM (obviously with hidden variables). Such hidden variables would give rise to a function of them - which here doesnt exist.
A secondary issue - where the "free will" comes from - is whether this just reconfirms an essential randomness in QM. Well the argument here, I believe, is that they interpret "random" to mean "a random function of" - but since no function exists even a random function doesnt exist (of any earlier properties). The responses of the particle A is determined at time $t_A$ based on no prior information (or information on B) - just the "free" choices of the experimenters as to what to measure.
A link to the Strong Free Will Paper: http://www.ams.org/notices/200902/rtx090200226p.pdf

A: The meaning is that either one shows that one or more of the axioms or some hidden premise is not acceptable for some reason, or one accepts the conclusion; or one can live in a state of "there's something wrong with that, I just can't find it" for as long as forever takes. If that means sleepless nights, so be it.
FWIW, a long time ago I chose to stop talking about particles. I haven't followed the Conway-Specker literature, since I argued some years ago that Bell inequalities cause almost no problem for random fields and no-one has so far contradicted that argument [go at it now, if you like, "Bell inequalities for random fields", J. Phys. A: Math. Gen. 39 (2006) 7441-7455, cond-mat/0403692, if you haven't previously decided it's wrong and decided not to publish a rebuttal]. Conway and Specker introduce assumptions that are fairly reasonable for classical particles but it's easy to exhibit that they do not hold for random fields.
The MIN axiom, in particular, is generally not true for quantum fields, because there are correlations at space-like separation in QFTs, without, because of microcausality, any need for there to be transmission of causal effects between space-like separated regions.
The MIN axiom is also generally not true for random fields. There are correlations, but there is no causality, because there is microcausality at time-like and light-like separation as well as at space-like separation. The correlations, to your taste, can either be pre-existing (the Conspiracy Loophole, if you like, but the conspiracy is probabilistic, not deterministic) or, instrumentally, they're there just because they're there (that is, we observe them, so they're there). The FIN axiom is harder, because then one has to be convinced that negative frequency components of the random field do not cause trouble, but of course classical electromagnetism lives happily with negative frequencies without problems of causality outside the light-cone, negative frequencies occur in QFT loop diagrams without difficulty, and also frequency is not linearly related to energy for classical fields.
For random fields, since they're not well known, you can try my approach in "Equivalence of the Klein-Gordon random field and the complex Klein-Gordon quantum field", EPL 87 (2009) 31002, arXiv:0905.1263 quant-ph, where a few references to other people's work can also be found. It's a niche, of course.
Move on, is what this theorem means; in my case on to random fields, but it's best if we all make different choices. You might, alternatively, be happy to drop locality and/or classical states and observables and/or something else, or to lose sleep.
On the other hand, I think you could do much worse than to accept the answer on Luboš Motl's blog, which I found very interesting, so I voted up his comment on Roy Simpson's Answer as proxy.


text:
Q: Optimize an index in select mysql I have a dating website and for years I've tried to optimize this query. Almost everyday the site gets stuck because of it.
User table structure:
CREATE TABLE `users` (
  `id` bigint(20) NOT NULL,
  `name` varchar(25) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
  `city` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
  `latitude` float(6,2) NOT NULL DEFAULT '0.00',
  `longitude` float(6,2) NOT NULL DEFAULT '0.00',
  `birth_year` smallint(4) NOT NULL DEFAULT '1997',
  `gender` tinyint(1) NOT NULL DEFAULT '1',
  `gender_search` tinyint(1) NOT NULL DEFAULT '2',
  `minimum_age` tinyint(2) NOT NULL DEFAULT '18',
  `maximum_age` tinyint(2) NOT NULL DEFAULT '80',
  `unix_timestamp_online` int(10) NOT NULL DEFAULT '0',
  `user_blocked` tinyint(1) NOT NULL DEFAULT '1',
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Indexes
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD KEY `multiple_index`(
    `unix_timestamp_online`,
    `user_blocked`,
    `gender`,
    `gender_search`,
    `maximum_age`,
    `minimum_age`,
    `birth_year`,
    `latitude`,
    `longitude`
) USING BTREE;

Query example
SELECT id, latitude, longitude
FROM users
WHERE gender=2
AND id NOT IN (11111111,2222222)
AND (birth_year BETWEEN 1961 AND 1999)
AND (latitude BETWEEN -25.14 AND -16.13)
AND (longitude BETWEEN -54.87 AND -45.86)
AND user_blocked=0
AND minimum_age<=35
AND maximum_age>=35
AND gender_search IN(0,1)
ORDER BY unix_timestamp_online DESC
LIMIT 20

Summarizing the conditions of the sample query..

*

*I am male=1 and search female=2

*Exclude some ids

*Born between 1961 AND 1999

*In latitude, longitude...

*Does not have any type of block=0

*My age=35 must be acceptable to these users

*My gender also needs to be acceptable (all=0, male=1)

*Order by displaying users who are online first

Explain the example query
id: 1
select_type: SIMPLE
table: users
partitions: NULL
type: index
possible_keys: PRIMARY
key: multiple_index
key_len: 19
ref: NULL
rows: 20
filtered: 0.25
Extra: Using where; Using index

This query takes an average of 0.0020 seconds
If I change the birth_year condition to (BETWEEN 1999 AND 1999)
The explanation is identical and the query takes an average of 9.1376 seconds
This multiple index does not look pretty, but it was the best so far. Any help is appreciated. Thank you.

A: why not do the query like this, using the simpler conditions before the complex ones.
SELECT id, latitude, longitude
FROM users
WHERE gender=2
AND user_blocked=0
AND minimum_age<=35
AND maximum_age>=35
AND gender_search IN(0,1)
AND id NOT IN (11111111,2222222)
AND (birth_year BETWEEN 1961 AND 1999)
AND (latitude BETWEEN -25.14 AND -16.13)
AND (longitude BETWEEN -54.87 AND -45.86)
ORDER BY unix_timestamp_online DESC
LIMIT 20


text:
Q: How to find correct columns by data from 1st row phpexcel I have excel file with some certain data i need.
"Category" is in first row of excel file.
Thing is that this data can be in different columns.
Is it possible to get column name based on data in first row ?
Example sheet:

For example, i need to get aircraft type and category, wich in this case are columns I & H.
At the moment i do it like this:
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet);
for($i=2;$i<=$arrayCount;$i++){
   $aircraftType = trim($allDataInSheet[$i]["I"]);
   $flightCategory = trim($allDataInSheet[$i]["H"]);

   #insert all data in these columns to database
   $query = "INSERT INTO {$databasetable} (aircraftType, flightCategory)
      VALUES('$aircarftType', '$flightCategory')";
   mysql_query($query) or trigger_error(mysql_error()." in ".$query);
}

But how can i do it, when i dont know column letter?
Maybe in next file aircraftType is in K and flightCategory is in L...
So is there a way to get column letter based on data in first row.
I think i could propably do it if i save all data to database, and then take it out with some where clauses, but maybe there is better way of doing this directly with PHPExcel ?
I am not really good explaining things, so sorry if this is confusing, please ask and i try to explain more.
Thanks in advance for help.

A: A simple call using the worksheet's rangeToArray() will give you an array of the headers
$headers = $objPHPExcel->getActiveSheet()
    ->rangeToArray(
        'A1:'.$objPHPExcel->getActiveSheet()->getHighestColumn().'1',
        null,
        false,
        false,
        true
    );
$headers = $headers[1];

The resultant array has the column letter as the key, and the cell content as the value; and you can then use it to map the appropriate columns to your data


text:
Q: Why can't MonoDroid find my assemblies? I made a simple Android HelloWorld app using Xamarin Studio 4.2.3 that doesn't do anything except it prints out some message if a random number is greater than 0.5. It works just great on a Nexus 4 and a Nexus 5.
The next thing I'm doing is to extract the .dll with the code from the app's apk (from the assemblies folder) using 7Zip. Using .Net Reflector and Reflexil I'm modifying a single instruction, usually the brfalse.s that gets generated by the IF statement in "if(rand.nextDouble()>0.5){doStuff()}" such that it branches to the instruction right in front of the call to doStuff(), thereby effectively making the IF statement useless and ensuring the method always gets called.
Next I'm saving the patched .dll, replacing the original one in the .apk with the patched one, sign and zipalign the .apk and finally I'm installing it using adb.
When I'm launching the app on my phones it crashes directly and LogCat shows the following:
03-20 10:12:08.709: I/ActivityManager(764): Start proc HelloMonoLVL.HelloMonoLVL for activity HelloMonoLVL.HelloMonoLVL/hellomonolvl.hellomonolvl.TrialSplashScreen: pid=23099 uid=10128 gids={50128}
03-20 10:12:08.729: D/dalvikvm(23099): Trying to load lib /data/app-lib/HelloMonoLVL.HelloMonoLVL-1/libmonodroid.so 0x427154a0
03-20 10:12:08.729: D/dalvikvm(23099): Added shared lib /data/app-lib/HelloMonoLVL.HelloMonoLVL-1/libmonodroid.so 0x427154a0
03-20 10:12:08.739: W/libc(23099): WARNING: generic atexit() called from legacy shared library
03-20 10:12:08.759: W/monodroid-gc(23099): GREF GC Threshold: 46800
03-20 10:12:08.769: A/monodroid-assembly(23099): Coult not load assembly 'HelloMonoLVL' during startup registration.
03-20 10:12:08.769: A/monodroid-assembly(23099): This might be due to an invalid debug instalation.
03-20 10:12:08.769: A/monodroid-assembly(23099): A common cause is to 'adb install' the app directly instead of doing from the IDE.
03-20 10:12:08.789: I/ActivityManager(764): Process HelloMonoLVL.HelloMonoLVL (pid 23099) has died.
03-20 10:12:08.789: W/ActivityManager(764): Force removing ActivityRecord{42752a50 u0 HelloMonoLVL.HelloMonoLVL/hellomonolvl.hellomonolvl.TrialSplashScreen t238}: app died, no saved state

Since this didn't work I used the C# port of the LVL. Built the LVL sample app, deployed and it works on the phones. I again extracted the .dll with the license verification code, using Reflexil I changed the code of a method, injected the patched .dll in the apk, signed and zipaligned the apk. Again it doesn't work but crashes on launch and I now get:
03-20 10:21:19.049: D/dalvikvm(23507): Trying to load lib /data/app-lib/de.marius.lvl-1/libmonodroid.so 0x42711448
03-20 10:21:19.049: D/dalvikvm(23507): Added shared lib /data/app-lib/de.marius.lvl-1/libmonodroid.so 0x42711448
03-20 10:21:19.069: A/MonoDroid(23507): No assemblies found in '/data/data/de.marius.lvl/files/.__override__' or '/storage/emulated/0/Android/data/de.marius.lvl/files/.__override__'. Assuming this is part of Fast Deployment. Exiting...
03-20 10:21:19.079: I/ActivityManager(764): Process de.marius.lvl (pid 23507) has died.
03-20 10:21:19.079: W/ActivityManager(764): Force removing ActivityRecord{42bc3c60 u0 de.marius.lvl/.TrialSplashScreen t239}: app died, no saved state

It doesn't seem to make any difference if I'm using the apk that Xamarin generates in Release mode or Debug mode. I tried both using the apk versions from the bin folder of the project and the ones I pulled from the phone with adb pull.
I'm new to Xamarin so maybe my approach is naive. Is there something like a hash check that my patched .dlls don't pass? I saw that Reflexil has an option to remove StrongNames, I tried that but it didn't seem to make any difference (but I must admit I don't really know how those work).
Is it even possible what I'm trying to do?
Any help is much appreciate.

A: Uninstall all the packages installed in your project including android support libraries like Android.Support.v4 support libraries and clean the solution.
Then again reinstall all the required packages and support libraries and rebuild your solution. It may help you sort out your query.


text:
Q: Flash Media Server calling a page that returns JSON data I am very new to Flash development.
I have an asp.net mvc site that has a controller action that returns JSON.
I have a Flash Media Server setup that needs to call that controller action every 15 minutes to get the current schedule. I can get the FMS to call the site (and every 15 minutes no problem) and I am getting the JSON right now as a string, but I need to parse it from the string to objects, in order to use the data returned.
Any pointers or ideas would be very welcomed.

A: Mike Chambers has an AS3 library on github (https://github.com/mikechambers/as3corelib). One of the libraries is for JSON serialization and parsing. Here's his example of it in a Flex MXML document, but would be the same in AS3 ( you basically get the JSON data, then call JSON.decode() on it to get an Array. ):
<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"
layout="absolute"
creationComplete="service.send()" viewSourceURL="srcview/index.html">

<mx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        import mx.rpc.events.ResultEvent;
        import com.adobe.serialization.json.JSON;

        private function onJSONLoad(event:ResultEvent):void
        {
            var rawData:String = String(event.result);
            var arr:Array = (JSON.decode(rawData) as Array);

            var dp:ArrayCollection = new ArrayCollection(arr);

            grid.dataProvider = dp;
        }
    ]]>
</mx:Script>

<mx:HTTPService
    id="service"
    resultFormat="text"
    url="http://weblogs.macromedia.com/mesh/mashedpotato.json"
    result="onJSONLoad(event)" />

<mx:DataGrid id="grid" right="10" left="10" top="10" bottom="10">
    <mx:columns>
        <mx:DataGridColumn headerText="Service" dataField="src"/>
        <mx:DataGridColumn headerText="Title" dataField="title"/>
    </mx:columns>
</mx:DataGrid>

A: I guess you are using a webservice call from FMS to get the data. In Actionscript 1, I think you should be able to use eval() to get an object that you can then query.
var callback = mWebService.NewGuid();
mWebService.onResult = function(resultString){
    var resultObject = eval(resultString);
    trace(resultObject.mProperty1);
}


text: Q: Microservices : hitting same microservice multiple time I was running microservices in debug mode but i recognise that my code is running multiple times means one request done his job still the other one is doing same I am new in microservices not able to understand why it is happening? is because of multiple eureka instances or what?how can i avoid it?


text:
Q: Commutative Tikz diagrams I am trying to draw a diagram similar to this

but my background is so basic I can not draw complected Tikz diagrams, the best I can come up with is the following:
\documentclass{article}
\usepackage{tikz-cd}
\begin{document}
\begin{tikzcd}
1 \arrow{rrr}{a}
\arrow[swap]{ ddd}{ h} & & & 2 \arrow{ddd}{g} \\
& 3 \arrow{r}{c}
\arrow{d}{d}
\arrow{ul}{0}
& 4 \arrow{d}{e}
\arrow{ur}{00}& \\
& 5 \arrow{r}{f}
\arrow{dl}{00}
& 6  \arrow{dr}{0}& \\
7 \arrow[swap]{rrr}{b} & & & 8
\end{tikzcd}
\end{document}

I'll appreciate any help, Thanks.

A: Did you want something like this? The diagonal arrows in the outer rim are not like those in your first image, but since you had added them yourself, I left them as they were.
Output

Code
\documentclass[margin=10pt]{standalone}
\usepackage{tikz-cd}
\begin{document}
\begin{tikzcd}
1 \arrow{rrrrr}{a} \arrow[swap]{dddd}{h} & & & & & 2 \arrow{dddd}{g} \\
& 3 \arrow{rr}{c} \arrow{dd}{d} \arrow{ul}{0} & & 4 \arrow{dd}{e} \arrow{dl} \arrow{urr}{00}& \\
& & Y & & \\
& 5 \arrow[""{name=F, anchor=center}]{rr}{f} \arrow{ur} \arrow{dl}{00} & & 6 \arrow{drr}{0} \arrow[dashed]{ul} & \\
7 \arrow[swap]{rrrrr}{b} & & & & & 8
\arrow[to=F, dashed, -] \arrow[from=F, dashed]{uulll}
\end{tikzcd}
\end{document}


text:
Q: Calculation of modularity from sonarqube Is there a way to calculate modularity metric from the preexisting metrics in SonarQube? I want to calculate modularity so that I can use it for my technical debt calculation.

A: The Modularity of software is a composite metric. Thus, first you need to define the modularity and participating metrics. The paper you mentioned (http://arxiv.org/ftp/arxiv/papers/1309/1309.5689.pdf) offers one of the ways.
An alternative way is to detect modularity design smells and form a modularity metric formula (that uses the number of detected instances of modularity design smells). The modularity design smells are: Insufficient Modularization, Broken Modularization, Cyclically-dependent Modularization, and Hub-like Modularization (refer "Refactoring for software design smells").


text:
Q: Database Transactions Not Found - Lumen I've been writing tests in lumen but I need to move to a different machine so I've been trying to set it all up. I copied over my tests but I get this error on all of them when I run them
 [Symfony\Component\Debug\Exception\FatalErrorException]
 Trait 'Laravel\Lumen\Testing\DatabaseTransactions' not found

I think I have lumen installed as I did the command composer require "laravel/installer". Is there something I'm meant to do?
Edit:
I looked at the version that was working on my old machine and this code was at the top of app.php in the bootstrap folder
try {
(new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
//
}

I inserted that at the top of app.php on my new machine and that error stopped appearing and I was now able to run a test. Unfortunately a new error occurs when I just have the default example test
1) ExampleTest::testBasicExample
   Error: Call to undefined method ExampleTest::visit()

I'm guessing that I'm still missing something from lumen/laravel

A: That command is for the Laravel installer. The command for the Lumen installer is:
composer require "laravel/lumen-installer"

However, even then, that only installs the installer. You still need to run the command to create a new install (e.g. lumen new my-site).
There's a lot of ambiguity as to what you're trying to do and what you've attempted.
Generally when installing your site on a new machine, you should just need to clone your repository (or copy your code over), and do a composer install.

A: Try the following:
composer cache clean
composer update
composer dump-autoload