text:
Q: Do you know the Maven profile for mvnrepository.com? I am trying to include some dependencies in my Maven project. These dependencies are not available in the default Maven 2 repository http://repo1.maven.org/maven2/.
They are available at http://mvnrepository.com/.
But I couldn't find the profile for this site to include in my settings.xml.
Does anyone know what this repository's URL and profile is?

A: Please use this profile
  <profiles>
    <profile>
        <repositories>
            <repository>
                <id>mvnrepository</id>
                <name>mvnrepository</name>
                <url>http://www.mvnrepository.com</url>
            </repository>
        </repositories>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>mvnrepository</activeProfile>
  </activeProfiles>

A: Once you've found your jar through mvnrepository.com, hover the "download (JAR)" link, and you'll see the link to the repository which contains your jar (you can probably Right clic and "Copy link URL" to get the URL, what ever your browser is).
Then, you have to add this repository to the repositories used by your project, in your pom.xml :
<project>
  ...
  <repositories>
    <repository>
      <id>my-alternate-repository</id>
      <url>http://myrepo.net/repo</url>
    </repository>
  </repositories>
  ...
</project>

EDIT : now MVNrepository.com has evolved : You can find the link to the repository in the "Repositories" section :
License
Categories
HomePage
Date
Files
Repositories

A: mvnrepository.com isn't a repository. It's a search engine. It might or might not tell you what repository it found stuff in if it's not central; since you didn't post an example, I can't help you read the output.

A: You can put this configuration in your settings.xml file:
            <repository>
                <id>mvnrepository</id>
                <url>http://repo1.maven.org/maven2</url>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
                <releases>
                    <enabled>true</enabled>
                </releases>
            </repository>

A: Place this in the ~/.m2/settings.xml or custom file to be run with $ mvn -s custom-settings.xml install
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>${user.home}/.m2/repository</localRepository>
<interactiveMode/>
<offline/>
<pluginGroups/>
<profiles>
    <profile>
        <repositories>
            <repository>
                <id>mvnrepository</id>
                <name>mvnrepository</name>
                <url>http://www.mvnrepository.com</url>
            </repository>
        </repositories>
    </profile>
</profiles>
<activeProfiles>
    <activeProfile>mvnrepository</activeProfile>
</activeProfiles>
</settings>

A:             <?xml version="1.0" encoding="UTF-8"?>

            <!--
            Licensed to the Apache Software Foundation (ASF) under one
            or more contributor license agreements.  See the NOTICE file
            distributed with this work for additional information
            regarding copyright ownership.  The ASF licenses this file
            to you under the Apache License, Version 2.0 (the
            "License"); you may not use this file except in compliance
            with the License.  You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
            Unless required by applicable law or agreed to in writing,
            software distributed under the License is distributed on an
            "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
            KIND, either express or implied.  See the License for the
            specific language governing permissions and limitations
            under the License.
            -->

            <!--
             | This is the configuration file for Maven. It can be specified at two levels:
             |
             |  1. User Level. This settings.xml file provides configuration for a single user,
             |                 and is normally provided in ${user.home}/.m2/settings.xml.
             |
             |                 NOTE: This location can be overridden with the CLI option:
             |
             |                 -s /path/to/user/settings.xml
             |
             |  2. Global Level. This settings.xml file provides configuration for all Maven
             |                 users on a machine (assuming they're all using the same Maven
             |                 installation). It's normally provided in
             |                 ${maven.conf}/settings.xml.
             |
             |                 NOTE: This location can be overridden with the CLI option:
             |
             |                 -gs /path/to/global/settings.xml
             |
             | The sections in this sample file are intended to give you a running start at
             | getting the most out of your Maven installation. Where appropriate, the default
             | values (values used when the setting is not specified) are provided.
             |
             |-->
            <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
              <!-- localRepository
               | The path to the local repository maven will use to store artifacts.
               |
               | Default: ${user.home}/.m2/repository
              <localRepository>/path/to/local/repo</localRepository>
              -->

              <!-- interactiveMode
               | This will determine whether maven prompts you when it needs input. If set to false,
               | maven will use a sensible default value, perhaps based on some other setting, for
               | the parameter in question.
               |
               | Default: true
              <interactiveMode>true</interactiveMode>
              -->

              <!-- offline
               | Determines whether maven should attempt to connect to the network when executing a build.
               | This will have an effect on artifact downloads, artifact deployment, and others.
               |
               | Default: false
              <offline>false</offline>
              -->

              <!-- pluginGroups
               | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
               | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
               | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
               |-->
              <pluginGroups>
                <!-- pluginGroup
                 | Specifies a further group identifier to use for plugin lookup.
                <pluginGroup>com.your.plugins</pluginGroup>
                -->
              </pluginGroups>

              <!-- proxies
               | This is a list of proxies which can be used on this machine to connect to the network.
               | Unless otherwise specified (by system property or command-line switch), the first proxy
               | specification in this list marked as active will be used.
               |-->
              <proxies>
                <!-- proxy
                 | Specification for one proxy, to be used in connecting to the network.
                 |
                <proxy>
                  <id>optional</id>
                  <active>false</active>
                  <protocol>http</protocol>
                  <username>proxyuser</username>
                  <password>proxypass</password>
                  <host>proxy.host.net</host>
                  <port>80</port>
                  <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
                </proxy>
                -->
              </proxies>

              <!-- servers
               | This is a list of authentication profiles, keyed by the server-id used within the system.
               | Authentication profiles can be used whenever maven must make a connection to a remote server.
               |-->
              <servers>
                <!-- server
                 | Specifies the authentication information to use when connecting to a particular server, identified by
                 | a unique name within the system (referred to by the 'id' attribute below).
                 |
                 | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
                 |       used together.
                 |
                <server>
                  <id>deploymentRepo</id>
                  <username>repouser</username>
                  <password>repopwd</password>
                </server>
                -->

                <!-- Another sample, using keys to authenticate.
                <server>
                  <id>siteServer</id>
                  <privateKey>/path/to/private/key</privateKey>
                  <passphrase>optional; leave empty if not used.</passphrase>
                </server>
                -->
              </servers>

              <!-- mirrors
               | This is a list of mirrors to be used in downloading artifacts from remote repositories.
               |
               | It works like this: a POM may declare a repository to use in resolving certain artifacts.
               | However, this repository may have problems with heavy traffic at times, so people have mirrored
               | it to several places.
               |
               | That repository definition will have a unique id, so we can create a mirror reference for that
               | repository, to be used as an alternate download site. The mirror site will be the preferred
               | server for that repository.
               |-->
              <mirrors>
                <!-- mirror
                 | Specifies a repository mirror site to use instead of a given repository. The repository that
                 | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
                 | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
                 |
                <mirror>
                  <id>mirrorId</id>
                  <mirrorOf>repositoryId</mirrorOf>
                  <name>Human Readable Name for this Mirror.</name>
                  <url>http://my.repository.com/repo/path</url>
                </mirror>
                 -->
              </mirrors>

              <!-- profiles
               | This is a list of profiles which can be activated in a variety of ways, and which can modify
               | the build process. Profiles provided in the settings.xml are intended to provide local machine-
               | specific paths and repository locations which allow the build to work in the local environment.
               |
               | For example, if you have an integration testing plugin - like cactus - that needs to know where
               | your Tomcat instance is installed, you can provide a variable here such that the variable is
               | dereferenced during the build process to configure the cactus plugin.
               |
               | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
               | section of this document (settings.xml) - will be discussed later. Another way essentially
               | relies on the detection of a system property, either matching a particular value for the property,
               | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
               | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
               | Finally, the list of active profiles can be specified directly from the command line.
               |
               | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
               |       repositories, plugin repositories, and free-form properties to be used as configuration
               |       variables for plugins in the POM.
               |
               |-->
              <profiles>

              <profile>
                <id>maven-https</id>
                <activation>
                    <activeByDefault>true</activeByDefault>
                </activation>
                <repositories>
                    <repository>
                        <id>central</id>
                        <url>https://repo1.maven.org/maven2</url>
                        <snapshots>
                            <enabled>false</enabled>
                        </snapshots>
                    </repository>
                </repositories>
                <pluginRepositories>
                    <pluginRepository>
                        <id>central</id>
                        <url>https://repo1.maven.org/maven2</url>
                        <snapshots>
                            <enabled>false</enabled>
                        </snapshots>
                    </pluginRepository>
                </pluginRepositories>
            </profile>

                <!-- profile
                 | Specifies a set of introductions to the build process, to be activated using one or more of the
                 | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
                 | or the command line, profiles have to have an ID that is unique.
                 |
                 | An encouraged best practice for profile identification is to use a consistent naming convention
                 | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
                 | This will make it more intuitive to understand what the set of introduced profiles is attempting
                 | to accomplish, particularly when you only have a list of profile id's for debug.
                 |
                 | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
                <profile>
                  <id>jdk-1.4</id>
                  <activation>
                    <jdk>1.4</jdk>
                  </activation>
                  <repositories>
                    <repository>
                      <id>jdk14</id>
                      <name>Repository for JDK 1.4 builds</name>
                      <url>http://www.myhost.com/maven/jdk14</url>
                      <layout>default</layout>
                      <snapshotPolicy>always</snapshotPolicy>
                    </repository>

                  </repositories>
                </profile>
                -->

                <!--
                 | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
                 | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
                 | might hypothetically look like:
                 |
                 | ...
                 | <plugin>
                 |   <groupId>org.myco.myplugins</groupId>
                 |   <artifactId>myplugin</artifactId>
                 |
                 |   <configuration>
                 |     <tomcatLocation>${tomcatPath}</tomcatLocation>
                 |   </configuration>
                 | </plugin>
                 | ...
                 |
                 | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
                 |       anything, you could just leave off the <value/> inside the activation-property.
                 |
                <profile>
                  <id>env-dev</id>
                  <activation>
                    <property>
                      <name>target-env</name>
                      <value>dev</value>
                    </property>
                  </activation>
                  <properties>
                    <tomcatPath>/path/to/tomcat/instance</tomcatPath>
                  </properties>
                </profile>
                -->
              </profiles>

              <!-- activeProfiles
               | List of profiles that are active for all builds.
               |
              <activeProfiles>
                <activeProfile>alwaysActiveProfile</activeProfile>
                <activeProfile>anotherAlwaysActiveProfile</activeProfile>
              </activeProfiles>
              -->
            </settings>


