text:
Q: Error adding new column I'm trying to add an "account subcategory" column to my report using the query builder.
I added the column and got the error message:

"An MDX expression was expected. An empty expression was specified."

How do I format the MDX in order to get the result I am looking for?
I posted the code below. Hope this helps.
SELECT NON EMPTY { [Measures].[Order Partic Adj], [Measures].[PY Net Cash], [Measures].[Order Merch Adj], [Measures].[OCCURS - APY BOOKING FACT], [Measures].[PY Orders], [Measures].[Net Cash Merch Adj], [Measures].[Net Cash Acq Adj], [Measures].[Total Proj Orders], [Measures].[Order Acq Adj], [Measures].[Net Cash Partic Adj], [Measures].[Total Proj Net Cash] } ON COLUMNS, NON EMPTY { ([Current Assignment].[Territory Code].[Territory Code].
ALLMEMBERS * [Current Assignment].[Sales Rep Name Caps].[Sales Rep Name Caps].

ALLMEMBERS * [Current Assignment].[Sales Rep Employee Code].[Sales Rep Employee Code].
ALLMEMBERS * [Account].[Account Subcategory Name].[Account Subcategory Name].
ALLMEMBERS * [Account].[ACCOUNT NAME].[ACCOUNT NAME].
ALLMEMBERS * [Account].[LIFETOUCH ID].[LIFETOUCH ID].
ALLMEMBERS * [Account].[NACAM Ordered].[NACAM Ordered].
ALLMEMBERS * [Account].[ENROLLMENT COUNT].[ENROLLMENT COUNT].
ALLMEMBERS * [Account].[STATE].[STATE].
ALLMEMBERS * [Account].[District Name].[District Name].
ALLMEMBERS * [Account].[City].[City].
ALLMEMBERS * [Account].[COUNTY].[COUNTY].
ALLMEMBERS * [APY].[BOOKING STATUS].[BOOKING STATUS].
ALLMEMBERS * [APY].[X BOOKING STATUS ID].[X BOOKING STATUS ID].
ALLMEMBERS * [APY].[AT RISK IND].[AT RISK IND].
ALLMEMBERS * [APY].[INCENTIVE ACQUISITION IND].[INCENTIVE ACQUISITION IND].
ALLMEMBERS * [APY].[CY BOOKING CAMERA TYPE NAME].[CY BOOKING CAMERA TYPE NAME].
ALLMEMBERS * [APY].[CURRENT YEAR SELLING METHODS].[CURRENT YEAR SELLING METHODS].
ALLMEMBERS * [APY].[PY ACTUAL CAMERA TYPE NAME].[PY ACTUAL CAMERA TYPE NAME].
ALLMEMBERS * [APY].[ACQUIRED BUSINESS NAME].[ACQUIRED BUSINESS NAME].
ALLMEMBERS * [APY].[PRIOR YEAR SELLING METHODS].[PRIOR YEAR SELLING METHODS].
ALLMEMBERS * [Marketing].[SUB PROGRAM NAME].[SUB PROGRAM NAME].
ALLMEMBERS * [Current Assignment].[AMS Business Unit Name].[AMS Business Unit Name].

ALLMEMBERS * [Account].[POSTAL CODE].[POSTAL CODE].
ALLMEMBERS ) } DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS FROM ( SELECT ( STRTOSET(@APYBOOKINGSTATUS, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( STRTOSET(@CurrentAssignmentSalesRepNameCaps, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( STRTOSET(@CurrentAssignmentTerritoryCode, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( STRTOSET(@CurrentAssignmentRegionName, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( STRTOSET(@CurrentAssignmentAreaName, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( STRTOSET(@CurrentAssignmentAMSBusinessUnitName, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( STRTOSET(@CurrentAssignmentCountryName, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( STRTOSET(@SchoolYearSCHOOLYEAR, CONSTRAINED) ) ON COLUMNS FROM ( SELECT ( STRTOSET(@MarketingSUBPROGRAMNAME, CONSTRAINED) ) ON COLUMNS FROM [BO_APY_Booking_Fact_Full]))))))))) WHERE ( IIF( STRTOSET(@SchoolYearSCHOOLYEAR, CONSTRAINED).Count = 1, STRTOSET(@SchoolYearSCHOOLYEAR, CONSTRAINED), [School Year].[SCHOOL YEAR].currentmember ), IIF( STRTOSET(@CurrentAssignmentCountryName, CONSTRAINED).Count = 1, STRTOSET(@CurrentAssignmentCountryName, CONSTRAINED), [Current Assignment].[Country Name].currentmember ), IIF( STRTOSET(@CurrentAssignmentAreaName, CONSTRAINED).Count = 1, STRTOSET(@CurrentAssignmentAreaName, CONSTRAINED), [Current Assignment].[Area Name].currentmember ), IIF( STRTOSET(@CurrentAssignmentRegionName, CONSTRAINED).Count = 1, STRTOSET(@CurrentAssignmentRegionName, CONSTRAINED), [Current Assignment].[Region Name].currentmember ) ) CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS


text:
Q: pdfbox : PDTrueTypeFont.loadDescriptorDictionary java.lang.NullPointerException pdfBox / JSF
Im getting nullpointer exception when trying to load barcode ttf font.
InputStream inputStream1 = getClass().getResourceAsStream("/fonts/code128.ttf");
            font = PDTrueTypeFont.loadTTF(pdDocto, inputStream1);

If I try with another ttf font It loads with success.
Stack error :
Caused by: java.lang.NullPointerException
    at org.apache.pdfbox.pdmodel.font.PDTrueTypeFont.loadDescriptorDictionary

A: Ive downloaded another .ttf and it was resolved.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access ui from main window in another qdialog? I am having trouble accessing a QTextEdit from a main window in another form. Please help.
void properties::on_okWordPushButton_clicked()
{
    if (ui->wordcombo->currentText() == "All Words") {

        int wordCount = notepad->textEdit->toPlainText().split(QRegExp("(\\s|\\n|\\r)+"), QString::SkipEmptyParts).count();
        ui->wordcountlabel->setText(QString::number(wordCount));

    }
}

I am getting an error since I cannot read notepad->textEdit

A: You can use at least 2 possibilities:

*

*Dirty way:
On form creation, pass pointer to your QTextEdit:

// mainwindow.cpp
auto myProperties = new properties(notepad->textEdit);
...

// properties.h
QTextEdit *outerEditor;

// properties.cpp
properties::properties(QTextEdit *editor) {
 outerEditor = editor;
 ...
}

Then, on your slot you can use:

int wordCount = editor->toPlainText().split(QRegExp("(\\s|\\n|\\r)+"), QString::SkipEmptyParts).count();

*Qt-way:
Remember - signals/slots are awesome.

Just after form creation, you can connect signal from MainWindow to properties passing text in your QTextEdit and store it locally:
// MainWindow.cpp
auto myProperties = new properties(notepad->textEdit);
connect(this->textEdit, QOverload<QString>::of(&QTextEdit::valueChanged), myProperties, GetNewValue);

// properties.h
void GetNewValue(QString val);

// properties.cpp
void properties::GetNewValue(QString val) {
    ui->wordcountlabel->setText(QString::number(val.toPlainText().split(QRegExp("(\\s|\\n|\\r)+"), QString::SkipEmptyParts).count());
}

A: You can't do this, the ui is a private member of a widget, create a function that returns or sets what you need!


text:
Q: wine has to be removed before installing nvidia-331 I would try the method of this link nvidia-libopencl1-331 has to be removed before installing WINE
But the Problem is i already have wine installed and so here is my problem.
I installed wine1.7 pepperlight and PlayOnLinux. The Problem would be i could delete these things and reinstall everything, but there should be an easier way.
Here my error:
        Die folgenden Pakete haben unerfüllte Abhängigkeiten:
        nvidia-libopencl1-331 : Kollidiert mit: libopencl1
                             Kollidiert mit: libopencl1:i386
        ocl-icd-libopencl1 : Kollidiert mit: libopencl1
        ocl-icd-libopencl1:i386 : Kollidiert mit: libopencl1

A: Sorry, but you may be out of luck. You could try temporarily disabling the driver, but the instructions work or bust. Sorry!


text:
Q: Why characters received in serial connection only after pressing enter? I have a simple PC to board connection using serial (9600, no parity, 8 bits, no hw flow)
I opened simple terminal *with teraterm) in PC and enter keys in teraterm and in board, I just do
 cat /dev/ttyO5

I see the pressed characters in scope, but I see the characters in the board console, only after pressing "enter" in teraterm (as if they are stored in some FIFO in Linux driver which only enter triggers out)

*

*why are the characters received in Linux driver only when pressing enter key  ?

*Is there some way to receive the characters without pressing the enter key ? (we use some protocol of ascii so it does not make sense to send this as dummy)

Thanks for advise,
Ran

A:
but I see the characters in the board console, only after pressing "enter" in teraterm

The behavior you describe is characteristic of canonical read (aka reading lines).
The behavior you seem to want is called non-canonical read (aka raw read or binary read).

*

*why are the characters received in Linux driver only when pressing enter key ?

No, the Linux serial port driver is receiving every character as it is appears on the wire.
Each character is buffered (typically in DMA-able memory), and then forwarded to a line discipline handler, which is also buffering the received data.
A canonical read() syscall by the userland program is blocked until the line discipline handler detects a line termination character.

*Is there some way to receive the characters without pressing the enter key ?

Yes, before issuing the cat command, configure the serial port to non-canonical mode:
stty -F /dev/tty05 raw

or more likely the correct device node is
stty -F /dev/ttyO5 raw

Or use the termios interface to configure the serial port to non-canonical mode in a userspace program on the board.  Sample code is here.
Documentation on how to properly program a serial port are
Serial Programming Guide for POSIX Operating Systems and Setting Terminal Modes Properly.


text:
Q: Mathematica: difference between periodogram and periodogramarray Right now I'm doing spectral analysis with sounds, and it is strange that drawing a graph with  Periodogram[] doesn't give the same result as using PeridogramArray[] and then using ListLinePlot[]. Is there anything I am understanding wrong?
Source code:
test1 = Import["/Users/phillipchang/Desktop/sounds/test1.wav",
  "SampledSoundList"]

Periodogram[test1]

ListLinePlot[PeriodogramArray[test1], PlotRange -> Automatic]

A: Any possibility you are working with stereo (or better) sounds?
http://reference.wolfram.com/mathematica/ref/PeriodogramArray.html
"For multichannel sound and image objects, a list of power spectra of each channel is returned."
http://reference.wolfram.com/mathematica/ref/Periodogram.html
"Periodogram also works with SampledSoundList objects. When applied to a multichannel sound object, it plots power spectra of all channels."
Click on "Details and Options" on each of those and read all the details.
People seem to routinely skip right over "Details and Options."
I can't guess what your sound file is, but you might also consider using a windowing function to minimize artifacts introduced if your sound file does not contain an integral multiple of cycles for every frequency present in the file.
Good debugging method might be to construct a sound that is a single pure sine wave with an integral number of cycles, convince yourself that you are absolutely positive that file is correct and then try your code on it. Debug until the spectra is correct. Then add a second frequency, still integral number of cycles, to the file and repeat. When all that has been done then you may have eliminated the problem with your original file.


text:
Q: Syntax error when trying to put together constant and string Normally i wouldn't post syntax errors here, but this case is a bit suspicious to me. I was trying to put together a constant with a string. I works fine on localhost, but when i push my project on my web server, it tells me:
Parse error: syntax error, unexpected '.', expecting ',' or ';' in xxx on line xxx

Code:
define("ROOT", str_replace("index.php", "", $_SERVER["SCRIPT_FILENAME"]));

and
$somePath = ROOT . "some/path"; //Synax error in this line

Has this something to do with different PHP versions? (5.5 on webserver, 7.0 localhost)
Update
Some updates in the code:
class SomeClass {

    private $somePath = ROOT . "some/path"; //Synax error in this line

    ...
}

A: You can't use str_replace() nor any function when defining a contant. Try:
define("ROOT", $_SERVER["SCRIPT_FILENAME"]);
$somePath = str_replace("index.php", "", ROOT) . "some/path";

Please refer to PHP Manual:

In PHP 5, value must be a scalar value (integer, float, string, boolean, or NULL). In PHP 7, array values are also accepted.


text:
Q: After post saved to database, how do I route to another ejs page How can I load another page after a post in node.js with ejs.
//router
function router() {
   ticketRouter.route("/create/submit") // tied to submit from one ejs
      .post(dataControllerThatTakesCareOfThis) // works fine

    // either in here, or even the controller I suppose I want to load another page after the submit takes place?
     res.redirect(200, '/load:postSubmit') // doesn't work
     res.send({ redirect: '/load:postSubmit' }) // great for ajax response only

}

module.exports = router;

So is the above something that you can do in node.js without having to go back out to the client with some information and then have it ask the question in order to process it? Is there a 'redirect' or a way to route the response like this?
Thanks

A: Supposing you're using ExpressJS and EJS is your Template Engine :
You should handle your redirection into the dataControllerThatTakesCareOfThis function.
These two lines :

// either in here, or even the controller I suppose I want to load another page after the submit takes place?
 res.redirect(200, '/load:postSubmit') // doesn't work
 res.send({ redirect: '/load:postSubmit' }) // great for ajax response only

Won't work because they are using the res object which is not defined here but in the callback of the Post method of the Router object.
More info in the express documentation


text:
Q: Выполнение задания из учебника Python Возникла проблема с заданием в учебнике. Задание написано так:
Кинотеатр установил несколько вариантов цены на билеты в зависимости от возраста посетителя. Для посетителей младше 3 лет билет бесплатный; в возрасте от 3 до 12 билет стоит $10; наконец,если возраст посетителя больше 12, билет стоит 15$.
Напишите цикл, который предлагает пользователю ввести возраст и выводит цену билета. ДОП ЗАДАНИЕ:
Выход из цикла по команде break, если пользователь вводит значение 'quit'
Собственно условия в цикле написаны, не могу понять как сравнить со значением 'quit' вот код
age = "How old are you?"
age += "\nEnter 'quit' to exit: "
while True:
    message = input(age)
    age1 = int(input(age))
    if message == 'quit':
        break
    elif age1 <= 3:
        print("Cinema is free")
    elif age1 <= 12:
        print("Cinema cost's 10$")
    else:
        print("Cinema cost's 15$")
    break

A: Исправленная версия программы
age = "How old are you?"
age += "\nEnter 'quit' to exit: "
while True:
    # возраст уже ввели в message, не нужно его спрашивать для age1 ещё раз
    message = input(age)
    # но перед тем, как перевести message в age1, проверим, не ввели ли quit
    # если сначала попробовать перенести значение в age1, будет вызвано исключение, в результате попытки использовать оператор int('quit')
    if message == 'quit':
        break
    age1 = int(message)
    if age1 <= 3:
        print("Cinema is free")
    elif age1 <= 12:
        print("Cinema cost's 10$")
    else:
        print("Cinema cost's 15$")

Результат работы программы:
How old are you?
Enter 'quit' to exit: 5
Cinema cost's 10$
How old are you?
Enter 'quit' to exit: 5
Cinema cost's 10$
How old are you?
Enter 'quit' to exit: 3
Cinema is free
How old are you?
Enter 'quit' to exit: 15
Cinema cost's 15$
How old are you?
Enter 'quit' to exit: quit

A: У вас пересекаются условия age <= 3 и age <= 12 (второе включает в себя первое). Плюс не понятно зачем вам второе break вконце цикла, который срабатывает всегда, независимо от ввода
age = "How old are you?"
age += "\nEnter 'quit' to exit: "
while True:
    message = input(age)
    if message == 'quit':
        break
    elif int(message) <= 3:
        print("Cinema is free")
    elif 3 < int(message) <= 12:
        print("Cinema cost's 10$")
    else:
        print("Cinema cost's 15$")


text:
Q: How to center and span table heading (row) I need to know how to center and span the "MyTable" heading. Can it be down with both HTML (the center tag) and CSS? I tried playing around with text-align, positioning etc but I couldn't get what I want.

<!DOCTYPE html>

My Table

FName	LName	Age

Derp	Derpania	69

Buzz	Killington	42

If there's a solution in both CSS and HTML, please give me both.

A: You have to add colspan to the th element.

My Table

FName	LName	Age

Derp	Derpania	69

Buzz	Killington	42

Fiddle: http://jsfiddle.net/y0tyapz6/


text:
Q: is it possible to save a link of a symbol chart as a screenshot from tradingview? For example i want to open this link using python request then :
extracting the chart of that symbol as .jpg or .png :
this is the link :
https://www.tradingview.com/chart/?symbol=FX:EURUSD&interval=60
i want a way to get that link chart as a screenshot without opening the browser ?
i want it cause i need it in my trading bots signals .


text:
Q: How can we configure the install4j executable to take query parameters provided in the custom uri to take as arguments to pass to the main app We have defined custom uri scheme for our Mac OS X using install4j but couldn't find a way to pass query parameters to the app as arguments using custom uri so that those are being passed to the underlying main method as arguments for us to process.
Example :
customuri://?somekey=value
when opened in a browser the app opens up with the parameters to be processed.

A: The application has to be registered to handle the URL invocation.
This is not related to install4j.
See
Handle custom URL schemes in an OS X Java application


text:
Q: Image collections are not recognized as the same size for processing I have two merged collections of images (LANDSAT and LANDTREND).
  var collection = Collection.select(['NDVI_to_ajust'],['LANDSAT']).merge(
    imageCollection.select(["NDVI"], ["LTGEE"]))

I need to store as property NDVI values calculated by each image collection, separately in array form, in 50 different samples (which are as a FeatureCollection called "antropVegPrima"). I used "reduceRegions" to do this.
var triplets = collection.map(
    function(image) {
    return image.reduceRegions({
      collection: ignoradoSamples50,
      reducer: ee.Reducer.first().setOutputs(image.bandNames()),
      scale: 30,
      tileScale: 4
    }).map(
      function(feature) {
      return feature.set({
        'imageID': image.id(),
        'date': ee.Date(image.get('system:time_start')).format('Y-MM-dd')
      })
    });
  }).flatten();

However, I have a problem that the size of the LANDSAT (124 x124) images is not the same as the LANDTREND (123 X12) image collection.
I was able to run this script for a sample collection determination, available at this link
However, for another collection of samples, the processing is not complete, as I demonstrated in this link


text:
Q: Simplified and manageable ACL implementation in cakephp I went through complete lesson on cakephp's ACL component, but gigantic ACL component do not seem to meet my very simple requirements.
I have only group based access control, three groups are users, managers and administrators the fourth is a anonymous users without logins for which I am not creating any group.
from acl concept it creates three table
aros -> this looks somewhat redundant data copied from groups table, I dont even need to have a group table but just field group_id in users table.
acos -> this is a list of public methods in controllers, I had to use AclExtra plugin to populate over 250+ actions in table, now this is the part which I think un-manageable, I noticed that tool used to populate acos table cannot reliably sync everytime when I do changes in controllers, the same work must be done at remote site for each changes that means terrible thing! this also mean i have to have a database backup during updates and migration.
Other side if I use php file based acos that is again un-manageable because we have to make sure syncing between controller and acl file.
aros_acos -> obviously
can we have a simpler mechanism something like i deny all actions using Auth component and then inside each action or maybe in beforeRender method i can specify what methods are open to what group ?
Thanks

A: There is an undocumented acl class PhpAcl it is much simpler to use than then the database driven ACL and more dynamic than the ini bassed ACL.
In Config/core.php
/**
 * The class name and database used in CakePHP's
 * access control lists.
 */
Configure::write('Acl.classname', 'PhpAcl');
// Configure::write('Acl.database', 'default');

This tells your ACL to use the PhpAcl
Then open up Config/acl.php
There are some good instructions there

Assumptions:

*

*In your application you created a User model with the following properties:    username, group_id, password, email, firstname,
  lastname and so on.

*You configured AuthComponent to authorize actions via    $this->Auth->authorize = array('Actions' => array('actionPath' =>
  'controllers/'),...)
Now, when a user (i.e. jeff) authenticates successfully and requests a
  controller action (i.e. /invoices/delete) that is not allowed by
  default (e.g. via $this->Auth->allow('edit') in the Invoices
  controller) then AuthComponent will ask the configured ACL interface
  if access is granted. Under the assumptions 1. and 2. this will be
  done via a call to Acl->check() with
array('User' => array('username' => 'jeff', 'group_id' => 4, ...))

as ARO and
'/controllers/invoices/delete'

as ACO.

I wanted to use static names for Groups or Roles so you can add a role field to your user table, and then set up the $map like this:
 **
 * The role map defines how to resolve the user record from your application
 * to the roles you defined in the roles configuration.
 */
$config['map'] = array(
    'User' => 'User/username',
    'Role' => 'User/role',
);

For my app we aren't using user based permissions only role, so we could remove the User from the $map.
Then you need to set up some roles:
/**
 * role configuration
 */
$config['roles'] = array(
    'Role/admin' => null,
);

Any role not in this array will get 'Role/default'
Now just set up your permissions, they are pretty self explanatory.
/**
 * rule configuration
 */
$config['rules'] = array(
    'allow' => array(
        '*' => 'Role/admin',
        'controllers/Reports/*' => 'Role/default',
        'controllers/EurRates/*' => 'Role/default',
        'controllers/Posts/index' => 'Role/default',
        'controllers/Users/(edit|index)' => 'Role/default',
    ),
    'deny' => array(
        'controllers/ProtectedController/*' => 'Role/default',
        'controllers/EurRates/(edit|add|delete)' => 'Role/default',
        'controllers/Reports/(edit|add|delete)' => 'Role/default',
        ),
);

That's it, now you can allow or deny permission to actions based on role.


text:
Q: Javascript Content Slider Before I put the html and css, I am having 2 problems, please keep in my that I am almost a complete amateur at html and css, and have no idea what the javascript means.
Problems:

*

*My 1st problem is that the content sider, doesnt slide far enough to the next content, but instead when clicking the button only brings the content over halfway (you will see what I mean when you paste the html and css into a page).

*My second problem is that the buttons are meant to be horizontal with eachother, and I also want to add more in the future
so if someone could tell me how to do that in elaboration with the javascript problem that would be great!
here is the working demo jsfiddle please check-out
Working code
Thank-you in Advance..!!

 // just querying the DOM...like a boss!
var links = document.querySelectorAll(".itemLinks");
var wrapper = document.querySelector("#wrapper");

// the activeLink provides a pointer to the currently displayed item
var activeLink = 0;

// setup the event listeners
for (var i = 0; i < links.length; i++) {
    var link = links[i];
    link.addEventListener('click', setClickedItem, false);

    // identify the item for the activeLink
    link.itemID = i;
}

// set first item as active
links[activeLink].classList.add("active");

function setClickedItem(e) {
    removeActiveLinks();

    var clickedLink = e.target;
    activeLink = clickedLink.itemID;

    changePosition(clickedLink);
}

function removeActiveLinks() {
    for (var i = 0; i < links.length; i++) {
        links[i].classList.remove("active");
    }
}

// Handle changing the slider position as well as ensure
// the correct link is highlighted as being active
function changePosition(link) {
    link.classList.add("active");

    var position = link.getAttribute("data-pos");
    wrapper.style.left = position;
}
#wrapper {
    width: 5000px;
    position: relative;
    left: 0px;
    transition: left .5s ease-in-out;
}

.content {
    float: left;
    width: 1250px;
    height: 600px;
    white-space: normal;
    background-repeat: no-repeat;
}

#itemOne {
    background-color: #ADFF2F;
    background-image: url("http://www.kirupa.com/images/blueSquare.png");
}
#itemTwo {
    background-color: #FF7F50;
    background-image: url("http://www.kirupa.com/images/yellowSquare.png");
}
#itemThree {
    background-color: #1E90FF;
    background-image: url("http://www.kirupa.com/images/pinkSquare.png");
}
#itemFour {
    background-color: #DC143C;
    background-image: url("http://www.kirupa.com/images/graySquare.png");
}

#contentContainer {
    width: 98%;
    height: 600px;
    border: 5px black solid;
    overflow: hidden;
    margin-left: 1%;
    margin-right: 1%;
}
#navLinks {
    text-align: center;
    width: 22.5%;
}
    #navLinks ul {
        margin: 0px;
        padding: 0px;
        display: inline-block;
        margin-top: 6px;
    }
        #navLinks ul li {
            float: left;
            text-align: center;
            margin: 10px;
            list-style: none;
            cursor: pointer;
            background-color: #CCCCCC;
            padding: 100px;
            border-radius: 10%;
            border: white 5px solid;
        }
            #navLinks ul li:hover {
                background-color: #FFFF00;
            }
            #navLinks ul li.active {
                background-color: #333333;
                color: #FFFFFF;
                outline-width: 7px;
            }
                #navLinks ul li.active:hover {
                    background-color: #484848;
                    color: #FFFFFF;
                }
