text:
Q: MySQL many 'and' statements I have this statement which is the wrong way to do it but how would I get the statement to work (the result of the statement needs to hold all the AND in it)
SELECT a.username, a.first_name, a.last_name
     , b.tx_time, b.account_id
     , a.id
     , b.table_id, b.tx_type, b.amount
FROM punter a
   , account_transaction b
WHERE b.tx_time >= '2011-07-01'
  AND b.tx_time < '2011-09-30'
  AND b.account_id = a.id
  AND b.tx_type = 4
  AND b.tx_type = 14

A: You could use explicit JOIN to simplify a bit:
SELECT a.username, a.first_name, a.last_name,
       b.tx_time, b.account_id, a.id,
       b.table_id, b.tx_type, b.amount
FROM punter a INNER JOIN account_transaction b
    ON b.account_id = a.id
WHERE b.tx_time BETWEEN '2011-07-01' AND '2011-09-30'
  AND b.tx_type = 4
  AND b.tx_type = 14

Note that I think it's an error using b.tx_type = 4 AND b.tx_type = 14 because it's always false. If you need to get records having tx_type = 4 or tx_type = 14 you can change last SQL lines with
AND b.tx_type IN (4,14)

A: AND b.tx_type = 4 AND b.tx_type = 14 will give you empty result set. One column can only have one value at the same time.
SELECT a.username, a.first_name, a.last_name,
       b.tx_time, b.account_id, a.id,
       b.table_id, b.tx_type, b.amount
FROM punter a
INNER JOIN account_transaction b ON b.account_id = a.id
WHERE b.tx_time BETWEEN '2011-07-01' AND '2011-09-30' AND b.tx_type IN (4,14)

A: I just guess you meant b.tx_type = 4 OR b.tx_type = 14
SELECT a.username, a.first_name, a.last_name, b.tx_time,
b.account_id, a.id, b.table_id, b.tx_type, b.amount
FROM punter a, account_transaction b
WHERE b.tx_time >= '2011-07-01' AND b.tx_time < '2011-09-30'
AND b.account_id = a.id
-- AND b.tx_type = 4 AND b.tx_type = 14
AND b.tx_type in (4, 14)

A: This part:
AND b.tx_type = 4
AND b.tx_type = 14

ensures that you will get zero rows in the result.

If you want to have punters with transcations of both type 4 and 14, you need to JOIN twice to table b:
SELECT a.username, a.first_name, a.last_name
     , b1.tx_time AS tx_time_1
     , b2.tx_time AS tx_time_2
     , a.id
     , b1.table_id AS table_id_1, b1.tx_type AS tx_type_1, b1.amount AS amount_1
     , b2.table_id AS table_id_2, b2.tx_type AS tx_type_2, b2.amount AS amount_2
FROM punter a
  JOIN account_transaction b1
    ON b1.account_id = a.id
  JOIN account_transaction b2
    ON b2.account_id = a.id

WHERE b1.tx_time >= '2011-07-01'
  AND b1.tx_time < '2011-09-30'
  AND b1.tx_type = 4

  AND b2.tx_time >= '2011-07-01'
  AND b2.tx_time < '2011-09-30'
  AND b2.tx_type = 14


text:
Q: Remove lines ending with "0." after lines ending with "0." I'm looking for a way to remove via bash a multilines pattern from a very large txt file.
I have lines like this ones:
    1;alias;1.872198312
    2;alias;0.
    3;alias;0.
    4;alias;2.982193126
    5;alias;1.987502017
    6;alias;0.
    7;alias;0.802829100
    8;alias;0.
    9;alias;0.
    10;alias;0.
    11;alias;0.
    12;alias;1.7210172

I would like to transform this file into something like:
    1;alias;1.872198312
    2;alias;0.
    4;alias;2.982193126
    5;alias;1.987502017
    6;alias;0.
    7;alias;0.802829100
    8;alias;0.
    12;alias;1.7210172

hence reducing the size of the file.
I have tried a grep approach:
    grep '0.$^[a-zA-Z0-9.;_]0.$' file.txt

with no success.

A: You can get it by using awk:
awk -F';' '{if ($NF == "0.") if (!z) z=1; else next; else z=0} 1' file

Output:
1;alias;1.872198312
2;alias;0.
4;alias;2.982193126
5;alias;1.987502017
6;alias;0.
7;alias;0.802829100
8;alias;0.
12;alias;1.7210172

A: With sed:
$ sed '/0\.$/{:a;N;/0\.$/s/\n.*$//;ta}' infile
    1;alias;1.872198312
    2;alias;0.
    4;alias;2.982193126
    5;alias;1.987502017
    6;alias;0.
    7;alias;0.802829100
    8;alias;0.
    12;alias;1.7210172

Commented:
/0\.$/ {              # If a line ends with '0.'
    :a                # Label to branch to
    N                 # Append next line to pattern space
    /0\.$/s/\n.*$//   # If that next line ends with '0.', remove it
    ta                # If we made a substitution, branch to label
}

To use the one-liner with BSD sed, there has to be an extra ; after the ta.

A: Perl solution:
perl -ne 'print if ! ($skipnext = /;0\.$/) || ! $skip; $skip = $skipnext;' input

*

*-n reads the input line by line.

*/;0\.$/ is a regex. It matches a semicolon, zero, dot, end of line.

*! is negation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Speeding up fullcalendar.io on shift roster I have a shift roster generated using fullcalendar.io.
I'm following and expanding on this tutorial: How can I create an event based on pattern for calendar?
I have events spanned over a time period of 50 years.
This makes the whole calendar laggy and heavy rather than lightweight. Prev/Next buttons are slow. Especially, for dayClick callback when the dates are filtered over all of the events created weekly over a period of 50 years, it takes a couple of seconds for the event to get executed.
I think its the logic behind the creation. When I lessen the period to generate the events, the whole process gets faster.
here is for the full illustration: https://codepen.io/gunblaze/pen/OZKBvE.
the day click is still the slowest due to its filtering, i guess:
..
dayClick: function(date, allDay, jsEvent, view) {
            $('#calendar').fullCalendar('clientEvents', function(event) {
                // match the event date with clicked date if true render clicked date events
                if(event.rendering == 'background'){
                    if (moment(date).format('YYYY-MM-DD') == event.start.format('YYYY-MM-DD')) {
            // do your stuff here
            $("#instructions").html(moment(date).format('YYYY-MM-DD')+': on ' +event.title+' shift.')
                    }
                }
            });
}
..

A: You're front-loading all your data; with 50 years of data, no way to prevent that from being slow.
If you have a server component you might want to think about serving up the data in smaller chunks. The documentation describes how to do this, but here's a quick sketch:
$('#calendar').fullCalendar({
  events: '/myfeed.php'
});

This would result in your server receiving a query string like this:
/myfeed.php?start=2013-12-01&end=2014-01-12&_=1386054751381

Then you can filter your calendar data on the server side to only return the data between start and end. This will generally be much more efficient if you can do it as part of your SQL query (assuming you're using a SQL database) as opposed to trying to filter in a javascript array.


text:
Q: How should I implement websocket in redux-saga? What should be my approach towards implementing websocket using boilerplate and saga, I would like to connect the websocket during starting of the application and reconnect when connection drops.
I am think of using fork for sending and receiving but still should I use actionChannel?
I need to cancel the forked send and receive threads when connection drops and respawn when connection comes back.
Some general questions: (not related to react/redux-saga)
What should be my approach when my applications wants to send messages during disconnected state? Should I
Also I have request-response where I send a request number in data and server responds me back, How should I handle this?

A: In practice there are several strategy which can be used for switching on of socket.io in redux infrastructure:
First, there are ready decisions in the form of middleware, for example https://www.npmjs.com/package/redux-socket.io
Secondly, it is possible to act simpler more cunning. At the moment when redux store and saga is created, it is at the same time possible to create also necessary client instance of socket.io, and further already logic of the functional closure.
Following example fully cover your case. Just setup MESSAGES_MAP map with name of events which should be mapped to Redux actions.
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import socketIO from 'socket.io-client';
import YourRootContainter from './YourRootContainter';

const MESSAGES_MAP = {
    'MESSAGE_1': 'REDUX_ACTION_1',
    'MESSAGE_2': 'REDUX_ACTION_2'
};

Promise.resolve(createSagaMiddleware()).then(saga => ({
    store: (compose(applyMiddleware(saga))(createStore))(
        YOUR_REDUCER,
        YOUR_INITIAL_STATE
    ),
    socketClient: socketIO(YOUR_SOCKET_URL, {
        path: YOUR_EXCHANGE_URL_PATH
    }),
    saga
})).then(({ saga, store, socketClient }) => (
    Object.keys(MESSAGES_MAP).forEach(name => (
        socketClient.on(name, event => store.dispatch({
            type: MESSAGES_MAP[name],
            payload: { ...event }
        }))
    )),
    saga.run(YOUR_SAGA_ENTRY_POINT),
    store
)).then(store => render(
    (<Provider store={store}>
        <YourRootContainter />
    </Provider>),
    document.getElementById('root')
));


text:
Q: String Functions for Nested Schema in Spark Scala I am learning Spark in Scala programming language.
Input file ->
"Personal":{"ID":3424,"Name":["abcs","dakjdb"]}}
Schema ->
root
  |-- Personal: struct (nullable = true)
  |    |-- ID: integer (nullable = true)
  |    |-- Name: array (nullable = true)
  |    |    |-- element: string (containsNull = true)

Operation for output ->
I want to concat the Strings of "Name" element
Eg - abcs|dakjdb
I am reading the file using dataframe API.
Please help me from this.

A: There is an inbuilt function concat_ws which should be useful here.

A: It should be pretty straightforward if you are working with Spark >= 1.6.0 you can use get_json_object and concat_ws:
import org.apache.spark.sql.functions.{get_json_object, concat_ws}

val df = Seq(
  ("""{"Personal":{"ID":3424,"Name":["abcs","dakjdb"]}}"""),
  ("""{"Personal":{"ID":3425,"Name":["cfg","woooww"]}}""")
)
.toDF("data")

df.select(
  concat_ws(
    "-",
    get_json_object($"data", "$.Personal.Name[0]"),
    get_json_object($"data", "$.Personal.Name[1]")
  ).as("FullName")
).show(false)

// +-----------+
// |FullName   |
// +-----------+
// |abcs-dakjdb|
// |cfg-woooww |
// +-----------+

With get_json_object we go through the json data an extract the two elements of the Name array which we concatenate later on.

A: to extend @Alexandros Biratsis answer. you can first convert Name into array[String] type before concatenating to avoid writing every name position. Querying by position would also fail when the value is null or when only one value exist instead of two.
import org.apache.spark.sql.functions.{get_json_object, concat_ws, from_json}
import org.apache.spark.sql.types.{ArrayType, StringType}

val arraySchema = ArrayType(StringType)

