text:
Q: SVG3d: Controlling the rotation of a path with an easing function I'm trying to emulate a 3d rotation among the y-axis for some paths I have in an SVG.
I've found the library SVG3D https://code.google.com/p/svg3d/
and I've given it a try.
The problem is that you can only control the ticking interval duration and the increment (in radians) of each "tick" (there's a setInterval timing function that calls the transform() function which executes the rotation).
There's a toggleRotation function, that works like a play-pause command, but it doesn't give you any control of the timing and rotation of the path.
I have the following example code for my path:
<g id="anim_container"
    z:xOrigin="0"
    z:yOrigin="0"
    z:zRatio="1000"
    z:sortAlgo="none"
    z:rotationTime="60"
    onload="init(this);">
    <path
    d="M 460.2203,600.93365 248.25964,263.59573 C 248.63437,272.77915 249.10289,281.86852 249.66521,290.86388 250.03994,298.54799 250.32105,306.70032 250.50856,315.32088 250.88328,323.75461 251.07069,331.251 251.07079,337.81007 L 251.07079,600.93365 203.28125,600.93365 203.28125,204.84271 265.68876,204.84271 479.89835,544.42955 C 479.33579,535.24653 478.77356,526.06345 478.21166,516.88029 477.83651,509.00916 477.4617,500.48202 477.0872,491.29883 476.71206,481.92845 476.52465,473.02649 476.52497,464.59291 L 476.52497,204.84271 524.87674,204.84271 524.87674,600.93365 460.2203,600.93365"
    id="path_n">
        <z:translation x="364.0790100097656" y="402.88818359375"/>
        <z:rotation incRotY="0.5"/>
        <z:translation x="-364.0790100097656" y="-402.88818359375"/>
    </path>
</g>

So, how could you control the spinning and speed of the objects? Is it possible to include an easing function to control the speed of each rotation?

A: Well I have found a workaround for this issue.
It requires three steps

*

*First, it needs you to alter the Svg3d library code.
Open the file "svg3d_parsing.js" and comment the following line within the "init" function
function init(g) {
    .......
    //clockRotation = window.setInterval("transform()", rotationTime);
    .......
}

What I'm doing here is avoiding the use of the "ticking" function included in the library, so we will be able to call transform() (the function that performs the rotation, which is available as a global function) with our own ticking function (and only when we need to).
Then, in the same file locate the "getAttrValue" function and comment the line shown here:
function getAttrValue(......
.....
if (incAttValue) {
   var incValue = parseFloat(incAttValue);
   //node.setAttribute(tag, returnedValue + incValue);
}
return returnedValue;

This is the core of the control of the rotation. When you execute init(this) and on every call to transform(), attributes rotX and/or rotY (depending if you set incRotX, incRotY, or both) are included to the <z:rotation incRotY="0.5"/> tag, resulting in  <z:rotation incRotY="0.5" rotY="0.5"/> (for this example). The function transform() then reads these values, and calculates the transform matrices using them as the angles of rotation for each axis (in radians).
It happens, as well, that on each call to transform(), there's an increment of rotX and/or rotY by incRotX and/or incRotY, respectively. So, by commenting this line (and following the next steps) we will be able to control the angle of rotation as we wish.

*Second, edit the <z:rotation> tag, by including an ID (I use one of the functions in the svg3d library file "dom_utils.js", but for the purpose of this solution we will just set an ID for easy accesing) --- (You could even remove the incRotY attribute)
So, we get
<z:rotation id="rot" incRotY="0.5"/>

*Last, get a tweening and ticking function to set the rotY (and/or rotX depending on your case) to the z:rotation tag. This will be the angle of rotation that the function transform will apply to the path.
For this example I use easeljs (for ticking) and tweenjs (for tweening) from createjs suite: http://www.createjs.com/
Append the following code to the file before the svg closing tag.
<!--Attaching easeljs and tweenjs libraries-->
<script
xlink:href="http://code.createjs.com/easeljs-0.7.0.min.js"
id="easeljs" />
<script
xlink:href="http://code.createjs.com/tweenjs-0.5.0.min.js"
id="tweenjs" />
<script id="rotate">
   var v = document.getElementById("rot");         //Get z:rotation tag element
   var numberSpins = 3.5;                          //Set number of spins
   //Setting object with variables to tween.
   //deg will be the current angle value, finalDeg the final value (both in degrees)
   degrees = {deg: 0, finalDeg: numberSpins*360};
   createjs.Tween.get( degrees, { loop: false } )  //apply tweening of degrees object
   .wait(1800)
   .to( { deg: degrees.finalDeg }, 3000, createjs.Ease.quadInOut )  //Here we set the variable to tween within the object (deg), the final value (finalDeg), the duration and the easing function
   .call(function(){createjs.Ticker.removeEventListener('tick',update)}); //Once we finish spinning, remove listener
   //Then set the update function to be called for each tick
   var update = function(){
      var rad = degrees.deg*Math.PI/180;            //Transform the current angle to radians
      v.setAttribute("rotY",rad);                   //Setting the rotation attribute to be read by transform()
      transform();                                  //Apply rotation with the values we've set in z:rotation tag element
   }
   createjs.Ticker.setFPS( 60 );                   //Just create a ticker. See TweenJs Documentation
   createjs.Ticker.addEventListener( 'tick', update ); //For each tick execute the update function
</script>

And now we can control the number of spins, the duration of the animation and incorporate an easing function.
Probably there must be a tidier solution.
I've posted the whole solution in http://pastebin.com/fjPV4Gb4
And remember: Don't use the toggleTransform function!

Comment: You could uncomment the clockRotation timing function that calls "transform()" function in the "init" function ("svg3d_parsing.js"), and remove the call to transform() in the "update" function, resulting in the same functionality. But, the calls to transform() would result unlimited.


text:
Q: Getting single variable from multiple NetCDF files using loop in R If I have n files named nc.data_1, nc.data_2... nc.data_n, how can I get the same variable from all of the files and store them into a single array in R? (i.e. (a) getting the time then (b) getting precipitation data with dimensions: [lon, lat, time] = [144, 91, 24] from n files respectively). The code below is what I've done so far.
Data path: https://www.dropbox.com/sh/m8u3xwm5za7m7mc/AACHq2AjeZaxHm1sEhaOJ_g2a/2011?dl=0
## Call library functions for future plot
library(abind)
library(fields)
library(maps)
library(ncdf4)

## create an empty list that saves the incoming files
nc.data<-list()
list.filenames<-list.files(pattern = ".nc")

## Read in all data files using a loop
for(i in 1:length(list.filenames)){
nc.data[[i]]<-nc_open(list.filenames[[i]])
}

## Getting lat and lon from a single file since they're the same for all files
lat_2x25 <- ncvar_get(nc.data[[1]], 'lat')
lon_2x25 <- ncvar_get(nc.data[[1]], 'lon')

For the time variable, I can't use the same method as the lat and lon since the time in each file are different(each file store the data of one day)

A: Not an R solution, but if in linux you could just use CDO first (I'm assuming you wrote the filename back to front as the extension ".nc" usually goes at the end):
cdo merge data_*.nc merge_file.nc
cdo selvar,variable_name merge_file.nc variable.nc

then you can simply open and read the latter in R.

redpajama_set_name: RedPajamaStackExchange


text:
Q: php, sql, избавиться от цикла Здравствуйте. Не очень давно начал изучать php и столкнулся с некоторой проблемой.
Дано:
    таблица с логами покупок в магазине (User, Cost, Date)
    таблица с пользователями (User, Money)
Первая таблица не имеет уникальных значений, поэтому имена пользователей повторяются.
Нужно из первой таблицы: получить имена всех пользователей, а также подсчитать потраченную сумму в определенный период
И добавить полученную сумму к балансу пользователю из второй таблицы. После чего эти записи удаляются.
С помощью php цикла я еще могу все это провернуть примерно так:
$query = $db->query(" SELECT `user`  FROM `table1` WHERE `date` >= $date GROUP BY `user` ");

if($query->rowCount() > 0) {
    while($res = $query->fetch(PDO::FETCH_BOTH)) {
        $db->query(" UPDATE `table2` SET `money` = `money` + (SELECT SUM(cost) FROM `table1` WHERE `user` = '$res['user']' AND `date` >= $date) WHERE `name` = '$res['user']' ");
    }
}

Но понимаю что это не лучший вариант.
Как лучше это сделать?

A: UPDATE `table2` T
  JOIN (SELECT user, SUM(cost) as M
          FROM `table1`
         WHERE `date` >= $date
         GROUP BY user
       ) A
    ON T.user=A.user
   SET T.`money` = T.`money` + A.M


text:
Q: ICU support in a 32-bit build of Qt5 with the VS2012 compiler causes Qt5 build failure; Webkit is also therefore unbuildable I have run into another in a long stream of obstacles attempting to build Qt5 with the VS2012 compiler.
When ICU is enabled ("-icu" on the configure command line, along with a proper 32-bit build of ICU in VS2012 and proper inclusion of all ICU paths (header, .lib, and .dll)), Line 688 of qtbase\src\corelib\codecs\qtextcodec.cpp returns a NULL codec (ICU fails to return a codec) when asked for a codec whose name is "US-ASCII".
Specifically:
QTextCodec* QTextCodec::codecForLocale()
{
    QCoreGlobalData *globalData = QCoreGlobalData::instance();
    if (!globalData)
        return 0;

    QTextCodec *codec = globalData->codecForLocale.loadAcquire();
    if (!codec) {
#ifdef QT_USE_ICU

        // THIS BLOCK IS REACHED WHEN ICU IS ENABLED

        textCodecsMutex()->lock();

        // ***
        // The following codec returned is NULL!!!
        //   (Internally, it sets the codec name to "US-ASCII",
        //    and fails to find a codec with this name)
        // ***
        codec = QIcuCodec::defaultCodecUnlocked();

        textCodecsMutex()->unlock();
#else
        // setupLocaleMapper locks as necessary
        codec = setupLocaleMapper();
#endif
    }

    return codec;
}

Later, the NULL codec variable noted above is dereferenced (in the code for the "lrelease.exe" utility), and when the "lrelease.exe" utility runs as part of the Qt5 build process and attempts to perform a translation, it crashes due to this NULL dereference and causes the Qt build to stop with an error.
Stepping into the above QIcuCodec::defaultCodecUnlocked() function reveals that the codec name is being set to US-ASCII, and that a codec with this name is not found.
It therefore seems to be impossible to include ICU support with a VS2012-compiler 32-bit build of Qt5.
Worse, because Webkit depends on ICU within Qt5, this means that Webkit cannot be built, either.
Can someone please tell me if this is reasonably likely to be a bug with Qt5 with VS2012, or is there something I am not setting up properly in my build environment?
Of use, also, would be knowing whether anybody has been able to build Qt5 with the VS2012 compiler with ICU support enabled.
I have also posted a comment in a relevant, ongoing thread in the Qt forum.

A: Qt uses UTF-8 as the default. Assuming ICU 51.2, rebuild ICU with U_CHARSET_IS_UTF8 defined to 1. Either: #define it in source\common\unicode\platform.h (see comment starting about around line 523), or you could also add it to the build in all ICU projects in allinone.sln (e.g. right click, select properties, select Configuration Properties>C/C++>Preprocessor and add it to Preprocessor Definitions).


text:
Q: When is rng.gen() not true? I am using the number generator  from std:rand as a template for a generic random number generator. The problem is sometimes, the function was silently failing so I added a fail clause that simply prints "Not true!"
use std::rand;
use std::rand::Rng;

fn main() {
    let mut rng = rand::task_rng();
    if rng.gen() { // bool
        println!("f64: {}", rng.gen::<f64>());
    } else {
        println!("Not true!");
    }
}

Sometimes running the executable prints a random number and sometimes it prints "Not true!". What could possibly be causing rng.gen() to evaluate to false?
Edit:grammar

A: From the documentation of the Rng::gen method:
// Return a random value of a Rand type.
fn gen<T: Rand>(&mut self) -> T

When T is of type bool, then it will randomly generate either true or false. If it always generated a true value, it wouldn't be usefully random.
Generally, if rng.gen() { ... } else { ... } is a useful idiom to say, "Randomly choose one of two code paths."

A: Let's look at the signatures.
fn gen<T: Rand>(&mut self) -> T
And Rand? "A type that can be randomly generated using an Rng.", which includes among its implementors bool.
In simple terms, gen() can return a value of any type that implements Rand, based on the types that it can infer. You can get a random number, a random char, even a random bool.
An if clause must be of type bool. Therefore the type inferrer determines that the T for that particular gen() invocation is bool. You could also write rng.gen::<bool>() to the same effect.
Thus, which branch of your if/else structure will be evaluated is random.


text:
Q: javax.validation.BootstrapConfiguration.getClockProviderClassName()Ljava/lang/String No such method I am getting below exception while executing springboot application:
Caused by: java.lang.NoSuchMethodError: 'javax.validation.BootstrapConfiguration.getClockProviderClassName()Ljava/lang/String;
at org.hibernate.validator.internal.xml.ValidationBootstrapParameters.<init>(ValidationBootstrapParameters.java:63) ~[hibernate-validator-6.0.7.Final.jar!/:6.0.7.Final]'

I included validation-api as a dependency with latest version & also made sure no other version is coming (not using hibernate validator as well) Still it is failing. Please suggest any solution.

A: Check the lib folder to differing version of validation-api -- for example

*

*jakarta.validation-api-2.0.2.jar

*validation-api-1.1.0.Final.jar

And try to see if you can remove validation-api-1.1.0.Final.jar


text:
Q: $Profile.Name in Formula field not updating the checkbox We have a Custom Field (Formula) on User object which has a simple formula to set the checkbox True if the user's profile is System Administrator.

But here i have a user with different profile with the Super User checkbox set to true.
I looked at all other users as well where the checkbox is set to true even though they different profiles.
I found this Similar Issue but our default language is English.
Does anyone have any idea on how to get this working or get current user's profile in a formula field if this doesn't work?

A: $Profile is the global variable for the profile of the user that is currently logged in. It allows you to to customize formulas to the profile of the user looking at the field. See: Salesforce global variable documentation for more information. You see the formula return true on every user record because you are a system administrator, and therefore your profile name is used for the comparison.
What you would want is the profile name of the user record. This would be Profile.Name (without the dollar sign).

A: I just used Profile.Name = "System Administrator" instead of $profile. it works fine for me


text:
Q: nginx: How to mass permanent redirect from a given list? I have about 400 url that will change in the new version and for some reasons I can't repeat the same type of url structure in the new website.
My question is, can I give a url list to nginx (yeah I know the 400 ones), and tell him simply that each one of them are going to another url?
Like I said the url structure will be different so I can't use any type of pattern.
Thanks in advance.

A: The map directive
If you have a very long list of entries, it could be a good idea to keep them outside of the nginx configuration file - using a .map file.
First you need to add a map directive inside your nginx.conf file - keep in mind that your .conf file could be named in another way (e.g. default.conf).
nginx.conf
map_hash_bucket_size 256; # see http://nginx.org/en/docs/hash.html

map $request_uri $new_uri {
    include /etc/nginx/oldnew.map; # or any file readable by nginx
}

server {
    listen       80;
    server_name  your_server_name;

    if ($new_uri) {
       return 301 $new_uri;
    }

    ...
}

Then, the map directive will map any $request_uri to the matching $new_uri found inside the oldnew.map file.
/etc/nginx/oldnew.map:
/my-old-url /my-new-url;
/old.html /new.html;

Be sure to end each line with a ";" char!

Additional configuration
If you need to redirect all URLs to another host, you can use:
return 301 http://example.org$new_uri;

Or, if you also need to redirect to another port, you can use:
return 301 http://example.org:8080$new_uri;

A: Probably the easiest way to do that is to wrap map directive around your list. The configuration in this case would look like this:
map $request_uri $new_uri {
    default "";
    /old/page1.html /new/page1.html;
    /old/page2.html /new/page2.html;
    ...
}

server {
    ...

    if ($new_uri != "") {
        rewrite ^(.*)$ $new_uri permanent;
    }

    ...
}


text:
Q: Breaking out of the Data Binding hierarchy I'm kind of new to WPF, and I'm trying to do some specialized data binding.  Specifically, I have a DataGrid that is bound to a collection of objects, but then I want the headers of the columns to be bound to a separate object. How do you do this?
I have a couple of classes defined like so:
public class CurrencyManager : INotifyPropertyChanged
    {
        private string primaryCurrencyName;

        private List<OtherCurrency> otherCurrencies;

         //I left out the Properties that expose the above 2 fields- they are the standard
        //I also left out the implementation of INotifyPropertyChanged for brevity
}

public class OtherCurrency : INotifyPropertyChanged
    {
        private string name;
        private double baseCurAmt;
        private double thisCurAmt;

        //I left out the Properties that expose the above 3 fields- they are the standard
        //I also left out the implementation of INotifyPropertyChanged for brevity
}

Then the important section of XAML is as follows.  Assume that I've already bound the Page to a specific object of type CurrencyManager.  Note how binding attached to the header of the 2nd DataGridTextColumn is incorrect, and needs to somehow get access to the CurrencyManager object's property PrimaryCurrencyName.  That is, the header of the column has the name "PrimaryCurrencyName", and the data in the column is still bound to the property ThisCurAmt for each element of the OtherCurrencies List.
<DataGrid ItemsSource="{Binding Path=OtherCurrencies}"  AutoGenerateColumns="False" RowHeaderWidth="0">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Currency Name" Binding="{Binding Path=Name}"/>
                        <DataGridTextColumn Binding="{Binding Path=BaseCurAmt}">
                            <DataGridTextColumn.Header>
                                <Binding Path="PrimaryCurrencyName"/>
                            </DataGridTextColumn.Header>
                        </DataGridTextColumn>
                        <DataGridTextColumn Header="Amt in this Currency" Binding="{Binding Path=ThisCurAmt}"/>
                    </DataGrid.Columns>

                </DataGrid>

How do I do this?  Thanks!

A: The problem is, that the DataGridTextColumn is not a part of the visual tree.
Normaly, this can be be worked around using DataGridTemplateColumn but in your case, I think this will not help.
Probably this article from Jaime Rodriguez
will lead you to a solution (I have only looked fast at it, but It looks appropriate).

A: Try this one:
<DataGridTextColumn Binding="{Binding Path=BaseCurAmt}">
    <DataGridTextColumn.Header>
        <TextBlock>
            <TextBlock.Text>
                <Binding Path="DataContext.PrimaryCurrencyName"
                        RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}"/>
            </TextBlock.Text>
        </TextBlock>
    </DataGridTextColumn.Header>
</DataGridTextColumn>

Basically, this one uses a RelativeSource to find the DataGrid's DataContext (which I'm assuming is a CurrencyManager) and display its PrimaryCurrencyName property.  Hope this helps.


text:
Q: Linux Restarting the network from a pthread of a C program We have an application that creates several threads using the pthread library.  As we want only the main process to handle certain signals all the pthreads have SIGTERM, SIGINT and SIGHUP blocked.  In one of our pthreads we restart the network using
system("/etc/init.d/networking restart");

It looks like the system call will fork another child process that inherits the signal mask of the pthread.  The problem is that it restarts the ssh daemon and the newly created ssh daemon has inherited the signal mask from our pthread (SIGTERM, SIGINT and SIGHUP being blocked).  The result being future network restarts taking a long time as it fails to send the SIGTERM and waits for a timeout before sending SIGKILL.
My question is what is the best way of restarting the network from a multi-threaded application like ours.  Is there a way of telling init to restart a service?
I thought of unblocking signals before calling system, but then if someone terminates our application during this time our main signal handler may not get called.
We are running a debian linux distribution running on an embedded ARM board.  Here's the output from uname -a
Linux ts 2.6.35.3-433-g0fae922 #6 PREEMPT Thu Jul 28 09:24:24 MST 2011 armv7l GNU/Linux

Any help appreciated,
Martin.

A:
In one of our pthreads we restart the network using system(...).

This is exceedingly unsafe, and will cause your application to hang or crash. See this question and discussion.

what is the best way of restarting the network from a multi-threaded application

Fork a child before you have created any threads. Have that child wait on a socket, or for a signal (e.g. SIGUSR1). When woken up, child will do system(...) and go back to sleep.


text:
Q: Is a meta table useful Lets say a lot of my tables will have the same few columns for example a name, description, created timestamp, last updated timestamp.
When is it appropriate to put these common columns in a separate table compared to keeping them in their individual tables.
Just to keep track of it better here is a quick schema.
Books                  Movies
---------------------  ---------------------
|ID|Name|Description|  |ID|Name|Description|
|  |    |           |  |  |    |           |

or
Books         Movies        Meta
------------  ------------  ---------------------
|ID|Meta_ID|  |ID|Meta_ID|  |ID|Name|Description|
|  |       |  |  |       |  |  |    |           |

Obviously this isn't the best example but it gives you the idea.

A: This is Vertical Partioning, as Michael Green states. I think it really depends on how frequently you need the Description field for Books and Movies. If it's rarely accessed/requested, then split it out as you described above. You would have two additional tables though, like BooksMeta and MoviesMeta, instead of the one Meta table. Then add your keys to the meta table.


text:
Q: Best way to send data from a show.route to a different RessourceController I'm using Laravel with a lof of RessourceControllers. No I'm thinkin about a best practise to implement a form in a show.route of RessourceController A. This Form should be send to the store function in a different ResourceController B. This works fine.
But, for example, after processing the store in Controller B, i'd like to redirect back to show.route of Controller A. Of course, I'm missing the data.
And: I'd like to do some validation on the store function in Controller B - But again, the validation will not return the user to show.route of Controller A.
So I'm wondering if I don't understand the architecture concept. Do you have any advisory for me?


text:
Q: Canonical treatment of thermalization of two gases at different temperatures I'd like to understand the thermalization process when two gases of different species and different temperatures are allowed to mix in an insulated container, interacting only through an elastic scattering process.  What is the time-dependence of the average energy per kinetic mode for each gas? How does this depend on the scattering cross-section?  (I am most interested in gases that primarily scatter in the forward direction.)  Is there a relevant Boltzmann equation?
A reference to the canonical treatment of this problem would be sufficient and very much appreciated.


text:
Q: R cannot be resolved to a variable & activity_main cannot be resolved or is not a field , xml is also ok but no file in gen folder i am new to android app development,
i have just created simple android project, but when it created it shows error.
"R cannot be resolved to a variable" when i press control shift +o
android.R is automatically added to my code but now it shows this error
"activity_main cannot be resolved or is not a field"
this is code of this project
package com.php.helloworld;

import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

and when i tried to write this line
import com.php.helloworld.R
it shows "The import com.php.helloworld.R cannot be resolved"
There is also no problem in my xml file and and there is no file in gen folder
can somebody help me please to resolve this

A: Delete the import android.R. It actually refers to android resource within the android default library. If you want to use your resources you must import your R file not android's default library. Check if R.java is present in gen folder in the project.


text:
Q: Search schedule not starting indexing I can manually kick off an incremental crawl for my content sources, however the scheduler does not initiate it on its own. I've attached an image of the crawl schedules if that helps.

I've also checked the ULS logs and event viewer and neither of them have any related errors. Any ideas on what else I can check?

A: Hum, maybe the SharePoint Timer Service is down. Check the Windows Service "Windows Sharepoint Services Timer".
Check also the status of SharePoint jobs (on Operation tab on central administration)


text:
Q: Efeito de expansão de navbar no angular Estou tentando fazer um efeito de expansão de navbar no angular.
Quando clicar no link "mostrar informações" o conteúdo deve subir, e quando clicar em "ocultar", o conteúdo deve abaixar.
O problema é que a parte superior do meu footer não está acompanhando o efeito de expansão.
Tentei algo como:

Minhas animações:
export const statusDisplay =

    trigger('statusDisplay', [
        state('aberto',  style({ display: 'block' })),
        state('fechado', style({ display: 'none'  })),
        transition('fechado => aberto', animate('0ms ease')),
        transition('aberto => fechado', animate('0ms 200ms ease'))
    ])

export const fadeInUpDown =

    trigger('fadeInUpDown', [
        state('fechado', style({
            transform: 'translate3d(0,100%,0)'
        })),
        state('aberto', style({
            transform: 'translate3d(0,0,0)'
        })),
        transition('fechado <=> aberto', animate('400ms ease'))
    ])

Se eu colocar minha animação fadeInUpDown direto no meu footer o efeito funciona como esperado, porém ele aplica o translate3d no início empurrando pra fora da página, habilitando um scroll.
Meu css:
 footer{
   position: absolute;
   bottom: 0;
   width: 100%;
 }


text:
Q: Where can I find the SECRET_KEY of existing Mezzanine Project? I am trying to upload my existing mezzanine project in pythonanywhere.com. However, I always get an error that the SECRET_KEY should not be empty. When I looked into the settings.py, the SECRET_KEY is not there.
In the mezzanine documentation, it says that the SECRET_KEY is automatically created after the command "mezzanine-project". But, where is it? How do I know the SECRET_KEY?
Thank you!

A: Starting with Mezzanine 4.0.0, the SECRET_KEY is populated automatically in local_settings.py in new projects.
In existing projects (or to rotate keys), one way to generate a new one is to simply make a new project and copy the SECRET_KEY:
$ mezzanine-project tmp
$ cat tmp/tmp/local_settings.py | grep "SECRET_KEY.*="
SECRET_KEY = "dontusesthisstringfromstackoverflowasyoursecretkey"
$ rm -rf tmp


text:
Q: Retrieve embedded image from ViewModel in xamarin I have a project that has a sequence of views that are used for an on boarding sequence/tutorial for the app. I prefer to embed the resources in the main project (they are not different for each platform). Also, some of the resources are GIFs while others are SVG and a couple of PNG's.
How do I reference embedded images from the ViewModel? I looked at the images sample on MSFT docs, but it doesn't really solve the problem for me. Also, I have to either use ffImageLoading (or Skia) to render my SVGs.
I am sure others have dealt with this issue - so looking for lessons learned. My GIF's are a little large - so perf is a big consideration. I have the project working but perf is very poor and maintaining iOS and Android versions of the same assets is a waste.
Thanks in advance!

A: Thanks to all for the comments. What I was forgetting is that I just needed to bind to the resource ID of the embedded image - and simply set that value in my viewmodel. In short, my question was poorly written and I was not thinking about it.


text:
Q: How to change Format "Hours" to "hour : minutes" in excel
hi everyone i have one columns is Duration columns, the column is in hour format, and I want to convert it to "hour:minutes" format, what formula can I use in excel?
i use =TEXT(A1/24,"hh:mm")

A: You need to divide hours by 24. Try below formula-
=TEXT(A1/24,"hh:mm")

Check this article from exceljet.net Convert decimal hours to Excel time.
From @Gary's Student answer, you can also use same format with text function.
=TEXT(A1/24,"[hh]:mm")

A: With data in A1, in another cell enter:
=A1/24

and format as follows:

Note the brackets in the formatting:
[hh]:mm

A: The other answers are fine, but I wanted to offer an alternative that does not involve formatting the cell (which may or may not be desirable, although it probably usually is the best way TBH).
The following formula splits the hours and minutes:
=FLOOR(S10,1) & ":" & (S10-FLOOR(S10,1))*60


text:
Q: can we convert Odata metadata to C# code (datacontract) there is a odata webservice, i can get metadata from
http://service-uri.com/$metadata

which contains definition of all its model object,
is there any tools that i can use, to convert that metadata xml to data contract class in C#?

A: The WCF Data Services Client library can generate C# classes for you from the $metadata endpoint. These classes won't have the [DataContract] attribute, but you can use them with the rest of the client library to interact with the service.
To use this feature, download the latest "tools" installer for the client library, currently available here: http://www.microsoft.com/en-us/download/details.aspx?id=35840
(Note: If you want the latest stable bits of the client library, also run the following from the Package Manager Console window in Visual Studio: Install-Package Microsoft.Data.Services.Client)
Then, from within Visual Studio, you can right click on your project, and select "Add Service Reference". Here you can enter the $metadata URL of the service, and the corresponding classes will be generated, along with a DataServiceContext class you can use to interact with the service. For more info on querying the service, see this documentation: http://msdn.microsoft.com/en-us/library/dd673933.aspx
Or, if you want to generate the classes manually, you can use the DataSvcUtil.exe command line tool that comes with the tools installer. On my system, for example, that file is located at
C:\Program Files (x86)\Microsoft WCF Data Services\Current\bin\tools\DataSvcUtil.exe
For instructions on how to use this tool, take a look at this page: http://msdn.microsoft.com/en-us/library/dd756369.aspx


text:
Q: Streaming data from one Lambda to another I want to build a distributed implementation of Samplesort using AWS Lambda functions for a 100GB dataset made of two columns (key and sorted value), each encoded using 64-bit floats. The dataset is to be distributed across 220 Lambda functions, each having 1GB of RAM, with 28.4M rows per function. Each Lambda can sort its subset within less than a second. From there, we send 220 × 220 = 48,400 equally distant samples to a root Lambda through 220 SNS messages (30ms to 50ms), have the root Lambda sort them (less than 2ms), then broadcast 220 equally distant samples to the sorting Lambda functions over SNS (30ms).
The hard part is to then have all the sorting Lambdas send portions of their respective datasets to the right sorting Lambdas. This requires that the full 100GB dataset be moved across the sorting Lambdas, with 220 × 219 = 48,180 individual data movements. My question is the following: what is the fastest way of doing that?
Using EFS would give me about 469MB/s of aggregated write bandwidth, which would take about 213s. Reads are about 20 times faster, therefore would require an extra 11s. S3 would be a lot faster. We know that read throughput of S3 from a Lambda is about 75MB/s. If we assume a similar write throughput (probably overly optimistic) and Parquet compression with a 5× compression factor, we get 375MB/s of read/write throughput. Each Lambda would need to write then read 454MB of data, which would require 2.42s.
A faster approach would be to have pairs of sorting Lambda functions communicate through WebSocket. Is that possible? If so, what is the proper way to configure it? If not, what would be an alternative that would not require the use of a slow persistence layer?
Note: this article gives a great introduction to the distributed Samplesort.


text:
Q: replace a character according to its index until the word does not contain '_' in Python I am trying to create a function that takes a word housed in a variable and modifies it according to the letter that I am entering until the variable does not contain any '_'. The code does not give any type of error, it simply does not work even though if I try line by line if it fulfills its function. any suggestion?
def reveal_word():
    string = '____'
    word = 'cat'
    while '_' in string:
        letter = input('Enter your letter: ')
        for index in string:
            index = word.find(letter)
            string[index].replace('_',letter)
        return string
print(reveal_word())

A: def reveal_word():
    word = "capybara"
    string = "_" * len(word)
    while "_" in string:
        print(string)
        char = input("Enter your letter: ")[0] # [0] to get the first letter
        idx = word.find(char)
        if idx != -1:
            word = word[:idx] + "_" + word[idx + 1 :]
            string = string[:idx] + char + string[idx + 1 :]
    return string

print(reveal_word())

A: Here is a somewhat simpler solution. It uses a list of characters in the word and drops matched characters from that list until the list is empty:
def reveal_word():
    word = 'cat'
    string = list(word)

    while string:
        letter = input('Enter your letter: ')
        if letter in string:
            string = list(filter(lambda val: val !=  letter, string))

    return word
print(reveal_word())

A: Here's a sample with a slightly different twist.  In this example if a character exists more than once in the word to guess, every location will be updated with that character.
def reveal_word():
    string = '________'
    word   = 'Hercules'
    while '_' in string:
        letter = input('Enter your letter: ')
        for index in range(0, len(string)):
            if (string[index] == '_'):
                if (word[index] == letter):
                    temp = list(string)
                    temp[index] = letter
                    string = "".join(temp)
        print('String: ', string)
    return string
print(reveal_word())

Here is some terminal output.
Enter your letter: e
String:  _e____e_
Enter your letter: H
String:  He____e_
Enter your letter: r
String:  Her___e_
Enter your letter: c
String:  Herc__e_
Enter your letter: u
String:  Hercu_e_
Enter your letter: l
String:  Hercule_
Enter your letter: s
String:  Hercules
Hercules

Just another take on the puzzle.
Regards.


text:
Q: Display ms document on a web browser using php or html How can I display an ms word document  to  a web browser  just like the way an image is displayed in html . I am using php and  html , I tried it using iframe but my  idea did not work .

A: try this :
<?php
        $word = new COM("word.application") or die ("Could not initialise MS Word object.");
        $word->Documents->Open(realpath("Sample.doc"));

        // Extract content.
        $content = (string) $word->ActiveDocument->Content;

        echo $content;

        $word->ActiveDocument->Close(false);

        $word->Quit();
        $word = null;
        unset($word);
?>

for More Info Refer  this

A: You can use Google Docs:


text:
Q: Button doesn't work in Asp.net? I become really confused ! I want to design online shopping web site and I create new empty asp.net web site in visual studio 2013 with framework 4.5 and I write Register.aspx with the following code:
Code-Behind:
protected void registerBtn_Click(object sender, EventArgs e)
    {
        lbReport.Text ="it works";
    }

Register.aspx:
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

                        ورود

                        ثبت نام

                        تغییرپسورد

ثبت نام

. ازاین که می خواهید عضوی ازفروشگاه من باشید بسیار متشکریم،بهترین لحظات را درفروشگاه من برای شما آرزومندیم

                <form class="form-Account">

                            <asp:TextBox ID="userText" runat="server" cssClass="logInTextBox" PlaceHolder="نام کاربری" ></asp:TextBox>

                            <asp:TextBox ID="passText" runat="server" TextMode="Password" cssClass="logInTextBox" PlaceHolder="پسورد"></asp:TextBox>

                            <asp:TextBox ID="confirmPassText" runat="server" TextMode="Password" cssClass="logInTextBox"  PlaceHolder="تکرار پسورد"></asp:TextBox>

                            <asp:TextBox ID="nameText" runat="server" cssClass="logInTextBox" PlaceHolder="نام و نام خانوادگی"></asp:TextBox>

                            <asp:TextBox ID="emailText" runat="server" cssClass="logInTextBox" PlaceHolder="آدرس الکترونیکی"></asp:TextBox>

                            <asp:TextBox ID="mphoneText" runat="server" cssClass="logInTextBox" PlaceHolder="شماره همراه"></asp:TextBox>

                             <asp:button ID="registerBtn"  runat ="server" Text="ثبت کنید" class="button" OnClick="registerBtn_Click" />

                            <asp:Label ID ="lbReport" Text="Hello world" runat="server" ForeColor="Black"></asp:Label>

                </form>

</asp:Content>

But when I click on the button nothing happens it seems that registerBtn_Click is not called ! what can I do ? how can I fix this issues?

A: You are using incorrect markup for the button i.e. <asp:button> .
Try using <asp:Button>
<asp:Button ID="registerBtn"  runat ="server" Text="ثبت کنید" class="button" OnClick="registerBtn_Click" />


text:
Q: take out margins on DataGridTextColumn in WPF Currenty I have a DataGrid like so
<DataGrid Grid.Row="0" ItemsSource="{Binding ResultSet}" AutoGenerateColumns="False"
        SelectedItem="{Binding AValue, Mode=TwoWay}"
        CanUserAddRows="False" CanUserReorderColumns="True" CanUserDeleteRows="False"
        KeyboardNavigation.TabNavigation="Once"
        CanUserResizeColumns="True" CanUserSortColumns="True" SelectionMode="Single" MinHeight="300">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding SelectedCommand}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        <DataGrid.InputBindings>
            <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding ViewDetailsCommand}"/>
        </DataGrid.InputBindings>
        <DataGrid.RowHeaderStyle>
            <Style TargetType="{x:Type DataGridRowHeader}">
                <Setter Property="Content" Value="{StaticResource AResource}" />
            </Style>
        </DataGrid.RowHeaderStyle>
        <DataGrid.Columns>
            <DataGridTextColumn KeyboardNavigation.IsTabStop="False" IsReadOnly="True" Width="Auto" Header="{l:LocText SomeText}" Binding="{Binding ABinding1}"  />
            <DataGridTextColumn KeyboardNavigation.IsTabStop="False" IsReadOnly="True" Width="Auto" Header="{l:LocText SomeText1}" Binding="{Binding ABinding2}" />
            <DataGridTextColumn KeyboardNavigation.IsTabStop="False" IsReadOnly="True" Width="Auto" Header="{l:LocText SomeText2}" Binding="{Binding ABinding3}" />
            <DataGridTextColumn KeyboardNavigation.IsTabStop="False" IsReadOnly="True" Width="Auto" Header="{l:LocText SomeText3}" Binding="{Binding ABinding4, StringFormat={}{0:MM/dd/yyyy}}" />
            <DataGridTextColumn KeyboardNavigation.IsTabStop="False" IsReadOnly="True" Width="Auto" Header="{l:LocText SomeText4}" Binding="{Binding ABinding5, StringFormat='{}{0:c}'}" />
        </DataGrid.Columns>
