text:
Q: kdbg continue debugging keyboard shortcut I am using kdbg for debugging.
> kdbg -v
Qt: 4.8.6
KDE Development Platform: 4.13.3
KDbg: 2.5.4
>

The official documentation is somewhat rudimentary. I am searching for a keyboard shortcut to continue running the program till it hits the next breakpoint. According to this F7 should do. However running on Ubuntu F7 seems to always jumop at the end of the current function. How can I get kdbg to run the executable till the next breakpoint?

A:
How can I get kdbg to run the executable till the next breakpoint?

Hit F5.
Yes, I know, the menu does not change text to Continue or so, but the icon shows something like the Play icon that you know from your media software (or CD player, if you grew up in the past century) which also just continues, and does not start from the beginning.


text:
Q: Insert only if timestamp is unoccupied I am using Android / Java and SQLite3 / SQLiteOpenHelper, with the Cursors and ContentValues.
I have a timestamp field in my table. I want to ensure that if someone is adding a new row, the row is not added if the timestamp is already occupied (so I do not want more than one value per timestamp).
Can this be enforced efficiently? Or do I have to perform a select statement every single time I perform an insertion to check first?

A: Add a UNIQUE qualifier on the timestamp field. You can then choose the behavior you want by calling inserWithOnConflict() and passing CONFLICT_FAIL as the conflict algorithm argument.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent calling constructor of component in ngFor directive Can I have components inside ngFor directive, in such a way, that component's constructor doesn't have to be called every time, when data changes?
Plunker example: http://plnkr.co/edit/6A6Aj8yeFqNd28Nl8cyS?p=preview
I just want to update data, not re-create component. Open console to see better what I mean.
AppComponent:
@Component({
  selector: 'my-app',
  template: `
    <div>
      <div *ngFor="let value of sourceData">
        <fizz [sampleInputValue]="value"></fizz>
      </div>
    </div>
  `,
})
export class App {

  sourceData: number[] = [];

  ngOnInit() {
    setInterval(() => {
      let newArrayOfRandomNumbers: number[] = [
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1
      ]

      newArrayOfRandomNumbers.forEach((randomNumber, index) => {
        this.sourceData[index]= newArrayOfRandomNumbers[index];
      });
    }, 500);
  }
}

FizzComponent:
@Component({
  selector: 'fizz',
  template: `
    {{sampleInputValue}}
  `
})
export class FizzComponent {

  @Input()sampleInputValue: number;

  constructor() {
    console.log("I dont want to be called, I just want the data to be updated")
  }
}

A: The problem is that Angular uses default trackBy function that compares by identity. If there is a mismatch it recreates the component and calls it's constructor as a consequence.
You could leverage that and pass values as object with numeric properties to ngFor:
  sourceData = [{},{},{},{},{}];

  ngOnInit() {
    setInterval(() => {
      let newArrayOfRandomNumbers: number[] = [
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1
      ]

      newArrayOfRandomNumbers.forEach((randomNumber, index) => {
        this.sourceData[index].v= newArrayOfRandomNumbers[index];
      });
    }, 500);

This will not be re-creating components. See this plunker.
Also see this answer to understand more about ngFor trackBy.

A: No, that's not possible.
Every time a component will be rendered, a new instance will be created. If you want to execute a logic just one time, move it from the constructor to a service.


text:
Q: Grails Find parent by child I look through the internet and I didnt find yet an answer for my question. Should be pretty easy:
class Parent {
  String name
  Child child
}

When I have a child object, how can I get the Parent by it?
like:
def Parent = Parent.findByChild(child)
How am I able to get a Parent object by it child?
thanks

A: Where have you looked?
Are these domain classes?  If so, then you can connect them via has_many and belongs_to:
class Parent {
    String name
    List children
    static has_many = [ children: Child ]
}

class Child {
   static belongs_to = [ parent: Parent ]
}

Then you can just write child.parent

A: def parent = Parent.findByChild(child) works fine - you can use dynamic finders for scalar fields (strings, numbers, booleans, etc.) and other objects.
Doing the reverse and finding all Child instances for a given Parent is a little more involved but can be done with HQL:
def p = Parent.get(id)
def children = Parent.executeQuery(
       'select c from Child c, Parent p where p.child=c and p=:parent',
       [parent: p])


text:
Q: Locking boxes in place CSS I have a website I'm building, and have a bit of positioning problem. I have two main text boxes on the content section, one to the top left and one to the bottom right. However, when the browser edges are moved in, th boxes move to the bottom box being on the left and the top box being on the right, as I'm using position:absolute. I was wondering if there was anyway to lock them in place, or to set a 'wall' in the middle where they couldn't be pushed past.
    #contentleft {
font: normal 14px verdana, sans-serif;
width: 450px;height:275px;
overflow-wrap:normal;
word-wrap:break-word;
position:absolute;
left:550px;
top:175px;
}
#contentright {
font: normal 14px verdana, sans-serif;
margin:0 auto;width: 500px;height:275px;
overflow-wrap:normal;
word-wrap:break-word;
position:absolute;
right:550px;
bottom:100px;
}

A: if the two textboxes are inside a parent div, then don't overuse css positioning.
Make #contentleft {float: left}
to control the positioning. Do not use position: absolute because when the browser is unmaximized, it will go to a different position. Instead, use position: relative so that the positioning is only inside its parent div.


text:
Q: How to initialise classes correctly The following code produces an error on the line pickUp.spawnShield() from my GameScene class whenever I try to call it.
There is no message from the compiler about what is causing the error, though I think it may be to do with the fact that my var pickUp: Pickup! is nil. If thats the case, how do I initialise it correctly?
class Pickup {

    var game: GameScene!

    func spawnShield() {

        let randomXStart = Random().random(min: game.gameArea.minX + game.player.size.width/2, max: game.gameArea.maxX - game.player.size.width/2)

        let randomXEnd = Random().random(min: game.gameArea.minX + game.player.size.width/2, max: game.gameArea.maxX - game.player.size.width/2)

        let startPoint = CGPoint(x: randomXStart, y: game.size.height * 1.1)
        let endPoint = CGPoint(x: randomXEnd, y: -game.size.height * 0.1)

        let shield = SKSpriteNode(imageNamed: "shieldDrop")
        shield.setScale(2)
        shield.position = startPoint
        shield.zPosition = 3

        game.addChild(shield)

        let moveShield = SKAction.move(to: endPoint, duration: TimeInterval(Helper().randomBetweenTwoNumbers(firstNumber: 3, secondNumber: 5)))

        shield.run(moveShield)
    }
}

Then I call it in my class like so:
class GameScene: SKScene, SKPhysicsContactDelegate {

    var pickUp: Pickup!

    override init(size: CGSize) {

        ....

        pickUp = Pickup() //something like this?

        super.init(size: size)
    }

    func startNewLevel() {

        pickUp.spawnShield()
    }
}

A: First: you have to create an instance of Pickup class stored (referenced) in var pickUp. I do not see anything like
class Pickup {
  weak var game: GameScene?
  init(game: GameScene) {
    self.game = game
  }
  func spawnShield() {...}
}

class GameScene: SKScene, SKPhysicsContactDelegate {
  var pickUp: Pickup!
  override init(size: CGSize) {
    super.init(size: size)
    pickUp = Pickup(game: self)
}

Second: I do not see too much reason to have pickUp implicitly unwrapped (!). I would rather propose weak var pickUp: Pickup? to avoid reference cycle (if referenced in cycle)
Third: it is strange that you see no compiler error of missing initializer, as you have properties in your classes and then initializer must be defined. Do not forget to call super.init(...) in your initializer, after you initialize your class properties.

A: here, I think you can do somthing like this
class GameScene: SKScene, SKPhysicsContactDelegate {

    var pickUp = Pikup()

    func startNewLevel() {

        pickUp.spawnShield()
    }
}

or you can just initialize you variable "pikUp" before calling spawnShield(), maybe in init method as you wrote.
so also make sure that you use 'game' variable after initializing it, because as I can see in your code it will also crash because it is nil when you use it.


text:
Q: Mongodb Shell Update Query I'm currently getting the following error below when trying to run an update query in MongoDB Shell. I can't for the life of me figure out why this is an error. I've tried all the below combinations of queries, and all give the same error:
1) db.users.update({"username":"jre"3},{ $set : { "email": "hello@a.com!"}});
2) db.users.update({"username":"jre"3},{ $set : { "email": "hello@a.com!"}})
3) db.users.update({username:"jre"3},{ $set : { email: "hello@a.com!"}})
4) db.users.update({username:"jre"3},{ $set : { email: "hello@a.com!"}});

Error: SyntaxError: Unexpected token ILLEGAL
I have MongoDB shell version: 2.6.3. Any help?
Thanks!
Jason

A: Some of your quotation marks look suspicious. You have " and ". Change the first ones to the latter ones.


text:
Q: why is my webapplication NoClassDefFoundError: org/aspectj/lang/reflect/AjTypeSystem I´ve a maven web application. I´m using JSF, Primefaces, Hibernate, Spring, Spring AOP and ORACLE 11g.
So when I deploy my application on Glassfish 3 it works perfectly, but when I deploy it on weblogic 12 I get the next error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Usuarios' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/lang/reflect/AjTypeSystem

Caused By: java.lang.NoClassDefFoundError: org/aspectj/lang/reflect/AjTypeSystem

So I opened my war then I looked in WEB-INF/lib and I found (aspectjrt.jar and aspectweaver.jar), so I´m not sure what´s wrong.
Here is the part of my pom where I declare the aspectJ libs:
<properties>
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <spring.version>3.2.4.RELEASE</spring.version>
    <aspectj.version>1.7.0</aspectj.version>
    <java.version>1.7</java.version>
    <netbeans.hint.deploy.server>WebLogic9</netbeans.hint.deploy.server>
    <netbeans.hint.j2eeVersion>1.6</netbeans.hint.j2eeVersion>
</properties>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- aspectJ -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${aspectj.version}</version>
    </dependency>

So does anyone knows what´s happening. I already googled the error but every one says that the aspectjrt.jar and aspectweaver.jar might be missing, but I´m pretty sure they aren´t.
Thanks in advance.

A: Have you tried this in weblogic.xml :
<container-descriptor>
   <prefer-web-inf-classes>true</prefer-web-inf-classes>
</container-descriptor>

and this in weblogic-application.xml :
   <prefer-application-packages>
      <package-name>org.springframework.*</package-name>
   </prefer-application-packages>