#navLinks ul li.active {
    background-color: #333333;
    color: #FFFFFF;
    outline-width: 7px;
}
#navLinks ul li.active:hover {
    background-color: #484848;
    color: #FFFFFF;
}

A: The main areas to update;
1) your "#contentContainer". This is basically the window of your slider. The height and width need to be updated to match the slider items.
2) the "data-pos" values of your list items. This should be the same as their width * their index starting at 0 and negative.
3) the list container is too narrow. make it as wide as your #contentContainer.
CSS Changes:
#contentContainer {
  width: 1250px;
  height: 600px;
}
#navLinks {
  width:1250px;
}
#navLinks ul li {
  width:80px;
}

HTML change:

https://jsfiddle.net/partypete25/9gpyL6o1/7/embedded/result/

A: I assume that the CSS posted in the bottom of your question is the content of the main.css file. As matt points out in the comments, experiment with changing the sizes of the divs. Particularly the #wrapper, which is specified by it's ID using tha hash tag (#):
#wrapper {
    width: 5000px;
    position: relative;
    left: 0px;
    transition: left .5s ease-in-out;
}

And referenced in the javascript here:
var wrapper = document.querySelector("#wrapper");

where it is assigned to the variable wrapper. It is 5000 pixels wide. The typical desktop web screen is around 1200 - 1700 pixels wide, I believe, for reference. This is about the size you want the .content, referenced by class using a . and what holds each displayed "slide" to be - keeping in mind that a responsive site that displays properly on phones and other mobile devices would need to have variations on the size using @media queries.
So I would add visible css borders where applicable (for development and to be removed later) and change around the numerical variables (data-pos, #wrapper and .container sizes) to find the optimal solution. As mentioned above, jsfiddle is a great resource, whether or not you're needing to share publicly.
For the navlinks, which should be displayed in a row, try the following CSS on the div that holds the list (
):
    #navLinks {
            text-align: center;
            width: 90.5%;
            border:1px solid white;
    }

