text:
Q: чиститься строка (а точнее lineEdit) в калькуляторе после нажатия на другую кнопку. Заранее спасибо! При создание калькулятора на python (графического) возникла проблема.
При повторном нажатии на ту же самую кнопку (допустим ноль) то строка очищалось и выводило опять 0.
Так же и случалось если ввести 2 цифры первая стирается а 2 появляется на месте 1
вот этот код:
from PySide import QtCore, QtGui
import sys
from ui import Ui_Dialog

#Creat application
app = QtGui.QApplication(sys.argv)

#Creat from Ui and init UI
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()

#hook logic

def numbers_logic():
    def bp():
        ui.lineEdit.setText( "0" )
    ui.pushButton_10.clicked.connect(bp)
    def bp2():
        ui.lineEdit.setText( "1" )
    ui.pushButton.clicked.connect(bp2)
    def bp3():
        ui.lineEdit.setText( "2" )
    ui.pushButton_2.clicked.connect(bp3)
    def bp4():
        ui.lineEdit.setText( "3" )
    ui.pushButton_3.clicked.connect(bp4)
    def bp5():
        ui.lineEdit.setText( "4" )
    ui.pushButton_4.clicked.connect(bp5)
    def bp6():
        ui.lineEdit.setText( "5" )
    ui.pushButton_5.clicked.connect(bp6)
numbers_logic()

#Run mane loop
sys.exit(app.exec_())