text:
Q: Dynamic scope variable in angularjs I am trying to create dynamic scope variable in angular.I am using a loop to set the variable name as v1,v2,v3 but still no success.
Any idea how achieve this ?
js
for (var i = 0; i < 4; i++) {
    $scope.v_i='value'+i;
  }

html

{{v1}}

{{v2}}

{{v3}}

A: You can use the $scope object as typeof Array.
But I would wrap them to a $scope object wrapper items.
See both approaches below.
VIEW

  {{v0}}

 {{v1}}

 {{v2}}

 {{v3}}

 {{items}}

    {{item}}

CONTROLLER
 angular
.module('app', [])
.controller('MainController', MainController)

function MainController($scope) {
  $scope.items = {};
  for (var i = 0; i < 4; i++) {
    $scope['v' + i] = 'value' + i;
    // or add to object wrapper
    $scope.items['v' + i] = 'value' + i;
  }
}

JSFIDDLE

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Keep ViewModel Constructor From Being Called Twice I'm very new to MVVM and am having an issue with my ViewModel constructor being called twice. In the code below, I'm instantiating a new MainWindowViewModel and assigning it to the MainWindow's DataContext.
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
        DataContext = mainWindowViewModel; //Set the datacontext to the view model
        this.Opened += mainWindowViewModel.WindowLoaded; //Subscribe to Window Opened Event

    }
}

I understand that I could have just done something like this:
DataContext = new MainWindowViewModel()
The thing is I need to be able to subscribe to the MainWindow's "Opened" event and that was the only way I could figure out how to do it. So in the MainWindowViewModel I have this function:
 public void WindowLoaded(object sender, EventArgs e)
    {

        //Do The Stuff When Window is Loaded

    }

Is there anyway I could keep the MainWindowViewModel constructor from being called twice and still be able to subscribe to the MainWindow event? Any help or nudge in the right direction is appreciated. Thanks!


text:
Q: Trying to read strings from .txt file into string array using fscanf, worked with ints but not strings. Segfault I'm trying to read numbers from a text file as strings then put them into an array. I initially had an integer array and was reading with fscanf with data type "%d". That worked fine, but I would like to read the numbers as strings instead.
So I've created the nums array, and I'm trying to have fscanf read strings into the nums array. (The reason the array is a fixed size is because my assignment dictates this).
The code compiles without any warnings, but the first attempt to read "%s" into nums[y] creates a segmentation fault.
The txt file I'm opening into fp is somewhat as follows: "83222 331111 335533 33222 33333..." with about 5000 numbers with a space between each one.
char *nums[76*76];
int y = 0;
while (fscanf(fp,"%s",nums[y]) == 1){
   y++;
}


text:
Q: PhantomJS script returning blank web page I'm using phantomJS to create PDFs in PHP via the shell (shell_exec). The script works fine on the production server, and also works fine if I plug the PhantomJS command directly into my terminal.
But it does not work when I run the script in my local dev environment. I'm wondering if there's a permissions issue involved. I won't dive into the specifics of my local environment for now since I'm guessing this is a high-level issue...
The command that is supposed to execute via shell_exec():

/usr/local/bin/phantomjs --ignore-ssl-errors=true --debug=true ../scripts/renderTeamProfile.js https://127.0.0.1/app_dev.php/pdf/enterprise-lpc-enterprise/profile/render /private/var/tmp/pjsK2N16E.pdf

The php code:
 public function pdfResponse($url, $script, $remote_filename)
 {
    $tempFile = tempnam('/tmp', 'pjs');
    // The extension specifies output format. Use pdf
    $tempFilePdf = $tempFile . '.pdf';
    rename($tempFile, $tempFilePdf);

    # nginx should restrict access to the localhost URL
    $urlLocal = preg_replace('/^https:..[^\/]+/', 'https://127.0.0.1', $url);

    $phantomJs = $this->container->getParameter('testsite.phantomjs_cmd');
    $command = $phantomJs.' --debug=true '.$script.' '.$urlLocal.' '.$tempFilePdf;
    $output = shell_exec($command);
    $content = file_get_contents($tempFilePdf);
    $response = new Response($content, 200);
    $response->headers->set('Content-Type', 'application/pdf');
    $response->headers->set('Content-Disposition',
    ('inline; filename="' .    $remote_filename . '"'));
    return $response;
}

A: Turns out there was a different version of phantomjs installed locally vs. on the prod server. Interestingly, the bug occurred with the newer version (2.0.0) vs. 1.9.8.


text:
Q: save header in a variable using php I need help saving one header in a variable using php. My problem its that i have a header called x-wap-msisdn, and this header content  a information that i need.
My question its how can i get that header using php?
thanks for your help.
pd.
I use this code to be sure that i have that header:
<?php

$headers = apache_request_headers();
$xwap = "x-wap-msisdn";
foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";

}
?>

thanks!.

A: This code will set the desired header content into $header_content
<?php
    $headers = apache_request_headers();
    $xwap = "x-wap-msisdn";
    $header_content = $headers[$xwap];

    //Output header content
    echo $header_content;
?>


text:
Q: AFNetworking 1.x to 3.x migration - get download progress? I need to download image with progress bar. This is what I've got for in AFNetworking 1.x which is not working for AFNetworking 3.x.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.mediaItem.media_item_hd_url]];

AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFImageResponseSerializer serializer];

[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    UIImage *image = responseObject;
    _image = image;

    [self.delegate browserItem:self loaded:1.0 finished:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { }];

[op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    CGFloat progress = ((CGFloat)totalBytesRead)/((CGFloat)totalBytesExpectedToRead);
    [self.delegate browserItem:self loaded:progress finished:NO];
}];

[[NSOperationQueue mainQueue] addOperation:op];

Finally this is what I could come up with, which is not complete. I have no idea how to use progress in code block.
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.mediaItem.media_item_hd_url]];

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

        NSLog(@"File downloaded to: %@", filePath);
//        UIImage *image = response;
//        _image = image;

        [self.delegate browserItem:self loaded:1.0 finished:YES];

    }];

    [downloadTask resume];

A: You can get best framework RSNetworkKit which handles all the network call with an ease. It has internally implemented AFNetworking 3.0.  It'll gives you download progress in single method either you upload, download.
It has also an enhanced method to show progress on UIImageView.
You can find it here. https://github.com/rushisangani/RSNetworkKit


text:
Q: In R: How can I check that I have consecutive years of data (to later be able to calculate growth)? I have the dataframe (sample) below:
companyID   year   yearID
    1       2010     1
    1       2011     2
    1       2012     3
    1       2013     4
    2       2010     1
    2       2011     2
    2       2016     3
    2       2017     4
    2       2018     5
    3       2010     1
    3       2011     2
    3       2014     3
    3       2017     4
    3       2018     5

I have used a for loop in order to try and create a sequence column that starts a new number for each new sequence of numbers. I am new to R so my definitions may be a bit wrong. My for loop looks like this:
size1 <- c(1:3)
s <- 0
for (val1 in size) {
  m <- max(sample[sample$companyID == val1, 4])
  size2 <- c(1:m)
  for (val2 in size2){
    row <- sample[which(sample$companyID == val1 & sample$yearID == val2)]
    m1 <- sample[sample$companyID == val1 & sample$yearID == val2, 2]
    m2 <- sample[sample$CompanyID == val1 & sample$yearID == (val2-1), 2]
    if(val2>1 && m1-m2 > 1) {
                  sample$sequence[row] s = s+1}
    else {s = s}
  }
  }

Where m is the max value of the yearID per companyID, row is to identify that the value should be entered on the row where companyID = val1 and yearID = val2, m1 is from the year variable and is the latter year, whereas m2 is the former year. What I have tried to do is to change the sequence every time m1-m2 > 1 (when val2 > 1 also).
Desired outcome:
companyID   year   yearID   sequence
    1       2010     1          1
    1       2011     2          1
    1       2012     3          1
    1       2013     4          1
    2       2010     1          2
    2       2011     2          2
    2       2016     3          3
    2       2017     4          3
    2       2018     5          3
    3       2010     1          4
    3       2011     2          4
    3       2014     3          5
    3       2017     4          6
    3       2018     5          6

Super appreciative if anyone can help!!