I haven't tried this myself, but found this on http://forum.spring.io/forum/spring-projects/aop/91846-can-t-find-ajtypesystem-during-deployment .. basically what's going is that even that you have aspectjrt.jar and aspectweaver.jar in your WAR, they don't get loaded because WLS thinks they are available somewhere else in its system classpath ("higher up" in the classloader hierarchy typically), sometimes with another version.  This is a typical problem on EE application servers, and each one of them (WLS, WAS, JBoss) has some configuration to influence class path loading order. If above doesn't exactly work, Google that further, and you'll figure it out... best of luck.


text:
Q: how to decrypt aes-256-gcm in PHP using IV & TAG I've found a difficult way to decrypt a string using aes-256-gcm, iv, and TAG.
Here are the parameters that I get.
$password = 'code1234';
$data = 'f4oGPQaf9ZolRc9oh8VLRiJWK2B35tkHq9L6WvrE+jbjS1mfi0fJB7re+0kVM2RRLiAEPBSFtIQzlJ5055yRlntIZwwpRvAN1cUBS0ze3hb+FrcO43vtBuuqftDw0exfmorPM5SOaKj3KtEQjB2ypwtbnQNCtegNizs6niqAdvs/XztlZPbq08Y=';

$ivstring = 'D7GVFFLn+K0sNj+YRskGTw==';
$tagstring = '9GSCia0QDujWTn3zpIRbCw==';

I use this function to decrypt
openssl_decrypt($data, 'aes-256-gcm', $password, OPENSSL_RAW_DATA, $ivstring, $tagstring);

but it always returns with the following error

Setting tag for AEAD cipher decryption failed

how to decrypt aes-256-gcm in PHP using IV & TAG
UPDATE :
the encryption are come from main app using node js. I tried to decrypt within nodejs app, it's working normally. I tried to convert decrypt function to PHP, but always get errors. Here the encrypt and decrypt script function
const crypto = require('crypto');

// Demo implementation of using `aes-256-gcm` with node.js's `crypto` lib.
const aes256gcm = (key) => {
    const ALGO = 'aes-256-gcm';
    const aes_password = key || 'code1234';
    const aes_key = crypto.createHash('md5').update(aes_password, 'utf-8').digest('hex').toUpperCase();

    // encrypt returns base64-encoded ciphertext
    const encrypt = (str) => {

        const iv = new Buffer(crypto.randomBytes(16), 'utf8');
        const cipher = crypto.createCipheriv(ALGO, aes_key, iv);

        let enc = cipher.update(str, 'utf8', 'base64');
        enc += cipher.final('base64');

        const ivString = iv.toString('base64');
        const authTagString = cipher.getAuthTag().toString('base64')
        return [enc, ivString, authTagString];
    };

    // decrypt decodes base64-encoded ciphertext into a utf8-encoded string
    const decrypt = (enc, ivString, authTagString) => {
        const iv = new Buffer(ivString, 'base64');
        const authTag = new Buffer(authTagString, 'base64');
//console.log(iv);
  //      console.log(authTag);
        const decipher = crypto.createDecipheriv(ALGO, aes_key, iv);
   //     console.log(iv);
        decipher.setAuthTag(authTag);
        let str = decipher.update(enc, 'base64', 'utf8');
        console.log(str);
        str += decipher.final('utf8');
        return str;
    };

    return {
        encrypt,
        decrypt,
    };
};

module.exports = aes256gcm;


text:
Q: Normal bundle to the base of a cone We work over the field of complex numbers. Consider the weighted projective space $\mathbb P(1^n,2)$, that is given by
$$
\frac{\mathbb A^{n+1} \setminus \{0\}}{\mathbb C^*}
$$
where $\mathbb C^*$ acts on the affine space $\mathbb A^{n+1}$ as
$$
t \cdot (x_0,\ldots,x_n) =(tx_0,\ldots,tx_{n-1},t^2x_n).
$$
It can be proved (see the notes of Miles Reid about weighted projective spaces) that $\mathbb P(1^n,2)$ is isomorphic to a cone over $\nu_2\mathbb P^{n-1}$, where $\nu_2:\mathbb P^{n-1} \hookrightarrow \mathbb P(H^0(\mathbb P^{n-1},\mathcal O(2))^\vee)$ is the second Veronese embedding.
It has been told me that the normal bundle of $\nu_2 \mathbb P^{n-1}$ inside the cone $\mathbb P(1^n,2)$ is the line bundle $\mathcal O(2)$, but I cannot find a proof of this fact.
Any idea?


text:
Q: Sort a vector of strings by substrings? I have a vector containing a number of strings of the same form:
'12345 QWERTY'
'23456 ASDFGH'
'34567 ZXCVBN'

I need to sort them by code (int type) and by names (string type). I am thinking of using the .substr() function to ignore the numbers. Is there a way I could use this within the sort function?
One attempt is to create a mapping function to compliment 'sort()':
bool mapFunc(string a, string b)
{
return a.substr(6) < b.substr(6));
}

plug into the sort function:
sort(begin, end, mapFunc);

where 'begin' and 'end' are both iterators pointing to the beginning and end of my vector.
Please correct me if Ive made any mistake here:)

A: You are on the right track by passing a custom predicate to std::sort(). You just need to flesh it out more:
void split(const string &s, int &code, string &name) {
    size_t idx = s.find(' ');
    code = stoi(s.substr(0, idx));
    name = s.substr(idx+1);
}

bool mapFunc(const string &a, const string &b) {
    int code1, code2;
    string name1, name2;
    split(a, code1, name1);
    split(b, code2, name2);
    if (code1 == code2)
        return name1 < name2;
    return code1 < code2;
}

This will sort the vector items by their numeric codes first, and will sort by name only for items with the same code value.

A: You can use a functor (function object):
struct Compare_By_Number
{
  bool operator()(const std::string& a, const std::string& b) const
  {
    std::istringstream a_input_stream(a);
    std::istringstream b_input_stream(b);
    int a_value, b_value;
    a_input_stream >> a_value;
    b_input_stream >> b_value;
    return a_value < b_value;
  }
};

You can then pass an instance of the function, as per the std::sort example.
Edit 1:  Standalone function
An alternative is to place the code inside a standalone function and pass the function:
bool Order_By_Number(const std::string& a, const std::string& b)
{
    std::istringstream a_input_stream(a);
    std::istringstream b_input_stream(b);
    int a_value, b_value;
    a_input_stream >> a_value;
    b_input_stream >> b_value;
    return a_value < b_value;
}

std::vector<std::string> database;
//...
std::sort(database.begin(), database.end(), Order_By_Number);

The fundamental concept is to return true if the first parameter comes before the second in your ordering.

A: I would think that using std::lexicographical_compare would be more efficient that extracting a substring.
What std::lexicographical_compare does is it compares substrings in place so you don't pay the cost of copying them out.
Something like this:
std::vector<std::string> v
{
    "12345 QWERTY",
    "23456 ASDFGH",
    "34567 ZXCVBN",
};

std::sort(std::begin(v), std::end(v), [](std::string const& a, std::string const& b){
    return std::lexicographical_compare(std::begin(a), std::begin(a) + 5, std::begin(b), std::begin(b) + 5);
});

std::cout << "By first column" << '\n';
for(auto const& s: v)
    std::cout << s << '\n';

std::sort(std::begin(v), std::end(v), [](std::string const& a, std::string const& b){
    return std::lexicographical_compare(std::begin(a) + 6, std::end(a), std::begin(b) + 6, std::end(b));
});

If you're going to be doing a lot of this kind of thing then you can wrap it up in a special comparator like this:
struct substring_compare
{
    std::size_t from;
    std::size_t len;

    substring_compare(std::size_t from, std::size_t len)
    : from(from), len(len) {}

    bool operator()(std::string const& a, std::string const& b) const
    {
        // sanity checks
        assert(from + len <= a.size());
        assert(from + len <= b.size());

        auto beg_a = std::begin(a) + from;
        auto end_a = beg_a + len;

        auto beg_b = std::begin(b) + from;
        auto end_b = beg_a + len;

        return std::lexicographical_compare(beg_a, end_a, beg_b, end_b);
    }
};

int main()
{
    std::vector<std::string> v
    {
        "12345 QWERTY",
        "23456 ASDFGH",
        "34567 ZXCVBN",
    };

    // start at position 0, comparing 5 characters
    std::sort(std::begin(v), std::end(v), substring_compare(0, 5));

    std::cout << "By first column" << '\n';
    for(auto const& s: v)
        std::cout << s << '\n';

    // start at position 6, comparing 6 characters
    std::sort(std::begin(v), std::end(v), substring_compare(6, 6));

    std::cout << "By second column" << '\n';
    for(auto const& s: v)
        std::cout << s << '\n';
}

Output:
By first column
12345 QWERTY
23456 ASDFGH
34567 ZXCVBN

By second column
23456 ASDFGH
12345 QWERTY
34567 ZXCVBN

A: You can use existing functionality that std::pair provides (comparison operator). So implement conversion function:
std::pair<int,std::string> convert( const std::string &str )
{
     int id = 0;
     std::string name;
     std::istringstream is( str );
     is >> id >> name;
     return std::make_pair( id, name );
}

then your comparator function is trivial:
bool compare( const std::string &s1, const std::string &s2 )
{
     return convert( s1 ) < convert( s2 );
}

A: You'd better have a std::vector<std::pair<int, string>> to void such complications.
Otherwise you should create a comparative function and pass substrings.

A: To set up the question, we have a vector of strings:
vector<string>myVec;

vector<string>::iterator vecBegin=myVec.begin(), vecBegin=myVec.end();

One attempt is to create a mapping function to compliment 'sort()':
bool mapFunc(string a, string b)
{
return a.substr(6) < b.substr(6));
}

plug into the sort function:
sort(vecBegin, vecEnd, mapFunc);

where 'vecBegin' and 'vecEnd' are both iterators pointing to the beginning and end of my vector.
This will sort the vector of strings by substrings. The vector can be accessed using iterator:
vector<string>::iterator currentVec;
for (currentVec=vecBegin; currentVec<vecEnd; ++currentVec)
{
// Do things
}


text:
Q: WSO2 api manager not propagating content type header for multipart form data I'm using WSO2 api manager 1.10.0.
I have a problem when using multipart/form-data , in fact i noticed that content type header isn't propagated to my back end service and so I'm getting unsupported media type 415 HTTP error.
Please any idea how to fix this?

A: Add the following property to repository/conf/passthru-http.properties file.
http.headers.preserve=Content-Type
This will preserve the content type header you send with the request and send it to the backend. If you want to preserve more such headers, you can add them to the same line with comma separated.