The border:1px solid white; will help you to see where the div is. Then experiment with a smaller padding size in #navLinks ul li to be sure you have room on the page to display horizontally.
I believe the last step is to adjust the

, where the data-pos attributes are just holding information for the javascript to use in the changePosition function, which is the last few lines of the javascript.
eloquentjavascript.net is a wonderful, free source to learn all of this.

A: <!DOCTYPE html>

<title>Dinosaurs 4 Kids!</title>


text:
Q: Redmine + Git = 404 Пытаюсь прикрутить Git(2.6.4) к Redmine(3.3.2).
Мне передали папку с файлами (HEAD, description, config, index, COMMIT_EDITMSG, hooks, info, logs, objects, refs)
Я закинул ее на сервер в корень приложения. В Администрировании включил Git поддержку. В настройках проекта для хранилища указал путь "/repo/rep.git" . Появился раздел "Хранилище". Но перейдя туда получаю 404 и сообщение: Хранилище не содержит записи и/или исправления.
Подозревал, что путь указал не правильно, но вроде все норм... В чем может быть проблема?


text: Q: Rutherford's and Bohr's model of atom Rutherford's model of atom was ruled out because it failed in explaining stability of an atom. Since any particle that is accelerating continuously emit radiation. And in case of an atom eventually electrons fall into the nucleus. Bohr said that they revolve in stable orbits around the nucleus. Still they're in uniform circular motion right? Why don't they radiate energy and fall into the nucleus?


text:
Q: Google Chrome Css Issues And WordPress Child Theme I've been working on my first WordPress child theme for a couple of days and have it looking just fine in firefox but when I check in chrome there's odd issues and no matter how hard I try and can't seem to  resolve them.
You can check the site out here...
http://stevefleming.co.uk

And the list of issues I've found are...
Front page: Main text to right of lemon is screwed up.
Widgets: All the headings have disappeared
Navigation: Gone!
Blog Title (and the rest): lemon has gone and top margin/padding has changed.
Blog: List of articles is missing thumbnails

I'm hoping that somebody more experienced than myself can spot the mistakes easily because I've been going round in circles for hours.
Thanks in advance
Steve

A: Just in case anybody with similar issues comes along the answer to all my problems was connected with the list of fonts the theme was listing. The first one on the list wasn't on my machine and Firefox correctly traversed the list and picked one but Chrome didn't
Instead of failing gracefully and giving some kind of message bits that relied on those fonts just didn't show.
I'm learning to loathe Chrome more and more each day.
Steve


text:
Q: How can I secure a CVS and Web Server Network? As part of my computer security class, I have to design a network topology diagram and security system for a fake software design company.
It has to have an external anonymous cvs server, external web server, internal cvs and web servers, and a mail server. I'm kind of getting lost between all the different security vulnerabilities.
This is what I have so far
Outside users are supposed to only access external servers...and internal users should be able to publish code to the external cvs server.
So my main question is: Will a dual firewall and DMZ defense work in this situation?
How does the web server fit in to this? I've heard that there should be defense from the back end of a website, like for user authentication. I'm going to be using github enterprise when I state some of my security designs and assumptions, but how does that fit in with my topology?
Github Security


text:
Q: Class two time repeating in Jquery Here is slideshow of three images, which is have fadeIn and fadeOut effect on every image, but when i add one new css animation effect fadeInLeft to middle image then it repeats two time, why ?
But if i remove fadeInLeft class to middle image then all three image comes one by one correctly, i need to add fadeInLeft effect but after that middle image not should be repeat again.
What mistake am making, can i know plz.
my code is:

$(document).ready(function() {
    var timer;
    $(".slideshow2 > div:gt(0)").hide();
    $(".slideshow2")
        .mouseenter(function() {
            if (timer) { clearInterval(timer) }
        })
        .mouseleave(function() {
        var delay = document.getElementById("rrrr").value;
            timer = setInterval(function() {
                $(".slideshow2 > div:first")
                    .fadeOut(500)
                    .next()
                    .fadeIn(500)
                    .end()
                    .appendTo(".slideshow2");
            }, delay);
        })
        .mouseleave();
});
.slideshow2 { position:relative;  height:332px; width:500px; overflow:hidden; }
.slideshow2 div{ position:absolute; }

img {
width: 100%;
height: 100%;

}

.fadeInLeft {
    animation: fadeInLeft 1000ms both;
}
@keyframes fadeInLeft {
    from {
        opacity: 0;
        transform: translate3d(-100%, 0, 0);
    }

    to {
        opacity: 1;
        transform: translate3d(0, 0, 0);
    }
}

<input type="text" id="rrrr" value="2000" placeholder="2500 is 2.5s" style="width:50">

A: You "absolutely" need to know which image is showing when... When dealing with "absolutely" positionned images. (did you notice the play on words? .oO(lol)). So I added a data-number attribute on each divs just to be able to clearly view what happens with them during the animation. There is no other use to that beyond debugging.
Additionnaly... Instead of having everything chained, define some meaningful variable names, so you can clearly read what you are coding.
So you will notice that the image "on top" (the first in the current markup at any time) is the one that is visible and fades out. Then, the slide in animation is done on class addition. You need to remove and add it again to have it "done" by CSS... And that needs to be done on the image "next image" (the second in the div stack) while the image "on the top" is fading out.
I suggest a fadeout time a bit longer than the slide in time for a "nice" effect.
In order, here is what happens at every interval iteration:

*

*Define the elements in some variables, so it's clear what you apply on which element.

*Remove the fadeInLeft class on all images.

*Add the fadeInLeft on the second image (so the animation starts right away). The chained .show() enact immediately to ensure it is visible.

*Start fading out the first div immediately... And when it is totally faded out, move it to the end of the div stack. Notice that is done using the .fadeOut() "complete" callback.

$(document).ready(function() {
  var timer;
  $(".slideshow2 > div:gt(0)").hide();
  $(".slideshow2")
    .mouseenter(function() {
      if (timer) {
        clearInterval(timer)
      }
    })
    .mouseleave(function() {
      var delay = document.getElementById("rrrr").value;
      timer = setInterval(function() {

        // Define some meaningful variable names
        let allDivs = $(".slideshow2 > div")
        let firstDiv = allDivs.eq(0)
        let nextDiv = allDivs.eq(1)

        allDivs
          .removeClass("fadeInLeft")

        nextDiv
          .addClass("fadeInLeft")
          .show()

        firstDiv
          .fadeOut(1200, function() {
            firstDiv
              .appendTo(".slideshow2");
          })

      }, delay);
    })
    .mouseleave();
});
.slideshow2 {
  position: relative;
  height: 332px;
  width: 500px;
  overflow: hidden;
}