A: This is a good question!

*

*First group_by companyID

*calculate the difference of each consecutive row in year column with lag to identify if year is consecutive.

*group_by companyID, yearID)

*mutate helper column sequence1 to apply 1 to each starting consecutive year in group.

*ungroup and apply a sequence number eachtime 1
occurs in sequence1

*remove column sequence1 and deltalag1
library(tidyverse)

df1 <- df %>%
  group_by(companyID) %>%
  mutate(deltaLag1 = year - lag(year, 1)) %>%
  group_by(companyID, yearID) %>%
  mutate(sequence1 = case_when(is.na(deltaLag1) | deltaLag1 > 1 ~ 1,
                               TRUE ~ 2)) %>%
  ungroup() %>%
  mutate(sequence = cumsum(sequence1==1)) %>%
  select(-deltaLag1, -sequence1)

data
df <- tribble(
~companyID,   ~year,   ~yearID,
1, 2010, 1,
1, 2011, 2,
1, 2012, 3,
1, 2013, 4,
2, 2010, 1,
2, 2011, 2,
2, 2016, 3,
2, 2017, 4,
2, 2018, 5,
3, 2010, 1,
3, 2011, 2,
3, 2014, 3,
3, 2017, 4,
3, 2018, 5)

A: It's not clear if you want the exact desired outcome or check that you have consecutive years by companyID.
According to your title message:
sample <- read.table(header = TRUE, text = "
companyID   year   yearID
    1       2010     1
    1       2011     2
    1       2012     3
    1       2013     4
    2       2010     1
    2       2011     2
    2       2016     3
    2       2017     4
    2       2018     5
    3       2010     1
    3       2011     2
    3       2014     3
    3       2017     4
    3       2018     5
")

library(data.table)
sample <- setDT(sample)
sample[ , diff_year := year - shift(year), by = companyID]
sample <- setDF(sample)
sample
#>    companyID year yearID diff_year
#> 1          1 2010      1        NA
#> 2          1 2011      2         1
#> 3          1 2012      3         1
#> 4          1 2013      4         1
#> 5          2 2010      1        NA
#> 6          2 2011      2         1
#> 7          2 2016      3         5
#> 8          2 2017      4         1
#> 9          2 2018      5         1
#> 10         3 2010      1        NA
#> 11         3 2011      2         1
#> 12         3 2014      3         3
#> 13         3 2017      4         3
#> 14         3 2018      5         1

# Created on 2021-03-13 by the reprex package (v1.0.0.9002)

Related to Calculate difference between values in consecutive rows by group
Regards,


text:
Q: null value for custom property aspects in alfresco 4.2e I am trying to insert document with custom property in java using Alfresco 4.2e. Now values are inserting without any error, but value for custom property is not set, it is showing null.
This my code:
    Map<String, String> props = new HashMap<String, String>();
    props.put(PropertyIds.NAME, newDocName);
    props.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document,P:kb:referencable");
    props.put("kb:documentRef", "123");
    props.put("kb:documentID", "1234");
    String content = "sample=================";
    byte[] buf = null;
    try {
        buf = content.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    ByteArrayInputStream input = new ByteArrayInputStream(buf);
    ContentStream contentStream = session.getObjectFactory()
            .createContentStream(newDocName, buf.length,
                    "text/plain; charset=UTF-8", input);
    target.createDocument(props, contentStream, VersioningState.MAJOR);

Serach query:
    String query = "SELECT * FROM kb:referencable ";
    ItemIterable<QueryResult> queryResult = session.query(query, false);
    for (QueryResult item : queryResult) {
         System.out.println("item="+item.getProperties());

    }

Here is the search output:
item=[Property [id=kb:documentRef, display Name=KB Reference, local name=documentRef, query name=kb:documentRef, values=[]][extensions=null], Property [id=cmis:objectTypeId, display Name=Object Type Id, local name=objectTypeId, query name=cmis:objectTypeId, values=[cmis:document]][extensions=null], Property [id=cmis:lastModifiedBy, display Name=Last Modified By, local name=lastModifiedBy, query name=cmis:lastModifiedBy, values=[admin]][extensions=null], Property [id=cmis:name, display Name=Name, local name=name, query name=cmis:name, values=[chemistryTest1.txt]][extensions=null], Property [id=cmis:createdBy, display Name=Created by, local name=createdBy, query name=cmis:createdBy, values=[admin]][extensions=null], Property [id=kb:documentID, display Name=kb:documentID, local name=documentID, query name=kb:documentID, values=[]][extensions=null], Property [id=cmis:objectId, display Name=Object Id, local name=objectId, query name=cmis:objectId, values=[149666ab-5745-4365-b63e-c26cb6f4f6cc;1.0]][extensions=null], Property [id=cmis:creationDate, display Name=Creation Date, local name=creationDate, query name=cmis:creationDate, values=[java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+05:30",offset=19800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=2015,MONTH=0,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=1,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=?,HOUR=?,HOUR_OF_DAY=9,MINUTE=32,SECOND=59,MILLISECOND=725,ZONE_OFFSET=?,DST_OFFSET=?]]][extensions=null], Property [id=cmis:changeToken, display Name=Change token, local name=changeToken, query name=cmis:changeToken, values=[]][extensions=null], Property [id=cmis:secondaryObjectTypeIds, display Name=Secondary Object Type Ids, local name=secondaryObjectTypeIds, query name=cmis:secondaryObjectTypeIds, values=[P:kb:referencable, P:cm:titled, P:cm:author, P:sys:localized]][extensions=null], Property [id=cmis:baseTypeId, display Name=Base Type Id, local name=baseTypeId, query name=cmis:baseTypeId, values=[cmis:document]][extensions=null], Property [id=alfcmis:nodeRef, display Name=Alfresco Node Ref, local name=nodeRef, query name=alfcmis:nodeRef, values=[workspace://SpacesStore/149666ab-5745-4365-b63e-c26cb6f4f6cc]][extensions=null], Property [id=cmis:description, display Name=Description, local name=description, query name=cmis:description, values=[]][extensions=null], Property [id=cmis:lastModificationDate, display Name=Last Modified Date, local name=lastModificationDate, query name=cmis:lastModificationDate, values=[java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+05:30",offset=19800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=2015,MONTH=0,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=1,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=?,HOUR=?,HOUR_OF_DAY=9,MINUTE=32,SECOND=59,MILLISECOND=725,ZONE_OFFSET=?,DST_OFFSET=?]]][extensions=null]]

Here value for kb:documentRef and kb:documentID (custom property)is null.

A: Well, honestly I don't know if kb:documentRef is parsed as a shorthand, but the passed props map has to be of this type:
Map<QName,Serializable> props = new Map<QName,Serializable>();

Then supposing your namespace in model is http://www.custommodel.com/kb/1.0 you should do:
props.put(new QName("http://www.custommodel.com/kb/1.0","documentRef"), "123");
props.put(new QName("http://www.custommodel.com/kb/1.0","documentID"), "1234");

Or, better, you could write your convenient interface:
public interface MyModel {
   KB_DOCUMENT_REF = new QName("http://www.custommodel.com/kb/1.0","documentRef");
}

Then, much clearer:
props.put(MyModel.KB_DOCUMENT_REF, "123");


text:
Q: coreplot dynamic graph line not visible I am working to have live graph displayed using coreplot. I am fetching the data every 2 seconds and passing that to the coreplot datasource but i dont see the line. i notice the x-axis (time axis) is updating correctly. Any advise please
  //listen to notification center and update the plot

    - (id) init
    {
        self = [super init];
        if (!self) return nil;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(receiveDownloadDataNotification:)
                                                     name:@"Data"
                                                   object:nil];
        NSLog(@" downalodData notification listening");
        return self;
    }

    -(void)constructGraph1
    {

    // Create graph from a  theme
    graph1 = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
    CPTTheme *theme = [ CPTTheme themeNamed:kCPTPlainWhiteTheme];
    [graph1 applyTheme:theme];

    CPTGraphHostingView *hostingView = (CPTGraphHostingView *)self.view;
    hostingView.hostedGraph = graph1;

    graph1.plotAreaFrame.masksToBorder = NO;

    //create x-axis time format

    NSTimeInterval refTimeInterval = [[NSDate date]
                                      timeIntervalSinceReferenceDate];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm:ss a"];

    CPTTimeFormatter *timeFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
    timeFormatter.referenceDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0];

    // Setup plot space
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph1.defaultPlotSpace;
    plotSpace.allowsUserInteraction = NO;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(refTimeInterval-(5*oneMin)) length:CPTDecimalFromFloat(2*oneMin)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(100.0)];
    plotSpace.globalYRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(100.0f)];

    //Line Styles
    CPTScatterPlot *boundLinePlot = [[CPTScatterPlot alloc] init];

    CPTMutableLineStyle *lineStyle = [boundLinePlot.dataLineStyle mutableCopy];
    lineStyle.lineWidth         = 1.0f;
    lineStyle.lineColor         = [CPTColor blueColor];
    boundLinePlot.dataLineStyle = lineStyle;

    CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
    majorGridLineStyle.lineWidth = 0.75;
    majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
    CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
    minorGridLineStyle.lineWidth = 0.25;
    minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];

    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph1.axisSet;

    // X-Axes formatting
    CPTXYAxis *x = axisSet.xAxis;
    x.majorIntervalLength = CPTDecimalFromInteger(30);
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
    x.minorTicksPerInterval = 0;
    x.labelOffset=0;
    x.labelFormatter = timeFormatter;
    x.majorGridLineStyle = majorGridLineStyle;
    x.minorGridLineStyle = minorGridLineStyle;
    x.title=@"Time Axis";
    x.labelFormatter = timeFormatter;

    //Y-Axes formatting
    CPTXYAxis *y = axisSet.yAxis;
    y.majorIntervalLength =  CPTDecimalFromInteger(10);
    y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(refTimeInterval-oneMin);
    y.minorTicksPerInterval = 5;
    y.labelOffset = 0;
    y.majorGridLineStyle = majorGridLineStyle;
    y.minorGridLineStyle = minorGridLineStyle;
    y.preferredNumberOfMajorTicks = 10;
    y.minorTickLineStyle = nil;
    y.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0) length:CPTDecimalFromInteger(100)];
    y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
    y.title=@"Mbps";

    // Create a plot that uses the data source method
    CPTScatterPlot *dataSourceLinePlot = [[CPTScatterPlot alloc] init] ;
    dataSourceLinePlot.identifier = @"graph Plot";
    dataSourceLinePlot.dataLineStyle = lineStyle;
    dataSourceLinePlot.dataSource = self;

    [graph1 addPlot:dataSourceLinePlot];
    graphDatatoPlot = [[NSMutableArray alloc]init];

}

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
    return graphDatatoPlot.count;
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    if ( [plot.identifier isEqual:@"graph Plot"] ){
        NSDecimalNumber *num = [[graphDatatoPlot objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];

        return num;
    }

    return 0;
}