</DataGrid>

This is the style of the Column Header:
<Style x:Key="AResource" TargetType="{x:Type DataGridColumnHeader}"
       BasedOn="{StaticResource MaterialDesignDataGridColumnHeader}">
    <Setter Property="Background" Value="#1c313a" />
</Style>

The thing is, each column has like some Margin, a left and right one so I can't put the columns almost together, I want to eliminate that Margin or whatever it is.
EDIT:

This is the image, As you can see If I put the Column2 "Close" to Column1, then there is this sort of content that takes out the space of Column1, each column has this space.


text:
Q: fbml application error the form is hosted on my website,when the user submit the form,i want to pass the data to my facebook app.
how to do that

A: Try
if(!$user) {
       $login_url = $facebook->getLoginUrl(array('scope' => "publish_stream,user_photos,friends_photos"));

    die("<script> top.location.href='".$login_url."'</script>");

}


text:
Q: Python not jumping into "else" condition Good morning,
This is my 1st post here & Im only dabbing my feet in programming pool so please be gentle :)
As it currently stands, I have to fulfill 2 conditions (sadcat & great == yes). What I want instead is to jump straight to else ( 'Why did you even start this game in the first place? This is a rhetorical question btw.'), if the 1st condition is not ulfilled (sadcat == something else than 'yes')
I have no idea why doesnt this work... Indentation seems to be OK to me. Any help is appreciated
sadcat = input('Do you like war? ')
great = input ('That\'s great but are you also a cat? ')