text:
Q: Package 'youngtab' should be in Miktex, but I get an error So I want to use the package youngtab, according to CTAN, this is already provided in MiKTeX, which I am using. However, when compiling with TeXmaker, I get the error that the package is not found.
I have no knowledge about the whole LaTeX package thing and don't know what to do, but I do need the package, its for an exam. Can anyone help me? Thanks!
PS: I am using Windows 8.1.

A: Windows 8.1 shows installed programs (like MiKTeX 2.9) on the App page.
Please click on the windows symbol in the task line, then go down and click on the following symbol (it will be shown if you move the mouse cursor down):

then the complite list of all installed apps is showed.  Usually you have now to go to the left side to find the programs to control MiKTeX:


text:
Q: Undefined reference to `COMP_zlib@libcrypto.so.10' (and others) I am working on Red Hat Enterprise Linux Server release 7.0 (Maipo). The server provides OpenSSL 1.0.1. I am getting a lot of crypto errors when trying to link to OpenSSL.
Here is my link command command line (order like in the command line):
g++ -g -O2 -Wl,-rpath -o output file1.o  libprivate_lib1.so -Lprivate_path -llib1 -ldl \
-lpthread -llib2 -lexpat -lgtest -lgtest_main -lboost_regex -lboost_filesystem -llzma \
-lcrypto private_lib2.so private_lib3.so -llib3

Here are some of the errors:
/lib64/libssl.so.10: undefined reference to `COMP_zlib@libcrypto.so.10'
/lib64/libssh2.so.1: undefined reference to `EVP_get_cipherbyname@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `X509_STORE_free@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `BIO_clear_flags@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `d2i_KRB5_AUTHENT@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `MD5_Transform@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `X509_VERIFY_PARAM_set_depth@libcrypto.so.10'
/lib64/libssh2.so.1: undefined reference to `DSA_do_verify@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `SHA384_Init@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `PEM_ASN1_read_bio@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `FIPS_mode@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `OBJ_find_sigid_algs@libcrypto.so.10'
/lib64/libssh2.so.1: undefined reference to `BN_bn2bin@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `EVP_rc2_40_cbc@libcrypto.so.10'
/lib64/libssl.so.10: undefined reference to `sk_num@libcrypto.so.10'
...

when I am running:
ll /usr/lib64/libcrypto.so

I am getting
/usr/lib64/libcrypto.so -> libcrypto.so.1.0.1e

and when running:
objdump -tT /usr/lib64/libcrypto.so.1.0.1e | grep COMP_zlib

I get
000000000013e500 g    DF .text  0000000000000002  libcrypto.so.10 COMP_zlib_cleanup
000000000013e460 g    DF .text  000000000000009e  libcrypto.so.10 COMP_zlib

so it means that I have it in this library.
The strangest thing is that it is able to link in redhat 6.5/4 but failing with redhat above 7.
any suggestions ?

A: Functions like COMP_zlib and EVP_get_cipherbyname are part of the OPenSSL SSL library, and not the Crypto library. You have -lcrypto but you appear to be missing -lssl:
g++ -g -O2 -Wl,-rpath -o output file1.o  libprivate_lib1.so -Lprivate_path -llib1 -ldl \
-lpthread -llib2 -lexpat -lgtest -lgtest_main -lboost_regex -lboost_filesystem -llzma \
-lcrypto private_lib2.so private_lib3.so -llib3

You should change to -lssl -lcrypto:
g++ -g -O2 -Wl,-rpath -o output file1.o  libprivate_lib1.so -Lprivate_path -llib1 -ldl \
-lpthread -llib2 -lexpat -lgtest -lgtest_main -lboost_regex -lboost_filesystem -llzma \
-lssl -lcrypto private_lib2.so private_lib3.so -llib3

If private_lib2.so private_lib3.so depend upon OpenSSL, then -lssl -lcrypto needs to be moved after them. That is, use private_lib2.so private_lib3.so -lssl -lcrypto.
Also libssh must proceed -lssl -lcrypto. I don't see where its being linked, but the library may be going by a different name. In the end, you might find it easier to use the library list <other libs> ... -lssl -lcrypto -llzma -pthread.
It could also be a newer or different version of OpenSSL is present, but its configured differently. For example, it looks like Red Hat removes compression (./configure no-comp ...) but headers are bringing in symbols like COMP_zlib.
I guess your next step is to: (1) show a typical compile command, and (2) provide g++ -v so we can see the header search paths.
One final thing to keep in mind is you are using g++, so linkage with be extern "C++" by default. It could be one of those old OpenSSL headers lacks the customary:
#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}
#endif

I don't have access to a Red Hat server, so I don't know for sure. I test another library using both CentOS and Fedora, but I know differences exist on occasion.


text:
Q: Text over flipped image CSS I've been selflearning a bit about Jscript and CSS playing with the code of this card memory game:
https://marina-ferreira.github.io/projects/js/memory-game/
Which I have in codeopen here:
https://codepen.io/jaimesoza/pen/xxwJBde
I would like to add some text (the name of the card) only to the flipped version, for obvious reasons. I've seen some examples which do that, but I have not been able to apply them to this current CSS, as I am a total noob in these matters. Every time I try something similar to this I end up messing everything.
CSS
    .bottom-right {
      position: absolute;
      bottom: 8px;
      right: 16px;
    }

HTML

Dog

I think it is quite simple for somebody with experience with css, please help!

A: With Some few changes of your code you will get your desire output.
First put your all class="front-face" images in a div like shown below.

Dog

Then changes following style sheets as follows.
.front-face,
.back-face {
  width: 100%;
  height: 100%;
  padding: 23px; // This value is only changed
  position: absolute;
  border-radius: 5px;
  background: #1C7CCC;
  backface-visibility: hidden;
}

Then add you new class CSS in style sheet
.bottom-right {
      position: fixed;
      text-align: center;
      display: block;
      bottom: 3px;
      color: white;
      left:60px
    }

You will get something like this


text:
Q: Changing root mysql password failed when done from mysql CLI Consider the following code:
UPDATE user set password=PASSWORD('NEWPASSWORD_CAME_HERE') WHERE User='root';

Where it is written NEWPASSWORD_CAME_HERE I've putted my password (between the quote marks).
Yet when I executed this query I got this error:

ERROR 1046 (3D000): No database selected

Why have I got this error?, I followed different guides and this is the most traditional way I've seen so I can't understand why it failed.

A: First of all, you'd have to specify the database in your UPDATE statement, not only the table:
UPDATE mysql.user ...

otherwise MySQL can't know on which database you're operating (hence the error).
However, this is not the proper way to change an user's password in MySQL. Fiddling with the mysql database (which contains database metadata) is not recommended. Do this instead:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('NEWPASSWORD_CAME_HERE');

A: to solve your error:
use mysql
But you should have a look at mysql reference manual:
ALTER USER user IDENTIFIED BY 'auth_string';

SET PASSWORD Syntax


text:
Q: Are two touching conductors connected in parallel or in series? Consider the following problem:
There are two spherical conductors $A, B$, with capacitances $C_A, C_B$ resp. Conductor $A$ is supplied some charge and is found to have a potential of $160 \space V$. Conductor $B$ is also supplied some charge and is found to have a potential of $50 \space V$. They are then connected so that their charges equalize. Now, their common voltage is $140 \space V$. Find $C_A: C_B$.
I started off with the basic relation, $Q_A = C_AV_A = 160\space C_A$ similarly, $Q_B = 50C_B$. Now, when they are connected the total charge will equal $Q_T = Q_A + Q_B = 160C_A + 50C_B$. Now, the total capacitance of the combination of these spheres will be $C_T$.
I can't seem to decide if these spheres should be considered to be connected in parallel or in series.

A: You don't need to determine whether they are in series or parallel to solve this problem(They might not be in either).
The final voltage of both spheres is given to you, so you can find the charges which will finally appear on both the spheres, given by
$$Q_f=140C_A+140C_B$$
This must be enough for you to solve further. If not then hover over the boxes below to see further solution
By conservation of charge we have

$$Q_f=Q_{A,i}+Q_{B,i}$$
$$140C_A+140C_B= 160C_A + 50C_B$$

Thus

$$90C_B=20C_A$$
$$\therefore \frac{C_A}{C_B}=\frac 92$$


text:
Q: Why Laravel Resource Create and Edit operations are depicted using GET I am picking up on Laravel, and noted that on Laravel's Documentation, it states that the the GET HTTP verb will be handled by the create and edit operations, but from my understanding of REST and CRUD, a create or edit operation actually results in change of records or state on the back-end. So why does Laravel choose to use GET for create and edit operations?

A: As per Laravel creat and edit method uses GET request because they are used to render a view where you can add or update your data. When you submit you form it will use store and update method which are POST and PUT/PATCH request to save the data into database.


text:
Q: Why can't I have multiple a 1:N and a 1:1 one-way reference to a class in Mongoid? I'm trying to set up multiple classes that reference a class, and they only need to be one way.
I have these classes:
class Widget
  include Mongoid::Document

  ...

class Template
  include Mongoid::Document

  has_and_belongs_to_many :widgets, inverse_of: nil
  ...

class EntryText
  include Mongoid::Document

  has_one :widget, inverse_of: nil
  ...

When I try something like:
 EntryText.new.widget = Widget.first

