text:
Q: Android RatingBar: handler for same star tapped as current rating? I have a RatingBar (as a "star bar") implementation I'm working on, and while I have it going just fine using the onRatingChanged() delegate method, there's a glaring omission (or something I'm just blind to) in the API: there's only this one event firing when the rating actually changes, not when the user taps the same star that it's already set at.
For example, if I am showing a 3/5 star rating in the rating bar, tapping 2 or 5 sets fires onRatingChanged() but tapping 3 does absolutely nothing.
I am capturing the onTouch and allowing it to propagate (for other custom UI purposes) but I don't have a reference to which star was tapped of course. If I did, I could compare that to the current getRating() and handle the "same star tapped" case.
Anyone else tried to accomplish this yet or have any tips on other methods I could explore? I've been up and down the RatingBar hierarchy and don't see anything helpful. Ideally onRatingChanged() would just fire with the same rating and I could handle it there. :/
Thanks.
UPDATE
Thanks to Bas van Stein below, I ended up using a Runnable to delay the execution of my current vs. new rating check in the ACTION_UP check of my touch event handler. It's not pretty but it does seem to work (TBD on device). Keep in mind this is a subclass impl of RatingBar itself:
@Override
public boolean onTouch(View v, MotionEvent event) {
    // we only want to handle this on DOWN or MOVE (drag)
    int action = event.getAction();

    if(action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) {
        Log.d(TAG, "Starbar touched; current rating=" + getRating());

        // do stuff for UI purposes here

        // capture the current rating before onRatingChanged does anything
        currentRating = getRating();
    }

    if(action == MotionEvent.ACTION_UP) {

        Handler handler = new Handler(Looper.getMainLooper());
        final Runnable r = new Runnable() {
            public void run() {
                float newRating = getRating();

                if(currentRating == newRating) {
                    Log.d(TAG, "Same rating tapped; would unrate");
                    // do something UI related here
                } else {
                    Log.d(TAG, "New rating, will just show it");
                    // this just falls through to my onRatingChanged()
                }
            }
        };

        handler.postDelayed(r, (long) 0.1);
    }

    // allow the touch event to propagate
    return false;
}

A: You actually do know which rating is being pressed because this is always the current rating when the touch event starts (touch_down).
The rating change function will be called after both touch events so what you should do is check the rating at the moment the touch action starts ACTION_DOWN and the rating a bit after the touch action ends ACTION_UP. If both are the same, you know the same rating has been given (the current rating), and if it has been changed, your onChangeRating listener will catch it.
private current_rating = 0;
ratingBar.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            current_rating = ratingBar.getRating()
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
              @Override
              public void run() {
                 if (current_rating == ratingBar.getRating() ){
                     //touched but no change between down and up, so fire the same rating.
                 }
              }
            }, 100);
        }
        return true;
    }
});

A: I've made simpler solution, you won't need hack with Handler, just don't pass touch further.
private previous_rating = 0;
ratingBar.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            previous_rating = ratingBar.getRating()
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (current_rating == ratingBar.getRating() ){
                //pressed same star as before, do your action here
                return true; //we have consumed this event
            }
        }
        return false; //do whatever ratingBar has to do
    }
});


text:
Q: Application crashes after notification *Notification is working fine but problem is it crashed after clicking button
*It says add @ Add@SuppressWarnings 'deprication' to n
         and
         add @ Add@SuppressWarnings 'deprication' to onclick
public class testInput extends Activity {

    Button Setbutton;
    Location location, locationA, locationB;
    LocationManager locationManager;
    NotificationManager nm;
    public static final int uniqueId =1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.showcoords);

        nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancel(uniqueId);

        Setbutton = (Button) findViewById(R.id.btnShowLocation);

        Setbutton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(testInput.this, goIn.class);
                PendingIntent pi = PendingIntent.getActivity(getBaseContext(),
                        0, intent, 0);
                String body = "This is a Notification";
                String title = "Test";
                Notification n = new Notification(R.drawable.route, body,
                        System.currentTimeMillis());
                n.setLatestEventInfo(testInput.this, title, body, pi);
                n.defaults = Notification.DEFAULT_ALL;
                nm.notify(uniqueId, n);
                finish();
            }
        });
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How I can GRANT EXECUTE ON  TO USER I need to allow user to execute only one function inside a package.
How I can
GRANT EXECUTE ON <only 1 procedure OR function in package> TO USER

A: You can't. Grant affects the whole package.

A: You can probably create 2 packages:

*

*main package - contents all logic

*interface package - contents wrapper methods.
"wrapper methods" - just make calls real methods from main package you want to get access by grant.

And get grants to interface package.


text:
Q: Как заставить телеграмм бота работать одновременно на нескольких аккаунтах? я написал парсер и хочу чтобы взаимодействие с ним происходило через telegram бота. в парсере есть некоторые настройки, которые должен вводить пользователь. Я написал бота и все работает, но только если ботом пользуется одновременно только 1 человек, так как если второй пользователь бота изменяет переменные устанавливая настройки парсера, то они меняются и у первого пользователя.
import telebot
from telebot import types
from bs4 import BeautifulSoup
import requests
import re

bot=telebot.TeleBot('2146604141:AAG6DH6tzjF6eVW5MO_HCoBM8')
HOST='https://www.bolha.com'
HEADERS={
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'
}

@bot.message_handler(content_types=['text'])
def start(message):
    bot.send_message(message.from_user.id, "введите ссылку категории для парсинга")
    bot.register_next_step_handler(message, get_URL)

def get_URL(message):
    global URL, ID, count1
    count1=0
    ID=message.from_user.id
    try:
        URL=message.text
        html=get_html(URL)
        if html.status_code==200:
            bot.send_message(message.from_user.id, "введите дату размещения искомых обьявлений в формате: ГГГГ-ММ-ДД например(2021-11-25) или напишите 'No' если не хотите учитывать этот параметр")
            bot.register_next_step_handler(message, get_DATA)
        else:
            bot.send_message(message.from_user.id, "ссылка не подходит")
            start(message)
    except:
        bot.send_message(message.from_user.id, "ссылка не подходит")
        start(message)

def get_DATA(message):
    global DATA, count1, count2
    count2=0
    if count1==0:
        DATA=message.text
    bot.send_message(message.from_user.id, 'максимально допустимое количество сделок у продавца на сайте?')
    count1+=1
    bot.register_next_step_handler(message, get_opit)

def get_opit(message):
    global opit_, count2, count3
    count3=0
    try:
        if count2==0:
            opit_=int(message.text)
        bot.send_message(message.from_user.id, "с какой страницы начать парсинг?")
        count2+=1
        bot.register_next_step_handler(message, get_PAGENATION_ot)
    except:
        bot.send_message(message.from_user.id, "введите число")
        get_DATA(message)

def get_PAGENATION_ot(message):
    global PAGENATION_ot, count3
    try:
        if count3==0:
            PAGENATION_ot=int(message.text)
        bot.send_message(message.from_user.id, "на какой закончить?")
        count3+=1
        bot.register_next_step_handler(message, get_PAGENATION_do)
    except:
        bot.send_message(message.from_user.id, "введите число")
        get_opit(message)

def get_PAGENATION_do(message):
    global PAGENATION_do
    try:
        PAGENATION_do=int(message.text)+1
        start_parsing(message)
    except:
        bot.send_message(message.from_user.id, "введите число")
        get_PAGENATION_ot(message)

далее идет сам функционал парсера

как мне сделать так чтобы ботом могли пользоваться одновременно несколько пользователей?
заранее спасибо.

A: Асинхронные запросы. Я бы использовал облачные функции: lambda от amazon или google/firebase. Каждый запрос от пользователя к боту - новая функция. При необходимости запросы собирать в бд, потом парсить и отправлять каждому пользователю его результаты.


text:
Q: Can i replace the system DLLs in Symbian? all DLLs and EXEs in Symbian goes to sys\bin folder, right?
does system DLLs (build-in DLLs) in there too?
can i replace while install my own app?
thank you!

A: They do go there, but you can't replace them from a normal process because of the strict security model Symbian employs.

A: Sometimes.
Some system DLLs and EXEs are protected and cannot be replaced.
For all the others you need to match the security permissions of the DLL or EXE or risk the stability of the device.
In general I'd say that you don't want to do this unless you are the original author of a executable.

A: If you are worried that you write over some system DLL by mistake then the recommended approach is to add you application's UID to the name of the DLL and EXE files, i.e. Calendar_20005ab12.EXE.
Otherwise there is quite a big chance to have conflict with some existing app, especially if you want to write your version of some popular application.