if sadcat == 'yes':
    if great == 'yes':
      print('ok I have no more questions')
    else:
      print('Not a cat ? How do you even live with yourself.')
else:
  print('Why did you even start this game in the first place? This is a rhetorical question btw.', end=" ")

A: If you want the "game" to end if the "player" doesn't like war, then the first if should be right after the first question
sadcat = input('Do you like war? ')
if sadcat == 'no':
    print('Why did you even start this game in the first place? This is a rhetorical question btw.', end=" ")
    exit()

great = input ('That\'s great but are you also a cat? ')
if great == 'yes':
    print('ok I have no more questions')
else:
    print('Not a cat ? How do you even live with yourself.')

A: so basically code works with it executing each line in the order it is written.
in your code it first takes input for sadcat, then input for great.
only after that it starts evaluating sadcat.
(your code is correct. once it gets to the evaluating part, it will go straight to the else)
if you wish the game to end right after the person types anything other than 'yes'
import sys

sadcat = input('Do you like war? ')
if sadcat != 'yes':
    print('Why did you even start this game in the first place? This is a rhetorical question btw.', end=" ")
    sys.exit() #this will terminate the program

great = input ('That\'s great but are you also a cat? ')

if sadcat == 'yes':
    if great == 'yes':
      print('ok I have no more questions')
    else:
      print('Not a cat ? How do you even live with yourself.')