- (void) receiveDownloadDataNotification:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:@"Data"])
    {
        NSLog(@"received item %@",[notification object]);
        [graphDatatoPlot addObject:[notification object]];
        [graph1 reloadData];
        CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph1.defaultPlotSpace;

        NSTimeInterval aTimeInterval = [[NSDate date]timeIntervalSinceReferenceDate];
        plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(aTimeInterval-(5*oneMin)) length:CPTDecimalFromInt(2*oneMin)];

        NSLog(@"plot count %i",graphDatatoPlot.count);
    }
}

just to test i am sending a constant value of 20 to the Notification center. Time is fired  OK, x-axis is updated but i dont see the actual line at 20 mark.
-(void)testTimer:(NSTimer *)Timer {

    NSTimeInterval timeNow= [NSDate timeIntervalSinceReferenceDate];

    NSMutableDictionary  *newData=  [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                           [NSDecimalNumber numberWithInt:timeNow], [NSNumber numberWithInt:CPTScatterPlotFieldX],
                                           [NSDecimalNumber numberWithInt:20], [NSNumber numberWithInt:CPTScatterPlotFieldX],nil
                                           ] ;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"Data" object:newData];

    NSLog(@"newdata is %@ %f",newData,timeNow);

}

A: The data points are outside the xRange. Each data point is given a x-value of the current time, but the xRange is set to a range starting five minutes before the current time with a length of two minutes, meaning it ends three minutes before the current time.


text:
Q: How Do I Merge These Two Datasets? I have two datasets. I would like to merge using the index.
The 1st data set:
index       A   B   C
01/01/2010  15  20  30
15/01/2010  12  15  25
17/02/2010  14  13  35
19/02/2010  11  10  22

The 2nt data set:
index  year  month     price
0      2010  january   70
1      2010  february  80

I want them to be joined like:
index       A   B   C   price
01/01/2010  15  20  30  70
15/01/2010  12  15  25  70
17/02/2010  14  13  35  80
19/02/2010  11  10  22  80

The problem is how to use two columns (year and month of the 2nd dataset)  to create a temporary datetime index.

A: Try this, by extracting .month_name() and year(.dt.year) from df1 and merge it with df2
>>> df1
        index   A   B   C
0  01/01/2010  15  20  30
1  15/01/2010  12  15  25
2  17/02/2010  14  13  35
3  19/02/2010  11  10  22
>>> df2
   index  year     month  price
0      0  2010   january     70
1      1  2010  february     80

# merging df1 and df2 by month and year.
>>> df1.merge(df2,
              left_on = [pd.to_datetime(df1['index']).dt.year,
                 pd.to_datetime(df1['index']).dt.month_name().str.lower()],
              right_on = ['year', 'month'])

Output:
      index_x   A   B   C  index_y  year     month  price
0  01/01/2010  15  20  30        0  2010   january     70
1  15/01/2010  12  15  25        0  2010   january     70
2  17/02/2010  14  13  35        1  2010  february     80
3  19/02/2010  11  10  22        1  2010  february     80

A: here is the stupid answer! I'm sure you can do smarter than that :) But that works, considering your tables are a list of dictionaries (you can easily convert your SQL tables in this format). I'm aware this is not a clean solution, but you asked for an easy one, probably that's the easiest to understand :)
months = {'january': "01",
          'february': "02",
          'march': "03",
          'april':"04",
          'may': "05",
          'june': "06",
          'july': "07",
          'august': "08",
          'september': "09",
          'october': "10",
          'november': "11",
          'december': "12"}

table1 = [{'index': '01/01/2010', 'A': 15, 'B': 20, 'C': 30},
          {'index': '15/01/2010', 'A': 12, 'B': 15, 'C': 25},
          {'index': '17/02/2010', 'A': 14, 'B': 13, 'C': 35},
          {'index': '19/02/2010', 'A': 11, 'B': 10, 'C': 22}]

table2 = [{'index': 0, 'year': 2010, 'month': 'january', 'price':70},
          {'index': 1, 'year': 2010, 'month': 'february', 'price':80}]

def joiner(table1, table2):
    for row in table2:
        row['tempDate'] = "{0}/{1}".format(months[row['month']], str(row['year']))
    for row in table1:
        row['tempDate'] = row['index'][3:]

    table3 = []
    for row1 in table1:
        row3 = row1.copy()
        for row2 in table2:
            if row2['tempDate'] == row1['tempDate']:
                row3['price'] = row2['price']
                break
        table3.append(row3)
    return(table3)

table3 = joiner(table1, table2)
print(table3)


text:
Q: How to add a delete function to angular HTTPClient? I've been working on angular that links to my back end API. I can retrieve my list of businesses from the back end and post reviews etc. But I am having trouble deleting records. I call the delete function in my by back end and nothing happens.

A: Try the code as below:
Delete.component.html
 <button class="btn btn-primary" (click)="Delete(product)"></button>

Delete.component.ts
 public Delete(del:products){
this.productservice.Delete(del.bookid)
.subscribe(
  res => {
    this.router.navigateByUrl('productview');

  });}

Delete.service.ts
Delete(id: any) {
return this.http.delete(this.rootUrl + '/Products/' + id);}


text:
Q: Change SQL Server 2005 Server Collation I need to set up an instance of SQL Server 2005 with SQL_Latin1_General_CP850_Bin as the server collation (the vendor did not take into accounting looking at DB collation for a bunch of things so stored procedures and temp tables default to the server level and the default collation will not work). During the install for SQL Server it did not give that as an option so I left it at default and finished installing it.
According to MSDN and Technet I should need to just run the following command:
setup.exe /q /ACTION=RebuildDatabase /INSTANCENAME=MSSQLSERVER /SAPWD="sa-pwd" /SQLSYSADMINACCOUNTS="BUILTIN\ADMINISTRATORS" /SqlCollation=SQL_Latin1_General_CP1_CI_AI

However, whenever I run the above command with my parameters I get the pop-up of the SQL Server installation wizard, accept the agreement, and then it gives me output stating how to use the command.
Any idea what I can do?

A: I think you're looking at instructions for SQL Server 2008.
See the article here for instructions for 2005.

A: If possible, I would uninstall and reinstall rather than trying to change it. Changing it without re-installing is not a simple process. To change from the default during install, just uncheck the "Hide advanced configuration options" check box on the Registration Information screen; doing that will give you a Collation Settings option about 4 screens later in the install.


text:
Q: Suppress headers and footers for complete chapter For my thesis, I need to include a chapter which can "stand alone", meaning it must be formatted in a way that allows the pages to be exported and be published separately.
This means, I need to get rid of the header and footer on these pages. I tried using
\thispagestyle{empty}

and it works as expected, but I don't want to set it manually for each page in my chapter.
Is there a way to extend this command to spread to all pages in the current section or is there another way to achieve my goal?

A: Use \pagestyle{empty} at the chapter start and switch back to \pagestyle{<normalstyle>} at the start of the next chapter. (<normalstyle> stands, e.g., for headings in the book class or for fancy if you use the fancyhdr package.)
In addition, it is necessary to set \thispagestyle{empty} at the chapter start in order to override the starting page's internal plain style.
\documentclass{book}

\usepackage{lipsum}

\begin{document}

\chapter{bla}

\lipsum[1-12]

\chapter{blubb}
\thispagestyle{empty}
\pagestyle{empty}

\lipsum[1-12]

\chapter{foo}
\pagestyle{headings}

\lipsum[1-12]

\end{document}


text:
Q: Implementing Gridview paging in asp.net 2008 i am using asp.net 2008 and i have implemented the in-build Gridview Paging.But it didn't work.then how can i implement Gridview Paging?i am using sql server 2005.