text:
Q: Photoshop rename to layer name I need a script to choose a folder, open the Photoshop files in the folder, then rename the files to the current name of layer plus the file extension. (Each of the layers will be named differently as the images have been created with a data merge. All I have so far is opening one image and getting the layer name, I can't figure out the repeat and the rename of the file:
set inputFolder to choose folder
tell application "Finder"
    set filesList to files in inputFolder
    set myDoc to item 1 of filesList as string
    tell application "Adobe Photoshop CC"
        set display dialogs to never
        open alias myDoc
    end tell
end tell
tell application "Adobe Photoshop CC"
    set layerName to name of current layer of current document as string
    -- close current document saving no
    return layerName as string
end tell

A: Like this :
set inputFolder to choose folder
activate application "Adobe Photoshop CC"
tell application "Finder"
    set filesList to document files in inputFolder
    repeat with tFile in filesList
        set nExtension to name extension of tFile
        set layerName to my getLayerName(tFile as string)
        if layerName is not "" then
            set newName to (layerName & "." & nExtension)
            if newName is not name of tFile then -- else the name is already the layer name
                set i to 1
                repeat while exists item newName in inputFolder -- if same name in the folder (maybe same layer name)
                    set newName to (layerName & i & "." & nExtension)
                    set i to i + 1
                end repeat
                set name of tFile to newName
            end if
        end if
    end repeat
end tell

on getLayerName(myDoc)
    tell application "Adobe Photoshop CC"
        set display dialogs to never
        open alias myDoc
        repeat 5 times
            tell current document to if exists then
                set layerName to (name of current layer) as string
                close saving no
                return layerName
            end if
            delay 1
        end repeat
    end tell
    return "" -- no document
end getLayerName

A: Brilliant that works a treat, just trying to backward engineer the script, in the photoshop function the repeat 5 times will that limit the script to only work with 5 files? and the variable tFile is that a constant as the variable doesn't seem to be declared?
Still quite new to this so forgive my lack of knowledge and thanks again


text:
Q: Why is the Ordered By disregarded? I want my SQL to return all records for a given date, with the most recent one on top (the column I'm ordering by contains both date and time - contains entries such as "5/21/2012 11:48:04 AM").
I would think my sql (below) would do this. However, the actual results disregard the time element. They are returned like this:
5/21/2012 10:48:04 AM
5/21/2012 10:12:04 AM
5/21/2012 9:48:04 AM
5/21/2012 10:54:04 AM
5/21/2012 11:48:04 AM
...
(IOW, the results returned are just randomly ordered, as far as the time element goes)
the query is:
SELECT ENTRYDATE ENTERED, ENTEREDBYABC ABC
FROM
   SomeTable v
   LEFT JOIN SomeTable w ON v.someCol = w.someCorrespondingCol
WHERE
   ABC = :abc AND ENTRYDATE = trunc(sysdate)
ORDER BY ENTERED DESC

UPDATE
More specific query and results:
This (column and table names have been changed):
SELECT ENTRYDATE ENTERED, ENTEREDBYABCID ABCID, COMMENTS
FROM
  WHITMAN.HOLLOWSKY@ATTORNEY v
  LEFT JOIN ABCworker w ON v.enteredbyabcid = w.abcid
WHERE
  ABCID = 124393 AND ENTRYDATE = TRUNC(sysdate)
ORDER BY ENTRYDATE desc

...returns records with:
ENTERED     ABCID   COMMENTS
5/21/2012   1234    At 1:36 PM, ...
5/21/2012   1234    At 1:36 PM, ...
5/21/2012   1234    At 9:23 AM, ...
5/21/2012   1234    At 11:07 AM, ...
5/21/2012   1234    At 11:12 AM, ...
5/21/2012   1234    At 1:42 PM, ...
5/21/2012   1234    At 11:02 AM, ...
5/21/2012   1234    At 9:19 AM, ...
. . .

UPDATED AGAIN
With the query:
select entrydate from WHITMAN.HOLLOWSKY@ATTORNEY order by entrydate desc

I get:
5/21/2012 3:15:50 PM
5/21/2012 3:15:35 PM
5/21/2012 3:15:25 PM
5/21/2012 3:15:25 PM
5/21/2012 3:14:31 PM
5/21/2012 3:14:22 PM
5/21/2012 3:14:11 PM
. . .

IOW, it works just fine.
Whether "entrydate" is a DateTime column - I reckon so, but I don't have privileges to look at the table structure, so ... ?

A: I suspect the problem is that you have a column called "ENTERED" in one of the tables you are joining.
As a consequence, you are ordering by that column, even though it is not in the SELECT list.  To fix this, you should do one of the following:
ORDER BY 1

or
ORDER BY ENTRYDATE

(The second having already been mentioned in Glenn's comment.)

A: Your ORDER BY is being honored.  The problem is that the time component on all 11 rows that you are selecting must be midnight in order to satisfy the predicate
entrydate = TRUNC(sysdate)

The query
SELECT ENTRYDATE ENTERED, ENTEREDBYABCID ABCID, COMMENTS
  FROM WHITMAN.HOLLOWSKY@ATTORNEY v
       LEFT JOIN ABCworker w ON v.enteredbyabcid = w.abcid
 WHERE ABCID = 124393
   AND ENTRYDATE = TRUNC(sysdate)
 ORDER BY ENTRYDATE desc

asks for all the rows where entrydate is today at midnight, then sorts on entrydate.  By definition, since there is only one possible value for entrydate that satisfies the predicate, that ORDER BY is irrelevant.  All 11 rows have exactly the same value for entrydate so sorting on that value produces an arbitrarily ordered result.  Oracle could, quite correctly, return the 11 rows in any order and still be honoring your ORDER BY clause.
Perhaps you want to order by the time that is stored in the comments column rather than the entrydate.  Perhaps you want to change your predicate to return all the rows where entrydate was some time today.
AND trunc(entrydate) = trunc(sysdate)

Perhaps you want to do something else.


text:
Q: Pandas .agg() convert to list but skip nans How do I consolidate/reduce a DataFrame so that it merges rows by custom column 'id' and puts values into a list if they are not Nan. So far I came up with this but it doesn't remove Nans:
x: pd.DataFrame = df_chunk.groupby('id', dropna=True).agg(lambda x: list(x))
for row in x.itertuples():
    print(row)

So the result is:
Pandas(Index=1, surname=['Bruce', nan, nan], given_name=['Erin', nan, nan], date_of_birth=['11/03/1961', '11/04/1961', '11/06/1961'], address=['10 Kestrel Wood Way, York', '4 Ward Avenue, Cowes', '11 Woodhill Court, Woodside Road, Amersham'], postcode=['YO31 9EJ', 'BD10 0LT', 'WA14 1LH'], mobile=['+64 21 421 2300', '+64 29 975 1551', '+64 22 5491 7112'])

Desired result is to have surname=['Bruce'], given_name=['Erin'] and so on

A: Use Series.dropna for remove NaNs and Nones:
df_chunk.groupby('id').agg(lambda x: list(x.dropna()))


text:
Q: ActiveRecord - Group by attribute of included table I have the following two models
post_comment.rb
class PostComment < ActiveRecord::Base
  has_many :replies, dependent: :destroy
  ...
end

reply.rb
class Reply < ActiveRecord::Base
  belongs_to :post_comments
  belongs_to :reply
  ...
end

I have the following query that gets all the post_comments and includes their respective replies:
PostComment.all.includes(:replies)
I want to, however, also group the replies of by the reply_id attribute of the reply model
Ideally I'd like to end up with something like the following straight out of the DB:
[
  <Post 1:
    replies: { nil: [...], 1: [...], 2: [...], ... }
    ...
  >,
  <Post 2:
    replies: { nil: [...], 123: [...], 341: [...], ... }
    ...
  >,
]

Thanks!

A: I don't think ActiveRecord can do that
We can group relies like this,but maybe it isn't the way you want
posts = PostComment.all.includes(:replies)
for post in posts
  ...
 replies_map = post.replies.group_by(&:reply_id)
  ...
end

you can add a virtual column to model

A: To group the replies by the reply_id attribute of the reply model, you can do this:
PostComment.joins(:replies).group('replies.reply_id')


text:
Q: React .map update on state change I realise this may be a really simple explanation/answer to this but it's driving me mad. I've got a React component that maps over a state and displays each item in the array as a p tag, but when I change the state using the buttons the UI doesn't change to add or remove any items. I think this has something to do with the way map create a copy of the array and doesn't mutate to original data but I need to have my UI update as the state changes and I just can't work out how to re-run the map function when the state changes.
import React, { useState } from 'react';

export default function Dashboard() {
  const [testState, setTestState] = useState([{ name: 'test' }, { name: 'test' }]);

  function addItem() {
    let obj2 = testState;
    obj2.push({ name: 'test' });
    setTestState(obj2);
  };

  function remItem() {
    let obj2 = testState;
    obj2.pop();
    setTestState(obj2);
  };

  return (

Dashboard

        {testState.map((item, i) => {
          return (
{item.name}
)
        })}

      <button onClick={addItem}>ADD</button>
      <button onClick={remItem}>REM</button>

  );
};

Thanks in advance,


text:
Q: android resource string % now I encounter a doubt about % in android string resource. The question as follow:
If I want to use % symbol in other language, such as in chinese. I must add resource string formatted="false" in /values-zh-rCN/strings.xml.
Yes, the string tag must have ther formatted attribute.
However, it could not add this formatted attribute in /values/strings.xml  in english language. it compile successfully, and work well.
Why?
I can't find any answer in android developer website.
ps: how i write Angle brackets in stackoverflow editor. I'm a freshman.
Java code:
autoDownloadLayout.findViewById(R.id.setItemContent)).setText(R.string.setting_auto_update_title_1_subtitle);

/values/strings.xml :
<string name="setting_auto_update_title_1_subtitle">Automatically download updates when connected to Wi-Fi, when the battery level is greater than 30% and CPU usage is less than 50%</string>

/values-zh-rCN/strings.xml :
<string formatted="false" name="setting_auto_update_title_1_subtitle">"仅在 WLAN 网络,手机电量高于 30% 且 CPU 占用率低于 50% 时,预先下载游戏更新包"</string>

A: It seems that Android Lint has different ideas when checking translated strings as compared to default strings. There's an open issue (Issue 74959) about this (although it's not exactly your problem). It would seem that technically you should be adding formatted="false" to the strings in /values as well as to those in /values-zh-rCN.
Alternatively, you could encode all literal percent signs as % (or %). That might be the simplest (and least risky) approach.


text:
Q: Icon twice after reloaded plugin I am making a QGIS plugin with QGIS 2.14.10
I use the reload plugin each time i want to update the plugin. But sometimes, when my plugin bug and i reload it, i get the icon twice in the toolbar and the first icon is off. It happen each first time that the plugin beug. And sometimes i get 3,4,5 same icon ...

How can i prevent this ?


text:
Q: What does it take to recreate double slit experiment with detectors? Is there any way to recreate this experiment with detectors at home?
I need detectors If I want to recreate the interference pattern.
I have a little know-how in electronics so If I need to buy a detector there wouldn't be a problem using it. The thing is I don't know which detector should I use.
Can I do this? Is It just too expensive for a DIY project?

A: The biggest restrictions on detectors are likely to be the light intensity, and the size of one pixel.
The intensity of light that comes through the slits is actually quite small. After all, the slits have to be narrow in order to function. Then you need to go to the screen, spreading out the energy over a wider area. Next, you want to cover the range of intensity in order to see the shape of the pattern. So you need quite a range of sensitivity.
To get details of the pattern, you will want a fairly small size detector pixel. Smaller area means you need more intense light to get signal.
A suggestion: Are you skilled enough to get and install something like a CCD from a digital camera? Probably you don't want to get an actual camera and take out the CCD because it will probably be pretty small for your purposes. To say nothing of destroying the camera. But there are various sizes of CCD devices. And they can be quite sensitive. And they come in a nice grid pattern so your data is automatically divided into locations.
A quick Google found a bunch of things, but I'm not sure where you want to go.
As well, you want to exert care with the light source. Monochromatic is necessary. Intense is good. Consider something like an LED laser pointer type device. You can get them for cheap. Possibly you can get a lens for it that will spread the beam out to the width that is most useful for your experiment.
Alternative: Instead of having the detectors directly receive the light, you could have the light fall on a screen. Then you could use any convenient camera to record the image. A few clever tricks with marks on the screen could give you calibration distances. Then you could extract any information you want from the camera image.

A: The question is what exactly it is you would like to observe. If all you are after is an interference pattern, then you could build a double slit experiment with shallow water waves or (classical) laser light. While these are classical waves, the underlying mechanism (maxima and minima due to interference of waves) is exactly the same.
If you insist on using bona fide quantum particles, both, creating a suitable source and a detector will be significantly more complicated. Ditto if you want to create low intensity sources so that you can see single impacts of, say, photons or electrons.


text:
Q: Trying to give a two different tints to background image using slanted divs I am a new to learning HTML and CSS and I am trying to give a background image two tilted tint with slanted divs. I can't understand how to do it so that the slant is only in the middle and not on the edges of the image. Here's what I have tried so far.

.tinted-image {

  width: 100vw;
  height: 100vh;

  background: url(https://static.pexels.com/photos/175941/pexels-photo-175941.jpeg);
  background-size: cover;
  filter: grayscale(100%);
  display: flex;
  overflow: hidden;
}

#one{
  background: linear-gradient(rgba(0,0,0,0.85), rgba(0,0,0, 0.85));
  tranform-origin: bottom-left;
  transform: skewX(10deg);
/*   margin-left: 1em; */
}
#two{
  background: linear-gradient(rgba(255, 255, 255, .45), rgba(255, 255, 255, .45));
  transform: skewX(10deg);
}
#one, #two{
  height: 100vh;
  width: 50vw;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family:'Nova Mono', monospace;
  font-size: 5rem;
}