text:
Q: JS - Child element to not listen to delegated event In the following snippet you will see a delegated event attached to document.
The key thing to note is:
if (e.target.parentNode.id === 'put-stuff-here') {
  e.target.classList.toggle('active');
}

function loadItems(target) {
  for (var i = 0; i < 10; i++) {
    setTimeout(function() {
      target.insertAdjacentHTML('beforeend', '
Click me!Or click me!
');
    }, (i * 250));
  }
}

document.getElementsByTagName('button')[0].addEventListener('click', function(e) {
  loadItems(document.getElementById('put-stuff-here'));
});

document.addEventListener('click', function(e) {
  if (e.target.parentNode.id === 'put-stuff-here') {
    e.target.classList.toggle('active');
  }
});
body {
  font-family: 'arial';
  display: flex;
  flex-flow: column;
}
body > * {
  margin-bottom: 16px;
}
#put-stuff-here:before {
  display: block;
  padding: 8px;
  text-align: center;
  content: 'Target Location:';
  background-color: PapayaWhip;
}
#put-stuff-here {
  border: 1px solid black;
}
.new {
  background-color: SteelBlue;
  padding: 8px;
}
.new span {
  border: 1px dotted red;
  margin: 8px;
}
.active {
  background-color: white;
}
<button>Press Me!</button>

As you can see, if you click on the "red-bordered span" it will not work, but if you click on the div it works. I know the reason for this and the "solution" is:
if (e.target.parentNode.id === 'put-stuff-here' || e.target.parentNode.parentNode.id === 'put-stuff-here') {
  e.target.classList.toggle('active');
}

This; however, does not fully work, and causes this (click on both the span and then the div):

function loadItems(target) {
  for (var i = 0; i < 10; i++) {
    setTimeout(function() {
      target.insertAdjacentHTML('beforeend', '
New!
');
    }, (i * 250));
  }
}

document.getElementsByTagName('button')[0].addEventListener('click', function(e) {
  loadItems(document.getElementById('put-stuff-here'));
});

document.addEventListener('click', function(e) {
  if (e.target.parentNode.id === 'put-stuff-here' || e.target.parentNode.parentNode.id === 'put-stuff-here') {
    e.target.classList.toggle('active');
  }
});
body {
  font-family: 'arial';
  display: flex;
  flex-flow: column;
}
body > * {
  margin-bottom: 16px;
}
#put-stuff-here:before {
  display: block;
  padding: 8px;
  text-align: center;
  content: 'Target Location:';
  background-color: PapayaWhip;
}
#put-stuff-here {
  border: 1px solid black;
}
.new {
  background-color: SteelBlue;
  padding: 8px;
}
.new span {
  border: 1px dotted red;
  margin: 8px;
}
.active {
  background-color: white;
}
<button>Press Me!</button>

There are various other methods I have tested, including:
if (e.target.parentNode.id === 'put-stuff-here' || e.target.parentNode.parentNode.id === 'put-stuff-here') {
  e.target.classList.toggle('active') || e.target.parentNode.classList.toggle('active');
}

But they all do not do what I want, which is: when you click anywhere in the div, it will toggle the active class

I think the solution lies somewhere event bubbling, but I have not been able to find a way to utilize this. Is there a way for child events to "ignore" event handlers on (non-)delegated events?