val df = Seq(
  ("""{"Personal":{"ID":3424,"Name":["abcs","dakjdb"]}}"""),
  ("""{"Personal":{"ID":3425,"Name":["cfg","woooww"]}}""")
)
.toDF("data")
.select(get_json_object($"data", "$.Personal.Name") as "name")
.select(from_json($"name", arraySchema) as "name")
.select(concat_ws("|", $"name"))
.show(false)


text:
Q: Need to Redirect on custom page After Click on Add to Cart - Magento We need to display one custom page after customer click on add to cart from product page. if customer can click on skip than its redirect to cart page other wise stay on custom page.
We can display some static products on custom page where customer can bought product from there.
Please let me know if any one know this..

A: Please override your cart controller and update function of _goBack(). you can add your custom URL instead of
$this->getResponse()->setRedirect($backUrl);

I have also share you how we can override cart controller. Please see link


text:
Q: Draw a rotated image directly to Graphics object, without creating a new Bitmap I was able to make an image to rotate by drawing on a separate graphics object, which draws on a separate Bitmap, and then draw the bitmap with the graphics object, which draws on the final image. This is drawing two basically same images. And I don't want that. The project is a simple graphics engine, so drawing time must be as fast as possible. On top of that, System.Graphics has not proven to be too good at drawing images.
Here is the code I am using. It needs an improvement or two, but the basic method should be visible.
    public static System.Drawing.Bitmap rotatedImage(System.Drawing.Bitmap img, double deg, bool hq)
    {
        int diag = (int)Math.Round(Math.Sqrt(img.Width * img.Width + img.Height * img.Height));
        System.Drawing.Bitmap res = new System.Drawing.Bitmap(diag, diag);
        System.Drawing.Graphics gfx = System.Drawing.Graphics.FromImage(res);
        if (hq) gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        DoublePair rotCent = new DoublePair(diag / 2, diag / 2);
        gfx.TranslateTransform((float)rotCent.a, (float)rotCent.b);
        gfx.RotateTransform((float)deg);
        gfx.TranslateTransform((-1) * (float)rotCent.a, (-1) * (float)rotCent.b);
        gfx.DrawImage(img, (diag - img.Width) / 2, (diag - img.Height) / 2, img.Width, img.Height);
        return res;
    }

Drawing a rotated image on a new Bitmap requires to rotate the graphics object, which is used for drawing. What I can do is pass the main graphics object to the method, rotate it to draw the image and then rotate the object back. But I don't know if rotating a graphics for a large image is faster or slower than rotating a graphics for a small image.
So, which is going to be faster - to rotate the whole graphics object twice (rotate to draw the image and then rotate back), or to draw the rotated image with a separate graphics and then draw it with the main graphics object? Is there an option to rotate an image without having to use a separate graphics object and without having to rotate a graphics object?

A: What I did in the last project was this one, this is inside Paint event, you dont need to create new bitmap, just reset transform and draw the image again:
e.Graphics.ResetTransform();
e.Graphics.TranslateTransform(Width/2, Height/2);
e.Graphics.RotateTransform(45f);  //45 degree
e.Graphics.DrawImage(.... //original image

e.Graphics.ResetTransform();
e.Graphics.TranslateTransform(Width/2, Height/2);
e.Graphics.RotateTransform(60f);  //60degree
e.Graphics.DrawImage(.... //original image
...


text:
Q: Запрос даты рождения и вывод количества прожитых дней Нужно создать HTML-страницу, которая при загрузке запрашивает дату вашего рождения и выводит в текстовое поле формы количество дней, которые Вы прожили.
Не получается, как по условию нужно. Выводит просто дату рождения.

var year = parseInt(prompt('ВВЕДИТЕ ГОД РОЖДЕНИЯ (в формате YYYY)'));
var month = parseInt(prompt('ВВЕДИТЕ НОМЕР МЕСЯЦ РОЖДЕНИЯ'));
var day = parseInt(prompt('ВВЕДИТЕ ДЕНЬ РОЖДЕНИЯ'));

if ((year.toString().length != 4)
    || (month < 1 || month > 12)
    || (day < 1 || day > 31)
) throw new Error('invalid date');

var arDay = ['воскресенье', 'понедельник', 'вторник', 'среду', 'четверг', 'пятницу', 'субботу'];
var arMonth = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];

var date = new Date(year, (month - 1), day);

document.body.innerHTML = "Я\040родился\040" +
                          day + "\040" + arMonth[(month - 1)] + "\040" +
                          year + "\040в\040" + arDay[date.getDay()];

A:

var year = parseInt(prompt('ВВЕДИТЕ ГОД РОЖДЕНИЯ (в формате YYYY)'));
var month = parseInt(prompt('ВВЕДИТЕ НОМЕР МЕСЯЦ РОЖДЕНИЯ'));
var day = parseInt(prompt('ВВЕДИТЕ ДЕНЬ РОЖДЕНИЯ'));

if ((year.toString().length != 4)
    || (month < 1 || month > 12)
    || (day < 1 || day > 31)
) throw new Error('invalid date');

var arDay = ['воскресенье', 'понедельник', 'вторник', 'среду', 'четверг', 'пятницу', 'субботу'];
var arMonth = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];

var date = new Date(year, (month - 1), day),
    currentDate = new Date(),
    days = Math.round((currentDate - date)/86400000);

document.body.innerHTML = "Я\040родился\040" +
                          day + "\040" + arMonth[(month - 1)] + "\040" +
                          year + "\040в\040" + arDay[date.getDay()] + "\040 " + days + " д. назад";


text:
Q: How do I show math block inside list in github readme? I tried this:
1. Setup
        1. item 1:
```math
                \left( \{g^{s^k}\}_{k\in[d]}, \{g_l^{l_i(s)}, g_r^{r_i(s)}, g_o^{o_i(s)}\}_{i\in\{0,...,n\}}, \\
                \{g_l^{α_{l}l_i(s)}, g_r^{α_{r}r_i(s)}, g_o^{α_{o}o_i(s)}, g_l^{βl_i(s)}g_r^{βr_i(s)}g_o^{βo_i(s)}\}_{i\in\{m+1,...,n\}}, \\
                g_l^{t(s)}, g_r^{t(s)}, g_o^{t(s)}, g_l^{α_{l}t(s)}, g_r^{α_{r}t(s)}, g_o^{α_{o}t(s)}, g_l^{βt(s)}, g_r^{βt(s)}, g_o^{βt(s)}  \right)
```extraly_added_not_exist_in_OP
        2. item 2

But it breaks the display of "item 2", which is supposed to be aligned with "item 1", now becomes aligned with the parent item, demo here
What's the correct way to make both math and list look normal?


text:
Q: Why is a rectangle shifted on a canvas? I have a canvas, I test on mobile, when I touch on the right side of the canvas, the rect is shifted to the right. The more I touch to the left, the more the rect is drawn where it is supposed to be, exactly at the location of the touch. Would you know why?The right part of the canvas is bugging, the left part is ok.

<canvas id="layerDraw"
style="position: relative; width:100%; height:auto; margin- top:2%; z-index: 2; border:1px solid red;">
</canvas>

function touch(){
ld.addEventListener("touchstart", follow);
ld.addEventListener("touchmove", follow);
}
function follow(evt){
//evt.preventDefault();
var ctx = ld.getContext("2d");
var touches = evt.touches;
ctx.fillStyle = chos;
var x = touches[0].pageX -getOffsetLeft(ld);
var y = touches[0].pageY -getOffsetTop(ld);
    ctx.fillRect(x-5,y, 20, 20);
}
function getOffsetLeft( elem ) {
var offsetLeft = 0;
do {
    if (!isNaN(elem.offsetLeft)) {
        offsetLeft += elem.offsetLeft;
    }
} while( elem = elem.offsetParent );
return offsetLeft;
}

function getOffsetTop( elem ) {
var offsetTop = 0;
do {
    if (!isNaN(elem.offsetTop)) {
        offsetTop += elem.offsetTop;
    }
} while( elem = elem.offsetParent );
return offsetTop;
}


text:
Q: Outlook 2010 Crashing Unpredictably Very often when I open up Outlook 2010 and start doing actions in it, it will hang and become non responsive.  I have tried letting it finish, but it never does come back (up to 20 minutes of letting it try).  I generally have to restart Outlook and try again.  Usually after about an hour of doing this, Outlook somehow snaps out of it and works for the rest of the day.  It's generally in the morning (though I doubt that's the key variable).  Generally, the emails that cause problems are HTML/formatted, but not always.
What I've done so far to troubleshoot:

*

*Install Latest Outlook Hotfix (I think Dec 14, 2010)

*Start Outlook in Safe Mode
Neither of those steps seem to make a difference.  Usually - after about 10-15 restarts of Outlook on any given day, then it starts working thereafter.  My next step is to uninstall/reinstall Office 2010, but I'm hoping someone has seen this and knows what to do about it - though not sure.
My configuration is like this:

*

