text:
Q: Is there a possibility that C++ multiple inheritance might be replaced with the Java interfaces? I have been studying a bit of Java and C++ more or less at the same time and I noticed that Java has a more friendly and intuitive way of interpreting the OOP than the C++ way.
Yes, Java is completely OO and, on the other hand, C++ supports many paradigms, but this doesn't mean that C++ couldn't improve its way of implementing the OO paradigm.
C++ supports multiple inheritance and Java translated it with multiple implementation (interfaces), which I find really intuitive and simple (I don't think that this is just an opinion).
My first question is in the title. I think that C++ would be more friendly, without losing practically a bit of its power. It's a question of improving a extraordinary programming language, which however is not perfect.
My second question is: what are the advantages of multiple inheritance compared to the interfaces of Java programming language (if any)?

A: Multiple inheritance can be dangerous, but it's sometimes the most appropriate solution to a problem, and there's lots of software already written that uses it.  Removing multiple inheritance from C++ would break all that software, in a way that's not simple to fix.  Being compatible with existing code is more important than being "friendly".
If you want the effect of a Java interface in C++, just write a class that contains nothing but pure-virtual member functions, and derive from it using virtual inheritance to "implement" it in another class.
Java was designed as a higher-level and simpler language than C++, and the tradeoffs between them are the same as between any high-level and lower-level language.  Java provides a bit less flexibility (e.g. single inheritance, little control over memory allocation) in exchange for being a bit easier to work with; C++ provides more power and flexibility at the cost of having to "know what you're doing" a bit more.  These differences are OK; there's no need to turn one language into the other.

A: *

*C++ is becoming more and more user-friendly with the updates, becoming bit by bit more like java, but it needs not to change too much not to wreck legacy code. The Boost library is more or less the pioneer of the c++ language, being the (probably) most used library of all times and taking an easier and more intuitive OO approach to c++. Features from the Boost libraries often get to the STD eventually.

*Let's take this easy example : class man and class parent have respective functions work and cry. class dad inherits from both man and parent. Now you don't have to write cry twice when you write class mom which inherits from class woman as well as from parent.

A: 1.Having multiple inheritance in a explicit way is seems to be more user friendly but actually it is not. There are lot of problem will be coming in the future if you do that i mean in your project for an instance knowingly unknowingly you will be adding the same code again and again to your final Class which makes your project more complicated and confuses the interpreter which method should be executed at the appropriate time.

*

*Just consider in C++ you have
Class A
{
     void display_a(){}
}
Class B A
{
    void display_b(){}//this class contains 'display_a()' too
}
Class C A,B //multiple inheritance.
{
   display_c(){} //this class contains two times 'display_a()' and one time 'display_b()'
}

so class a contains two times 'display_a()' this is the problem we have in multiple inheritance in C++ so that we go for Interface in Java,which solve that problem.


text:
Q: Sign up still successful even though username is taken I want to create a system where the user can't sign up if the username is already taken by others. However, this seems to not work as even though the username is taken, the sign up process is still completed.
I am doing this by retrieving every username from Firebase and running it through it see if the username entered by the user is already used. If it is, it should stop the sign up process and tell user to enter another username.
Code:
let ref = Database.database().reference(fromURL: "https://heytest.firebaseio.com/")
        let usernamesRef = ref.child("users")

        usernamesRef.observeSingleEvent(of: .value, with: { (snapshot) in
            let con = snapshot.value as! [String:[String:Any]]
            var usernamesArray = [String]()
            Array(con.keys).forEach {
                if let res = con[$0] , let username = res["username"] as? String {
                    usernamesArray.append(username)
                }
            }

            for storedUsername in usernamesArray {
                if storedUsername == self.usernameTextField.text! {
                    self.usernameVerified = false
                    self.usernameLabel.textColor = UIColor.red
                    self.usernameLabel.text = "USERNAME TAKEN"
                    self.usernameTextField.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor.red, thickness: 1.5)
                    return
                }
           }

        }) { (error) in
            print(error.localizedDescription)
        }

        print("TEST")
        self.usernameVerified = true
        print(self.usernameVerified)
        self.usernameTextField.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor.black, thickness: 1.5)
        self.usernameLabel.textColor = UIColor.black
        self.usernameLabel.text = "USERNAME"

On sign in button clicked:
@IBAction func onSignUp(_ sender: Any) {

    print("Sign Up pressed")
    isValidUsername(username: usernameTextField.text!)
    print("[SIGN UP] - Username: \(usernameVerified)")
    isValidEmail(email: emailTextField.text!)
    print("[SIGN UP] - Email: \(emailVerified)")
    isValidPassword(password: passwordTextField.text!)
    print("[SIGN UP] - Password: \(passwordVerified)")

    if passwordVerified && emailVerified && usernameVerified {

        Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) { (authResult, error) in
            if error != nil {
                self.errorLabel.alpha = 1
                self.errorLabel.text = error?.localizedDescription
                self.shake(viewToShake: self.errorLabel)
                return
            }

            guard let user = authResult?.user else {
                return
            }

            //Successfully Authenticated User
            let ref = Database.database().reference(fromURL: "https://heytest.firebaseio.com/")
            let usersReference = ref.child("users").child(user.uid)
            let values = ["username": self.usernameTextField.text!, "email": self.emailTextField.text!, "games-played": "0"]
            usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
                if err != nil {
                    print(err!)
                    return
                }

                //Successfully registered user's data to database
                print("[SIGN UP] - Successfully Signed Up")
                self.errorLabel.alpha = 0
                self.present((self.storyboard?.instantiateViewController(withIdentifier: "TabBarViewController"))!, animated: false, completion: nil)

            })
        }

    } else {

        errorLabel.alpha = 1
        shake(viewToShake: errorLabel)
        print("Password/Email/Username verification not complete!")
        print("[SIGN UP] - Password: \(passwordVerified)")
        print("[SIGN UP] - Username: \(usernameVerified)")
        print("[SIGN UP] - Email: \(emailVerified)")

    }

}

A:
I am doing this by retrieving every username from Firebase and running it through it see if the username entered by the user is already used.

IMHO this is not the right approach, the logic should be handled server side. Imagine if you have 1 million user this will never work.

A: I think it will be easier for you to see if any matches are thrown from firebase for a specific userName.
let reference = Database.database().reference()
reference.child("users").queryOrdered(byChild: "username").queryEqual(toValue: "yourNewUserName").observeSingleEvent(of: .value) { (snapshot) in
    // if there is data in the snapshot reject the registration else allow it
}

Otherwise you are downloading way too much data to the client. If you grow on users it will also take forever to download.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the exact program logic so that a chat user is 'pinged' using "@joesmith" in a chatroom? I would like a definitive program logic description that takes into account all factors below to determine whether or not a chat user is 'pinged' using if I posted a message using "@joesmith" in a chatroom.

*

*If the person has never been in that chatroom (and consequently never posted in it), is it for certain that the person will not get a 'ping' in his/her chat inbox?  (seems the answer is 'yes')

*What is the precise definition of the FAQ's "has been in the room at some point" or "recently active" (see quote in point 6 below)?

*

*The time period: 1 day?  1 week?

*How it is measured: since the last post, or since the last time the user enters that chatroom?

*The factor of being present in other chatrooms (listed in the avatar list for those rooms, even if grayed out) vs. not at all (left all rooms).
For example, let's say @joesmith is not in any chatroom presently but has posted a message in that chatroom 45 days ago, will @joesmith sees something in his chat inbox the next time he goes to chat?

*Posted previously vs. currently in the room (i.e. didn't leave).  @balpha in a comment says

Note that you can only invite to a room that you're already in.

What does it mean?  Does it mean I have to remain present in the room, or does it mean I have posted messages in that room already?  Does it matter how long ago I have posted?

*The role of some chat preferences: ignoring, "quicker notification" flag

*Different behavior ("super ping") if you are a moderator.
For example, from the answer to a 12-year old question:

You can't, unless the person's been recently active in the room you're currently in. Only moderators can use a "super-ping" feature to invite people to chat, even if they haven't visited it before.

*Whether or not I own the room

*Whether the person is a chat user (i.e. received a chat user id)

*Reputation of the user

*Status of the user (whether suspended or not)

*Other factors not mentioned above
I have reviewed:

*

*the Chat FAQ on notification

*How to make sure I'll be pingable in chat for a few days? (thanks, @rene)

*Contacting someone unannounced via chat
Motivation: I'm trying to use chatrooms more to avoid unnecessary comments on older questions or older answers when I want to engage the post writers to discuss the topic rather than to improve the post (per SE guidance).  I want to have some assurance of the other being 'pinged' and don't want to press the other into responding if he/she is not interested.

A: Here is what I know from years of chat experience.
In order for @JoeSmith to ping Joe Smith in a chat room, one of the following conditions must be met:

*

*Joe is currently in the room. In this case, it doesn't matter if Joe ever posted a message in the room.

*Joe is not currently in the room, however he did post at least one message in the past and it's not yet a week since he was last seen inside the room. Week being 7 calendar days, or 168 hours.

There is one less known rule, that for 48 hours since last being seen, short ping is also possible, e.g. @Joe will also ping Joe Smith, no need for the full name.


text:
Q: Onmouseover using Hyperlinks I have a hyperlink and 2 pictures (one is the link's normal picture and the other is its onmouseover picture)
I can't figure out how to make the hyperlink's picture change onmouseover. I know I can do it with the 'a' tag but this tag doesn't support this : '~/Site/Page.aspx' so if I want to navigate through folders I need to use '../../Site/Page.aspx' which is inaccurate.
So how can I change picture with the asp:hyperlink button?

A: Don't. Use css:
a {
  background-image: url(images/image1.jpg);
}
a:hover {
  background-image: url(images/image2.jpg);
}

Only use specific selectors for you case, of course.

A: I'd also recommend the CSS route, however to ensure no latency with image load you could merge the two images into the one file with an image editor and use 'background-position' to switch the viewable portion of the image.


text:
Q: Find(query) return empty table The first query return the rigth table with the matching value. From those matching value i want to query my other table to get all the information
 var query = { partition : req.params.partition }
    PartitionFilter.find(query)
    .then(partition => {
        if (!partition)
            return res.status(400).send({message : "Partition not found"})
        var query = {
            name : { $in : partition.filter }
        }
        Filter.find(query)
        .then(filter => {
            if (!filter)
                return res.status(400).send({message : "Filter not found "})
            return res.status(200).send(filter)
        })
        .catch(err =>{
            return res.status(500).send(err)
        })
    })
    .catch(err => {
        return res.status(500).send(err)
    })

Here is the schema of Filter
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var filterSchema = new Schema({
    description: {
        type: String,
        required: true,
    },
    name: {
        type: String,
        unique: true,
        required: true,
   },
   duration: {
        type: Number,
        required: true
   }
});

module.exports = mongoose.model('Filter', filterSchema);

'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var partitionfilterSchema = new Schema({
  filter: String,
  partition: String
});