I get this error:
undefined method `=' for #<Widget:

I am able to change Entry Text to have this reference to Widget:
has_and_belongs_to_many :widgets, inverse_of: nil

But since it will only have one widget, this is kind of an ugly workaround.

A: Instead of using has_one :widget, you should use belogs_to :widget, inverse_of: nil. Mongoid(also active record) stores id on the belongs_to side. So if the relation needs to be persisted only on one side, it has to be belongs_to otherwise we cannot get back from db the association which we tried to store.


text:
Q: How to find X,Y coordinates on Half Doughnut Chart JS react I've got the doughnut part of the chart complete and the gauge needle. I want to add this circular pointer on the doughnut instead of the needle. I was able to draw the circular pointer but couldn't find the right X,Y coordinates to place the pointer.
Here is the DEMO
Here in the below image, the circle should be placed at the gauge needle pointer

The code I've used is the following for the circular pointer.

const pointer = {
  id: "pointer",
  afterDatasetsDraw: (chart) => {
    const { ctx } = chart;

    var data = chart._metasets[0].data[0];

    var radius = data.innerRadius + (data.outerRadius - data.innerRadius) / 2;

    var centerX = data.x;
    var centerY = data.y;

    const angle = (180 / 1000) * speed;
    // this thing needs to be fixed
    var x = centerX + radius * Math.cos(angle * Math.PI);
    var y = centerY + radius * Math.sin(angle * Math.PI);

    ctx.save();

    ctx.beginPath();
    ctx.lineWidth = 6;
    ctx.arc(x, y, 12, 0, 2 * Math.PI);
    ctx.stroke();

    ctx.restore();
  }
};

Target to achive:

A: Basically you want 75% of 180 Degrees (because the speed = 75):
const angle = Math.PI * ( speed / 100)  +  Math.PI;

And than Math.cos and Math.sin expect a radiant value(link to mdn documentation), which you already have, so no multiplication with Math.PI is needed anymore.
  var x = centerX + radius * Math.cos( angle );
  var y = centerY + radius * Math.sin( angle );

Full working demo (Updated Example, now with animation):

const speed = 75;
let animationAngle = 0;

var pointer = {
    id: 'pointer',
    defaults:{
     percentage: 0,
     maxAngle: 0
    },
    afterDraw: function(chart, args, opt) {
      const { ctx } = chart;

      var data = chart._metasets[0].data[0];
      var radius = data.innerRadius + (data.outerRadius - data.innerRadius) / 2;

      var centerX = data.x;
      var centerY = data.y;

      const angle = (Math.PI * ( speed / 100) * chart.options.plugins.pointer.percentage)  +  Math.PI;

      var x = centerX + radius * Math.cos( angle );
      var y = centerY + radius * Math.sin( angle );

      ctx.save();

      ctx.beginPath();
      ctx.lineWidth = 6;
      ctx.arc(x, y, 12, 0, 2 * Math.PI);
      ctx.stroke();

      ctx.restore();
    },
}

var options = {
    type: 'doughnut',
    data: {
    datasets: [{
        data: [20, 50, 30],
        backgroundColor: [
            'rgba(231, 76, 60, 1)',
            'rgba(255, 164, 46, 1)',
            'rgba(46, 204, 113, 1)'
        ],
        borderColor: [
            'rgba(255, 255, 255 ,1)',
            'rgba(255, 255, 255 ,1)',
            'rgba(255, 255, 255 ,1)'
        ],
        borderWidth: 0
    }]},
    options: {
      cutout: 80,
      rotation: -90,
      circumference: 180,
      animation:{
        onProgress: function(context){
            if(context.initial){
                this.options.plugins.pointer.percentage = context.currentStep / context.numSteps;
            }
        }
      },

      maintainAspectRatio: false,
      legend: { display: false },

      plugins:{
        tooltip: {  enabled: false },
        pointer: {currentAngle: 1}
      }
    },
    plugins:[pointer]
}

const chart = document.getElementById('chart1')
new Chart(chart, options);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div style="width:500px;height:184px">
   <canvas id="chart1" width="500" height="184"></canvas>
<div>


text:
Q: Jquery mouseover do not work properly I have been write a jquery code  for slide to previous or next image in  element when hover the first or last  image but it not work properly, it just slide one time but not smoothly at first mouseover and after that it not slide any more when i mouseover again on it. please take a look and find out what happen in my code, why dont it slide smoothly ? and why do it slide when i mouseover again ?  thanks in advance .

You can look at the fiddle here: http://jsfiddle.net/9M3dM/
HTML code :

CSS code :
#slide-wrapper{
    position:relative;
    overflow:hidden;
    height:183px;
    padding-top: 1px;
}
#slide-wrapper ul.slide-container{
    overflow:hidden;
    position:absolute;
    width:100%;
    height:183px;
}
ul.slide-container li{
    cursor: pointer;
    display: block;
    float: left;
    height: 183px;
    padding-right: 1px;
    width: 145px;
}
ul.slide-container li img{
    border: none;
    height: 183px;
    width: 145px;
}
ul.slide-container li.last{
    padding-right: 0;
}

Jquery code :
(function ($) {
    var isAnimating = false;
    var methods = {
        init: function (options) {
            var self = this;
        },
        display: function () {
            methods.slide();
        },
        slide: function () {
            $(".slide-container li.last").mouseover(function () {
                methods._next(".slide-container", -147);
            });
            $(".slide-container li.first").mouseover(function () {
                methods._prev(".slide-container", 147);
            });
        },
        _next: function (target, move) {
            var base = parseInt($(target).css("margin-left"), 10);
            var maxLeng = ($("ul.slide-container li").length * $("ul.slide-container li").not("first").innerWidth()) - (7 * $("ul.slide-container li").not("first").innerWidth());
            if (base == maxLeng || isAnimating) {
                return false;
            }
            isAnimating = true;
            base = base + move;
            $(target).find("li.last").next("li").addClass("last");
            $("#slide-wrapper").animate({
                "margin-left": base
            }, 600, "easeInOutSine", function () {
                isAnimating = false;
                $(target).find("li.last:first").removeClass("last");
            $(target).find("li.first").removeClass("first").next("li").addClass("first");
            });
        },
        _prev: function (target, move) {
            var base = parseInt($(target).css("margin-left"), 10);
            if (isAnimating || base === 0) {
                return false;
            }
            base = base + move;
            isAnimating = true;
            $(target).find("li.first").prev("li").addClass("first");
            $("#slide-wrapper").animate({
                "margin-left": base
                }, 600, "easeInOutSine", function () {
                    isAnimating = false;
                $(target).find("li.last").removeClass("last").prev("li").addClass("last");
                    $(target).find("li.first").removeClass("first");
            });
        }
    };
    $(document).ready(function () {
        self.display();
    });
})(jQuery);

A: I think you messed up your code when posting.

Uncaught SyntaxError: Unexpected token )

display: function() {}) methods.slide();
//--------------------^

http://jsfiddle.net/9TRnR/


text:
Q: Centering a pgf-pie chart with legend with respect to center of the chart, not the entire figure I have a pie chart with a legend at the side made using pgf-pie. It is centered with respect to the center point of the entire figure, including the legend.
MWE:
\documentclass[tikz, 12pt, a4paper]{report}
\usepackage[T1]{fontenc}
\usepackage{caption}
\usepackage{subcaption}
\usepackage[usenames, dvipsnames, rgb]{xcolor}
\usepackage{tikz}
\usepackage{pgf-pie}
\usetikzlibrary{arrows, positioning, shadows}
\begin{document}
\pagenumbering{gobble}
\begin{figure}[h]
\centering
\begin{tikzpicture}
\pie[sum=auto,text=legend]{10/A,20/B,30/C,10/D, 56.8/E}
\end{tikzpicture}
 \caption{Caption}
 \vspace*{1em}
\end{figure}
\end{document}

Screenshot with an indicated line crossing the center of my chart, perpendicular to the caption, showing that it is not properly centered.

Is there a way to center it with respect to the center of my pie chart?

A: Here, I save a legend-less pie chart in box 0 and the desired one in box 2. Then, I typeset it as such
\makebox[\wd0][l]{\box2}

Here is the MWE.
\documentclass[tikz, 12pt, a4paper]{report}
\usepackage[T1]{fontenc}
\usepackage{caption}
\usepackage{subcaption}
\usepackage[usenames, dvipsnames, rgb]{xcolor}
\usepackage{tikz}
\usepackage{pgf-pie}
\usetikzlibrary{arrows, positioning, shadows}
\begin{document}
\pagenumbering{gobble}
\begin{figure}[h]
\centering
\sbox0{\tikz{\pie[sum=auto]{100/}}}%
\sbox2{\tikz{\pie[sum=auto,text=legend]{10/A,20/B,30/C,10/D, 56.8/E}}}%
\makebox[\wd0][l]{\box2}
 \caption{Caption}
 \vspace*{1em}
\end{figure}
\end{document}


text:
Q: Scaffolding Controller not working in asp.net core 5 in Ubuntu 20.04 I am new to .net core. With background in NodeJS ecosystem, currently asp.net core feels overwhelming. I am following Microsoft doc for tutorial to build a simple Web API, and I am stuck at scaffolding a controller part
I  try to run the following command
dotnet aspnet-codegenerator controller -name TodoItemsController -async -api -m TodoItem -dc TodoContext -outDir Controllers

but I get the following error

scaffolding failed.
no such file or directory

I have tried updating the code-generator with
  dotnet tool update dotnet-aspnet-codegenerator -g --version 5.0.2

But the end result is still same.
I wonder if asp.net core is just too hard for a newbie or the framework is just too complicated.


text:
Q: How to convert venn diagram code from javascript
A: You can see a working example at https://stackblitz.com/edit/angular-f4popv
import { Component, OnInit } from '@angular/core';

// import * as fs from 'graceful-fs';
// now go and do stuff with it...
//fs.writeFile('test.delme')
//fs.readdir('./');

import * as d3 from 'd3'
import * as venn from 'venn.js'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';

  sets = [ {sets: ['A'], size: 12},
                {sets: ['B'], size: 8},
                {sets: ['C'], size: 5},
                {sets: ['D'], size: 10},
                {sets: ['A','B'], size: 2},
                {sets: ['A','C'], size: 2},
                {sets: ['A','D'], size: 2}];

  ngOnInit(){
    // console.log(grfs);
    console.log( "d3 ", d3 );
    console.log( "venn ", venn );

    var chart = venn.VennDiagram()
    d3.select("#venn")
      .datum(this.sets)
      .call( chart );

    console.log( this.sets );

    // redraw the diagram on any change in input
    d3.selectAll("#venn").on("mouseover", function(d) {

        d3.selectAll("#venn").data()[0].forEach(
          function (dd, ii){
            dd.size = Math.round( Math.random()*20+1 );
            console.log( `${ii} ${dd.sets} `, dd.size );
          }
        );

        d3.select("#venn").datum(d).call(chart);
    });

    // setTimeout( () => {
    //   console.log("timeout out")
    //   this.sets[0].size = 5;
    // },2000)

   }

}

Hope this helps you.


text:
Q: Collection view is shown on simulator but not on device-very strange This one,is one of the strangest i have seen for a while .
Using iPhone6 on simulator, our app has a main class(view controller) that has a UIScrollview.
That scrollview loads to its 3 pages,a 3 different view controllers(classes).
Each view controller has its own collection view.
We load them to the main scroller like that :
 self.someviewcontroller=[[someviewcontroller alloc] initWithPosition:0];
  self.someviewcontroller2=[[someviewcontroller2 alloc] initWithPosition:1];
[scroller addSubview:self.someviewcontroller];
[scroller addSubview:self.someviewcontroller1];

Now these someviewcontroller has a UICollectionview inside it.
In simulator we see the collection view and it works great.
On the actual iPhone6, you just dont see the collection view !
(his delegates are still being called- all cells delegates are called)
the someviewcontroller looks like that :
    - (id)initWithPosition:(NSInteger)position
    {
        if (self = [super init])
        {
            myPosition = position;
         }
        return self;
    }

- (void)viewDidLoad
{
    [super viewDidLoad];
 //some stuff here
//collection view
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    self.collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    [self.collectionView setDataSource:self];
    [self.collectionView setDelegate:self];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    [self.collectionView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:self.collectionView];

Why i dont see the collection view in the actually device? does it has to do with the fact that it is inside a view controller that is inside a scroller ??
btw:
on the simulator, i see the collection view only if its in a view controller that is in page number0 in the scroller. if its in viewcontoller in page 1 , i also not see it on the simulator.


text:
Q: Swift: Add image to CAShapeLayer I have a CAShapeLayer with a fill color, and want to add an icon in the center of this shape:
var shape = CAShapeLayer()
shape.fillColor = UIColor(white: 0.90, alpha: 1).CGColor
var image = UIImage(named: "some_image")
shape.contents = image?.CGImage

This code does compile and does show the grey shape- but no image. :(
I looked into these posts, but I can't cast the CGImage like they do.
add UIImage in CALayer and Display an image or UIImage with a plain CALayer
Is there another way? Or a workaround to the id cast?
Full code:
ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet var menuView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(animated: Bool) {

        let menu: CircularMenu = CircularMenu(frame: menuView.bounds, numberOfMenuItems: 4, hasProgressBar: false)
        self.menuView.addSubview(menu)
    }

}

CircularMenu.swift
import UIKit

// *** Helper methods start
func DegreesToRadians (value: Double) -> CGFloat {
    return CGFloat(value * M_PI / 180.0)
}

func RadiansToDegrees (value: Double) -> CGFloat {
    return CGFloat(value * 180.0 / M_PI)
}
// *** Helper methods end

class CircularMenu: UIControl {

    var parent: UIViewController!

    var centerButton: UIButton!
    var menuButtonShapes = [CAShapeLayer]()
    var menuButtons = [UIButton]()

    var numberOfButtons: Double = 4

    var bigSize: CGFloat = 300
    var centerButtonSize: CGFloat = 100
    var centerButtonPadding: CGFloat = 70
    let paddingBetweenButtons = 1

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    convenience init(frame: CGRect, numberOfMenuItems: Int, hasProgressBar: Bool = false) {
        self.init(frame: frame)
        self.bounds = frame

        self.bigSize = frame.width
        self.centerButtonSize = bigSize/2
        self.centerButtonPadding = bigSize/4-5

        if hasProgressBar {
            self.centerButtonSize -= 10
        }

        if numberOfMenuItems != 0 && numberOfMenuItems <= 10 {
            self.numberOfButtons = Double(numberOfMenuItems)
        }

        // Draw center button
        var centerButtonView = UIView(frame: CGRectMake(0, 0, centerButtonSize, centerButtonSize))
        centerButtonView.backgroundColor = UIColor(red: 160.0/255, green: 197.0/255, blue: 25.0/255, alpha: 1)

        centerButtonView.center = self.center;
        centerButtonView.layer.cornerRadius = centerButtonSize/2
        self.addSubview(centerButtonView)
        self.centerButton = UIButton(frame: centerButtonView.bounds)

        let degreesPerButton: Double = 360.0/numberOfButtons

        // Draw button shapes
        for (var i: Double = 1; i <= numberOfButtons; i++)
        {
            // Determine start and end radians of pizza slice
            let startAngle = DegreesToRadians(degreesPerButton*i+degreesPerButton-Double(paddingBetweenButtons))
            let endAngle = DegreesToRadians(degreesPerButton*i+Double(paddingBetweenButtons))

            // Determine center and angle of slice
            var buttonCenter = self.center;
            var offsetDirection = (startAngle - endAngle)/2 + endAngle

            // Shove slice outward to make space for inner padding
            var offsetX = cos(offsetDirection)*tan(DegreesToRadians(Double(paddingBetweenButtons)))*bigSize/2
            var offsetY = sin(offsetDirection)*tan(DegreesToRadians(Double(paddingBetweenButtons)))*bigSize/2

            buttonCenter.x += offsetX
            buttonCenter.y += offsetY

            // Create mask for outer rim of slice to a circular form (from triangle to pizza slice)
            let outerCircleRadius = bigSize/2;
            var bigCircle = UIBezierPath(arcCenter: self.center, radius: bigSize/2, startAngle: startAngle , endAngle: endAngle, clockwise: false);
            bigCircle.addLineToPoint(buttonCenter)
            bigCircle.closePath()

            // Take padding into consideration when creating mask
            let tmpBigSizeX = (bigSize+2*abs(offsetX))
            let tmpBigSizeY = (bigSize+2*abs(offsetY))

            // Create mask for inner rim of slice to a circular form (from pizza slice to donut slice)
            let smallSize = bigSize-centerButtonSize-centerButtonPadding
            let innerCircleRadius = outerCircleRadius-bigSize/2/2;
            var smallCircle = UIBezierPath(arcCenter: self.center, radius: smallSize, startAngle: 0 , endAngle: DegreesToRadians(360), clockwise: false);

            // Apply masks for everything but the donut slice shape
            var buttonShape = CAShapeLayer()
            var maskLayer = CAShapeLayer()
            var maskPath = CGPathCreateMutable();

            CGPathAddRect(maskPath, nil, CGRectMake(outerCircleRadius-tmpBigSizeX/2, outerCircleRadius-tmpBigSizeY/2, tmpBigSizeX, tmpBigSizeY));
            CGPathAddPath(maskPath, nil, smallCircle.CGPath);
            maskLayer.path = maskPath;
            maskLayer.fillRule = kCAFillRuleEvenOdd;

            buttonShape.path = bigCircle.CGPath
            buttonShape.mask = maskLayer
            buttonShape.fillColor = UIColor(white: 0.90, alpha: 1).CGColor

            // Add icons and labels to the button
            var image = UIImage(named: "menu-icon_users_grey")
            let imageSubLayer = CALayer()
            imageSubLayer.contents = image?.CGImage
            buttonShape.addSublayer(imageSubLayer)

            // Save references to both shape and button
            self.menuButtons.append(UIButton(frame: buttonShape.frame))
            self.menuButtonShapes.append(buttonShape)

            // Add shape to view
            self.layer.addSublayer(buttonShape)
        }
    }

}

Lines of interest are in the bottom of the custom UIControl under the comment:
"Add icons and labels to the button"

A: You have two options:
The not-so-good one, transform the UIImage in a color and then cast it to CGColor, but since your code snippet is so small, I don't know what is going to work:
let image = UIImage(named: "")
if let realImage = image {
    let color = UIColor(patternImage: realImage)
    shape.fillColor = color.CGColor
}

And the recommended one, create a new layer and set the UIImage on its contents:
let imageSubLayer = CALayer()
imageSubLayer.contents = image?.CGImage
shape.addSublayer(imageSubLayer)

I can't test it right now, so tell me if it works.


text:
Q: Synchronize two input fields , without building an endless loop? I have two input fields which i would like to sync with each other.
Unfortunately, when I add a ChangeListener to each of the TextFields they will trigger each other,
and so create an andless loop.
Ofcourse I could unregister the Listeners, on every change and them put them back,
but is there any Java native approach?
Maybe something with bindings?

A: From general reasoning (i.e. not knowing swt or java): you can add a boolean flag (probably your class member) m_enteredChangeListener, temporary setting it to true in one of your handlers (not both), making the same handler do nothing if it's reentered recursively.


text:
Q: Issues with flickering C# I'm having trouble with a Bitmap flicking when it's moved or resized. I'm basically making a paint type application which will also include layers similar to that of photoshop.
I've set the scroll wheel to zoom/resize the Bitmap and set the middle mouse button to move the panel while it is held down and moving.
I have a panel with a checkered background image which is set to tile. This is so that the background pattern stays the same size when resizing.
This panel is basically used to set the size of a Bitmap and have a background.
Here is a video of of the issue:
https://youtu.be/HRcCGaPmNU0
Here is the script that draws and moves with the irrelevant stuff removed.
 public Canvas()
    {
        InitializeComponent();
        this.SetStyle(ControlStyles.ResizeRedraw, true);
        this.MouseWheel += new MouseEventHandler(Canvas_WheelZoom);
        this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
        this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

    }
 private void panel_DrawArea_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
        Graphics g;
        g = e.Graphics;
        //--------LAYERS--------//
        layerCount = layerBMPs.Count;
        if (layerCount > 0)
        {
            for (int i = 0; i < layerCount; i++)
            {
                Console.WriteLine("Draw Layer");
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
                g.DrawImage(layerBMPs[i], 0, 0, canvasSize.Width, canvasSize.Height);
            }
        }
        //--------LAYERS--------//

        //--------GRID--------//
        Console.WriteLine("Draw Grid");
        Bitmap gridArea;
        gridArea = new Bitmap(canvasSize.Width, canvasSize.Height);
        Pen myPen = new Pen(Brushes.Black);
        int tileCountX = canvasSize.Width / tileSize.Width;
        int tileCountY = canvasSize.Height / tileSize.Height;
        for (int i = 0; i < tileCountX; i++)
        {
            g.DrawLine(myPen, i * tileSize.Width * canvasScale, 0, i * tileSize.Width * canvasScale, canvasSize.Height);
        }
        for (int j = 0; j < tileCountY; j++)
        {
            g.DrawLine(myPen, 0, j * tileSize.Height * canvasScale, canvasSize.Width, j * tileSize.Height * canvasScale);
        }
        //--------GRID--------//
        g.Dispose();
        myPen.Dispose();
        }
    //Clicking the canvas
    private void panel_DrawArea_MouseDown(object sender, MouseEventArgs e)
    {
        //Detect which mouse button is pressed
        switch(MouseButtons)
        {
            case MouseButtons.Middle:
                //Move Canvas
                canvasMove = 1;
                canvasMoveX = e.X;
                canvasMoveY = e.Y;
                break;
        }
    }
    private void panel_DrawArea_MouseMove(object sender, MouseEventArgs e)
    {
        //Detect which mouse button is pressed
        switch (MouseButtons)
        {
            case MouseButtons.Middle:
                //Move Canvas
                if (canvasMove == 1)
                {
                    int xPos = Cursor.Position.X - canvasMoveX - this.Location.X;
                    int yPos = Cursor.Position.Y - canvasMoveY - this.Location.Y - 16;

                    drawAreaPos = new Point(xPos, yPos);

                    panel_DrawArea.Refresh(); <--- This makes it flicker really fast when moving or resizing.
                    //panel_DrawArea.Invalidate(); <--- Does nothing
                }

                break;
        }
    }
    private void panel_DrawArea_MouseUp(object sender, MouseEventArgs e)
    {
        switch (MouseButtons)
        {
            case MouseButtons.Middle:
                //Move Canvas
                canvasMove = 0;
                break;
        }
    }

So basically what happens here is that the list contains bitmaps. The loop in the draw event draws those bitsmaps. Once all of them have been drawn then the grip is drawn on top.
I've tried double buffering and endless ammounts of playing about with no success.
Is anyone able to help?
Thanks


text:
Q: How to use local variable of whitespace array in chef template resource I am trying to use whitespace arrays in chef template, like below and when I run the chef-client to execute the recipe getting an error saying: option variables must be a kind of [Hash]! below is recipe file
abc = node['abc']
def1 = node['def']
abc_sit = abc['sit']
def_sit = def1['sit']
%w{abc_sit def_sit}.each do | client |
  template "/etc/#{client}.sh" do
   source 'tunnel.erb'
   owner 'root'
   group 'root'
   variables ("#{client}") --> At this line I am getting error
 end
end

The error I am getting when I run the chef-client:

option variables must be a kind of [Hash]! You passed "abc_sit"

A: As it says, you have to pass in a Hash. Perhaps something like variables myclient: client and then <%= @myclient %> in the template.


text:
Q: free disk space via cmd batch file need a cmd command to use it in batch file to get free disk space on C drive after and before removing some folders in .txt format or need to know a space for specific folders and also export it in .txt folder

A: Since cmd.exe's set /A-math is limited to signed 32bit integers, you could get into trouble calculating free space on an empty 4TB drive. A way around is to use PowerShell for the calcuation.
@Echo off

For /f "tokens=2 delims==" %%A in (
  'wmic logicaldisk where "DeviceID='C:'" get FreeSpace /format:value'
) Do Set FS1=%%A

:: Delete something
Del /F /A /Q /S "%tmp%\*" >Nul 2>&1

For /f "tokens=2 delims==" %%A in (
  'wmic logicaldisk where "DeviceID='C:'" get FreeSpace /format:value'
) Do Set FS2=%%A

set FS
:: Let PowerShell do the calculating
powershell.exe "\"{0,10} GB freed\" -f [math]::round(($env:FS2-$env:FS1)/(1GB),2)"

Sample output:
FS1=87454994432
FS2=85188575232
     2,11 GB freed


text:
Q: How can I generate randomness with commands in Bedrock Edition? What is the most efficient way to get a random output with my commands? In Java there are tons of ways to do this, but a lot of them don't seem to work for Bedrock Edition.

A: @r is an obsolete method. It is really only effective for up to 10 outputs.
The standard way to get a random output in Bedrock Edition is /scoreboard players random, an MCBE only command.
Syntax:
scoreboard players random <player: target> <objective: string> <min: int> <max: int>

This will set a scoreboard number to a random value between min and max.

A: Concept
The @r selector can be used to pick a random player. What some people do not know, though, is that if you specify another type other than player you can have it select things other than players.
Commands
Lets say I want to have my machine output white or black wool. We have 2 command blocks with a tick delay of 7 (if we don't have a tick delay it will sometimes fail) with the command:
setblock ~ ~1 ~ air

Now chains attached to them with these (one will be white, one black):
setblock 5 5 5 wool 0

and
setblock 5 5 5 wool 14

Now above the original impulse command have air and a block above that bedrock with armor stands on top of each. Name the armor stands the same thing. I will use test.
Now somewhere else have a command block that says:
execute @r[type=armor_stand,name="test"] ~ ~ ~ setblock ~ ~-2 ~ redstone_block

Now when that command block is activated, it will place either a white or black wool block at 5, 5, 5!


text:
Q: Xdebug do netbeans não funciona Estou tentando usando o Xdebug do Netbeans. Faço a marcação da linha, e depois clico em "Depurar arquivo". No entanto, não me acontece nada! Tem alguma configuração especifica que devo fazer? Quando faço esse procedimento, no canto direito do Netbeans fica "Aguardando conexão (netbeans-xdebug)".

A: Andraw, sou iniciante em php e passei pelo mesmo problema, pesquisei, pesquisei, e deu consegui!
Para verificar certinho o caminho para colocar a dll do xdebug, utilize o próprio site do xdebug, onde tem uma parte de Instruções de instalação*, te fornecera o caminho correto, como disse o @rray devera começar aparecer os erros em laranjado.
php.ini
(no meu php.ini não tinha nada referente a XDebug)
[XDebug]
zend_extension = C:\xampp\php\ext\php_xdebug-2.4.0-5.6-vc11.dll
xdebug.remote_enable=1
xdebug.profiler_enable=1

O caminho foi o que o site com as instruções me gerou:

You're already running the latest Xdebug version
But here are the instructions anyway:

*

*Download php_xdebug-2.4.0-5.6-vc11.dll

*Move the downloaded file to C:\xampp\php\ext

*Update C:\xampp\php\php.ini and change the line
zend_extension = C:\xampp\php\ext\php_xdebug-2.4.0-5.6-vc11.dll

*Restart the webserver

*Cole na caixa de texto do site, a saída de phpinfo() (pode ser o codigo fonte da pagina HTML gerada, ou a saída do php -i)
Qualquer dúvida pode perguntar, fiquei tentando resolver isso pode ter faltado alguma coisa :)

A: adicione a seguinte seção no seu php.ini
[XDebug]
zend_extension_ts = "./php/ext/php_xdebug<version>.dll"
xdebug.remote_enable=1
xdebug.remote_autostart = 1
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000
xdebug.remote_handler=dbgp
xdebug.profiler_enable=1
xdebug.profiler_output_dir="<XAMPP_HOME>\tmp"

Fonte: https://netbeans.org/kb/docs/php/configure-php-environment-windows.html


text:
Q: Programatically instrument an app for use with Quamotion WebDriver I'm automating an iOS app using Quamotion WebDriver. This app uses a couple of custom controls which don't work very well with Apple's UI Automation (i.e. they get reported as XCUIElementOther* with very little information about what they are/which text they display). Hence, I want to use App Automation/instrumentation to automate my app.
I'm able to successfully launch the Spy for this app in App Automation mode.
I now want to automatically instrument this app. Can I use the Quamotion.Malaga NuGet package to do this?

A: You don't need to instrument the application yourself. The Quamotion WebDriver does the check and instruments the application if needed.
The workflow is like this:

*

*You add your application to the Quamotion app repository (local).

*You create a new session, specifying the App ID and version of your application.

You can use this code:
// Add your application to the app repository
Application application = WebDriverExtensions.AddApplication(yourAppPath);

// Start an application session
AppCapabilities appCapabilities = new AppCapabilities(
         deviceId: yourDeviceId
         appId: application.AppId,
         appVersion: application.Version,
         clearApplicationSettings: false
);
appCapabilities.ReuseSession(true);
AppDriver = new AppDriver(appCapabilities);


text:
Q: What is more optimal way of inserting image I am using laravel. Speaking of load time on a website, I was wondering which method would be more optimal for adding images. Say I am uploading about 10 images per post. This maybe stupid but here are the two thoughts

*

*Make a field in tables named 'image' 'image1' and so on until 'image10'.

*Create a separate table for image storage with the 'post_id' being the relation to images table.

So i was wondering which would be slower in terms of running queries. For an example I have this query.
$id = Post::first();
Image::where("post_id", "=", $id);

In that exmaple, I am taking all the images from the Image table which is related to the post.
Now for the second query
$second = Post::findOrFail($id);

And foreach loop it in our blade view and take the image1 to image10.
Which would be better in terms of query.
Now one thing I have noticed on my recent build is that it takes sometime to process some of the queries I had in the application and it takes about 250ms to just process the request and 15ms for downloading the content. I shortened some of my queries and optimized the code/query and I got it to 150ms processing time.
Which query will take shorter time to process and which will help cut down load time.
Note: this is completely a thought and the examples used above are written in real-time and does not reflect any actual project coding.

A: You're looking for Eloquent Relationships
In your post model you can define the images relationship to tell Laravel how to find images. Using the separate images table is the best way to associate an arbitrary number of images per post.
in Post.php class:
public function images()
{
    return $this->hasMany(Image::class, 'post_id');
}

Then to replace your first example you can do
$post = Post::first();
$images = $post->images; // this will be an array of all the images associated with that post.

Since you're asking about performance, you should look up eager loading. Basically once a relationship is defined you can tell laravel to load all of the relevant records.
$posts = Post::with('images')->get();

This line of code will get all of the posts and all of the images associated with each post. It will run two queries; one to get all the posts and one to get all the images.
SELECT * FROM POSTS
SELECT * FROM IMAGES where post_id IN (results from above query)

Then you can access all the images in a foreach loop without worrying about additional queries
@foreach($posts as $post)
    {{ $post->images }}
@endforeach

A: it's better to user seconde option:
Create a separate table for image storage with the 'post_id' being the relation to images table.
and use
in Post.php class:
public function images()
{
    return $this->hasMany(Image::class, 'post_id');
}

to fetch them back
because by this way you can update,delete or insert new images limitless in you database

A: If you do have multiple Image Make A Different Model
Post.php
public function images()
{
    return $this->hasMany(Image::class, 'post_id');
}

Image.php
public function post()
{
    return $this->belongsTo(Post::class, 'post_id');
}

This is best way
This allows you to save multiple image, no matter how many images you have


text:
Q: Converting nested for loops with a depth of n I've been trying to build a recursive function to replace the following n deep nested loop algorithm, the depth will change based on the length of the combination anywhere for 2 to n (most likely less than 20)
    Edit: removed confusing code

I have searched this site  and found  Converting nested loop and More nested loop conversions but I can't seam to tweak them to output what I need.
or I could just be looking at it wrong and not needing a recursive function at all.
trying to do this in C#, thanks for any help.
Edit: hope this explains things a bit more.
What I'm trying to do is find the best combination of options and amounts to give me maximum return without going over budget.
So I have a cut down list of options that meets my requirements, then I want to feed them into this program/script to get the best combination with highset return, I also need to reduce my risk by buying more than one option normally 3-10
So below is my full code so far fixed at a depth of 3:
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace Combinations
    {
        class Program
        {
            static void Main(string[] args)
            {

                Stopwatch stopwatch = new Stopwatch();

                List<option> options = new List<option> {
                            new option("A", 6.50, 0.18, 25000, 3),
                            new option("B", 23.00, 0.59, 25000, 3),
                            new option("C", 27.50, 0.60, 25000, 3),
                            new option("D", 21.00, 0.40, 25000, 3),
                            new option("E", 16.00, 0.30, 25000, 3),
                            new option("F", 7.00, 0.13, 25000, 3),
                            new option("G", 22.50, 0.38, 25000, 3),
                            new option("H", 27.00, 0.45, 25000, 3),
                            new option("I", 13.00, 0.20, 25000, 3),
                            new option("J", 20.50, 0.30, 25000, 3),
                            new option("K", 17.50, 0.25, 25000, 3),
                            new option("L", 10.50, 0.15, 25000, 3),
                            new option("M", 29.00, 0.41, 25000, 3),
                            new option("N", 26.50, 0.37, 25000, 3),
                            new option("P", 15.50, 0.21, 25000, 3),
                            new option("Q", 16.00, 0.20, 25000, 3),
                            new option("R", 10.00, 0.12, 25000, 3),
                            new option("S", 25.00, 0.30, 25000, 3),
                            new option("T", 27.00, 0.32, 25000, 3),
                            new option("U", 22.00, 0.25, 25000, 3),
                            new option("V", 26.50, 0.30, 25000, 3),
                            new option("W", 27.00, 0.30, 25000, 3),
                            new option("X", 14.50, 0.16, 25000, 3),
                            new option("Y", 28.50, 0.31, 25000, 3),
                            new option("Z", 28.50, 0.30, 25000, 3)
                        };
                stopwatch.Start();
                IEnumerable<List<option>> combinations = GetCombination(options, 3);
                stopwatch.Stop();
                Console.WriteLine("Combinations - Time elapsed: {0}", stopwatch.Elapsed);

                stopwatch.Start();
                bestFit(combinations);
                stopwatch.Stop();
                Console.WriteLine("Best Fit - Time elapsed: {0}", stopwatch.Elapsed);

                Console.ReadKey();
            }

            static IEnumerable<List<option>> GetCombination(List<option> list, int _size)
            {
                double count = Math.Pow(2, list.Count);
                List<option> combination = new List<option>();

                int size = 0;

                for (int i = 1; i <= count - 1; i++)
                {
                    for (int j = 0; j < list.Count; j++)
                    {
                        if (((i >> j) & 1) == 1)
                        {
                            combination.Add(list[j]);
                            size++;
                        }
                    }

                    if (size == _size)
                    {
                        yield return combination;
                    }
                    combination.Clear();
                    size = 0;
                }
            }

            static void bestFit(IEnumerable<List<option>> combinations)
            {
                double max = 0d;
                double results = 0d;
                double total = 0d;
                string output = "";
                string tmpOutput = "";

                int y0 = 0;
                int y1 = 1;
                int yn = 2;

                foreach (var combination in combinations)
                {
                    option A1 = combination[y0];
                    for (int x1 = A1.lower; x1 < A1.upper; x1++)
                    {
                        option A2 = combination[y1];
                        for (int x2 = A2.lower; x2 < A2.upper; x2++)
                        {
                            option An = combination[yn];
                            for (int xn = An.lower; xn < An.upper; xn++)
                            {
                                int[] counts = { x1, x2, xn };
                                int i = 0;
                                foreach (option objOption in combination)
                                {
                                    results += objOption.bid * 100 * counts[i] / objOption.cash;
                                    total += (objOption.strike - objOption.bid) * 100 * counts[i];
                                    tmpOutput += objOption.symbol + " STO " + counts[i].ToString() + " @ $" + objOption.strike + ", ";

                                    i++;
                                }

                                if (results > max && total < A1.cash)
                                {
                                    output = tmpOutput.Remove(tmpOutput.Length - 2) + " for a gain of " + results*100 + "% using a total of $" + total;
                                    max = results;
                                }
                                results = 0d;
                                total = 0d;
                                tmpOutput = "";
                            }
                        }
                    }

                }
                Console.WriteLine(output);
            }
        }

        class option
        {
            public string symbol { get; set; }
            public double strike { get; set; }
            public double bid { get; set; }
            public double cash { get; set; }
            public int lower;
            public int upper;

            public option(string _symbol, double _strike, double _bid, double _cash, int _trades)
            {
                this.symbol = _symbol;
                this.strike = _strike;
                this.bid = _bid;
                this.cash = _cash;

                double tradeCash = _cash / _trades;

                this.lower = (int)((0.25 * tradeCash) / ((_strike - _bid) * 100));
                this.upper = (int)((1.25 * tradeCash) / ((_strike - _bid) * 100));

            }
        }
    }

This should give an output of:
Combinations - Time elapsed: 00:00:00.0002575
A STO 15 @ $6.5, B STO 3 @ $23, D STO 4 @ $21 for a gain of 2.428% using a total of $24443
Best Fit - Time elapsed: 00:00:11.9196411

hope this help to clear things up.

A: it seems as if you are only using the for loops to produce your count entry. I would first begin by refactoring this part out into something like this:
public struct Bound
{
    public int Lower { get; set; }
    public int Upper { get; set; }
}

public static class Counting
{
    public static IEnumerable<int[]> Indizes(this Bound[] bounds)
    {
        return Indizes(bounds, 0);
    }

    static IEnumerable<int[]> Indizes(this Bound[] bounds, int index)
    {
        if (index >= bounds.Length)
            yield return new int[] {};
        else
        {
            foreach(var comb in Indizes(bounds, index+1))
            {
                for (var i = bounds[index].Lower; i < bounds[index].Upper; i++)
                {
                    var newArr = new int[comb.Length + 1];
                    Array.Copy(comb, 0, newArr, 1, comb.Length);
                    newArr[0] = i;
                    yield return newArr;
                }
            }
        }
    }
}

remark mostlikely you can get this faster but I think it shows you how you can do such thinks using recursion
With something like this (replace the Bound struct with your data-structure - it's only in there so I could test my code) your insane-loop simplifies to:
   foreach(var combination in combinations)
   {
        foreach (var counts in Counting.Indizes(combination))
        {
            int i = 0;
            foreach (myClass objMyClass in combination)
            {
               results += objMyClass.a * 100 * counts[i] / objMyClass.b;
               total += (objMyClass.c - objMyClass.a) * 100 * counts[i];
               tmpOutput += objMyClass.symbol + " count " + counts[i].ToString() + ", ";
               i++;
            }
            // ...
        }
   }

for the rest I don't understand your code enough to give any advice


text:
Q: Error: object references an unsaved transient instance I am using Hibernate, and I got the following error:
org.hibernate.TransientObjectException: object references an unsaved transient instance-save the transient instance before flushing: db.Concern
I created an object of the Concern entity, where I did the following:
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "concernId")
private Concern concern;

A: When using Hibernate or any other JPA provider, setting cascade = CascadeType.ALL causes persist and update and other operations being cascaded down to child relationships.
In addition by default @OneToOne relationships are FetchType.Eager. So you can either save  concern explicitly or you can remove fetch = FetchType.LAZY from the annotation .
You are probably saving some other object when this error is thrown. So before saving that object save the concern object and then the other object.


text:
Q: Rails twitter gem causing error Missing required parameter: status I am using twitter gem with rails in order to retrive the user timeline and post an update:
  def index
    @tweets = Twitter.home_timeline
  end

  def tweet
    text = params[:text]
    Twitter.update(text) unless text = nil
  end

The view which sends the request via jquery/ajax:
<input type="text" class="tweet-box" placeholder="tweet something" />
<input type="submit" class="tweet-button" value="tweet" />

<script type="text/javascript">
    $(".tweet-button").on('click',function(e){
        e.preventDefault();
        $.post('/twitters/tweet', { text: $(".tweet-box").val() });
    });
</script>

finally the routes:
get "twitters/index"
post "twitters/tweet"

getting the timeline works fine, however when trying to send the update, i get this error:

Missing required parameter: status

What is the problem?
Thanks

A: In my case with the same error message, it turned out that my equivalent of your text variable was an empty string.  You check for nil?  Try checking for empty?

A: "unless text = nil"
This is setting text TO nil, so there is no text being passed into update()
A good habit is to always put the literal on the left:
nil == text
That way if you for get == and do = it will fail because you can't assign to a literal.
try either "unless text == nil" or "unless text.nil?"


text:
Q: Should a function which can fail only due to integer overflow be noexcept? The full question fits the title. Here's a quick example:
constexpr int increment(int const value) /*noexcept?*/ {
  return value + 1;
}

As far as I know, noexcept should be interpreted as "nofail" when deciding whether to mark a function with it or not. Therefore, no possible situation for throwing isn't the only reasoning which must be considered.
I'm not using C++20 so my signed overflows aren't defined yet. :)

A:
As far as I know, noexcept should be interpreted as "nofail"

That's not correct.  noexcept literally means "I promise this function will never throw an exception."  There are myriad other types of failures, such as segmentation faults, illegal instructions, the calling of pure virtual functions, integer divide by zero, not to mention "Bob in accounting told me all our customer numbers consist only of digits, but I just found out our very first customer's ID was actually Q001 and it doesn't parse."  None of those will necessarily result in an exception, and neither will signed integer overflow, so functions failing in those ways can still be noexcept even though they can fail--they just can't throw C++ exceptions.
You may then wonder, "What happens if an exception is thrown by a noexcept function?"  In that case, std::terminate() will be called, and your program will end.

A: noexcept is just your "promise" that the function will never allow an exception escaping from it, and the meaning is that if that instead happens your code will stop right there by calling std::terminate instead of allowing the exception to escape.
Knowing that a function will never throw an exception allows the compiler to generate more efficient/compact code in the caller and allows the creation of more robust software (a software that immediately terminates when something that was not designed to handle happens is more robust that software that instead keeps running doing random things... this is something that many young programmers are confused about).
Exceptions unfortunately are not the only source of failures in C++, where you have the big elephant int the room of "undefined behavior", so writing truly robust software in C++ is an extremely difficult task because you should also avoid every potential undefined behavior (and that's close to impossible to do; for example can generate undefined behavior any integer math operation, any use of iterators, any array access, any pointer access, any uninitialized variable, any multiple unsequenced side effect to the same memory, any race condition... etc. etc.).
Note of course that even a perfectly "safe" low level language that has no undefined behavior but guaranteed runtime errors instead would be no "silver bullet" for writing truly robust software. The reason is that you can have sort of "undefined behavior" at a more logical level if your algorithms do not handle the way you wanted all cases that are presented to them.
In other words there's not much of a difference for the end user if your program does random things because of C++ undefined behavior or because you caught and handled an exception that was not sourcing where you thought it was coming from (what nothrow wants to protect you from) or because your code simply didn't consider and handled that the customer contact data could have and empty phone number.
Undefined behavior concept of course is bad, and is there because allows generation of faster code. In my opinion it is debatable this should be the default in a programming language; other languages preferred a safer default environment and instead allow specifically marked "fast and dangerous" zones where the requirement is that a programmer never makes any low-level mistake.


text:
Q: Android setImageBitmap on onActivityResult don't work sometimes I have an ImageView and want to set imagebitmap for it when receive data on onActivityResult().
But sometimes setImageBitmap() don't work. I don't know why? Can anyone help me to fix this issue? I tested on Galaxy S2 NTT Docomo.
This is my code :
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 0) {
           bitmap = .... //I got bitmap by some function here, data get from Intent data below
           imgUpload.setImageBitmap(bitmap); //imgUpload is an ImageView I init it onCreacte function

A: Add this on Your onResume() also
imgUpload.setImageBitmap(bitmap);

A: I have the same problem. sometimes, when you get to this line, the image is not saved yet. ( saving a pic can take some time).
Put your function that create and save your bitmap in an AsyncTask, and display the thumb in postExecute


text:
Q: Problema con Pivot con query en Mysql tengo mi tabla:

y necesito convertirla en este:

lo que realice fue algo como esto,
pero pienso que debe haber otra forma mejor, ademas que no entiendo porque me aparece un espacio en blanco en la segunda fila:
                SELECT
                    (
                        CASE
                            WHEN P.anno='2011'
                            THEN P.anno
                            ELSE NULL
                        END
                    ) AS 'ANO',
                    (
                        CASE
                            WHEN P.anno='2011' AND P.t_mes_01
                            THEN 'ENERO'
                            ELSE NULL
                        END
                    ) AS 'MES',
                    (
                        CASE
                            WHEN P.anno='2011' AND P.t_mes_01 = P.t_mes_01
                            THEN P.t_mes_01
                            ELSE NULL
                        END
                    ) AS 'VENTA_REAL'

                FROM    import_ventas_008 P

                UNION

                SELECT
                    (
                        CASE
                            WHEN P.anno='2011'
                            THEN P.anno
                            ELSE NULL
                        END
                    ) AS 'ANO',
                    (
                        CASE
                            WHEN P.anno='2011' AND P.t_mes_02
                            THEN 'FEBRERO'
                            ELSE NULL
                        END
                    ) AS 'MES',
                    (
                        CASE
                            WHEN P.anno='2011' AND P.t_mes_02 = P.t_mes_02
                            THEN P.t_mes_02
                            ELSE NULL
                        END
                    ) AS 'VENTA_REAL'

                FROM    import_ventas_008 P

                UNION

                SELECT
                    (
                        CASE
                            WHEN P.anno='2011'
                            THEN P.anno
                            ELSE NULL
                        END
                    ) AS 'ANO',
                    (
                        CASE
                            WHEN P.anno='2011' AND P.t_mes_03
                            THEN 'MARZO'
                            ELSE NULL
                        END
                    ) AS 'MES',
                    (
                        CASE
                            WHEN P.anno='2011' AND P.t_mes_03 = P.t_mes_03
                            THEN P.t_mes_03
                            ELSE NULL
                        END
                    ) AS 'VENTA_REAL'

                FROM    import_ventas_008 P

                UNION

                SELECT
                    (
                        CASE
                            WHEN P.anno='2011'
                            THEN P.anno
                            ELSE NULL
                        END
                    ) AS 'ANO',
                    (
                        CASE
                            WHEN P.anno='2011' AND P.t_mes_04
                            THEN 'ABRIL'
                            ELSE NULL
                        END
                    ) AS 'MES',
                    (
                        CASE
                            WHEN P.anno='2011' AND P.t_mes_04 = P.t_mes_04
                            THEN P.t_mes_04
                            ELSE NULL
                        END
                    ) AS 'VENTA_REAL'

                FROM    import_ventas_008 P

A: ¿Tal vez buscas algo así? Y si espacio en blanco en la segunda fila

SELECT anno,CONCAT(anno,'-01-01') fecha,'Enero' mes_de_corte,t_mes_01 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-02-01') fecha,'Febrero' mes_de_corte,t_mes_02 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-03-01') fecha,'Marzo' mes_de_corte,t_mes_03 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-04-01') fecha,'Abril' mes_de_corte,t_mes_04 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-05-01') fecha,'Mayo' mes_de_corte,t_mes_05 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-06-01') fecha,'Junio' mes_de_corte,t_mes_06 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-07-01') fecha,'Julio' mes_de_corte,t_mes_07 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-08-01') fecha,'Agosto' mes_de_corte,t_mes_08 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-09-01') fecha,'Septiembre' mes_de_corte,t_mes_09 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-10-01') fecha,'Octubre' mes_de_corte,t_mes_10 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-11-01') fecha,'Noviembre' mes_de_corte,t_mes_11 venta_real  FROM import_ventas_008 UNION
SELECT anno,CONCAT(anno,'-12-01') fecha,'Diciembre' mes_de_corte,t_mes_12 venta_real  FROM import_ventas_008;


text:
Q: PII violation emails even while its being fixed and shows no PII in reports I used customTask in Universal Analytics tags via tag Manager to tackle PII. After that, I regularly monitored reports in Google Analytics and found all the hits were cleaned.(i.e. PII redacted)
But I still get emails from adwords-noreply@google.com, that some of the URLs  linked to particular 'remarketing lists' are violating PII.
Now there's no way to confirm that PII is actually violated. I dont know where I am supposed to look, in which section (of Adwords account or Analytics account) can I see the URLs being passing PII info to Google?
This is what I'm seeing in GA reports:
https://siteurl/u/password-reset/reset?email=ja[ REDACTED EMAIL]l.com&authenticationCode=8127489044212
this is what is sent in the violation email:
https://siteurl/u/password-reset/reset?email=jack@emabell.com&authenticationCode=8127489044212
If I have redacted the PII using tag manager, do I still need to do something in the Adwords account ?

A: It turns out that custom fields cannot be added with tag type- 'AdWords Remarketing', due to which I couldn't run my redacting logic using 'customTask'.
Hence I created a customHTML tag and fired it on the 'Page View' event which filtered all the URLs

A: PII in GA is of a serious concept. Eventually, Google might delete your data.
I usually solve this by using filters in GA View. This is like a last line of defence
Guide on how to setup is here
https://www.internetrix.com.au/blog/google-analytics-pii-safe-guarding-emails-2/


text:
Q: Fix button's position on screen How do I nail a button down to the screen and fix it there? When you open the keyboard, the button rises above the keyboard, when closed, it goes back down to the screen. I need it to hide under the keyboard, that is, it was constantly on a fixed place.
The code fragment that is responsible for the button:
<RelativeLayout
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/confirm_order_layout">

        <Button
            android:id="@+id/confirm_order"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="@drawable/button_style_green"
            android:text="@string/confirm_order"
            android:textSize="18dp"
            android:textStyle="bold" />

    </RelativeLayout>

A: add below line in activity area of menyfest file.
android:windowSoftInputMode="adjustResize"


text:
Q: Accessing a Class through ActiveRecord::Base I am writing a ruby gem that is importing data to ActiveRecord, taking in the environment and Class the user wants to put in the data.
I am able to connect to the environment with ActiveRecord::Base.establish_connection(...), but I can not figure out how to access the passed in Class to do, say, Location.create(...).
I don't want to pass it in via execute, because it'll skip validations, but I'm doubting I can access the ActiveRecord class.
I found an article that I thought would help (http://erikonrails.snowedin.net/?p=212), but with this I am putting:
ActiveRecord::Base.const_get(model).create(attributes)

and getting
uninitialized constant ActiveRecord::Base::Location (NameError)

When I try the above with ActiveRecord::Base.connection.const_get(model) I just get a huge object back.  I'm just looking for a way to get to the class like how if I was in Rails I could just call User.create().  Any help would be much appreciated.

A: You can use String#constantize and String#classify:
=> cons = "user".classify.constantize
#> User
=> cons.create()

A: There is no need to call this on ActiveRecord::Base, because that model is a subclass of ActiveRecord::Base, but not a constant in the ActiveRecord::Base namespace.
Instead just call it on Module:
Module.const_get(model).create(attributes)


text:
Q: Alternative to PHP includes? I have a client who has built her entire site using html extensions. As such, renaming files and changing links just isn't an option. I need a way to include a footer file into each .html page. I've read a bit on the subject and initially thought html includes would be fine, but then realized they are only valid if the file extension is .shtml or something else. So are there any other alternatives? Any help is greatly appreciated.

A: Alternatives are all ugly :

*

*insert header and footer using iFrames

*use a HTML editor having template feature like Dreamweaver

*use a script of yours that will edit all HTML pages adding the header and footer

*insert header and footer using Javascript

*...

All of those are very bad because the HTML page has no real header/footer (iframes, javascript), or it is hard to maintain.
Of course the best way is to make easy to maintain real HTML pages. That is turn the "changing links just isn't an option" into "let's change extensions and links". Some tools can help you to do that.

A: An .htaccess rule would work, if you setup 301 redirects it will notify search engines of your change and there should not be any seo repurcussions.  This will redirect that for you.  The other benefit for seo is php includes are server side so the html will be passed to the search engine spider for index, where javascript will execute after the document loads, and most spiders are not going to execute your JS, just index the html passed down from the server.
    RewriteEngine on
RewriteBase /
RewriteRule (.*).htm$ /$1.php [R=301,NC]

A: You could accomplish this with javascript by creating a footer template in a separate html file and then dynamically load the footer template markup into each page through some javascript code.
Although, you would still have to modify each html file that you want a footer to appear on by adding the javascript code which adds the footer.
Other than that, there is no equivalent in html to includes or master pages.  These are server side concepts.

A: Use javascript or preferrably jquery.  With this function you can just load external files into a div with 1 line.  http://api.jquery.com/load/

A: I would suggest a major rewrite as some pointed out but, given your situation that you can't change the technology used, I am assuming it's a reasonably big site too, my suggestion is to use sed to include the footer code as you mentioned into each HTML file.
Either that or add the footer using Javascript, which is not a bad idea in your situation.

A: Maybe you can write a script that will append the footer to all the html files. So basically just copy the whole set of html files to a dev location and then run the script to output the new files.
Alternatively, copy and paste may be less time-consuming.
Javascript is probably simpler, but doesn't work when the user doesn't have js enabled.

A: Two ways to create client-side includes: javascript and iframe. While using javascript, the search engine will not see the included text. And iframe element must have a fixed width and height.