A: Set the GridView.AllowPaging property to true. Ensure that your data source supports the paging.


text:
Q: xwatermark in xepersian does not work together? \documentclass{book}
\usepackage{hyperref}
\usepackage[printwatermark]{xwatermark}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{tikz}
\usepackage{xepersian}
\newwatermark[allpages,color=cyan!30,angle=45,scale=0.5,xpos=0,ypos=0]{$Wellcome$}
\newwatermark[allpages,color=gray!30,angle=90,scale=0.5,xpos=-50,ypos=0]{$Wellcome$}
\begin{document}
\begin{persian}

نظریه اعداد از مباحث ریاضی است.

\end{persian}
\end{document}

A: The xwatermark package is not among the ones supported by bidi. You can use draftwatermark, instead. Perhaps it's not as customizable as xwatermark, but it works.
\documentclass{book}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{tikz}

\usepackage{draftwatermark}

\usepackage{hyperref}
\usepackage{xepersian}

\SetWatermarkText{\latin{Draft}}

\usepackage{lipsum}

\begin{document}
\begin{persian}

نظریه اعداد از مباحث ریاضی است.

\end{persian}
\end{document}


text:
Q: Express 4.0 Failed to Look up view in "/views" directory I am working with Express 4.0 and Express3-handlebars libraries for NodeJS.
Here is the configuration
app.set('views', path.join(__dirname, 'views/'));
app.engine('hbs', hbs({defaultLayout: 'main', extname: '.hbs'}));
app.set('view engine', 'hbs');

The contact.html is in the views directory
app.get('/', function(req, res) {
 res.render("contact");
});

This is the error i get :
Error: Failed to lookup view "contact" in views directory "/Users/max23/Desktop/Node/views/"

I spent over an hour trying to fix it to no avail. What is Wrong with the code?

A: As you are using hbs as your view system, you should use the .hbs extension for your view files. It fails to lookup the view because its an HTML, and its looking for contact.hbs
I personally dont have much experience with the handlebars library, but I suggest you change the contact.html extension to .hbs and try again

A: You're using Handlebars templating library, so your views should have .hbs extension, not .html. Change contact.html to contact.hbs and do that to all of your templates. Also, change this line
app.engine('hbs', hbs({defaultLayout: 'main.hbs', extname: '.hbs'}));

A: There is something wrong in the setting views path.
Try changing the line
app.set('views', path.join(__dirname, 'views/'));

by
app.set('views', path.join(__dirname, '/views'));

If not solved, show your folder structure.


text:
Q: php array formatting ( convert an array in to another array) I have an array in php like the following
Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 4
        )

    [1] => Array
        (
            [0] => 5
            [1] => 0
        )

    [2] => Array
        (
            [0] => 0
            [1] => 8
        )

     [3] => Array
        (
            [0] => 10
            [1] => 27
        )

)

How can I convert it into the following format.
array(0,4,5,0,0,8,10,27);

A: check
foreach($mainarray as $s){
    foreach ($s as $v){
        $str .=$v.',';
    }
}
echo $str;

A: This will work fine:
$array = array(array(1, 4), array(5, 0), array(0, 8), array(10, 27));

$result = array();

foreach ($array as $val)
{
  $result = array_merge($result, $val);
}

print_r($result);


text:
Q: If $f:A\to\mathbb{R}$ is integrable, then, for all $\delta>0$, the set $E_{\delta} = \{x\in A; w(f;x)\ge \delta\}$ has volume $0$
If $f:A\to\mathbb{R}$ is integrable, then, for all $\delta>0$, the set
  $E_{\delta} = \{x\in A; w(f;x)\ge \delta\}$ has volume $0$

Since this question involves the oscilation, I thought about using the theorem that says that if a function $f$ is integrable, then
$$\sum_{B\in P}w_B\ vol \ B <\epsilon$$
To prove that this set has measure $0$, we must cover it by an enumerable quantity of blocks such that the sum of their volumes is $<\epsilon$. I think it has something to do with the oscilation being as big as I want to, so the integral will have a problem in $E_{\delta}$. Could somebody help me?

A: Given a Riemann integrable function $f$ over a bounded rectangle $A$, for any $\epsilon > 0$ there exists, by the Riemann integrability criterion,  a partition $P$ such that upper and lower sums satisfy
$$U(P,f) - L(P,f) < \delta \epsilon.$$
The LHS can be decomposed into contributions from sub-rectangles that meet $E_\delta$ and  those that do not, namely
$$U(P,f) - L(P,f) = \sum_{R \cap E_\delta \neq \phi}(M_R - m_R) \text{vol}(R) + \sum_{R \cap E_\delta = \phi}(M_R - m_R) \text{vol}(R)$$
where $M_R = \sup_{x \in R} f(x)$ and $m_R = \inf_{x \in R} f(x).$
Since$M_R - m_R \geqslant 0$ we have
$$\sum_{R \cap E_\delta \neq \phi}(M_R - m_R) \text{vol}(R) \leqslant U(P,f) - L(P,f) < \delta \epsilon.$$
You should be able to show (try) that for each rectangle represented in the sum on the left there is a point $c \in R$ where $M_r - m_r \geqslant \omega(f;c) \geqslant \delta$.
Hence,
$$\delta \sum_{R \cap E_\delta \neq \phi} \text{vol}(R) < \delta \epsilon.$$
What can you conclude?


text:
Q: SELECT * FROM with different values in doctrine2 So I have little problem, I have code like this:
$query = $repository->createQueryBuilder('p')->
                    where('p.kalorie <= :kalorie AND p.cena <= :kwota AND p.deser = :sniadanie')->
                    setParameters(array(
                        'kalorie' => $kalorie,
                        'kwota' => $kwota,
                        'sniadanie' => 1))->getQuery();
$wynik = $query->getResult();

But I want to do something like:
if id = 1 then 'kwota' => $kwota + 20
if id = 2 then 'kwota' => $kwota + 55
if id = n then 'kwota' => $kwota + x

I mean something like:
SELECT * FROM Recipe WHERE (id = $id AND kwota < ($kwota + 20)) OR (id = $id2 AND kwota < ($kwota + 55)) OR (id = $idN AND kwota < ($kwota + x))

A: If it's about your SQL query, you can use the 'expr' class : http://doctrine-orm.readthedocs.org/en/latest/reference/query-builder.html#the-expr-class
If it's about php variable you can use a ternary operator :
$query = $repository->createQueryBuilder('p')->
                where('p.kalorie <= :kalorie AND p.cena <= :kwota AND p.deser = :sniadanie')->
                setParameters(array(
                    'kalorie' => $kalorie,
                    'kwota' => $id == 1? $kwota + 20 : ($id == 2 ? $kwota + 55 : $kwota + x),
                    'sniadanie' => 1))->getQuery();
$wynik = $query->getResult();


text:
Q: How to write an EF Core outer join that returns objects that contain subarrays? I am attempting to do a left outer join in Linq to Sql in order to include all roles for a given user:
from au
    in Db.AspNetApplicationUsers
where au.ApplicationId == applicationId
join u in Db.AspNetUsers
    on au.UserId equals u.Id
join r in Db.AspNetUserRoles
    on au.UserId equals r.UserId
    into ur
from userRole in ur.DefaultIfEmpty()
select new UserSummary
{
    Active = au.Active,
    Email = u.NormalizedEmail,
    Name = u.FullName,
    Id = u.Id,
    LastLogin = u.LastLogin,
    LastPasswordChange = u.PasswordLastChanged,
    LockedOut = u.LockoutEnabled,
    Roles = (from x in ur where userRole.RoleId != null select userRole.RoleId).ToArray()
}

but receive the following error:
System.InvalidOperationException: 'When called from 'VisitLambda', rewriting a node of type 'System.Linq.Expressions.ParameterExpression' must return a non-null value of the same type. Alternatively, override 'VisitLambda' and change it to not visit children of this type.'

I don't use outer joins in EF often, so I'm sure I'm just messing up the syntax.
Is it possible to return an array to a property in Linq to SQL?
If I add the where userRole.RoleId != null condition after from userRole in ur.DefaultIfEmpty() the code doesn't fail there anymore, but does during serialization.  I've disabled lazy loading so that's interesting.

A: As per CamiloTerevinto's suggestion, the following worked just fine:
from au
    in Db.AspNetApplicationUsers
where au.ApplicationId == applicationId
select new UserSummary
{
    Active = au.Active,
    Email = au.User.NormalizedEmail,
    Name = au.User.FullName,
    Id = au.User.Id,
    LastLogin = au.User.LastLogin,
    LastPasswordChange = au.User.PasswordLastChanged,
    LockedOut = au.User.LockoutEnabled,
    Roles = au.User.AspNetUserRoles.Where(r => r.RoleId != null).Select(r => r.RoleId).ToArray()
}