module.exports = mongoose.model('PartitionFilter', partitionfilterSchema);

It should return the table of all the matching filter but i get an empty table

A: Ok, I think I know how to solve your problem. Your first query returns an array of PartitionFilters so, when you reference to partition.filter in your second query, it is undefined because partition is an array (did you printed the result of the first query and the value of partition.filter?).
Your second query should be something like:
var query = {
    name: { $in: partition.map(function(elem){ return elem.filter; }) }
}

EDIT:
Although this may solve your problem, I think you could improve your code in different ways.

*

*As find queries return arrays, I suggest you rename the variables returned to plural (partitions, filters...).

*If you intended to get only one result, you should do a findOne but in the case of PartitionFilter, as partition is not defined as
unique, there could be more than one result with the same partition
and it would only return the first one.

*If it is not defined as unique because you want to make a ManyToOne relationship and there are several documents that relate a
partition to a filter, what you should do is define partition as
unique and filter as an array.

*In any case, you should relate the tables by ID (in this case, partitionFilter.filter should be an ID or an array of Filter IDs).
For example:
var partitionfilterSchema = new Schema({
    partition: {
        type: String,
        unique: true,
        required: true
    },
    filters: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Filter'
    }]
});

And your code could look like:
var query = { partition : req.params.partition }
PartitionFilter.findOne(query)
.then(partition => {
    if (!partition)
        return res.status(400).send({message : "Partition not found"})

    var query = {
        _id: { $in: partition.filters }
    }

    Filter.find(query)
    .then(filter => {
        if (!filters || !filters.length)
            return res.status(400).send({message : "Filters not found "})
        return res.status(200).send(filters)
    })
    .catch(err =>{
        return res.status(500).send(err)
    })
})
.catch(err => {
    return res.status(500).send(err)
})


text:
Q: Totally blocking Internet Access though Group Policy on Windows Server 2008 R2 I need to block internet access for some users on our Windows Servers 2008 R2. If you google this question you will find a lot results that propose to disabling Internet Explorer and setting a proxy to 0.0.0.0. Unfortunately this can easily bypassed using a portable Firefox for example.
Is there a more restrictive solution? I need to find a way that even telnet, ftp etc. won't work.
Thanks for your help!
Update for clarification: I would like to block internet access only for some users, not or all on this server.

A: The best solution is probably to do this on the network level with a proxy. You can force all Internet-bound traffic through the proxy using WCCP or the like and not configure anything on the hosts themselves.
Otherwise, I think you might be able to configure the Windows firewall to disallow this outbound traffic via GPO which would catch all outbound traffic.
Furthermore, since it's a server, it likely has a static IP and you could just block outbound traffic at your perimeter firewall - assuming you are actaully trying to block Internet access from the server itself - it wasn't clear to me if you mean for all users (using the server and GPO to accomplish) or if you just wanted to block access from your servers.

A: ...why not just set the gateway in DHCP to a non-routed address or a blank address so traffic can't go out? Set it for those user's MAC address so they always get that (incorrect) gateway address.
Otherwise proxy it, log it, and then fire them if this is a business discipline problem.

A: You could use a proxy for this or you could set up an ACL (access control list) on your router to block outbound traffic from the workstations in question.

A: I hate to give an expensive commercial recommendation, but the Barracuda Web Filter 310 does everything you're asking and can definitely tie into your AD topology. It has content and protocol awareness, so you could restrict downloads, telnet, ftp, etc. on a user or group basis.

A: The only realistic option probably is to disable direct internet acces, thus forcing all internet traffic through a proxy. Then configure this proxy to require authentication (ideally against the Active Directory[AD]). That way, everyone has to authenticate to go online.
Disadvantages:

*

*If any programs on the server require net access, they need to get special service accounts that grant them access (either real AD accounts, or just special accounts on the proxy). These accounts will of course need to be protected.

*If some programs or users require protocols that cannot be easily proxied (e.g. exotic protocols), you will have to find a case-by-case solution.

*It will mean extra configuration for all users (though I believe some browsers can automatically log on to a proxy)

I have never implemented this, but I believe it should work. At least Squid lets you authenticate against an AD; I assume other proxies can do the same.


text:
Q: Crawl react pages in Java I'm writing a web crawler in Java. The target is a website written in react. I use selenium to render the page to a DOM tree:
HtmlUnitDriver unitDriver = new HtmlUnitDriver();
unitDriver.get("https://www.instagram.com/9gag/?hl=en");
WebElement body = unitDriver.findElement(By.tagName("body"));

What I get for body is:
<body class="">

Which is almost nothing. Does selenium render react pages ? I also tried this on google.com and it worked fine.


text:
Q: transact-sql question Assume there were 100 records in tableA and tableA contained a column named 'price'.
How do I select the first-n record if where sum of price > a certain amount (e.g. 1000) without using cursor?
thanks

A: Top N implies some kind of order, which you did not supply, so I assumed any random order.
You can change this on the OVER clause of the ROW_NUMBER().
Try something like
DECLARE @Table TABLE(
        Price FLOAT
)

INSERT INTO @Table SELECT 1
INSERT INTO @Table SELECT 11
INSERT INTO @Table SELECT 12
INSERT INTO @Table SELECT 15
INSERT INTO @Table SELECT 10
INSERT INTO @Table SELECT 65
INSERT INTO @Table SELECT 100

DECLARE @TotalPrice FLOAT
SELECT  @TotalPrice = 100

;WITH Vals AS (
        SELECT  *,
                ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) RNR
        FROM    @Table
)
, Totals AS (
        SELECT  v.RNR,
                SUM(vP.Price) TotalPrice
        FROM    Vals v LEFT JOIN
                Vals vP ON  v.RNR >= vP.RNR
        GROUP BY    v.RNR
)
, LimitValue AS (
        SELECT  TOP 1
                RNR
        FROM    Totals
        WHERE   TotalPrice >= @TotalPrice
        ORDER BY    RNR
)
SELECT  *
FROM    Vals
WHERE   RNR <= (
                    SELECT  RNR
                    FROM    LimitValue
                )

A: select price from tableA
where price > 1000
limit n;
n - no. of records you want in result set
--
Cheers


text:
Q: How to enable address sanitizer for multiple C++ binaries I am working on a product that is composed of multiple C++ executables and libraries that have various dependencies on one another. I am building them all with GCC and -fsanitize-address.
From what I understand, if I want to use address sanitizer with a library I have to build it as a shared object (which is the default option for GCC). Because of this, I thought the best option would be to build address sanitizer statically with -static-libasan for the executables and build it dinamically for the libraries. However, when I do that I get a link error when building one of the C++ executables:
==10823==Your application is linked against incompatible ASan runtimes

This makes me think that static and dynamic version of address sanitizer cannot be mixed with GCC, am I right? I was not able to find any information about this on the sanitizers GitHub page.

A: TLDR:

*

*If you use GCC/Clang and both main executable and shlibs are sanitized, you don't need to do anything special - just stick with default -fsanitize=address.

*If you use GCC and only shlibs are sanitized, again keep using -fsanitize=address and additionally export LD_PRELOAD=$(gcc -print-file-name=libasan.so) when running your application.

*If you use Clang and only shlibs are sanitized, compile/link with -fsanitize-address -shared-libasan and additionally export LD_PRELOAD=$(clang -print-file-name=libclang_rt.asan-x86_64.so) when running the app.

Now some explanations. Originally Asan existed only in Clang which by default used (and still uses) -static-libasan. When it was ported to GCC, GCC developers decided that shared runtime is preferred (e.g. because it allows one to sanitize just one shared library and keep main executable unsanitized e.g. sanitize Python module without recompiling python.exe, see wiki for other examples). Both approaches are binary incompatible so you can't link part of your applications with static runtime and part with dynamic runtime.
Roughly

*

*GCCs -fsanitize=address is equivalent to Clangs -fsanitize=address -shared-libasan (and -shared-libasan is second-class citizen in Clang so not as well supported)

*Clangs -fsanitize=address is equivalent to GCCs -fsanitize=address -static-libasan (and again, -static-libasan is second-class citizen in GCC so has some issues)

As a side note, for other GCC/Clang Asan differences see this helpful wiki.


text:
Q: remove iOS push notification after fresh reinstall I have application which has successfully integrated apple push notifications, when user logs in to the application app registers with the push notification and token is saved on our back-end, when user sign out from the app, we remove the push notification tokens from our back-end. but if user uninstall app from the device WITHOUT SIGN-OUT from app, and then re-install,in that case we can still send push notifications to the device, since app is newly installed and not logged in any user we have to remove tokens from the backend. since iOS app does not have any API for uninstallation events how can I remove device token from back-end. I can use push notification feedback service to get uninstalled device tokens but how can I resolve the issue when user removes the application and then reinstall.
I tested this scenario with skype, it also have this issue. (install Skype > Log In > (now you can send app to Background and send some chats from any other device, you will get push notifications) > then Remove app from Device without Sign-Out from Skype > Re-Install Skype > now if we send skype chat we receives push notifications but skype app is newly installed and no one is logged in)

A: I guess the best thing you can do is to preventively unregister/remove the tokens, when the app is started without a logged in user. You should update the registration anyways each time the app is started, so register/unregister at each app start, depending on if a user is logged in or not. This way, if the user reinstalls the app and starts it the first time, it will be unregistered.
This is the best behaviour you can achieve, as it is the same for Twitter, Facebook, Skype, etc...

A: I think you are not able to get an event or detect if a user has removed the app or not. What you can do is to send periodic notifications to a device (only setting the badge, without sending a notification) and remove the tokens for what you get a 401 status code. Then you know the app has been removed and you can delete the token.

A: Yeah! as you have quoted yourself it will continue to send notification unless your server has the info that someone has logged out. Obviously you won't get the info when your app was uninstalled and then reinstalled.
Workaround: If your app is reinstalled you can call an API to deregister since no user is logged in.


text:
Q: getting date in php different format I just wanna know how to get the php date on this one. "April 4 - 25, 2015",
The table structure of this one is like "date_start = 04 - 04" and "date_end = 04 - 25" and "year = 2015"
Regards,

A: Try this code.
$date_start = "04 - 04";
$date_end = "05 - 25";
$year = "2015";

$date_start = preg_replace('/\s+/', '', $date_start);
$date_end = preg_replace('/\s+/', '', $date_end);

list($month1, $startDate) = explode("-",$date_start);
list($month2, $endDate) = explode("-",$date_end);

if($month1 == $month2)
{
    $month1 =  date("F",strtotime("2015-".$month1."-01"));
    $Output = $month1." ".(int)$startDate." - ".(int)$endDate.", ".$year;
}
else
{
    $month1 =  date("F",strtotime("2015-".$month1."-01"));
    $month2 =  date("F",strtotime("2015-".$month2."-01"));

    $Output = $month1." ".(int)$startDate." - ".$month2. " ". (int)$endDate.", ".$year;
}

echo $Output;