#one h1 {
  color: #eee;
  margin-left: auto;
  margin-right: 1rem;
}

#two h1 {
  color: #222;
  margin-right: auto;
  margin-left: 1rem;
}

<link href="https://fonts.googleapis.com/css?family=Nova+Mono" rel="stylesheet">

WEB

DEV

A: I am able to get the desired effect by using a negative margin on the left margin-left: -200px; and a positive left padding with the same amount  padding-left: 200px; to offset it.
I added those two to your selector #one alongside overflow: hidden; to tidy things up
Working example:

.tinted-image {
  width: 100vw;
  height: 100vh;
  background: url(https://static.pexels.com/photos/175941/pexels-photo-175941.jpeg);
  background-size: cover;
  filter: grayscale(100%);
  display: flex;
  overflow: hidden;
}

#one {
  background: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.85));
  tranform-origin: bottom-left;
  margin-left: -200px;
  padding-left: 200px;
  overflow: hidden;
  transform: skewX(10deg);
  /*   margin-left: 1em; */
}

#two {
  background: linear-gradient(rgba(255, 255, 255, .45), rgba(255, 255, 255, .45));
  transform: skewX(10deg);
}

#one,
#two {
  height: 100vh;
  width: 50vw;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Nova Mono', monospace;
  font-size: 5rem;
}

#one h1 {
  color: #eee;
  margin-left: auto;
  margin-right: 1rem;
}

#two h1 {
  color: #222;
  margin-right: auto;
  margin-left: 1rem;
}

  <link href="https://fonts.googleapis.com/css?family=Nova+Mono" rel="stylesheet">

WEB

DEV


text:
Q: Do I use Option as result when fetching an object from the database with an Id? I have made a definition which fetches a user from the database.
 def user(userId: Int) : User = database withSession {
    (for{
      u <- Users if u.id === userId}
    yield u).first
  }

Potetially the database could return an empty list if used with an non existing userId.
However I can't see when a non existing userId would be provided. For example my userId is fetched from the logged in user. And if a non existing userId is provided then I think it's ok to fail the request hard.
Any thoughts?

A: No it's not ok to fail the request hard :
def user(userId: Int) : Option[User] // is OK
def user(userId: Int) : Either[String,User] // is OK
def user(usedId: Int) : User // is not OK

or else you could create a type (a concept) which encapsulate an Integer which make sure it's a valid UserId (at birthing).
sealed case class UserId(u:Int) //extends AnyVal // If it's scala 2.10.0

object UserId {
    def get(i:Int) : Option[UserId] = //some validation

} /// ....

def  user(userId:UserId) : User //is OK // well it depends on the semantic of user destruction.

When you make a def, you must make sure there is a proper relation between the domain (this and args) of your function and the codomain (result).
Anyways, do not hesitate to type (create concepts), it will help you to reason about your code.

Why def user(userId: Int) :User is not Ok ?
Because a relation between the elements of Integer to the elements of User doesn't exist. What if UserIds are all positive integers, but you ask for user(-10) ? (it won't happen, right ?) Should this call raise an exception ? Or return null ?
If you think it should return null, then return an Option, it encapsulates the potential missing correspondance.
If you think it should raise an exception, then return :

*

*a Validation[SomethingRepresentingAnError, User] (scalaz),

*an Either[SomethingRepresentingAnError, User] (scala 2.7, 2.8, 2.9)

*or a Try[User] (scala 2.10)

Having rich return types will help you to use your API correctly.
Btw Scala doesn't use checked exception, so you cannot use exception as an alternative result. Exception should be keept for truly exceptional behaviour (as Runtime Exceptions).
See also :

*

*http://www.scala-lang.org/api/current/index.html#scala.util.control.Exception$

A: I think it's always good idea to return Option[] when fetching data by id. You can not be sure that user with such id exist. E. g. another request has deleted this user or somebody was trying to tamper with your input data. Database is an external system to your application and if you know how to recover from such failures then you should do it. Especially in Scala where Option is a good tool for such task.

A: Option is the most minimalistic way to represent the return value from some computation that may fail. Throwing exceptions or returning null are acceptable only when dealing with Java code and your hands are somehow tied by an existing API (and when you're code is being called from Java code).
The next step up from Option would be Either[FailureIndication, SuccessValue].
A further improvement is ScalaZ's Validation.


text:
Q: What is the windows equivalent for envsubst in linux I use envsubst to substitute environment variables to a file in linux.
envsubst < task-definition.json > new-task-definition.json

How to achieve this feature in windows using default resources or using a 3rd party tool?

A: I don't directly know of a built in substitute for the envsubst command in Windows. However as you've made 3rd party tools an option, I would recommend MinGW, a minimalist GNU package for Windows users. It also comes with a envsubst implementation for Windows.
CygWin could also be an option. It provides a more complete collection of GNU tools and other Open Source tools for Windows (comes also with a POSIX API for Windows for example). It should also have an envsubst but as I don't have CygWin locally I cannot confirm this.
I would go for MinGW though as the extra functionnalities CygWin provides (POSIX environment) are not needed for envsubst but the choice is up to you (this SO post and this article may help you make a decision).

A: Packet in Ubuntu/Debian gettext-base has envsubst with same functional.
Online documentation for envsubst in gettext project.

A: See PowerTip: Expand Environmental Variables with PowerShell


text:
Q: .dbo type in SQL? I'm new to scripting, and I have noticed "[ABC].dbo.xyz" in one of the scripts.
But I can't find the database "[ABC]". Any help if .dbo is a database or anything else.
Cheers

A: .dbo is schema name. [ABC].dbo.xyz it means
DataBase.SchemaName.Table


text:
Q: Bug in glibc `div()` code? As quoted in "Integer division rounding with negatives in C++", in C before C99 (i.e. in C89) and in C++ before C++11 (i.e. in C++98 and C++03), for an integer division computation where either operand is negative the sign of the remainder (or equivalently, the rounding direction of the quotient) is implementation-defined.
Then comes the standard function std::div which is specified to truncate the quotient towards zero (i.e. the remainder has the same sign as the dividend (numerator)) (see for example this answer to "what is purpose of div() library function?").
Here is glibc's code for div() (source) (also quoted in "Is div function useful (stdlib.h)?"):
(Note: div_t is defined as:
typedef struct
  {
    int quot;
    int rem;
  } div_t;

-- end note.)
/* Return the `div_t' representation of NUMER over DENOM.  */
div_t
div (numer, denom)
     int numer, denom;
{
  div_t result;

  result.quot = numer / denom;
  result.rem = numer % denom;

  /* The ANSI standard says that |QUOT| <= |NUMER / DENOM|, where
     NUMER / DENOM is to be computed in infinite precision.  In
     other words, we should always truncate the quotient towards
     zero, never -infinity.  Machine division and remainer may
     work either way when one or both of NUMER or DENOM is
     negative.  If only one is negative and QUOT has been
     truncated towards -infinity, REM will have the same sign as
     DENOM and the opposite sign of NUMER; if both are negative
     and QUOT has been truncated towards -infinity, REM will be
     positive (will have the opposite sign of NUMER).  These are
     considered `wrong'.  If both are NUM and DENOM are positive,
     RESULT will always be positive.  This all boils down to: if
     NUMER >= 0, but REM < 0, we got the wrong answer.  In that
     case, to get the right answer, add 1 to QUOT and subtract
     DENOM from REM.  */

  if (numer >= 0 && result.rem < 0)
    {
      ++result.quot;
      result.rem -= denom;
    }

  return result;
}

As you can see there is a test after the big comment block, whose purpose is to "correct" the result if the built-in division truncates towards -infinity instead of towards zero.
Now the question:
Isn't there a bug in that code?
Let's first consider the example call div(42, -5). "In math" 42/-5 is exactly -8.4, so theoretically in C89 and C++03 42 / -5 could yield either -8 (truncated) or -9 (floored) depending on the implementation. Reading the code:

*

*If 42 / -5 yields -8 then 42 % -5 yields 2 (as 42 == -8 * -5 + 2), so the test is (42 >= 0 && 2 < 0) which is not true and the above function returns -8 and 2, as wanted;

*If 42 / -5 yields -9 then 42 % -5 yields -3 (as 42 == -9 * -5 + -3), so the test is (42 >= 0 && -3 < 0) which is true, so the above function returns the "corrected" -9 + 1 and -3 - -5, i.e. -8 and 2, as wanted.

But now let's consider the call div(-42, 5) (signs inverted):

*

*If -42 / 5 yields -8 then -42 % 5 yields -2 (as -42 == -8 * 5 + -2), so the test is (-42 >= 0 && -2 < 0) which is not true and the above function returns -8 and -2, as wanted;

*If -42 / 5 yields -9 then -42 % 5 yields 3 (as -42 == -9 * 5 + 3), so the test is (-42 >= 0 && 3 < 0) which... is not true! and the above function returns -9 and 3 instead of -8 and -2!

The comment in the code above first seems right when it says that the situation that needs a correction is when "REM has the opposite sign of NUMER", but then it makes the huge simplification "This all boils down to: if NUMER >= 0, but REM < 0, we got the wrong answer", which seems wrong (incomplete) to me because it omits the case "if NUMER < 0, but REM > 0" (-42 and 3 in the previous example).
I can hardly believe that such a bug would have remained unnoticed since 1992 or 1990 (apparently someone tried to "fix" it but it still seems incorrect because div(-42, 5) could return -10 and 8)... Arguably, most implementations have been truncating towards zero by default (and all are required to do so starting from C99 and C++11, so the issue is "moot" in the latest Standards 1) so the bug wouldn't manifest on them, but still... Maybe I'm missing something here?
Thank you for any insights.

1 (Edit) As for "the issue is moot in C++11 and C99 (and newer)": accordingly, in these Standards the built-in division is required to truncate towards zero, so we never need to adjust the result, but doesn't that then mean that the present implementation is more complex than needed and unnecessarily inefficient? The "big comment" is obsolete and the if test useless, so shouldn't that part just be removed entirely?

A: As the original author of the code, I have to say: You're right.  It's broken.  We had no systems that behaved "the wrong way" for testing, and I probably wrote the above too late (or early...) in the day or something.
We're saved by the newer standards, and the entire thing should be cleaned out, maybe with a small #ifdef (and corrected adjustment code) for pre-C99 if necessary.
(Also I'll note that the original was not indented with GNU-style indentation :-) )

A: There's rationale, why it can't be implementation-defined and what must it be.
TLDR: remainder sign must match the division sign.
Rationale:
When recovering divided value, knowing divions result, remainder and divisor, it remainder has to be summed with divisor-division product. If remander flag is implementation-specific, than operation to sum it should be also implementation-specific, is not it? Or at least have a code, after division, which would fix remainder sign if it's incorrect.


text:
Q: mp4 video recorded from iPhone 8 not playing iPad mini 2 & website I am capturing video using UIImagePickerController. Exporting video into mp4. Code is here:
- (NSString *)convertMOVToMp4:(NSURL *)url : (NSString *)filename
   {
       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory

      NSString *dataPath = [documentsPath stringByAppendingPathComponent:@"/doctorphoto"];
      NSError *error = nil;
      if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];

      NSString *videoPath1 = [dataPath stringByAppendingPathComponent:@"xyz2.mov"]; //Add the file name
      NSString *movfilepath = videoPath1;
      NSURL *videoURL = url;
      NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
      [videoData writeToFile:videoPath1 atomically:NO];

      AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:movfilepath] options:nil];
      NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];

      if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
       {
         AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetPassthrough];
         videoPath1 = [self getLocalVideoPath:filename];
         exportSession.outputURL = [NSURL fileURLWithPath:videoPath1];
         NSLog(@"videopath of your mp4 file = %@",videoPath1);  // PATH OF YOUR .mp4 FILE
         exportSession.outputFileType = AVFileTypeMPEG4;

        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {

                case AVAssetExportSessionStatusFailed:
                    NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                    break;

                case AVAssetExportSessionStatusCancelled:
                    NSLog(@"Export canceled");
                    break;
                default:
                    NSLog(@"Export success.");
                    [self.delegate onCompleteConvert: videoPath1 : anyobj];
                    break;
                }
                NSFileManager *fileManager = [NSFileManager defaultManager];
                [fileManager removeItemAtPath:movfilepath error:NULL];
            }];
        }

        return videoPath1;
    }