A jsfiddle for this can be found here.
P.S. I know another way to do this is:
if (e.target.classList.contains('new') || e.target.parentNode.classList.contains('new')) {
  e.target.classList.toggle('active');
}

and all the other variations, etc. but that runs into the same problem that I list above.

A:
I think the solution lies somewhere event bubbling, but I have not been able to find a way to utilize this. Is there a way for child events to "ignore" event handlers on (non-)delegated events?

Yes event bubbling is part of the solution, and utilizing the properties of event.target and event.currentTarget will help you isolate a specific element along the event chain.
SNIPPET

// Reference the parent element
var parent = document.getElementById('parent');

// add an eventListener to the parent element
parent.addEventListener('click', function(event) {

  /*
  | While in bubbling phase, we only want event.target
  | (i.e. the element that was clicked on) and not
  | all of the other elements that happen to be on the
  | event chain (i.e. event.currentTarget)
  */

  if (event.target !== event.currentTarget) {

    // Store the event.target in a var
    var tgt = event.target;

    // Do whatever you want to event.target
    tgt.classList.toggle('active');
  }
  /*
  | Stop any further bubbling so that event.target is
  | the only element on the event chain that reacts to
  | the click event.
  */
  event.stopPropagation();
}, false);
#parent {
  background: rgba(0, 0, 0, .75);
  border: 3px dashed red;
  padding: 10px;
}
.child {
  background: rgba(255, 255, 255, .75);
  border: 1px solid blue;
  margin: 5px;
  height: 15px;
}
.active {
  background: red;
  outline: 2px dotted orange;
}

A: You can use pointer-events:

The CSS property pointer-events allows authors to control under what
  circumstances (if any) a particular graphic element can become the
  target of mouse events.

.new > * {
  pointer-events: none;
}

function loadItems(target) {
  for (var i = 0; i < 10; i++) {
    setTimeout(function() {
      target.insertAdjacentHTML('beforeend', '
Click me!Or click me!
');
    }, (i * 250));
  }
}

document.getElementsByTagName('button')[0].addEventListener('click', function(e) {
  loadItems(document.getElementById('put-stuff-here'));
});

document.addEventListener('click', function(e) {
  if (e.target.parentNode.id === 'put-stuff-here') {
    e.target.classList.toggle('active');
  }
});
body {
  font-family: 'arial';
  display: flex;
  flex-flow: column;
}
body > * {
  margin-bottom: 16px;
}
#put-stuff-here:before {
  display: block;
  padding: 8px;
  text-align: center;
  content: 'Target Location:';
  background-color: PapayaWhip;
}
#put-stuff-here {
  border: 1px solid black;
}
.new {
  background-color: SteelBlue;
  padding: 8px;
}
.new > span {
  border: 1px dotted red;
  margin: 8px;
  pointer-events: none;
}
.active {
  background-color: white;
}
<button>Press Me!</button>


text:
Q: Remove empty table rows output buffering? I have a large static table which is generated by a cgi script from a tmp file to a php file.
If it outputs

Can I remove these with output buffering.

A: You could use preg_replace, it would look something like this
$str = '<tables>
bla

';
$str = preg_replace('/\\s+<\/td>/', '', $str);

But keep in mind if you delete the whole blank td you need to manage the colspawn's so i would prefere something like this
$str = '<tables>
bla

';
$str = preg_replace('/\\s+<\/td>/', '	', $str);


text:
Q: Pandas accidentally setting entire column, not last in row This may be a dumb question but I am a tad stuck with this. Say I have this dataframe:
   amount  amount_str  buy_order_id        id   midprice       price
0  0.01545000  0.01545000     915692220  53424450  0.1286495  0.12947460
0  1.65956203  1.65956203     915692330  53424458        NaN  0.12947460
0  0.68427900  0.68427900     915692581  53424487        NaN  0.12947460
0  0.22306417  0.22306417     915692632  53424491        NaN  0.12808629
0  0.22306396  0.22306396     915692964  53424530        NaN  0.12808646
0  2.31474046  2.31474046     915693081  53424535        NaN  0.12947460
0  0.16808924  0.16808924     915694097  53424600        NaN  0.12808675
0  5.30166589  5.30166589     915694819  53424629        NaN  0.12808710
price_str  sell_order_id   timestamp  type
0  0.12947460      915690988  1518045004     0
0  0.12947460      915690988  1518045006     0
0  0.12947460      915690988  1518045010     0
0  0.12808629      915692647  1518045010     1
0  0.12808646      915693012  1518045016     1
0  0.12947460      915690988  1518045017     0
0  0.12808675      915694117  1518045031     1
0  0.12808710      915694862  1518045041     1

Here is my issue: each time the program gets a new order from bitstamp, it appends the values to this dataframe, and then adds the current midprice.
I could normally do that with df['midprice'] = value; however, this sets it for the entire column and not just that entry.
How would I make it so it adds it per line and not to the entire column?
Thanks!

A: Pandas specialises in vectorised calculations.
So df['midprice'] = value sets an entire series (or column) to a fixed value.
It seems like you want to amend the last midprice value only, straight after a row is added by another process. This is one way you can achieve this:
df.iloc[-1, df.columns.get_loc('midprice')] = value


text:
Q: c# DataContext Binding Problem with binding SelectTask field. I checked in the debugger, the necessary information goes there through selecteditem, but for some reason in the stackpanel it does not want to bind...
public ObservableCollection<Task> Tasks { get; set; }
        public Task SelectTask { get; set; }

        public MainWindowViewModel()
        {
            TabCollection = new ObservableCollection<object>();
            TabCollection.Add(new HomeViewModel() { TabName = "Main" });
            TabCollection.Add(new NewTaskViewModel() { TabName = "Add" });

            using (TaskContext db = new TaskContext())
            {
                Tasks = new ObservableCollection<Task>(db.Task);
            }
        }

 <ListBox Grid.Row="1" Grid.RowSpan="2" Grid.Column="0"
                    SelectionMode="Extended"
                    ItemsSource="{Binding Tasks}"
                    SelectedItem="{Binding SelectTask}">
        </ListBox>

        <StackPanel DataContext="{Binding SelectTask}" HorizontalAlignment="Center" Grid.Column="1" Grid.Row="1">
            <Button Content="Удалить" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="74" />
            <Button Content="Редакт" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" />
            <UniformGrid  Columns="2">
                <TextBlock Text="Задача: " />
                <TextBlock Text ="{Binding Title}"  />
            </UniformGrid>


text:
Q: проблема с flex-wrap + bootstrap3 на safari 9 В проект сделан на bootstrap3 подключаю модуль из bootstrap4 flex.
Исполльзую такую конструкцию

      some text

      some text

Суть в том, что свойство (flex-wrap: wrap) для класса .row, дает возможность выровнять по высоте блоки .col-md-6
На современных браузерах это отлично работает, и даже в ие11.
Но в safari 9.3 (ipad2) и в хроме < v43 , последний  блок .col-md-6 переносится на следующую строку.
Тестируется через сервис, потому поиграть с свойствами в инспекторе возможности нет.

A: Проблема  заключалась в особенности класса .row в bootstrap3.
Как известно, бутстрап задает стили для псевдоклассов before и after, устанавливая им свойство display: table; Таким образом предотвращает "схлопывание контейнера" .row , т.к для внутренних элементов задано обтекание float: left.
Но в новых брраузерах, содержимое псевдоклассов было безразмерное, 0x0 и данная проблема не всплывала.
Видимо в старых браузерах таблица имела обределенные габариты, или отступы (наверняка сказать не могу, т.к выводы делал по скринам, если у кого есть возможность посмотреть инспектор в данной версии браузера отпишите в коммент), что смещало первый элемент на 1px, в результате 2 блока с шириной в 50% уже не помещались в один ряд.
Проблему решил путем задания псевдоклассам ширину в 100%.