.slideshow2 div {
  position: absolute;
}

img {
  width: 100%;
  height: 100%;
}

.fadeInLeft {
  animation: fadeInLeft 1000ms both;
}

@keyframes fadeInLeft {
  from {
    opacity: 0;
    transform: translate3d(-100%, 0, 0);
  }
  to {
    opacity: 1;
    transform: translate3d(0, 0, 0);
  }
}

<input type="text" id="rrrr" value="2000" placeholder="2500 is 2.5s" style="width:50">


text:
Q: curl -d equivalent in Node.js http post request I know that the command
curl -X POST -d 'some data to send' http://somehost.com/api

can be emulated in Node.js with some code like
var http = require('http');
var post_data = 'some data to send',
    headers = {
        host: 'somehost.com',
        port: 80,
        method: 'POST',
        path: '/api',
        headers: {
            'Content-Length': Buffer.byteLength(post_data)
        }
    };

var request = http.request(headers, function(response) {
    response.on('data', function(d) {
        console.log(d);
    });
});
request.on('error', function(err) {
    console.log("An error ocurred!");
});
request.write(post_data));

request.end();

The question is because I'm looking for the equivalent in node of the cURL command
curl -d name="Myname" -d email="myemail@gmail.com" -X POST http://somehost.com/api

how can i do that?
This is because I wanna do a POST request to a Cherrypy server like this one, and I'm not able to complete the request.
EDIT The solution, as @mscdex said, was with the request library:
I've resolve the problem with the request library. My code for the solution is
var request = require('request');

request.post('http://localhost:8080/api', {
  form: {
    nombre: 'orlando'
  }
}, function(err, res) {
  console.log(err, res);
});

Thank you!

A: You could encode it manually:
var post_data = 'name=Myname&email=myemail@gmail.com';

Or you could use a module like request to handle it for you (becomes especially nice if you have to upload files) since it will handle data escaping and other things for you.


text:
Q: is there any difference between 'it' and 'this' to these sentences? Do they have same meaning? Is there any difference by intuition?

*

*What does it signify?

*What does this signify?

A: There's a subtle difference.
"This" is indicative. For example, if you pointed at something, you would refer to it as "this".
"It" is referential. If you mentioned something, you would refer to it as "it".
So, "What does it signify" asks what the thing you are talking about signifies (usually the subject of a recent phrase). Similarly, "What does this signify?" asks what the thing you indicated (drew attention to) signifies.
Here's an example where the two refer to different things.

"That book is Jeff's favorite. What does this signify?"

This asks what Jeff's fondness for the book signifies. Jeff's fondness for the book is the thing you just indicated.

"That book is Jeff's favorite. What does it signify?"

This asks what the book itself signifies. The book is the subject of the preceding phrase.
("It" need not always refer to the subject of the previous phrase, of course, that's just how it works in this case. Consider, "Mary saw the beautiful bicycle in the store window. She wanted it." This is not saying she wants herself!)
Consider:

"You remember the book that is Jeff's favorite? What does it signify?"

The preceding sentence doesn't really indicate anything. You cannot change "it" to "this" here.

A: Both it and this are pronouns that refer to other objects or concepts. As used in these sentences, they each refer to something that has been identified in a prior sentence.
While both are nominally singular, it is slightly more aggressively so, and would be used when a discrete single thing or concept has been previously identified.

They raised the blue flag. What does it signify?

The sentence could either mean

What does the blue flag signify
or
What does the raising of the blue flag signify.

To convey either of these meanings, you could also say

What does this signify?.

This is a somewhat broader term and can be used to refer to a single concept or to multiple things that together form a pattern or concept.

They ran around, fired cannons and shouted Hurrah! What does this signify?

The collection of events is being discussed as a whole, and this refers to that amalgam. In this case, it would generally seem too narrow.
You could say

They ran around, fired cannons and shouted "Hurrah"! That was a strange set of behaviors. What does it signify?

In this example, the events have been summarized into a discrete item, set and it becomes appropriate. But this could also be used.
In many cases, either would do. In some, this would be preferred.

A: They appear to mean the same thing, but again it depends on how they're used. For example "this" refers to an object.
That book belongs to George, but this book belongs to me.
That book is with George, but it belongs to me.


text:
Q: Invalid Entitlements iOS SDK 4.1 Ever since upgrading to the 4.1 SDK my Entitlements are no longer valid when users try to install the Ad-Hoc builds.  We originally had this issue a long time ago and and solved it by adding to the project an Entitlements.plist file with a get-task-allow = false key.
I don't think I've changed anything in the project configuration except upgrade the Base SDK to "iOS Device 4.1".   I've also tried removing and creating a new entitlements file with no luck.

A: Here's a working Entitlements file screenshot:
The Code Signing Entitlements key in the project settings should be blank.

A: Be sure that your setting for code signing identity is the same for Target and Project.
I had a problem of getting "Signer is not valid" error when installing through other iTunes than the one on the development mac. Very odd, but there you go.
Target is reached by right-clicking your app name under targets in the left menu and 'get info'->build
check all three configurations, debug/release/ad hoc they are not necessarily the same, but they have to be the same as in Project (target:debug as project:debug and so on), which is reached by using the top menu, "Project"->edit project settings->build
Having all three matching up made my ad hoc builds work again... after much headache and hair pulling. Hope this helps. :)

A: Try revoking your Ad Hoc mobile provisioning profile and regenerating it.  Sounds a bit hacky, I know, but I've had a number of issues with build signing that I had to resolve by nuking everything and starting over from scratch.

A: If you are using Development profile then you have to set the value of the Entitlement to true. But if you are using Distribution profile then the value should be false.
I tried this and it worked for me.

A: After Mucho Frustrationado, I finally (with the help of this thread) got my app working again! :)
Thanks for the tips everyone, especially Nicki!
My situation was that I had an app working on my 3GS, set it aside for a few weeks and when I came back to it, I remembered that I was having trouble. I was merely trying to get a Debug version on my phone, but ran into the situation where it would start to load (you'd catch a glimpse of the Default.png), and then it would quit. The Debugger just said:
Error launching remote program: failed to get the task for process 532.
Error launching remote program: failed to get the task for process 532.
The program being debugged is not being run.
The program being debugged is not being run.
I went through the whole Entitlements quaqmire, and finally, after revoking all my certificates (through Keychain Access) and re-creating all my Provisioning Profiles, Developer Certificate, et al, and today's step which revolved around all kinds of screwed up version values in my Project and Target Build settings.
Today, my last piece of the puzzle, was to get all the versions and Code Signing stuff straightened out as Nicki described. Make sure no "gremlin" settings (values you may have plugged while pulling your hair out) are left behind, check the versions match (the Base SDK you're publishing for) in Project and Target Build, check the Entitlements (I had to manually assign mine as there were multiple Distribution profiles, and Xcode guessed wrong), cross your eyes, and Build and Run on your device.
Thanks again everyone! Hope this little tidbit helps someone else connect the dots. :)
Ciao,
-Jei.

A: Code signing entitlements are no longer necessary for Ad Hoc builds in Xcode 4 - see details notes in Apple Technical Note TN2250


text:
Q: The 'powerbi://api.powerbi.com/v1.0/myorg/MyDataset;initial catalog' property name is not formatted correctly Trying to refresh a Power BI dataset via SQL Server 2017 Agent Job.
Run As user has full sysadmin access.
Running via XMLA script inside SSMS query works perfectly in refreshing the Power BI dataset
Executing the XMLA script via SQL Server Agent job gives the following error:
Message Executed as user: GROUPETVA\ManSha01. Microsoft.AnalysisServices.Xmla.ConnectionException: The connection string is not valid. ---> System.FormatException: Input string was not in a correct format.   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
For the server name, I have tried the following formats:
a) powerbi://api.powerbi.com/v1.0/myorg/Conformité - TI - ITGC;initial catalog=S4M_Conformite-AvecR
b) powerbi://api.powerbi.com/v1.0/myorg/Conformit%C3%A9%20-%20TI%20-%20ITGC
c) powerbi://api.powerbi.com/v1.0/myorg/Conformit%C3%A9%20-%20TI%20-%20ITGC;initial catalog=S4M_Conformite-AvecR
All of the above are triggering the same error.
Here is how the job step appears in the SQL Server Agent SSMS:

Here is where I copied my connection string for my Power BI workspace:

I cannot figure out what the correct format for my Power BI workspace connection string is for the SQL Server Agent to accept.
Note that I had even tried copying the connection string of my sctual dataset in Power BI:

However, I am getting the same "property name is not formatted correctly" error.
Does anyone have any further insight into properly getting the PowerBI dataset refresh working in SSMS via the SQL Agent?
Thanks in advance,
Shawn


text:
Q: how to slide images in a block in drupal 7 Is there any module in drupal 7 that provides image sliding. My images are in a block. It has about 10 images positioned horizontally and there will be arrows at the end of blocks that will slide images left or right. Images will slide only if arrows are clicked. Is there any module doing that job in drupal 7?

A: Check out the Views Slideshow module and the related modules that are linked on that page.


text:
Q: what is the bracket used for in making an instance on android? for example like this code.
Button button1 = (Button)findViewById(R.id.button1);

what is the bracket() in the button used for?

A: The bracket around the Button says - You are casting the view as Button.


text:
Q: Read XML to LabVIEW as task / Cluster using Python to configure DAQ I am trying to load an XML file that will be used to configure my DAQ in LabVIEW.
So when looking at the options I have:

*

*my XML channel configuration is dynamic - meaning one XML may have 3 channels the other may have >100 channels.

*would be much easier for me to pars the xml in Python and pass the data as structure/task to LabVIEW.

e.g. for XML channel
<Channels>
        <Channel name="CH_PH1" enable="True" visible="False" virtual="False" units="A" physical_channel="PXI1Slot2/ai0" b_factor="0" m_factor="1033.221069" measurement_type="VOLTAGE" type="D" max_value="0.1" min_value="-0.1">
          <RollingAvg do_rolling_avg="False" rolling_avg_frame_sec="0" />
        </Channel>
        <Channel name="CH_PH2" enable="True" visible="False" virtual="False" units="A" physical_channel="PXI1Slot2/ai1" b_factor="0" m_factor="1073.772766" measurement_type="VOLTAGE" type="D" max_value="0.1" min_value="-0.1">
          <RollingAvg do_rolling_avg="False" rolling_avg_frame_sec="0" />
        </Channel>
        <Channel name="P_CH" enable="True" visible="False" virtual="True" units="V" formula="CH_PH1*CH_PH2" doTotalEnergy="False">
          <RollingAvg do_rolling_avg="False" rolling_avg_frame_sec="0" />
        </Channel>
        <Channel name="P_PH_Total" enable="True" visible="False" virtual="True" units="V" formula="CH_PH1+CH_PH2" doTotalEnergy="False">
          <RollingAvg do_rolling_avg="False" rolling_avg_frame_sec="0" />
        </Channel>
</Channels>