A: Are you looking for something like this:
<?php
$date_start = explode(" - ","04 - 04");
$date_end   = explode(" - ","05 - 25");
$year       = "2015";

$monthNumStart  = $date_start[0];
$monthNumEnd    = $date_end[0];

if($monthNumStart == $monthNumEnd)
{
    $monthName = date('F', mktime(0, 0, 0, $monthNumStart, 10));
    $date = $monthName.' '.$date_start[1].' - '.$date_end[1].', '.$year;
}else{
    $monthName = date('F', mktime(0, 0, 0, $monthNumEnd, 10));
    $date = $monthName.' '.$date_start[1].' - '.$date_end[1].', '.$year;
}
echo $date;
?>


text:
Q: How to change the way shading looks on cubes in Three.js? I'm creating a little game using Three.js and everything is going well apart from shome shading issues with cubes. I'm basically building a game level by just dropping textured cubes down to form a maze. The problem is that when the cubes are next to one another, each one is shaded in such a way that it looks as if it's a separate entity and not part of a larger wall.
Here is an example, notice the illusion of a single wall is lost:

Is there a different shading technique i should use or is there a nice property to be set somewhere to change this shading behavior?
This is my cube model:
{

    "metadata" :
    {
        "formatVersion" : 3,
        "generatedBy"   : "Blender 2.60 Exporter",
        "vertices"      : 8,
        "faces"         : 6,
        "normals"       : 8,
        "colors"        : 0,
        "uvs"           : 4,
        "materials"     : 1,
        "morphTargets"  : 0
    },

    "scale" : 1.000000,
    "materials": [{
        "DbgColor" : 15658734,
        "DbgIndex" : 0,
        "DbgName" : "WallCube",
        "colorAmbient" : [1.0, 1.0, 1.0],
        "colorDiffuse" : [1.0, 1.0, 1.0],
        "colorSpecular" : [0.15, 0.15, 0.15],
        "mapDiffuse" : "../../textures/walls/stone/stone.png",
        "mapDiffuseWrap" : ["repeat", "repeat"],
        "mapNormal" : "../../textures/walls/stone/stone_normal.png",
        "mapNormalFactor" : 1.0,
        "shading" : "Lambert",
        "specularCoef" : 25,
        "transparency" : 1.0,
        "vertexColors" : false
    }],

    "vertices": [50.000000,-50.000000,-50.000000,50.000000,-50.000000,50.000000,-50.000000,-50.000000,50.000000,-50.000000,-50.000000,-50.000000,50.000000,50.000000,-50.000000,50.000000,50.000000,50.0000050,-50.000000,50.000000,50.000000,-50.000000,50.000000,-50.000000],

    "morphTargets": [],

    "normals": [1.000000,-1.000000,-1.000000,1.000000,-1.000000,1.000000,-1.000000,-1.000000,1.000000,-1.000000,-1.000000,-1.000000,1.000000,1.000000,-1.000000,-1.000000,1.000000,-1.000000,-1.000000,1.000000,1.000000,1.000000,1.000000,1.000000],

    "colors": [],

    "uvs": [[0.000000,1.000000,1.000000,1.000000,1.000000,0.000000,0.000000,0.000000]],

    "faces": [43,0,1,2,3,0,0,1,2,3,0,1,2,3,43,4,7,6,5,0,0,1,2,3,4,5,6,7,43,0,4,5,1,0,1,2,3,0,0,4,7,1,43,1,5,6,2,0,1,2,3,0,1,7,6,2,43,2,6,7,3,0,1,2,3,0,2,6,5,3,43,4,0,3,7,0,3,0,1,2,4,0,3,5]

}

and this is how i load it:
JSONLoader = new THREE.JSONLoader();

Light = new THREE.PointLight(0xFFFFFF);
Light.position = {x:0, y:75, z:350};

Meshes = [];
JSONLoader.load("../assets/models/cube.js", function(Geometry)
{
    for (var MeshIndex = 0; MeshIndex <= 5; MeshIndex++)
    {
        Meshes[MeshIndex] = new THREE.Mesh(Geometry, new THREE.MeshFaceMaterial());
        Meshes[MeshIndex].position.x = MeshIndex * 100;
        Scene.add(Meshes[MeshIndex]);
    }
});

Scene.add(Light);

Any ideas how to make the cubes look like a continuous wall?

A: JSONLoader.load("../assets/models/cube.js", function(Geometry)
{
    Geometry.materials[ 0 ].shading = THREE.FlatShading;

    // ...
}

This was kindly answered by alteredq over at the three.js site.
https://github.com/mrdoob/three.js/issues/1258#issuecomment-3834489


text:
Q: appending variable to an input value using val() The following code appends text goes here to an input value
$('#someid').val($('#someid').val() + 'text goes here');

I'm trying to use variable like below but It isn't working
var someText= text goes here;
$('#someid').val($('#someid').val() + 'someText');

How can I properly append variable using val() ?

A: You don't use string delimiters around a variable:
$('#someid').val($('#someid').val() + someText);

A: Take away the quotes so you're accessing the variable and not the string literal.
var someText = 'foo bar';
$('#someid').val($('#someid').val() + someText);

A: assign your variable like a string; below
var someText= "text goes here";
$('#someid').val($('#someid').val() + someText);

A: jsFiddle
Description
In my jQuery you'll see that I used .html this can easily be switched to .val if needed.  I used .html only for demo's sake, the main part to learn is that a variable is used by name only.
HTML

more stuff

JS
# someText is a string variable by putting quotes around the text
var someText=' text goes here';
# someText is a variable and thus is just appended without quotes
$('#someid').html($('#someid').html() + someText);


text:
Q: How to disable foreign key constraints in Postgres dump file? I used pg_dump -U postgres -p 65432 --table=tableName --data-only --column-inserts DBName>fileName.sql to dump one particular table's rows. Now I need to insert them to another database but I get this error

insert or update on table "tableName" violates foreign key constraint "tableName_fk1"

How to proceed by dropping the foreign key contraint?

A: the command is:
alter table "tableName" drop constraint "tableName_fk1"

The foreign key must already exist in the database where you want to import, since the dump was made --data-only.


text:
Q: flatlist rendering data from json api as 3 items per row Hello all i am fetching data from json api and i am using flatlist to render items . i am using numColumns property to display 3 items per row
but let's suppose i have 7 or 8 items
i am having trouble with rendering. the layout i want to be displayed is like this
X X X
X X X
X X

but what i am getting is this:
layout
Here is my code:
    _renderItem = ({ item, index }) => (
            <View style={categorystyles.Category} key={index}>
                <TouchableOpacity activeOpacity={.5}
                    onPress={() => this.props.navigation.navigate('ListingPerCategory', { catid: item.id })}>
                    {item.category_app_icon ? <Image style={categorystyles.CategoryImg}
                        source={{ uri: `${item.category_app_icon}` }} /> :
                        <Image style={categorystyles.CategoryImg}
                            source={require('../assets/coffeecup.png')} />}
                </TouchableOpacity>
                <Text style={{ marginTop: 5 }}>{escape(item.name).replace('%20', ' ').replace('%26amp%3B%20', ' ')}</Text>
            </View>
        )
   render(){
     return(
        <FlatList
        horizontal={false}
        data={this.state.categories}
        keyExtractor={(item, index) => item.id}
        numColumns={3}
        renderItem={this._renderItem}
    />
     )
   }

    const styles = StyleSheet.create({
       Category: {
            flex:1,
            justifyContent: 'center',
            alignItems:'center',
            margin:5
        },
        CategoryImg: {
            resizeMode: 'contain',
            width: 50,
            height: 50
        }
    })

A: Since you're using flex: 1 and alignItems: center ,  your layout will look like this
Therefore the items inside it will be aligned to center vertically and horizontally based on the items layout.
Instead you need to check for the width of the device and add layout based on that.
In your styles
Category: {
  flex:1,
  maxWidth: Dimensions.get('window').width / 3 - 10, // Width / 3 - (marginLeft and marginRight for the components)
  justifyContent: 'center',
  alignItems:'center',
  margin:5
},

After adding this style , layout will look like this

A: if you want to be displayed like this
X X X
X X X
X X

not
X X X
X X X
 X X

just change the style:
   const styles = StyleSheet.create({
   Category: {
        flex:1,
        justifyContent: 'flex-start',
        alignItems:'center',
        margin:5
    },
    CategoryImg: {
        resizeMode: 'contain',
        width: 50,
        height: 50
    }
})

A: Flatlist lazy loads the items - which means they render when you scroll. This is the behaviour of flat list due to performance. If you are interested to render all together, you should use ScrollView instead


text:
Q: iterate through If statment checking checkboxs in vba word I have a code that works to check singel checkbox
Sub check_if_checked()
    If CheckBox1.Value Then
        MsgBox "checked"
    Else
        MsgBox "not checked"
    End If
End Sub

What i want to do is to create a loop where in the if statment i can replace the check box number with the loop iteration variable.
Something like
If "CheckBox" & i.Value Then

Can this be done or maybe done a diffrent way?

A: In the below example I have 4 Check Boxes with the following names CheckBox1, CheckBox2, CheckBox3, CheckBox4.
Sub check_if_checked()
  Dim i As Integer
  i = 1
  Do While i <= 4
    If (IsNull(Me("CheckBox" & i).value)) Then _
      MsgBox ("CheckBox" & i & " is Null") Else _
      MsgBox (Me("CheckBox" & i).value)
    i = i + 1
  Loop
End Sub

Or the following may work for you:
Sub check_if_checked()
  Dim TempCntrl As Control

  For Each TempCntrl In UserForm1.Controls
    If TempCntrl.Name Like "CheckBox*" Then
      MsgBox (TempCntrl.Name & ":  " & TempCntrl.value)
    End If
  Next
End Sub


text:
Q: youtube URL's not valid? Im using code like this to check if URL's are real and exist:
its working fine generally, but it's not working for youtube urls..
eg this valid url: http://www.youtube.com/watch?v=c4IBN5OAdZc
Utils.UrlExists(uri)

public static bool UrlExists(string url)
        {

            using (var client = new MyClient())
            {
                client.HeadOnly = true;
                // fine, no content downloaded
                try
                {
                    string s1 = client.DownloadString(url);
                    return true;
                }
                catch { return false; }
            }
        }

        class MyClient : WebClient
        {
            public bool HeadOnly { get; set; }
            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest req = base.GetWebRequest(address);
                if (HeadOnly && req.Method == "GET")
                {
                    req.Method = "HEAD";
                }
                return req;
            }
        }

A: Consider this approach:
Hit this URL with your C# code, and analyze the response:
http://gdata.youtube.com/feeds/api/videos/<your ID>

You will be able to see the HTTP response of 200 when successful.
Try it in your browser; you'll see that good IDs give you content, others will return plaintext of "Private video" or "Invalid id".

A: erics comment was the answer. If he puts an answer I'll mark it as correct. in the meantime I'll mark this as correct


text:
Q: This command works in the terminal, but not in a shell script I have a command that I would like to run from a shell script:
LD_PRELOAD='/usr/$LIB/libstdc++.so.6' DISPLAY=:0 steam