Its converting into mp4. Then uploading into AWS server. This link is streaming into iPhone 8, but not playing in iPhone 5S, iPad mini2. In website, audio is playing, but showing black screen.If I follow the same procedure from iPhone 5S or iPad mini, its working fine. Can anybody help me. Thanks in advance.

A: This change solved the problem:
- (NSString *)convertMOVToMp4:(NSURL *)url : (NSString *)filename
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory

    NSString *dataPath = [documentsPath stringByAppendingPathComponent:@"/doctorphoto"];
    NSError *error = nil;
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];

    NSString *videoPath1 = [dataPath stringByAppendingPathComponent:@"xyz2.mov"]; //Add the file name
    NSString *movfilepath = videoPath1;
    NSURL *videoURL = url;
    NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
    [videoData writeToFile:videoPath1 atomically:NO];

    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:movfilepath] options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];

    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
    {
        NSString *preset = AVAssetExportPreset1920x1080;

        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:preset];
        videoPath1 = [self getLocalVideoPath:filename];
//        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        videoPath1 = [NSString stringWithFormat:@"%@/doctorphoto/%@", [paths objectAtIndex:0], filename];
        exportSession.outputURL = [NSURL fileURLWithPath:videoPath1];
        NSLog(@"videopath of your mp4 file = %@",videoPath1);  // PATH OF YOUR .mp4 FILE
        exportSession.outputFileType = AVFileTypeMPEG4;
        exportSession.shouldOptimizeForNetworkUse = true;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {

                case AVAssetExportSessionStatusFailed:
                    NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                    break;

                case AVAssetExportSessionStatusCancelled:
                    NSLog(@"Export canceled");
                    break;
                default:
                    NSLog(@"Export success.");
                    [self.delegate onCompleteConvert: videoPath1 : anyobj];
                    break;
            }
//            UISaveVideoAtPathToSavedPhotosAlbum(videoPath1, self, nil, nil);
            NSFileManager *fileManager = [NSFileManager defaultManager];
            [fileManager removeItemAtPath:movfilepath error:NULL];
        }];
    }

    return videoPath1;
}


text:
Q: follow ajax call in debugger I'm using Chrome (and IE's) network tools in the debugger to view
what form data I'm sending by ajax calls.
This is the parsed data:

This is the source data:

The lines marked in yellow are what my question is about.
The first picture shows the correct string that I'm sending: description +'---'.
The second picture shows: description%2B'+---', where %2B is code for a plus sign.
I'm wondering, how can there be 2 plus signs in the second picture (the actual plus and the %2B)? Furthermore, what is this second plus doing inside the quotes?
That's not the data that I'm sending. On the server side it receives correctly, but I'm just wondering, is it a bug in IE and chrome Debugger or am I missing something?
Thanks

A: You are missing something, but it's very subtle: in application/x-www-form-urlencoded encoding, the space character is changed to a +. So the second plus is not a plus, but rather an encoded space.
For more information, see the answer to this question.


text:
Q: Path isn't changing using Router instead of BrowserRouter To solve a problem cause by Server Side Rendering, I had to change BrowserRouter to Router and pass history by using a function:
function App() {

    const history = createMemoryHistory();

    return (

            <Router history={history}>
                <ScrollToTop>

                    <Route path="/project/:name" component={Project}/>
                    <Route path="/about" component={About}/>

                        <Route path={["/", "/project/:name"]} exact component={CartHolder}/>

                        <Route path="/" exact component={CartHolderMobile}/>

                </ScrollToTop>
            </Router>

    );
}

Ever since I've made those changes, the path isn't changing anymore. In other words, it's always localhost:3000, no matter what route I'm on. How so?

A: You need to add Switch.
import { Route, Router, Switch } from 'react-router-dom';

function App() {

    const history = createMemoryHistory();

    return (

            <Router history={history}>
                <ScrollToTop>

                    <Switch>
                    <Route path="/project/:name" component={Project}/>
                    <Route path="/about" component={About}/>

                        <Route path={["/", "/project/:name"]} exact component={CartHolder}/>

                        <Route path="/" exact component={CartHolderMobile}/>

                    </Switch>
                </ScrollToTop>
            </Router>

    );
}

A: Create the history object outside of the component, since it is creating a new instance each time you re-render; also, try using createBrowserHistory() instead of createMemoryHistory():
const history = createBrowserHistory();

function App() {

    return (

            <Router history={history}>
                <ScrollToTop>

                    <Route path="/project/:name" component={Project}/>
                    <Route path="/about" component={About}/>

                        <Route path={["/", "/project/:name"]} exact component={CartHolder}/>

                        <Route path="/" exact component={CartHolderMobile}/>

                </ScrollToTop>
            </Router>

    );
}


text:
Q: Play framework 2.x (Scala) Navigation menu - Best practice to get some data from db on every request I've a question....I'm structuring a website with Play 2.7 (Scala).
I'm building something like a cms ..where you can create Page , Events, post comments and so on...I'm stuck building a navigation menu that should be created from some data stored in my db tables (categories).
My problem is that this "data" should be extracted on every request (home page, events page, posts page) and I'm not sure about the best approach of doing this. I was thinking about those 3 solutions:

*

*Inject my category service on each controller and pass for every action the navigation menu data on the view

*Create a filter that before each controller will call the service retrieve the data and pass it through the request eventually in my template get data from "request object"

*(not sure if possible) create a Module or Helper that can be used directly on template something like @GiveMeTheMenu() that return Seq[Category]
What do you think? any advice will be great!! thank you all.

A: Something like this @LucatT. Hope it helps.
routes
GET     /menu                  controllers.HomeController.giveMeTheMenu()

HomeController.scala
def giveMeTheMenu() =  SecureUserAction.async { implicit request =>
  // Codes here and fetch data from DB..
}


text:
Q: Access external xml file using jquery/javascript in html5 app without hosting the file I am new to jquery/java script/html 5.
I am creating an app where I will be reading an XML file from sdCard folder in mobile and parsing it;after which the data will be populated on page accordingly.
How can I access external XML file for mobile app without hosting the XML file?
I need to access it from local drive.I will have a specific path.
I need to pick the XML data through my application.
Currently I am creating the application as HTML page in Microsoft Visual Studio and trying to access the XML file which is placed in a folder in my 'D drive'.
Thanks in advance.
No help yet...can anyone suggest some ideas please????


text:
Q: Why does the variable executes the window object right away and not store it instead? I would like to understand what's happening with the code in which a variable is not stored immediately, but instead executed first before it can be called. An example code can be this (in the global scope):
var alertMe = alert("I\'m being executed then stored to be called again, but why?");

A: Because you are storing the result of calling the function, not storing a function.
This would be what you are after:
var alertMe = function () {
        alert("I\'m being executed then stored to be called again, but why?");
    };

And then when you want to call it:
alertMe();


text:
Q: How to include CMake files from source tree of included project I'm setting up a CMake based build system for an old framework, written in C. It consists of a single binary, some core libraries and many dynamically linked libraries, which are built against the core libraries. My goal is to structure those libraries in several CMake projects ("base framework", "extension libraries", …), supporting two scenarios:

*

*Independent build of extension libraries against base framework's build tree:
- base_framework/
  - cmake/
    - functions.cmake
  - core_libraries/
  - CMakeLists.txt
- extension_libs/
  - lib1/
  - lib2/
  - CMakeLists.txt

For this scenario, I use
export(EXPORT foo
  FILE FooFrameworkConfig.cmake)

and
find_package(FooFramework)

and add the build tree to CMAKE_PREFIX_PATH when configuring the extension_libs project.

*Using base framework and extension libraries as sub-projects (e.g. as git submodules) of an application specific project:
- my_project/
  - base_framework/
    - cmake/
      - functions.cmake
    - core_libraries/
    - CMakeLists.txt
  - extension_libs/
    - lib1/
    - lib2/
    - CMakeLists.txt
  - my_lib1/
  - CMakeLists.txt