*Microsoft Online Services (using Microsoft's Sign In App) - Connecting to Exchange

*I have two other Exchange accounts in this profile (new feature in 2010) connected through Outlook Anywhere.

*Life Meeting Conferencing Add In

*I've disabled the People tab/add in.

*I've disabled the "Send to Bluetooth" add-in.
Not sure what else to do?

A: Are you sure your PST files are ok?
look for a file named SCANPST.EXE in your program files \Microsoft Office\Office14 directory,
launch it, and have it check and repair your outlook mail files

A: I had this for months; early mornings were worst. Then one day I noticed it didn't happen. I'd left my phone in the pub (Office is installed on it as well), and its battery had died.  But when I collected it and turned it on, the errors came back.
I looked at the Outlook support page and the only thing I noticed was a switch for stopping reminders from getting tangled up. I closed Outlook and started it from the Run command:
outlook /cleansniff

Since then, no more crashes.

A: Let the Outlook download all the messages before performing any action on it .I have faced the same trouble too and this seems to help in my case

A: disable the Microsoft Conferencing Add-On for Microsoft in your Tools Add-Ons.
Make Sure Outlook is shut, then proceed

*

*Start > Control Panel > Programs and Features > wait for the list of all installed programs to populate the view

*Right click Microsoft Conferencing Addon For Microsoft Outlook > Uninstall > Yes

*Enter the Administrative username and password to perform the action as shown.

*Reboot > login > you have now saved time and avoided the Outlook bug (if Outlook crashes at this point, simply open Outlook again, it should be OK)


text:
Q: Can i use flex without Flex builder? i am starting to study FLEX. i have only flex sdk. So can i start study only using that. If so please suggest me the link to go through..
But still, Using an editor will minimize our work and will create the code by its own. So as a new learner it would be tedious to understand and also hard to learn new things...

A: If you are a student, you can get Flex Builder for free.
Free for students

A: I like FlashDevelop @ http://www.flashdevelop.org/
Open source editor for Adobe Flash/Flex for Windows (may work under Wine?).

A: You can certainly build application with solely the open source Flex SDK.  I have posted some instructions for using only the Flex SDK on Linux.  If you are on a different platform the instructions can be slightly adjusted.

A: Yes, you can use any text editor to write MXML and ActionScript code, and then use the command line to compile the code into a SWF (Flash Movie). The SDK does not include Charts, however.
http://opensource.adobe.com/wiki/display/flexsdk/Downloads

A: If you're on Windows, see if you can run mxmlc.exe (the compiler) from a command prompt.  Create a simple Example.mxml file to test it out.
mxmlc.exe Example.mxml

Here's a simple Hello World mxml source code.
Easy steps are well documented on Adobe's site and in chapter 2 of "Flex 3 in Action"

A: Yes.
Just a bit of background: Flex Builder (a.k.a Flash Builder), the mxmlc compiler (free) and Flash CSx all compile Actionscript code into SWF files and/or AIR files. Flash CSx is a design-centric tool with a ultra-simplistic coding editor built in (not much more useful than Notepad); Flex Builder/Flash Builder is a full-blown programmer's IDE (based on Eclipse); the mxmlc compiler is a free command-line tool that compiles Actionscript files into SWF and AIR files. (You have to use your own editor to write the source files.)
MXML is an xml language that acts as a shortcut for Actionscript. You can code in mxml instead of Actionscript and the compiler will convert your mxml into Actionscript before compiling. You can't use mxml as a shorthand for all AS coding. Mostly you can use it as a substitute for UI coding and as a way of binding data to UI elements. The compiler converts the mxml into Actionscript classes and then compiles the Actionscript classes (the ones created as mxml and the ones coded natively in Actionscript) into bytecode. The Flash virtual machine (e.g. the browser plugin) runs the bytecode.
Currently, you can code both Actionscript and mxml -- and then compile using Flex Builder/Flash Builder or the mxmlc compiler (which is free). Flash CSx can does not understand mxml, so you it can only compile straight-forward Actionscript.
Note: there are third-party tools, such as FDT that can also be used to write and compile Actionscript and mxml.
The language Actionscript has been revised several times. After a brief phase when it was a proprietary language, it morphed into something much like Javascript. Then, with AS 2.0, it became much more like Java -- and it continues in this direction with AS 3.0. (its syntax is very similar to Java and, like Java, it is class-based).
There are a core set of Actionscript classes that are available to you in Flash CSx, Flex Builder/Flash Builder and the free sdk. There are additional classes, known as the Flex Framework, which are available to you in Flex Builder/Flash Builder and in the sdk -- but not in Flash CSx. These extra classes add new visual components, such as a datagrid, an advanced UI-layout engine, and a framework for data-binding.
You can use the Flex Framework without the Flex Builder IDE (which is going to renamed, in the next version to Flash Builder).
Compiling without Flex Builder
You can also use Flex Builder/Flash Builder without using the Flex Framework -- meaning you can program in the IDE and use only Actionscript classes that aren't part of the framework (the classes you'd use if you programmed in Flash and not Flex Builder).
You can choose to use or not use mxml.
You can even use mxml to auto-generate Actionscript that's not part of the Flex Framework (e.g. your own custom classes).
Using mxml for your own classes
Good luck!
my Actionscript blog

A: Flex Builder (now Flash Builder) is based on the Eclipse IDE - it's actually a plugin to Eclipse. So with Eclipse being open source and free, you can use that as your editor.
You won't get the integrated debugger, and visual design view... but using some free plugins you can still be productive.
1) You'll need the Flex SDK: www.adobe.com/products/flex/flexdownloads/
2) Get Eclipse: eclipse.org/
3) Two notable Eclipse plugins:
   - www.eclipse.org/webtools/
   - www.aptana.com/studio
Alternatively, if you have MSFT's Visual Studio, there's a Flex plugin for that too:
- www.sapphiresteel.com/Adobe-Flex-Development-in-Visual
To compile your code you'll use the Flex compiler, information on how to use it can be found here:
www.adobe.com/livedocs/flex/3/html/compilers_13.html#150640
Chapter 2 of Flex 3 In Action also has a section on how to develop Flex applications without Flex Builder:
http://www.amazon.com/dp/1933988746/?tag=insidemark-20
Note that Flex Builder is free for academic faculty, students, and out of work coders. So that's another option.
Cheers.

A: Flex Builder will be the very best way to learn as its got a debugger and thus lets you step thru code see how it works. FlashDevelop is free tho it lacks a debugger - still very useful

A: Intellij actually has pretty good support. AS3 support is wonderful, but there is no WYSIWYG tool.
Still, it is not a problem for many programmers, as MXML is easy to read and edit without WYSIWYG.


text:
Q: Debugging why an element appears on page load briefly when opacity is set to 0 I'm sorry in advance if this question isn't deemed acceptable by the moderators.
I'm just not sure how to debug this issue because there is about 1 or 2 seconds to catch the problem occurring.
Please view this website.
The opening message with the coloured blocks are set to opacity 0 and then with jQuery, after a delay, we set the opacity to 1 and use CSS transitions to create the effects.
As far as I can make out, all three blocks are built the same way yet for some reason the green block is displaying briefly on page load before the opacity=0 kicks in.
Can anyone spot why this is happening or advise on how I can get to the bottom of this, everything looks the same across all three blocks in Chrome's dev tools.
I'd appreciate any advice. Thanks in advance.

A: Fixed the issue, wasn't anything to do with the loading of jQuery.
A CSS declaration of display: block for a particular media query and up was overriding the base default of display: none for a split second before the jQuery was setting the opacity to 0.


text:
Q: Static members of a Class I am beginner in JAVA, I was reading this code:
class trying1{
    static int x =40;
    public static void main(String ...s){
        trying1 t = new trying1();
        x =20;
        System.out.println(x); // print 20
        t.show1();
    }

    void show1(){
        System.out.println(x); // print 20
    }

}

class trying2{
    public static void main(String ...s){
    System.out.println(trying1.x); // print 40
    }
}

Why does it print 40 in  class trying2 ?
I know that static data members get memory only once and everyone shares that memory. As in Class trying1,  'x' is a class var, & if I change the value of x it will be  reflected in every instance of class or you can say it value will been changed at its memory location. aAfter compiling and running class trying1,  if I run trying2.class it shows 40 as output.
However its value should have been changed to 20?
Can someone help me out in this.
Thank you!!

A: If you start trying2, you start another JVM. The first instance of the JVM, that was using trying1 as the main class, is stopped, and whatever trying1.main(...) did, has no effect on the second JVM.

A: Maybe cause you never persist the new value, and every time x=40


text:
Q: Accessing vertices in the triangle++ (delaunay/voronoi triangulation) Wrapper class I'm using the triangle++ wrapper class from http://www.compgeom.com/~piyush/scripts/triangle/ to triangulate a point cloud for visulaizing with OpenGL.
I was able to put in my points and caluculate the triangulation. After that i also was able to access the vertices over a vertex iterator, how it is shown in the main.cpp example included in the package. Now i want to access the vertices over the face iterator (theres also an example in the main.cpp). I want to iterate over all faces and get the three vertices for every face. Has anyone done that already? I've been trying to modify the wrapper class for ~2 days already with no success.
thanks a lot in advance!
Sebastian

A: the sample code works, but doesn't contain what i want. I want to take one face an get all three vertices separately, for example:
Delaunay::fIterator fit  = delobject.fbegin();
double x0 = fit.GetVertex(0).x();
double y0 = fit.GetVertex(0).y();
double z0 = fit.GetVertex(0).z();
double x1 = fit.GetVertex(1).x();
double y1 = fit.GetVertex(1).y();
double z1 = fit.GetVertex(1).z();
or something like that. Of course these functions doesnt exist, but I even don't know how to access the vertices of a concret face in generally.

A: I got a solution for the problem. Just for the sake of completeness, which works like this:
double x0 = delobject.point_at_vertex_id(delobject.Org(fit))[0];
double y0 = delobject.point_at_vertex_id(delobject.Org(fit))[1];
double x1 = delobject.point_at_vertex_id(delobject.Dest(fit))[0];
double y1 = delobject.point_at_vertex_id(delobject.Dest(fit))[1];
double x2 = delobject.point_at_vertex_id(delobject.Apex(fit))[0];
double y2 = delobject.point_at_vertex_id(delobject.Apex(fit))[1];
...


text:
Q: AWS Amplify support for the Next js Image API Amplify's documentation shows that current version of Amplify does not support Next.js's Image API yet. Does anyone know if Amplify team has a plan to support Image API if so, when that will be released?

A: It appears Amplify hosting now supports Next.js version 11, which includes:

*

*Automatic image optimization

*incremental static regeneration

*script optimization

More info https://aws.amazon.com/about-aws/whats-new/2021/08/aws-amplify-hosting-support-next-js-version-11/


text:
Q: Front end developers vs HTML/CSS coders plus "the JavaScript developer" I was just googling around to find a good definition of front-end developer and the definitions that I found were pretty much "a guy that does HTML/CSS/JavaScript (jQuery)".
But I think this is no longer the case. Today we have very complex interfaces, say a single page BackboneJS app that require a lot more than just "a guy that does HTML/CSS/JavaScript" and has no background in Computer Science.
I would argue that the guy that engineers the front-end app (Backbone, Angular, etc) should be as (if not more) skilled  programmer than the guy that engineers the back-end.
So in my scenario (single page webapp - say with Backbone), I have 3 people:

*

*A back-end programmer - the guy responsible for all the API calls that the Backbone app would make

*A "front-end" programmer - they guy that's responsible for getting the work from the designer (wireframes if you will) and turning it into responsive, cross-browser, cross-platform HTML/CSS code

*The "JavaScript" developer who makes everything light up, hooks up the HTML/CSS to the API and brings the app to life.

My question is: What is the most usual modern dev team structure? How is the work usually divided between the front end and back end developers.
Of course if you only have full-stack developers that can produce JavaScript and say PHP equally well, then you have less of an issue. But still, who is the front-end developer and how do you call "the JavaScript developer"?
Excuse my simple language, I tried to stay as far away from terminology as possible.

A: I  agree it sounds like you do have a 'modern' dev team structure. Much like the last few I have been a part of.
I think inefficiencies can arise from defining responsibilities or 'domains' as intrinsic properties of the team though, it smells too much like a collection of jobs rather than a team of engineers adding the most value they can towards achieving a common goal.
I think full stack familiarity is essential, so everyone fluently speaks the same language - describing problems and solutions precisely (end to end if appropriate) builds confidence in the direction of the project, and accelerates discussion of the hard problems.  It also creates an 'us', an 'our thing' for each team member to get behind and own. If just one guy is 'the UI' you have a doorway to concepts like blame and martyrdom creeping in to the dynamic.
Conversely, shared ownership and skills, combined with having true expertise in specialised areas creates a fertile ecosystem where each member is inspired by their teammates, and has the empowering experience of building a fulfilling contribution, in which they 'led' the whole team, inspiring I turn.
Above all,  my opinion is there should be a recurring focus on the user, and the design of an ''experience' which transparently 'just works'
Honesty and trust in your team's abilities can't be manufactured,  however a culture with a pervasive appreciation of real customer service is what I've seen work before, to great effect.


text:
Q: MediatR command inside Azure Function ServiceBusTrigger Using some references, I have created the Azure Function App with Clean Architecture and the Project structure looks like this:

My Azure Function is of the type Service Bus Queue Trigger. Basically, I want to Call MediatR command CreateProductCommand inside this function trigger. So that, whenever there is a message pushed into Service bus Queue, I can read that and save that into SQL database using this MediatR command. CreateProductCommand has EF Core implementation.
public class SaveProductDataToDatabase
    {
        private readonly IMediator _mediator;

        public SaveProductDataToDatabase(IMediator mediator)
        {
            _mediator = mediator;
        }

        [FunctionName("SaveProductDataToDatabase")]
        public void Run([ServiceBusTrigger("product-data-dev-01", Connection = "ServiceBusConnectionString")] string myQueueItem, ILogger log)
        {
            log.LogInformation($"Processed message: {myQueueItem}");
        }
    }

I'm not sure how to use the CreateProductCommand inside this function trigger. Please help.

A: Adding MediatR command handler on top of a function is redundant as function is already a handler in itself and a small unit of work. A function has a single responsibility usually that responsibility is encapsulated in the function code. Unless your function has multiple responsibilities, which it shouldn't, MediatR is unnecessary.


text: Q: Write pre written bio page in real- time with delay I'm creating a website and i want to add a bio page to it. I want the user to come onto the website and the bio page to type as if it was being typed up in real-time. My first thought was to get some form of a bot to do it as I have experience with automation anywhere but then I thought that maybe it can be done by javascript/jquery. What I'm looking for would be similar to how it looks if two people were editing a document on google drive. You would see the cursor move as the other user types. The bio will be pre-written and there would be a delay in what is typed to replicate somebody actually typing. Sorry if this has been asked before, ive tried searching the web but im not sure what to even search for.


text:
Q: Bootstrap v4 buttongroup (radio button) smaller than button I am trying to get a dropdown and a multi-toggle (radio buttons) to stay aside of each other. However, I can't get why they keep appearing of different size... I use bootstrap 4.0.
here is the html snippet of my header

Price Indicies

        <button class="btn btn-primary btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" aria-haspopup="true" aria-expanded="false" data-toggle="dropdown">Boroughs
        </button>

            Boroughs
            Brooklyn hoods
            Manhattan hoods
            Queens hoods

            <input type="radio" name="options" id="sales" autocomplete="off">sales</input>

            <input type="radio" name="options" id="rentals" autocomplete="off">rentals</input>

Here is the live code:
https://run.plnkr.co/64KRhkyz35xXoeMw/

A: I am assuming you want them to the the same heihgt as the drop down button.  Your buttons are smaller because there is no text in them.  If you were to add a space ( ) they would be the size of the normal bootstrap button.  Then you would need to add the btn-sm class to make them the same size as the drop down button (or remove that class from the dropdown button).

A: You can use following css to have dropdown and radio button of same size
   label.btn.btn-primary {
      padding :13px;
  }


text:
Q: Como puedo sacar un dato de json node Hola amigos tengo el siguiente codigo
json:
"detail": [
        {
            "sum01": 10
        },
        {
            "sum01": 10
        },
        {
            "sum01": 10
        }
    ],

codigo:
 for (let i = 0; i < detail.length; i++) {
                console.log(detail[i])
        }

lo que mi imprime es esto { sum01: 10 }{ sum01: 10 } y lo que yo quiero que haga es tener es la variable ejemplo {sum01}, sum01
lo que quiero hacer es imprimir lo que esta dentro de las comillas de mi json pero no logro hacerlo

A: Te recomiendas que leas en la web de develop mozzilla que esta muy bien explicado.
Fijate si te sirve esto
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Lo podrias solucionar de la siguiente manera
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']


text: Q: Bootstrap3 --- How to split a page if it is a mobile device? I have a registration page in my application. And I want to split into 2 pages if the user is using a mobile phone. Could someone please suggest me some code to achieve this in Bootstrap 3?


text:
Q: solaris filemerge and pstack equivalents for linux Accepting the possibility of extreme ridicule, I must admit that I really miss sun Teamware's filemerge tool. I have switched from solaris to red hat linux, and find myself regularly missing filemerge (not to be confused with the Apple tool of the same name), as well as the solaris version of pstack (which worked on core files just as well as pids).
Do any experts out there have any advice of consolation? Better merging tools that incorporate ancestry? A single-line way to view the call stack of a core file?
Please help!

A: gdb -ex bt program_file core_file should print out the stack trace of the core file.
As for filemrege, there's a bunch of open source stuff:
tkdiff
meld
mgdiff
kdiff3

A: meld is great

A: I use kdiff3 instead of filemerge. kdiff3 can resolve conflicts much better that filemerge.
Usage:
kdiff3 x.A.cpp x.C.cpp x.P.cpp -o x.M.cpp

where:
x.A.cpp - ancestor version of x.cpp
x.C.cpp - child verion of x.cpp
x.P.cpp - parent version of x.cpp
x.M.cpp - merged file

These files are produced after you run the resolve command.


text:
Q: 'heroku logs' returns 'Response Code 404 (Not Found)' I'm logged into heroku but for some reason when I type:
heroku logs

...I get the following error message:
Response Code 404 (Not Found)

Any insight into what might be causing this or how to fix it? As additional info: I have Papertrail installed and sometimes my logs are rather long.

A: It's an issue on heroku's end: https://status.heroku.com/incidents/1249.  Hopefully they'll resolve it soon.

A: Issue can be resolved by logging in again using
heroku login


text:
Q: Cannot able to add more than one field in firestore database, but it works fine when adding single field MY index.js file:
const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {

 let action = request.body.result.action;

 var Name = request.body.result.parameters.Name;

 var Answer1 = request.body.result.parameters.Answer1;

  let query = request.body.result.resolvedQuery;

    const parameters = request.body.result.parameters;

    const inputContexts = request.body.result.contexts;

     if(action === 'save.name'  || inputContexts == 'welcome'  && action === 'save.answer1' || inputContexts == 'question1'){

                  admin.firestore().collection('users').doc('details').collection('user1').add({
                         name: Name ,
                       answer1 : Answer1

                    }).then(ref => {
                      console.log('Added new user');
                      console.log('name' +Name);
                      console.log('answer1' +Answer1);
                    });

    }
});

I am getting a typerror like admin.firestore(...).collection(...).document.add is not a function, When I attempt to store all the user details under a document 'details' . This code is just a attempt to check whether it is possible to add more fields in same document!
I'm using api v1 chatbot