This command is necessary to run Steam correctly on my system.  If I try to run Steam without this command, the icon appears on the launcher then disappears again, leaving just a process that I have to end in system monitor.
If I cut and paste that command directly into a terminal, it works perfectly.  Steam opens and works just fine, and the terminal sits there in the background giving output until Steam is closed again.
If I try to run that command from a shell script, it doesn't work anymore.  The same problematic behavior shows up.
Interestingly, if I go into the terminal and type ./Steam.sh - which is the name of my script - Steam opens correctly.
Steam.sh is located in my home folder, and I run all the commands from my home folder in the terminal, and I have given execute permission to Steam.sh.  I have also tried adding & to the end of the command in the shell script, but that hasn't helped.
Any idea why this command works differently depending on whether it's launched from a shell script or from a terminal?  I thought shell scripts were supposed to be basically the same thing as running commands from a terminal.

A: Because the default Terminal interpreter is Dash, where you are running the script in Bash. Bash features things that Dash doesn't.
Anyway you can fix Steam like this:
Before running Steam:
ln -sf /usr/lib/libstdc++.so.6.0.20 ~/.local/share/Steam/ubuntu12_32/steam-runtime/i386/usr/lib/i386-linux-gnu/libstdc++.so.6

After running Steam:
rm $HOME/.steam/steam/ubuntu12_32/steam-runtime/i386/usr/lib/i386-linux-gnu/libstdc++.so.6
rm $HOME/.steam/steam/ubuntu12_32/steam-runtime/amd64/usr/lib/x86_64-linux-gnu/libstdc++.so.6


text:
Q: Python giving errors. How to solve it? Here's the code:
import numpy as np
np.random.seed(123) #for reproducibility

from keras.models import sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist

(X_train, y_train), (X_test, y_test) = mnist.load_data()

X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)

model = Sequential()

model.add(Convolution2D(32, 3, 3, activation='relu', input_shape=(28,28,1)))
model.add(Convolution2D(32, 3, 3, activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X_train, Y_train,
          batch_size=32, epochs=10, verbose=1)
score = model.evaluate(X_test, Y_test, verbose=0)

Here's the error:
Epoch 1/10
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-71-db342978fb82> in <module>()
     37
     38 model.fit(X_train, Y_train,
---> 39           batch_size=32, epochs=10, verbose=1)
     40 score = model.evaluate(X_test, Y_test, verbose=0)

9 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    992           except Exception as e:  # pylint:disable=broad-except
    993             if hasattr(e, "ag_error_metadata"):
--> 994               raise e.ag_error_metadata.to_exception(e)
    995             else:
    996               raise

ValueError: in user code:

    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:853 train_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:842 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1286 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:2849 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:3632 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:835 run_step  **
        outputs = model.train_step(data)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:787 train_step
        y_pred = self(x, training=True)
    /usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py:1020 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    /usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py:254 assert_input_compatibility
        ' but received input with shape ' + display_shape(x.shape))

    ValueError: Input 0 of layer sequential_29 is incompatible with the layer: expected axis -1 of input shape to have value 1 but received input with shape (32, 1, 28, 28)

A: Change
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)

To,
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)


text:
Q: How to get all the classname used inside the button from one class? I have a button with multiple classname a, b and active.
<button class="a b active"></button>

I want to get the classname a & b only using active. I have used following code
document.querySelectorAll('.active')

I get
<button_ngcontent-c1="" class="a b active" ng-reflect-klass="0,0" ng-reflect-ng-class="[object Object]"></button>

I am not being able to get this class a and b.
Can anybody help?

A: querySelectorAll gives you a NodeList.
From that, spread that list into an array, and iterate over it to get the className property :

const nodeList = document.querySelectorAll('.active');

const els = [...nodeList];

for (let el of els) {
  console.log(el.className.split(' '));
}
<button class="a b active"></button>
<button class="c d active"></button>
<button class="e f active"></button>


text:
Q: Show that if a metric space is complete, separable and not countable then it has cardinal $\aleph_1$
Show that if a metric space is complete, separable and not countable then it has cardinal $\aleph_1$

I have encountered this exercise and I don't know where to start. There is a lot of important information and I can't imagine how to use it. Any hint?

A: Although the answer @Shalop contributed with is surely correct, this course is about metric spaces, not topological spaces. And that's why when dealing with the concepts of given a topology, etc, I can't follow. However, I came up with a proof, that in a similar manner, I don't see why $X$ has to be complete.
Since $X$ is separable, it contains a countable dense subset $\mathcal{D} \subset X$. We have that $\overline{\mathcal{D}}=\mathcal{D} \cup \{\text{the set of limit points of } \mathcal{D}\}=X$. (Here $\overline{\mathcal{D}}$ stands for the closure of $\mathcal{D}$).
Now, since $\mathcal{D}$ is countable, then the "number" of sequences in $\mathcal{D}$ is $\aleph_{0}^{\aleph_{0}}=\aleph_{1}$ Therefore, $\#  \{\text{the set of limit points of } \mathcal{D}\} \leq \aleph_{1}$.
However $\#  \{\text{the set of limit points of } \mathcal{D}\} > \aleph_{0}$. Because if not $\# (\overline{\mathcal{D}})=\#(\mathcal{D} \cup \{\text{the set of limit points of } \mathcal{D}\})= \# (X) = \aleph_0$ Which contradicts the fact that $X$ is not countable.
Therefore $\# (\overline{\mathcal{D}})= \# (X) = \aleph_{1}$

A: We will show that the cardinality of any second-countable $T_1$ space is at most $\aleph_1$, which includes this as a special case.
Let $X$ be such a space, and let $\{U_n \}_{n \in \mathbb{N}}$ be a countable basis for $X$.
Let $\tau$ denote the topology (i.e, the collection of open sets) of $X$, and define a map $f: \mathcal{P}(\mathbb{N}) \to \tau$ as $J \mapsto \bigcup_{k\in J} U_k$. Then $f$ is surjective since $\{U_k\}$ forms a basis for $\tau$. Therefore $|\tau| \leq |\mathcal{P}(\mathbb{N})| = \aleph_1$.
Next, define a map $g: X \to \tau$ by $x \mapsto X \setminus \{x\}$. Then $g$ is injective, and thus $|X| \leq |\tau| \leq \aleph_1$.
Edit: It has been pointed out to me that the above argument only shows that $|X| \leq \aleph_1$, not that $|X| = \aleph_1$. Assuming the continuum hypothesis, this would automatically hold (given that $|X|> \aleph_0$), and we would be done.
If we don't assume CH, we can still obtain the result that $|X| \geq \aleph_1$ using complete metrizability of $X$. I don't see a truly elementary argument for this, but see theorem A.4 in the following set of notes for a terse little proof: http://www.math.tamu.edu/~kerr/book/appendixA.pdf

A: Joaquin's and Shalop's answers prove the desired result without assuming completeness but using the continuum hypothesis (CH). In fact, they show that $\#X\leq\#\mathbb R$, and for this particular result there is no reliance on the CH.
Here is a somewhat involved proof (Lemma 2) that every uncountable Polish space (that is, separable and complete metric space) has cardinality of at least that of $\#\mathbb R$; this proof does exploit completeness. Hence, it is possible to give a complete solution to Joaquin's question without relying on the CH.


text:
Q: Cauchy Euler Equation How do I find the particular integral of
$$(x^2D^2+xD-1)y=x^2 e^{2x}$$
where $D=\frac{d}{dx}$? I have tried using the substitution $x=e^z$, but I got stuck.

A: You should have first tried the direct Euler-Cauchy approach by computing the characteristic polynomial $0=m(m-1)+m-1=m^2-1$ giving $x,x^{-1}$ as basis solutions. The right side is not of the form $x^r\ln(x)^p$ or a sum of such terms, so that the method of undetermined coefficients does not work.
Use the variation-of-constant method
\begin{align}
y_p(z)&=xv(x)+x^{-1}w(x),\\
0&=xv'(x)+x^{-1}w'(x)\\
y_p'(x)=v(x)-x^{-2}w(x)
x^2e^{2x}=x(xy_p'(x))'-y_p(x)&=x^2v'(x)-w'(x)
\end{align}
so that one coefficient integration is readily solvable
$$
v'(x)=\frac12e^{2x}\implies v(x)=\frac14e^{2x}+C
$$
while the more complicated reads as
\begin{align}
w'(x)=-\frac12x^2e^{2x}\implies
w(x)=-\frac12\int x^2e^{2x}dx
&=-\frac14x^2e^{2x}+\frac12\int xe^{2x}dx
\\
&=-\frac14x^2e^{2x}+\frac14xe^{2x}-\frac18e^{2x}+D
\end{align}
Combined this results in
\begin{align}
y_p(x)&=\frac14e^{2x}-\frac18x^{-1}e^{2x}\\
&\color{blue}{\text{test: }\begin{aligned}[t]
xy_p'(x)&=\frac12xe^{2x}+\frac18x^{-1}e^{2x}-\frac14e^{2x}\\
x(xy_p'(x))'&=\frac12xe^{2x}+x^2e^{2x}-\frac18x^{-1}e^{2x}+\frac14e^{2x}-\frac12xe^{2x}
\\
&=x^2e^{2x}+y_p(x)
\end{aligned}}
\end{align}

A: Hint: try $y=\sum\limits_{k=0}^\infty a_nx^{n}$. The coefficient of $x^{n}$ on the left side becomes $(n^{2}-1)a_n$. Equate this to the coefficient of $x^{n}$ on the right side.

A: Render $y=u/x$ where $1/x$ is the homogeneous solution with the lower power of $x$ (using the other solution could complicate the integral you eventually get by forcing unneeded fractions in the integrand).  Terms containing $u$ with no derivative cancel out and then
$x\dfrac{d^2u}{dx^2}-\dfrac{du}{dx}=x^2e^{2x}$
$\color{blue}{\text{When you "vary the coefficient" on a homogeneous solution,}}$
$\color{blue}{\text{adding a constant just adds multiples of the homogeneous solution.}}$
$\color{blue}{\text{So only derivatives of your variable coefficient will have any effect.}}$
Introduce an integrating factor $1/x^2$ which matches the left side with the product rule for derivatives:
$\dfrac{1}{x}\dfrac{d^2u}{dx^2}-\dfrac{1}{x^2}\dfrac{du}{dx}=e^{2x}$
$\dfrac{d}{dx}(\dfrac{1}{x}\dfrac{du}{dx})=e^{2x}$
$\color{blue}{\text{The ratio of homogeneous solutions is }x^{-1}/x=x^{-2}.}$
$\color{blue}{\text{That will become the coefficient of the first derivative in the exact differential.}}$
$\color{blue}{\text{We choose our integrating factor accordingly.}}$
Integrating (and leaving out constants since only a particular solution is needed):
$\dfrac{du}{dx}=\dfrac{xe^{2x}}{2}$
$u=\dfrac{(x-2)e^{2x}}{4}$ with integration by parts
Back substituting:
$\color{blue}{y=\dfrac{(x-2)e^{2x}}{4x}}$


text:
Q: Не создаётся директория на андроид При попытке создать директорию
filePath.getParentFile().mkdirs();

возвращает False.
Разрешения в Manifest даны
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

При нажатии на кнопку динамически проверяется присутствие разрешения.
Собственно сам код:
case R.id.buttonCreateWaybill:
                if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        == PackageManager.PERMISSION_GRANTED) && (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED)) {
                HSSFWorkbook workbook = new HSSFWorkbook();
                HSSFSheet sheet = workbook.createSheet();
                HSSFRow row = sheet.createRow(0);
                HSSFCell cell = row.createCell(0);
                cell.setCellValue("test");
                File filePath = new File(Environment.getExternalStorageDirectory() + File.separator + "Waybills", "demo.xls");
                try {
                    if (!filePath.getParentFile().exists()) {
                        filePath.getParentFile().mkdirs();
                    }
                    if (!filePath.exists()) {
                        filePath.createNewFile();
                    }
                    FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                    workbook.write(fileOutputStream);
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                }
                break;


text:
Q: Bug on fixed sidebar with smooth scrolling I have a fixed sidebar with a smooth scrolling in the content div, I have 4 links in this sidebar and each link points to a section with an anchor, when the link is clicked its state changes and take the class "current". the problem that if I go from the fourth link to the third link, the state of the second link changes.

    let mainNavLinks = document.querySelectorAll("a.link-timeline");
    let mainSections = document.querySelectorAll("div.bloc-decennie");

    let lastId;
    let cur = [];

    // passe to the observer
    const options = {
      root: document.getElementById('#all-story'), // The scroll area
      rootMargin: '0% 0% -80% 0%',
      threshold: 0
    }

    // The observer
    const observer = new IntersectionObserver((entries, observer) => {

      // Entries are all the items observed which have entered to the scroll area
      entries.forEach(entry => {
        // We only want the ones intersecting wuth our threshold
        if (entry.isIntersecting) {
          // map to the link
          let link = document.querySelector('[href="#'+entry.target.id+'"]');
          if (link) {
            // Remove current class from all links
            mainNavLinks.forEach(item => {
              item.classList.remove("current");
            });
            // Add current to new target
            link.classList.add("current");
          }
        }
      })
    }, options);

  // foreach section we send to the observer
  mainSections.forEach(target => {
    observer.observe(target);
  });
html {
  scroll-behavior: smooth;
}

li a.current {
  letter-spacing: -.5px;
  font-size: 3.2rem;
  line-height: 3.8rem;
  font-weight: 500;
}

.bloc-decennie {
  min-height: 600px;
}

@media (min-height: 300px) {
  #sidebar-story {
position: fixed;
top: 0;
  }
}

     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