My code in Python to parse the xml:
def xml():
    import xml.etree.ElementTree as ET
    tree = ET.parse(r'C:\Users\LAB_PTG\Desktop\Cosmo_v0.93.6\nidaq.xml')
    root = tree.getroot()
    P={}
    C={}
    for Channel in root.iter('Channel'):
        z=(Channel.attrib)
        if z['virtual']=='False':
            P.update({z['name']:(z['physical_channel'],z['enable'],z['m_factor'],z['max_value'])})
        else:
            C.update({z['name']:(z['formula'])})
    print(P,C)

Help needed:

*

*how to execute the code in LabVIEW?

*how to handle DICT in LabVIEW? or is there a better solution to pass the data?

*use the paras data to dynamically configure the DAQmx channels

I didn't manage creating a xml parser in LabVIEW as it enforces more hard coding and having a fixed stricture.
I am targeting the LV DAQmx continues sampling  example and replace the configuration with the parsed xml.

Thanks for every one supporting
Assaf Baker

A: Parsing XML in Labview
Parsing XML in LV is a bit tricky, but not that difficult. Maybe, you give it a try?
This code loops over all channels, extracts attributes name and virtual, and from their children RollingAvg, it extracts the attribute do_rolling_avg.

May be, it is more handy to get a list of all attributes / values of a node first, and then work on the generated array:

Now, it is important to close all references at the end to avoid a memory leak, which is done quick and dirty, here.
Further more, if something is not found, the search VIs will throw an error. (Your Python will do so, too). Some error handling should be added if necessary.

If you insist on using Python
Today, there's an option to run Python directly from LV. I don't know this, my LV is from 2017.
There, it is possible to use the System Exec.vi to run any command on the commandline, and read its output back into LV:

Finally, what Python prints, will be returned as string.
I'd work with JSON, which easily converts a dict to JSON:
import json

a=[]
a.append({'name':'CH_PH1', 'virtual':False, 'RollingAvgFrame':3.141})
a.append({'name':'CH_PH2', 'virtual':True, 'RollingAvgFrame':42.0})
print(json.dumps(a))

Output:
[{"name": "CH_PH1", "virtual": false, "RollingAvgFrame": 3.141},
{"name": "CH_PH2", "virtual": true, "RollingAvgFrame": 42.0}]

In LV, define a cluster according to the JSON structure, and use the Unflatten from JSONVI to fill it. The names of the cluster elements must match those in the JSON code.

However, JSON knows only simple data types. There is no way to transfer time or any other more complex datatype, unless it can be packed as something more simple like a string containing a timestamp.


text:
Q: Laravel session and auth issue in MacOS I have a issue with my laravel project in macOS. I have project where in a moment could be have two auth actives, with diferent guard. Is a place where teacher can be accés to play like a student. Then I use two guards and some sessions variables. After do the second auth in ajax Request, the code have a redirect. In mac this redirect goes to login page and not to Student home.
This source works perfect in windows, and in Linux Server. But not in MAMP or XAMPP in macOs.
Some idea?
thank you


text:
Q: Deleting a file IF any folders in current directory contain a keyword using batch I am trying to write a batch file that takes a backup using temporary folders and a "sub-batch" file that needs to be deleted once all backups are completed.
The method I'm trying to use copies a batch file to the main directory, opens multiple instances of this batch which create "temp" folders, then they remove the temp folder once they are done their business.
I want to implement a command at the end of the sub-batch that checks if any folders with the word "temp" exist in the directory, then delete the sub-batch if none exist.
I have tried many iterations, but this is what I kind of ended at before asking this question:
rd %TempFolder% /S /Q

cd C:\BackupDirectory
if exist C:\BackupDirectory\*_Temp_*\ goto :unconnect
del subBatch.bat
:unconnect

I realize that this won't work, but I can't find a good way to find the string "temp" in the sub-directory name.
Any help is appreciated.


text:
Q: Py2app can't read files I want to read from a file with a python application. Here is my source code.
MyApplication.py:
if __name__ == '__main__':
    fin = open("/absolute/path/to/file.txt", "r")
    fin.readline()
    fin.close()

setup.py:
# Copied and pasted it from their docs
from setuptools import setup
setup(
    app=["MyApplication.py"],
setup_requires=["py2app"],
)

Then I try to run python setup.py py2app and everything goes smoothly, however when I open the app a popup appears saying "MyApplication Error".
Is there a way for me to solve this or at least get more information about what's happening?

EDIT FOR MORE CLARITY:
The line that is causing problems is fin.readline(). Also, writing to files works, and reading a file that the app itself has created doesn't generate errors. This code, for example, works.
if __name__ == '__main__':
    fout = open("/absolute/path/to/newfile.txt", "a+")
    fout.write("Test\n")
    fout.close()
    fin = open("/absolute/path/to/newfile.txt", "r")
    line = fin.readline()
    fin.close()
    fout = open("/absolute/path/to/newfile.txt", "a+")
    fout.write("Line read: " + line)
    fout.close()

The output file will show:
Test
Line read: Test

A: I found this hint veeery useful:

"right click -> Show Packages -> Resources -> Mac OS", and execute your app directly do help, because it shows specific errors on the console

Source: http://uxcrepe.com
It might help you a lot, as it shows you typical python errors you are already familiar with!
Enjoy!

A: It was the encoding, because of course it was. Just open the file like this.
fin = open("/absolute/path/to/file.txt", "r", encoding="utf-8")


text:
Q: how does check works, im having a problem I am using check constraint to check whether the entry is either male or female, but for some reason it is not working. OS: Ubuntu 18.04 LTS
I tried modifying every bit of the code, but nothing worked
 ALTER TABLE BANK ADD GENDER VARCHAR(1)
      CHECK(GENDER = 'M' OR 'F' OR 'T') AFTER NAME;

I want only M and F in the entry, nothing else.

A: MySQL does not support check in versions prior to 8. It gets parsed but does nothing.
You can use a trigger to check the values and abort the execution in your trigger if the values are not what you expect.
delimiter //
  CREATE TRIGGER BANK_check_gender BEFORE INSERT ON BANK
  FOR EACH ROW
  BEGIN
   IF NEW.GENDER not in ('M', 'F', 'T')
   THEN
       SIGNAL sqlstate '45000'
       SET message_text = 'invalid gender';
   END IF
END
DELIMITER ;


text:
Q: Select2 no funciona el buscar PHP Hola buen día estoy usando el js select2 para llenar un combo, logre llenarlo pero la búsqueda ahora no funciona por ningún carácter.
Este es mi código js
$(document).ready(function(){
// $('#panel_mantenimiento').hide();
$('#reg_id').select2({
    ajax: {
        url: '../ajax/region.php?op=region_listar_combo',
        dataType: 'json',
        delay: 250,
        data: function(params) {
            return {
                q: params.term,
                page: params.page
              };
        },
        processResults: function (data) {
            return {
                results: data
            };
        },
    }
  });

});


text:
Q: Allow lightning component to override specific object's standard button We are using Lightning out with Visualforce page to allow users to override standard button of specific object.
Now we are planning to use a Lightning component to be used as a override option for standard buttons directly, which can be done from below highlighted setting.

Note: One issue with components is if its directly used to override as Lightning Component Bundle, it does not works in Classic. But we still want users to have an ability to do so.
Solution: use lightning:actionOverride in implements attribute of the component as mentioned in this question.
Problem: The component is still available as an option in other objects.

Try 1: Option suggested by Brian in this answer, its still available for other objects, basic markup is as follows:
Component:
<aura:component description="TestOverride"
    implements="lightning:actionOverride">

Basic component

</aura:component>

Design:
<design:component>
    <sfdc:objects>
        <sfdc:object>Contact</sfdc:object>
    </sfdc:objects>
</design:component>

Please share some thoughts if this seems possible.

A: From the documentation- Creating a Lightning Component for Use as an Action Override:

The Lightning Component Bundle menu includes every component that implements the lightning:actionOverride interface.
A component that implements lightning:actionOverride can't restrict an admin to overriding only certain actions, or only for certain objects. We recommend that your organization adopt processes and component naming conventions to ensure that components are used to override only the intended actions on intended objects. Even so, it's your responsibility as the component developer to ensure that components that implement the lightning:actionOverride interface gracefully respond to being used with any action on any object.

Also there is a known issue reported: Filter Lightning Components when assigning Action Overrides


text:
Q: Scaffold dbContext in .net: Erro with password that cotains simple quote in the end I have a problem with connection string password to connect to database in visual studio.
In the end of password has a simple quote. I tried to escape using ' and others way like password="****'", password='****'', password='****'', password="****'". I'm using Pomelo.EntityFrameworkCore.MySql. Can some one help me?
I tried this in visual studio PM console :
PM> Scaffold-DbContext "server=remoteServe, port=3306; User Id=Myuser; database=database; Password=1234'" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -ContextDir Context
return this erro:
Format of the initialization string does not conform to specification starting at index 108

A: Assuming your password is 1234', the following command will work:
Scaffold-DbContext "server=127.0.0.1;user=test;password='1234''';database=test" [...]

Use a pair of single quotes around the password value and escape all single quotes of the password value with a second single quote.


text:
Q: how to map object (Alamofire object mapper) in my application i am using alamofire object mapper for object mapping.
now this is my code
class OrderDetail: Mappable {

var Message : String!
var Status : Int!
var result:[OrderDetailData]?

required init?(_ map: Map) {

}

func mapping(map: Map) {
    Message <- map["Message"]
    Status <- map["Status"]
    result <- map["Result"]

}

}

class OrderDetailData: Mappable {

    var statusId: String?
    var tax: String?
    var total: String?
    var toTime: String?
    var updated: String?
    var userId: String?
    var orederDetail : [OrderDetailSecond]?

    required init?(_ map: Map){

    }

    func mapping(map: Map) {

        statusId <- map["status_id"]
        tax <- map["tax"]
        total <- map["total"]
        toTime <- map["totime"]
        updated <- map["updated"]
        userId <- map["user_id"]
        orederDetail <- map["F017A_order_detail"]

    }

}

class OrderDetailSecond: Mappable {

    var id : String?
    var isRxMedicine : Int?
    var medicineTypeId : String?
    var name : String?
    var orderId : String?
    var price : String?
    var quentity : String?
    var strength : String?

    required init?(_ map: Map){

    }

     func mapping(map: Map) {

        id <- map["id"]
        isRxMedicine <- map["is_rx_medicine"]
        medicineTypeId <- map["medicine_type_id"]
        name <- map["name"]
        orderId <- map["order_id"]
        price <- map["price"]
        quentity <- map["qty"]
        strength <- map["strengh"]
    }
}

this is how i am doing mapping.
this my api call
class DataControllerOrderDetail: UIViewController {

func get_order_detail(orderId : String,completion : (orderDetailObject : OrderDetail) -> Void) {

    let url = "\(OrderURL)full_order_data"
    let param : [String : AnyObject] = [
        "orderId" : orderId
    ]

    Alamofire.request(.GET, url, parameters: param, encoding: .URL).responseObject { (response:Response<OrderDetail, NSError>) in

        switch response.result{
        case .Success(let value) :
            var my_order_detail : OrderDetail?
            my_order_detail = value
            completion(orderDetailObject: my_order_detail!)
        case.Failure(let error) : break
        }

    }
}
}