text:
Q: Phalcon MySQL UPDATE not working I am trying to create RESTful API and I am trying to update my MySQL database row through Phalcon via pure queries. But I run into the issue that the query is runned Phalcon status->success() returns true but when I look into the db values are the same as before.
I tried to change from SQL queries to using model->update() but has the same issue. Both values country_id and university_id are integers.
Any clue or workaround?
My POST handling function:
$app->post("/api/user/university/{id:[0-9]+}", function($id) use ($app){

    $university_id = $app->request->getPost("university_id");

    $country_id = universities::findFirstById($university_id)->country_id;

    $phpql = "UPDATE users
                SET university_id=:university_id:,
                    country_id=:country_id:
                WHERE
                    id=:user_id:";

    $status = $app->modelsManager->executeQuery($phpql, array(
        'user_id' => $id,
        'university_id' => $university_id,
        'country_id' => $country_id
    ));

    $response = new Response();

    if($status->success() == true){
        $response->setStatusCode(201, "Created");

        $response->setJsonContent(
            array(
                'status' => 0
            )
        );
    } else {

        $response->setStatusCode(409, "Conflict");

        $errors = array();
        foreach ($status->getMessages() as $message) {
            $errors[] = $message->getMessage();
        }

        $response->setJsonContent(
            array(
                'status'   => 'ERROR',
                'messages' => $errors
            )
        );
    }
    return $response;
});

A: Is university_id and country_id part of PK ? If yes then phalcon don't allow to change primiary keys. If you need such behaviour remove those columns from primiary key and use uniquness validator.


text:
Q: Need help in animating a Wheel on iphone I am doing an application in iphone that need to spin the Dart Wheel when I drag on it. The view will have a dart wheel image and when we drag the wheel it spins and slowly it stops.
Can any one help me in doing this animation.

A: You can use CoreAnimation for the rotation animation:
[UIView beginAnimations:nil context:nil];

[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:1.0f];
[view.layer setTransform:CGAffineTransformMakeRotation(M_PI)];

[UIView commitAnimations];

You will have to tweak the animation for your needs.


text:
Q: SSH X11 Forwarding XInputExtension missing When trying to open a GUI-program on a SSH-Session with X11-Forwarding (both client and server have X11Forwarding activated) I get this error:
Xlib:  extension "XInputExtension" missing on display ":4".
Application asked to unregister timer 0x8000003 which is not registered in this thread. Fix application.
VNC to this server is working correctly.
OS: Ubuntu Server
Thanks!

A: Try using
ssh -Y

to connect to the box as explained in this post


text:
Q: After deploy the webpart is not updating? We deployed a webpart but it keeps old html. And ı only changed a text in a div, but i cannot see the code changes in the site. Also, everything looks perfect . I mean visual studio shows the deployment is successful, we tried powershell to deploy, but it shows deployment succeed too, also in Central Admin it shows deployment  succeed too. On the other hand, we tried to Retract solution , Remove Solution and Add Solutuion but it is not working.
So, How can we do this?


text:
Q: Significance of the the Lagrange multipliers in statistical mechanics In classic thermodynamics one can derive the Maxwell Boltzmann statistics by solving a Lagrange multipliers equation. In this process a new parameter $\beta$ is introduced to take account of the total energy constraint,
$$L = \beta(E-\sum_i p_i \epsilon_i)+...$$
and it is later connected to $\frac{1}{k_B T}$ by inserting our knowledge about perfect gases. On a side note, about every book around seems to skip the passage with a frustrating "it can be shown that".
My problem is that, given similar Lagrange multipliers equation, I'm not sure whether one can in general relate $E$ and $\beta$: it is evident that $\beta$ has no physical significance by itself, and it's always bounded to some parameter in the constraints that it is multiplying.
For example, say that I have an array of cells that can be either occupied by 0, 1 or 2 dots. I have some constraints, one of which is the density of the dots $\rho$. The Lagrange multipliers equation has the form
$$L = \gamma(\rho-p_1-2p_2)+...$$
where $p_i$ is the probability of having a cell with $i$ dots. Is there some way to eliminate the $\gamma$ parameter in the final explicit formula for $p_1$, and use $\rho$ instead?

A: You probably realize that the Lagrange multiplier $\gamma$ that you introduced is nothing but the chemical potential, right?
Coming back to the Lagrange multiplier $\beta$, you have many ways to convince yourself that it is inversely proportional to the temperature. I will just focus on some of them:

*

*The first one consists of devising a simple way to measure experimentally $\beta$. The simplest model you can think of is evidently the ideal gas. You can work out easily that the pressure in this case will be inversely proportional to $\beta$. Now, it is logically very important to remember that the canonical ensemble characterized by the set $(\beta, N, V)$ is model independent in the same way that setting the temperature in usual thermodynamics has nothing to do with the system under study. Therefore, if you find it to be an inverse temperature in one case, it has to be it for every case you can imagine.

*The second one might actually be easier. The Lagrange multiplier method arises in a more global strategy called a statistical inference that has been much popularized by E.T. Jaynes in the second half of the last century. The idea is to start from Shannon's entropy and to maximize it with respect to some constraints that characterize the statistical ensemble.
If you replace the probability within Shannon's entropy by the canonical one, you get the expression for the entropy in the canonical ensemble. It reads:
$S(\beta,N,V) = -k_B \sum_{m} \frac{e^{-\beta \epsilon_m}}{Q(\beta, N,V)}\ln \left( \frac{e^{-\beta \epsilon_m}}{Q(\beta, N,V)} \right)$
where the sum runs over all the microstates $m$ and $Q$ is the canonical partition function.
Now you can compute what is the value of $\frac{\partial S}{\partial \epsilon}$ and you will find out that it is $k_B \beta$...that is $1/T$ if you trust thermodynamics.

*There is actually another easy way that consists in starting from the microcanonical ensemble and define the temperature from there. If you then subdivide a system into a big part and a small part, you will find directly the Boltzmann weight with the temperature of the big system for any microstate of the small part. Now, if you separately model this small system with your Lagrange multiplier you will find the same law but with $\beta$ instead of $1/k_B T$. Now, this is true whatever the system and if we moreover assume that the partition function is a monotonic function of $\beta$ (unless we are at a phase transition), we have to conclude that $\beta = 1/k_B T$.

A: Check this link
http://www.irc.leeds.ac.uk/~phy6pdo/teaching/thermo/hw/part5.pdf
The Langrange multiplier is simply d(function to be maximized)/d(constrain function), and it is related to physical quantities in this case. You can read through the document.


text:
Q: How to create new .clj files in Eclipse? I am very new to Clojure and just installed CounterClockWise and created my first Clojure project in Eclipse.
However I need to create another .clj file aside from the provided core clojure file.
How do I do this?

A: There is a New File command in Eclipse which can be used to create an empty file of any type. If you create a file and name it something.clj you have a new Clojure file.
The New File command can be accessed through the menus like this:
File menu > New > Other... > General > File
Or with a keyboard shortcut: Press Ctrl+N to open the New wizard, then type file in the search box to filter out the file creation command.
This technique is very useful generally to create various new things.

Maybe there also is a New Clojure File command (or something like that) in the list of things in the New wizard.

A: Not an Eclipse answer, but I sometimes have a similar issue with IDEA.  The simplest answer (on linux) is to just do touch src/myproj/newfile.clj or similar, to create an empty file with the desired name and location. The IDE can then easily open the (pre-existing) file for further editing.
A similar strategy is to open the file for the 1st time in another editor like vi, emacs, or whatever.

A related issue on IDEA is that it uses the namespace declaration (ns xyz ...) to label the editor tab, not the actual file name.  If you are renaming files you cannot actually see the new name easily until you change the ns declaration, which is very confusing.  In these cases, I will also fall back to using gvim to edit the ns declaration, or any other low-level or detailed edits.


text:
Q: Implementing a multi-level custom menu in Wagtail I'm working on enhancing a single-level menu that my site is currently using to great effect. The code is as follows (with irrelevant parts clipped out):
from wagtail.contrib.settings.models import BaseSetting
from modelcluster.models import ClusterableModel

class AbstractCustomMenuItem(models.Model):
    """
    Derive from this model to define one or more CustomMenus.
    """

    url = models.CharField('URL', max_length=200, blank=True,
        help_text='This must be either a fully qualified URL, e.g. https://www.google.com or a local absolute URL, '
                  'e.g. /admin/login'
    )
    page = models.ForeignKey('wagtailcore.Page', null=True, blank=True, on_delete=models.CASCADE, related_name='+',
        help_text='If a Page is selected, the URL field is ignored. The title of the selected Page will be displayed '
                  'if the Link Text field is blank.'
    )
    link_text = models.CharField('Link Text', max_length=50, blank=True)
    is_separator = models.BooleanField( 'Separator', default=False,
        help_text='Separators are used to visually distinguish different sections of a menu.'
    )

    panels = [
        MultiFieldPanel([
            FieldPanel('url', classname='col8 url'), FieldPanel('link_text', classname='col4 link-text'),
        ], classname='url-and-link-text'),
        # This is a bit gnarly, but it was the best way I could find to render the form in a pretty
        # way. I'm using MultiFieldPanel and classname='col8' entirely for formatting, rather than organization.
        MultiFieldPanel([PageChooserPanel('page')], classname='col8 page-chooser'),
        MultiFieldPanel([FieldPanel('is_separator', classname='separator')]),
    ]

    class Meta:
        abstract = True