1977-1987

1988-1998

1999-2009

2010-2019

          11111
Cum asperiores temporibus itaque consequatur quod inventore, quia quis explicabo dicta esse minus voluptatem reiciendis eveniet animi, necessitatibus illum dolorem doloremque repellat placeat, dolores eaque.

          2222
Cum asperiores temporibus itaque consequatur quod inventore, quia quis explicabo dicta esse minus voluptatem reiciendis eveniet animi, necessitatibus illum dolorem doloremque repellat placeat, dolores eaque.

          33333
Cum asperiores temporibus itaque consequatur quod inventore, quia quis explicabo dicta esse minus voluptatem reiciendis eveniet animi, necessitatibus illum dolorem doloremque repellat placeat, dolores eaque.

          44444
Cum asperiores temporibus itaque consequatur quod inventore, quia quis explicabo dicta esse minus voluptatem reiciendis eveniet animi, necessitatibus illum dolorem doloremque repellat placeat, dolores eaque.

A: .bloc-decennie {
  min-height: 600px;
  margin-top: 1px;
}


text:
Q: IntelliJ refusing to add custom component my problem is as follows: Assume that we have the following file:
package p;
import javax.swing.*;
public class test extends JPanel {
  test(){
    super(true);
  }
}

I save the file and compile it. Now, in IntelliJ, I open a form and try to add test to it. It won't work! I click 'Non-Palette Component', click on my form and in the dialog that open up, I type p.test as my class name (IntelliJ even offers name completion here) and check 'create binding automatically'. After I click ok, nothing happens. But - if I take 'javax.swing.JButton' for the class name, it works. It's ridiculous. I don't see what I am doing wrong? Does test have to implement or override a certain function? Do I have to modify a path? Or should I just kick my PC out of my window?

A:
java.lang.UnsupportedClassVersionError: Test : Unsupported major.minor version 51.0

The problem is that you have the project language level set to 1.7 and using JDK 1.7 to build it. IntelliJ IDEA is running under JDK 1.6 on your system and cannot load the custom component class that was compiled with the 1.7 language level.
Possible solutions to this problem:

*

*change project/module JDK to 1.6

*in IDEA 12 it's possible to configure bytecode version per module, set it to 1.6

*in Additional command line parameters field specify the following options: -source 1.6 -target 1.6

*run IDEA under JDK 1.7 (applies to Windows and Linux, not recommended on Mac)

A: Are you running the latest version of IntelliJ IDEA? The action you describe works for me in 11.1.5 and 12.0.2 (the latest versions for IDEA 11 and 12). There might be a bug in an earlier version. Also, since test is a 'JPanel', are you selecting the "Is Container" option on the "Add Non=Palette Component". For the simple example you show, without this option selected, I do not get anything visible in the GUI designer when it is not selected in the "UI Designer" tool window. But you mentioned you do not even see it in the controls-hierarchy.
If you are at the latest version, I recommend you check the log (Help > Reveal Log) to see if there is an error in there that might shed some light on the issue.
Lastly, you can try invalidating the caches and restarting. (File > Invalidate Caches). It's possible there is some corruption that is causing an issue.
I would have added this as a comment to your question, but I do not have enough reputation points to do such.

A: Make sure you compile the custom component and then click on Reload Custom Components button on the toolbar. That solved the issue for me.


text:
Q: Create folders based on file-content I have txt file like this:
f1 3
f2 4
f3 2

I have to create folder (directory) in bash with name f1, and with 3 subfolders with random names, then folder with name f2, and with 4 subfolders with random names, etc.
I made the following attempt, but it is creating me only folders, without subfolders.
#!/bin/bash

dir=/home/bae/Desktop/egzamin/5
filename=$dir/nazwy.txt

cut -d " " -f 1 $fi

A: while read dir count
do
    # some sanity checks
    [[ $dir = "" || $count = "" ]] && continue
    ((count<0)) && continue

    mkdir -p "$dir" # only needed for count==0
    for (( i=0; i<count; i++ ))
    do
        mkdir -p "$dir/$RANDOM-$i"
    done
done < TEXTFILE

A: <txt xargs -l sh -c 'mkdir "$1"; cd "$1"; mkdir $(seq "$2" | xargs -l sh -c "echo \$RANDOM")' --

*

*<txt - input the content from the file named txt onto standard input of the command

*xargs -l - run the command for each line passing the line as the arguments to the command

*mkdir "$1" - creates a directory and cd's into it from the first column of the file

*seq "$2" - outputs sequentially increasing numbers from 1 to the number in the second column passed as the second argument

*xargs -l sh -c "echo \$RANDOM" - just a shortcut for outputting a random number for each line of the input.

*cd "$1"; mkdir $(....) - creates the files inside the folder

A: What you are after is something like this:
while read -r dirname count; do
   mkdir -p "$dirname"
   for (( i=0; i < $count; ++i)); do mktemp -d -p "$dirname"; done
done < textfile

This reads your file lines by line, reading two arguments dirname and count. It will first make the parent directory and then run a loop to create the requested subdirectories using mktemp. Have a look at man mktemp for the various options to manipulate the naming of the subdirectories.
note: if there are possible "empty" lines or wrong entries in your textfile, you might want to incorporate the sanity checks from Wiimm.


text:
Q: Java2D: scaling issues I'm a reasonably experienced Java programmer but relatively new to Java2D. I'm trying to scale an image but I'm getting poor quality results. The image is a preview of a panel so contains things like text and textfields. I'll always be scaling down, never up.
Currently I'm using the following code:-
g.drawImage(panelImage, 0, 0, scaledWidth, scaledHeight, null);

Where panelImage is the full sized preview (BufferedImage) and scaledWidth and scaledHeight are the respective target dimensions. I seem to lose a lot of detail in the text and edges of things like textfields etc.
Is there a better call I should be using to scale the image?
Thanks,
John

A: May be you should call:
 g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

and
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

A: A suggestion I can make is to first resize the image onto a separate BufferedImage. The reason being, a Graphics2D object of the BufferedImage can be obtained in order to produce a better quality scaled image.
Graphics2D can accept "rendering hints" which instruct the way image processing should be performed by the Graphics2D object. The setRenderingHint method is one of the methods which can be used to set those rendering hints. The rendering hints from the RenderingHints class can be used.
Then, using that Graphics2D object, an image can be drawn to the BufferedImage using the rendering hints specified earlier.
A rough (untested) code would work as the following:
BufferedImage scaledImage = new BufferedImage(
    scaledWidth,
    scaledHeight,
    BufferedImage.TYPE_INT_RGB
);

Graphics2D g = scaledImage.createGraphics();
g.setRenderingHints(
    RenderingHints.Key.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BICUBIC
);