For this scenario, I use add_subdirectory() for both, the base framework and the extension libs.
(A third scenario would be building the extension libraries against an install tree of the base framework. Unfortunately, this scenario is currently prevented by other CMake problems.)
Now, I want to include the base_framework/cmake/functions.cmake file, containing some custom CMake functions for all libraries, into all projects' top-level CMakeLists.txts in both scenarios.
For the second scenario, I simply set a cached CMake variable in base_framework/CMakeLists.txt:
set(BASE_FRAMEWORK_DIR ${CMAKE_CURRENT_SOURCE_DIR}
    CACHE PATH "" FORCE)

and use this variable for including the functions file in extension_libraries/CMakeLists.txt as well as my_project/CMakeLists.txt:
include(${BASE_FRAMEWORK_DIR}/cmake/functions.cmake)

But how do I find the function.cmake file in the base framework's source tree from extenstion_libs/cmake in the first scenario? All the directories (base_framework, extension_libs, base framework's build tree) may be anywhere on my computer.

A: To expand on my comment regarding your first scenario, it looks like you can set one of the properties of your exported core_libraries targets to contain the path to the base_framework/cmake modules. So you can set this in the base_framework/CMakeLists.txt file, let's set it in the LABELS target property. Then, we tell CMake to export the LABELS property using EXPORT_PROPERTIES:
Yourbase_framework/CMakeLists.txt file:
# Define the path to 'base_framework/cmake'
set(BASE_FRAMEWORK_CMAKE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/cmake")

add_library(CoreLibrary1 ...)
# Set the LABELS property, and tell CMake to export it.
set_target_properties(CoreLibrary1 PROPERTIES
    LABELS "${BASE_FRAMEWORK_CMAKE_MODULES}"
    EXPORT_PROPERTIES "LABELS"
)
# Define the export 'foo'.
install(TARGETS CoreLibrary1 EXPORT foo DESTINATION /path/to/install/targets)
export(EXPORT foo FILE FooFrameworkConfig.cmake)

This will ensure the path to the base_framework CMake modules gets exported explicitly, and can be accessed when imported by another project:
Your extension_libs/CMakeLists.txt file:
find_package(FooFramework)
# Get the LABELS property from the imported target.
get_target_property(BASE_FRAMEWORK_MODULE_DIR CoreLibrary1 LABELS)
message(STATUS "BASE_FRAMEWORK_MODULE_DIR: ${BASE_FRAMEWORK_MODULE_DIR}")

With a debug message(), we can verify the CMake modules directory was imported:
BASE_FRAMEWORK_MODULE_DIR: /your/path/to/base_framework/cmake

EDIT: Instead of hijacking the LABELS target property, you could also use define_property() to define your own custom property for the target.


text:
Q: Sixth grade math (number related) problem We have this statement (about rational numbers, btw):
If $m-n+p = p$ and $ m \neq n \neq 0$ then $ m = -n$
Is this true?
   a) always
   b) never
   c) sometimes
The given answer is b) but:
   1) this textbook often has some wrong answers and
   2) this question got me really thinking...
According to the truth table of the implication if the premise is false, then the whole implication is true, no matter what the conclusion is.
In this case the premise is a conjunction of several facts, two of which are contradictory ($m = n $ and $m \neq n$).
So the premise is false. And so I conclude the whole implication is true.
Then... what does that mean? I guess it means the correct answer is a).

A: I believe this is a poorly worded math problem, sixth grade or otherwise. The statement
$$m \neq n \neq 0$$
is possibly meant to be something like
$$m, n \neq 0$$
instead. This would be to ensure that $m = n$ and $m = -n$ can't both be true simultaneously as it only occurs when $m = n = 0$.
This is only a guess, but it would mean the question would then be consistent with the textbook's provided answer.


text:
Q: Backbone.js model.save() issues with a RESTful api I have a model that I save to a database using an api. My problem is when updating this model. The first time I change anything and call model.save, the attributes get passed as JSON to the api, which parses it and saves it without an issue. Now, the second time I make a change to that model in the same view, model.save adds an undefined object to my model. The api sees this object and rejects the PUT request.
Why does it work with the first update and not the second one?
Thanks for helping.
Here is the code, I hope you can understand it.
var LDAccount = Backbone.Model.extend({
    defaults : {
        ACC_NUM : '',
        BOOK_DATE : '',
        F_NAME : ''
    },
    template : _.template(
        "
Full Name
<input data-id='F_NAME' type=text value='<%= F_NAME %>' />" +
        "
Book Date
<input data-id='BOOK_DATE' type=text value='<%= BOOK_DATE %>' />"
    ),
    urlRoot : 'api/account'
});

var LDAccountView = Backbone.View.extend({
    el : '', // set this when instantiating this model in the router
    initialize : function(options) {
        this.model = options.model;
        this.model.id = options.id;
        this.model.bind('change', this.render, this);
        this.model.bind('error', this.renderError, this);
    },
    render : function() {
        $(this.el).html(this.model.template(this.model.toJSON()));
        $(this.el).append(
            '
' +
            '<input type=button id=reset value=Reset />' +
            '<input type=button id=save value=Save />' +
            '
'
        );
        return this;
    },
    events : {
        'click #save' : 'save2db'
    },
    save2db : function() {
        var $fields = $(this.el).find('input[type=text]');
        var modObj = new Object();
        $fields.each(function() {
            var $field = $(this);
            var prop = $field.attr('data-id');
            var val = $field.val();
            modObj[prop] = val;
        });
        this.model.set(modObj);
        console.log(modObj);
        this.model.save({
            success : function() {
                self.reset();
            }
        });
        return false;
    },
    renderError : function() {
        $(this.el).append('
Account does not exist
');
    },
    reset : function() {
    }
});

var MainView = Backbone.View.extend({
    // code omitted since it's not relevant to the question
});

var LDRouter = Backbone.Router.extend({
    routes : {
        "account/:modl/:acc_num": "renderView"
    },

    initialize : function() {
        this.search = new MainView({ el : '#main'});
    },

    // THIS IS THE VIEW THAT RENDERS THE MODEL
    renderView : function(modl, acc_num) {
        var self = this;
        var model = null;

        switch(modl) {
            case 'account':
                model = new LDAccount();
                break;
            // these other models were omitted for clarity
            case 'asset':
                model = new LDAsset();
                break;
            case 'info':
                model = new LDInfo();
                break;
            default:
                model = new LDAccount();
                break;
        }

        this.account = new LDAccountView({ id : acc_num, el : '#accDetail', model : model });
        this.account.reset = function() {
            self.renderView(modl,acc_num);
        };
        this.account.model.fetch();
    },

    accountInfo : function (acc_num) {
        var root = '';
        var url = window.location.href;
        var hashPos = url.indexOf('#');
        if(hashPos != -1) {
            root = url.substr(0,hashPos);
        } else {
            root = url;
        }
        window.location = root + "#account/account/" + acc_num;
    }

});

$(function() {
    var app = new LDRouter();
    Backbone.history.start();
});

A: Well,
Passing all arguments to model.save seems to work.
In other worlds,
this.model.save(
    {
        success: function() {
            // do some stuff here
        },
        error: function() {
            // do other stuff here
        }
    }
);

solved the issue I was having.
I still wonder why save was passing an undefined object that was added to the model attributes.

A: That is because you forgot to initialize variable, which stores POST data parts, with '' for example. So when data is appended to your variable as string it appends to 'undefined'. Resolution: the problem is in your server!


text:
Q: Connecting talend with Hadoop I see on product description of talend MDM free version that it supports connectivity with Hadoop however do not see any option on the interface.
I need to get the data from S3 and connect it with Talend. Can you please suggest if this can be done or not. If yes, then how?

A: You should use tJDBCConnection component to connect to Hadoop and tJDBCOutput to load data there.


text:
Q: Unknown error sequelize when adding new table column I have the following models.js:
const sequelize = require('../db')
const {DataTypes} = require('sequelize')

const User = sequelize.define('user', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    email: {type: DataTypes.STRING, unique: true},
    password: {type: DataTypes.STRING, unique: true},
    role: {type: DataTypes.STRING, defaultValue: "USER"}
})

const Basket = sequelize.define('basket', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}
})

const BasketDevice = sequelize.define('basket_device', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
})

const Device = sequelize.define('device', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    name: {type: DataTypes.STRING, unique: true, allowNull: false},
    price: {type: DataTypes.INTEGER, allowNull: false},
    rating: {type: DataTypes.INTEGER, allowNull: false, defaultValue: 0},
    img: {type: DataTypes.STRING, unique: true, allowNull: false},
})

There contains User, Device, Basket for User, and basketDevice for many-to-many relationship.
And this controller:
async getOne(req, res, next){
      const basket = await Basket.findOne({
          where: {userId: req.user.id},
          include: {
              model: BasketDevice,
              include: {
                  model: Device
              }
          }
      })
      return res.json(basket)
  }

And this correctly working(basket JSON):
{
    "id": 11,
    "createdAt": "2022-06-27T23:15:28.431Z",
    "updatedAt": "2022-06-27T23:15:28.431Z",
    "userId": 11,
    "basket_devices": [
        {
            "id": 6,
            "createdAt": "2022-06-27T23:15:40.782Z",
            "updatedAt": "2022-06-27T23:15:40.782Z",
            "basketId": 11,
            "deviceId": 1,
            "device": {
                "id": 1,
                "name": "12 pro",
                "price": 10000,
                "rating": 0,
                "img": "43049c4e-e50b-4aec-b6a9-de7fec272f25.jpg",
                "createdAt": "2022-06-18T21:10:18.036Z",
                "updatedAt": "2022-06-18T21:10:18.036Z",
                "typeId": 2,
                "brandId": 2
            }
        }
    ]
}

But if i add new column in basketDevice table, which store count of devices:
   const BasketDevice = sequelize.define('basket_device', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    count: {type: DataTypes.INTEGER, allowNull: false, defaultValue: 0},
})