@register_setting(order=1000)
class Settings(BaseSetting, ClusterableModel):

    ####### FIELD CODE #######
    ...

    ####### FORM CODE #######
    ...

    theme_and_menu_panels = [
        InlinePanel( 'header_menu_items', label='Header Menu Item',
            help_text='You can optionally add a Header Menu to your site, which will appear in the ribbon at the top '
                      'of the page.'
        ),
        InlinePanel('footer_menu_items', label='Footer Menu Item',
            help_text='You can optionally add a Footer Menu to your site, which will appear in the footer.'
        ),
    ]

    ...

    edit_handler = TabbedInterface(
        [
            ...
            ObjectList(theme_and_menu_panels, heading='Theme and Menus', classname='theme-and-menus'),
            ...
        ]
    )

class HeaderMenuItem(Orderable, AbstractCustomMenuItem):
    """
    This class provides the model for the Header Menu Items that can be added to a Site's settings.
    """

    settings = ParentalKey('www.Settings', related_name='header_menu_items', on_delete=models.CASCADE)

class FooterMenuItem(Orderable, AbstractCustomMenuItem):
    """
    This class provides the model for the Footer Menu Items that can be added to a Site's settings.
    """

    settings = ParentalKey('www.Settings', related_name='footer_menu_items', on_delete=models.CASCADE)

This gives my code the ability to assign separate, custom Header and Footer menus.
Now, however, I need to upgrade this code to allow the Header menu items to optionally have their own submenu beneath them. And I figured that I could do basically the same thing I did to create the MenuItems in the first place, and just parent them beneath the HeaderMenuItem class, rather than beneath Settings.
So I changed the HeaderMenuItem class, and added HeaderMenuDropdownItem:
class HeaderMenuItem(Orderable, ClusterableModel, AbstractCustomMenuItem):
    """
    This class provides the model for the Header Menu Items that can be added to a Site's settings.
    """

    settings = ParentalKey('www.Settings', related_name='header_menu_items', on_delete=models.CASCADE)

    panels = [
        MultiFieldPanel([
            FieldPanel('url', classname='col8 url'), FieldPanel('link_text', classname='col4 link-text'),
        ], classname='url-and-link-text'),
        # This is a bit gnarly, but it was the best way I could find to render the form in a pretty
        # way. I'm using MultiFieldPanel and classname='col8' entirely for formatting, rather than organization.
        MultiFieldPanel([PageChooserPanel('page')], classname='col8 page-chooser'),
        MultiFieldPanel([FieldPanel('is_separator', classname='separator')]),
        InlinePanel('dropdown_items', classname='dropdown-items'),
    ]

class HeaderMenuDropdownItem(Orderable, AbstractCustomMenuItem):
    """
    This class provides the model for the Header Menu Dropdown items.
    """

    header_menu_item = ParentalKey('www.HeaderMenuItem', related_name='dropdown_items', on_delete=models.CASCADE)

Unfortunately, I now get the following exception when I load the Wagtail admin page for editing the Settings class:
File "/.../django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/.../django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/.../django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/.../django/views/decorators/cache.py" in _cache_controlled
  31.             response = viewfunc(request, *args, **kw)

File "/.../wagtail/admin/urls/__init__.py" in wrapper
  102.             return view_func(request, *args, **kwargs)

File "/.../wagtail/admin/decorators.py" in decorated_view
  34.             return view_func(request, *args, **kwargs)

File "/.../wagtail/contrib/settings/views.py" in edit
  83.             instance=instance, form=form, request=request)

File "/.../wagtail/admin/edit_handlers.py" in bind_to_instance
  152.         new.on_instance_bound()

File "/.../wagtail/admin/edit_handlers.py" in on_instance_bound
  294.                                                    request=self.request))

File "/.../wagtail/admin/edit_handlers.py" in bind_to_instance
  152.         new.on_instance_bound()

File "/.../wagtail/admin/edit_handlers.py" in on_instance_bound
  294.                                                    request=self.request))

File "/.../wagtail/admin/edit_handlers.py" in bind_to_instance
  152.         new.on_instance_bound()

File "/.../wagtail/admin/edit_handlers.py" in on_instance_bound
  708.                                                     request=self.request))

File "/.../wagtail/admin/edit_handlers.py" in bind_to_instance
  152.         new.on_instance_bound()

File "/.../wagtail/admin/edit_handlers.py" in on_instance_bound
  294.                                                    request=self.request))

File "/.../wagtail/admin/edit_handlers.py" in bind_to_instance
  152.         new.on_instance_bound()

File "/.../wagtail/admin/edit_handlers.py" in on_instance_bound
  693.         self.formset = self.form.formsets[self.relation_name]

Exception Type: AttributeError at /admin/settings/www/settings/3/
Exception Value: 'HeaderMenuItemForm' object has no attribute 'formsets'

What am I doing wrong? Can a ParentalKey simply not be nested inside another ParentalKey? If not, how could I implement this multi-level menu? Maybe I'm going about this all wrong from the start?

A: Have you looked into wagtailmenus?  It might save you some development time and effort.


text:
Q: On dual nature of light? It is said that light exhibits dual nature, in some instances as particles or photons and other instances as electromagnetic waves. How to detect which nature is light exhibiting and why only one nature exhibited at a time, why can't the be photons moving in wave-like motion? The Michelson-Morley experiment tries to refute the existence of ether but all waves require a medium to propagate?

A:
How to detect which nature is light exhibiting and why only one nature exhibited at a time,

We perform an experiment and make some observations. We then see whether those observations show wave-like or particle-like behavior of the light involved.
For example, when we see interference or diffraction effects, we call those wave-like behaviors. When we see that only discrete amounts of energy can be absorbed from or emitted into the electomagnetic field we call that a particle-like behavior.
But really, light doesn't sometimes behave like a particle and sometimes behave like a wave. It always behaves like light. It's only that some of the behaviors of light are analogous to the behavior of particles in classical physics and others are analogous to the behavior of waves in classical physics.

why can't the be photons moving in wave-like motion?

Because we observe behavior (for example diffraction) that isn't consistent with this model.

all waves require a medium to propagate?

This just isn't true. Many of the waves that pre-1900 physicists were familiar with (for example, sound) propagated through physical media.
But that doesn't mean it's not possible for some other type of wave (light) to propagate without a medium.


text:
Q: How to make controller to insert time on click and remove time on another click? This is my controller where i want to know what is correct.
public function complete($id)
{
    $task = Task::find($id);
    if($task->done_at = '' or $task->done_at = null) {
        $task->done_at = date( 'Y-m-d H:i:s', strtotime( 'now' ) );

        $task->save();
    } elseif ($task->done_at !== null) {
        $task->done_at = null;

        $task->save();
    }

    return redirect()->route('tasks.index')->withSuccess('Done');
}

and this is my index page where there is form for clicking
<form action="{{ route('tasks.complete', $task->id) }}" method="post">
                        @csrf
                        <button type="submit" name="submit">

</button>
                    </form>

A: You can check with that using empty() function. and do not repeat yourself you can also use save function in last after if else condition.
Thanks :)


text:
Q: How to write a function in R given a function

I'm not sure how to write this in R, I wrote it as:

But I'm getting this error:

A: Maybe you are looking for this:
#Function
f <-function(x) {4*x*exp(-2*x)}
#Integral
integrate(f,lower = 0,upper = Inf)


text:
Q: Integrating html, css, and python I am building a web application that contains calculators for various industries. I am using html and css for the layout(color, size, etc). However, the core funtionality like arithmetic operations will be done using pure python programming and not javascript. So I will have html, css, and python files. Question is - how can I link my python file to html?

A: You can't use python to run in the browser on the client's machine in the same way as JS, just because browsers are built to execute JS and not Python. However if all you want to do in the python is backend work, that is definitely possible.
I would suggest looking at Flask a popular python web framework that is quite easy to get started with.

A: I could think of two easy ways right away, either stick to a solid framework, like django. Or you can make python scripts that manipulate .js files since text manipulation is easy and fun in python. But there are many more possibilities, like Flask and more.

A: You can use Brython

Brython is designed to replace Javascript as the scripting language for the Web. As such, it is a Python 3 implementation (you can take it for a test drive through a web console), adapted to the HTML5 environment, that is to say with an interface to the DOM objects and events.

A: If the only function you want from the python(and the server side in general) is the calculation, I would suggest taking a serverless structure. It's simpler, less low-level work, easier to upgrade and scalable.
An example of build one with python is with Zappa (AWS lambda)

A: I know I'm two months late, but if you're still set to using Python with your HTML/CSS website, it is completely doable.
However, as the previous answer mentioned, if it is only for calculations and light functionality, you're better off using javascript.
Please refer to this link to get an idea on how to integrate python using Flask with your HTML website.

A: I would recommend you to use flask as a backend as big platforms such as youtube use Django(which is a python framework). And I am sure that js is powerful that it can handle arithmetic operations you can check the webs out for that. But if you want to use flask it is very easy here is the basic structure

from flask import Flask, render_template
import pyautogui
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

app.run()

Keep in mind that python is limited to things and it would be hard to publish a website with python as backend


text:
Q: Google Geocoder service is unavaliable (Coordinates to address) I have to get an address by coordinates, but it doesnt work and outputs "Couldnt get address":
public String GetAddress(String lat, String lon)
        {
            Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
            String ret = "";
            try {
                List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(lat), Double.parseDouble(lon), 1);
                if(addresses != null) {
                    Address returnedAddress = addresses.get(0);
                    StringBuilder strReturnedAddress = new StringBuilder("");
                    for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                        strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                    }
                    ret = strReturnedAddress.toString();
                    ret=ret.substring(0, ret.length() - 1);
                }
                else{
                    ret = "Unknown Address";
                }
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                ret = "Couldn't get Address";
            }
            return ret;
        }