text:
Q: Flutter print a specific value I have a very easy question dont know why I am not able to find it anywhere I just need to print the specific value of data
My code
  Future<http.Response> _trySubmit() async {
    final isValid = _formKey.currentState.validate();
    FocusScope.of(context).unfocus();

    if (isValid) {
      _formKey.currentState.save();

      print(_userEmail.trim());
      print(_userPassword.trim());

      var map = new Map<String, dynamic>();

      map['grant_type'] = 'password';
      map['username'] = _userEmail.trim();
      map['password'] = _userPassword.trim();

      http.Response res = await http.post(
        'http://sublimeapi.netcodesolution.com/token',
        headers: <String, String>{
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: map,
      );
      var data = res.body;
      print(data);
    }
    }

Its printing the value like this
I/flutter ( 5147):{"access_token":"FwYttAQIDDSRpuFFUgzznmMYgMNNfiW4OvQ4","token_type":"bearer","expires_in":86399}

I need to print just access_token value
Something like this print(data.access_token)

A: Here data is a Map. So if you want to print a specific value out of it, you need to mention the corresponding key name like this
print(data['access_token']);

A: You need to decode the response result before printing the value :
 http.Response res = await http.post(
            'http://sublimeapi.netcodesolution.com/token',
            headers: <String, String>{
              'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: map,
          );
          var data = json.decode(res.body.toString());
          print(data["access_token"]);

Don't forget importing :
import 'dart:convert';

A: Your can try something like this: Decode the json response first then access the data in the Map
http.Response res = await http.post(
    'http://sublimeapi.netcodesolution.com/token',
    headers: <String, String>{
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: map,
  );
     var responseBody = json.decode(res.body);
     print(responseBody['access_token']); //This should return your token
 }
}


text:
Q: ControlsFX runtime error when trying to instantiate SpreadsheetView Here is the error message, it occurs when trying to create a new SpreadsheetView():
Caused by: java.lang.IllegalAccessError: class org.controlsfx.control.spreadsheet.GridBase (in module org.controlsfx.controls) cannot access class com.sun.javafx.event.EventHandlerManager (in module javafx.base) because module javafx.base does not export com.sun.javafx.event to module org.controlsfx.controls

I looked at another stack overflow post here, but it does not solve the problem.
I am using maven as the build tool, so would like to be able to add something to the pom.xml file.
I'm using java 17, javaFx 17, controlsFx 11.1.1. To create the project I used IntelliJ's generator for a javafx project.
Does anyone have a working example of SpreadsheetView? or a way to make this work?


text:
Q: Swiperjs Carousel that overlaps the container on its right side [Angular] I'm setting up a simple Swiperjs carousel that must be inside a container of a maximum size of 1150px (is the size I use throughout the web), but that on its left side overlaps the container and reaches the end of the right side of the body.

The carousel is working perfectly, but I can't get the container on the right side to pass over and the left side to keep its position regardless of the size of the screen.
Component:

       <swiper [config]="modulConfig" >
           <ng-template swiperSlide *ngFor="let item of modulCards">
              <app-course-stage [modulStageInput]="item"></app-course-stage>
           </ng-template>
       </swiper>

Slider conf:
  modulConfig: SwiperOptions = {
   slidesPerView: 2.5,
   spaceBetween: 24,
   rewind: false,
 };

this is how it looks like in my project

I tried to replicate the slider in StackBlitz, but the repository is in version 9 and Swiper has removed support for Angular from version 8.


text:
Q: Is it possible to run a program that requires elevation unelevated My program normally needs to be launched as an elevated process and therefore it contains the usual manifest (...<requestedExecutionLevel level="requireAdministrator"/>...), so the UAC will pop up when the program is launched. This work fine as intended.
Now under certain conditions I'd like to run that program (programmatically from another unelevated process) as an unelevated process (IOW it should act just as if the manifest would not contain level="requireAdministrator").
Is this possible?

A: For the sake of clarity, lets call the program you want to run X.
I normally use a 'shim' to launch X elevated.  The shim is just a little program that is marked requireAdministrator and whose sole purpose is to run X elevated.  X is then marked asInvoker and will run elevated (only) when invoked from the shim.  You then make the shim the icon that the user clicks on.
Having done all that, you can then run X unelevated by launching it direct.
I hope that all makes sense!  I don't know of any other way.

A: Raymond Chen covered this topic on his Old New Thing blog:
November 18th, 2013: How can I launch an unelevated process from my elevated process and vice versa?

Going from an unelevated process to an elevated process is easy. You can run a process with elevation by passing the runas verb to ShellExecute or ShellExecuteEx.
Going the other way is trickier. For one thing, it's really hard to munge your token to remove the elevation nature properly. And for another thing, even if you could do it, it's not the right thing to do, because the unelevated user may be different from the elevated user.
...
The solution here is to go back to Explorer and ask Explorer to launch the program for you. Since Explorer is running as the original unelevated user, the program (in this case, the Web browser) will run as Bob. This is also important in the case that the handler for the file you want to open runs as an in-process extension rather than as a separate process, for in that case, the attempt to unelevate would be pointless since no new process was created in the first place. (And if the handler for the file tries to communicate with an existing unelevated copy of itself, things may fail because of UIPI.)

April 25th, 2019: How can I launch an unelevated process from my elevated process, redux

There's another way which is a bit more direct, but it assumes that the thing you want to do can be done with a direct CreateProcess call. In other words, if you need the system to look up the user's file associations or default browser, then this technique is not for you.
The idea is to take advantage of PROCESS_CREATE_PROCESS access and the accompanying PROC_THREAD_ATTRIBUTE_PARENT_PROCESS process thread attribute:
...
Basically, this lets you tell the CreateProcess function, "Hey, like, um, pretend that other guy over there is creating the process."

Both blog articles contain full source code examples.


text:
Q: How to set text in a static label to bold style? I'm writing an application for a Pocket PC 2003 device. In it there is a dialog where various text information is shown. The information is separated so that each piece resides inside its own label, defined as LTEXT in the resource file.
Now my problem is that, at the moment, all text lables have the same font and style (normal or simple, i.e. not bold or italic); I want want one to be set in bold. I know that I can set the font to bold in the resource file, but that sets the style of all labels.
How does one achieve this? I've seen it be used in the Windows 'About' screen so I know it's possible. I've written the program in C++ using the Win32 API directly (except for certain dialogs where I've used the resource file) so I would appreciate if the answer was given in the same language and approach.
Thanks.

A: In the resource editor, edit the static text item, and change its control ID to something unique: IDC_BOLD for example.
In the DialogProc for the dialog boxes that is hosting the control, add a WM_CTLCOLORSTATIC handler:
case WM_CTLCOLORSTATIC:
  HDC hdc;
  HWND hwndCtl;
  hwndCtl = (HWND) lParam;
  hdc = (HDC) wParam;

  if( GetWindowLong(hwndClt, GWL_ID ) == IDC_BOLD )
  {
    SetBkMode(hdc,TRANSPARENT);
    SetTextColor(hdc,RGB(0xff,0,0)); // turn the text red for fun :)
    SelectObject(hdc,hBoldFont);     // but you want this...
    return (INT_PTR)GetSysColorBrush(COLOR_BTNFACE);
    //return 0L; // if visual themes are enabled (common controls 6) then 0 is better.
  }
  // default processing
  return 0;

You are developing for Pocket PC 2003, I don't know what buttons styles are available. This Page refers of course to desktop XP. But, if the buttons in the dialogs are not flat grey 95esq buttons, then it might be more appropriate to return 0 as that will paint the text background correctly if the dialogs background is not plain grey.
Pre-visual styles a return of 0 causes the system to reset the DC so its important to know which return is appropriate.


text:
Q: Right way to convert of BigDecimal to String Why I should use valueOf()?
why cant I use the implicit conversion?
Code Snippet is shown below:
BigDecimal xmlvalue = new BigDecimal(12.3434379328948927894789237);
String str1 = String.valueOf(xmlvalue); //Option 1
String str2 = "" + xmlvalue; //Option 2

A: You can use BigDecimal#toString to convert a BigDecimal to string

A: you can use the toString() method
xmlvalue.toString();

A: One could argue that it is more readable to use valueOf(x) than "" + x. Internally, both will fall back to toString but they can also deal with null values (where null.toString() will throw a NullPointerException).
In theory, the performance of valueOf(x) should be better than "" + x, as the latter uses a StringBuilder internally, which can lead to some overhead.
When you know that your BigDecimal is non-null (as in your example), you should just use toString.
By the way, be careful with the BigDecimal(double) constructor. The safer approach is to use
new BigDecimal("12.3434379328948927894789237") in your example. The reason why BigDecimal(double) is unpredicable is explained in its Javadoc comment.

A: Why would you ever manually use "" + string for a conversion to String? I know that a lot of developers use that, but to me it seems just like taking an advantage of Java's developer friendliness and the fact that it does a lot of stuff(terminus technicus "conversions") automatically. In other words it's a lazy way around and I don't like raping Java when String.valueOf() is implemented exactly for this purpose.
Technical answer:
When a + "" is used with an integer a. It behaves as such:
String.valueOf(a) + new String("");

This creates two String objects, while String.valueOf(a) uses just one.

A: Using BigDecimal doesn't bring back the precision lost in double If you need more than 15 digits of accuracy you need to use String and BigDecimal.
BigDecimal xmlvalue = new BigDecimal("12.3434379328948927894789237");
String str1 = xmlvalue.toString(); // Simplest Option

If you have a double you may as well just do
// creating BigDecimal here doesn't help unless you do rounding.
String str1 = String.valueOf(d);

A: I think better way is to use class - java.text.DecimalFormat because in practical scenarios , there is no relation between actual value represented by these number classes like BigDecimal & their String representations, though you haven't listed your reason for wanting a String value for an altogether different type of data.
In my opinion, String representation is all about formatting & this DecimalFormat class gives you better control over that e.g. I needed to write few BigDecimal values to a text file and different values needed to be in different format.
A portion of Java Doc,

DecimalFormat is a concrete subclass of NumberFormat that formats
  decimal numbers. It has a variety of features designed to make it
  possible to parse and format numbers in any locale, including support
  for Western, Arabic, and Indic digits. It also supports different
  kinds of numbers, including integers (123), fixed-point numbers
  (123.4), scientific notation (1.23E4), percentages (12%), and currency
  amounts ($123). All of these can be localized.

A: For two reasons:

*

*Using String.valueOf better conveys your intent: you obviously try to get the String representation of a BigDecimal value; abusing String concatenation requires a little more mental effort to understand what you are trying to do

*It may be faster: Using concatenation will internally create a StringBuilder, which concatenates two Strings and then calls toString() onto itself (though the compiler may be clever enough to get rid of these unnecessary operations)

A: The String#valueOf use Double#toString method in this case.
I think is better use BigDecimal#toString method. For example if you want to converted back this data, it better use this toString method.

If that
  string representation is converted back to a BigDecimal using the
  BigDecimal(String) constructor, then the original value will be
  recovered.


text:
Q: Getting an image to upload using Dropzone and Laravel I'm trying to create a page where a user can add a title and then upload an image or 2. I'm using dropzone and Laravel and I've tried to make it look different,
I made it look like http://www.dropzonejs.com/bootstrap.html
The problem I'm having is that I need to add a url to the js file but it keeps giving me this error

POST http://crud.test/portfolios 419 (unknown status)

and in my Preview in my dev tools

{message: "", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}

I know that in Laravel I would use
{{ csrf_field() }}

and I can't upload my images to the folder I specified in my controller or save the images to my database.
What I would like is how do I get my images to upload to the folder and save to my database.
My blade:
<form action="{{ route('portfolios.store') }}">
    {{ csrf_field() }}

        Title
        <input type="title" name="title" class="form-control">

                Add files...

            <button type="button" class="btn btn-info start">

                Start upload
            </button>

            <button type="reset" class="btn btn-warning cancel">

                Cancel upload
            </button>

                <button class="btn btn-info start">

                    Start
                </button>

                <button data-dz-remove class="btn btn-warning cancel">

                    Cancel
                </button>

                <button data-dz-remove class="btn btn-danger delete">

                    Delete
                </button>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

My main.js:
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);

var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
    url: "/portfolios", // Set the url
    thumbnailWidth: 80,
    thumbnailHeight: 80,
    parallelUploads: 20,
    previewTemplate: previewTemplate,
    autoQueue: false, // Make sure the files aren't queued until manually added
    uploadMultiple: true,
    previewsContainer: "#previews", // Define the container to display the previews
    clickable: ".fileinput-button" // Define the element that should be used as click trigger to select files.
});

myDropzone.on("addedfile", function(file) {
    file.previewElement.querySelector(".start").onclick = function() {
        myDropzone.enqueueFile(file);
    };
});

myDropzone.on("totaluploadprogress", function(progress) {
    document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
});

myDropzone.on("sending", function(file) {
    document.querySelector("#total-progress").style.opacity = "1";
    file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});

myDropzone.on("queuecomplete", function(progress) {
    document.querySelector("#total-progress").style.opacity = "0";
});

document.querySelector("#actions .start").onclick = function() {
    myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
};

document.querySelector("#actions .cancel").onclick = function() {
    myDropzone.removeAllFiles(true);
};

My controller:
public function store(Request $request)
{
    $portfolio = new Portfolio();

    $portfolio->fill($this->getSafeInput($request));

    if($request->hasFile('file'))
    {
        $names = [];
        foreach($request->file('file') as $image)
        {

            $destinationPath = 'portfolio_images/';
            $filename = $image->getClientOriginalName();
            $image->move($destinationPath, $filename);
            array_push($names, $filename);
        }

        $portfolio->file = json_encode($names);
    }

    $portfolio->save();

    return redirect()->route('portfolios.index');
}

My routes:
Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::resource('/portfolios', 'PortfolioController');

I hope I've explained properly and if I've left any information out please let me know