I get following error:
Executing (default): SELECT "basket".*, "basket_devices"."id" AS "basket_devices.id", "basket_devices"."count" AS "basket_devices.count", "basket_devices"."createdAt" AS "basket_devices.createdAt", "basket_devices"."updatedAt" AS "basket_devices.updatedAt", "basket_devices"."basketId" AS "basket_devices.basketId", "basket_devices"."deviceId" AS "basket_devices.deviceId", "basket_devices->device"."id" AS "basket_devices.device.id", "basket_devices->device"."name" AS "basket_devices.device.name", "basket_devices->device"."price" AS "basket_devices.device.price", "basket_devices->device"."rating" AS "basket_devices.device.rating", "basket_devices->device"."img" AS "basket_devices.device.img", "basket_devices->device"."createdAt" AS "basket_devices.device.createdAt", "basket_devices->device"."updatedAt" AS "basket_devices.device.updatedAt", "basket_devices->device"."typeId" AS "basket_devices.device.typeId", "basket_devices->device"."brandId" AS "basket_devices.device.brandId" FROM (SELECT "basket"."id", "basket"."createdAt", "basket"."updatedAt", "basket"."userId" FROM "baskets" AS "basket" WHERE "basket"."userId" = 11 GROUP BY "basket"."id" LIMIT 1) AS "basket" LEFT OUTER JOIN "basket_devices" AS "basket_devices" ON "basket"."id" = "basket_devices"."basketId" LEFT OUTER JOIN "devices" AS "basket_devices->device" ON "basket_devices"."deviceId" = "basket_devices->device"."id";
node:internal/process/promises:265
            triggerUncaughtException(err, true /* fromPromise */);
            ^