"""

A: Решение вопроса, как написал @gil9red, заключается в замене строки
ui.lineEdit.setText("0") на text = ui.lineEdit.text()  + "0"
и ui.lineEdit.setText(text), так как setText очищает предыдущий текст.


text:
Q: Java hibernate No validator could be found for boolean I have a service method that tries to add an object with store() method of hibernate. get method is working for this DAO and service class whereas adding not working. In console there is no error.
UrlWhiteListDaoImpl urlDao;

MapperFacade mapper;

@Autowired
public UrlWhiteListingServiceImpl(UrlWhiteListDao urlWhiteListDao, MapperFacade mapper, UrlWhiteListDaoImpl urlDao) {
    this.urlDao = urlDao;
    this.urlWhiteListDao = urlWhiteListDao;
    this.mapper = mapper;
}

@Override
public UrlWhiteListDto addUrlWhiteListItem(UrlWhiteListDto urlWhiteListDto) throws Exception {
    String domainUrlToBeAdded = parseUrl(urlWhiteListDto.getDomain());
    if (isDomainExistbyName(domainUrlToBeAdded)) {
        throw new Exception("Already existed domain is tried to be added");
    }
    UrlWhitelist urlModel = mapper.map(urlWhiteListDto,UrlWhitelist.class);
    urlDao.store(urlModel);
    return urlWhiteListDto;

}
My model class is:
@Entity
@Table(name = UrlWhitelist.TABLE_NAME)
public class UrlWhitelist implements EntityBean {

    public static final String TABLE_NAME = "URL_WHITE_LIST";

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false)
    private Long id;

    @NotBlank
    @Column(name = "DOMAIN", nullable = false)
    private String domain;

    @NotBlank
    @Column(name = "DISABLE", nullable = false)
    private boolean disabled;

    // getters & setters omitted
}

And DAO implementation class is:
public class UrlWhiteListDaoImpl extends EntityDaoImpl<UrlWhitelist, Long> implements UrlWhiteListDao {

    protected UrlWhiteListDaoImpl() {
        super(UrlWhitelist.class);
    }

    @Override
    public List<UrlWhitelist> getByDomainName(String name) {
        DetachedCriteria criteria = DetachedCriteria.forClass(UrlWhitelist.class);
        criteria.add(Restrictions.eq("domain", name));
        return getAllByCriteria(criteria);
    }
}

In console there is no error but in server log it says:

SEVERE: Servlet.service() for servlet [services] in context with path [] threw exception [Request processing failed; nested exception is javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'org.hibernate.validator.constraints.NotBlank' validating type 'java.lang.Boolean'. Check configuration for 'disabled'] with root cause
      javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'org.hibernate.validator.constraints.NotBlank' validating type 'java.lang.Boolean'. Check configuration for 'disabled'

I thought there is something wrong with mapping between to and model class, but, then why get method is working and only store() is not working? What is the solution ?

A: You should use the @NotNull annotation.
Your boolean is a primitive type, not an object type (Boolean) hence the constraint @NotNull cannot be applied since the primitive type cannot be null. The annotation performs the following validation (formatting added by me):

The annotated element must not be null. Accepts any type.

Use the object type:
@NotNull
@Column(name = "DISABLE", nullable = false)
private Boolean disabled;

A: to solve this error you MUST use correct annotations. In the above problem, @NotBlank annotation must be applied to any String field only.
To validate boolean type field, use annotation @NotNull or use Boolean boxed type

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retain only last N bytes of pipe? I'm piping data from a socket to a file. If I need to save all the data, this is easy enough:
$ nc -l 5001 > file.bin

If I want to save only the first n bytes, that's easy enough as well:
$ nc -l 5001 | pv -Ss 2M > file.bin

Is there a way I can pipe the data to a file with a fixed maximum size, such that when new data arrives it displaces the old data in the file like a queue? Perhaps using a fixed-size named pipe if such a thing exists.
Ideally this would run continuously and not require saving all of the file, then chopping it. In other words I don't want to simply run tail after the whole file is saved.

A: For n = 2M, use this:
nc -l 5001 | tail -c 2M > file.bin

Or use this:
nc -l 5001 | tail -c 2097152 > file.bin

A: So, do I get it right that you want to be able to view the last N bytes at any time, without having to store significantly more than that?
If you want that in actual real-time, as in byte-by-byte, you'll probably need some dedicated software for it. Often, one would store the latest data in a ring buffer, but you probably couldn't find software that could read data arranged like that from a file. Another option would be to just write all the data to a file the normal way, and periodically tell the OS to discard the earlier data that's no longer needed. (I think I saw a comment suggesting that earlier, but maybe it was deleted.)
You could probably do that with a Perl script that fallocate to do the discarding.
If you don't need the very latest data, a quick and dirty shell solution would store fixed chunks in a file, renaming the file to another name between each chunk. The latest complete chunk would then be always available in the second file.
E.g.
i=0
while true; do echo $i; sleep .1; i=$((i+1)); done |
    while true; do
        head -10 > out1
        mv out1 out2
    done

The first loop produces some test output, while the second reads chunks of 10 lines so that the last complete chunk is in out2 and the last partial chunk in out1. Change the argument to head as needed.
Note that with a small chunk like that, output buffering in head will make out1 always appear empty. Use stdbuf -o0 head ... instead if that's an issue.


text:
Q: in mysql is it possible to sort results using one columns of a table if not empty or another table column I have those two tables, Artist and Pseudonym, Artist belongsTo Pseudonym
I'd like to join the two tables and sort the result on Artist.lastname. Now, if he has a pseudonym, the pseudonym should be used, like in the example below, Balthus is between BACON and CHAGAL, even if his lastname starts with K
Artist.Lastname     Pseudonym.name
BACON
KLOSSOWSKI          Balthus
CHAGAL
CEZANNE

Is it possible to make a virtual column that has the pseudo if not empty or the lastname, and then sort on that column?
SELECT .....
FROM Artists as a
LEFT JOIN Pseudonyms as p ON (a.pseudonym_id = p.id)
ORDER BY the_virtual_column

A: Try this:
SELECT .....
  FROM Artists as a LEFT JOIN Pseudonyms as p
    ON (a.pseudonym_id = p.id)
 ORDER BY COALESCE(p.name , a.Lastname)

A: ...ORDER BY COALESCE(p.name, a.Lastname)


text:
Q: Deploy files in Magento2 while theme developement When developing, do I need to clear caches everytime I change a file?
I have set my env to developer with
$ php bin/magento deploy:mode:set developer
Magento now build Symlinks to my themes file for each file that has to be loaded. However, if I make a change to a *.css file and save it, no changes are made.
Therefore I delete the whole cache everytime I change something, which is quiet a pain.
I do so with:
$ rm -rf var/page_cache/* var/cache/* var/view_preprocessed/* pub/static/frontend/* var/tmp/*
Logically Magento has to rebuild all this stuff. This is time consuming. How can I speed up things? Can I delete specific files directly and if so, where do I find them?
My Cache Settings are:
Current status:
                        config: 0
                        layout: 0
                    block_html: 0
                   collections: 1
                    reflection: 1
                        db_ddl: 1
                           eav: 1
         customer_notification: 1
                     full_page: 0
            config_integration: 1
        config_integration_api: 1
                     translate: 1
             config_webservice: 1

A: This was pretty easy. Just delete the CSS folders, nothing else.
rm -rf var/page_cache/* var/cache/* var/view_preprocessed/css/frontend/Vendor/Theme/de_DE/css/* pub/static/frontend/Vendor/Theme/de_DE/css/* var/tmp/*
Loads fast, works nice. JS doesnt need a clean cache, since it does symlinks, as said.


text:
Q: Setting width of all columns in dataTable I am showing data in table format using dataTable in JSF page using JSF2.0. Below is the code that I have.
<h:dataTable id="patentBudgetList" var="patentBudgetList" value="#{PersonalInformationDataBean.budgetInfoList}"  border="1" width="40%">
    <h:column>
        <f:facet name="header">
            <h:outputText value="Description" />
        </f:facet>
        <h:outputText value="#{patentBudgetList.budgetTitle}"/>
    </h:column>
    <h:column>
        <f:facet name="header">
            <h:outputText value="Cost" />
        </f:facet>
        <h:outputText value="#{patentBudgetList.budgetCost}"/>
    </h:column>
</h:dataTable>

What I want is to set the width of Description column to 80% and set  width of column Cost to 20%.
Any idea how to get this done?

A: Below is how I did...
<h:dataTable id="patentBudgetList" var="patentBudgetList"
 value="#{PersonalInformationDataBean.budgetInfoList}"
 border="1" width="40%"
 columnClasses="setWidthOfFirstColumn,setWidthOfSecondColumn"
>
    <h:column>
        <f:facet name="header">
            <h:outputText value="Description" />
        </f:facet>
        <h:outputText value="#{patentBudgetList.budgetTitle}"/>
    </h:column>
    <h:column>
        <f:facet name="header">
            <h:outputText value="Cost" />
        </f:facet>
        <h:outputText value="#{patentBudgetList.budgetCost}"/>
    </h:column>
</h:dataTable>

And in css I have
.setWidthOfFirstColumn {
    width: 80%;
}

.setWidthOfSecondColumn {
    width: 20%;
}


text:
Q: Changing attribute type - data bind Spring MVC Form Let's say I have the following:
Hibernate:
@Entity
@Table(name = "users")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "companyId")
    private Integer companyid;

My JSP:
<form:form commandName="user" id="userForm">
<form:input path="name" />
<form:input path="companyId" />

Now I would like to show the company name in the text field rather than its id.
And when I submit the form, at some point, I query the company id by providing its name to populate and persist the entity. I want to be able to do the other way around.
Is it possible?

A: One option is to hide the companyId in your jsp:
<form:form commandName="user" id="userForm">
<form:input path="name" />
<form:hidden path="companyId" />
<form:input path="companyName" />

With this, you will be able to show companyName in your JSP and to receive both in your controller.


text:
Q: Count data for 15 minute intervals that are grouped by date I have the following MySQL table:
+---------------------+-----------+
|      timestamp      | sensor_id |
+---------------------+-----------+
| 2010-04-09 01:42:31 |    M049   |
| 2010-04-09 01:43:31 |    M049   |
| 2010-04-09 01:44:31 |    M049   |
| 2010-04-09 01:59:31 |    M049   |
| 2010-04-10 01:10:31 |    M049   |
| 2010-04-10 01:40:31 |    M049   |
| 2010-04-10 01:42:31 |    M049   |
| 2010-04-11 16:43:31 |    M049   |
+---------------------+-----------+

I know how to query the db to get a count of the entries for a specific daytime intervall and group the result by date.
An example to query the event count between 1 am and 2 pm would look like this:
SELECT
    date(timestamp) as date,
    count(timestamp) as count
FROM
    event_data
WHERE
    EXTRACT(HOUR FROM TIME(timestamp)) BETWEEN 1 AND 14
GROUP BY
    date

The query returns the following table:
+------------+-------+
|    date    | count |
+------------+-------+
| 2010-04-09 |   4   |
| 2010-04-10 |   3   |
+------------+-------+

Now I only want to count an event every 15 minutes.
The desired result would be:
+------------+-------+
|    date    | count |
+------------+-------+
| 2010-04-09 |   2   |
| 2010-04-10 |   2   |
+------------+-------+

How do I alter my query to get these results?

A: You have a good start to group by date and query for the hours you want. Similarly, you can write a query that gets the intervals. I would start by writing a case statement that reads each row you want, and adds a column specifying which interval of the hour it is. (0:14 - 1, 15:29 - 2...) like this:
SELECT timeCol,
  HOUR(timeCol) AS hour,
  CASE WHEN MINUTE(timeCol) BETWEEN 0 AND 14 THEN 1
  WHEN MINUTE(timeCol) BETWEEN 15 AND 29 THEN 2
  WHEN MINUTE(timeCol) BETWEEN 30 AND 44 THEN 3
  ELSE 4 END AS minute
FROM myTable;

This gives you something like this:
|      timeCol        | hour | minute |
+---------------------+------+--------+
| 2010-04-09 01:42:31 |  1   |   3    |
| 2010-04-09 01:43:31 |  1   |   3    |
| 2010-04-09 01:44:31 |  1   |   3    |

Once you have that, you can select the distinct hour/minute pairs in each day, and that will give you what you want, as long as you use your WHERE clause accordingly:
SELECT DATE(timeCol) AS dateCol, COUNT(DISTINCT hour, minute) AS numEvents
FROM(
  SELECT timeCol,
    HOUR(timeCol) AS hour,
    CASE WHEN MINUTE(timeCol) BETWEEN 0 AND 14 THEN 1
    WHEN MINUTE(timeCol) BETWEEN 15 AND 29 THEN 2
    WHEN MINUTE(timeCol) BETWEEN 30 AND 44 THEN 3
    ELSE 4 END AS minute
  FROM myTable) tmp
WHERE HOUR(timecol) BETWEEN 1 AND 14
GROUP BY dateCol;

Here is an SQL Fiddle example.
I would just like to add that you don't have to record the intervals as 1, 2, 3, 4. Make sure you use something readable, that will make sense to you again in the future. For example, maybe something like this would be better:
WHEN MINUTE(timeCol) BETWEEN 0 and 14 THEN 'firstInterval'...


text:
Q: I have already used job table and model Laravel 5.6
In my project there is a table named "jobs" and
Model named "Job".
Now i want to use  Laravel Queues,
But migration will make job table and model which i have already taken.
So how to tackle this situation?
Somebody help!
Thanks in advance.!

A: 1) Run php artisan queue:table
2) Update the table name to a new name in the created migration and run migration using php artisan migrate
3) You can edit the job table name inside config/queue.php :
'connections' => [
    ...
    'database' => [
        'driver' => 'database',
        'table' => 'your_jobs_table',
        'queue' => 'default',
        'expire' => 60,
    ],
]


text:
Q: OSRM doesn't show actual route while plotting from osrm-backend JSON response While trying to test routing using OSRM Demo server I sent GET request with the following url:
http://router.project-osrm.org/route/v1/driving/90.4007354,23.7936502;90.3925568,23.7746739?steps=true
When I plot the intersections on a web map with OpenStreetMap tiles in the background I get the following route.:

But when I use the same cordinate in the OSRM Demo Server's front-end I get the following route:

I have also check that the JSON response from the OSRM Demo Server's front-end which is the same as the response from the url I requested. From the first screenshot we can see that the while routing the flyover is being ignored and the starting and the ending point of flyover are being connected with a straight line when plotted but that is not the case for the OSRM Demo Server's front-end. What am I doing wrong? Can anybody please help?

A: The difference is that you plot only the intersections, whereas the OSRM Demo Server plots the whole route.
To plot the whole route, use the geometry element in routes[0] in the JSON. The route is encoded using Google's polyline algorithm.
If you want the route as GEOJSON linestring instead of the encoded polyline, add &geometries=geojson to your request.


text:
Q: Foreign language meta questions shouldn't be migrated This question is about my post that was migrated.
With the arrival of new websites in different languages, I cannot help but to think that it will create some confusion for were the issues that are coming with these sites will be addressed.
Every sites are going to have their own meta but issues might be discovered outside the boundaries of that website so it might make it difficult for users to address the found issue in a foreign language.
In any different sites, it works since it is all the same language so it might be addressed anywhere and since English is Stack Exchange's primary language, it will be understood no matter where you migrate it. But migrating my question to another website might be causing a few issues :

*

*The language of the question will not be understood by all users

*It will make a various language website

*Comments and answer in a different language won't make sense to the users

*It will create mutli-language questions where you only understand part of the post

I can already see the comments telling me that the question wasn't asked on the right site and that it is my job to make sure I post it on the right site... I agree... But not for these site no.

*

*I cannot address an issue in a language I do not understand

*I will not simply try to use a translator that might make my question barely understandable

This is going to create a few problems with the bug / feature requests and stuff. I do not speak Portuguese but I can find plenty bugs on the site and report them so the fact that shouldn't go on that website in the first place isn't a valid argument in my opinion.

A: I cannot say for other SE sites, but in Stack Overflow em Português, I believe that you can feel free to ask and answer in english (on meta, of course), and we will do the best effort to translate it properly and keep both versions. Dealing with the problems outside of "our" meta (pt) will cause redundant reports, split proposals, and we will loose the coordination to solve properly the problem.


text:
Q: 0x89721500 error in Visual Studio 2015 After installing Visual Studio 2015 from previous 2013 update 4 I was not able to deploy my Windows Phone apps to devices getting error 0x89721500.

A: I solved just deleting directory "C:\Users\AppData\Local\Microsoft\Phone Tools\CoreCon\11.0" then restarting Visual Studio.
Hope this helps.


text: Q: How to create raster attribute table to a raster data using gdal python? I classified a remote sensing data and saved it as a raster using Gdal python. I want to create a raster attribute table for this classified result.. my classified raster has five classes with 1,2,3,4,5 representing classes A,B,C,D,E respectively... Is it possible to assign color to each class.. since it is a single band raster image..


text:
Q: how to convert angular js dynamic array into php array and submit array values into new php file can anybody suggest me how to convert angular js dynamic array into php array and then submit value of php array in any new file. in my program i am working in arraytest.php and want to send php array in saveform.php in php format. please anybody help me to do this. thanks

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<form name="myform" action="saveform.php" method="post">

    <input type="text" value="254" ng-model= "input.var1"/>
        <input type="text" ng-model="input.var2"/>
   <button type='button' ng-click='remove(input)'>Remove</button>

    <button type='button' ng-click='add()'>Add</button>

TotalDays = {{getTotal(value)}}

{{ fir_value = dateTimeList.first }}

{{ sec_value = dateTimeList.second }}

                <?php
                 $array1 = array("{{fir_value}}","{{sec_value}}");
                 print_r($array1);
                ?>

     <input type="submit" name="submit" />

</script>

here is another file saveform.php
<?php
echo "output of array is:- ";
extract($_POST);
if(isset($submit))
{
print_r($arr);
}
?>

plnkr demo: http://plnkr.co/edit/20PLT52Ia86UyGClQh7h?p=preview

A: First at all:
You are mixing AngularJS and php but you cant use AngularJS expression in php.
Your code:

{{ fir_value = dateTimeList.first }}

{{ sec_value = dateTimeList.second }}

<?php
$array1 = array("{{fir_value}}","{{sec_value}}");
print_r($array1);
?>

will be parsed into this:

{{ fir_value = dateTimeList.first }}

{{ sec_value = dateTimeList.second }}

array("{{fir_value}}","{{sec_value}}")

And then is AngularJS called. If that is what you want, okay.
by the way, you are closing the bottom scripttag twice
Submitting Forms:
AngularJS will submit forms as json via the $http service and not as key/value pairs like normal forms.
If you want to receive this data with php you have to read the input stream like this:
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

$request will now contain the form data.


text:
Q: Android: IllegalStateException with Navigation Component My app uses android navigation component. There is case where IllegalStateException: Fragment not attached to an activity is logged. I couldn't understand this. The flow is as follows:
The activity_layout has this code:
<androidx.fragment.app.FragmentContainerView
    android:id="@+id/fragment_container"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    app:defaultNavHost="true"
    app:navGraph="@navigation/buy_graph" />

The nav graph contains all fragments in the journey. When a webservice is called, it updates the values in the viewmodel and user proceeds to next step in the journey. From one of the fragments, when this happened the user was supposed to goto other activity, but IllegalStateException was thrown with detail fragmentXXX not attached to the activity. The intent that was to be called was this one:
val intent = Intent(requireActivity(), MatchesActivity::class.java)
intent.putExtra("id", viewModel._id)
startActivity(intent)
requireActivity().finish()

This is not happening everytime. It is logged in crashlytics. The logs are as follows:
Fatal Exception: java.lang.IllegalStateException: Fragment Step8Fragment{e918a72} (0fededbf-6edd-442a-921c-5a33717b712e) not attached to an activity.
   at androidx.fragment.app.Fragment.requireActivity(Fragment.java:928)
   at com.view.fragment.Step8Fragment.onStepCompleted(Step8Fragment.kt:114)
   at com.view_model.ReqViewModel$submitStep5$stepSuccess$1.invoke(ReqViewModel.kt:831)
   at com.view_model.ReqViewModel$submitStep5$stepSuccess$1.invoke(ReqViewModel.kt:37)
   at com.view_model.Repo$submitStepData$responseListener$1.onResponse(Repo.kt:104)
   at com.view_model.Repo$submitStepData$responseListener$1.onResponse(Repo.kt:16)
   at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
   at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
   at android.os.Handler.handleCallback(Handler.java:938)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:223)
   at android.app.ActivityThread.main(ActivityThread.java:7698)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:952)

Not getting any hint why is it happening.


text:
Q: Principal curvature at a given point Compute the principal curvature of the surface$$\frac {x^2}{p}+\frac {y^2}{q}=2z $$ at the point $M(0,0,0)$
Can someone help me with this problem?

A: The following geometric observation should help you to answer your question without long calculations.
Let $S\subset \mathbb{R}^3$ be a smooth\regular surface, $p\in S$ and a unit speed curve $c:(-\epsilon,\epsilon)\to S$ with $c(0)=p$ and $c'(0)=v.$ Then $$\langle c''(0),\nu(p)\rangle=II_p(v,v),$$
where $\nu:S\to S^2$ is the gauss map and $II_p$ the second fundamental form. This implies the following geometric interpretation of the principal curvatures:
For $v\in T_pS$ let $V$ denote the plane going through $p$ and including $v,\nu(p)$ (vectors attached to $p$). Then consider $S\cap V.$ This can be parametrized by a unit speed curve $c_v.$ Let $\kappa_v(p)$ denote the curvature (with respect to the given unit normal vector) of the curve $c_v$ at the point $p.$ Then the principal curvatures are
$$\kappa_1(p)=\min_{v\in T_pM}\kappa_v(p)\text{ and } \kappa_2(p)=\max_{v\in T_pM}\kappa_v(p).$$
So in order to solve your problem try to imagine the surface and make yourself clear that the tangent plane to the origin is the xy-plane and that as a unit normal vector you can choose $\nu(p)=(0,0,1).$ When you intersect your surface with a plane through the origin and the z-axis, you get a smooth curve. The principal curvatures are the minimal and maximal curvatures of all curves obtained by intersecting your surface with such a plane.


text:
Q: Treat String as JavaScript and output variables Assume I have string '${hello} ${love} times'
I would like to replace hello by the variable named hello and love by the variable named love without removing times. I am using ReactJS with JSX.
My attempt is just removing the $, { and } from the string and then deal with it.
var cut = this.props.string.split(" ");
var one = cut[0].split("{");
var two = one[1].split("}");
var thin = this.var[two[0]];

and then use thin

A: Your question is completely unclear... Do you know how ES6 template literals work? You have to use backticks to enable string interpolation, not regular quotes ('' or "").
Is this what you are trying to do?

let hello = 'Hello',
    love = 'LOVE';

console.log(`${hello} ${love} times`);


text:
Q: Process one function and then process another one automatically I'm stuck here

HD

JS 2ND UPDATED:
$(document).ready(function () {
    $(".servidor").on("click",function()  {
        $('.container > #servidores-bg').hide();
        $('#servidores-player').show();
        if ($("#player").length==0)
            $("#servidores-player").append($("",{id:"player",src:$(this).data("url"));
        else
            $("player").attr("src",$(this).data("url")) });
        $('#servidores-player .servidor-info').show();
        var distance = $('#servidores-player iframe').offset().top
        $('html,body').animate({scrollTop:distance},1500);

    });
});

function mostrarServidores() {
    if (document.getElementById('inserido-utilizador')) {

        if (document.getElementById('inserido-utilizador').style.display == 'none') {
            document.getElementById('inserido-utilizador').style.display = 'block';
            document.getElementById('servidores-bg').style.display = 'none';
        }
        else {
            document.getElementById('inserido-utilizador').style.display = 'none';
            document.getElementById('servidores-bg').style.display = 'block';
        }
    }

}

Can someone help me to just create de  tag when I click in the image? And jump to iframe element before it loads?
I already updated the codeuntil the part that i'm getting error

A: *

*you need to replace the iframe if the content is not from the same origin as the page you are on.

*some URLs like google and stackexchange cannot be loaded into an iframe

*Use data- attribute for the URL

$(function() {
  $(".servidor").on("click", function() {
    $('#servidores-bg').hide(); // IDs must be unique
    $("#player").replaceWith(
      $("", {
        id: "player",
        src: $(this).data("url")
      })
    );
    $('#servidores-player .servidor-info').show();
    var distance = $('#servidores-player iframe').offset().top;
    $('html,body').animate({
      scrollTop: distance
    }, 1500);
    $('#servidores-player').show();
  });
});

function mostrarServidores() {
  var $inser = $('#inserido-utilizador');
  if ($inser.length) {
    $inser.toggle();
    $('#servidores-bg').toggle($inser.is(":visible"));
  }
}

      HD

A: If you want to set the iframe src use:
$('#player').attr('src', $(this).data('url'));

And to scroll to it:
$('html, body').animate({scrollTop: $("#player").offset().top}, 2000);

-


text:
Q: why not display correctly bootstrap praragraph in laravel I am using this bootstrap blade view in Laravel. But my view file did not display correctly. That means my @extends('layouts.app') override

@extends('layouts.app')
@section('content')

ABOUT US

Wealth Lanka Management (Private) Ltd (Wealth Lanka or WLM) is a specialized investment banking and financial consultancy firm engaged in feasibility studies , project advisory services, investment banking, capital market and corporate advisory services as well as consultancy services.The main promoters, Messrs Mangala Boyagoda and Asoka Sirimane possess over three decades of local and international expertise in financial and business management, banking and financial services.

@endsection

How can I fix this?
updated
app.blade.php
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="{{asset('favicon.ico')}}">

    <title>Wealth Lanka</title>

    <link href="{{asset('css/bootstrap.min.css')}}" rel="stylesheet">

    <link href="{{asset('css/ie10-viewport-bug-workaround.css')}}" rel="stylesheet">

    <link href="{{asset('css/carousel.css')}}" rel="stylesheet">

        <nav class="navbar navbar-default

              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

              </button>

                  {{--  WEALTH LANKA MANAGEMENT--}}

            {{--
--}}

Home

                  About

About Us

Boad of Ditectors

Senior Team

                    {{--

Nav header

Separated link

One more separated link
--}}

Services

Contact

    @yield('content')


text:
Q: JAXB marshalling into HTML table via XSLT contains empty values I am trying to emulate table generation via xslt. I have these two class models.
Table entry contains rows:
@XmlRootElement(name = "table")
@XmlType(propOrder = { "header", "rows" })
public class TableEntry extends PropertyEntry {

    private String header;

    private final List<TableRowEntry> rows = new ArrayList<TableRowEntry>();

    @XmlElement(name = "row", required = true)
    public List<TableRowEntry> getRows() {
        return rows;
    }

    public String getHeader() {
        return header;
    }

    @XmlAttribute
    public void setHeader(String header) {
        this.header = header;
    }
}

Then I have TableRowEntry model class:
@XmlRootElement(name = "tableRow")
public class TableRowEntry implements Reportable {

    private List<String> cells = new ArrayList<String>();

    @XmlElement(name = "cell")
    public List<String> getCells() {
        return cells;
    }

    public void setCells(List<String> cells) {
        this.cells = cells;
    }
}

and I have this in xsl template
<xsl:for-each select="table">

        <xsl:if test="@header">
            <xsl:value-of select="@header"/>
        </xsl:if>
        <xsl:for-each select="row">

              <xsl:for-each select="cell">
                  <xsl:value-of select="cell"/>
              </xsl:for-each>

        </xsl:for-each>

</xsl:for-each>

Then I do this and I marshall it
TableEntry tableEntry = new TableEntry();
tableEntry.setHeader("This is my header");

TableRowEntry tableRow = new TableRowEntry();
tableRow.setCells(Arrays.asList("cell", "cell2", "cell3"));

TableRowEntry tableRow2 = new TableRowEntry();
tableRow2.setCells(Arrays.asList("cell4", "cell5", "cell6"));

tableEntry.getRows().add(tableRow);
tableEntry.getRows().add(tableRow2);

Whenever I marshall it into HTML, there are empty values in cells, why? When I marshall it into XML, these values in cells are there but I can not select that value in xsl template. Why?
There are two rows with three cells in each row in HTML file but these cells are empty.
I am using eclipse moxy

A: I need to use this to pick that value:
<xsl:value-of select="."/>


text:
Q: name 'get_config' is not defined when i am working with ipython notebook, i want to run a notebook server. I followed the official tutorial  However, when I want to obtain the get_config() function as said in the tutorial, I come across with the name get_config is not defined problem.
I searched the internet and found the page . However, there is no ~/.ipython/profile_default/ipython_config.py  file in my ubuntu 12.04 system. What can I do to solve the problem?

A: Paul Ivanov stated in the forum post:

get_config is available only inside the configuration files at
  load time.

So you can only use get_config in configuration files, not in an ipython session.
You basically have two options:
If you only want to make temporary changes, you can use the %config magic. But note that changes are lost after you exit the session.
The documentation says:

At present, this only affects the current session - changes you make to config are not saved anywhere. Also, some options are only read when IPython starts, so they can't be changed like this.

The second option is to create a new profile. (see ipython profile help). Each profile comes with its own config files. You can find the files by executing:
ls $(ipython locate profile <your-profile-name>)

You can add your configuration options to a specific *_config.py file.
For a further reading, see ipython's config intro.


text:
Q: Difficulty executing a shell script from a python script When I run a shell script in terminal it works as I want it to
In terminal when I type: ./hello.sh
pdflatex runs and the file compiles.  It works perfectly.  pdflatex creates a pdf file and it's all good.
I have a python script in the same directory as the shell script.  When I run that script with a call to the shell script nothing happens
The code does not error out
I've looked through the forums, but this specific question is not addressed
The shell script called hello.sh contains:
#! /bin/bash
pdflatex n1.tex

import subprocess
subprocess.Popen(['/bin/bash', './hello.sh'],shell=True)

All I want to happen is that when I run this python script it executes the shell script and the other program pdflatex creates the pdf document

A: Try the following:
import subprocess
subprocess.run(['/bin/bash', './hello.sh'])

Or alternatively
import subprocess
subprocess.run(['./hello.sh'])

Or even
import subprocess
subprocess.run(['pdflatex', 'n1.tex'])


text:
Q: Apex - application static files not found I have installed recently Apex 19.2
Apex works fine, however my applications don't show any static application files.
I uploaded an image to my workspace app and I insert it in a region as follows :
<img src="#APP_IMAGES#Logo.png" />

When the page loads, the substitution string is parsed and I have an error :
9#GET https://www.example.com:8080/ords/useralias/r/100/files/static/v2/Logo.png 404 (Not Found)
I tried this but it's not working
@apex_epg_config.sql C:\My\01-Tools\04-Apex  (Apex home)

Also here is my standalone.properties file :
jetty.secure.port=8080
standalone.context.path=/ords
standalone.doc.root=C\:\\My\\01-Tools\\03-Ords Installation\\ords\\standalone\\doc_root
standalone.scheme.do.not.prompt=true
standalone.static.context.path=/i
standalone.static.path=C\:\\My\\01-Tools\\04-Apex\\apex\\images
ssl.cert=C\:\\My\\01-Tools\\03-Ords Installation\\ords\\standalone\\certificate\\certificate.der
ssl.cert.key=C\:\\My\\01-Tools\\03-Ords Installation\\ords\\standalone\\certificate\\private.der
ssl.host=www.example.com

All the paths are correct.
Does any know how to solve that please ?
Thanks
Cheers,

A: Are you updating apex and using ords? If so, executing this command might solve your problem.
java -jar ords.war validate

this validates the instalation and the static files.


text:
Q: Strategy Tester Overview Data Extract I was wondering if anybody knows if the values in the Strategy Testing tab, under Overview:

*

*List item

*Net Profit

*Total Closed Trades

*Percent Profitable

*Profit Factor

*Max Drawdown

*Avg Trade

*Avg # Bars in Trade

Are stored in variables somewhere in pine script to be utilized for further analysis and comparison?

A: Some of them are available as strategy.* variables which you will find in the refman. The others need to be calculated as is done in this script: Backtesting & Trading Engine [PineCoders].


text:
Q: Sub functions of a function as a prototype i'm trying to extend the Number object with a function that has two sub-functions. It works fine, except that the sub-functions can't access the Number object value via this and I don't figured out how to access it or if this is possible.
My code looks something like this
var currency = function(prefix) {
    var val = this.toString();
    prefix = prefix || 'R$';

    if(val > 99999) {
        val = val.replace(/(\d+)(\d{3})(\d{2})$/,prefix + " $1.$2,$3");
    } else if(val == 0) {
        val = prefix + ' 0,00';
    } else {
       val = val.replace(/(\d+)(\d{2})$/, prefix + " $1,$2");
    }
    return val;
};

currency.cents = function() {
    var val = this.toString();
    return val == 0 ? '00' : val.substring(val.length - 2);
};

currency.integer = function() {
    var val = this.toString();
    return val == 0 ? '0' : val.substring(0, val.length - 2);
};

Number.prototype.currency = currency;

alert((12345).currency()); // "R$ 123,45"
alert((12345).currency.cents()); // return " }"

The problem is in the line "var val = this.toString();" because this refers to the function itself, not the value of the Number object.
Is there any way to accomplish this?
Second question: Why I need to put ( ) around the number 12345 for this to work? I'm not extending the number object and 12345 is not an instance of it?
Thanks in advance

A: It may not look as nice as what you are trying to do, but you could add all three methods directly to the prototype like this.
var currency = function(prefix) {
    var val = this.toString();
    prefix = prefix || 'R$';

    if(val > 99999) {
        val = val.replace(/(\d+)(\d{3})(\d{2})$/,prefix + " $1.$2,$3");
    } else if(val == 0) {
        val = prefix + ' 0,00';
    } else {
       val = val.replace(/(\d+)(\d{2})$/, prefix + " $1,$2");
    }
    return val;
};

var currencyCents = function() {
    var val = this.currency();
    return val == 0 ? '00' : val.substring(val.length - 2);
};

var currencyInteger = function() {
    var val = this.currency();
    return val == 0 ? '0' : val.substring(0, val.length - 2);
};

Number.prototype.currency = currency;
Number.prototype.currencyCents = currencyCents;
Number.prototype.currencyInteger = currencyInteger;

alert((12345).currency());         // R$ 123,45
alert((12345).currencyCents());    // 45
alert((12345).currencyInteger());  // R$ 123,

And now for your second question..

Why I need to put ( ) around the number 12345 for
  this to work? I'm not extending the number object and 12345 is not an
  instance of it?

I found this question a lot trickier. I found the answer in
Nick Craver's answer to Why don't number literals have access to Number methods? - it's because numbers can have decimals, so surround the number with parenthesis to make it clear that the period is for a function call and not for the decimal portion of the number.


text:
Q: AWS S3 JavaScript SDK - NetworkingError: Network Failure I am trying to use the examples provided by AWS in their Examples in the Browser webpage, and I keep receiving the NetworkingError: Network Failure error. Here is what I am using:

<input type="file" id="file-chooser" />
<button id="upload-button">Upload to S3</button>

My bucket is in the US Standard region, and I am trouble figuring out whether it uses us-west-2 or us-east-1. When I go to my bucket's console, the URL is https://console.aws.amazon.com/s3/home?region=us-west-2 yet someone mentioned on here that US Standard is us-east-1.

A: This error occurs because you don't set the CORS configuration.

*

*Open the Amazon S3 console at https://console.aws.amazon.com/s3/.

*Select the name of the bucket you are using from the bucket list.

*Next, Choose "Permission" tab.

*Then in an editor titled "Cross-origin resource sharing (CORS)", you need to make sure the S3 bucket has following CORS configuration:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "HEAD",
            "GET",
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "ETag"
        ]
    }
]

A: As of the writing of this answer, according to the Amazon Web Services General Reference, US Standard uses us-east-1.

A: This is really late but if anyone else stumbles over this you need to make sure your CORS file in console has sufficient permissions.


text:
Q: Is there a good way to encrypt and store a mailbox while still being able to quickly access and search it? I am wondering if it is possible to :

*

*Store a mailbox in a way that the system administrator (ie: root) cannot see it

*User(s) with the valid credentials would be able to see it AND be able to search quickly in it, preferably via http access

I know that I can:

*

*Encrypt on the partition level, but it won't disallow the system administrator from seeing files in it.

*Encrypt emails with the GPG system, but I don't if and how I could apply it to an entire mailbox (ie: past and future emails in this mailbox).

*Give access to a mailbox via an open source webmail like roundcube, but I don't know if and how he would be able to access an encrypted mailbox

Do you know if this is possible?

A: This is impossible: root can always access all data. Even if you encrypt it, as soon as you decrypt it for access, root can snoop on the data, and snoop on your credentials as well. You cannot protect anything from the local root.
You can store files on a machine whose administrator you don't rust, but you need to encrypt and sign them. This means that you'll only be able to search them on a machine that you trust. You can store the email and search indices on the untrusted machine, but the search must happen on a trusted machine. There is ongoing research on forms of encryption that could allow searching, but this is difficult (searchable and encrypted are fundamentally contradictory) — don't expect usable software anytime soon, if ever.

A: I suppose in theory it should be possible to encrypt all incoming emails on the server with a public key from an e-mail user. Then this e-mail user can decrypt the e-mail with his private key when it retrieves the e-mail from the server on his local machine.
It is still not perfect, because incoming mail can still be intercepted at reception and of course you still have the e-mail stored probably at the actual sender's server. However, it is better than nothing in two ways. 1) If the root is not constantly monitoring all traffic, root will not be able to decrypt already received and stored messages. 2) It is contact friendly as you can use this on your own server without forcing your contacts to use pgp or encryption, as most people are probably not willing or able to. It would shield against most abuse of just peeking roots, offline and hot backups. Only not against active wiretapping (so not strictly government proof, but hardened non the less).
That's in theory however, I have no idea how to do this. If you encrypt the whole folder your email server is probably not able to give you individual messages. Would be nice if some server would allow to apply pgp on incoming messages instead of only outgoing messages. Workaround is rsyncing your encrypted folder and retrieve the actual mail from your local setup, or some other two-mail-server solution with one private mail server encrypting and sending (but no sending) to your private mail server.

A: I don't believe you can protect against root access when you are viewing the data yourself, but you can certainly  keep root out when you are not using it.
The easiest way is probably ecryptfs. This comes as standard on Ubuntu, and probably others too.
There's two ways to set it up:
1. When you create a new user you have the option of encrypting the entire home directory.
2. Alternatively you can set it up to encrypt only the contents of your "Private" directory.
You can do number 2 pretty simply:
ecryptfs-setup-private

Normally the decryption password is the same as your login password: this means you only have to enter the password once and it will automatically mount the filesystem when you log in. Beware though: your password is stored one-way encrypted in the system passwd file; nobody can read it directly,  but given time it can be cracked.
Ecryptfs does not store your password at all. Instead it used the password you enter as a cypher to decrypt a proper encryption key,  so if you use an alternative password it's much more secure.
You can tell your email client to keep all your files in the secure directory and that should serve your purpose.  Thunderbird makes this quite easy and also indexes your mail so you can search your mail efficiently, even if it is encrypted. I keep a very large mail folder this way with no obvious performance hit.


text:
Q: batch file for looping a folder and copy and then renaming Basically what I want to achieve is to copy all files in that directory and pasting it with new in the name in the same directory so
2ic.mdl to new2ic.mdl
code:
for f in ../models/model/vehicle/train/* DO
(
copy $f  ../models/model/vehicle/train/$new{f}
)

but because of the loop I don't even get a error it just closes
and I need to do that for a lot of different folders
all my effort to fix it didn't work out so far
and that i don't see the copy error doas imply my for loop is already flawed
for /r  .\models\model\vehicle\train\  %%name in (.) do (
echo test
pause
echo copy $f  ..\models\model\vehicle\train$new{f}
)
echo ende
pause

A: @echo off
for /r  .\models\model\vehicle\train\  %%i in (*) do (
&:: for each file in path. make i the path+file  D:\..train\bigboy.exe

copy "%%i" "%%~dpi\new%%~nxi"
&::%%~dpi takes the path from i
&::%%~nxi takes the old file name and ending
echo done
pause
)
echo ende
pause

so in case i or someone else need this i tryed my best to explain every operation
because that did hurt my own Research on this platform


text:
Q: What's the difference between multiverse, universe, restricted and main? I've been peeking into the ubuntu respository and I see four folders, multiverse, universe, restricted and main.  What do they represent?

A: Ubuntu provides four different official software repositories:

*

*Main

*Restricted

*Universe

*Multiverse
Main – Officially Supported, Open-Source Software:
Licence: Open Source
Updates: Canonical provides critical updates.
Restricted – Officially Supported, Closed-Source Software:
Licence: Proprietary
Updates: Canonical provides critical updates supplied by the developers.
Universe – Community-Maintained, Open-Source Software:
Licence: Open source
Updates: Canonical does not provide update.
Some updates may be provided by the Ubuntu community.
Multiverse – Unsupported, Closed-Source and Patent-Encumbered Software:
Licence: Unknown
Updates: Canonical does not provide updates.
Some updates may be provided by Ubuntu community.
About Canonical and Ubuntu
reference here

A: From the Ubuntu documentation:

The repository components are:

*

*Main - Officially supported software.

*Restricted - Supported software that is not available under a completely free license.

*Universe - Community maintained software, i.e. not officially supported software.

*Multiverse - Software that is not free.

For example:

*

*The Ubuntu Desktop team manages the gnome-terminal package, it is officially supported and in the main repository.

*bcmwl-kernel-source (the Broadcom wireless driver) is in restricted, since it is a supported, but proprietary, driver.

*Community written software that is not officially supported (for example, the game supertuxkart) is in the universe repository.

*Packages like ubuntu-restricted-extras (which contains proprietary codecs that allow you to play media files, including flash player) are in the multiverse repository because they are not free and their restrictive licenses prevent inclusion in the default package set.

From Wikipedia:-


text:
Q: Communication between Controller and Main class in JavaFX? I am using IntelliJ and as some might know, there is a nicely ordered template project structure of a Main.java, a Controller.java and a FXML.fxml file.
I want to use this and I am trying to switch between 2 Scenes by clicking a Button which is defined in the FXML document. I wonder, how I am able to change the stage which lies in the Main.java when the Controller is called by clicking the button. Of course, it would be possible to make the Stage and the Scene static in the Main.java but it kinda is hard to call it then from the controller.
This does work but it looks awful in the Controller
Take a look
I am quite new to FX and I though there might be better possibilities than the one I choose. I wondered if I should declare Stage stage and the Scenes in Controller instead.
Thank you!

A: I would pass a runnable that switches the scenes as a parameter to the Controller.
First instead of defining the controller in the FXML file, define it in your Main class like this.
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getRessource("Scene1.fxml");
fxmlLoader.setController(new Controller());
scene1 = fxmlLoader.load();

This allows you to pass parameters to the controller's constructor. So know pass a Runnable as a parameter which will switch the scenes. Like this:
Instead of :
new Controller()

Do
new Controller(() -> {
    //Code to switch scenes
});

P.S. This is a lambda expression. You could instead move the content to a separate method and pass the method as the parameter.
Finally, make your controller class look like this
/*
 * The method to run when the button is pressed. Passed in as a parameter when the controller was created
 */
private final Runnable switchScenes;

public Controller(Runnable switchScenes) {
    this.switchScenes = switchScenes;
}

@FXML
public void handleSwitchButton(){
    switchScenes.run();
}

This makes the following. When the button is pressed, the switchScenes Runnable is executed. This Runnable is the Runnable that was passed from the main class to the controller as a parameter in the constructor. The Runnable contains the code to switch the scenes. Note : This requires  Java 8. For Java 7 you could use an interface with an anonymous class.
On an other note, I recommend switching roots instead of scenes (aka. only one scene and you call scene.setRoot()). This gives you more flexibility (ex. You can add a fade transition when switching).


text:
Q: ScaleDrawable doesn't seem to work I've looked at a lot of threads on how to change the size of a drawable but none of them seem to work.
Bitmaps throw me a class cast exception and even setting the level of the ScaleDrawable doesn't work.
What's wrong? I'm not looking for an xml solution because I want to change the size in terms of how other items are sized based on how big the screen is.
Thanks.
//set seekbar thumb to height of bar
        Drawable thumb = mSeekBarSpeed.getThumb();
        thumb = new ScaleDrawable(thumb, 0, thumb.getIntrinsicWidth(), mSeekBarSpeed.getHeight());
        thumb.setLevel(10000);
        thumb.setBounds(0, 0, thumb.getIntrinsicWidth(), thumb.getIntrinsicHeight());
//        Bitmap thumbBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.seekbar_thumb);
//        Bitmap scaled = Bitmap.createScaledBitmap(thumbBitmap, thumb.getIntrinsicWidth(), mSeekBarSpeed.getHeight(), true);
////
////        Bitmap thumb = Bitmap.createBitmap(50,50, Bitmap.Config.ARGB_8888);
////        Canvas canvas=new Canvas(thumb);
////        canvas.drawBitmap(bitmap,new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()),
////                new Rect(0,0,thumb.getWidth(),thumb.getHeight()),null);
////        Drawable drawable = new BitmapDrawable(getResources(),thumb);
////        setThumb(drawable);
//
//        //Drawable thumb = mSeekBarSpeed.getThumb();
////        thumb.setBounds(0,0, thumb.getIntrinsicWidth(), mSeekBarSpeed.getHeight());
////        Bitmap orig = ((BitmapDrawable)thumb).getBitmap();
////        Bitmap scaled = Bitmap.createScaledBitmap(orig, thumb.getIntrinsicWidth(), mSeekBarSpeed.getHeight(), true);
//        Drawable newThumb = new BitmapDrawable(getResources(), scaled);
//        newThumb.setBounds(0,0,newThumb.getIntrinsicWidth(),newThumb.getIntrinsicHeight());
        mSeekBarSpeed.setThumb(thumb);

A: Found a way to get it to work using Bitmaps.
    Drawable thumb = mSeekBarSpeed.getThumb(); //get thumb of seekBar

    Bitmap thumbBitmap; //try to find bitmap of thumb
    if(thumb instanceof BitmapDrawable) {
        thumbBitmap  = ((BitmapDrawable)thumb).getBitmap();
    }else{
        Bitmap bitmap = Bitmap.createBitmap(thumb.getIntrinsicWidth(),thumb.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        thumb.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        thumb.draw(canvas);
        thumbBitmap = bitmap;
    }

    //scale the bitmap
    float scale =  (float)1.00 * mSeekBarSpeed.getHeight() / thumb.getIntrinsicHeight();
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(thumbBitmap,
            Math.round(thumb.getIntrinsicWidth() * scale),
            Math.round(thumb.getIntrinsicHeight() * scale), true);

    //make is a drawable
    Drawable newThumb = new BitmapDrawable(getResources(), scaledBitmap);

    //set thumb to new thumb
    mSeekBarSpeed.setThumb(newThumb);

Source: Get All Installed Application icons in Android : java.lang.ClassCastException has some info about the Class Cast Exception for Bitmap.


text:
Q: how to create properties with sub properties having constant values in a class using c# I would like to create a string using the StringBuilder() class. I have a collection of records of say Employees. Each record of Employee has columns such as firstName, lastName, city, etc.
The string that I want to create will have the values of the above mentioned columns each.
For this I need to create a class
class Columns
{
    string Firstname
    {
        startPosition = 1;
        length = 32;
    }

    string LastName
    {
        startPosition = 33;
        length = 32;
    }
}

In the string that I'm building I need to insert the values of Firstname,Lastname in the respective start positions mentioned. I'm new to this and I need help in creating the above class. The above specified code is just the prototype of what the class should be like but I do not know how exactly to create this. I need the properties startPosition and length to be present in all the columns and these values need to be hardcoded. Sorry if my question is vague. Please help..

A: Let me start with telling you, there is no such thing as "sub properties". What you can do is have a property/field of a class which exposes properties itself.
Therefore, you might want to create a class for one Column and then create a List to keep track of your Columns like in the following example.
public class Column
{
    public string Name { get; set; }
    public int StartPos { get; set; }
    public int Length { get; set; }
}

public class Test
{
    private List<Column> Columns = new List<Column>();

    public Test()
    {
        this.Columns.Add(new Column { Name = "FirstName", StartPos = 1, Length = 32 });
        this.Columns.Add(new Column { Name = "LastName", StartPos = 33, Length = 32 });
    }

    public string GetThatString(string str)
    {
        foreach (var col in this.Columns)
        {
            // Do what you need. Sample:
            var item = str.Substring(col.StartPos, col.Length);
            Console.WriteLine("{0}: {1}", col.Name, item);
        }
    }
}

You could then iterate over the items in the List and have your string builder do the work yo need.
Of course, you could also create a property for each Column instead of a List of all the Columns.


text:
Q: How do I access the managedObjectContext from a controller deep in the UI? I'm still a little fuzzy on understanding iPhone/Cocoa in general so this is probably a simple question.
I have a CoreData Window-Based App for the iPhone.  The rootController is a UITabBarController.  The first tab view has a UINavigationController attached to it with a table in it's main view.
When the App starts the objectContext is set up, which makes sense to have the App do that once.  But now I have the managedObjectContext in the main Controller but I want to get that passed down to the Controller of the View inside the navcontroller, inside the first item in the TabBarController's tab list.  How do I do this?
Would naming the one of the fields in the UI Inspector Tool allow me to do something like:

tabcontroller.navcontroller.manageObjectContext = self.managedObjectContext;

Would this only work if the controller was instantiated and 'live'. (Do the controllers not get instantiated until they are needed?) What if this was in a view that was for the most part hidden?
Anyway this is probably a simple thing I'm just not understanding things properly yet.
What is the general right way to share the manageObjectContext that is created and setup in the rootController to the many sub-controllers in the app?

A: I'm guessing this is the preferred method assuming the core-data initialization is done in the AppDelegate:

 [[[UIApplication sharedApplication] delegate] managedObjectContext]

A: I usually give controllers a - (id)initWithManagedObjectContext:(NSManagedObjectContext *)context init method and a corresponding variable.
If a controller creates another controller in turn, it will, if needed, pass the NSManagedObjectContext to that controller in the same manner.

If you don't want to create an extra init method, just give the controllers a property for the NSManagedObjectContext and set that property directly after creating them.
I usually try to limit the number of controllers that directly deal with and "know about" Core Data though.

A: The answers to this question provide several means of accessing the Core Data stack deep within your application.  As I indicate in one of the comments, I prefer to use a singleton DatabaseController that can be accessed from wherever, similar to how the NSUserDefaults' standardUserDefaults works.


text:
Q: WCF WebGet parameter pass, you can pass the output parameter (out)?     [OperationContract]
    [WebGet(UriTemplate = "GetAwardList?COUNT={COUNT}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    List<discount_awardModel> GetAwardList(out int COUNT);

Through the browser call "http://localhost:50590/WCFService/Product/PublicProductService.svc/GetAwardList? COUNT=1"
The error:

"/"Server error in application.
  The operation "GetAwardList" in the Convention "IPublicProductService" should have a UriTemplate, which has the name "COUNT", but the operation does not have an input parameter for this name.
Description: an exception that occurs during the execution of the current Web request. Please check the stack trace information to understand the details of the source of the error and the code that causes the error.
Exception details: System.InvalidOperationException: agreed with the name "count" parameters UriTemplate IPublicProductService operating GetAwardList ", but the operation and not the name of the input parameters.
Source error:
An exception is generated during the execution of the current Web request. You can use the following exception stack trace information to determine the cause and location of the exception.
Stack trace:
InvalidOperationException: agreed with the name "count" parameters UriTemplate IPublicProductService operating GetAwardList ", but the operation and not the name of the input parameters.


text:
Q: How to move a table row in Apple iWork Pages? Is it possible to drag a table row to a new position in order to reorder them?
Things we've tried

*

*Drag the row: either swaps or overwrites (perhaps depending on Pages version?)

*Drag the row with alt: overwrites the target and leaves the original row.

*Cut leaves a blank row, and paste overwrites, which requires manual addition of blank row.

A: Insert a new row below the row you want to insert below.
Example:
Rows
1
2
3
4

You want to move 4 between 1 and 2.  Insert a blank row below 1, and then drop 4 on the blank row.
1
(new blank)
2
3
4


text:
Q: Importing multiple csv files at the same time want the date data converted into (date and time) format in R I have 20 files as .csv; all have the same headers as in the picture.

I want to import them once at the same time. I want the timestamp converted from character format to date and time format.
I used this code for importing all the 20 files, which works fine.
path <- "~/Google Drive/Plumeflowlabs test/Data from Plume 17 Nov 2020/"

files <- list.files(path=path, pattern="*.csv")

for(file in files)
{
  perpos <- which(strsplit(file, "")[[1]]==".")
  assign(
    gsub(" ","",substr(file, 1, perpos-1)),
    read.csv(paste(path,file,sep="")))

}

However, it doesn't contain the function to convert the date.
After that, I want to merge all the 20 files into one data frame by the timestamp.
I need help with that too.

A: Try this approach. As no data was shared I can not test it. Taking into account the sage advice from @GregorThomas it is better to store data in a list like this:
#Code
path <- "~/Google Drive/Plumeflowlabs test/Data from Plume 17 Nov 2020/"
files <- list.files(path=path, pattern="*.csv")
#Function to load and transform date
myfun <- function(x)
{
  df <- read.csv(x,sep="")
  df$timestamp <- as.POSIXct(df$timestamp,format='%d/%m/%Y %H:%M',tz = 'GMT')
  return(df)
}
#Apply
List <- lapply(files,myfun)
#Names
names(List) <- files

The names are assigned in reference to files object. After that you can process them.


text:
Q: Computing determinant and using division and multiplication of uint64_t C type This question has been edited to clarify it.
I have the following matrix, defined in page 1 of [reteam.org/papers/e59.pdf], written in R notation:
m1 = matrix(c(207560540,956631177,1,956631177,2037688522,1,2037688522,1509348670,1),ncol=3,byrow=T)

The determinant of m1 should be a integer multiple of 2^31 -1.
As indicated in accepted answer, det(m1) should be -1564448852668574749.
However, in R, I got
> det(m1)
[1] -1564448852668573184

and, using a simple equation by hand:
> m1[1,1]*(m1[2,2]-m1[3,2]) - m1[2,1]*(m1[1,2] - m1[3,2]) + m1[3,1]*(m1[1,2]- m1[2,2])
[1] -1564448852668574720

As indicated in accepted answer, the correct determinant is obtained
and checked by:
#include <inttypes.h>
#include <stdio.h>

int main() {

int64_t m1[3][3] = {{INT64_C(207560540) , INT64_C(956631177)   , INT64_C(1)},{ INT64_C(956631177), INT64_C(2037688522),       INT64_C(1)},{INT64_C(2037688522), INT64_C(1509348670) ,   INT64_C(1)}};

int64_t dm1 = m1[0][0]*(m1[1][1]-m1[2][1]) - m1[1][0]*(m1[0][1] - m1[2][1]) + m1[2][0]*(m1[0][1]- m1[1][1]);
int64_t divisor = (INT64_C(1)<<31) -1;
int64_t tmp = dm1/divisor;
int64_t check = tmp * divisor;

printf("dm1 == %" PRIu64"\n",dm1);
printf("(dm1/(2^31 -1))* %" PRIu64 " == %" PRIu64 "\n", divisor, check);

}
The following text is the old question. The main error was using a unsigned type.

My old minimum non-working code example was:
  #include <inttypes.h>
  #include <stdio.h>

  int main() {

  uint64_t dm1 = 1564448852668573184;
  uint64_t divisor = (UINT64_C(1)<<31) -1; //powl(2,31)-1;
  uint64_t tmp = dm1/divisor;
  uint64_t check = tmp*divisor;

  printf("dm1 == %" PRIu64"\n",dm1);
  printf("(dm1/(2^31 -1))* %" PRIu64 " == %" PRIu64 "\n", divisor, check);
}

Its output is
dm1 == 1564448852668573184

(dm1/(2^31 -1))* 2147483647 == 1564448850521091102

The problem is that the value of the second line should be equal to the one in the first line.
What is my mistake? How can I make this work?

A: For the same reason that (using integers) you get 10 / 3 * 3 = 9. There is a remainder of the division. 10 / 3 = 3, with remainder 1. When you multiply by 3, the remainder is lost, so you get 9 instead of 10.
In this case, your remainder is 2147482082, which, when added to 1564448850521091102, gives 1564448852668573184. Try this:
uint64_t dm1 = 1564448852668573184;
uint64_t divisor = (UINT64_C(1)<<31) -1; //powl(2,31)-1;
uint64_t tmp = dm1/divisor;
uint64_t remainder = dm1%divisor;
uint64_t check = tmp*divisor+remainder;

And you should get the correct result.

A: The numerator is not an exact multiple of the divisor, so there is a remainder, and the quotient is truncated.
1564448852668573184 / 2147483647 = 728503266 remainder 2147482082

Multiplying back,
2147483647 * 728503266 + 2147482082 = 1564448852668573184

EDIT:
The determinant of the 3x3 matrix shown in your linked reference is -1564448852668574749. This is exactly divisible by 2147483647 to give -728503267.
So you have an arithmetic overflow somewhere.
ANSWER:
The value of the matrix determinant in your linked example is negative. Please use int64_t instead of uint64_t.


text:
Q: DragShadowBuilder Not working in Android 11 Running this simple code on two android emulators:
Pixel 4 API 30,
Pixel 4 API 28
When I long-click the image-view on API 30 emulator the view gets invisible as per the expectations but the views shadow is not visible until I start dragging or moving after long-click whereas it's working fine on API 28 emulator. I tried adding startDragAndDrop as startDrag was deprecated(showed Gradle warning due to that) But still the issue remains.
If there is a need I can share the video of the issue.
public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.myimage4);
        imageView.setOnLongClickListener(new MyLongClickListener());
    }

    private final class MyLongClickListener implements View.OnLongClickListener {

        @Override
        public boolean onLongClick(View view) {
            View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
            // Start the drag of the shadow
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                view.startDragAndDrop(null, shadowBuilder, view, 0);
            } else {
                view.startDrag(null, shadowBuilder, view, 0);
            }

            // Hide the actual view as shadow is being dragged
            view.setVisibility(View.INVISIBLE);
            return true;
        }
    }
}

A: Ok I found a work-around (tested on Pixel 2 API 30 emulator, but not any other).  The idea is to postpone hiding the view being dragged until the dragging starts.  So, I hide the view in my View.OnDragListener.  Here is some of the code from that class:
private int mStartedAtX = -99;
private int mStartedAtY = -99;
private boolean mMoved = false;

private void onDragPageItem(DragEvent dragEvent)  {
    int dragAction = dragEvent.getAction();

    // On drag started...
    if (dragAction == DragEvent.ACTION_DRAG_STARTED) {
        mStartedAtX = (int)dragEvent.getX();
        mStartedAtY = (int)dragEvent.getY();
    }

    // On drag exit...
    else if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
        mPageAdmin.handleItemDragExit();
    }

    // On drag motion...
    else if (dragAction == DragEvent.ACTION_DRAG_LOCATION) {
        int draggedToX = (int)dragEvent.getX();
        int draggedToY = (int)dragEvent.getY();
        mPageAdmin.handleItemDragMove(draggedToX, draggedToY);

        if (!mMoved) {
            handleFirstMove(draggedToX, draggedToY);
        }
    }

    // On drag drop...
    else if (dragAction == DragEvent.ACTION_DROP) {
        setDragInProgress(false);
        mPageAdmin.handleItemDragDrop();
        resetMovedFields();
    }

    // On drag end...
    else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
        setDragInProgress(false);
        mPageAdmin.handleItemDragEnd();
        resetMovedFields();
    }
}

private void handleFirstMove(int locX, int locY) {
    if ((locX != mStartedAtX) || (locY != mStartedAtY)) {
        View draggingView =  mPageAdmin.getItemTouchListener().getTouchedView();
        if (draggingView != null) {
            draggingView.setVisibility(View.GONE);
        }
        mMoved = true;
    }
}

private void resetMovedFields() {
    mStartedAtX = -99;
    mStartedAtY = -99;
    mMoved = false;
}

The handleFirstMove() method is where the view is hidden.


text:
Q: Sharepoint Calendar interaction with Lotus notes calendar Can anybody help me how to connect sharepoint 2010 calendar to lotus notes calendar? Means if we add something in Sharepoint calendar that should reflect in lotus notes calendar.
Thank you in advance...

A: I've not seen any 3rd party tools that do that specifically so you would need to create custom code on the SharePoint side that can interface with the Notes API.  Most likely you would want to do this with an event receiver, but you may be able to do it with a workflow as well, though it would be a little trickier and would still require custom code.


text:
Q: Haskell namespace when reexporting I am not sure how the namespace works in the following case :
Data.Streaming.Network reexports HostPreference from  Data.Streaming.Network.Internal
When I load up in ghci, I can see that the constructors are prefixed by the original namespace.
$ ghci
GHCi, version 7.8.4: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> import Data.Streaming.Network
Prelude Data.Streaming.Network> :info HostPreference
data HostPreference
  = Data.Streaming.Network.Internal.HostAny
  | Data.Streaming.Network.Internal.HostIPv4
  | Data.Streaming.Network.Internal.HostIPv4Only
  | Data.Streaming.Network.Internal.HostIPv6
  | Data.Streaming.Network.Internal.HostIPv6Only
  | Data.Streaming.Network.Internal.Host String
        -- Defined in 'Data.Streaming.Network.Internal'

But some program expect the bindings for the constructors to be available under the reexporting module Data.Streaming.Network.
Prelude Data.Streaming.Network> :l src/Server.hs
[1 of 1] Compiling Main             ( src/Server.hs, interpreted )

src/Server.hs:14:58: Not in scope: data constructor 'HostAny'

What is going on, who is correct ?

A: The constructors for HostPreference are not exported, the streaming-commons package intends for them to be private, if I am to judge by what is exported.  Instead, the documentation suggests using OverloadedStrings and typing string literals to get the different values:

data HostPreference
Which host to bind.
Note: The IsString instance recognizes the following special values:
* means HostAny
*4 means HostIPv4
!4 means HostIPv4Only
*6 means HostIPv6
!6 means HostIPv6Only
Any other values is treated as a hostname. As an example, to bind to the IPv4 local host only, use "127.0.0.1".

So in your Server.hs, just enable OverloadedStrings and then where ever you're trying to use HostAny just type "*" instead.


text:
Q: Tool for analyzing lucene index I have a Solr application which stores lots of fields.
I want to reduce the Lucene index size.
For that I want to analyze how much does each field takes out of the total index file.
Are there any tools for this task?
I've tried Luke which is very handful, but didn't see these specific details.


text:
Q: Logstash does not index when I run the service Here is my conf file in /etc/logstash/conf.d/apachelog.conf (Below)...I don't see index in kibana
But when i enter this command it works
/opt/logstash/bin/logstash -f /etc/logstash/conf.d/apachelog.conf
and I see the index in elasticsearch
I want to start it when i restart my services like "service logstash start"
input {
file {
path => "/var/log/apache2/access.log"
type => "apache_log" # a type to identify those logs (will need this later)
start_position => "beginning"
sincedb_path => "/dev/null" #to clear since db
}
}

filter {
grok {
match=> { message => "%{COMBINEDAPACHELOG}" }
}
date {
locale => "en"
match => [ "timestamp", "dd/MMM/yyyy:HH:mm:ss Z" ]
}
}

output {
#stdout { }
elasticsearch {
hosts => ["localhost:9200"]
sniffing => true
manage_template => false
index => "mylogs"

}

}


text:
Q: How to set keyboard shortcuts common to both windows and mac using jquery I had an web application which had piece of code for shortcuts which is working fine for windows in both chrome and firefox. How can i extend this to Mac machine for both chrome and firefox.
Code in windows
$(document).bind("keydown","Ctrl+s", function() {
       //Save code
       alert("Save");
});

For mac i tried below piece of code which is working fine.
$(document).bind("keydown","meta+s", function() {
       //Save code
       alert("Save");
});

The other way i can do this is by having a common function for both like as below
var save = function(event) {
   //save code
   return false;
};

$(document).bind("keydown","Ctrl+s", save);
$(document).bind("keydown","meta+s", save);

Let me know any other better way to do this which works for both windows and mac in chrome and firefox.


text:
Q: Hex code lose his format Can somebody say me what is the problem:
I will print out a hex file on the "Epson TM-t88II" printer, but after this all my "Umlaute" (ä/ö/ü/ß) lost its format and are black dots, etc.
My Hex code for an ü is "FC". Is it false?

A: &00FC is "ü" in many encoding formats, but not all. If your printer does not know what encoding you're using, it may well not understand what you want to print.
Exactly what are you sending to the printer? And what application are you printing from?
The following may also be of interest.
http://www.joelonsoftware.com/articles/Unicode.html


text:
Q: JPA: how to map SQL Server uniqueidentifier type I've inherited a SQL Server database that I'm trying to map via JPA. Many of the tables have a uniqueidentifier column. I'm trying to map them like so:
@Id
@GenericGenerator(name = "generator", strategy = "guid", parameters = {})
@GeneratedValue(generator = "generator")
@Column(name = "APPLICATION_ID")
private String id;

Hibernate complains with:
Found: uniqueidentifier, expected: varchar(255)

A: The data type of the primary key property in the POJO determines the data type of its mapped DB column, which is specified by the Dialect class. According to the SQLServerDialect provided by hibernate, it does not have any data type that maps to uniqueidentifier, and String by default maps to varchar(255)
I think  guid strategy on a String primary key only means that hibernate will  generate a GUID value for POJO's primary key property  and this generated  GUID value will be inserted to the varchar(255) column to simulate the effect of uniqueidentifier
You can try to override the mapping specified by the Dialect class by using the columnDefinition attribute of @Column
 @Id
 @GenericGenerator(name = "generator", strategy = "guid", parameters = {})
 @GeneratedValue(generator = "generator")
 @Column(name = "APPLICATION_ID" , columnDefinition="uniqueidentifier")
 private String id;

A: You need to use uuid2
@Id
@GenericGenerator(name = "generator", strategy = "uuid2", parameters = {})
@GeneratedValue(generator = "generator")
@Column(name = "APPLICATION_ID" , columnDefinition="uniqueidentifier")
private String id;

This works for me.


text:
Q: User groups without Active Directory Is it possible for Windows Server 2003 R2 to configure several user groups with different setups without using Active Directory?  The admin has turned it off for 'security reasons'.
Which setups I need:
I connect to a Windows Server remotely using RDP. And the server abrupts after 5 min of inactivity. The admin of the server doesn't want to increase the amount of time of inactivity for all users. I need more than 5 hours of inactivity because of a long running database task on the server.


text:
Q: Error after update to 1.9.2.0 - item detail page I've done a update to Magento 1.9.2.0 - still after the update I get the error message at my item detail page.
Have anyone a idea to fix the problem?
    Invalid method DerModPro_BasePrice_Block_Catalog_Product_View::cacheSelf(Array
(
)
)

Trace:
#0 [internal function]: Varien_Object->__call('cacheSelf', Array)
#1 [internal function]: DerModPro_BasePrice_Block_Catalog_Product_View->cacheSelf()
#2 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Core/Model/Layout.php(348): call_user_func_array(Array, Array)
#3 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Core/Model/Layout.php(214): Mage_Core_Model_Layout->_generateAction(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#4 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Core/Model/Layout.php(210): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#5 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Core/Controller/Varien/Action.php(344): Mage_Core_Model_Layout->generateBlocks()
#6 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Cms/Helper/Page.php(113): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#7 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Cms/Helper/Page.php(52): Mage_Cms_Helper_Page->_renderPage(Object(Mage_Cms_IndexController), 'no-route')
#8 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Cms/controllers/IndexController.php(75): Mage_Cms_Helper_Page->renderPage(Object(Mage_Cms_IndexController), 'no-route')
#9 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Cms_IndexController->noRouteAction()
#10 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('noRoute')
#11 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#12 /www/htdocs/w01325dc/oppacher-advent/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#13 /www/htdocs/w01325dc/oppacher-advent/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#14 /www/htdocs/w01325dc/oppacher-advent/index.php(83): Mage::run('', 'store')
#15 {main}

A: It looks like one of your modules, DerModPro_BasePrice, might be incompatible with Magento 1.9.2.0.
Go into etc/modules/DerModPro_BasePrice.xml and change <active>true</active> to <active>false</active>
Clear the cache and recheck.
If this module is the problem you should contact the module developer and ask if there is an updated version.


text:
Q: jQuery propogation issue with WordPress menus I am having an issue stopping propogration of jQuery with WordPress submenus.
Here is my script:
$("#menu-item-302900 a").click(function(){
    $.get('/?deletecookie', function() {
        window.location.href = "/";
    });
    return false;
});

Generated HTML:

        Future Residents

Apply Online

Other Link

Other Link 1

Other Link 2

The javascript is taking effect even when one of the sub-menu items is being clicked.
Of course, I tried amending the code with function(e){e.stopPropagation();} however this hasn't helped the issue.
Looking for a workaround that would limit the jQuery specifically to the  element on the selected menu item and not any of the  elements in the sub-menu.
Can anyone advise on a solution?
Thanks

A: At the moment you're using the "descendant selector"; which matches all a's under the ul. Instead, you could use the "child" selector, which is more restrictive:
"#menu-item-302900 > li > a"


text:
Q: Serenity+Cucumber: Reading testdata from Excel I am running Automation test cases with @RunWith(CucumberWithSerenity.class).
 We want to expose and maintain the Testdata separately in the Excel sheets instead of placing it in the Feature files.
The Template for Excel Testdata looks like:
|Scenario |UserName |Password|Name     |Address|City    |Pincode|
|Testcase1|testuser1|pass1   |testUser1|US     |Jersy   |12345  |
|Testcase1|testuser2|pass1   |testUser1|US     |Virginia|78955  |

We have chose to use Primary Key as 'Scenario' which would be present in both Feature file and Excel sheet and based on that we will read the specific row from excel and refer the specific row data as Testdata for that particular Scenario.
Questions:

*

*Is there a way to get the Scenario Name at run time from Feature file when Test is running, so that we can get the Excel sheet the extract the data for it from the Excel Sheets?

*Is there a default way/method available in above mentioned use case, so that we can use it for above use case?

A: Cucumber doesn't support external sources by design (it is a collaboration tool, not a test automation tool). In Serenity, you can build a parameterised JUnit test that gets data from a CSV file: http://serenity-bdd.info/docs/serenity/#_using_test_data_from_csv_files

A: public class ExcelDataTable {
private XSSFWorkbook book;
private FileInputStream file;

public String ReadDataSheet(String page, String path, int rowValue, int cellValue) throws IOException {
    String pointer;
    file = new FileInputStream(new File(path));
    book = new XSSFWorkbook(file);
    Sheet sheet = book.getSheet(page);
    Row row = sheet.getRow(rowValue);
    Cell cell = row.getCell(cellValue);
    pointer = cell.getStringCellValue();
    book.close();
    file.close();
    return pointer;
}

}
Just create a class with this code and here is how I'm using it
public class OpenWebSite implements Task {
    ExcelDataTable data = new ExcelDataTable();

    public static OpenWebSite openWebSite(){
        return Tasks.instrumented(OpenWebSite.class);
    }

@Override
public <T extends Actor> void performAs(T actor) {

    try {
        actor.attemptsTo(Open.url(data.ReadDataSheet("info", "Data.xlsx", 1, 1)));
    }
    catch (IOException e) {
        e.printStackTrace();
    }

}

}
Sort that out to make yours bro


text:
Q: Memory allocation in OS Having this simple code in C++:
#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class Empty{};

int main() {
    array<unique_ptr<Empty>, 1024> empties;

    for(size_t i =0; i < 1024; i++){
        empties[i] = make_unique<Empty>();
    }

    for(auto& element : empties){
        cout << "ptr: " << element.get() << endl;
    }

    return 0;
}

when running in ideone.com or Windows we get following result:
ptr: 0x2b601f0c9ca0
ptr: 0x2b601f0c9cc0
ptr: 0x2b601f0c9ce0
ptr: 0x2b601f0c9d00
ptr: 0x2b601f0c9d20
ptr: 0x2b601f0c9d40
ptr: 0x2b601f0c9d60 ...

For me it's totally strange. what kind of allocation algorithms in OS or standard library might cause, that there happened no allocation at address, that ends with number different than 0?
The reason I did this experiment is, that given the OS uses buddy algorithm, that manages pages and allocation request will cause OS to allocate a piece of contiguous memory, then a couple of next allocations (until running out of allocated memory) should be allocated quite nearby. If that would be the case , then probably cache issue with lists would not be so significant in some cases , but I got results I was not expecting anyways.
Also second number from the right in allocated nodes is totally randomly. What may cause such a behavior?

A: Please notice that the printed pointers is inaccurate, the OS allow you to see them as subsequent pointers when they could be allocated to an entirely different pages.

A: The minimum size of a class in C++ is one byte, if I recall correctly. As there is a consistent 32 byte spacing between the class, it could be that that happens to be the sizeof the empty class you made. To determine this, try adding
std::cout << "Empty class size: " << sizeof(Empty) << std::endl;

It probably won't be 32 bytes, instead, there will probably be some consistent spacing between each object.
Note:
Does this compile for you. It doesn't for me because empties cant be implicitly initialised.


text:
Q: horizontal scrollbar in iframe I am trying to provide a horizontal scrollbar for the html form which gets loaded within an iframe which itself is loaded inside a cshtml page. I added the below code:
$('#iframe').contents().find('body').css('overflow-x', 'scroll');

This gave me the scroll bar but a disabled one. I mean the scrollbar appears by there can be no scrolling done.

A: You told the element to be scrollable if an overflow exists in x-axis direction. If there is no overflow the scrollbar stays disabled.
If you want the content of the iframe to be wider, simply put the contents inside the iframe into a container with
.container {
  width: 200%;
}

The iframe should have position: relative; set.
Please confirm if this solves your problem.


text:
Q: Proving a trigonometric expression is identical to $2(\operatorname{cosec}^{2}{B}-1).$ I came across this trigonometric identity:
$$\frac{\operatorname{cosec}{B} - \cot{B}}{\operatorname{cosec}{B} + \cot{B}} + \frac{\operatorname{cosec}{B} + \cot{B}}{\operatorname{cosec}{B} - \cot{B}} = 2(\operatorname{cosec}^{2}{B} - 1) = 2(\frac{1+\cos^{2}{B}}{1 - \cos^{2}{B}})$$
And as I solved it, the equation came down to:
$2\operatorname{cosec}^{2}{B}+2\cot^{2}{B}.$
This can be written as $2(\operatorname{cosec}^{2}{B} + \cot^{2}{B}),$ which can further be written as $2\frac{1+\cos^{2}{B}}{1 - \cos^{2}{B}}.$
But I can't seem to get my mind around the middle part of the question, that is, $2(\operatorname{cosec}^{2}{B} - 1)$
Is it possible to write it like this, or is this an error in the question paper itself?

A: Get rid of cosecants and cotangent:
$$
\frac{\csc B-\cot B}{\csc B+\cot B}=
\frac{\dfrac{1}{\sin B}-\dfrac{\cos B}{\sin B}}
     {\dfrac{1}{\sin B}+\dfrac{\cos B}{\sin B}}=
\frac{1-\cos B}{1+\cos B}
$$
Thus your left-hand side is
$$
\frac{1-\cos B}{1+\cos B}+\frac{1+\cos B}{1-\cos B}=
\frac{(1-\cos B)^2+(1+\cos B)^2}{(1+\cos B)(1-\cos B)}=
\frac{2(1+\cos^2B)}{1-\cos^2B}
$$
and hence it equals the right-hand side.
On the other hand, the middle term is
$$
2(\csc^2B-1)=2\left(\frac{1}{\sin^2B}-1\right)=
2\frac{1-\sin^2B}{\sin^2B}=2\frac{\cos^2B}{1-\cos^2B}
$$
which is definitely not equal to the right-hand side.
Just apply it with $B=\pi/2$: the left-hand side and the right-hand side are both $2$, whereas the middle term is $0$.
The identity would be true if the middle term is
$$
2\csc^2B-1
$$
because
$$
2\csc^2B-1=\frac{2}{\sin^2B}-1=\frac{2-\sin^2B}{\sin^2B}
=\frac{2-1+\cos^2B}{1-\cos^2B}
$$

A: The middle part can be easily proven from the right hand side.
$$\left(\frac{1+\cos^2x}{1-\cos^2x}\right)=\frac{2}{1-\cos^2x}-\frac{1-\cos^2x}{1-\cos^2x}=2\operatorname{cosec}^2x-1$$

A: $$(\csc B-\cot B)(\csc B+\cot B)=1\implies\dfrac{\csc B+\cot B}{\csc B-\cot B}=(\csc B+\cot B)^2$$
$$(\csc B+\cot B)^2+(\csc B-\cot B)^2=2(\csc^2B+\cot^2B)$$
Now $\cot^2B=\csc^2B-1$
Finally,  $$\dfrac{1+\cos^2B}{1-\cos^2B}=\dfrac{1+\cos^2B}{\sin^2B}=\csc^2B+\cot^2B$$

A: For the first part-
$$\frac{\operatorname{cosec}{B} - \cot{B}}{\operatorname{cosec}{B} + \cot{B}} + \frac{\operatorname{cosec}{B} + \cot{B}}{\operatorname{cosec}{B} - \cot{B}} $$
$$=\frac{(\operatorname{cosec}B-\cot B)^2+(\operatorname{cosec}B-\cot B)^2}{1}$$
$$=2(\operatorname{cosec^2}B+\cot^2B)$$
$$=2(2\operatorname{cosec^2}B-1)$$
For the second part $$2(\frac{1+\cos^2B}{1-\cos^2B})=2(\frac{1+\cos^2B}{\sin^2B})=2(\operatorname{cosec}^2B+\cot^2B)$$.Now,proceed as previous part.


text:
Q: Make all footnotes numbered subsequently, but one with a symbol I was wandering if there's a way to make only one footnote appear with a symbol (*) instead of the number.
Thanks!!!

A: If you're not using anything fancy in your document (like hyperref, say), you can redefine \@xfootnote:

\documentclass{article}
%\setlength{\textheight}{.3\textheight} Just for this example
\makeatletter
\def\@xfootnote[#1]{%
  \protected@xdef\@thefnmark{#1}%
  \@footnotemark\@footnotetext}
\makeatother
\begin{document}
This is a\footnote{Regular footnote} piece of text.
This is a\footnote[*]{Different footnote} piece of text.
This is a\footnote{Regular footnote} piece of text.
This is a\footnote{Regular footnote} piece of text.
This is a\footnote[$\dagger$]{Different footnote} piece of text.
This is a\footnote{Regular footnote} piece of text.
This is a\footnote[$\star$]{Different footnote} piece of text.
\end{document}


text:
Q: Random infinit rotation animation with jQuery I've been playing around with JS+CSS animations for the first time.
I am trying to rotate a div (or a bunch of them independently) with these random factors:

*

*Random direction

*Random degrees

*With random pauses

I managed to gather this script , which worked well. It rotates a div with id="square" infinity, into a [random] direction, by [random] degrees
    function redo() {
    $.fn.animateRotate = function(angle, duration, easing, complete) {
            return this.each(function() {
            var $elem = $(this);

            $({deg: 0}).animate({deg: angle}, {
                duration: duration,
                easing: easing,
                step: function(now) {
                    $elem.css({
                        transform: 'rotate(' + now + 'deg)'
                    });
                },
                complete: complete //|| $.noop
            });
        });
    };
    plusOrMinus = Math.random() < 0.5 ? -1 : 1;
    randAngle = Math.floor(Math.random()*70+30) * plusOrMinus;
    randDelay = Math.floor(Math.random()*3000+2000);
    $('#square').animateRotate(randAngle);
    timer = setTimeout(function() { redo(); },randDelay);
}

redo();

http://jsfiddle.net/NWLVY/1
Now I've been having a few difficulties:

*

*I would like to pass more than one element into this loop, and I want them to behave independently. I wouldn't mind if they all had the same class, or if I just needed to write multiple lines to execute each one. There won't be too many.

*This rotation doesn't continue from the last angle. It keeps jumping back. I can't figure out how to fix this.

*I can't seem to pass any easing options like swing or linear, nor any other options such as duration and complete

A: Solved.
I used a slightly different script but it now works.
I added Transition and Animation lines to the CSS of the rotating element,
transition:2s;
animation:ease-in-out;

Those seemed to have fixed the issue for the jagged spinning, and let me add some easing.
Then I used a wrapping function to pass different elements through the function.
<Script>
 function rotate (elementID) {

    var $rota = $(elementID),
        degree = 0,
        timer;

    function spin() {
        $rota.css({ transform: 'rotate(' + degree + 'deg)'});   // rotate element
        plusOrMinus = Math.random() < 0.5 ? -1 : 1;       // random spin direction
        randAngle = Math.floor(Math.random()*70+50) * plusOrMinus; // random degrees
        randDelay = Math.floor(Math.random()*1000+2000);  //random delay
        timer = setTimeout(function() {  // set delay
            degree += randAngle;  // add random degree to current variable
            spin(); // loop it
        },randDelay);
    }

    spin();    // start first spin for element

};

rotate ('#square'); // run it
rotate ('#square2'); // run it again

</script>

Here it is at work http://jsfiddle.net/NWLVY/2/