now for access value of orderDetailSecond class element i am doing this code
override func viewDidLoad() {
    DataControllerObject.get_order_detail(order_id) { (orderDetailObject) in
        self.my_order_list = orderDetailObject
        if let orderdetail = self.my_order_list, orderDetailDataObject = orderdetail.result {

            let detailArray = orderDetailDataObject[0].orederDetail

            if  let orderdata = detailArray
            {
                print(orderdata.count)

            }

        }

    }

}

is this compulsory every time to access  orderDetailSecond class element value. how can i map so i can directly access like. orderDetailSecond.elementname

A: If you don't need the separation, you could delete the OrderDetailSecond class and add its properties to OrderDetailData using nested mapping:
class OrderDetailData: Mappable {

    var statusId: String?
    var tax: String?
    var total: String?
    var toTime: String?
    var updated: String?
    var userId: String?

    //OrderDetailSecond elements
    var id : String?
    var isRxMedicine : Int?
    var medicineTypeId : String?
    var name : String?
    var orderId : String?
    var price : String?
    var quentity : String?
    var strength : String?

    required init?(_ map: Map){

    }

    func mapping(map: Map) {

        statusId <- map["status_id"]
        tax <- map["tax"]
        total <- map["total"]
        toTime <- map["totime"]
        updated <- map["updated"]
        userId <- map["user_id"]
        orederDetail <- map["F017A_order_detail"]

        //OrderDetailSecond elements
        id <- map["F017A_order_detail.id"]
        isRxMedicine <- map["F017A_order_detail.is_rx_medicine"]
        medicineTypeId <- map["F017A_order_detail.medicine_type_id"]
        name <- map["F017A_order_detail.name"]
        orderId <- map["F017A_order_detail.order_id"]
        price <- map["F017A_order_detail.price"]
        quentity <- map["F017A_order_detail.qty"]
        strength <- map["F017A_order_detail.strengh"]
    }
}

Source: https://github.com/Hearst-DD/ObjectMapper#easy-mapping-of-nested-objects


text:
Q: Facebook Like Button: Titles and descriptions no longer display on FB We've had Facebook set up for a while, and its been working well...but recently I noticed that it's no longer including the article title and description when it shows up in my feed. I cleared my cache and the problem resolved itself, but we can't ask our users to clear their cache.
Is there a way to get Facebook to do this automatically, or some code that I can use to make it do so?

A: Have you tried checking your url in the facebook Lint tool?
http://developers.facebook.com/tools/debug
I had a similar problem to this yesterday. The debugger got the correct data from my "og:" meta tags, but when actually clicking like button, none of that data was posted. Similarly, if I posted the "liked" url onto my wall, the preview got all the data, but when clicking 'share' nothing showed up.
As of this morning, all was looking better, but I didn't make a change. Facebook is known to break their own api at times and something that was working will stop suddenly, but then sometime later will work fine, all without us doing any updates. shrug
Run the url through the linter first, make sure it can grab your page's data.

*

*keith


text:
Q: How to allow other programs to read file, while writing to it using fopen and fwrite? I'm opening a file for a video I'm creating and writing to disk with fopen in C++, I'm able to write to disk. But when I try to read it as I'm writing it, it will throw errors saying that it doesn't have permission to read the file as soon as I close the file or stop the program, I can suddenly read from it.
Not an issue with not finishing writing the write as if I crash the program, can still read it. Also, VLC's logs tell me it's a permission issue.
Any idea how to change that permission?
Response to William asking for code snippets or if open happened before the file existed:
Thanks William, here's what I've got. I waited a few minutes and could see the file with windows explorer by that point and waited until after I'd flushed and data was there, couldn't open with VLC or Notepad++ or Notepad or Windows Media Player

Notepad says cannot access because it is being used by another process, others too.
Here is the VLC log while it tries to open this:
http://snippi.com/s/g4cbu23

Here is where I create the file with fopen:
http://snippi.com/s/cyajw4h

At the very end is where I write to the file using fwrite and flush:
http://snippi.com/s/oz27m0g

A: You need to use _fsopen with _SH_DENYNO if you want the file to be shareable.


text:
Q: jQuery detach, prepend and condition I have two div elements that are clickable. When  I click one that contains "1" it will give it class="active", when I click one that contains "2" it will give it class="active" and remove class="active" from the 1st one. Basically it is like switch.

1

2

then this block:

and after all this code: which is supposed to detach div that don't have data-id of "active" div. When switched, it's supposed to re-attach detached div and detach the second one.

however, it is not working. when I switch (class active moves from one div to another) nothing happens. only first div is detached but on switch it is not reattaching. Any ideas why ? Thanks for any help !
PS: 1. For certain reasons (FU mobirise) I'm not able to manipulate with those two divs with active class(give them onclick() attribute, new class or id and so on).
    2. Sorry for my English.

A: Here is one possible solution.  I changed around how you were doing the swap so it isn't doing a detach.  But it should give you an idea of how to potentially do it, if you did want to do the detach anyway.

//emulate the external logic that swaps the active class
$(function(){
  var $elements = $('.top');

  $elements.on('click', function(){
    $elements.not(this).removeClass('active');
    $(this).addClass('active');
  });
});

$(function(){
  var $top = $('.top');
  var $carousel = $('.carousel-inner');
  var $carouselItems = $carousel.find('.carousel-item');

  $top.on('click', function(){
    var $this = $(this);

    $carousel.prepend($carouselItems.filter(function(){
      return $this.data('id') === $(this).data('id');
    }));
  });
});

1

2

Number 1

Number 2


text:
Q: Sending image through sockets not receiving fine I'm trying to send a jpg image from a client process to a server via sockets. The image contains binary data so I want to do it on a low-level programming basis using reads and writes. I'm also sending the image data in iterations of 100 bytes.
This is the code I've done, which is not sending the image identically as I want:
CLIENT
void send_image(char *path, char *filename, int socket) {

    int fd = open(path, O_RDONLY); //I open the file of the image.jpg

    int n = 1;

    while (n > 0) {
        char img_data[100];
        n = read(fd, img_data, 100); //sending 100 bytes of image each iteration till n=0 (end of file)

        if (!n) break;

        int sending = 1;
        write(socket, &sending, sizeof(int)); //Tell the client the image still has data to send

        write(socket, img_data, strlen(img_data));

        usleep(250);
    }

    sending = 0; //Tell the server the image has been fully sent
    write(socket, &sending, sizeof(int));

    close(fd);
}

SERVER
void receiving_image(char *path) {

    int receiving = 0;
    int j=0;
    char *image_data = NULL; //Variable to store all the image data

    read(socket, &receiving, sizeof(int)); //Reads that the client is going to send an image

    while (receiving) {

        char data[100]; //Variable that stores partial data (100 bytes) of an image on each iteration
        read(socket, data, 100);

        image_data = realloc(image_data, (j + strlen(data)) * sizeof(char)); //Readjust the size of the main image data.

        for (int i=0; i<(int) strlen(data); i++) {

            image_data[j] = data[i]; //copy the partial data of the image to the main variable of the image
            j++;
        }

        j = (int) strlen(image_data);

        read(socket, &receiving, sizeof(int)); //Read if the image is still sending
    }

    image_to_directory(path, image_data); //Copy image to directory
}

This compiles and runs fine, but when I check the directory on the server side where the image has been stored, I can see it's not the same image as the client has sent (I confirmed via md5sum and hashes are not equal).
Is there something I am missing?

A: You shouldn't be using strlen for your binary data length calculations. It is intended only for terminated strings (thus the name). You also have highly-ill-advised naked calls to read/write, which is a recipe for disaster when sending data over sockets.
You never seem to be sending more than 100 bytes at a time, which is helpful in this case to develop a more solid protocol. Consider this:

*

*First octet is a uint8_t byte count N, and will be in 0..100.

*Following the byte count, N bytes are transferred.

*Repeat 1-2 until no more bytes remain.

*Notify the server of EOF by sending a single zero-octet

An example of this sender code is shown here.
void send_image(const char *path, int socket)
{
    int fd = open(path, O_RDONLY); //I open the file of the image.jpg
    if (fd == -1)
        return;

    ssize_t n = 0;
    do
    {
        // note the first octet will prefix the length
        uint8_t img_data[101];
        n = read(fd, img_data+1, 100);
        if (n > 0)
        {
            // you never know  just how many bytes are going to
            // be sent, so setup the frame, but then ensure even
            // piecewise deliver can succeed.
            img_data[0] = (uint8_t)n;
            ssize_t sent = 0;
            size_t pos = 0;
            do
            {
                sent = write(socket, img_data+pos, (n+1)-pos);
                if (sent < 0)
                    break;
                pos += sent;
            } while ( pos < (n+1) && sent > 0);
        }

    } while (n > 0);

    uint8_t done = 0;
    write(socket, &done, sizeof done); // not much we can do if this fails

    close(fd);
}

I make no claims the above code will even compile, but the concept should be fairly obvious. That's it, however. Obviously there is more that could/should be done (checksums, restart options, etc.), but that's the basic premise.
The server side can do something similar, which I leave as an exercise for you. The point of all of this is to utilize the return values from your read/write calls. They're there for a reason. If you find yourself coding a "naked" read or write (where you don't gather the result of function and utilize it in some way), chances are you've done something horribly wrong.


text:
Q: Operator overloading in map/pair I'm trying to understand operator overloading used in case of STL class templates, such as: map or pair.
Let me introduce you to my code:
#include <iostream>
#include <iomanip>  // left, setw
#include <string>
#include <map>
#include <utility> // pair
#include <algorithm> // count if
using namespace std;

typedef pair <string, int> Emp;
typedef map <string, Emp> MAP;

class Zakr{
   int min, max;
public:
   Zakr(int min, int max): min(min), max(max){}

bool operator()(const pair<const string, Emp> &p) const{
    int wage = p.second.second;
    return (min < wage) && (wage < max);
}
};

void print (const MAP& m) {
   MAP::const_iterator it, fin = m.end();

for(it = m.begin(); it != fin; it++)
    cout << "Key:  " << left << setw(7) << it -> first
    << "Name:  " << setw(10) << it->second.first
    << "Wage:  " << it->second.second << endl;
}

int main(void){
   MAP emp;

   MAP object;

   emp["John"] = Emp("John K.", 1900);
   emp["Tania"] = Emp("Tania L.", 1900);
   emp["Jeremy"] = Emp("Jeremy C", 2100);
   emp["Susie"] = Emp("Susie W.", 3100);
   emp["Toto"] = Emp("Toto T.", 9900);
   emp["Adrian"] = Emp("Adrian N.", 1600);
   emp["Germy"] = Emp("Germy P.", 2600);

 print(emp);

 int mn = 0, mx = 2000;
 int how_much = count_if(emp.begin(), emp.end(), Zakr(mn, mx));

 cout << how_much << " earn from"
 << mn << " to " << mx << endl;
 }

I'm struggling to understand some bits, especially one in particular, i.e.:
class Zakr{
   int min, max;
public:
   Zakr(int min, int max): min(min), max(max){}

bool operator()(const pair<const string, Emp> &p) const{
    int wage = p.second.second;
    return (min < wage) && (wage < max);
}
};