A: The problem is that Dropzone will automatically POST your files when you drop them.  But it does not include any other fields in the request it POSTs - just the file.  So your CSRF token is missing (as are all other fields on your form), and Laravel throws an error.
There are a few ways around that.  Perhaps simplest here is to add the CSRF token to the data POSTed in your sending() even handler.  The Dropzone docs even mention doing exactly this:

... you can modify them (for example to add a CSRF token) ...

So, in your code:
// First, include the 2nd and 3rd parameters passed to this handler
myDropzone.on("sending", function(file, xhr, formData) {

    // Now, find your CSRF token
    var token = $("input[name='_token']").val();

    // Append the token to the formData Dropzone is going to POST
    formData.append('_token', token);

    // Rest of your code ...
    document.querySelector("#total-progress").style.opacity = "1";
    file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});

Note though that your CSRF token, which is still on the form unchanged, is now invalid - the POST request just handled means it will have updated.  The next file you drop will re-use the same token and it will fail.
A more complete solution is to disable sending of files completely until you hit your submit button, then send all files and all form fields at once.  To do that, you must disable autoProcessQueue:
autoProcessQueue = false,

Next, since the queue is not autoprocessed, you must now manually process it, by firing processQueue(), when you submit your form.  You need some kind of event handler to fire when your form is submitted:
// Event handler to fire when your form is submitted
$('form').on('submit', function(e) {
    // Don't let the standard form submit, we're doing it here
    e.preventDefault();

    // Process the file queue
    myDropzone.processQueue();
});

And finally, you need to add your CSRF token and any other fields in your form to the data Dropzone will POST:
myDropzone.on("sending", function(file, xhr, formData) {

    // Find all input values on your form
    var data = $('form').serializeArray();

    // Append them all to the formData Dropzone will POST
    $.each(data, function(key, el) {
        formData.append(el.name, el.value);
    });

    // Rest of your code ...
    document.querySelector("#total-progress").style.opacity = "1";
    file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});

A: Your form is missing enctype for file updloads,the enctype attribute specifies how the form-data should be encoded when submitting it to the server. so add that attribute to your form:
<form action="/action_page_binary.asp" method="post" enctype="multipart/form-data">
adn specify the method as post also !


text:
Q: Get cell address of a defined cell in excel by excel formula If lets say I define cell "B6" name as value_date
How can i get cell address "B6" from a excel formula ?

A: If by "define cell B6 as value_date" you mean that you create a named range that refers to B6 and has the range name "value_date", then you can use this formula to return the address of the named range:
=CELL("address",value_date)
Be aware that if the named range contains more than one cell, this formula will return the address of the top left cell of the range.
In the screenshot below, cell C6 has the formula as per above.

Edit after comment:
If the range name is stored as text in a cell, you can use the Indirect() function to evaluate the cell text as a range.
=CELL("address",INDIRECT(A1))

To get the row of value_date via the text in cell A1, use =row(indirect(A1))

A: This should work:
=ADDRESS(ROW(value_date),COLUMN(value_date))


text:
Q: Сохранение полного пути текущей директории в переменную Как в postgresql в sql-скрипте сохранить полный путь текущей рабочей директории в переменную или в таблицу?
Знаю, как вывести на экран('! pwd'), но не знаю, как сохранить этот полный путь.

A: Все-таки удалось самому придумать. Ниже код
DROP TABLE tbl_pwd;
CREATE TABLE tbl_pwd(
    pwd TEXT
);

\COPY tbl_pwd FROM PROGRAM 'pwd';
SELECT * FROM tbl_pwd;

A: Если под юниксом, то вот так можно:
postgres=# \! pwd
/home/postgres

postgres=# \set dir `pwd`
postgres=# \echo :dir
/home/postgres

Вот что говорит на эту тему документация (по-русски, по-английски):