A: You're getting this error because the method add is not supported by the Firestore library.  You're looking for the set method.  Change this line:
admin.firestore().collection('users').doc('details').collection('user1').add({

to this:
admin.firestore().collection('users').doc('details').collection('user1').set({


text:
Q: NullPointerException runtime error I'm pretty new to java and working on a program that should simulate the Mastermind game. Here's the description:
Write an application in Java that allows a user to play the game Bulls and Cows against a computer. The game works as follows: The computer chooses a 4-digit number in secret. The digits must all be different.  The user then guesses the number and the computer provides the number of matching digits. If the matching digit is in the right position it is a "bull", if it is on a different position it is a "cow"
There are two classes that I'm allowed to have: Oracle and Game. Oracle class generates the 4-digit number that computer picks and calculates the number of bulls and cows in the player's guess. Game class gets the number of bulls and cows from Oracle and reports it. I'm getting this error when I run the program:
the error appears to be here:
    at Game.play(Game.java:34)
    at BullsAndCows.main(BullsAndCows.java:5)
Can you help me figure out what's wrong? Thanks a lot.
these are the images of Oracle and Game classes as well as the main method

A: Oracle's member variable computer is not initialized.
That's because on Oracle's constructor, you're not initializing the member variable computer, but another variable with the same name, that's local to the method.
To fix it, on line 21 of Oracle, replace this:
Oracle computer = new Oracle();

by this:
computer = new Oracle();


text:
Q: Express error from Postman: column doesn't exist (in Node, Postgres, Express) I'm making an api on my express server for getting a single game information by id.
    router.get("/:id", async (req, res, next) => {
  try {
    const { id } = req.params;
    const result = await pool.query("SELECT * FROM games WHERE id = $1", [id]);
    res.json(result.rows[0]);
  } catch (err) {
    return next(err);
  }
});

I tested on Postman and it showed as below:
    {
    "error": {
        "length": 102,
        "name": "error",
        "severity": "ERROR",
        "code": "42703",
        "position": "27",
        "file": "parse_relation.c",
        "line": "3359",
        "routine": "errorMissingColumn"
    },
    "message": "column \"id\" does not exist"
}

When I made a post route for creating new game and a get route for all games, they both worked.
My game table is
    CREATE TABLE games
(
    pk_game_id SERIAL PRIMARY KEY,
    game_name VARCHAR NOT NULL
);

I tried to change /:id to /:pk_game_id, I got the same error. I need help debug this error.

A: In your table, you have create the primary key as pk_game_id. Therefore, you need to use the same name when sending query.
const result = await pool.query("SELECT * FROM games WHERE pk_game_id = $1", [id]);

I tried to change /:id to /:pk_game_id, I got the same error. I need help debug this error.

The id here indicates how you should deconstruct it in the req.param but the error msg said it is about column. Therefore, you may focus more on the postgresSQL side to debug. As long as you have successfully retreive it in the express side(eg. console.log(id) shows the right thing), there is no need to change it.


text:
Q: Microsoft Access, Calculations - Text Box Control Source vs VBA Functions I need opinions from others concerning the best approach.
I have a form and a report that are based on an already created and printed form (not access form).  This access form and report have close to 100 boxes that numerical values are assigned to based on a handful of numerical values from a table.  The remaining text boxes are calculations based on these handful of numerical values.  My original plan was to enter in the calculations into all the control sources of the text boxes.  So the control source of Box13 would be the values of Box2 + Box5.  Although this worked okay on the form, I now have a report as well with seven different subreports (to allow seven seperate distinctly different pages) that have these same boxes.  Now I need to go through and set each box to reference not only the box but also the subreport this box resides on.
The solution I am thinking is to put all these cacluations into vba functions.  Then the control sources for the text boxes on both the form and reports would just reference these VBA functions.  So instead of the control source of box13 being Box2+Box5 it will be Function Box13.  and so on and soforth.
This would allow easy maintenance if calcs where to need to change in the future and potentially make everything easier to understand.
What are your thoughts and ideas concerning my two options.  It is always great to hear opinions of others, so I appreciate any and all feedback.
Thanks,

A: An improved 'option 1':

*

*design one table to store the data directly entered by the user

*design a query to contain all data from the form and the calculated
fields

*use this query as data source for the report

The VBA approach should also work fine, but I would not use it in this situation.
My .02$ :-)


text:
Q: pass viewModel object from controller to view in asp.net MVC I have the following method in controller
public ActionResult Categorized()
{
    var x=new Test.Models.MobileClass();
    return View(x);
}

x object contains methods that return xmldocument data
how can I pass this object to view to access methods and  display data from  xmldocument in browser
I can display it element element by using the following code
document.writeln("@Model.getxml().ChildNodes.Count");

but I want to use for loop displaying the contents of object and the following code didn't work in javascript
var size=parseInt("@Model.Getxml().ChildNodes.Count");
for  (var i=0; i<size; i++)

{

    document.writeln("@Model.Getxml().ChildNodes[i].InnerText");

 }

can you help me please

A: First of all, your view should not be calling Getxml and mucking about with the XML DOM. It's the job of the controller to present the view with "ready to render" data. That's what a ViewModel is for.
public ActionResult Categorized()
{
    var foo = new Test.Models.MobileClass();
    var xml = foo.Getxml();
    var viewData = xml.ChildNodes.Cast<XmlNode>().Select(x => x.InnerText);
    return View(viewData);
}

Now we're passing an IEnumerable<string> to the view, containing just the values we want to render.
In the view, you should not be using javascript to render your data to HTML - use the view to render your data to HTML - the Razor template engine is really good at that! Something like...

@foreach (var item in Model) {

@item

}

A: The javascript will fail, since the variable i will be evaluated on the server side and doesn't exist then.
Use a foreach in the view, with razor:
@foreach(var child in Model.Getxml().ChildNodes)
{
    child.InnerText
}


text:
Q: Handle Firebase Auth Errores on Flutter for End Users Everytime i get an error, for example on the login screen: "invalid password", i get a string with a message like:

How can i change this message to an user friendly one? I tried with the following code that i found on another post:
class Errors {
  static String show(String errMsg) {
    switch (errMsg) {
      case 'ERROR_EMAIL_ALREADY_IN_USE':
        return "This e-mail address is already in use, please use a different e-mail address.";

      case 'ERROR_INVALID_EMAIL':
        return "The email address is badly formatted.";

      case 'ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL':
        return "The e-mail address in your Facebook account has been registered in the system before. Please login by trying other methods with this e-mail address.";

      case 'ERROR_WRONG_PASSWORD':
        return "E-mail address or password is incorrect.";

      default:
        return "An error has occurred";
    }
  }
}

But it always displays the default error on screen. I tried using "firebase_auth/wrong-password" or "wrong-password" on the cases but did not work. Did anyone have a better solution? I'm new on this!

A: try read this docs here:
https://firebase.flutter.dev/docs/auth/usage
As you can see on the docs, the letter is in small letter and is seperated by "-".

A: I searched a bit on the post from ZOthix and i did find the solution.

I post it here for anyone who needs it:

class Errors {
  static String show(String errMsg) {
    switch (errMsg) {
      case "email-already-in-use":
        return "Email already used. Go to login page.";
        break;
      case "wrong-password":
        return "Wrong email/password combination.";
        break;
      case "user-not-found":
        return "No user found with this email.";
        break;
      case "user-disabled":
        return "User disabled.";
        break;
      case "ERROR_TOO_MANY_REQUESTS":
      case "operation-not-allowed":
        return "Too many requests to log into this account.";
        break;
      case "ERROR_OPERATION_NOT_ALLOWED":
      case "operation-not-allowed":
        return "Server error, please try again later.";
        break;
      case "invalid-email":
        return "Email address is invalid.";
        break;
      default:
        return "Login failed. Please try again.";
        break;
    }
  }
}


text: Q: Как отобразить на карте все городские маршруты транспорта? Необходима карта всех городский маршрутов транспорта. Возможно ли наложить их всех друг на друга на одной карте, чтобы не прорисовывать вручную?


text:
Q: Use the command line (or python) to gradually shutdown a gui program Is it possible to use the command line (or python) to gradually shutdown a gui program?
For instance, would it be possible to gradually shutdown programs (such as pressing the X in the window, not killing the process), giving the user the ability to save unsaved files before the program shuts down (such as gedit?)

A: It's possible using wmctrl (packaged in ubuntu), which sends signals to EWHM/NetWM-compatible (most) window managers.
Closing kate gracefully would be done with the command:
wmctrl -c kate

A: I think the word 'gracefully' might better describe the type of shut-down you're after?
And have you tried just killall processname or kill pidnumber? (where processname or pidnumber are replaced with the name or PID of the process you're trying to shut down)
By default, kill sends a TERM signal which the application may treat as a graceful shutdown request (though its technically up to the developer what they do with the TERM signal).

A: The shutdown command lets you specify a grace period as well as a shutdown message (of your choosing) to warn users to save their work.

A: It seems unlikely there's a mechanism for shutting down a single application apart from shooting it dead.
It's probably better to think of the application as a black box. We could kill it, but it is difficult to influence its internal operation in subtle ways.
And from outside, shutting down gracefully (saving files, etc) is very subtle.

A: If the program is one you are writing, the best way to do this is to capture signals from the operating system and specify in the program how you want the program to handle them.  Then, you can use the (unfortunately named IMO) kill command to send the appropriate signal to the program so that it stops in the manner you want.  (Unfortunately, I have never done this with Python, but it looks like you may be able to use os.kill to send the signal.)  Of course, you could do the same thing if it's not a program you wrote, but you know (or find out, possibly by trial and error) that it handles a specific signal in a fashion you desire.
I don't have Ubuntu, but you may be able to get a list of signals available by typing man signal at the command line.


text:
Q: Add a trigger directly to the Qmenu Object from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtGui

class helpwindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Avirs Help')
        self.setGeometry(450, 350, 150, 600)
        self.ui()

class mainwin(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Qmenu')
        self.setGeometry(340, 340, 360, 700)
        self.ui()

    def ui(self):
        self.mainMenu = self.menuBar()
        self.project = QLabel()
        self.fileMenu = self.mainMenu.addMenu('File')
        self.fileMenu.addAction('Add File')
        self.aboutus = self.mainMenu.addMenu('About us')
        self.aboutus.triggered.connect(self.helpwindow) # this is where the problem is, i think

        # self.fileMenu.triggered.connect(self.loadImageFromFile)

    def helpwindow(self):
        self.newwin = helpwindow()
        self.close()

def main():
    app = QApplication([])
    win = mainwin()
    win.show()
    app.exec()

if __name__ == "__main__":
    main()

I don't want to add a new tab to the menu object, I just want to trigger a new window when the "about us" menu button is clicked. i know i could add an action button to it, but I don't think it is intuitive to do that for ab "about us" button


text:
Q: Android TextView I have an example in android that I am trying to run.
There were 2 ways to do it..
// Get a drawable
ColorDrawble redDrawable = (ColorDrawable).getResources().getDrawable(R.drawable.red_rectangle);

//Set it as a background to a text view
textView.setBackground(redDrawable);

When I put this in the Eclipse IDE I get an error ColorDrawble cannot be resolved to a type
I have the textview in the main XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView android:layout_width="fill_parent"
            android:id="@+id/texter"
          android:layout_height="wrap_content"
          android:text="this string"/>

</LinearLayout>

and the resources in the strings xml file
<resources>
    <string name="hello">Hello World, ResourceTesterActivity!</string>
    <string name="app_name">ResourceTester</string>
     <drawable name="red_rectangle" >#f00</drawable>
    <drawable name="blue_rectangle">#0000ff</drawable>
    <drawable name="green_rectangle" >#f0f0</drawable>
</resources>

**

A: It should be:
ColorDrawble redDrawable = (ColorDrawable)
          getResources().getDrawable(R.drawable.red_rectangle);

You don't need the dot (perhaps it's a typo).
Then press Ctrl+Shift+O (Organize Imports) to import ColorDrawble class.

A: you can simply use a drawable like this :
// Get a drawable
Drawable redDrawable = YourActivity.this.getResources().getDrawable(R.drawable.red_rectangle);

//Set it as a background to a text view
textView.setBackgroundDrawable(redDrawable);//i've changed setBackground with setBackgroundDrawable.

or you can directly use :
textView.setBackgroundResources(R.drawable.red_rectangle);

NOTE : clean and rebuild your project  , and run it to test
and for the drawable, you dont need to declare it in strings.xml , just add your drawable on the folder drawables , and it will work


text:
Q: How to hide dynamic properties in OData .net core I have a class that have dynamic properties. In dynamic property I want to show interface property (because OData does not support interface EDM yet). For example:
 public class Student
    {
        public Guid Id { get; set; }

        public string Name { get; set; }

        public IBackpack Backpack
        {
            get
            {
                return new Backpack() { Id = Guid.NewGuid() };
            }
            set
            {

            }
        }

        Dictionary<string, object> interfaces;
        public Dictionary<string, object> Interfaces
        {
            get
            {
                if (interfaces == null)
                {
                    interfaces = new Dictionary<string, object>
                    {
                        { "Backpack", this.Backpack as Backpack }
                    };
                }
                return interfaces;
            }
            set
            {
            }
        }
    }

My model config is :
 static IEdmModel GetEdmModel(ODataConventionModelBuilder builder)
        {
            builder.EntityType<IEntity>().Abstract().HasKey(s => s.Id);
            var entity = builder.EntityType<Student>();
            entity.Ignore(s => s.Backpack);
            builder.EntityType<Backpack>();
            builder.EntitySet<Student>("Student");
            var model = builder.GetEdmModel();
            return model;
        }

When I send request: https://localhost:44383/odata/Student
I am getting:
{
    "@odata.context": "https://localhost:44383/OData/$metadata#Student",
    "value": [
        {
            "Id": "18d63120-75e3-4039-ae41-23f2f5550cc7",
            "Name": "Test",
            "Backpack": {
                "@odata.type": "#ODataCoreTest.Backpack",
                "Id": "ac37d6ab-9064-4b54-ac33-84a4639e26c5"
            }
        }
    ]
}

I don't want to show dynamic properites when it was not selected. How can I do this?

A: Implement custom ODataResourceSerializer and override AppendDynamicProperties
public class CustomODataResourceSerializer : ODataResourceSerializer
{
    public CustomODataResourceSerializer(ODataSerializerProvider serializerProvider) : base(serializerProvider)
    {

    }

    public override void AppendDynamicProperties(ODataResource resource, SelectExpandNode selectExpandNode, ResourceContext resourceContext)
    {
        if (selectExpandNode.SelectedDynamicProperties?.Any() == true)
        {
            base.AppendDynamicProperties(resource, selectExpandNode, resourceContext);
        }
    }
}

public class CustomODataSerializerProvider : DefaultODataSerializerProvider
{
    private CustomODataResourceSerializer resuoruceSerializer;

    public CustomODataSerializerProvider(IServiceProvider serviceProvider) : base(serviceProvider)
    {
        resuoruceSerializer = new CustomODataResourceSerializer(this);
    }

    public override ODataEdmTypeSerializer GetEdmTypeSerializer(IEdmTypeReference edmType)
    {
        if (edmType.IsEntity())
        {
            return resuoruceSerializer;
        }
        return base.GetEdmTypeSerializer(edmType);
    }
}

Configuration:
configureAction.AddService(ServiceLifetime.Singleton, typeof(ODataSerializerProvider), sp => new CustomODataSerializerProvider(sp));


text:
Q: Convert an interpreter to a compiler? First off, I know this is a question asked by MANY other programmers before me. But I couldn't find any usable resource that could help me.
Well, I'm creating an programming language called "Light" the syntax is comparable to python but it has a strict object-orientated concept.
I have made an interpreter ( in C++ ) for this language yet, my problem is how to turn this into an executable. ( Or simply: how do I make a compiler ? )
Thanks for your attention
P.S.: I've found some links to a very old tutorial but it is in Pascal...
EDIT:
Well, well. Now I have found a suitable tutorial for C++.
About the project: There have been some changes. Now the language is called "Q." ( kju Dot ).

A: If all you really want is an executable, you can append the script to the end of an interpreter executable and have it run that.
See: https://stackoverflow.com/questions/5795446/appending-data-to-an-exe
Alternately, you can just have the interpreter load the code from a file in the same directory as the interpreter and get largely the same result, just with multiple files.
A true compiler would convert the code into some other language and use the compiler for that language. But if you just want to distribute executables, there's no need to do that.

A: You may also want to consider using System.Reflection.Emit from the .NET runtime to generate a .NET executable. This will give you access to an existing object-oriented environment which has already solved some problems for you, and the resulting exe can be platform-independent. The runtime will compile the intermediate code in the .exe to machine code as needed, so performance should be comparable to what you'd get from compiling directly to native code.

A: The first couple of steps lexing/parsing (and analysis, depending on how that's structured) can be the same. But you will need to convert your representation to a code-generating representation. Typically LLVM is used for hobbyists as it is pretty much the only remotely decent free code-generating library around.

A: You are asking about the technique known as "tracing compiler": the interpreter gathers information about code execution, and incrementally builds low-level code using collected data.
https://en.wikipedia.org/wiki/Tracing_just-in-time_compilation
https://stefan-marr.de/papers/oopsla-marr-ducasse-meta-tracing-vs-partial-evaluation/
The difference from the classical JIT is the fact that collected tracing data and compiled code is preserved from every run of a program, which gives you not only executable machine code but also optimization on a real (or training) data. The first pass is a set of tests, which must pass all program branches, to make code for every part of your program. The next ones are program runs on real data (production use), which collects and applies optimizations (things like branch ordering to most frequently used cases).
This method much more complex to implement than a classical compiler construction scheme, so it is not used frequently, and it is complex to find a good set of tutorials on how to do such alike compiler.


text:
Q: Speaker similarity using Resemblyzer I am using Resemblyzer to get the similarity chart for the speakers in an MP3 file that I have. But I am getting an AttributeError:
AttributeError: 'ExtAudioFile' object has no attribute 'closed'

The code:
from resemblyzer import preprocess_wav, VoiceEncoder
from demo_utils import *
from pathlib import Path

wav_fpath = Path("/Users/...")
wav = preprocess_wav(wav_fpath)

Entire error log:
/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/librosa/util/decorators.py:88: UserWarning: PySoundFile failed. Trying audioread instead.
  return f(*args, **kwargs)
Traceback (most recent call last):
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/librosa/core/audio.py", line 164, in load
    y, sr_native = __soundfile_load(path, offset, duration, dtype)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/librosa/core/audio.py", line 195, in __soundfile_load
    context = sf.SoundFile(path)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/soundfile.py", line 629, in __init__
    self._file = self._open(file, mode_int, closefd)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/soundfile.py", line 1183, in _open
    _error_check(_snd.sf_error(file_ptr),
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/soundfile.py", line 1357, in _error_check
    raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
RuntimeError: Error opening '/Users/sankalpbhatia/Dropbox/Mac/Desktop/voice_similarity/meta_full_qa.mp3': File contains data in an unknown format.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/sankalpbhatia/Dropbox/Mac/Desktop/voice_similarity/test_two.py", line 14, in <module>
    wav = preprocess_wav(wav_fpath)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/resemblyzer/audio.py", line 27, in preprocess_wav
    wav, source_sr = librosa.load(fpath_or_wav, sr=None)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/librosa/util/decorators.py", line 88, in inner_f
    return f(*args, **kwargs)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/librosa/core/audio.py", line 170, in load
    y, sr_native = __audioread_load(path, offset, duration, dtype)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/librosa/core/audio.py", line 226, in __audioread_load
    reader = audioread.audio_open(path)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/audioread/__init__.py", line 111, in audio_open
    return BackendClass(path)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/audioread/macca.py", line 200, in __init__
    url = CFURL(filename)
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/audioread/macca.py", line 140, in __init__
    filename = filename.encode(sys.getfilesystemencoding())
AttributeError: 'PosixPath' object has no attribute 'encode'
Exception ignored in: <function CFObject.__del__ at 0x7feee048e3a0>
Traceback (most recent call last):
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/audioread/macca.py", line 134, in __del__
    _corefoundation.CFRelease(self._obj)
AttributeError: 'CFURL' object has no attribute '_obj'
Exception ignored in: <function ExtAudioFile.__del__ at 0x7feee048eb80>
Traceback (most recent call last):
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/audioread/macca.py", line 335, in __del__
    self.close()
  File "/Users/sankalpbhatia/opt/anaconda3/lib/python3.9/site-packages/audioread/macca.py", line 329, in close
    if not self.closed:
AttributeError: 'ExtAudioFile' object has no attribute 'closed'
(base) Sankalps-MacBook-Air:voice_similarity sankalpbhatia$

How do I fix this?


text:
Q: When magento widgets are run for the first time do they alter the database? I've been following this tutorial http://www.magentocommerce.com/knowledge-base/entry/tutorial-creating-a-magento-widget-part-1 to create a Magento widget as part of an extension I'm working on.
Whilst the widget was created successfully and worked as I wanted it, I changed the code and started getting the following error
Warning: Invalid argument supplied for foreach() in app/code/core/Mage/Widget/Model/Widget/Instance.php on line 502

When I changed the code back, the error was still present. However when I copied all my module to a fresh Magento install then the error wouldn't appear.
Although my widget does not explicitly use the database does anyone know if the act of installing and uninstalling a Magento widget makes changes to the core databases tables and if it does, which tables are altered.
Thanks

A: The core_resource table contains a list of all modules, so adding a new module will cause a new row to be created.
If you have anything in your module's sql folder, that code will be run depending on your module's version.
Without knowing exactly what code was run and changed, it's hard to know what your specific problem is.
http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-6-magento-setup-resources

A: So if you followed that tutorial you linked to I do not think it changed any database settings.
You can tell if a module will add tables or modify table columns by the following method.
Assume the module is called Foo_Bar and it is installed in the "community" code pool (as opposed to core or local).
Navigate to app/code/community/Foo/Bar. You will at minimum usually see etc and Block directories there.
If you see a sql directory then this module makes db changes. You also need to understand a module is versioned and may initially make a certain table and then modify it.
By way of example you can go to any core module and look for the same. For example I am running Enterprise 1.12 and went to:
app/code/core/Mage/Sendfriend/sql/sendfriend_setup
I see:
mysql4-upgrade-1.5.9.9-1.6.0.0.php
mysql4-upgrade-0.7.3-0.7.4.php
mysql4-upgrade-0.7.2-0.7.3.php
mysql4-upgrade-0.7.1-0.7.2.php
mysql4-install-0.7.0.php
install-1.6.0.0.php
Note the upgrade x-y nomenclature. That is what core_resource keeps track of.
If you are wondering where your new module's settings are saved, that is actually in core_config_data. try this:
SELECT * FROM core_config_data where path like '%foo%';

Assuming you have some setting in the admin you named "foo".
Now back to your problem. That is a common php error. You are running a foreach on something which can not be iterated. The code right before that is probably not returning an array or collection or whatever.
Ideally you should always wrap the foreach with a statement that checks that the item you are iterating over is not empty.
You can also turn off displaying errors or suppress that error using the @ statement which is a bad practice...


text:
Q: Design classes for "two-dimension"-like expansion by inheritance I'd like to make two base classes (e.g. figure and move) with some children for each one(cube, sphere and so on for figure; shift, rotate, rescale and so on for moves). Initial number of figures and moves is unknown - it must be expandable. Each move should know how to move each figure, so having N figures and M moves means to have N*M function for them. (Adding a move requires creation of N functions for each already existing figure and adding figure requires creation of M functions for each already existing move).
The question is how to declare theese functions? For example, I'll have a class Set containing list of figures (aka vector) and I need to ask this class to move all the figures by i-th move. Probably set would have a method of
set::move_all (const move& )

and... well what next? The easiest idea is to create virtual method
class figure {
    ...
    virtual void move_this (const move& )
    ...
}

to call a virtual method move_figure
class figure_i: public figure {
    ...
    virtual void move_this (const move& M)
       {M.move_figure(*this);
       }
    ...
}

class move {
    ...
    template <class T> virtual void move_figure (T&) const
    ...
}

and specialize it for each i-th move like this
template <> void shift::move_figure <cube> (cube& C)
    {
    }

and so on, but virtual templates are illegal.

A: You are making things more complicated than needed.  You have a collection of objects (which you are calling figures) and a collection of actions (which you are calling moves).  The obvious choice from an OOP perspective is to make the moves methods in your figures classes.
Update
Based on the comment below, you should be using a linear algebra library such as boost::ublas.  There are others as well that you might want to look into such as Eigen (more or less shown below).
The basic idea is to abstract both the figures and the moves to generalize both so you don't have to rewrite the code for each possible combination.  Thus, you would create a base class which looks something like:
template <typename T> class figure
{
    std::vector<Eigen::Vector3d<T> > point_list;
    ...

    void applyTransform(const Eigen::Affine3d<T>& src)
    {
       for (auto pt=point_list.begin(); pt != point_list.end(); pt++)
           (*pt) = src * (*pt);
    }
}
In this case, you define your point list based on the shape you are rendering.  You can adjust meaning of the points in your derived classes to define specific geometric figures you're interested in.  The Eigen::Affine3D class is used to define the transformations you want to apply.  Eigen already has rotations and other affine transformations defined, so you should be able to reuse those.
You can also look into some specialized OpenGL or DirectX geometry classes which does all of this for you.

A: Well, my current solution is to use typeid/typeinfo to identify figure/move pair and call corresponding function (non-member) to move figure by this move from global object of map type like this
typedef pair<string, string> fm_pair_t;
typedef figure (*fm_act_f) (const figure& F, const move& M);
map<fm_pair_r, fm_act_f> global_fm_map;

class move {
   ...
   figure move_figure (const figure& F) const
     {map<fm_pair_r, fm_act_f>::const_iterator i =
          global_fm_map.find (fm_pair_t(typeid(F).name(), typeid(*this).name()));
      if (i == global_fm_map.end()) return F;
      return i->second (F, *this);
     }
   ...
};

and somewhere
figure cube_shift (const figure& _F, const move& _M)
   {const cube& F = *dynamic_cast <const cube*> (&F);
    const shift& M = *dynamic_cast <const shift*> (&M);

    // act here with F and M like normal instances of cube and shift!

   };

and, of course
global_fm_map(typeid(cube).name(), typeid(shift).name()) = cube_shift;

so unlike case of using templates, everything is independent and well expandable.


text:
Q: In Power Automate, how do I filter a list and save the result? I am trying to filter a list in Power Automate. I followed the instructions, and it's correct, but it doesn't save the result to my variable and there is no "output" variable for me to save it manually. How do I save the result?

A: Oh nevermind; I found the results, it was in the "Body" variable.


text:
Q: WebRTC audio distortion -- Intermittent and Repeated When engaging in a hangout (or via custom webrtc application) on a video and audio call, one caller will observe distortion in the affected party's audio. This distortion will directly correlate to the packetsSentPerSecond (as observed from chrome://webrtc-internals (from the affected side))

I've observed this pattern on two separate machines. Both Windows 7, (8 to 10) with Chrome 45.0.2454.93 m. The audio interface has been varying, with both internal and USB interfaces tested. Once it occurs, it continues to occur more repeatedly. The pattern also seems to reset. In the above figure, the valleys increase in frequency, and seemingly reset (~9:13) and repeat that pattern.
Wondering if anyone has seen a similar problem or has any thoughts on how this can be further diagnosed.


text:
Q: configure: error: cannot find the required ev_run() function despite trying to link with -lev I'm trying to install i3-gaps on Ubuntu and I've come across this problem:
I run
../configure --prefix=/usr --sysconfdir=/etc --disable-sanitizers

and then I get this error message:
configure: error: cannot find the required ev_run() function despite trying to link with -lev

A: You should install all needed build dependencies (-dev packages) with :
sudo apt-get build-dep i3-wm

and then retry your ./configure procedure.

You may be also interested with adding PPA to your system:

*

*i3blocks-gaps for Ubuntu 16.04 LTS (xenial) from ppa:monettes/i3wm-gaps

*i3-gaps-wm for Ubuntu 16.04 LTS (xenial) and Ubuntu 18.04 LTS (bionic) from ppa:kgilmer/regolith


text:
Q: Sorting list in python - Give priority I have two lists, each is made up of objects having a date. I am trying to combine them and then order by date:
combined = invoices + payments
combined.sort(key = lambda x: x.date)

All well and good. However, if there is both an invoice object and payment object on the same day, I want the payment to be placed in the list before the invoice.

A: Just do this instead:
combined = payments + invoices

python iterable.sort method is guaranteed to be stable. (See python docs on standar types, 5.6.4 note 9)
That means if there are 2 elements a and b on your list such that key(a) == key(b), then they'll keep their relative order (that means, if a was placed before b on the unsorted list, it'll still be like that after it's sorted).

A: You should be able to do something like this to get the sorting you want:
combined.sort(key = lambda x: (x.date, 1 if x in invoices else 0))

The idea being that, as long as the objects are distinct, you can create a sorting tuple that includes an indicator of which list the object came from.  That'll make it sort by the dates first, then fall over to the 2nd field if the dates match.

A: In addition to key=, you can also use cmp= in the sort function.
class Invoice(object):
    P = 1
    def __init__(self, date):
        self.date = date

class Payment(object):
    P = 0
    def __init__(self, date):
        self.date = date

l = [Invoice(10), Payment(10), Invoice(10)]

def xcmp(x, y):
    c0 = cmp(x.date, y.date)
    return c0 if c0 != 0 else cmp(x.__class__.P, y.__class__.P)

l.sort(cmp=xcmp)


text:
Q: What is the use of "Preview Assets" assets catalog in Xcode 11 beta? What is the use of "Preview Assets" assets catalog in Xcode 11 beta?

I have just created new project with SwiftUI.
I have checked release notes of Xcode 11 beta but there is no information about this assets catalog.
What is the use of it?

A: For more info about it:
The idea of it, it's to avoid releasing the files inside it into production. In that way you decrease the size of the build since they will be removed in the archive fase.
https://www.avanderlee.com/xcode/development-assets-preview-catalog/
Like @peterSchorn mentioned in the comment before mine

A: Now, when you layout your views you can preview it in Canvas (the window from the right side of the code editor).
Obviously, some images and other data for your app you can get only in runtime, from your API for example.
So all stubs can be placed into Preview Content folder, in particular in Preview Assets


text:
Q: How do I enable WebGL in headless chrome in Ubuntu? How do I enable webgl or install webgl in headless chrome in Ubuntu 14? I tried installing libosmesa6, but that did not help.
Can someone please point me in the right direction?
I want to use webgl to work with headless chrome and selenium tests? I am using nightwatch to run the tests.

A: This worked for me to get chrome to use osmesa
sudo apt-get install libosmesa
sudo ln -s /usr/lib/x86_64-linux-gnu/libOSMesa.so.6 /opt/google/chrome/libosmesa.so
google-chrome --no-first-run --user-data-dir=~/chrome-stuff --use-gl=osmesa

Warning: When running with osmesa the entire page is rendered with osmesa making it pretty slow. So, if there are tests you have that can run without WebGL you probably want to run them without osmesa.
Also note that chrome itself uses osmesa to headless test but it uses a specific version. At the time of this answer it was version 9.0.3. It also makes a few changes listed here
Otherwise to run headless in general I found this
https://gist.github.com/addyosmani/5336747


text:
Q: video.js Handle Click Event of the play/stop Button Hey Guys similar to the question here I would like to execute custom JavaScript, but when the small play/stop Button of video.js is pressed.
Image Until now I was not able to find a way of doing that, any Ideas?
Thanks

A: You can add an event listener on the button component.
player.controlBar.playToggle.on('click', function() {
  console.log('click');
});


text:
Q: pdfscreen's panel Table of Contents I am having trouble understanding how the panel table of contents of the pdfscreen package works. The only thing that I got from the documentation was that in an article-type document, the section names will become the default items in the table of contents, and that \tableofcontents should not be used in the body. So I did as instructed and created a test presentation from one of the templates online:
\documentclass[titlepage]{article}
\usepackage{xspace,colortbl}
\usepackage[screen,panelright,code,sectionbreak,paneltoc,chocolate]{pdfscreen}
 \margins{.5in}{.5in}{.5in}{.5in}
 \screensize{6in}{8in}

\usepackage{amsmath}

\title{\Huge\textbf{My Title}}
\\
author{\Large M. Y. Name \\
  {Department} \\
  {Organization} }

\setcounter{secnumdepth}{2}
\definecolor{darkblue}{rgb}{0,0,0.635}
%\maketitle

\begin{screen}
% \margins{.65in}{.65in}{.65in}{.65in}
 \margins{.35in}{.45in}{.35in}{.35in}
 %\screensize{6.25in}{8in}
 \screensize{5.25in}{7in}
 %\changeoverlay
 \paneloverlay{but.pdf}
 %\overlay{logo.pdf}
 \def\pfill{\vskip6pt}
 \definecolor{panelbackground}{rgb}{0.5,0.5,0.9}
 \backgroundcolor{white}
 \paneloverlayempty
\end{screen}
\setlength{\parindent}{0cm}

\begin{document}
\maketitle

\section{Overview}
Lorem
\section{Body}
Ipsum
\section{Summary}
Dolor
\end{document}

In a normal LaTeX document, the table of contents are updated after compiling twice. However, here I am unable to get the TOC to update after I modify my section headings or such. I do not understand this, as it appears rather ad-hoc (I made some changes, they did not appear after multiple compilations. I removed them, and the earlier sections appeared). Does anyone know what is happening and how to fix this so that I know the most recent table of contents will appear when I am making the presentation?

UPDATE: Gonzalo's solution works. There is another inelegant way through which i got it to work, though I don't know the exact mechanism. In the body, introduce the \tableofcontents and compile (twice). This suppresses anything that the package itself does and you get an updated table of contents. Now remove the TOC and the default pdfscreen table of contents takes over, with the updated contents.

A: Remove the auxiliary file .toc and compile again (two times).


text:
Q: What happen if Hawking radiation is not found? I'm not a physicist but reading from a few popsci books. I read that Hawking has equations that explain Hawking Radiation precisely, right? Is this equation a proof that the radiation is real or we still need more evidence. And if it's proven wrong what does it mean to have rigid equations.

A: I will first show a simple way to think of Hawking radiation and how we might indirectly observe it. If you have a particle on an accelerated frame it is within what is called a Rindler wedge. Below is a diagram of spacetime for an accelerated frame. We think of a particle in region I

The hyperbolic lines are regions of constant radius from the $45$ degree lines that are a particle horizon. An observer on an accelerated frame, with acceleration $g$, has the observer behind them at a distance $\rho~=~c^2/g$. The larger the acceleration the the closer to the horizon the observer is. It is also interesting that for two particles to remain a constant distance from each other they must have different accelerations.
One observer, call him Bob, in region $I$ is not able to ever observe anything in region $II$, say if there is an observer named Alice there, or communicate to region $II$, and Alice in region $II$ is not able to communicate to Bob.
The spacetime metric distances are parameterized as
$$
t~=~\rho sinh\omega,~x~=~\rho cosh\omega
$$
the angle $\omega$ is a parametrized time. the metric in the Minkowksi form is then
$$
ds^2~=~-d\rho^2~~-~\rho^2 d\omega^2~-~dy^2~+~dz^2.
$$
If we euclideanize this so that the metric is not Lorentzian we can then think of the unitary time development operator $U(t)~=~exp(-iHt)$ across region $I$ to region $II$. We do this to consider the evolution of a quantum fluctuation that encloses the origin of the diagram above. We then replace $i~\rightarrow~1$ and the time is evaluated for the entire loop, think of this as the perimeter of the loop, as $t~\rightarrow~\rho\omega|_0^{2\pi}$ $=~2\pi\rho$. We then have the operator $U(\omega)~=~exp(-2\pi\rho H)$.
Alice and Bob measure the quantum fluctuation, say a loop that encloses the origin, as a particle that emerges from the horizon and then approaches it again. The particle emerges from the past horizon slowly and then slowly approach the future horizon, for Bob in region $I$ can only observe in a redshifted and time dilated form. Alice in region $II$ observes the same. For this virtual loop we may think of Bob and Alice as witnessing different states $\phi(b,b')$ and $\chi(a,a')$, but which form an entangled state $\psi$ with density matrix $\rho_{AB}~=~\psi^*\psi$
$$
\rho(a,a',b,b')~=~\chi^*(a,a')\phi^*(b,b')\phi(b,b')\chi(a,a'),
$$
where Alice and Bob observe what can be found by tracing over Bob's and Alice's state variables $b,b'$ and $a,a'$.
The time evolution operator has become a thermal or Boltzmann operator. The temperature is then $\beta~=~2\pi\rho$ or
$$
T~=~\frac{1}{2\pi\rho k_B}.
$$
This is the Unruh effect, explained in elementary terms. The Rindler wedge has no curvature. A black hole of course has curvature; the Riemann curvature has zero Ricci curvature and is all Weyl curvature for a sourceless region. We can however "map" the Unruh effect to the black hole case. This is done by considering the Unruh case as a case of an observer close to the horizon on an accelerated frame. The Hawking radiation emitted for large $\rho$, which persists because of spacetime curvature can be realized by the substitution $\omega~\rightarrow~tc^3/4GM$ with then gives the temperature for the black hole
$$
T~=~\frac{\hbar c^3}{8\pi k_B GM}.
$$
This is a quick way to think of Hawking radiation.
We can now use this to consider the empirical cases possible. The most likely empirical evidence will come from Unruh radiation. I wrote a paper in 2006 that won an honorable mention by the GRF essay contest for how this could be done. The idea is to make a Bose-Einstein condensate (BEC) of Rb ions, and then pass these through a capacitor with a large electric field. The acceleration then induces a phase change on the BEC which is measured by detecting the paths of the ions. Unfortunately this experiment has not to my mind been performed. Other ideas that I think are "noisier" have been to look at various high energy scattering processes.
As for measuring Hawking radiation directly, that may be tough. We are not obviously going to produce quantum black holes, at least not any time soon. Primordial micro-black holes might have emerged from the big bang. However, the exponential expansion of space during inflation tends to suppress that. If primordial black holes were produced in the very early universe it might have been prior to the inflationary period, or maybe after the vacuum transition to generate reheating. In the latter case this would occur in a much less dense environment. However, fluctuations might have produced some of these.
If we absolutely fail to observe Hawking-Unruh radiation this would be a problem. A failure to observe Unruh radiation would be unfortunate. The failure to observe Hawking radiation directly might mean conditions in the early universe preclude the production of primordial black holes.
If Unruh radiation is not detected by some means it would point to something terribly wrong with our current understanding of physics. The physics is spacetime of accelerated frames plus quantum entanglement. The failure to detect this means either there is a flaw in how these two are being considered with each other. Maybe there is some additional physics we are not aware of. The other alternative is that something is fundamentally wrong with either relativity or quantum mechanics. This would be a very disturbing development.

A: Hawking radiation is a theoretical result from the analysis of quantum field theory in general relativistic, curved spacetime.  This sort of semi-classical analysis, combining aspects quantum mechanics of with classical GR, is a stepping stone to a full theory of quantum gravity.
The theoretical result does not prove that Hawking radiation exists. If Hawking radiation is found to not exist then the underlying theoretical methods used to derive it are incorrect in some way.  So far both classical GR and QFT have agreed with every experiment conducted.  In that sense neither theory would be fully broken by a no Hawking radiation observation, but the method used to combine the two would be suspect.
We should already expect both GR and QFT are incomplete on some level.  So maybe we know less about how to put them together than we think.  There are many other semi-classical GR results that would instantly become suspect.
For researchers who are working towards grand unified theories or other quantum theories of gravity, this would be a problem.  The two leading candidates for a quantum theory of gravity: string theory and loop quantum gravity, both predict Hawking radiation.
The Bekenstein-Hawking result for the entropy of a black hole is closely related to Hawking radiation.  Both string theorists and loop quantum graviteers hold their respective theories' independent prediction of the same result as strong proof of their validity.  Of course, no one knows which theory (or both, or neither) is correct.
Using LQG, Ashtekar et al. derived the Bekenstein-Hawking entropy.  Others have since expanded that result to include higher order corrections to the original Bekenstein-Hawking result.  Also using LQG, Barriera et al. reproduced the Hawking radiation spectrum.  Using string theory techniques, Banks et al. derived both the Bekenstein-Hawking entropy and the Hawking temperature, which is related to the radiation spectrum.  There are many other references that I'm forgetting...
If Hawking radiation is shown to be incorrect, then we can likely throw out both string theory and loop quantum gravity, since they both predict it.


text:
Q: Can php handle multiple http post request at the same time? I'am working on angularjs project in which there are 2 users admin and office staff.And to insert data to database i need to send data to server using http request using post method and this request is received on server side in php. This is simple request to server with some parameters and its working correctly until both the users hit submit button and http request is made at the same time. ie when http request is made by both the users at the same time.If that happens than 2nd request is does not get any response.Now  my question is that is there a way to check if server is processing one http request and make 2nd request wait.
angularjs:
$http({
    method: "post",
    url: $localStorage.weburl + "abc.php?f=abc_data",
    timeout: 1 * 10 * 2000,
    params: {
        action: "add"
    },
    data: {
        data1: data1,
        data2: data2
    }.then(function mySucces(response) {

    }, function myError(err) {
        $ionicLoading.hide();
        alert("Please check the connection");
    })
});

PHP:
function abc_data($conn)
{
    $_POST = json_decode(file_get_contents('php://input'), true);
}

A: You should try like this way
var deferred = $q.defer();
$http.post($localStorage.weburl + "abc.php",{action: "add"})
    .success(function (data) {
        deferred.resolve(data);
    })
    .error(function (error) {
        deferred.reject(error);
    });

return deferred.promise;

If you are using post method then pass you data like {data:arrayOfdata} instead of url: $localStorage.weburl + "abc.php?f=abc_data"


text:
Q: Parallel the particle swarm optimization in Julia I wrote the particle swarm optimization algorithm in Julia, and I tried to use Threads to accelerate the computation for each population.
Here is the code
function uniform(dim::Int, lb::Array{Float64, 1}, ub::Array{Float64, 1})
    arr = rand(Float64, dim)
    @inbounds for i in 1:dim; arr[i] = arr[i] * (ub[i] - lb[i]) + lb[i] end
    return arr
end

function initialize_particles(problem, population)
    dim = problem.dim
    lb = problem.lb
    ub = problem.ub
    cost_func = problem.cost_func

    gbest_position = uniform(dim, lb, ub)
    gbest = Gbest(gbest_position, cost_func(gbest_position))

    particles = []
    for i in 1:population
        position = uniform(dim, lb, ub)
        velocity = zeros(dim)
        cost = cost_func(position)
        best_position = copy(position)
        best_cost = copy(cost)
        push!(particles, Particle(position, velocity, cost, best_position, best_cost))

        if best_cost < gbest.cost
            gbest.position = copy(best_position)
            gbest.cost = copy(best_cost)
        end
    end
    return gbest, particles
end

function PSO(problem; max_iter=100,population=100,c1=1.4962,c2=1.4962,w=0.7298,wdamp=1.0)
    dim = problem.dim
    lb = problem.lb
    ub = problem.ub
    cost_func = problem.cost_func

    gbest, particles = initialize_particles(problem, population)

    # main loop
    for iter in 1:max_iter
        @threads for i in 1:population
            particles[i].velocity .= w .* particles[i].velocity .+
                c1 .* rand(dim) .* (particles[i].best_position .- particles[i].position) .+
                c2 .* rand(dim) .* (gbest.position .- particles[i].position)

            particles[i].position .= particles[i].position .+ particles[i].velocity
            particles[i].position .= max.(particles[i].position, lb)
            particles[i].position .= min.(particles[i].position, ub)

            particles[i].cost = cost_func(particles[i].position)

            if particles[i].cost < particles[i].best_cost
                particles[i].best_position = copy(particles[i].position)
                particles[i].best_cost = copy(particles[i].cost)

                if particles[i].best_cost < gbest.cost
                    gbest.position = copy(particles[i].best_position)
                    gbest.cost = copy(particles[i].best_cost)
                end
            end
        end
        w = w * wdamp
        if iter % 50 == 1
            println("Iteration " * string(iter) * ": Best Cost = " * string(gbest.cost))
            println("Best Position = " * string(gbest.position))
            println()
        end
    end
    gbest, particles
end

Obviously, it is not thread-safe in main loop of PSO. This is because the position of gbest needs to be modified when computing.
I tried to use Atomic, but the position of each particle is an array. So this method is not suitable.
The Lock needs initialization, so it also won't work.
I also tried to use Floop, but it went wrong.
So is there a way to make sure the data is locked when doing parallel computation?
Thank you for your time!
Wang

A: There is no need to lock variables. When you are doing parallel calculations you can always think in the terms of Split-Combine strategy (sorry just invent this term in analogy with DataFrames calculation, you may also call it Map-Reduce approach). The idea is that you split calculations around different threads and do them independently and on the final stage you combine results together on a single thread. So your code can look like this (there can be syntax errors, since I can't run the code without Particle and other definitions, but I hope it is enough to give the idea)
function minby(itr; by=identity, init=nothing)
     init = isnothing(init) ? pop!(itr) : init
     mapreduce(x->(by(x)=>x), (x,y)->(first(x)>first(y)) ? y : x, itr; init=by(init)=>init).second
end

function PSO(problem; max_iter=100,population=100,c1=1.4962,c2=1.4962,w=0.7298,wdamp=1.0)
    dim = problem.dim
    lb = problem.lb
    ub = problem.ub
    cost_func = problem.cost_func

    gbest, particles = initialize_particles(problem, population)

    # main loop
    for iter in 1:max_iter
        gbests = fill((gbest.cost, 0), Threads.nthreads())
        @threads for i in 1:population
            particles[i].velocity .= w .* particles[i].velocity .+
                c1 .* rand(dim) .* (particles[i].best_position .- particles[i].position) .+
                c2 .* rand(dim) .* (gbest.position .- particles[i].position)

            particles[i].position .= particles[i].position .+ particles[i].velocity
            particles[i].position .= max.(particles[i].position, lb)
            particles[i].position .= min.(particles[i].position, ub)

            particles[i].cost = cost_func(particles[i].position)

            if particles[i].cost < particles[i].best_cost
                particles[i].best_position = copy(particles[i].position)
                particles[i].best_cost = copy(particles[i].cost)

                if particles[i].best_cost < gbests[Threads.threadid()][1]
                    gbests[Threads.threadid()] = (particles[i].best_cost, i)
                end
            end
        end
        gbest1 = minby(gbests, by = x -> x[1])
        if gbest1[2] != 0
            idx = gbest1[2]
            gbest.position = copy(particles[idx].best_position)
            gbest.cost = copy(particles[idx].best_cost)
        end
        w = w * wdamp
        if iter % 50 == 1
            println("Iteration " * string(iter) * ": Best Cost = " * string(gbest.cost))
            println("Best Position = " * string(gbest.position))
            println()
        end
    end
    gbest, particles
end

By the way, you may find that package UnPack.jl is rather convinient. Instead of manual assignments, you can do just
using UnPack
function PSO(problem; max_iter=100,population=100,c1=1.4962,c2=1.4962,w=0.7298,wdamp=1.0)
    @unpack dim, lb, ub, cost_func = problem
    ....


text:
Q: Does admob provides rewarded video ads? I have a banner ad and an rewardes video ad the banner is working perfectly but the rewarded video is showing only test ads even with the real ad id

A: Wait for some times.
After waiting some times/hours if still having problem then you need to cross check Ad unit Id and AppId from AdMob account.
If you are able to load test ads but not live ads, it sounds like an issue with your AdMob account.
Make sure that you properly set up a payment system and/or verified your PIN? If they are not done, then live ads would not be served from your account.
I've link below, you can post your problem there.
https://groups.google.com/forum/#!category-topic/google-admob-ads-sdk/android/fBe3YL3ffpo