g.drawImage(panelImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();

Other rendering hints of interest may include:

*

*KEY_ANTIALIASING

*KEY_RENDERING
The Controlling Rendering Quality section of The Java Tutorials also has more information on how to control the rendering quality of Graphics2D objects.
And for a very good source of information on dealing with graphical interfaces in general, Filthy Rich Clients by Chet Haase and Romain Guy is highly recommended. There is one section of the book that deals with the issue of scaling images, which seems quite relevant.

A: Coobird is right that you need to incrementally down-scale (preferably using BICUBIC) to get a good-looking result for a small enough thumbnail. Image.getScaledInstance used to do this with the AREA_AVERAGED approach, but it is much slower than the incremental downscale that was original proposed by Chris Campbell in his "Perils of Image.getScaledInstance()" article.
Please excuse the self-promotion here, but I rolled a handful of "native Java best practices" when it comes to image scaling into a library called imgscalr.
It's available under an Apache 2 license and source is all on GitHub; the goal of the library was to make image-scaling in native Java dead-easy (1 class, 5 static methods) and ensure the best looking result (which is what you originally wanted), the fastest result (great when scaling among large images) or a balance between the two and let the library decide which one to use.
I just wanted a lib that could "Resize my image and get out of my way" and after reading all these posts for a few days as I addressed the pain point (my own as well) just was circling back and sharing the work for anyone else it may help.

A: Coobird has the correct idea. I would also try RenderingHints.VALUE_INTERPOLATION_BILINEAR interpolation and see if it's nicer looking. Bicubic works better when upscaling, though. For the best results when downscaling, one should downscale in several steps. First halve the resolution, then halve again, etc. until you get near the desired resolution (i.e. you cannot halve or the image will get too small). Final step is to scale down to the desired resolution.
For example, let's say your input image is 800x600 and you want downscale to 160x120:

*

*Downscale 50%. --> 400x300

*Downscale 50%. --> 200x150

*Downscale to 160x120.


text:
Q: get value checkbox in zk i have a grid with list checkbox

<grid id ="actListBox" model="@bind(vm.actions)" >
<template name="model">
<row style=" width:200px !important; ">
    <cell rowspan="5" align="left" >
      <checkbox style="height: 70px; width:1000px; overflow: auto;   margin-left:10px;"
      label="${each.action_name}" id ="${each.actionid}" value ="${each.actionid}"  />
     </cell>
</row>
</template>
</grid>

<checkbox label="Check all" value ="checkall" id="chkAll"/>

and now i want get all value of checkbox but i can't found anyway
please help me
thanks all

A: You can in your composer get checked Ids by iterating over actions:
@Command
public void checkedIds(final Event e){
    final StringBuilder builder = new StringBuilder("Checked Ids: ");
    for (final Action action : actions) {
        if (action.getChecked()) {
            builder.append(action.getId()).append(' ');
        }
    }
    Messagebox.show(builder.toString());
}

I updated the ZK fiddle.


text:
Q: A 228 row results query job writing to table with gives 0 rows when allow large results is True I have a SQL query that, when I write the results to a table without 'allow large results' set, will write 228 rows.
When I set allow large results however, the destination table will contain 0 rows. Both attempts use write disposition WRITE_TRUNCATE.
I see this both using the API and the BigQuery console.
The working no-allow-large-results job:
eagTEiR0wSMK6b5WLSL04vB9RfTUb8bhvEi1YFWjuhfaF_W0zEeLogxUYwOrhGyOheS_CyyaB1dUeafGPdyR592xMcbeEmpJ85_CO29PSbBAnmEBGHJVHWjpH5DvGyVCEjarfJ5XUQ9UmVT_FSHmkcEZktbfln9E_E1jobM65IuQv2sP4_r7eqK60aPaqxD7taEc1bpM2kS6GAtkxqFsUUOv_JXQgTn3ebCodHFKsdquhy3e1mfbu4QhqnoO5QCi
The non-working allow-large-results job:
G40HW4Z5zGTgL1NSCBBy380kY7Gu7WOU7s_zB9F8Kdrtao2gbzRLptWSSi76MC2gHCHPG0srssaGejfCIN4j1upjyh9vQnA3kPmuJcgm5ZgdYd3YwsmGzvcBXiPy9bY0x0GRhJXimHqhKiYbKz7fa3LljOb4kxNvB8wPazqeYj3xAXwbV8G2Sl3L6gmutvvYPalhd1CCtUbLfiw520_I4zKDgn7LYosyFjA0h9TwR8GQ80Scd5n8yKAsIEou7XDG
Query:
SELECT t1.email, MIN(t1.min_created_time), GROUP_CONCAT(t1.id)
FROM (
  SELECT email, MIN(created) as min_created_time, id
  FROM TABLE_QUERY([xxxxx], 'table_id in       ("yyyyyy_201601", "yyyyyy_201602",     "yyyyyy _201603", "yyyyyy_201604")')
WHERE created >= "2016-01-11 00:00:00" AND created < "2016-04-01    00:00:00" AND id != "null" AND name LIKE "%trike%"
  GROUP BY email, id
   ) t1

GROUP EACH BY t1.email
IGNORE CASE

Also note, a simpler SQL works for both cases such as:
select email from xxxx group by email limit 100

A: This looks like a problem due to IGNORE CASE. The fix is underway, but in the meantime could you wrap string comparisons with LOWER() calls, i.e.
LOWER(id) != "null"
LOWER(name) LIKE "%trike%"

etc.


text:
Q: Is the transformation $T: (r, \theta) \to (r, \theta + \phi)$ linear? Here $\phi$ is a given angle Let $T$ rotate every point through the same angle $\phi$ about the origin, $i.e.$ $T: (r, \theta) \to (r, \theta + \phi)$ where $\phi$ is given. If in addition that $T(O) = O,$ namely, if $T$ maps the zero element to itself, must $T$ be linear?
I think not so; for $T(ar + b\psi_{1}, a\theta + b\psi_{2}) = (ar + b\psi_{1}, a\theta + b\psi_{2} + \phi) = a(r, \theta) + b(\psi_{1}, \psi_{2}) + (0, \phi).$
Is this true?

A: The issue with your work is that
$$
(ar+b\psi_1,a\theta+b\psi_2+\phi)\neq a(r,\theta)+b(\psi_1,\psi_2)+(0,\phi).
$$
The second vector doesn't have the proper form of $(\text{radius},\text{angle})$.  In general, adding polar coordinates isn't easy without converting to rectangular coordinates first.
You need to answer two questions.  If you rotate a vector and then increase its magnitude, is that the same as increasing its magnitude and then rotating it?  And, if you add two vectors and then rotate, is that the same as rotating those vectors and then adding them?
It is probably best to consider rectangular coordinates, and find a matrix that represents rotation by $\theta$.  If you can find such a matrix, then the transformation will be linear.


text:
Q: AWS API Gateway in China We are planning to launch an app that will be available globally, including China and we plan to use AWS for this.
However, because of the "Great Firewall of China" we may run into problems:

*

*The app may not be permitted to connect to an API endpoint outside
China.

*If we host in AWS Beijing, the latency would be bad for the
rest of the world.

So basically, my questions are:

*

*Is it possible to setup an AWS API Gateway in Beijing that connects to a backend server in AWS outside China?

*What are the common solutions to addressing this concern?

*Are there any non-AWS solutions to this problem?

A: It really depends on your app. In short you can say, that if the chinese government doesn't like your app, there isn't too much you can do. AWS traffic flows through the firewall as well.
You can try to see China as a seperate deployment with it's own data backend. this way even when the Chinese governments decides, that your app allows unwanted things to enter the country, the functionality inside China might still stay up.
If you really want your app to work in China you probably have to make your app compliant. You will probably not have any kind of success by trying to circemvent the rules. The rules (in Chinese) can be found here: http://www.cac.gov.cn/2016-06/28/c_1119123114.htm


text:
Q: Fetch a file from task in same Ansible playbook How do I transfer a file I have created from a previous task in my Ansible playbook? Here is what I got so far:
- name: Create Yum Report
  shell: |
     cd /tmp
     yum history info > $(hostname -s)_$(date "+%d-%m-%Y").txt
  register: after_pir

- name: Transfer PIR
  fetch:
     src: /tmp/{{ after_pir }}
     dest: /tmp/

However, I receive this error message when I run my playbook.
TASK [Transfer PIR] ************************************************************************************************************
failed: [x.x.x.x] (item=after_pir) => {"ansible_loop_var": "item", "changed": false, "item": "after_pir", "msg": "the remote file does not exist, not transferring, ignored"}

I have tried to run different fetch, synchronzie and pull methods but I'm not sure what the issue is.

A: One way to do that:
    - name: Create Yum Report
      command: yum history info
      register: yum_report

    - name: Dump report on local disk for each host
      copy:
         content: "{{ yum_report.stdout }}"
         dest: "/tmp/{{ inventory_hostname_short }}-{{ '%d-%m-%Y' | strftime }}"
      delegate_to: localhost


text:
Q: Adding text to a JPG image in ASP.net C# and save to file on server I'm using the following code (credit to Dolph Larson) to take a pre-made image file in bitmap format on an ASP.net server, draw a string on it and save it to file on the server.  In the original code, he dumps the bitmap to the OutputStream, but I'd like to dump it instead to a file.
The version of code below successfully creates the new file, but when I open it, the string does not appear drawn on the image in the new file.  I imagine I am missing a step -- when I use bitMapImage.Save("bitmaptest.jpg", ImageFormat.Jpeg) am I just re-saving the original instead of the modified version?
Here is the code:
        //Load the Image to be written on.
        Bitmap bitMapImage = new
        System.Drawing.Bitmap(Server.MapPath("generic.jpg"));
        Graphics graphicImage = Graphics.FromImage(bitMapImage);
        graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
        graphicImage.DrawString("testing 1 2 3",
        new Font("Arial", 20, FontStyle.Bold),
        SystemBrushes.WindowText, new Point(0, 0));
        Response.ContentType = "image/jpeg";
        bitMapImage.Save("bitmaptest.jpg", ImageFormat.Jpeg);
        graphicImage.Dispose();
        bitMapImage.Dispose();

Thanks in advance!

A: Your code works just fine; You simply need to specify the path where you want to save the image:
Example:
//Load the Image to be written on.
        Bitmap bitMapImage = new
        System.Drawing.Bitmap((@"c:\\foo\\generic.jpg"));
        Graphics graphicImage = Graphics.FromImage(bitMapImage);
        graphicImage.DrawString("testing 1 2 3",
        new Font("Arial", 20, FontStyle.Bold),
        SystemBrushes.WindowText, new Point(0, 0));
        bitMapImage.Save("c:\\foo\\bitmaptest.jpg", ImageFormat.Jpeg);
        graphicImage.Dispose();
        bitMapImage.Dispose();

Note In your case, bitMapImage.Save needs to be as follows: bitMapImage.Save(Server.MapPath("~/Images")+"newImage.jpg",ImageFormat.Jpeg); since you are attempting to save the image on an asp.net app. ~/Images in my example is just the virtual directory Images inside your app.

A: Yes ..You are saving the same image .You have to create a ne wbitmap and save it:-
Bitmap bitMapNew = Bitmap.FromHbitmap(graphicImage.GetHdc());
bitMapNew.Save("bitmaptest.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

Add these lines instead of your bitMapImage.save


text:
Q: ASP.NET MVC 3 and HttpContext.Current.User.Identity.Name I'm using the .net membership in an MVC 3 (razor) application.
I've implemented a custom profile class where I use HttpContext.Current.User.Identity.Name to get the membership user.
public class UserProfile : ProfileBase
{
    static public UserProfile CurrentUser
    {
        get {
               return (UserProfile)(ProfileBase.Create(Membership.GetUser(new Guid(HttpContext.Current.User.Identity.Name)).UserName));
            }
    }

    public string FirstName
    {
        get { return ((string)(base["FirstName"])); }
        set { base["FirstName"] = value; Save(); }
    }

    public string LastName
    {
        get { return ((string)(base["LastName"])); }
        set { base["LastName"] = value; Save(); }
    }
}

As you can see in the above class, I have to cast HttpContext.Current.User.Identity.Name as a GUID to get the membership user.
The question is, why after the login validation, in the HttpContext.Current.User.Identity.Name I get the GUID value (userID) and not the username?
Is that normal?

A: Just use Membership.GetUser() to get the current user.

A: If you are using default .NET membership, (FormAuthentication with default GenericPrincipal, FormsIdentity) and you have created your MVC application from the default 'Internet Application' template, then:
Check your 'LogOn' Action method of the AccountController. One possible cause of altering the userName to the UserId(GUID) value is to set the Auth-cookie to 'ProviderUserKey' as userName, like:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            var user = Membership.GetUser(model.UserName);
            FormsAuthentication.SetAuthCookie(user.ProviderUserKey.ToString(), model.RememberMe);

            //...
            return Redirect(Url.Content("~/"));
        }
        else{
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}


text:
Q: How to scrape fetch data from multiple pages and display in one page using Puppeteer and Cheerio? I try to scrape data from two different webpage and display/compare in my own page. It works fine for display data from one website, and crashed when I add another URL.(well, still display the information get from 1st website but keep blank for 2nd one)
so how to write the code to get data from multiple websites?
here is code
//modules for express, path, ejs, puppeteer, cheerio

//steup const
const express = require('express');
const app = express();
const puppeteer = require('puppeteer');
const cheerio = require('cheerio');
const path = require('path')

let browser;
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//async getData
async function getData(url, page){
    try{
       await page.goto(url, {waitUnitl : 'load', timeout : 0})
       const html = await page.evaluate( () => document.body.innerHTML);
       const $ = cheerio.load(html);
       let text1 = $("#feature-bullets > ul > li:nth-child(6) > span").text();
       let text2 = $("#feature-bullets > ul > li:nth-child(8) > span").text();
       let text3 = $("#feature-bullets > ul > li:nth-child(10) > span").text();
       let text4 = $("#feature-bullets > ul > li:nth-child(9) > span").text();
       let img = $("#landingImage").attr("src");
       let aprice = $("#priceblock_dealprice").text();
       let aunit = $("#variation_style_name > div > span > span.a-truncate-cut > span").text();
       let ashipping = $("#deliveryMessageMirId > b").text();
       let awarranty = $("#creturns-policy-anchor-text").text();
       let eprice = $("#a-autoid-10-announce > span.a-color-base > span").text();
       return{text1, text2, text3, text4, aprice, aunit, ashipping, awarranty, img, eprice}
    }
    catch(error){
      console.log(error);
    }
}

//routes
app.get('/results', async function(req, res){
    browser = await puppeteer.launch({headless : true})
    const page = await browser.newPage();
    //calling the getData function and sending URL and the page
    let data = await getData('https://www.amazon.com/TP-Link-Deco-Whole-Home-System/dp/B06WVCB862/ref=sr_1_3?dchild=1&keywords=mesh+wifi+system&qid=1606836634&sr=8-3', page, 'https://www.amazon.com/gp/product/1616770813/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1', page );
    res.render('results', {data : data});
})

//server
app.listen(3000, ()=>{
    console.log('server running');
})
----

Hope I am asking in right way, this is very first question I asked here. I'm just start learning node.js so haven't got much knowledge yet. Many Thanks

A: You need to change the calling of getData function, you cannot pass 4 parameters when it only accepts 2 at a time.
So, you can solve this by separating out the calls to the two pages like this:
let data1 = await getData('https://www.amazon.com/TP-Link-Deco-Whole-Home-System/dp/B06WVCB862/ref=sr_1_3?dchild=1&keywords=mesh+wifi+system&qid=1606836634&sr=8-3', page);
let data2 = await getData('https://www.amazon.com/gp/product/1616770813/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1', page );
let data = [data1, data2]
res.render('results', {data})


text:
Q: Stacking decorators in Python So...
This works
def makeBold(fn):
    def wrapped():
        return ''+fn()+''
    return wrapped
@makeBold
def sayhello():
    return 'Ey yo wassup'

and produces an expected Ey yo wassup
However, this does not work
def makeBold(fn):
    def wrapped():
        return ''+fn()+''
    return wrapped

def makeItalic(fn):
    def wrapped():
        return ''+fn()+''

@makeItalic
@makeBold
def sayhello():
    return 'Ey yo wassup'

Which all produces this nice NoneType error...
I thought it would produce something like Ey yo wassup
Thoughts?

A: def makeBold(fn):
    def wrapped():
        return ''+fn()+''
    return wrapped

def makeItalic(fn):
    def wrapped():
        return ''+fn()+''
    return wrapped

@makeItalic
@makeBold
def sayhello():
    return 'Ey yo wassup'


text:
Q: ionic 3 bind ID to  is it possible to bind an ID to a ion-textarea ?
Like:
<ion-textarea placeholder="Enter your thoughts" id="thoughtsBox"></ion-textarea>

Thanks a lot

A: Of course you can do it. The way u have used it is correct.


text:
Q: how to block nodejs for result of query I am pretty new to nodejs.
What I want my code to do it to query a database a number of times, collect data from all the queries in one variable and then use it somewhere.
But I guess nodejs instead of waiting for the result of the queries, execute without blocking.
This is what I think is happening. Sorry if I am wrong.
for (var i = step_min; i < (step_max); i += step) {
    query = 'select count(' + colName + ') as num_count from ' +
        rows[0].tablename + ' where ' + 'dictionaryid=' +
        rows[0].dictionaryid + ' and ' + colName + ' between ' + i +
        ' and ' + (i + step);

    connection.query(query, function(err, rows1, fields) {
        if (err) {
            console.log(err);
            throw err;
        }

        try {
            console.log("$$$$$$$$$$$$$$$ pushed : "+ rows1[0].num_count);
            contents.push(rows1[0].num_count);
            console.log('contents : '+ contents+'\n');

        } catch (e) {
            if (e instanceof SyntaxError) {
                console.log("Syntax Error for input function");
            }
        }

    });

    console.log("##################### " + query + "\n");

    console.log('contents : '+ contents+'\n');
}

Any advice either on how to block nodejs till the result from query is obtained or otherwise a way to restructure my code ?
Thanks in advance.

A: You are correct that it is not waiting for your queries before executing. You can look at the node-mysql-queues module which you can use to queue queries, and execute the given callback after all have executed (it will also allow you do perform transactions)
Another (hack) approach is to set a counter of the number of queries you are executing. In the callback of each transaction save the result into your return object and decrement the counter. If it is <= 0 then all your queries have completed, and you can execute your main callback with the return object.
Also, watch out for SQL injection.

A: try this:
https://github.com/luciotato/waitfor
your code with wait.for:
for (var i = step_min; i < (step_max); i += step) {
    query = 'select count(' + colName + ') as num_count from ' +
        rows[0].tablename + ' where ' + 'dictionaryid=' +
        rows[0].dictionaryid + ' and ' + colName + ' between ' + i +
        ' and ' + (i + step);

    var rows1 = wait.forMethod(connection,"query",query); //waits until callback
    console.log("$$$$$$$$$$$$$$$ pushed : "+ rows1[0].num_count);
    contents.push(rows1[0].num_count);
}
console.log("##################### " + query + "\n");
console.log('contents : '+ contents+'\n');

} catch (e) {
            if (e instanceof SyntaxError) {
                console.log("Syntax Error for input function");
            }
            ....
        }