Метакоманды
...
Текст аргумента, заключённый в обратные кавычки (`), считается
  командной строкой, которая передаётся в командную оболочку ОС. Вывод
  от этой команды (с удалёнными в конце символами новой строки) заменяет
  текст в обратных кавычках.


text:
Q: Python cross platform If I create a gui for windows using python 2.6 and Qt, and then want to running in solaris or linux world.
What do I need on both systems, I'm guessing 2.6 and Qt for both platforms.
Is this correct or would there be a better solution.
If wxpython, the same right?

A: To run a Python application, one obviously need to have the Python interpreter installed, usually at least the same version used for developement (but sometimes you didn't use features new to that version, so the code is backwards-compatible). A newer version should work, too - only Python 3 isn't backwards compatible to 2.x versions.
Also, all third party libraries need to be installed, of course. So if your GUI uses PyQt, users need PyQt installed. If you use wxPython, users need wxPython installed.
Apart from that, it is possible, although much harder than with certain other languages, to break compability with other platforms, especially when dealing with files and paths manually (e.g. joining an absolute with a relative path with "\\" instead of using the cross-platform os.path.join).
It is possible (and especially for applications aimed at casual users, especially on Windows) to "freeze" a Python program and libraries it uses into an executable file (ideally without dependencies, I don't know if that's always the case in practice). There are a few tools that work for one platform, and the supposedly cross-platform cx_Freeze. Although I don't know if one can produce a Linux executable on a windows machine...


text:
Q: PHP login page using session variable I am new to php, and trying to create a login page through session without using database, if user successfully logs in, it will be redirected to some page "portfolio.php" and then session will expire after 15 mins but if user randomly types the "portfolio.php" as url it will be redirected to the login page. it should only redirect to that page ("portfolio.php") after the user has login successfully.
here is my "login.php" page code:
 <?php
session_start();
include("functions.php");
$message="";
if(count($_POST)>0) {
    if( $_POST["user_name"] == "admin" and $_POST["password"] == "admin-1") {
        $_SESSION["user_id"] = 1001;
        $_SESSION["user_name"] = $_POST["user_name"];
        $_SESSION['loggedin_time'] = time();

    } else {
        $message = "Invalid Username or Password!";
    }
}
if(isset($_SESSION["user_id"])) {
    if(!isLoginSessionExpired()) {
        header("Location:portfolio.php");
    } else {
        header("Location:logout.php?session_expired=1");
    }
}
if(isset($_GET["session_expired"])) {
    $message = "Login Session is Expired. Please Login Again";
}
?>

portfolio.php code:
<?php
session_start();
include("functions.php");
if(isset($_SESSION["user_id"])) {
    if(isLoginSessionExpired()) {
        header("Location:logout.php?session_expired=1");

    }
 }

?>

funcation.php code:
<?php
function isLoginSessionExpired() {
    $login_session_duration = 10;
    $current_time = time();
    if(isset($_SESSION['loggedin_time']) and isset($_SESSION["user_id"])){
        if(((time() - $_SESSION['loggedin_time']) > $login_session_duration)){
            return true;
        }
    }
    return false;
}
?>

Thanks in advance.

A: I see you haven't set any check in portfolio.php file.
Try to check if session login is valid for every php page you create. For example add a session helper in your functions.php file:
function session_helper() {
  if(isset($_SESSION["user_id"])) {
      if(isLoginSessionExpired()) {
        header("Location:logout.php?session_expired=1");
      }
      // check valid user id?
      // session is fine, let the code continue
  } else {
    // no session user_id so redirect to login or
    // any other welcome page

    header("Location:login.php");
  }

}

then you could use that method in all your files, including the portfolio.php:
<?php
    session_start();
    // the new functions.php file
    include("functions.php");
    session_helper();

    // more code
?>

If you are planning to do a php application, you can consider using a Php Framework which handles a lot of stuff for you and cares about security issues you may not be aware of, as well as providing built-in safer user authentication.

A: I have seen your code...
You should change $login_session_duration = 10; to   $login_session_duration = 900; for 15 mins
and your portfolio.php should be:
<?php
session_start();
include("funcation.php");
if(isset($_SESSION["user_id"])) {
    if(isLoginSessionExpired()) {
        header("Location:login.php?session_expired=1");
    }
 } else {
     header('Location:login/index(ur html input file)');
 }

?>


text:
Q: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() while using csr_matrix I have 4 sparse matrixes with following dimensional:
X_train_content_sparse.shape
(62313, 100000)

X_train_title_sparse.shape
(62313, 100000)

X_train_author_sparse.shape
(62313,31540)

X_train_time_features_sparse.shape
(62313, 7)

And then I stack arrays in sequence horizontally.
X_train_sparse = hstack([X_train_content_sparse, X_train_title_sparse,
                                    X_train_author_sparse, X_train_time_features_sparse])

After that I transform this array of sparse matrixes into a sparse matrix.
I apply csr_matrix(X_train_sparse) and I receive such error:

ValueError: The truth value of an array with more than one element is
  ambiguous. Use a.any() or a.all().

>X_train_sparse
array([ <62313x100000 sparse matrix of type '<class 'numpy.float64'>'
    with 68519885 stored elements in Compressed Sparse Row format>,
       <62313x100000 sparse matrix of type '<class 'numpy.float64'>'
    with 795892 stored elements in Compressed Sparse Row format>,
       <62313x31540 sparse matrix of type '<class 'numpy.uint8'>'
    with 62313 stored elements in Compressed Sparse Row format>,
       <62313x7 sparse matrix of type '<class 'numpy.int64'>'
    with 176241 stored elements in Compressed Sparse Row format>], dtype=object)

A: In [83]: M
Out[83]:
<10x10 sparse matrix of type '<class 'numpy.float64'>'
    with 20 stored elements in Compressed Sparse Row format>
In [84]: np.hstack([M,M])
Out[84]:
array([<10x10 sparse matrix of type '<class 'numpy.float64'>'
    with 20 stored elements in Compressed Sparse Row format>,
       <10x10 sparse matrix of type '<class 'numpy.float64'>'
    with 20 stored elements in Compressed Sparse Row format>], dtype=object)
In [85]: sparse.csr_matrix(_)
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

That was the wrong hstack.  The np.hstack knowns nothing about sparse matrices.  So it just wraps each one in object array, and joins them into a 2 element array.  So it's not surprising that csr_matrix has problems digesting that.
In [86]: sparse.hstack([M,M])
Out[86]:
<10x20 sparse matrix of type '<class 'numpy.float64'>'
    with 40 stored elements in COOrdinate format>

The sparse.hstack converts all matrices into coo format, and then joins their rows,cols,data arrays appropriately, and then makes a new sparse matrix.
sparse.hstack with format parameter:
In [88]: sparse.hstack([M,M],format='csr')
Out[88]:
<10x20 sparse matrix of type '<class 'numpy.float64'>'
    with 40 stored elements in Compressed Sparse Row format>


text:
Q: Как в регулярном выражении игнорировать символ переноса строки - \n Нужно между тегами заменить е на Ё и z на Z, например.
    String s= "
еееееееееееzzzzzzzzzzzzzz
";
    String startTag = "
";
    String endTag = "
";
    Pattern pattern = Pattern.compile(startTag + "(.*?)" + endTag);
    Matcher matcher = pattern.matcher(s);

    while (matcher.find()) {
        s = s.replace(matcher.group(0), startTag + matcher.group(1).replace("z", "Z").replace("е", "Ё") + endTag);
    }

    System.out.println("\nПосле изменения: \n" + s);

Выводит всё корректно:

ЁЁЁЁЁЁЁЁЁЁЁZZZZZZZZZZZZZZ

СтОит же в условии (в переменную s) добавить \n в любом месте, как реализация перестаёт работать:
        s= "
ееее\nеееееееzzzzzzzzzzzzzz
";

выдаст:

ееее
еееееееzzzzzzzzzzzzzz

т.е. - без изменений.
Что я делаю не так? Не соображу.

*

*На этом сайте нашел похожую статью (Перенос в регулярном выражении), но ответы не проконали.

A: Используйте флаг PCRE_S_DOTALL.
По умолчанию метасимвол . не включает в себя перенос строки и только применение данного флага включает совпадение . с литералом переноса строки.
Pattern.compile( regex, Pattern.S );
Pattern.compile( regex, Pattern.DOTALL );

Оба варианта равносильны.


text:
Q: The cublas function call cublasSgemv Thank for @hubs , when call cublasSgemv should notice that CUBLAS_OP_T is also transpose vector.
/*I am learning cuda and cublas for a month, and I want to test the performance of cublas for further use. But in my matrix-vector multiplication using cublasSgemv , the answer is wrong.
  I initialize Matrix A and Vector x in row-major. I sent them to device using cudaMemcpy, and call the function cublasSgemv , because the A is row-major, I transpose it using a parameter CUBLAS_OP_T.*/
 //the row is 50,and col is 10, A[i]=i;x[i]=1; And A matrix is row major.
 //the answer I get is 45,545,.....4545,0,0,0,0,0,0,0,0,........0

int main(){
int row=50;
int col=10;
int N=row*col;
float*A=new float[N];
float* y_gpu=new float[50];
for (int i=0;i<N;i++)
{
    A[i]=(float)i;
}
float* x=new float[10];
for (int i=0;i<10;i++)
{
    x[i]=1;
}
GpuVec(A,x,y_gpu,row,col);  //call the function
    for(int i=0;i<50;i++){
    cout<<" "<<y_gpu[i]<<endl;  //
}

return 0;

}
int GpuVec(const float* A,const float* x, float* y,const int row,const int col){
cudaError_t cudastat;
cublasStatus_t stat;
int size=row*col;
cublasHandle_t handle;
float* d_A;  //device matrix
float* d_x;  //device vector
float* d_y;  //device result
cudastat=cudaMalloc((void**)&d_A,size*sizeof(float));
cudastat=cudaMalloc((void**)&d_x,col*sizeof(float));
cudastat=cudaMalloc((void**)&d_y,row*sizeof(float));// when I copy y to d_y ,can I cout d_y?

cudaMemcpy(d_A,A,sizeof(float)*size,cudaMemcpyHostToDevice);  //copy A to device d_A
cudaMemcpy(d_x,x,sizeof(float)*col,cudaMemcpyHostToDevice);   //copy x to device d_x
float alf=1.0;
float beta=0;
    stat=cublasCreate(&handle);
stat=cublasSgemv(handle,CUBLAS_OP_T,col,row,&alf,d_A,col,d_x,1,&beta,d_y,1);//swap col and row
cudaMemcpy(y,d_y,sizeof(float)*row,cudaMemcpyDeviceToHost); // copy device result to host
cudaFree(d_A);
cudaFree(d_x);
cudaFree(d_y);
cublasDestroy(handle);
return 0;

}

A: To use two-dimensional arrays stored in row-major order in cublas (that works with column-major order) you can call the gemv in this way.
stat = cublasSgemv(handle, CUBLAS_OP_T, col, row, &alf, d_A, col, d_x, 1, &beta, d_y, 1);

You have to swap m (rows) and n (columns) in the call, too, to perform y = A * x, but it allows you to use the cublas call without transposing the original array.


text:
Q: jquery Iframe src attribute Why does x alerts undefined for iframe but works for embed. I'm grabbing the iframe or embed code from a textarea
<iframe src="http://www.youtube.com/embed/9kiWvkj2ldWiU?hd=1"></iframe>

var textarea = $('#embedModal textarea'),
textareaValue = textarea.val(),
$embed = $($(textareaValue).find('iframe')),
x = $embed.attr('src');
alert(x); //alerts undefined for iframe

If you change find('iframe') to find('embed') and you try with the below embed code. then i'm able to get the value of src, but with iframe i get undefined. Seems strange.
<embed src="http://www.youtube.com/embed/9kiWvkj2ldWiU?hd=1"></embed>

A: Iframe and embed are not the same tag, why would you be able to find them both with the same selector.

A: If your iframe is for a different domain, the browser will block any interaction between its contents and your Javascript. This cross-domain separation is to prevent phishing and the like.

A: Nevermind. find('iframe') is not really needed. it works without.


text:
Q: Can I store duplicated strings in a string array? In my Android app I have a String[].

If I have 2 of the same Strings, like:
String a = "abc";
String b = "abc";

Can I store both Strings a and b in the same String[]?

A: Yes, you can add the same string text to two entries in a string array.
String[0] = "abc" and
String[1] = "abc"are perfectly fine


text:
Q: How can I execute a subset of tests in OpenLiberty dev mode In order to execute the whole test suite you only have to press enter key in dev mode.
But how to execute one only test or a subset of the whole test suite?

A: Since dev mode dynamically loads pom.xml changes, one approach would be to dynamically edit the pom.xml configuration and then hit <Enter>  e.g.:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>

            <configuration>
                <test>BonusPayoutIT#testForceFailure</test>
            </configuration>

        </plugin>


text:
Q: Allow user when registered to browse to username.host.com I am using Asp.net MVC3 and C# and IIS 7.5. I want that once user is registered he can browse my site using username.host.com and this username should be available to me in my URL so I can show the data related to that particular username only. All the logic is the same for all users. I don't want to do any fancy thing like if user1.host.com is entered then I want to redirect to a separate controller and action etc. All the application logic is the same for all users. I just want to change the way the url is shown in the browser.
Also, if possible I want this to work on localhost also in IIS/Cassini.
Eg: If I browse to jaggu.localhost:19883. It should send me to localhost:19883/Home/index/Jaggu (because by default Home is the controller and index is the method)
I am completely clueless on how to achieve this. Any help would be appreciated.

A: You may need a star A record, like *.host.com that points to your host.com site.
On your default page (or elsewhere via something like an IHttpModule) reroute the request to where you want the registered user to land.
Google: URL Rewriting for more information.


text:
Q: Set up authorization for user roles nested in groups I am working on a project where I am using role authorization for the first time and I can't get it to work.
The thing is that the project is set up in a way that when a new user is created, they are added to a group. These groups contain one ore more roles.
For example the group "ReadOnly" contains the roles "userReadOnly" and "groupsReadOnly" (this user can go in to the pages user and groups, see the data, but not edit it)
The part that I do get is the [Authorize(Roles = "..., ...")] in the controllers and @if(user.IsInRole("...") in the views, but when I add this to the project things stop working. I know I need to create a custom AccountRoleProvider, but here I get stuck. I don't understand how to do this and I don't understand how to adapt the (standard)providers that are found online to fit my project. A nudge in the right direction, or an explanation of what the provider actually does would be very much appreciated.

A: To create a custom authorization filter you need to create a folder in your solution and add a file named AuthorizedRoles.cs inside it.
AuthorizedRoles.cs file as:
 sealed class AuthorizedRoles : ActionFilterAttribute
    {
       public string Roles { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var status = false;
            string[] roles = Roles.Split(',');
            var currentUserRole = Session.UserRole; // Get here the role of the user
            var Role = "";
            switch (currentUserRole)
            {
                case 1:
                    Role = "Role1";
                    break;
                case 2:
                    Role = "Role2";
                    break;
                case 3:
                    Role = "Role3";
                    break; // Check here for more role
                default:
                    break;
            }

          if (Role != ""){
                foreach (var role in roles)
                {
                    if (role.Contains(currentRoleName))
                    {
                        status = true;
                    }
                }
            }

      if (status == false)//That means user is not in the role, so redirect it to the new controller returning a view showing information that you are not autorized
            {
              if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    //The request can be ajax callso it will redirect to another ajax method
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "ControllerName",
                        action = "AjaxActionName",
                        area = ""
                    }));
                }
                else
                {
           filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "ControllerName",
                        action = "ActionName",
                        area = ""
                    }));
}
         }
      base.OnActionExecuting(filterContext);
        }

}

The redirection methods will be like;
public ActionResult ActionName()
        {
            return View(); //Create view for this action
        }

public JsonResult AjaxActionName()
        {
            return Json(new { status = false, message = "Unauthorized access." }, JsonRequestBehavior.AllowGet);

        }

Above any method where you want a check can be used to call custom authorization filter :
//This method will execute only if the user have Role1 and Role2 other wise redirected to other no permission methods before the action executes.
  [AuthorizedRoles(Roles = "Role1,Role2")]
        public ActionResult NeedPermissionAction(int id)
        {

}


text:
Q: insert symbols into mysql using php I have this web service
http://www.example.com/addregisteredusers.php?emailId=test@tets.com&userName=
php code:
    $emailId=$_REQUEST['emailId'];
$userName=$_REQUEST['userName'];

    $insertDetails=mysql_query("INSERT INTO `registration` (`userName`, `emailId`) VALUES ('$userName', '$emailId')");

when go to database the userName field is empty.

A: I have created table with fields like below screens
Structure of table

Datas in the table

I have used this code.
     $emailId = mysql_real_escape_string($_REQUEST['email']);
$userName = mysql_real_escape_string($_REQUEST['uname']);

mysql_query("INSERT INTO `new` (`userName`, `emailId`) VALUES ('$userName', '$emailId')") or die(mysql_error());

A: i solved the problem by change table and field charset from utf8 to utf8mb4

A: please run this one
$insertDetails = mysql_query("INSERT INTO `registration` (`userName`, `emailId`) VALUES ('".$userName."', '".$emailId."')");


text:
Q: Enterprise Keywords required in Publishing page I have added the enterprise keyword column to my custom content type that is tied to a publishing page. It works fine editing and publish pages based on this layout  unless I set the keyword column to be required. If I do this I get an error message when pressing the Publish action stating "You must fill out all required properties before completing this action." and then I get transfered to edit properties for the page. It works fine if I save the page first and then publish it.
The control on my page layout looks like this:
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
  <Taxonomy:TaxonomyFieldControl ID="TaxonomyFieldControl" FieldName="TaxKeyword" runat="server" />
</asp:Content>

Have someone stumbled upon this problem before?

A: You can find a solution here:
http://www.itidea.nl/index.php/what-about-you-must-fill-out-all-required-properties-before-completing-this-action-when-publishing-a-page/
The solution requires a custom control on the page, the code is provided in the post.
Regards, Anita