Error
    at Query.run (D:\JavaScript\testNodeReact\server\node_modules\sequelize\lib\dialects\postgres\query.js:50:25)
    at D:\JavaScript\testNodeReact\server\node_modules\sequelize\lib\sequelize.js:311:28
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async PostgresQueryInterface.select (D:\JavaScript\testNodeReact\server\node_modules\sequelize\lib\dialects\abstract\query-interface.js:407:12)
    at async Function.findAll (D:\JavaScript\testNodeReact\server\node_modules\sequelize\lib\model.js:1134:21)
    at async Function.findOne (D:\JavaScript\testNodeReact\server\node_modules\sequelize\lib\model.js:1228:12)
    at async getOne (D:\JavaScript\testNodeReact\server\controllers\basketController.js:16:24) {
  name: 'SequelizeDatabaseError',
  parent: error: column "basket.id " must appear in the GROUP BY clause or be used in an aggregate function

I dont understand why this error occurs. Thank you in advance.

A: Fixed, needed rename 'count', because it is sql keyword


text:
Q: Why can't ✳1.1 be expressed symbollically in Whitehead and Russell's PM?
✳1.1. Anything implied by a true elementary proposition is true. Pp.

In the follow passage, it says, "we cannot express the principle symbolically, partly because any symbolism in which p is variable only gives the hypothesis that p is true, not the fact that it is true."*
*The footnote refers to Russell's Principles of Mathematics, §38, but I don't understand how exactly Russell solved Lewis Carroll's puzzle, "What the Tortoise said to Achilles."

A: About :

✳1.1. Anything implied by a true elementary proposition is true. Pp.

this is (a not very clear) formulation of modus ponens.
Modus ponens is an inference rule, so it is not "at the same level" of the laws of the calculus; in modern term, formula like $p \supset q$ are expressions in the language, but modus ponens is a rule fomulated in the meta-language, usually with schemata.
If you try to "download" mp in the languge, you will have :

$\vdash (p \cdot (p \supset q) ) \supset q$

and this is valid also when $p$ is false and $q$ is true.
We want instead, that the rule license a sound argument. What we need is something like :

$\frac {\vdash p \quad \vdash p \supset q}{\vdash q}$

The reference to Lewis Carroll is about the issue, discussed for the first time in "What the Tortoise said to Achilles", exactly about the role of "rules"; if I remeber well, was Carroll that argumented about the necessity of "postulating" rules that are not themselves "inferred", because in order to make a sound inference ... you need to apply a rule; this is the core of his paradox (a case of regressus). See the passage :

"Readers of Euclid will grant, I suppose, that Z follows logically from A and B, so that any one who accepts A and B as true, must accept Z as true?"
"Undoubtedly! The youngest child in a High School -- as soon as High Schools are invented, which will not be till some two thousand years later -- will grant that."
"And if some reader had not yet accepted A and B as true, he might still accept the sequence as a valid one, I suppose?"
"No doubt such a reader might exist. He might say 'I accept as true the Hypothetical Proposition that, if A and B be true, Z must be true; but, I don't accept A and B as true.' Such a reader would do wisely in abandoning Euclid, and taking to football."
"And might there not also he some reader who would say 'I accept A and B as true, but I don't accept the Hypothetical '?"


text:
Q: C++/CLI Convert unmanaged native C++ list into a managed C++/CLI List I have a C++ list which contains a struct.  My C++/CLI project consumes the native C++.  I would like to return a managed list to my C# project.  How can I convert my C++ list into a managed list?

A: First you need a ref class that acts as a wrapper around the struct for each item. You can store a pointer to the struct as a field in the ref class. Let's call it StructWrapper.
Then you need something to represent the list. The most flexible way to do that is to expose an IEnumerable<StructWrapper>. Either write your own implementation (not as bad as it sounds) or just load all the items into a List<StructWrapper> and return that.


text:
Q: Displaying an array of images in picturebox? I'm very new to visual C# I want to display an array of images in a picture box
Here's my code:
string[] list = Directory.GetFiles(@"C:\\pictures", "*.jpg");
Image[] images = new Image[5];
for (int index = 0; index < 5; index++)

{
    //HERE IS WHERE IM STUCKED WITH
    picturebox[index] = Image.FromFile(list[index]);
}

A: Edit-1 : This answer has a scope limited to Win-Forms C#.
You need certain assemblies added in your application before using this code.
using System.IO;
using System.Windows.Forms;

Edit ended;
Original Answer
You have to draw all image to one image for displaying them in single picturebox
That is bit complex you can use mutiple pictureboxes
In following code they are created dynamically according to need:
    // For confirm visibility of all images set
    this.AutoScroll = true;

    string[] list = Directory.GetFiles(@"C:\pictures", "*.jpg");
    PictureBox[] picturebox= new PictureBox[list.Length];
    int y = 0;
    for (int index = 0; index < picturebox.Length; index++)
    {
        this.Controls.Add(picturebox[index]);
        // Following three lines set the images(picture boxes) locations
        if(index % 3 == 0)
            y = y + 150; // 3 images per rows, first image will be at (20,150)
        picturebox[index].Location=new Point(index * 120 + 20, y);

        picturebox[index ].Size = new Size(100,120);
        picturebox[index].Image = Image.FromFile(list[index]);
    }

A: The answer provided throws an object reference exception.  Otherwise thanks for the example!
for (int index = 0; index < picturebox.Length; index++)
{
     this.Controls.Add(picturebox[index]);
     // Following three lines set the images(picture boxes) locations

should be
for (int index = 0; index < picturebox.Length; index++)
{
    picturebox[index] = new PictureBox();
    this.Controls.Add(picturebox[index]);
    // Following three lines set the images(picture boxes) locations

A: Use picturebox[index].Image  = Image.FromFile(list[index]);

A: //this code help you to work with picturebox in arraye
public partial class Form_Begin : Form
    {
        PictureBox[] pictureBoxs = new PictureBox[50];
        public Form_Begin()
        {
            InitializeComponent();
            pictureBoxs[0] = pictureBox1;
            pictureBoxs[1] = pictureBox2;
            pictureBoxs[2] = pictureBox3;
            pictureBoxs[3] = pictureBox4;}

            List<PictureBox> pictureBoxes = new List<PictureBox>();
 private void buttonX1_Click(object sender, EventArgs e)
            {
                for (int i = 0; i <2; i++)
                {
                    pictureBoxs[i].Image =your_name_project.Properties.Resources.Image_1;                     // Load Image_1 from Resources on property of picturebox
                }
                for (int i = 2; i < 4; i++)
                {
                    pictureBoxs[i].Image =your_name_project.Properties.Resources.Image_2;                    // Load Image_12 from Resources on property of picturebox

                }

A:  private void picbutton_Click(object sender, EventArgs e)
    {
        OpenFileDialog open = new OpenFileDialog();
        PictureBox[] picture = new PictureBox[5];
        int x = 0;
        int y = 15;
        for (int index = length; index < picture.Length; index++)
        {
                picture[index] = new PictureBox();
                picture[index].Size = new Size(100, 50);
                open.Title = "OPen Image";
                open.Filter = "JPG Files (*.jpg)|*.jpg|JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|GIF Files (*.gif)|*.gif";
                DialogResult result = open.ShowDialog();
                if (result == DialogResult.OK)
                {
                    picture[index].BackgroundImage = new Bitmap(open.FileName);
                    picture[index].SizeMode = PictureBoxSizeMode.AutoSize;
                    listBox1.Controls.Add(picture[index]);
                    if ((x % 3 == 0) && (index != 0))
                    {
                        y = y + 150; // 3 images per rows, first image will be at (20,150)
                        x = 0;
                    }
                    picture[index].Location = new Point(x * 210 + 20, y);
                    picture[index].Size = new Size(200, 150);
                    x++;
            }
        }
    }


text:
Q: json encode no parentheses leaflet I have a problem. I want to show my markers in leaflet api but i can't. Because i can't create needed json format properly.
This is what leaflet wants
var geojsonFeature = [{
            "type": "Feature",
            "properties": {
                "name": "Coors Field",
                "amenity": "Baseball Stadium",
                "popupContent": "This is where the Rockies play!"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [29.0502548217773, 41.0171458178711]
            }
        }, {
            "type": "Feature",
            "properties": {
                "name": "Coors Field",
                "amenity": "Baseball Stadium",
                "popupContent": "This is where the Rockies play!"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [29.1502548217773, 41.0171458178711]
                }
            }];

what i did
echo "[";

while ( $row = pg_fetch_row ( $result ) ) {
$marker_id = $row [0];
$name = $row [1];
$category = $row [2];
$information = $row [3];
$latitude = $row [4];
$longitude = $row [5];
$owner = $row [6];

// print ($marker_id . "," . $name . "," . $category . "," . $information . "," . $latitude . "," . $longitude . "," . $owner."\r\n") ;
$coordinates = "[" . $longitude . "," . $latitude . "]";

echo json_encode ( array (
        "type" => "Feature",
        "properties" => array (
                "name" => "Coors Field",
                "amenity" => "Baseball Stadium",
                "popupContent" => "This is where the Rockies play!"
        ),
        "geometry" => array (
                "type" => "Point",
                "coordinates" => $coordinates
        )
) );
echo ",";
}

echo "]";

But in coordinates my json looks like coordinates":"[29.0505981445312,40.9878676184644]" but i dont want quotes. I want like this "coordinates": [29.0502548217773, 41.0171458178711] So how can i do that ?
Edit: i found solution $latitude = (float) $row [4];   $longitude = (float) $row [5]; $coordinates = array($longitude, $latitude); solve this problem. but stil not working because i think i need json object.
My new code
echo "{type:\"FeatureCollection\",features:[";

$isfirst = true;
while ( $row = pg_fetch_row ( $result ) ) {
if ($isfirst){
    $isfirst = false;
}else{
    echo ",";
}
$marker_id = $row [0];
$name = $row [1];
$category = $row [2];
$information = $row [3];
$latitude = (float) $row [4];
$longitude = (float) $row [5];
$owner = $row [6];

// print ($marker_id . "," . $name . "," . $category . "," . $information . "," . $latitude . "," . $longitude . "," . $owner."\r\n") ;
//$coordinates = "[" . $longitude . "," . $latitude . "]";
$coordinates = array($longitude, $latitude);

echo json_encode ( array (
        "type" => "Feature",
        "properties" => array (
                "name" => "Coors Field",
                "amenity" => "Baseball Stadium",
                "popupContent" => "This is where the Rockies play!"
        ),
        "geometry" => array (
                "type" => "Point",
                "coordinates" => $coordinates
        )
) );

echo "]}";

i take string and in js did this
var geoJSON = JSON.parse(data);
    L.geoJson(geoJSON).addTo(map);

but giving error SyntaxError: JSON.parse: expected property name or '}'
var geoJSON = JSON.parse(data);

A: i solved my geojson object problem. First i use eval method after that parse to json and now markers in map.
$.post( "show_markers.php")
.done(function(data) {

    var json = JSON.stringify(eval("(" + data + ")"));
    var obj = JSON.parse(json);

    L.geoJson(obj, {
        onEachFeature : function(feature, layer) {
            var popupContent = ""+feature.properties.name+"
"+feature.options.information;
            if (feature.properties && feature.properties.popupContent) {
                //popupContent += feature.properties.popupContent;
            }
            layer.bindPopup(popupContent);
            layer.on('click', onClick);
            //layer.on('dragend', updateCoordinate);
        },
        pointToLayer : function(feature, latlng) {
            return new customMarker(new L.LatLng(feature.geometry.

            coordinates[1], feature.geometry.coordinates[0]), {
                marker_id : feature.options.marker_id,
                draggable : true
            });
        }
    }).addTo(map);

});


text:
Q: How do I check for the existence of a character in a Linq query on a CSV file? I have a query which gets an employees number from a field containing their username and employee number in a field like this:

name [employee number]

e.g.

Fred Bloggs [1234]

My query works fine most of the time, but occasionally the field does not contain the employee number, and hence it throws an "index out of range" exception. (i.e. if the field just contains "Fred Bloggs" it will fail.)
The query is as follows:
var allEmpNos = (from row in csvTable.AsEnumerable()
                 join d in DeltekList
                 on row.Field<string>("Phone number") equals d.Mobile into t
                 from rt in t.DefaultIfEmpty()
                 select new
                 {
                   name = row.Field<string>("User name"),
                   empNo = rt == null ? row.Field<string>("User name").Split('[')[1].Replace("]", "") : rt.EmpNo,
                  });

How can I handle the "bad data" at run time? My ideal would be for it to throw an exception telling the user to correct the CSV file. I could do this by parsing the CSV twice, once to check the presence of a "[" and "]" and then again to do the actual import, but this seems inefficient as the CSV is pretty big.

A: You could change your condition to something like this..
empNo = rt == null ? ( row.Field<string>("User name").Contains("[")?
                       row.Field<string>("User name").Split('[')[1].Replace("]", "")
                       :"--Invalid data--" )
                   : rt.EmpNo,

This way, you have all your incorrect formats in the collection. After this line of code, you could check if there are any items in collection with ""--Invalid data--" as empNo. You can give UserName as reference to users so that they can correct their data.
Optionally, you could also return your whole row.Field<string>("User name") appended with some hardcode text like --ERROR. This will help you capturing even the incorrect data.

A: You could use a let clause and check the Length of the string array before you try to access index 1. This is indeed untested but it should give you the idea:
var allEmpNos = (from row in csvTable.AsEnumerable()
             join d in DeltekList
             on row.Field<string>("Phone number") equals d.Mobile into t
             from rt in t.DefaultIfEmpty()
             let arr = row.Field<string>("User name").Split('[')
             select new
             {
                 name = row.Field<string>("User name"),
                 empNo = rt == null ? ((arr != null && arr.Length > 1) ? arr[1].Replace("]", "") : string.Empty) : rt.EmpNo,
             });


text:
Q: Inserting data into SQL table from HTML form A HTML form has been created that should (when filled) send the data it's holding to a database inserting a new row so it can be used later on. However, I can't seem to get it to work, I'm getting the following error:

Notice: Use of undefined constant con - assumed 'con' in C:\xampp\htdocs\form\insert.php on line 4
Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampp\htdocs\form\insert.php on line 17
Data not inserted

HTML Code
<!DOCTYPE html>

        <title>Form linked to database</title>

        <form action="insert.php" method="post">
            Name: <input type="text" name="username">

            Email: <input type="text" name="email">

            <input type="submit" value="insert">
        </form>

PHP Code
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');

if(!con) {
    echo 'Not connected to server!';
}

if(!mysqli_select_db($con,'tutorial')) {
    echo 'Database not selected!';
}

$Name = $_POST['username'];
$Email = $_POST['email'];

$sql = "INSERT INTO person (Name,Email) VALUES ('$Name','$Email')";
if(!mysql_query($con,$sql)) {
    echo 'Data not inserted';
} else {
    echo 'Data inserted';
}
//header("refresh:2; url=form.html");
?>

I'm new to PHP and followed the following YouTube tutorial.
I'm also using XAMPP for this, on a localhost. Any help is appreciated. Thank you.

A: You should change:
if(!con){
    echo 'Not connected to server!';
}

to:
if(!$con){
    echo 'Not connected to server!';
}

as you're missing a dollar sign there.
Additionally, you're using a mysql_ function here, on the mysqli_ object $con:
if(!mysql_query($con,$sql))

Change this to
if(!mysqli_query($con,$sql))

SQL injection
As your query is vulnerable to SQL injection, then I'd like to recommend you take a look at using prepared statements, or using mysqli_real_escape_string()-- though, this comes with a few gotcha's: https://stackoverflow.com/a/12118602/7374549

A: You have done two small mistakes ie
1) forgot to add $ before the variable name ie changes is
if(!$con){
        echo 'Not connected to server!';
    }

2) you are connected with mysqli_connect but you are trying to use mysql_query functions in it. so please change and use mysqli_query
if(!mysqli_query($con,$sql)){ }

This is issue in your case. My suggestion is to use mysqli or PDO that is good practice.

A: You are not using the correct mySQL query function, you have used:
mysql_query($con
You should use:
mysqli_query
instead. Let me know if you still have issues.

A: Try this :
<?php

// Create connection
$conn = new mysqli("localhost", "username", "password", "databasename");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('test fname', 'test lname', 'test@example.com')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

A: Altough you have a lot of answers right now, I think none of those is the right one. I've written your code new, procedural as you did, but with prepared statements, so you're going to be save to SQL injections.
<?php
    $con = mysqli_connect('localhost','[retracted]','[retracted]');

    if(!$con){
        echo 'Not connected to server!';
    }

    if(!mysqli_select_db($con,'tutorial')){
        echo 'Database not selected!';
    }

    $Name = $_POST['username'];
    $Email = $_POST['email'];

   if ($stmt = mysqli_prepare($con, "INSERT INTO person (Name, Email) VALUES (?, ?"))) {
    mysqli_stmt_bind_param($stmt, "ss", $Name, $Email);
    mysqli_stmt_execute($stmt);
    echo "Data inserted";
   }
   else {
    echo "Error";
   }

mysqli_close($con);

    //header("refresh:2; url=form.html");
?>

I think it should work, if not let me know.


text:
Q: machine learning binary classification I am trying binary classification using multilayer perceptron.
It's basically sentiment analysis of sentences. Only binary at the moment. positive vs negative (there's no neutral in my data currently), so it's binary.
One thing weird I found is that the performances (accuracy, recall, precision, f1-score) are significantly different when positive is encoded 1 (positive=1, negative=0) and when negative is encoded 1 (positive=0, negative=1). of course I used the same X dataset and the same model (architecture). only label encoding was changed.
when positive cases are encoded 1, average f1 score is about 89. (I ran the same model 10 times)
when negative cases are encoded 1, average f1 score is about 50. (I ran the same model 10 times)
I am quite confused with this result. I think there shouldn't be any significant difference.

A: F1-score is the harmonic mean of the precision and recall and his formula is given by :
TP/(TP + 1/2(FP + FN)).More details here: https://en.wikipedia.org/wiki/F-score .
So as you can observe there is not much symmetry in the formula and is biased towards the True Positives. What about accuracy ?


text:
Q: Access SQL - I need a query to count fields based on several criteria I have used stackoverflow for years and usually I have been able to find what I need through searching but I apologize, I couldn't find an example like this.  I am extremely new to this stuff but love doing it at work to assist with various projects.
I work in the insurance claims industry, we have insurance claims as electronic files.  The supervisors do reviews of these files, simply called a file review. I have an Access db which I use to track all the file reviews at work.
Sometimes as Claims Supervisors we are doing a file review on our OWN associates, meaning the associate reports to me.  Other times I am doing a file review on an associate who reports to a DIFFERENT supervisor.
My master table looks like this (with lots of other columns) and each record indicates a file review:
ClaimNumber | Supervisor | Reviewer
----------- | -----------| ------------
1---------- | ---Bob-----| Bob
2---------- | ---Bob-----| Amy
3---------- | ---John----| Amy
4---------- | ---John----| Dean
5---------- | ---John----| John
6---------- | ---Dean----| Dean
7---------- | ---Dean----| Dean
8---------- | ---Dean----| Bob
9---------- | ---Kyle----| Bob
10--------- | ---Bob-----| Shawn

Depending on if a join is used, please note that sometimes a supervisor name is not listed a single time in the reviewer column.  Likewise, sometimes a reviewer name is not listed a single time in the supervisor column.
So, I need a single query that returns
Reviewer  ------  TotalReviews ----  Self_Reviews ---- Cross_Reviews

The reviewer is all the unique reviewers
TotalReviews is a count of how many times that reviewer's name is listed in reviewer column
Self reviews is a count of how many times that reviewer's name is listed in the reviewer column where their name is equal to the supervisor name for that particular record
Cross reviews is a count of how many times that reviewer's name is listed in the reviewer column where their name is NOT equal to the supervisor name for that particular record
Bob has 3 reviews total, 1 self,  2 cross
Amy has 2 reviews total, 0 self, 2 cross
Dean has 3 reviews total, 2 self, 1 cross
John has 1 review, 1 self, 0 cross
Shawn has 1 review, 0 self, 1 cross
I know this seems complex to me but I am hoping someone can assist to make it much easier.  I am just using Access so any oracle or other SQL syntax may not work.

A: There is a simple trick you can use here: summing over indicator functions.
The indicator function for self reviews would be Switch(Supervisor = Reviewer,1,True,0).
That leads to the following query:
SELECT
  T.Reviewer,
  COUNT(*) AS TotalReviews,
  SUM(Switch(T.Supervisor = T.Reviewer,1,True,0)) AS Self_Reviews,
  SUM(Switch(T.Supervisor <> T.Reviewer,1,True,0)) AS Cross_Reviews
FROM TableName T
GROUP BY T.Reviewer

In other environments than Access, the indicator function would typically be the fllowing:
CASE WHEN Supervisor = Reviewer THEN 1 ELSE 0 END


text:
Q: Аналог Firebug'а для других браузеров Здравствуйте. Существует ли аналог плагина Firebug для браузеров Chrome, Opera? (Для Chrome я видел уже нечто похожее)
A: зачем? у хрома встроенный дебаггер отличный, у оперы тоже её DragonFly нормально работает, даже у ie есть дебаггер, конечно он по функционалу слабее но пользоваться можно.
A: Chrome: нажмите ctrl + shift + J. Это Web Inspector.
Opera: главное меню - страница - средства разработки - Open Opera Dragonfly.
A: firebugLite


text:
Q: Symfony or something else get confused with logged in user while executing a test After a lot of research and without found nothing helpful I come here to see if can get some help. I'm building some functional tests for my code and one of those test need a fake user for work since in the function at controller I need to access to User object by using this piece of code:
$account = $this->getUser();
$user = $account->getUser();

This is the code in my test:
public function testmodifyCommissionAction() {
    $this->logIn();

    $updateCompanyCommission = $this->client->getContainer()->get('router')->generate('updateCompanyCommission', array(), false);
    $this->client->request("POST", $updateCompanyCommission, array(
        'id' => rand(1, 10),
        'fee' => rand(1, 10)
    ));

    var_dump($this->client->getResponse()->getContent());

    $this->assertSame(200, $this->client->getResponse()->getStatusCode()); // Test if response is OK
    $this->assertSame('application/json', $this->client->getResponse()->headers->get('Content-Type')); // Test if Content-Type is valid application/json
    $this->assertNotEmpty($this->client->getResponse()->getContent()); // Test that response is not empty

    $decoded = json_decode($this->client->getResponse()->getContent(), true);

}
private function logIn() {
    $session = $this->client->getContainer()->get('session');

    $firewall = 'secured_area';
    $token = new UsernamePasswordToken('admin', null, $firewall, array('ROLE_ADMIN'));
    $session->set('_security_' . $firewall, serialize($token));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $this->client->getCookieJar()->set($cookie);
}

Now, where is the problem here? If I login in my application using valid credentials and run the test then I got this error:

Cannot set session ID after the session has started. (500 Internal
  Server Error)

If I logout and run the same test it works, so something is wrong here and I can't get what is, any help? advice? tips? example of working code?
EDIT: created User and try to login with the current created User
I modified a bit the method and now this is the current code I have:
protected function createUser() {
    $kernel = new \AppKernel('test', true);
    $kernel->boot();

    $this->container = $kernel->getContainer();
    $userManager = $this->container->get('fos_user.user_manager');
    $userManager->createUser();

    $data['firstname'] = $this->generateRandomString(4);
    $data['lastname'] = $this->generateRandomString(4);
    $data['lastname2'] = "";
    $data['photo'] = "";
    $data['banner'] = "";
    $data['password'] = md5($this->generateRandomString(18));
    $data['email'] = $this->generateRandomString(6) . "@test.com";

    $user = $userManager->createAccountAndUser($data);

    return $user;
}

This is the function I'm using to login, modified also to add support for current user:
private function logIn($client, $user) {
    $session = $client->getContainer()->get('session');

    $firewall = 'main';
    $token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_USER'));
    $session->set('_security_' . $firewall, serialize($token));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $client->getCookieJar()->set($cookie);
}

And this is the test I'm trying to run:
public function testmodifyCommissionAction() {
    $client = static::createClient();
    $user = $this->createUser();

    $this->logIn($client, $user->getUser()->getAlias());

    $updateCompanyCommission = $client->getContainer()->get('router')->generate('updateCompanyCommission', array(), false);
    $client->request("POST", $updateCompanyCommission, array(
        'id' => rand(1, 10),
        'fee' => rand(1, 10)
    ));

    $this->assertSame(200, $client->getResponse()->getStatusCode());
    $this->assertSame('application/json', $client->getResponse()->headers->get('Content-Type'));
    $this->assertNotEmpty($client->getResponse()->getContent());
}

But fails with this message:
PHP Fatal error:  Call to a member function getUser() on a non-object in /var/www/html/kraken/src/Wuelto/Company/ApprovalBundle/Controller/FeeCompanyController.php on line 47
PHP Stack trace:
PHP   1. {main}() /usr/bin/phpunit:0
PHP   2. PHPUnit_TextUI_Command::main() /usr/bin/phpunit:46
PHP   3. PHPUnit_TextUI_Command->run() /usr/share/pear/PHPUnit/TextUI/Command.php:129
PHP   4. PHPUnit_TextUI_TestRunner->doRun() /usr/share/pear/PHPUnit/TextUI/Command.php:176
PHP   5. PHPUnit_Framework_TestSuite->run() /usr/share/pear/PHPUnit/TextUI/TestRunner.php:349
PHP   6. PHPUnit_Framework_TestSuite->runTest() /usr/share/pear/PHPUnit/Framework/TestSuite.php:745
PHP   7. PHPUnit_Framework_TestCase->run() /usr/share/pear/PHPUnit/Framework/TestSuite.php:775
PHP   8. PHPUnit_Framework_TestResult->run() /usr/share/pear/PHPUnit/Framework/TestCase.php:783
PHP   9. PHPUnit_Framework_TestCase->runBare() /usr/share/pear/PHPUnit/Framework/TestResult.php:648
PHP  10. PHPUnit_Framework_TestCase->runTest() /usr/share/pear/PHPUnit/Framework/TestCase.php:838
PHP  11. ReflectionMethod->invokeArgs() /usr/share/pear/PHPUnit/Framework/TestCase.php:983
PHP  12. Wuelto\Company\ApprovalBundle\Tests\Controller\FeeCompanyControllerTest->testmodifyCommissionAction() /usr/share/pear/PHPUnit/Framework/TestCase.php:983
PHP  13. Symfony\Component\BrowserKit\Client->request() /var/www/html/kraken/src/Wuelto/Company/ApprovalBundle/Tests/Controller/FeeCompanyControllerTest.php:71
PHP  14. Symfony\Bundle\FrameworkBundle\Client->doRequest() /var/www/html/kraken/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:325
PHP  15. Symfony\Component\HttpKernel\Client->doRequest() /var/www/html/kraken/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:111
PHP  16. Symfony\Component\HttpKernel\Kernel->handle() /var/www/html/kraken/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Client.php:81
PHP  17. Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle() /var/www/html/kraken/app/bootstrap.php.cache:2303
PHP  18. Symfony\Component\HttpKernel\HttpKernel->handle() /var/www/html/kraken/app/bootstrap.php.cache:3022
PHP  19. Symfony\Component\HttpKernel\HttpKernel->handleRaw() /var/www/html/kraken/app/bootstrap.php.cache:2883
PHP  20. call_user_func_array:{/var/www/html/kraken/app/bootstrap.php.cache:2911}() /var/www/html/kraken/app/bootstrap.php.cache:2911
PHP  21. Company\ApprovalBundle\Controller\FeeCompanyController->modifyCommissionAction() /var/www/html/kraken/app/bootstrap.php.cache:2911

I can't find where is the problem, any help?
Solution: The problem was on this line:
$this->logIn($client, $user->getUser()->getAlias());

since I was trying to pass $user->getUser()->getAlias() instead of $user the object.
EDIT 2: Sort code and getting error while trying to DELETE the recently test user
Now I made some changes and pass the $this->createUser() to setUp() function in order to have User object on $this->user var.
public function setUp() {
    static::$kernel = static::createKernel();
    static::$kernel->boot();
    $this->em = static::$kernel->getContainer()->get('doctrine')->getManager();

    $fixture = new LoadFeeData();
    $fixture->load($this->em);

    $this->user = $this->createUser();

    parent::setUp();
}

Now in tearDown() I'm trying to delete the current User I created earlier with this code:
protected function tearDown() {
    parent::tearDown();

    $this->em->remove($this->user);
    $this->em->flush();
    $this->em->close();
}

But get this error:
1) Company\ApprovalBundle\Tests\Controller\FeeCompanyControllerTest::testmodifyCommissionAction
Undefined index: 0000000065c988b30000000022bd0894

/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:2860
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1736
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1397
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1677
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1645
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:647
/var/www/html/kraken/app/cache/test/jms_diextra/doctrine/EntityManager_533ab9b6c8c69.php:59
/var/www/html/kraken/src/Company/ApprovalBundle/Tests/Controller/FeeCompanyControllerTest.php:131

Why I can't delete the User?

A: What I typically do is enable http_basic security for the test environment and then do the following to get an authenticated client:
config_test.yml
security:
    firewalls:
        wsse_secured: # This should be your firewall name
          http_basic: true

Next, make sure your tests extend the Symfony WebTestCase (Symfony\Bundle\FrameworkBundle\Test\WebTestCase)
Then you can just call:
$client = $this->createClient([], [
    'PHP_AUTH_USER' => $username,
    'PHP_AUTH_PW'   => $password,
]);

client->request("POST", $updateCompanyCommission, array(
    'id' => rand(1, 10),
    'fee' => rand(1, 10)
));

...

Using this method, the users need to either be loaded as a data fixture, or you can write a method to create a user in the setUp and destroy the user in the tearDown.  Here is the method that I use to create a user for a test:
protected function createUser($password, $timezone, $roles)
{
    $kernel = new \AppKernel('test', true);
    $kernel->boot();

    /** @var Account $user */
    $this->container    = $kernel->getContainer();
    $userManager        = $this->container->get('fos_user.user_manager');
    $user               = $userManager->createUser();

    $user->setEmail('unique-email-address@not-here.com');
    $user->setUsername('auniqueusername');
    $user->setPlainPassword($password);
    $user->setTimezone($timezone);
    $user->setEnabled(true);

    foreach ($roles as $role) {
        $user->addRole($role);
    }

    $userManager->updateUser($user);

    return $user;
}