So I build class called Zakr, so that I will be able to use it to determine as a functor in count_if statement.
Am I right ?
I initialize private fields, min and max to use them in constructor and than so that operator which has been overloaded could return the boolean value based on their own values.
The most diffucult part is to understand bool operator overloading.
 bool operator()(const pair<const string, Emp> &p) const{
    int wage = p.second.second;

Why the hell I need to 1* make a pair of some useless string value and EMP?
Since all I'm interested in is stored in EMP, i.e.: int value which will be used in overloading is stored in Emp.
Why couldn't I just access int stored in Emp like so:
bool operator(Emp &p)
{
  int wage = p.second;
  return (min < wage) && (wage < max);
}

Why I do I need to make another pair like so: (const pair &p), if all I'm interested in is values stored in pair called Emp.
Why do I need to make another pair with useless first element of above named pair: string.
I'm not going to make use of it, so why it's needed to compile the code ?
I did try my best to explain my doubts as clear as its possible.
Hopefully someone will understand this rather long post.
Cheers!

A: This is because iterators over std::map return you a std::pair for each element. The first item in the pair is the map key, the second item is the map value. See the value_type in the documentation for std::map.
This question has some answers on how to get iterators over the map's values only.

A: 1. Class Zakr:
Indeed, it's typically for use with count_if().  If you look at the link, you'll see count_if(first, last, pred) is equivalent to something like:
  int ret = 0;
  while (first!=last) {
    if (pred(*first)) ++ret;  // works as soon as object pred has operator() defined.
    ++first;
  }
  return ret;

2. Why is a pair needed in operator():
A map works with pairs, each made of a unique key and a corresponding value.
This is in part hidden.  For example, when you use a map as associative array with expression as emp["John"], the map will find the pair having the unique key "John" and return a reference to the corresponding value.
However, as soon as you iterate through the map, your iterator will address these pairs.  Why ? Because if it would just iterate through the value, you would get value, but you would never know to which unique key it corresponds.
Consequence:  count_if() iterates through the map,  so the predicate is called with an iterator that addresses a pair.
3. Why make a useless pair:
First, the counting function does not create a dummy pair.  It uses a reference to an existing pair (from performance point of view, it's no more cost than passing a pointer !)
And, well, the map is here to address general problems.  You could one day be interested to make count not only on wage,  but for example also on the associated key (example: all the wages no in the range for employees with name starting with 'A').


text:
Q: How to find the distance between sprites? I want to check when the worker object comes closely to any of the fence objects in order to print a notification message. By "closely" I mean the distance of 20 pixels between the worker and the border of fence. For example, something like "distances_list = worker.get_dist(fences)", where "distances_list" would contain the current distances to all fences.
I could adopt the approach proposed here, but maybe there is some built-in function for my task?
In pygame we can use different collision detection functions, but in the case described above there is no collision. Is there any built-in function to find the distance between the sprites?
import pygame, random
import sys

WHITE = (255, 255, 255)
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)

SCREENWIDTH=1000
SCREENHEIGHT=578

IMG_BACKGROUND = "background.jpg"
IMG_WORKER_RUNNING = "images/workers/worker_1.png"
IMG_WORKER_IDLE = "images/workers/worker_2.png"
IMG_WORKER_ACCIDENT = "images/workers/accident.png"

class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location, *groups):
        # we set a _layer attribute before adding this sprite to the sprite groups
        # we want the background to be actually in the back
        self._layer = -1
        pygame.sprite.Sprite.__init__(self, groups)
        # let's resize the background image now and only once
        self.image = pygame.transform.scale(pygame.image.load(image_file).convert(), (SCREENWIDTH, SCREENHEIGHT))
        self.rect = self.image.get_rect(topleft=location)

class GeoFenceInfluenceZone(pygame.sprite.Sprite):
    def __init__(self, rect, *groups):
        # we set a _layer attribute before adding this sprite to the sprite groups
        self._layer = 0
        pygame.sprite.Sprite.__init__(self, groups)
        self.image = pygame.surface.Surface((rect.width, rect.height))
        self.image.fill(GREY)
        self.rect = rect

class GeoFence(pygame.sprite.Sprite):
    def __init__(self, rect, risk_level, *groups):
        # we set a _layer attribute before adding this sprite to the sprite groups
        self._layer = 1
        pygame.sprite.Sprite.__init__(self, groups)
        self.image = pygame.surface.Surface((rect.width, rect.height))
        self.image.fill(GREEN)
        self.rect = rect
        self.risk_level = risk_level
        self.font = pygame.font.SysFont('Arial', 20)
        text = self.font.render(risk_level, 1, (255,0,0), GREEN)
        text_rect = text.get_rect(center=(rect.width/2, rect.height/2))
        self.image.blit(text, text_rect)

class Worker(pygame.sprite.Sprite):

    # we introduce to possible states: RUNNING and IDLE
    RUNNING = 0
    IDLE = 1
    ACCIDENT = 2
    NUMBER_OF_ACCIDENTS = 0

    def __init__(self, image_running, image_idle, image_accident, location, *groups):

        self.font = pygame.font.SysFont('Arial', 10)

        # each state has it's own image
        self.images = {
            Worker.RUNNING: pygame.transform.scale(get_image(image_running), (45, 45)),
            Worker.IDLE: pygame.transform.scale(get_image(image_idle), (20, 45)),
            Worker.ACCIDENT: pygame.transform.scale(get_image(image_accident), (40, 40))
        }

        # we set a _layer attribute before adding this sprite to the sprite groups
        # we want the workers on top
        self._layer = 2
        pygame.sprite.Sprite.__init__(self, groups)

        # let's keep track of the state and how long we are in this state already
        self.state = Worker.IDLE
        self.ticks_in_state = 0

        self.image = self.images[self.state]
        self.rect = self.image.get_rect(topleft=location)

        self.direction = pygame.math.Vector2(0, 0)
        self.speed = random.randint(1, 3)
        self.set_random_direction()

    def set_random_direction(self):
        # random new direction or standing still
        vec = pygame.math.Vector2(random.randint(-100,100), random.randint(-100,100)) if random.randint(0, 5) > 1 else pygame.math.Vector2(0, 0)

        # check the new vector and decide if we are running or fooling around
        length = vec.length()
        speed = sum(abs(int(v)) for v in vec.normalize() * self.speed) if length > 0 else 0

        if (length == 0 or speed == 0) and (self.state != Worker.ACCIDENT):
            new_state = Worker.IDLE
            self.direction = pygame.math.Vector2(0, 0)
        elif self.state != Worker.ACCIDENT:
            new_state = Worker.RUNNING
            self.direction = vec.normalize()
        else:
            new_state = Worker.ACCIDENT

        self.ticks_in_state = 0
        self.state = new_state

        # use the right image for the current state
        self.image = self.images[self.state]

    def update(self, screen):
        self.ticks_in_state += 1
        # the longer we are in a certain state, the more likely is we change direction
        if random.randint(0, self.ticks_in_state) > 70:
            self.set_random_direction()

        # now let's multiply our direction with our speed and move the rect
        vec = [int(v) for v in self.direction * self.speed]
        self.rect.move_ip(*vec)

        # if we're going outside the screen, change direction
        if not screen.get_rect().contains(self.rect):
            self.direction = self.direction * -1

        # spritecollide returns a list of all sprites in the group that collide with
        # the given sprite, but if the sprite is in this group itself, we have
        # to ignore a collision with itself
        if any(s for s in pygame.sprite.spritecollide(self, building_materials, False) if s != self):
            self.direction = self.direction * -1

        if any(s for s in pygame.sprite.spritecollide(self, machines, False) if s != self):
            self.direction = self.direction * -1

        # Risk handling
        self.handle_risks()

        self.rect.clamp_ip(screen.get_rect())

    def handle_risks(self):
        for s in pygame.sprite.spritecollide(self, fences, False):
            if s != self:
                self.speed = 0
                self.state = Worker.ACCIDENT
                self.image = self.images[self.state]
                Worker.NUMBER_OF_ACCIDENTS += 1

class BuildingMaterials(pygame.sprite.Sprite):
    def __init__(self, image_file, location, *groups):
        # we set a _layer attribute before adding this sprite to the sprite groups
        self._layer = 2
        pygame.sprite.Sprite.__init__(self, groups)
        self.image = pygame.transform.scale(pygame.image.load(image_file).convert_alpha(), (40, 40))
        self.rect = self.image.get_rect(topleft=location)

class Excavator(pygame.sprite.Sprite):
    def __init__(self, image_file, location, *groups):
        # we set a _layer attribute before adding this sprite to the sprite groups
        self._layer = 3
        pygame.sprite.Sprite.__init__(self, groups)
        self.image = pygame.transform.scale(pygame.image.load(image_file).convert_alpha(), (170, 170))
        self.rect = self.image.get_rect(topleft=location)

image_cache = {}
def get_image(key):
    if not key in image_cache:
        image_cache[key] = pygame.image.load(key)
    return image_cache[key]

pygame.init()

# currently, one group would be enough
# but if you want to use some collision handling in the future
# it's best to group all sprites into special groups (no pun intended)
all_sprites = pygame.sprite.LayeredUpdates()
workers = pygame.sprite.Group()
building_materials = pygame.sprite.Group()
fences = pygame.sprite.Group()
fences_infl_zones = pygame.sprite.Group()

screen = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
pygame.display.set_caption("TEST")

# create multiple workers
for pos in ((30,30), (50, 400), (200, 100), (700, 200)):
    Worker(IMG_WORKER_RUNNING, IMG_WORKER_IDLE, IMG_WORKER_ACCIDENT, pos, all_sprites, workers, building_materials, machines, fences)

# create multiple building material stocks
for pos in ((50,460),(50,500),(100,500),(850,30),(800,30)):
    BuildingMaterials("images/materials/building_blocks{}.png".format(random.randint(1,3)), pos, all_sprites, building_materials)

# create multiple geo-fences
risks = ["H","M","L"]
for rect in (pygame.Rect(510,150,75,52), pygame.Rect(450,250,68,40), pygame.Rect(450,370,68,48),
             pygame.Rect(0,0,20,SCREENHEIGHT),pygame.Rect(0,0,SCREENWIDTH,20),
             pygame.Rect(SCREENWIDTH-20,0,20,SCREENHEIGHT),pygame.Rect(0,SCREENHEIGHT-20,SCREENWIDTH,20)):
    risk = risks[random.randint(0,2)]
    GeoFence(rect, risk, all_sprites, fences)

# create influence zones for all geo-fences
for rect in (pygame.Rect(495,135,105,80), pygame.Rect(435,235,98,68), pygame.Rect(435,355,98,76)):
    GeoFenceInfluenceZone(rect, all_sprites, fences_infl_zones)

# and the background
Background(IMG_BACKGROUND, [0,0], all_sprites)

carryOn = True
clock = pygame.time.Clock()
while carryOn:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            carryOn = False
            pygame.display.quit()
            pygame.quit()
            quit()

    all_sprites.update(screen)
    all_sprites.draw(screen)

    pygame.display.flip()

    clock.tick(20)

A: Here's this solution ported to pygame. The y-axis in pygame is flipped, so I had to swap the top and bottom variables and the distance can be calculated with math.hypot. You need to pass the rects of the two sprites to rect_distance where they will be unpacked into the x1, y1 (top left) and x1b, y1b (bottom right) variables. (You can see the distance in the window title.)
import math
import pygame as pg