A: Doing something like below could be a work around.
//Its just a test code whatever came to mind first so I'll tune it later...
        var contents = [];

        var lock = 0;

        for (var i = step_min; i < (step_max + step); i += step) {
            lock++;
        }

        for (var i = step_min; i < (step_max + step); i += step) {
            query = 'select count(' + colName + ') as num_count from ' + rows[0].tablename + ' where ' + 'dictionaryid=' + rows[0].dictionaryid + ' and ' + colName + ' between ' + i + ' and ' + (i + step);

            connection.query(query, function(err, rows1, fields) {
                if (err) {
                    console.log(err);
                    throw err;
                }

                try {
                    console.log("$$$$$$$$$$$$$$$ pushed : " + rows1[0].num_count);
                    contents.push(rows1[0].num_count);
                    console.log('contents : ' + contents + '\n');

                } catch (e) {
                    if (e instanceof SyntaxError) {
                        console.log("Syntax Error for input function");
                    }
                }

                lock--;

                if (lock == 0) {
                    queryDone();
                }

            });

        }

        function queryDone() {

            console.log("##################### " + query + "\n");

            console.log('contents : ' + contents + '\n');

            var id = obj.exptID + '.' + obj.exptITR + '.' + obj.nodeID + '.' + obj.resourceName + '.' + colName;
            serie = {
                name: colName,
                data: contents,
                id: id
            };

            console.log("--------------------\n " + step_max + "\n" + step_min + "\n------------------------\n");
        }

The approach is to fire a function when all queries are done as Nick said...


text:
Q: Linking to an ID does not work I have an image that, when clicked I'd like to take the user to the top of the page (it's a "back to top" link.)
I have linked the image using an ID to my 'navigation' div using the code below, as I have been told is the correct way to do so, but it does nothing.
Live site
HTML

     stuff in here

and

This doesn't seem to do anything though, I thought the name attribute was deprecated and thus id's should be used instead but this doesn't do anything?

A: Since your #navigation element is positioned with position: fixed it is always on screen. You need to link to an element that will stay at the top of the document.
You could add in another element, or add an id to the body. Alternatively, change the position of the navigation so it stays in flow. Or, you could use JavaScript to animate a scroll to the top (e.g. with jQuery .animate and the scrollTop property).

A: Put this:

right after/before your navigation div.
Then, change

to

P.S.: After looking at page-source, I'd suggest you put it just after the  tag.

A: you have linked it to something which stays already on the screen(Fixed positioned). link it something which is not fixed positioned .

A: Just to throw this out there for people coming along reading this... Linking to an A NAME is deprecated and not a best practice... Linking to an ID is the best way to go in the long run.
http://www.w3.org/TR/html4/struct/links.html


text:
Q: How, depending on the settings in the property file, force service to use a particular repository? I set VM options to -Dmyapp.conf=config/my.properties. I need to use this file content to select which repository to use. I use SpringBoot.
There is service, now it gives Could not autowire. There is more than one bean of 'MyRepository' type:
@Service
public class MyServiceImpl implements MyService {

    @Autowired
    private MyRepository repository;
...}

Repositories:
public interface MyRepository  {...}

@Repository
public class MyRepositoryImpl01 implements MyRepository  {...}

@Repository
public class MyRepositoryImpl02 implements MyRepository  {...}

A: You can use Spring profiles for that purpose.
@Profile("profile1")
@Repository
public class MyRepositoryImpl01 implements MyRepository  {...}

@Profile("profile2")
@Repository
public class MyRepositoryImpl02 implements MyRepository  {...}

Then in the property file you need: spring.profiles.active=profile1 or spring.profiles.active=profile2.

A: I would actually consider having this logic in some Java Config (a class annotated with @Configurtation) than in both (or possibly N) repositories.
You could use @ConditionalOnProperty and in this Java Config you would encapsulate entire logic of this "repository selection". This would be a benefit since you would only have 1 bean of the specified type, which in turn could be useful if your repositories connect to databases that are not available for certain configuration options.