LogCat:
09-27 23:47:49.837: W/System.err(1862): java.io.IOException: Service not Available
09-27 23:47:49.847: W/System.err(1862):     at android.location.Geocoder.getFromLocation(Geocoder.java:136)
09-27 23:47:49.847: W/System.err(1862):     at com.example.free.Add.GetAddress(Add.java:634)
09-27 23:47:49.857: W/System.err(1862):     at com.example.free.Add$LoadAddress.doInBackground(Add.java:608)
09-27 23:47:49.857: W/System.err(1862):     at com.example.free.Add$LoadAddress.doInBackground(Add.java:1)
09-27 23:47:49.857: W/System.err(1862):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-27 23:47:49.857: W/System.err(1862):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-27 23:47:49.857: W/System.err(1862):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-27 23:47:49.857: W/System.err(1862):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-27 23:47:49.857: W/System.err(1862):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-27 23:47:49.857: W/System.err(1862):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-27 23:47:49.857: W/System.err(1862):     at java.lang.Thread.run(Thread.java:856)

A: The common answer to this problem is that you have to restart your device.
Surely you cannot tell your users to restart device in order for your app to function, so my solution was to use a HTTP fallback, here is the AsyncTask I use in my code.
You will have to modify it for your situation, as I lookup address from position and not the other way around.
    private class GetAddressPositionTask extends
        AsyncTask<String, Integer, LatLng> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected LatLng doInBackground(String... plookupString) {

        String lookupString = plookupString[0];
        final String lookupStringUriencoded = Uri.encode(lookupString);
        LatLng position = null;

        // best effort zoom
        try {
            if (geocoder != null) {
                List<Address> addresses = geocoder.getFromLocationName(
                        lookupString, 1);
                if (addresses != null && !addresses.isEmpty()) {
                    Address first_address = addresses.get(0);
                    position = new LatLng(first_address.getLatitude(),
                            first_address.getLongitude());
                }
            } else {
                Log.e(TAG, "geocoder was null, is the module loaded? "
                        + isLoaded);
            }

        } catch (IOException e) {
            Log.e(TAG, "geocoder failed, moving on to HTTP");
        }
        // try HTTP lookup to the maps API
        if (position == null) {
            HttpGet httpGet = new HttpGet(
                    "http://maps.google.com/maps/api/geocode/json?address="
                            + lookupStringUriencoded + "&sensor=true");
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            StringBuilder stringBuilder = new StringBuilder();

            try {
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                int b;
                while ((b = stream.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {
            } catch (IOException e) {
            }

            JSONObject jsonObject = new JSONObject();
            try {
                // Log.d("MAPSAPI", stringBuilder.toString());

                jsonObject = new JSONObject(stringBuilder.toString());
                if (jsonObject.getString("status").equals("OK")) {
                    jsonObject = jsonObject.getJSONArray("results")
                            .getJSONObject(0);
                    jsonObject = jsonObject.getJSONObject("geometry");
                    jsonObject = jsonObject.getJSONObject("location");
                    String lat = jsonObject.getString("lat");
                    String lng = jsonObject.getString("lng");

                    // Log.d("MAPSAPI", "latlng " + lat + ", "
                    // + lng);

                    position = new LatLng(Double.valueOf(lat),
                            Double.valueOf(lng));
                }

            } catch (JSONException e) {
                Log.e(TAG, e.getMessage(), e);
            }

        }
        return position;
    }

    @Override
    protected void onPostExecute(LatLng result) {
        Log.i("GEOCODE", result.toString());
        super.onPostExecute(result);
    }

};


text:
Q: HTML / CSS Transparent Image Keeps showing background I am trying to insert a logo into the header of my webpage, and although it is transparent when I save it locally, it still shows a grid when the URL is inserted into my stylesheet. How can I get rid of that ugly grid in the logo?
header {
      background-color: #5C9632;
      background-image: url(https://library.kissclipart.com/20190218/sgq/kissclipart-cartoon-snake-logo-clipart-snakes-logo-9150a5362e4635c4.png);
      background-repeat: no-repeat;
      background-size: 100px 100px;
}

A: DO:
You just need to download the image from https://www.kissclipart.com/ using the Free Download button.
DON'T
Using right-click, then Save Image, it will get you the grid photo.
Your CSS code is fine.

A: Here is image without background ;)


text:
Q: Animated UIPickerView not rotating in landscape mode I have a UIPickerView that animates up and down in a UITableViewController. I adapted an example from apple (DateCell). The UIPickerView is created programmatically, no nib files.
In Portrait mode everything looks nice. When I rotate the simulator (I not testing on the device), the UITableView rotates well, but the picker remains were it was. I read tons of threads about that topic and many developers seem to have problems with pickers behaving weird in landscape mode but at least their pickers rotate. I made a subclass of UIPickerView as described in this link: http://www.llamagraphics.com/developer/using-uidatepicker-landscape-mode, but it didn't help for the rotation issue.
I tried to rotate the picker with a transform but it looked very weird, like broken.
I'm suspecting that the problem is that I'm using the picker inside of a UITableViewController, and so I add it as a subview of self.view.window. If I try to add the picker as a subview of self.view, only a white frame (without any picker) appears.
Any suggestions?
The initialization code in the UITableViewController subclass:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.pickerView.superview == nil)
    {
        //Initialization code
        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
        CGRect initFrame = orientation == UIInterfaceOrientationPortrait ? CGRectMake(0, 0, 320, 200) : CGRectMake(0, 0, 480, 160);

        self.pickerView = [[RotatingUIPickerView alloc] initWithFrame:initFrame];
        [self.pickerView setDelegate:self];
        [self.pickerView setShowsSelectionIndicator:YES];
        [self.pickerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];

        [self.view.window addSubview:self.pickerView];

        // compute the start frame
        CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
        CGSize pickerSize = [self.pickerView sizeThatFits:CGSizeZero];
        CGRect startRect = CGRectMake(0.0,
                                      screenRect.origin.y + screenRect.size.height,
                                      pickerSize.width, pickerSize.height);

        [self.pickerView setFrame:startRect];

        // compute the end frame
        CGRect pickerRect = CGRectMake(0.0,
                                       screenRect.origin.y + screenRect.size.height - pickerSize.height,
                                       pickerSize.width,
                                       pickerSize.height);

        // start the slide up animation
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];

        // we need to perform some post operations after the animation is complete
        [UIView setAnimationDelegate:self];

        [self.pickerView setFrame:pickerRect];

        [UIView commitAnimations];
    }
}

Implementation of UIPicker subclass as described on the link above:
- (id)initWithFrame:(CGRect)frame
{
    if (self == [super initWithFrame:frame])
    {
        for (UIView * subview in self.subviews)
        {
            [subview setFrame:self.bounds];
        }
    }
    return self;
}

- (id) initWithCoder:(NSCoder *)aDecoder
{
    if (self == [super initWithCoder: aDecoder])
    {
        for (UIView * subview in self.subviews)
        {
            [subview setFrame:self.bounds];
        }
    }
    return self;
}

A: By executing:
 [self.view.window addSubview:self.pickerView];

you are adding pickerView as a subview of your UIWindow. I don't know how the main UIWindow can be rotated, if it can be.
When you are adding pickerView to the view
 [self.view addSubview:self.pickerView];

you get problems due to the view being a UITableView.
What I suggest is adding pickerView to some intermediate UIView, added as subview to UIWindow and to which you add the UITableView. This intermediate UIView would also have a UIViewController associated to it so that shouldAutorotateToInterfaceOrientation can return the proper value to have auto rotation working.


text:
Q: When send individual parameter, action result cannot be hit. when send object, it gets hit I have one application consist of ASP.Net WebAPI 2 and Web project for which angularJS is used. The Problem is when i call API with parameters, it does not hit. and when send object, it gets hit.
anjularJS Code:
with parameters
$http({
    cache: false
        , method: 'POST'
        , url: 'http://localhost:51341/api/User/UpdateUser'
        , data: { userId: $scope.UsersId, fullName: $scope.name }
}).success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});

Webapi Code
[HttpPost]
public ApiResponse UpdateUser(int userId, string fullName)
{
    return this.Response(true, MessageTypes.Success, "User has been saved successfully.");
}

with object
var model = { userId: $scope.UsersId, fullName: $scope.name };
$http({
    cache: false
        , method: 'POST'
        , url: 'http://localhost:51341/api/User/UpdateUser'
        , data: model
}).success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});

webapi code
[HttpPost]
public ApiResponse UpdateUser(User model)
{
    return this.Response(true, MessageTypes.Success, "User has been saved successfully.");
}

User class
public class User
{
    public int UserId { get; set; }
    public string FullName { get; set; }
    public int Age { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

when call made with parameters, api DOES NOT get hit. but When call made with Object, api GETS hit.
What I missed when call made with parameters ? Help will be truly appreciated.

A: From WebApi docs:

At most one parameter is allowed to read from the message body. So
  this will not work:
// Caution: Will not work!
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

For other info I suggest to read:
https://damienbod.wordpress.com/2014/08/22/web-api-2-exploring-parameter-binding/
https://stackoverflow.com/a/24629106/3316654