class Player(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = pg.Surface((30, 50))
        self.image.fill(pg.Color('dodgerblue1'))
        self.rect = self.image.get_rect(topleft=pos)

def rect_distance(rect1, rect2):
    x1, y1 = rect1.topleft
    x1b, y1b = rect1.bottomright
    x2, y2 = rect2.topleft
    x2b, y2b = rect2.bottomright
    left = x2b < x1
    right = x1b < x2
    top = y2b < y1
    bottom = y1b < y2
    if bottom and left:
        print('bottom left')
        return math.hypot(x2b-x1, y2-y1b)
    elif left and top:
        print('top left')
        return math.hypot(x2b-x1, y2b-y1)
    elif top and right:
        print('top right')
        return math.hypot(x2-x1b, y2b-y1)
    elif right and bottom:
        print('bottom right')
        return math.hypot(x2-x1b, y2-y1b)
    elif left:
        print('left')
        return x1 - x2b
    elif right:
        print('right')
        return x2 - x1b
    elif top:
        print('top')
        return y1 - y2b
    elif bottom:
        print('bottom')
        return y2 - y1b
    else:  # rectangles intersect
        print('intersection')
        return 0.

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    player = Player((50, 80), all_sprites)
    player2 = Player((100, 200), all_sprites)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEMOTION:
                player.rect.topleft = event.pos
                distance = rect_distance(player.rect, player2.rect)
                pg.display.set_caption(str(distance))

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()


text:
Q: wordpress tagcloud styling doesn't work Been messing with it for the past couple of hours. Trying to get a vertical space betweeb tags, but no luck...
Blog has a separate template file.
Live link here
http://soloveich.com/pr6/blog/
Html code
<div id="tagy">
widget code
</div>

css
#tagy {
margin-top: 20px !important;
}

#one h2 {
text-align: center;
width: 100%;
padding-top: 45px;
padding-bottom: 10px;
font-family: 'Raleway', sans-serif;
font-size: 26px !important;
color: #7e7e7e;
border-bottom-style: dotted;
border-bottom-color: #a6a6a6;
border-bottom-width: 1px;
}

 .seo-tag-cloud a {
margin: 10px;
padding: 7px;
background-color: #dddddd;
color: #666666;
font-size: 14px !important;
text-align: center;
}

A: Add display: inline-block to your .seo-tag-cloud a styling.  Anchors are inline by default, which means they don't have margin.


text:
Q: Does the definition of compactness require the open cover to consist of subsets? Sorry if the title is a bit unclear, but I'm stuck on the definition of compactness for metric spaces using open covers. So our professor wrote (word for word) that in a metric space $(X,d)$, an open cover is a family $\{U_i\}_{i\in I}$ with
$U_i\subset X$ open,
$\bigcup_{i\in I}U_i=X$
and that $X$ is compact if from every open cover $\{U_i\}_{i\in I}$ finitely many $U_{i_1},...,U_{i_r}$ can be chosen such that $U_{i_1}\cup U_{i_2} \cup ... \cup U_{i_r}=X$.
Is this definition correct? Because in one of our exercises, they ask us to find an open cover (that doesn't have a finite subcover) for $X=[0,1]\cap \Bbb Q$ with the Euclidian distance, but I can't for the life of me think of any set that is a subset of $X$, contains $0$ or $1$, and on top of that is an open set - those three things seem mutually exclusive to me. Was our prof mistaken in writing that $U_i$ is a subset of $X$ in the definition for open covers?
Any help would be greatly appreciated!

A: Open means relatively open. A subset of $U$ of $X = [0,1] \cap \mathbf Q$ is open if there is an open set $O \subset \mathbf R$ satisfying $U = O \cap X$.

A: A subset $K$ of a metric space $X$ is compact if and only if for every any collection of open sets $U_i\subseteq X,i\in I$ for which $K\subseteq \bigcup_{i\in I} U_i$, there is a finite set $F\subseteq I$ for which $K\subseteq \bigcup_{i\in F}U_i$. Note that $U_i$ need only be subsets of $X$.
However, $K$ being compact as a subset of $X$ is equivalent to $(K,d|_K)$ being a compact space. Here, $d|_K$ is the metric on $X$ with its domain restricted to $K\times K$. It can be shown that $V\subseteq K$ is open in $(K,d|_K)$ if and only if $V=U\cap K$ for some open $U\subseteq X$.
For your problem, for example, letting $K=[0,1]\cap \mathbb Q$, then $(a,b)\cap [0,1]\cap \mathbb Q$ would be an open set for any $a,b\in \mathbb R$. Even though such sets are not open in $\mathbb R$, they are open when viewed as subsets of $K$ with the metric inherited from $\mathbb R$.

A: e.g. $[0,\frac12)\cap \mathbb{Q}$ is an open set of $X=[0,1]\cap \mathbb{Q}$ in its subspace topology.


text:
Q: How do you default an image's right edge in a CSS Overflow DIV? I have the following on a page:

If the image is wider than 600px then you can scroll the image to the left to see the rightmost part. However, I want to default it so that it is already scrolled fully to the left when initially displayed.
I've tried setting a style in the image to float:left which works but that disables the horizontal scrollbar.
Ideas?
EDIT: Here's a page that might help explain what I'm trying to do: http://guyellisrocks.com/ie-example/
Do you see how you have to move the scroll bar to the right to see the right most edge of the image? I'd like it to default to that when you first hit the page.
I don't have a problem doing this in JavaScript and if that's possible some hints would be appreciated. Otherwise if it's possible to do this with CSS then this is how I would first attempt to do this.

A: Try adding an anchor to the right of the image. Something like:

When or after navigating to the page, if you append the #right_of_image anchor to the document URL, the browser will try to focus on the anchor, effectively scrolling to the right edge of the image. This probably won't work if you're using a scrolling container like the one you have, but should work if the image is directly embedded in your page. Does this work for you?


text:
Q: Is there a way to selectively use mouse events on overlayed elements? I have a slider component that should handle all click events. I have overlaid a few tool-tip icons over this slider using absolute positioning. I want to be able to mouseover the tool-tip icons and trigger their mouseover event, but I don't want these icons to block clicking on the slider.
Any ideas?
For the slider, I'm using Angular Materials' "mat-slider". For the icons, I have mat-icons that are using matTooltip.
I don't think this question is really Angular specific necessarily, but I'd greatly appreciate any help :)
Not much code to show, but here's an image of what the slider looks like. The comment icons can block clicking on the slider. Right now, I have the comment icons use this class:
.comment-icon {
position: absolute;
z-index: -1;
}

A: That's a tough one since something like pointer-events: none; would prevent hover and even JS from listening to mouseover events.
What you could do is add a click listener to the tooltips, and if the mouse position is within the bounds of the slider it'll trigger the click event on that too.
Something like:
document.querySelector('.comment-icon').addEventListener('click', e => {
    const slider = document.querySelector('.slider');
    const sliderBounds = slider.getBoundingClientRect();

  if (e.clientX >= sliderBounds.left && e.clientX <= sliderBounds.right
    && e.clientY >= sliderBounds.top && e.clientY <= sliderBounds.bottom) {
        slider.click();
  }
});

Here's a quick fiddle: http://jsfiddle.net/wfpv5oka/2/


text:
Q: How do I decide which appenders act on a log with `clojure.tools.logging`? In my project.clj :dependencies, I have:
[org.clojure/tools.logging "0.2.6"]
[ch.qos.logback/logback-classic "1.0.11"]
[net.logstash.logback/logstash-logback-encoder "1.0"]

In my core.clj, I have:
(clojure.tools.logging/info "both stdout and stash")
(clojure.tools.logging/log "stash" :info nil "only stash?")

On my resource path, I have a file logback.xml, in which I define two appenders stdout and stash both attached to root:
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">

  <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="stash" class="ch.qos.logback.core.FileAppender">
    <file>example.log</file>
    <encoder class="net.logstash.logback.encoder.LogstashEncoder" />
  </appender>

  <root level="all">
    <appender-ref ref="stash" />
    <appender-ref ref="stdout" />
  </root>

</configuration>

When I run my program, I see the following (desired) output in example.log:
{"@timestamp":"2013-04-10T12:42:16-04:00","@message":"both stdout and stash","@fields":{"logger_name":"scheduler.core","thread_name":"main","level":"INFO","level_value":20000}}
{"@timestamp":"2013-04-10T12:42:16-04:00","@message":"only stash?","@fields":{"logger_name":"stash","thread_name":"main","level":"INFO","level_value":20000}}

However, I see both of the following lines printed to stdout -- I only wanted to see the first:
12:42:16.573 [main] INFO  scheduler.core - both stdout and stash
12:42:16.641 [main] INFO  stash - only stash?

How do I select which appender to log to with clojure.tools.logging?  Specifically, with both stdout and stash attached at root, how can I log only to stash?

A: logback applies all active appenders that match not just the first one so your root level will apply to all messages.
take the <appender-ref ref="stdout" /> out of the root level and add a logger specifically to use it.
 <logger name="project.core" level="INFO">
    <appender-ref ref="stash" />
  </logger>

 <root level="ERROR">
    <appender-ref ref="stdout" />
  </root>

A: A few things to clarify for you:
The configuration of what gets logged where is entirely controlled by your logging implementation (logback in this case).
All clojure.tools.logging messages use a logging namespace. By default, the value used is the clojure namespace from which the logging call is invoked; this is analogous to how in Java you might pass the current class to the logger factory.
This logging namespace is used by most logging implementations to allow you to set logging configuration at the namespace level.
As to your questions:
How do I select which appender to log to with clojure.tools.logging?
Do it exactly how you would do it when logging from Java, either globally, or specific to some package/class/namespace.
Specifically, with both stdout and stash attached at root, how can I log only to stash?
In logback, the name of the appender has no bearing on log message namespace.  If you want to configure namespace-specific logging, you can do something like the following:
<appender name="foo">...</appender>
<appender name="bar">...</appender>

<root level="WARN">
  <appender-ref ref="foo" />
</root>

<logger name="myproject.core" level="DEBUG">
  <appender-ref ref="bar" />
</logger>

In the above, every WARN (or higher) message in any namespace will be sent to the foo appender, and every DEBUG (or higher) message from myproject.core namespace will be sent to the bar appender.


text:
Q: Longest Matching SubPath Between Two Paths I need to compare two paths to get the index of the last char of the max subpath in common between them. For ex:
/folder1/folder2/folder3/ybjagh/
/folder1/folder2/folder3/yAAAAAA

In this case the max subpath would be /folder1/folder2/folder3/ because /folder1/folder2/folder3/y doesn't make it a complete path. The index returned would be 23 then and not 25.
I know how to do it but I think I might be overthinking this. Is there a simple javascript code that looks neat that does this?
Thanks!

A: Here's one off the top of my head - there's probably a better way using array.reduce too - this way you don't need to persist a match or any such stuff, works on one "folder" of the path at a time
function longpath(a, b) {
    var cont = true;
    b = b.split('/');
    return a.split('/').filter(function(item, index) {
        return cont = cont && b[index] === item;
    }).join('/')+'/';
}