text:
Q: Pagination not working correctly with Twig I'm using Twig inside WordPress within the Timber plugin and I have basically followed the layout they have used for pagination here.
It displays fine and everything, but it appears the arguments aren't working correctly for this bit:
{% include 'partials/pagination.twig' with { pagination: posts.pagination({show_all: false, mid_size: 2, end_size: 1}) } %}

No matter what I set those arguments to it outputs every page; so if I have 10 pages it will print out all 10 page numbers; I don't want this, I'm trying to restrict it to 5.
What is wrong here?

A: You don't need to use the default pagination template, you can go full custom
{% set pages_to_show = 5 %}
{% set current = posts.pagination.current %}
{% set max = current + (pages_to_show - 1) %}
{% if max > posts.pagination.total %}
    {% set current = posts.pagination.total - (pages_to_show - 1)  %}
    {% set max = posts.pagination.total %}
{% endif %}

    {% if posts.pagination.prev %}
        Prev
    {% endif %}

        {% for i in current..max %}

                {% if posts.pagination.pages[i].link %}
                    {{posts.pagination.pages[i].title}}
                {% else %}
                    {{posts.pagination.pages[i].title}}
                {% endif %}

        {% endfor %}
        {% if posts.pagination.next %}
            Next
        {% endif %}

lightweight demo

do not this is just a small example of how you could solve this


text:
Q: Field equals regular expression In my excel file, I'd like field A2 to equals regular expression match of field A1. The regular expression is as follows: ^NATURE-[0-9]+ .
Intuitively, the formula for A2 would be:
=RegEx(A1,"^NATURE-[0-9]+")
Except there's no Regex function. How to do that?


text:
Q: Scroll if any alphanumeric character or symbol is pressed I am writing a JS code that scrolls a container is any alphanumeric character or symbol is pressed.
This is what I came up with:
var $q = $('input#q');
$q.on('keydown', function (e) {
    var reMatch = /[!-~]/.exec(e.which);
    if (typeof reMatch != 'null' && reMatch.length > 0) {
        $('#container').animate({scrollTop: 410}, 500);
        $(this).off('keydown');
    }
}).focus();

But this executes for all keys like shift, tab, enter etc ...
What's wrong with the code?

A: e.which gives a numeric representation of the key pressed. The number keys are represented by 48-57 (or 96-105 on the keypad) while letters are represented by 65-90
Try this:
var $q = $('input#q');
$q.on('keydown', function (e) {
    var val = e.which;
    var num = (val > 47 && val < 58 || val > 95 && val < 106);
    var letter = (val > 64 && val < 91);
    if (num || letter) {
        $('#container').animate({scrollTop: 410}, 500);
        $(this).off('keydown');
    }
}).focus();

You could do this for it to work with anything that creates an input in the text field:
var $q = $('input#q');
$q.on('input', function (e) {
    $('#container').animate({
        scrollTop: 410
    }, 500);
    $(this).off('input');
}).focus();

but this will not work for IE versions less than 9. Although if you look, you can find shims. Here is an example

You could do this, but it would not scroll immediately if the user is holding a key down for a long time (until the user releases the key).
var $q = $('input#q');
var qval = $q.val()
$q.on('keyup', function (e) {
    if(qval != $q.val()) {
        $('#container').animate({scrollTop: 410}, 500);
        $(this).off('keyup');
    }
}).focus();


text:
Q: How to use having clause on relationship with sequelize node I have 2 models, business and documents in a 1:n relationship, i want to filter the business in two ways,

*

*business that has documents where every document.due_balance is greater than 0

*business that has documents where every document.due_balance is equals to 0

I want to make something like this
select
    A.name, B.due_balance, sum(B.due_balance) as total_due_balance
from
    business A
inner join documents B ON A.id = B.business_id
group by A.id
having total_due_balance > 0;

select
    A.name, B.due_balance, sum(B.due_balance) as total_due_balance
from
    business A
inner join documents B ON A.id = B.business_id
group by A.id
having total_due_balance = 0;

these will get me what i want, the problem, is that the previus code was made with sequelize ORM, and i can't change it, something like this
const businesses = await db.business.paginate({
    attributes: [
    ...
    ],
    where: {
    ... //bunch of where
    },
    page: parseInt(params.page, 10) || 1,
    paginate: parseInt(params.limit, 10) || 10,
});
here is where the problem begins, i don't know how to join the tables and use the having to filter it, i have tried addind this
let toInclude;
if (params.contactability === 'with_balance') {
    toInclude = {
        include : [
            {
                attributes: [
                    [db.Sequelize.fn('sum', db.Sequelize.col('due_balance')), 'total_due_balance'],
                ],
                model: db.document,
                as: 'documents',
                having: db.Sequelize.where(db.Sequelize.fn('sum', db.Sequelize.col('due_balance')), {
                    $gt: 0,
                }),
            },
        ],
    };
} else if(params.contactability === 'without_balance') {
    toInclude = {
        include : [
            {
                attributes: [
                    [db.Sequelize.fn('sum', db.Sequelize.col('due_balance')), 'total_due_balance'],
                ],
                model: db.document,
                as: 'documents',
                having: db.Sequelize.where(db.Sequelize.fn('sum', db.Sequelize.col('due_balance')), {
                    $eq: 0,
                }),
            },
        ],
    };
} else {
    toInclude = {};
}
const businesses = await db.business.paginate({
    attributes: [
    ...
    ],
    where: {
    ...
    },
    ...toInclude,
    page: parseInt(params.page, 10) || 1,
    paginate: parseInt(params.limit, 10) || 10,
});

but that does not work at all, how can i solve this problem?

A: *

*I don't think HAVING will work without GROUP.

*I would move the having clause outside the include section and use the AS aliases.
So, roughly:
group: ['id'],  // and whatever else you need
 having : { 'documents.total_balance_due' : {$eq : 0 }}

(Making some guesses vis the aliases)

A:
To filter the date from joined table which uses groupby as well, you can make use of HAVING Property, which is accepted by Sequelize.

So with respect to your question, I am providing the answer.
You can make use of this code:
const Sequelize = require('sequelize');

let searchQuery = {
    attributes: {
        // include everything from business table and total_due_balance as well
        include: [[Sequelize.fn('SUM', Sequelize.col('documents.due_balance')), 'total_due_balance']]
    },
    include: [
        {
            model: Documents, // table, which you require from your defined model
            as: 'documents', // alias through which it is defined to join in hasMany or belongsTo Associations
            required: true, // make inner join
            attributes: [] // select nothing from Documents table, if you want to select you can pass column name as a string to array
        }
    ],
    group: ['business.id'], // Business is a table
    having: ''
};

if (params.contactability === 'with_balance') {
    searchQuery.having = Sequelize.literal(`total_due_balance > 0`);
} else if (params.contactability === 'without_balance') {
    searchQuery.having = Sequelize.literal(`total_due_balance = 0`);
}

Business // table, which you require from your defined model
    .findAll(searchQuery)
    .then(result => {
        console.log(result);
    })
    .catch(err => {
        console.log(err);
    });

Note : Change model name or attributes according to your requirement.
Hope this will help you or somebody else!


text:
Q: Doctrine findBy() Can't Find A Row In A Table I'm attempting to use Doctrine as the 'model' of an MVC framework app I wrote.
I have a situation where I want to store a 'free space' record for every 'rack' record. I want to be able to get the freespace record from the rack_id.
Here's my table.
create table if not exists freespace (
    id int(11) unsigned not null auto_increment,
    rack_id int(11) unsigned not null,
    -- other fields
    primary key (id),
    unique key (rack_id)
);

I whipped up some Doctrine classes...
BaseFreespace.php
abstract class BaseFreespace extends Doctrine_Record {
    public function setTableDefinition()
    {
        $this->setTableName('freespace');
        $this->hasColumn('id', 'integer', 11, array(
            'type' => 'integer',
            'length' => 11,
            'fixed' => false,
            'unsigned' => true,
            'primary' => true,
            'autoincrement' => true,
        ));
        $this->hasColumn('rack_id', 'integer', 11, array(
           'type' => 'integer',
           'length' => 11,
           'fixed' => false,
           'unsigned' => true,
           'primary' => false,
           'notnull' => true,
           'notblank' => true,
           'autoincrement' => false,
        ));
        // other fields
    }
}

Freespace.php
class Freespace extends BaseFreespace {
    public function findByRackId($rack_id = 0) {
        //die(var_dump($rack_id));
        $res = $this->getTable()->findBy('rack_id', $rack_id);
        die(var_dump($res));
    }
}

From client code, if I say:
$freespace = new Freespace();
$rackFreeSpace = $freespace->findByRackId($rack_id);

... then it hangs until Apache resets the connection. If I comment out the die(var_dump($rack_id)) it dies there right away.
I tried:
$res = $this->getTable()->findBy(array('rack_id', $rack_id));

Saw that online in their docs - but Doctrine doesn't want the args like that - musta been the wrong docs version.
I tried:
$q = Doctrine_Query::create()
    ->from('Freespace')
    ->where('rack_id = ?', $rack_id);
$result = $q->fetchOne();

But this hangs, too.
I'm losing my mind. What am I doing wrong?


text:
Q: add and implement a custom validator to JSF dynamic form I am building my JSF form dynamically using the javax.faces.component like:
...
} else if ((formFields.get(i).getFieldType().equals("Numeric"))) {
    HtmlInputText input = (HtmlInputText)application.createComponent(HtmlInputText.COMPONENT_TYPE);
    input.setId("G000"+i);
    input.setValueExpression("value", FacesContext.getCurrentInstance().getApplication().getExpressionFactory().createValueExpression(FacesContext.getCurrentInstance().getELContext(), "#{reviewReportBean.cRReviewerFormDataList["+i+"].fieldData}" , String.class));
    input.setDisabled(checkTaskStatus(taskId));
    //input.addValidator(numericValidator);
    dynamicPanelGrid.getChildren().add(input);
...

I would like to add & implement a numeric validator to inputText field dynamically. i have no idea how to implement?
For example if i try to validate using a regular expression, how can i add the relevant component (e.g. In a static form represented with f:validateRegex pattern="") dynamically? Is there any relevant interface?

A: for best use and i have also implemented validation through JAVA SCRIPT in JSF,
code(JAVASCRIPT validation):
htmlInputTextObj.setMaxlength(8);
htmlInputTextObj.setOnkeypress("javascript:return limitinput(event, '0123456789', true);");
htmlInputTextObj.setOnfocus("javascript:return clearThisField(this);");
htmlInputTextObj.setOnblur("javascript:return loadDefaultValue(this);");

Code(JAVA validation)
final LengthValidator validator =

     (LengthValidator)getApplication().createValidator(LengthValidator.VALIDATOR_ID);

   if (question.getMinLength() > 0)

     validator.setMinimum(question.getMinLength());

   if (question.getMaxLength() > 0)

     validator.setMaximum(question.getMaxLength());

   htmlInputText.addValidator(validator);

JAVA validator more reference use link