text:
Q: Raising an event I have a form with two RichTextBoxs on them, I want to raise an event in one to trigger an event on the form which updates something in the other rtb.
Where must I define the EventArgs extended class?
What is and where must my delegate be? Is this the function that is called from the event being raised?
Do these three classes (rtb1, rtb2, form1) need to be in the same namespace?

A: Rather than defining your own delegate you can almost always use the generic EventArgs class, or the Action class as the delegate for your events.  When using one of these you won't need to define any delegate at all, they are already defined by the library.
The delegate is not the function being called, it merely defines the signature of all methods that are called by the event.
The three classes do not need to be in the same namespace, no.  In fact, as a general rule, there are almost no situations (none that I can think of anyway) which would force you to have classes in the same namespace for them to do something.


text:
Q: Corebluetooth, How to get a unique UUID? my question is the UUID of CBPeripheral seems not to be unique.
I have two iPad2, and a bluetooth4.0 device.
The UUID of the bluetooth device differs from the two iPad.
As shown in following images.

Is there any way to find a unique UUID of bluetooth device on iOS device?
I need to find a UUID or mac address that would not change between different devices.
Thank you very much, please help me!!

A: The peripheral uses a random resolvable address that changes at least every 15 minutes, at which point the peripheral will appear to be new. To change this behavior you need to pair with the peripheral, then you will see the UUID and it will be persistent.

A: To answer your question, the UUID is unique given the same pair iDevice-btDevice, but it changes if you change the iOS device, as you noticed in your try.
To reach the goal to have a unique identifier, unfortunately, you have to modify the firmware and add an application identifier.

A: In case when you develop and control Bluetooth 4.0+ device,
Option #1 Assign Bluetooth Address to Device Name and put it in Scan Response
Assign your bluetooth device address as it's device name and broadcast it via Scan Response package.
Scan Response package is a 31 bytes of data that bluetooth device broadcast after master device (e.g. smartphone) send scan request.
Important
Some bluetooth devices allow to set their name without programming, for example HM-10 bluetooth module name can be changed with AT+NAME text command.
Option #2 Send some unique Manufacturer Specific Data in Advertising Data
You can add some unique "Manufacturer Specific Data" in Bluetooth advertising data package and read it from iOS. It's much faster than reading "System ID" attribute from "Device Information Service", as was proposed in other answer, because it does not require connect to bluetooth device.
Long explanation
Advertising data is 31 bytes of data that bluetooth 4.0+ broadcasting to air (before anyone connected to it) at some interval of time (from 20ms to 10s) depending on this device configuration.
Also there is scan response data, it's extra package of 31 byte that bluetooth device broadcast after master device (e.g. smartphone) send scan request. It have same structure as advertising data package.
In total there 31+31=62 bytes of data that we can use.
Advertising data consist of set of advertising data structures (AD struct)
First byte describes the length of AD Struct including 1 byte of data type + variable size payload.
Second byte describes the type of data stored in AD Struct, here list of identifiers.
All later bytes are payload data.
For advertising data is mandatory to include configuration Flags AD Struct (does not concern to scan response), it takes 3 bytes. We have 28 bytes left.
Assuming that you developing your own GATT Service, so you need to specify it identifier in advertising data. Custom GATT Service UUID identifier can be only in 128bit full length format (unlike 16bit and 32bit service identifiers predefined by Bluetooth standard). In advertising data it will consume 2+16=18 bytes. So, We have 10 bytes left.
Now we can defined manufacturer data
2 bytes used for length and data type
first 2 bytes in payload comes for company identifier (as required in document Supplement to Bluetooth Core Specification section 1.4), company identifiers are assigned by Bluetooth Special Interest Group
For testing purposes you can use 0xFF, 0xFF identifier
And using left 6 bytes you can uniquely identify 281,474,976,710,656 devices.
Sample of advertising data, written in C:
#define GAP_ADV_FLAGS                   0x01
#define GAP_ADV_128_UUID                0x06
#define GAP_ADV_MANUF_DATA              0xFF

uint8_t raw_adv_data[31] = {
//  len     type                        payload....

    0x02,   GAP_ADV_FLAGS,              0x06,

//                                      GATT service 128 bit UUID
    0x11,   GAP_ADV_128_UUID,           0x1d, 0x15, 0xee, 0x49,
                                        0x10, 0x78, 0xc8, 0xa3,
                                        0x9f, 0xaa, 0x82, 0x84,
                                        0x8e, 0x28, 0xbe, 0x43,

//                                      2 bytes of company ID
    0x09,   GAP_ADV_MANUF_DATA,         0xff, 0xff,

//                                      6 bytes of unique data
                                        0xff, 0xff,
                                        0xff, 0xff,
                                        0xff, 0xff,
};

PS: Well, if you need to send even more data, you can put in scan response package, which give you extra 31 byte of payload.

A: I was looking for a way to deploy platform-independent, static configurations of BLE devices.  I was getting discouraged (Apple's UUIDs are +/- meaningless, and the MAC/BDADDR which can be obtained on most/all other platforms is not accessible from CoreBluetooth). Fortunately, I noticed that the "Device Information Service" profile (0x180A) contains a "System ID" attribute (0x2A23) which encodes the device's unique MAC/BDADDR address.  I don't know if it is mandatory for a BLE device to expose this service, however.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can someone check my proof that every positive real has a positive nth root? I am studying Abbott, and this proof is based on Abbott's suggestion of using the binomial theorem. This is in chapter 1, so not very many assumptions are allowed.
Notable assumptions: Axiom of completeness, Archimedian principle, binomial theorem, induction.
My proof:

Edit: The reason it is so verbose is that this is a homework assignment and I need to justify every step, otherwise I will lose points.


text:
Q: Recommended GID for users group in Linux (100 or 1000)? I have several GNU/Linux installations that share home and data directories.  Over time some user files in these directories have received the group ID 100 (users group under some variants of Linux), others have the group ID 1000 (also the users group, under other variants).
Now I wish to unify the users group ID between all my distributions, but which one should I choose?
I remember there is a Linux standard, does that give a recommended GID for users?  If not, is there any other recommendation or trend (I am not asking about personal preferences)?

A: LSB specifies some group names, but users is not one of them.
http://refspecs.linux-foundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/usernames.html
On a completely new setup, you might prefer to avoid using 1000.  The way useradd works, it would allocate each user a group, and the numeric identifiers for user and group id will conveniently end up the same.  I would call that the preferred approach for modern multi-user systems (I think older systems defaulted to a shared group like users as the primary group of the user instead).
My users are not necessarily a member of a shared group like this on either Fedora or Debian.  In this case it would be somewhat academic what number is assigned - it would just be another system group which varies between different distributions.  (And another group like bin with no apparent purpose in modern times).
LSB says that UIDs and GIDs 0-99 are statically allocated by the system.  UIDs 100-499 (and on all modern systems 100-999) are supposed to be allocated dynamically.  This is confirmed by the Debian Policy Manual; it just doesn't have the virtue of being strictly true at the current time.
I'm not really sure what it means that I see users as 100 on a Debian system.  It might not be a safe assumption to make, in case the order the groups are allocated in changes for some reason.
On Fedora, it's pretty safe to assume you can allocate id 100, because the automatic allocation of id's 100-1000 actually counts down.  (To be clear, this is the opposite of Debian).
Possible options considering your information so far:

*

*Stop using the group users.  But probably you have some shared files and you'll need to allocate a shared group ID anyway.

*Use 100 and hope it doesn't break if you [re]install a system that allocates system IDs counting up from 100 like Debian.

*Use something high enough like 10000, which would never end up allocated automatically.

*Use 1000 if none of your existing systems use it for something else and you never plan on adding a new OS which accesses your filesystems.[*]

*Allocate a free ID towards the start of the range 500-1000.  (Fedora over five years ago, counted down from 499-100 instead of 999-100, so I can't exclude that you have allocations like that).

[*] Once a system is installed, you can add users with any IDs you want.  But my worry is that the initial user created by an OS installer is likely to have ID & GID 1000, not allow you to change them, and particularly if it doesn't create a root user then changing its ID later can be quite annoying).
The 10000 option sounds simplest to me.  It would work nicely if you were ever creating a new system, or instructing someone else.  It should also work on your current system.


text:
Q: How to upload multiple images on imageKit from nodeJs app? I'm trying to the images submitted through HTML form and then upload those in the imagekit through node app. I'm completely lost with the configuration. Any help would be greatly appreciated.
const app = express();
const multer = require('multer');
const path = require('path');
const upload = multer({
    dest: "uploads/" // "uploads"
});

var ImageKit = require("imagekit");
var fs = require('fs');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.urlencoded({extended: true}));

var imagekit = new ImageKit({
    publicKey : "public_6ImvGNsOViPhZ*******",
    privateKey : "private_IZ1pjwUR9F********",
    urlEndpoint : "https://ik.imagekit.io/*****/"
});

app.get('/upload', (req, res) => {
    res.render('index')
})

app.post('/upload', upload.single("image"), (req, res) => {
    fs.readFile('uploads/' + req.file.filename, function(err, data) {
        if (err) throw err; // Fail if the file can't be read.
        imagekit.upload({
          file : req.file, //required
          fileName : req.file.filename + '.jpg', //required
          tags: ["tag1", "tag2"]
        }, function(error, result) {
          if(error) console.log(error);
          else console.log(result);
        });
      });
    console.log(req.file.filename);
    res.redirect('/upload');
})

A: You don't need to send your images to the node app and then upload them, you can directly upload your images from the client-side with a backend authentication endpoint. You can use imagekit-javascript sdk for this.
It also has a sample app which you can refer to.

A: First setup a middleware for Multer and inside it set the storage destination to memory:
    module.exports=(req, res, next) =>{
    const uploadFiles = multer({storage:multer.memoryStorage()}).single('image'); //'image' = the input name  in will be in the form
    uploadFiles(req, res, err => {
        if (err instanceof multer.MulterError) { // A Multer error occurred when uploading.
            if (err.code === "LIMIT_UNEXPECTED_FILE") { // Too many images exceeding the allowed limit
            // ...
            }
        } else if (err) {
            // handle other errors
        }

        // Everything is ok.
        next();
    });
}

then in your post request do this:
    exports.addImage = async (req, res, next) => {

    await imagekit.upload({
        file : req.file.buffer, //required
        fileName : req.file.originalname, //required
        folder:'myFolder', // optional
      }, function(error, result) {
        if(error) console.log(error);
        else
        return res.status(200).json({
            message:result
        })
    });
}


text:
Q: Getting and matching values from array I have an array which is like this:
var Data=[{
    "Class":"item1","element":["a","b","c","d","e"],
    "Class":"item2","element":["a","b","c","d","e"],
    "Class":"item3","element":["a","b","c","d","e"],
    "Class":"item4","element":["a","b","c","d","e"]
}];

I have two variables:
var class='item1';
var element='a';

I want a condition that if var class values match "item1" then var element value should be matched with its elements only like:
if (class == Data.Class) then element should be matched with Data.element near it
Any ideas?

A: This should be your data...
var Data= [
    { "Class":"item1","element":["a","b","c","d","e"] },
    { "Class":"item2","element":["a","b","c","d","e"] },
    { "Class":"item3","element":["a","b","c","d","e"] },
    { "Class":"item4","element":["a","b","c","d","e"] },
];

Then you can iterate over it and find your value. Like this
var class='item1';
var element='a';
for(var i = 0; i < Data.length; ++i){
    if (Data[i].Class == class){
        for( var j = 0; j < Data[i].element.length; ++j){
            if ( Data[i].elements[j] == element){
               // do whatever
            }
        }
    }
}

A: First of all you need to fix your data
var Data= [
    { "Class":"item1","element":["a","b","c","d","e"] },
    { "Class":"item2","element":["a","b","c","d","e"] },
    { "Class":"item3","element":["a","b","c","d","e"] },
    { "Class":"item4","element":["a","b","c","d","e"] },
];

Now it is an array of objects.
Then you can look into that array, for example with a for loop
var myclass = "item3"; // class is a reserved word
for (var i=0; i<Data.length;i++) {
    if (Data[i].Class == myclass) {
        // do something with that its data Data[i].element
    }
}


text:
Q: Combine data from different parts of the store tree and dispatch actions? I have data that is read from different endpoints, and is dependent on each other, as if they were relational tables.
An example response from endpoint users_country, for example, could be
[
  { id: 4, first_name: "Mary", last_name: "Jones", country: "Brazil" },
  { id: 7, first_name: "Peter", last_name: "Martinez", country: "US" },
  { id: 14, first_name: "Joe", last_name: "Roland", country: "France" }
]

This is stored in the redux store by a reducer, suppose it's called countries.
Then I also receive data from a ws, handled by a usersPets reducer. I get new row every time a user gets a pet (this is a fictional example)
I get an object { id: 4, first_name: "Mary", last_name: "Jones", pet: "cat" }, and add it to the usersPets data in the redux store
[
  { id: 104, first_name: "Jesus", last_name: "Martin", pet: "cat" },
  { id: 4, first_name: "Mary", last_name: "Jones", pet: "cat" }
]

Then there is an endpoint user_details which is called by user id that gives details for a specific user, that returns more detailed data for that user.
For each of the ids in the redux store, I have to call this endpoint id by id, but only once per id.
Where would I make this call and how to architect this?
I would need to store the ids for which the user_details has already been called separately? how do I do that from the reducer? I can't
Should I handle this from the actions? Dispatch an action every time I have a new row for users_country and users_that_have_pets?
I don't understand how to handle this problem
I think what I need to know is if there is a place in the code outside the components where A) I have access to the store, and know when it updates, and B) can dispatch an action.


text:
Q: How to configure AutoMapper if not ASP.net Application? I'm using AutoMapper in a number of projects within my solution.
These projects may be deployed independantly, across multiple servers.
In the documentation for AutoMapper it says:

If you're using the static Mapper
  method, configuration only needs to
  happen once per AppDomain. That means
  the best place to put the
  configuration code is in application
  startup, such as the Global.asax file
  for ASP.NET applications.

Whilst some of the projects will be ASP.net - most of these are class libraries / windows services.
Where should I be configuring my mappings in this case?

A: The idea that it should only be required once per AppDomain stays the same, as far as I can tell.  I always perform my mappings upon the initialization of the program itself.  While I am not using AutoMapper I am using an IoC library (Windsor) which requires a mapping of sorts and this is done from my program.cs file.  So when the application loads it performs the mapping and because the resolver is static and in a shared library it is available globally.
I don't know if this answers your question or not, but essentially every app has an entry point and if you need your mappings immediately after entry then the entry is the best place to put them.

A: I've elected to store my mappings in separate classes for each project so that they are reusable.
    protected void Application_Start()
    {
        RegisterMaps();
    }

    private void RegisterMaps()
    {
        WebAutoMapperSettings.Register();
        BusinessLogicAutoMapperSettings.Register();
    }

This way I can easily call BusinessLogicAutoMapperSettings.Register() if I were to reuse only my BusinessLogic dll in another application or webservice


text:
Q: Print glossaries EXCLUDING certain types How can I exclude the 'main' glossary from the printglossaries macro, since I want to be able to use one format for the main glossary, and a different one for the remaining.
IE I would like to be able to do something like this:
%Print the main glossary
\glossarystyle{altlist}
\printglossary[type=main]

%Print the remaining glossaries
\glossarystyle{list}
\printglossaries

Therefore, in the above, the command \printglossaries should print the remaining glossaries EXCLUDING the main glossary (ie, for example, acronyms, nomenclature, symbols and user defined glossaries)
I also have a 'hidden' glossary, which I use for some internal document nomenclatures, which I don't want printed at all.
At the moment, in the above, the main glossary is duplicated.

A: \printglossaries is just defined to iterate over all glossaries using:
\forallglossaries{\@@glo@type}{\printglossary[type=\@@glo@type]}

This command has an optional argument that can be used to specify a subset of glossaries to iterate over, so instead of doing \printglossaries, you could do:
\forallglossaries[foo,bar,baz]{\glotype}{\printglossary[type=\glotype]}

To just print the glossaries whose labels are foo, bar and baz.
Here's a more generic approach:
\documentclass{article}

\usepackage{etoolbox}
\usepackage[acronym,symbols,numbers,index]{glossaries}

\makeglossaries

\newglossaryentry{sample1}{name={sample1},description={}}
\newglossaryentry{sample2}{type={symbols},name={sample2},description={}}
\newglossaryentry{sample3}{type={numbers},name={sample2},description={}}

\newacronym{abc}{ABC}{an example acronym}
\newterm{sample}

\newcommand*{\shownlist}{}
\renewcommand*{\glossarypreamble}{\listxadd\shownlist{\currentglossary}}

\newcommand*{\printremaining}{%
  \renewcommand*{\glossarypreamble}{}%
  \forallglossaries{\glotype}{%
    \xifinlist{\glotype}{\shownlist}{}{\printglossary[type=\glotype]}%
  }%
}

\begin{document}

\glsaddall

\printglossary
\printindex

\printremaining

\end{document}

This produces:


text:
Q: How to prevent click event in link or button using Vue directive Hi I'm playing around with vue directives and I'm trying to prevent click event if the element is  or <button> tag. So my question is, is this possible to do using vue directive?
Html

    I'm a link

Vue directive
Vue.directive('noclick', {
    bind( elem, binding, vnode ) {

        let user = {'name': 'John Doe'}

        if( user ) {
            let hasAccess = false

            if( !hasAccess ) {
                if( elem.tagName === 'A' ) {
                    elem.addEventListener( 'click', ( event ) => {
                        //this should prevent the element on click event
                        //but not working

                        event.stopPropagation()
                        event.preventDefault()
                        event.stopImmediatePropagation()
                        return false
                    })
                    return true
                }
            }
        }
    }
}

A: Vue registers the @click event first before v-noclick where you add a second click event listener on that element. When the  is clicked, the displayModal() function will be executed first, then the listener in the v-noclick directive will be executed. If the listeners were registered in the opposite order, then it would probably work.
That aside though, it doesn't look like what you are trying to do should be done inside a custom directive. Instead you can do the same logic in the click handler itself:
Foo

onClick() {
  if (whatever) {
    this.displayModal()
  }
}

A: i couldn't find a vue way to do this. but with js you can use conditional sequence like this

in this case if cond be equals to true then onClick will called


text:
Q: Converting jQuery using CakePHP's Javascript Helper I'm having issues converting the following jQuery/AJAX call to CakePHP's JS Helper.
Here is what currently works:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
    $("#DatabaseServerId").bind("change", function (event) {
        var server_id = $("#DatabaseServerId").val();
        $.ajax({
            async:true,
            dataType:"html",
            evalScripts:true,
            success:function (data, textStatus) {
                $("#DatabaseEnvironmentId").html(data);
            },
            url:"\/apsportal\/servers\/get_environments/"+server_id
            }
        );
    return false;
    });
});
//]]>
</script>

Here is what I have thus far:
$data = $this->Js->get('#DatabaseServerId')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#DatabaseServerId')->event('change',
    $this->Js->request(
            array('controller' => 'servers', 'action' => 'get_environments'),
            array(
                    'update' => '#DatabaseEnvironmentId',
                    'async' => true,
                    'type' => 'html',
                    'dataExpression' => true,
                    'evalScripts' => true,
                    'data' => $data,
            )
    )
);

The issue is that the parameter passed has an array key specified and narrows the usage of this action.
http://my.domain.com/servers/get_environments?data%5BDatabase%5D%5Bserver_id%5D=36

Since server_id is being used in other models, I would rather have this as generic as possible.
Note: I figure if I standardize to the JS Helper, if something changes in the future, I'll only have to change things once.

A: Per the comments, I used raw jQuery instead of CakePHP's methods.


text:
Q: Without Doubt , Firmly I have a question about the usage of "firmly".  If I write these two sentences, one using "without doubt" and one using "firmly":

*

*The experiment was without doubt successful.

*The experiment was firmly successful.

Are sentences 1 and 2 truly the same?

A: Sentence 1 can be adjusted using these words:
without a doubt
OR
undoubtedly
Since the experiment is successful, there is no issue with it in terms of complications and firmly doesn't capture that sense.
Sentence 2: Firmly usually refers to things held in place or it can be used metaphorically to describe thoughts or actions that are strong and unyielding as opposed to loose and weak.
For example:

The cat firmly gripped the mouse.


text:
Q: Rotate a position according to forward I am currently making a climbing detection system that follows the player around and detects the closest point the player can climb. I have a game object that casts rays according to the players position. The rays move with the player but do not rotate around. How can I make them rotate with the player ?

This is the code that draws the rays
void Update()
{
    //Debug.DrawRay();
    raySpace = surfaceWidth / definition;
    raySpaceDividedByTwo = raySpace / 2;
    surfaceWidthDividedByTwo = surfaceWidth / 2;

    for (int i = 0; i < definition; i++)
    {
        for (int y = 0; y < definition; y++)
        {
            raycastCoordinates = new Vector3(
                (this.transform.position.x + (i * raySpace) + raySpaceDividedByTwo) - surfaceWidthDividedByTwo,
                 this.transform.position.y,
                (this.transform.position.z + (y * raySpace) + raySpaceDividedByTwo) - surfaceWidthDividedByTwo);

            //offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
            //raycastCoordinates = Quaternion.AngleAxis(this.transform.rotation.y, Vector3.up) * raycastCoordinates;

            raycastUpHitsList.Add(Physics.RaycastAll(raycastCoordinates, Vector3.up, detectionHeight, LayerMask.GetMask("Water")));
            Debug.DrawRay(raycastCoordinates, Vector3.up * detectionHeight, Color.green, 0.1f);
        }
    }
}

A: This should work:
void Update()
{
    //Debug.DrawRay();
    raySpace = surfaceWidth / definition;
    raySpaceDividedByTwo = raySpace / 2;
    surfaceWidthDividedByTwo = surfaceWidth / 2;

    for (int i = 0; i < definition; i++)
    {
        for (int y = 0; y < definition; y++)
        {
            raycastCoordinates = new Vector3(
                (this.transform.position.x + (i * raySpace) + raySpaceDividedByTwo) - surfaceWidthDividedByTwo,
                 this.transform.position.y,
                (this.transform.position.z + (y * raySpace) + raySpaceDividedByTwo) - surfaceWidthDividedByTwo) * transform.forward;//if this doesn't work, try transform.right instead

            //offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
            //raycastCoordinates = Quaternion.AngleAxis(this.transform.rotation.y, Vector3.up) * raycastCoordinates;

            raycastUpHitsList.Add(Physics.RaycastAll(raycastCoordinates, Vector3.up, detectionHeight, LayerMask.GetMask("Water")));
            Debug.DrawRay(raycastCoordinates, Vector3.up * detectionHeight, Color.green, 0.1f);
        }
    }
}


text:
Q: How does the distance between the center of the north anchor and the north of the node vary by the string length inside the anchor? I measured the distance between the center of the north anchor and north of a node and got 7.20068 pt which is 0.1 inches. This is for a especial case as below:

Here is my code:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary {positioning}
\usetikzlibrary { calc}
\begin{document}

\begin{tikzpicture}
[simple/.style={rectangle,draw, inner sep=0pt,minimum size=10 pt}]

\node[simple] (the node)  {};
\node (the anchor) [red,above] at (the node.north) {$a < b$};

\draw[latex-latex] let \p1 = ($(the anchor.center)-(the node.north)$), \n1={veclen(\x1,\y1)} in (the
node.north) --  node[above] {\n1} (the anchor.center);
\end{tikzpicture}

\end{document}

The main question is: assuming the fontsize is constant let us say 10 pt, how the length of the string inside anchor affects this distance? If instead of $a > b$ we make a longer string such as $aaaaaaaaaaaaa$ the distance described above changes. The question is how it varies.

A: As you are not disclosing for what purpose you need to know the distance between node center and north anchor, it is really hard to help here, therefore I answer your questions straight:
Is this true in general?
No it is not, because the size of a node is dependent on its content, therefore imagine your node has another font size, like \node (the anchor) [red,above] at (the node.north) {\LARGE $a < b$};, then the distance is different, too:

If not, what is the default distance?
Following the logic of the size dependency from the content, there cannot be a default distance.


text:
Q: Import .sql file using ssh I read many tutorials online on how to import sql scripts using ssh, and that is mysql –u [username] –p [database] < [file_name].sql but only works for single database. I created an sql file of my localhost (all databases), I did this using PhpMyAdmin and tried to use the code of importing but nothing happens.
Is there a separate way on how to do this?

A: mysql -h localhost -u root -p -e "source d:\test.sql"

A: As long as you don't specify the --one-database arg, there's nothing preventing you from adding a USE <some-other-db>; statement as necessary within your .sql file.


text:
Q: Formalizing a Parameter Selection Problem in Machine Learning I have a simple problem,
I have an array (say of length 300), which gives me the fraction of importance of some value.
I plot it and see that the value becomes flat after some index.
So, I select the index after which the importance fraction just becomes flatter by just plotting the value.
So, my question is how should I formalize the problem of selecting this index.
The curve is like: Example Curve
How should I select the index? What mathematical condition is guaranteed to allow me to find that index after which the values become flat?

A: Why not slope of the curve? $dy/dx$? Consider value at the consecutive indices then $dx=1$.
From figure
            @ index 1, value= 3.5
            @ index 2, value= 1.8
                     etc
            @ index 7, value= 0.5
            @ index 8, value= 0.3

search through the array and find out when the slope is less than the required...so that the curve is flat ...close to $dy/dx=0$
for i=1:300
       check=value(i)-value(i+1); %dy, dx=1
          if check<=0.2
             display('index value')
             i
             break
          end
end%end for loop

Isnt this you are asking for?


text:
Q: process for Importing excel.xslx into Azure Data Studio I'm about to be switched over to an M1 MacBook Pro. I need some insight from current M1 MacBook Pro users.
My current process is

*

*get data in .xslx,.csv from source

*clean up data in the spreadsheet

*import data into MS Access as tables and correct any incorrect data types etc

*export from MS Access OBDC into SQL Server Management Studio

What application should I be using as alternatives? I found Azure Data Studio as a good alternative to SQL Server Management Studio.
What should I be using as my MS Access alternative?
What is your process if you do something similar to mine?


text:
Q: htaccess clean url to file I'm trying to redirect my users to a specific page that has a clean url, I managed to do this for one url but when I try a second one it just sends me to the original one.
(request url)  /page/mail  (real url) /content/mail.php
Is there any way I can do this?
My code:
RewriteEngine On
RewriteRule ^page       content/index.php (works)
RewriteRule ^page/mail  content/mail.php (not working)


text:
Q: Continuous, true or false Decide if the following claims are true or false, providing either a short proof or counterexample to justify each conclusion. Assume throughout that g is defined and continuous on all of R.
(a) If $g(x)\geq 0$ for all $x<1$, then $g(1)\geq 0$ as well.
(b) If $g(r)=0$ for all $r \in Q$, then $g(x)=0$ for all $x \in R$.
(c) If $g(x_{0}) > 0$ for a single point $x_{0} \in R$, then $g(x)$ is in fact strictly positive for uncountably many points.
My solution:

A: (a) is nonsense, as $g$ is assumed to be continuous on all of $\mathbb{R}$, so in all points in particular. Suppose that $g(1) < 0$. Set $\varepsilon = \frac{-g(1)}{2} > 0$ and apply continuity on the left...
(b) is true, but your argument is insufficient here. Where do you use continuity and denseness? Do you apply to some theorem, and if so, which one?
(c) your example is false in two ways: it is not continuous (which it has to be), and it is strictly positive for all $x > 0$, so uncountably many $x$. Try to prove it instead. Same idea as (a): set $\varepsilon = \frac{g(x_0}{2} > 0$ and apply continuity at $x_0$.


text:
Q: image processing i have some images..if these images are selected then it should generate another image which is the combination of all the selected images..
can anyone suggest as how to start with?
thanks

A: Use someting like that:
public void MergeImages(string FirstFileName, string SecondFileName)
{
    Image firstImg = Image.FromFile(@"C:\temp\pic1.jpg");
    Image secondImg = Image.FromFile(@"C:\temp\pic2.jpg");
    Bitmap im1 = new Bitmap(firstImg);
    Bitmap im2 = new Bitmap(secondImg);
    Bitmap result = new Bitmap(im1.Width + im2.Width, (im1.Height > im2.Height) ? im1.Height : im2.Height);
    Graphics gr = Graphics.FromImage(result);
    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
    gr.DrawImage(firstImg, 0, 0);
    gr.DrawImage(secondImg, im1.Width + 1, 0);
    gr.Save();
    result.Save(@"C:\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}

this code merges two images in one, systeming them into line.

A: i used ImageMagick to do these kind of things (http://www.imagemagick.org/Usage/layers/)
It is however a little bit different then using gdi to create images, but it is a very fast (and when you get used to the imagemagick syntax) and powerful way to edit images.
Normally you use gdi to edit images in memory; imagemagick uses a commandline utility to create images.
So for example you want to layer two images on top, you start a new process in your code in which you fire up a imagemagick proces with the right parameters and then the image is created ON DISK.
Then you can server the created image with a response.writebinary.


text:
Q: Pixel space depth offset in vertex shader I'm trying to draw simple scaled points in my custom graphics engine. The points are scaled in pixel space, and the radius of the points are in pixels, but the position of the points fed to the draw function are in world coordinates.
So far, everything is working great, except for a depth clipping issue. The points are of constant size, regardless of how far away they are, which is done by offsetting the vertices in projected/clip space. However, when they are close to surfaces, they partially intersect them in the depth buffer.
Since these points represent world coordinates, I want them to use the depth buffer, and be hidden behind objects that are in front of them. However, when the point is close to a surface, I want to push it toward the camera, so it doesn't partially intersect it. I think it is easier to just always do this push, regardless of the point being close to a surface. What makes the most sense to me is to just push it by its radius, so that all of its vertices are exactly far enough away to avoid clipping into nearby surfaces.
The easiest way I've found to do this is to simply subtract from the Z value in the vertex shader, after transforming into view-projection space. However, I'm having some trouble converting my pixel radius into a depth offset. Regardless of the math I use, what works close up never seems to work far away. I'm thinking maybe this is due to how the z buffer is non-linear, but could be wrong.
Currently, the closest I've been to solving this is the following:
proj_vertex_pos.z -= point_pixel_radius / proj_vertex_pos.w * 100.0

I'm honestly not sure why 100.0 helps make this work yet. I added it simply because dividing the radius by w was too small of a value. Can anyone point me in the right direction? How do I convert my pixel distance into a depth distance? Especially if the depth distance changes scale depending on which depth you are at? Or am I just way off?

A: The solution was to convert my pixel space radius into world space units, since the z-buffer is still in world space, even after transforming by the view-projection transform. This can be done by converting pixels into a factor (factor = pixels / screen_size), then convert the factor into world space units, which was a little more involved - I had to calculate the world-space size of the screen at a given distance, then multiply the factor by that to get world units. I can post the related code if anyone needs it. There's probably a simpler way to calculate it, but my brain always goes straight for factors.
The reason I was getting different results at different distances was mainly because I was only offsetting the z component of the clip position by the result. It's also necessary to offset the w component, to make the depth offset work at any distance (linear). However, in order to offset the w component, you first have to scale xy by w, modify w as needed, then divide xy by the new w. This resulted in making the math pretty involved, so I changed the strategy to offset the vertex before clip space, which requires calculating the distance to the camera in Z space manually, but it honestly ended up being about the same amount of math either way.
Here is the final vertex shader at the moment. Hopefully the global values make sense. I did not modify this to post it, so please forgive any sillyness in my comments. EDIT: I had to make some edits to this, because I was accidentally moving the vertex along the camera-Z direction instead of directly toward the camera:
lerpPoint main(vinBake vin)
{
    // prepare output
    lerpPoint pin;

    // extract radius/size from input
    pin.InRadius = vin.TexCoord.y;

    // compute offset from vertex to camera
    float3 to_cam_offset = Scene.CamPos - vin.Position.xyz;

    // compute the Z distance of the camera from the vertex
    float cam_z_dist = -dot( Scene.CamZ, to_cam_offset );

    // compute the radius factor
    // + this describes what percentage of the screen is covered by our radius
    // + this removes it from pixel space into factor-space
    float radius_fac = Scene.InvScreenRes.x * pin.InRadius;

    // compute world-space radius by scaling with FieldFactor
    // + FieldFactor.x represents the world-space-width of the camera view at whatever distance we scale it by
    // + here, we scale FieldFactor.x by the camera z distance, which gives us the world radius, in world units
    // + we must multiply by 2 because FieldFactor.x only represents HALF of the screen
    float radius_world = radius_fac * Scene.FieldFactor.x * cam_z_dist * 2.0;

    // finally, push the vertex toward the camera by the world radius
    // + note: moving by radius will only work with surfaces facing the camera, since we are moving toward the camera, rather than away from the surface
    // + because of this, we also multiply by another 4, to compensate for nearby surface angles, but there is no scale that would work for every angle
    float3 offset = normalize(to_cam_offset) * (radius_world * -4.0);

    // generate projected position
    // + after this, x=-1 is left, x=+1 is right, y=-1 is bottom, and y=+1 is top of screen
    // + note that after this transform, w represents "distance from camera", and z represents "distance from near plane", both in world space
    pin.ClipPos = mul( Scene.ViewProj, float4( vin.Position.xyz + offset, 1.0) );

    // calculate radius of point, in clip space from our radius factor
    // + we scale by 2 to convert pixel radius into clip-radius
    float clip_radius = radius_fac * 2.0 * pin.ClipPos.w;

    // compute scaled clip-space offset and apply it to our clip-position
    // + vin.Prop.xy: -1,-1 = bottom-left, -1,1 = top left, 1,-1 = bottom right, 1,1 = top right (note: in clip-space, +1 = top, -1 = bottom)
    // + we scale by clipping depth (part of clip_radius) to retain constant scale, but this will give us a VERY LARGE result
    // + we scale by inverter resolution (clip_radius) to convert our input screen scale (eg, 1->1024) into a clip scale (eg, 0.001 to 1.0 )
    pin.ClipPos.x += vin.Prop.x * clip_radius;
    pin.ClipPos.y += vin.Prop.y * clip_radius * Scene.Aspect;

    // return result
    return pin;
}

Here is the other version that offsets z & w instead of changing things in world space. After edits above, this is probably the more optimal solution:
lerpPoint main(vinBake vin)
{
    // prepare output
    lerpPoint pin;

    // extract radius/size from input
    pin.InRadius = vin.TexCoord.y;

    // generate projected position
    // + after this, x=-1 is left, x=+1 is right, y=-1 is bottom, and y=+1 is top of screen
    // + note that after this transform, w represents "distance from camera", and z represents "distance from near plane", both in world space
    pin.ClipPos = mul( Scene.ViewProj, float4( vin.Position.xyz, 1.0) );

    // compute the radius factor
    // + this describes what percentage of the screen is covered by our radius
    // + this removes it from pixel space into factor-space
    float radius_fac = Scene.InvScreenRes.x * pin.InRadius;

    // compute world-space radius by scaling with FieldFactor
    // + FieldFactor.x represents the world-space-width of the camera view at whatever distance we scale it by
    // + here, we scale FieldFactor.x by the camera z distance, which gives us the world radius, in world units
    // + we must multiply by 2 because FieldFactor.x only represents HALF of the screen
    float radius_world = radius_fac * Scene.FieldFactor.x * pin.ClipPos.w * 2.0;

    // offset depth by our world radius
    // + we scale this extra to compensate for surfaces with high angles relative to the camera (since we are moving directly at it)
    // + notice we have to make the perspective divide before modifying w, then re-apply it after, or xy will be off
    pin.ClipPos.xy /= pin.ClipPos.w;
    pin.ClipPos.z -= radius_world * 10.0;
    pin.ClipPos.w -= radius_world * 10.0;
    pin.ClipPos.xy *= pin.ClipPos.w;

    // calculate radius of point, in clip space from our radius factor
    // + we scale by 2 to convert pixel radius into clip-radius
    float clip_radius = radius_fac * 2.0 * pin.ClipPos.w;

    // compute scaled clip-space offset and apply it to our clip-position
    // + vin.Prop.xy: -1,-1 = bottom-left, -1,1 = top left, 1,-1 = bottom right, 1,1 = top right (note: in clip-space, +1 = top, -1 = bottom)
    // + we scale by clipping depth (part of clip_radius) to retain constant scale, but this will give us a VERY LARGE result
    // + we scale by inverter resolution (clip_radius) to convert our input screen scale (eg, 1->1024) into a clip scale (eg, 0.001 to 1.0 )
    pin.ClipPos.x += vin.Prop.x * clip_radius;
    pin.ClipPos.y += vin.Prop.y * clip_radius * Scene.Aspect;

    // return result
    return pin;
}


text:
Q: Facebook helper not appearing in MVC4 I created a new test project in MVC4 to test if I could use Facebook Helper from the Nuget gallery.  I followed the instructions which are very simple, point and click to install the Facebook helper from Nuget, edit your page, and insert like button.
When I run the project I can actually see the facebook likebutton being generated when I view it through firebug, but it does not appear on the page.
Here is my default index page
@{
    ViewBag.Title = "Home Page";
}
@section featured {

            <hgroup class="title">

@ViewBag.Title.

@ViewBag.Message

            </hgroup>

                To learn more about ASP.NET MVC visit
                http://asp.net/mvc.
                The page features videos, tutorials, and samples to help you get the most from ASP.NET MVC.
                If you have any questions about ASP.NET MVC visit
                our forums.

}

We suggest the following:

    @Facebook.LikeButton()

I´ve gone through several pages regarding Facebook helper and they all describe the process in the same way.  Does anyone know if I should config any files before using this library?
Edited:
I will paste my html code that is loaded into the markup after execution.  I will abbreviate some scripts and stuff since it has many hundreds of line of code  :)

<meta charset="utf-8">


text:
Q: Problemas de Envio de email html e php ( via outlook), limitando mensagem Estou com um problema qto a enviar emails via php e Html, tem um botão que abre o outlook ja com os campos de email, assunto e cc preenchidos, no corpo do email vem ja preenchido tbem com as informações, porém é como se limitasse , o texto não sai completo, ele limita e corta pela metade das informações do email no corpo, que vem de um formulario.
as informações vem de "action="mailto:" e o corpo de um texto ja fixado com variaveis que podem ser adicionadas mais informações ao texto padrão atravez de um modal


text:
Q: Mediaelement.js the flash player won't hide the play button I have set the features to be empty which works fine except in the flash player. It still shows the big play button. Any ideas?
I realise I can manually hide this but I'd rather find the proper solution
$('video').mediaelementplayer({
    features: [],
    success: function (me) {
        me.play();
    }
});

A: I just added a style over-ride to my page after loading the CSS.
<style>
   .mejs-overlay-button {display:none;}
</style>


text:
Q: Querying max, min and other via Core Data Is it possible to query the database for the max, min and other values using Core Data framework?

A: You need to use the collection operators in objective c. More info here: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html

A: You can indeed have an NSFetchRequest calculate such values. You need to set your fetch request to return NSDictionaryResultType results, and create appropriate NSExpressionDescription objects to describe the operations (e.g. min, max, sum, etc.) you're after.
Take a look at the worked example in Apple's Core Data Programming Guide: http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html#//apple_ref/doc/uid/TP40002484-SW6 .

A: You can use query builder, which allows you write your requests like this:
NSDictionary *productTotalSumAndAveragePriceGroupedByCountries =
[[[[[Product all
] aggregatedBy:@[
                 @[kAggregateSum, @"amount"],
                 @[kAggregatorAverage, @"price"]]
] groupedBy:@[@"country"]
] having:predicate
] execute];


text:
Q: How can I copy a LVM logical volume to a loopback file on another system? I am trying to copy an LVM logical volume with an ext3 filesystem from one system to a file on another system that I will be able to mount as a loopback device. I have tried the following command to copy the volume:
dd if=/dev/VolGroup01/example-volume bs=1M | ssh target-system dd of=/backup/example-volume-image bs=1M
This gives me a file with the same size as the logical volume however when I try to mount it I get:
[root@target-system backup]# mount -o loop example-volume-image /mnt
mount: you must specify the filesystem type
[root@target-system backup]# mount -o loop -t ext3 dev2-endeca1-rootfs /mnt
mount: wrong fs type, bad option, bad superblock on /dev/loop0,
       missing codepage or other error
       In some cases useful info is found in syslog - try
       dmesg | tail  or so

Am I not copying the volume correctly or is it just possibly corrupt?

A: If it is a running lvm, you should create a snapshot of it, and then back up the snapshot. Otherwise your command looks fine. It is better if you unmount the lvm before doing the copying.
Then, force a filesystem check on the resulting loop file before attempting to mount.


text:
Q: Why Python `filter` vs similar list comprehension is not returning similar results? Why below two statements are not returning same lists?
with open("test.py") as f:
    upChars = list(filter(lambda ch : ch.isupper(), [ch for ch in f.read()]))
    upChars1 = [ch1 for ch1 in f.read() if ch1.isupper()]
    print(f"\n1:  {upChars},\n2:  {upChars1}")

Output :

1:  ['T', 'B', 'S', 'T', 'T', 'C', 'T', ...contains all uppercase chars],
2:  []

A: That's because you cannot read a file twice. After the first read(), the descriptor is at the end of file. Usually, when preforming multiple things on a file, putting it into a list makes sense:
test = f.read()

then you can use it multiple times. Try and print the result of a double read to see this in action. If you really insist, you could f.seek(0) to reset it, but this is more overhead than its worth.


text:
Q: My metasploit module(s) not found/loading Any custom metasploit module I create isn't getting loaded.
I tried both of these demos:
https://www.offensive-security.com/metasploit-unleashed/building-module/ https://github.com/rapid7/metasploit-framework/wiki/Loading-External-Modules
and got the same result that the modules were NOT found.
Before posting here, I checked these out:
https://forums.kali.org/showthread.php?28940-Metasploit-modules-not-loading!
https://www.offensive-security.com/metasploit-unleashed/modules-and-locations
and from SO:
I can't get new modules to load in metasploit
How to add module in Metasploit?
no help
Just working with the github example, on the Kali host, I do indeed have the file in the right location (according to the demo):
root@kali:~/.msf4/modules/exploits/test# ls -al
total 12
drwxr-xr-x 2 root root 4096 Mar 19 13:59 .
drwxr-xr-x 3 root root 4096 Mar 19 13:58 ..
-rw-r--r-- 1 root root 9 Mar 19 13:59 test_module.rb

I then ran reload_all and when using this command:
use exploit/test/test_module it returns with Failed to load module.
I also tried to manually load that path and it failed too:
msf > loadpath ~/.msf4/modules/
Loaded 0 modules:

A: Posting the answer for anyone who may come across this.  I'm kinda new to this; didn't know where metasploit info gets logged.
It's in:   ~/.msf4/logs/framework.log
The log told me I had a syntax error... must have happened from copying and pasting the text from the browser.  Cleaned that up and everything works.


text:
Q: What exactly happens when free() is called on a pointer? Does free just go byte by byte and set every byte to NULL? I am just curious as to how free explicitly works.
Edit:
I guess I should be a bit more specific, I apologize. I implemented my own version of malloc and am now attempting to implement free. I have the void * returned from malloc and am using that as an argument for my free function obviously. I am trying to figure out what to do with this function and how I would go about coding this. I implemented malloc using an explicit free list so I want to return this block back to the free list which I know how to do I just don't know what to do with the data inside the memory block.

A: The C standard defines the behavior of the free function:

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.

In other words, it doesn't really matter what exactly happens to it. What matters is it's available for further malloc().


text:
Q: Blurry image when using LiipImagineBundle Symfony 3 I've read the documentation to install and use LiipImagineBundle in Symfony 3 and when I want to resize an image that was uploaded through my administration interface, it becomes blurry. If an editor publishes a very large picture I would like it to be resized automatically to be displayed on my site. I do not understand why my image gets very blurry and does not resize to the specified size..
config.yml :
liip_imagine:
filter_sets:

    # name our filter set "my_thumb_filter"
    my_thumb_filter:
        filters:

            # use and setup the "thumbnail" filter
            thumbnail:

                # set the thumbnail size to "500x500" pixels
                size: [500, 500]

                # crop the input image, if required
                mode: outbound

Twig :
<img src="{{ ('bundles/sg/images/articles/' ~ article.image2.file ~ '.' ~ article.image2.extension) | imagine_filter('my_thumb_filter') }}" alt="{{ article.titre }}">

I created a media/cache folder and my image is placed correctly in the "articles" folder (http://localhost/SG/web/media/cache/my_thumb_filter/bundles/sg/images/articles/c71068976ec6efefc3c3c75886c6089b.jpeg)
Thanks you in advance for your help


text:
Q: i have a problem with limit calculation $\lim\limits_{x \to 0+} {x}^{(x^x-1)}=,$
i tried L'Hôpital but i really don't know how
i got to the second derivative

A: $$\lim_{x\rightarrow0^+}x^{x^x-1}=\lim_{x\rightarrow0^+}\left(1+x^x-1\right)^{\frac{1}{x^x-1}\cdot\frac{(x^x-1)^2}{x}}=e^{\lim\limits_{x\rightarrow0^+}\frac{(x^x-1)^2}{x}}=$$
$$=e^{\lim\limits_{x\rightarrow0^+}2(x^x-1)x^x(1+\ln{x})}=e^{2\lim\limits_{x\rightarrow0^+}\frac{e^{x\ln{x}}-1}{x\ln{x}}\cdot x\ln^2x}=e^{2\cdot1\cdot0}=1.$$

A: write $$e^{\lim_{x\to 0^+}(x^x-1)\ln(x)}$$ and use L'Hospital
Hint: $$\lim_{x \to 0^+}(x^x-1)\log(x)=0$$


text:
Q: SVN svnrdump load - pre-revprop-change hook I am trying to migrate a subversion repository from one server to another. I can dump the repository from the old server to a file, but I am having issues with loading the dump file to the new server.
I created a repository on the new server, and added the hook file: /svn/repo2/hooks/pre-revprop-change
#!/bin/sh
exit 0

And I change that file's permissions (I get this when I enter ls -la:
-rwxr-xr-x 1 apache apache   17 Apr  7  2020 pre-revprop-change
-rwxr-xr-x 1 apache apache 2786 Apr  7 14:49 pre-revprop-change.tmpl

When I try to load the dump file to the new repository, I enter this command:
svnrdump load http://myUserName@123.456.78.9/repo2 < fileName.dump --username myUserName
I get this error:
svnrdump: E175008: While handling the 'svn:rdump-lock' property on '/repo2/!svn/bln/0':
svnrdump: E175008: Revprop change blocked by pre-revprop-change hook (exit code 255) with no output.

As a note that may be relevant, there is another repository that is working on the same server (/svn/repo1) that is working.
Does anyone have any suggestions as to how I can fix this?
Thanks!

A: You need to setup ownership, in this case /var/www/svn is the root directory of my subversion repositories.

sudo chown -R apache.apache /var/www/svn

A: Regular execution permissions are needed but not enough.  You need to grant the execution in SELinux.to Apache/HTTPD to the script like this.
chcon -t httpd_exec_t pre-revprop-change


text:
Q: How to plot more data points on D3.js as you zoom in? I am developing a few graphs by using D3.js and I am facing a few issues as I am not really familiar with the framework yet.
My main requirement is to plot a graph of price X time and my data points could be over a million data points in one day. So my idea was to use a similar approach to what google maps does. Every time you make a zoom in, maps takes more data from the server and display it. I would do the same by taking a few points to draw the chart and as you go zooming in I would take more points and making the chart sharper. How can I archive this solution?

A: You could interlink the number of data points plotted with the zoom factor by  using the zoom as a modulus. For example, let's say your zoom has 10 levels with 10 being the most zoomed out (earth in Google maps) and 1 the most detailed view (a single house) and assuming this function:
var scatter = d3.select("#svg").selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
  .attr("cy", function(d) {
    return y(d.y);
  })
  .attr("cx", function(d) {
    return x(d.x);
  })
  .attr("r", function(d, i) {
    return i % zoom == 0 ? 3 : 0; // <== This is _the_ line.
  });

The marked line goes through the data points and only if i % zoom == 0 the drawn circle will have a radius of 3, all other circles get 0 and thus are not visible.
Of course, this still goes through all of the data points available but I think there was something like .defined() in d3 to avoid getting a data point drawn. The same function as above could be used there.


text:
Q: How to solve Heap inspection vulnerability for MVC viewmodel? Checkmarx reported a Heap inspection vulnerability regarding having a string for a Password property. This property is part of a model, which gets bound when submitting a login form. Is there a way in ASP.NET MVC to use anything else other than regular string to bind password from the form?
So far I have tried changing the property type to char [] or SecureString, but in that case the form doesn't bind the data to it.
public class LoginModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

A: Rename password field to something else... like "alienSecurity" and that's it CheckMarx will not able to catch it :)

A: Use SecureString instead of String.
A SecureString instance provides more data protection than a String.
When creating a string from a character-at-a-time source, String creates multiple intermediate in memory, whereas SecureString creates just a single instance.
Garbage collection of String objects is non-deterministic. In addition, because its memory is not pinned, the garbage collector will make additional copies of String values when moving and compacting memory. In contrast, the memory allocated to a SecureString object is pinned, and that memory can be freed by calling the Dispose method.
https://msdn.microsoft.com/en-us/library/system.security.securestring(v=vs.110).aspx


text:
Q: ¿Como creo mi propio error en Python™? Mi necesidad es crear mi propio error
algo así:
raise ErrorSistema_Problema("Error")

¿Como creo esto sin que me diga

ErrorSistema_Problema is not defined

?

A: Es muy facil, solo hay que definir la clase "ErrorSistema_Problema" y darle el argumento "_StandardError"
#Definimos "_StandardError"
_StandardError=Exception
# Si esto no funciona, revisa el archivo
# llamado builtins.pyi
# En este archivo se definen las cosas mas importantes, como
# la funcion print()

#Creamos la clase del error
class ErrorSistema_Problema(_StandardError) : ...

¡ Y listo !
¡Ya podremos usar el raise con nuestro error!
(
raise ErrorSistema_Problema("Error Del Sistema")

)
¡Sin Errores de por medio, solo el que creamos jaja!


text:
Q: Alignment of HTML contents I have coded buttons and input boxes but I want them to be aligned and placed in the center of the browser, but my output looks messy. I tried using center but the input boxes are not aligned. How do I align them? Thanks in advance.
Here is my complete code:

Name:
<input type="text" id="NameInput">

Number:
<input type="text" id="NumberInput">

<input type="button" value="ADD" onClick="press(input.value)">
<input type="button" value="EDIT" onClick="press(input.value)">
<input type="button" value="DELETE" onClick="press(input.value)">

Name:
<input type="text" id="NameSearch">

Number:
<input type="text" id="NumberSearch">

<input type="button" value="SEARCH" onClick="press(input.value)">

A: Try below using margin on a div and specifying a width:

        Name: <input type="text" id="NameInput">

        Number: <input type="text" id="NumberInput">

        <input type="button" value="ADD" onClick="press(input.value)">
        <input type="button" value="EDIT" onClick="press(input.value)">
        <input type="button" value="DELETE" onClick="press(input.value)">

        Name: <input type="text" id="NameSearch">

        Number: <input type="text" id="NumberSearch">

        <input type="button" value="SEARCH" onClick="press(input.value)">

Also take a look at this url: CSS replacement for

If you want to make all the input boxes align you can try something like below:

        Name:
        <input type="text" id="NameInput">

        Number:
        <input type="text" id="NumberInput">

        <input type="button" value="ADD" onClick="press(input.value)">
        <input type="button" value="EDIT" onClick="press(input.value)">
        <input type="button" value="DELETE" onClick="press(input.value)">

        Name:
        <input type="text" id="NameSearch">

        Number:
        <input type="text" id="NumberSearch">

        <input type="button" value="SEARCH" onClick="press(input.value)">

A: Depending on the requirements, you could try playing around with the placeholder attribute:
    <input type="text" id="NameInput" placeholder="Name">

A: The  is working properly because it considers the field and the text to be all one line, and it finds the centre of that line. Because the label for each field is a different length, each line has a different centre point.
How to align input forms in HTML has a few different approaches. You should use styling to make the label for each field the same length.


text:
Q: Why didn't the weaker tributes gang up on the stronger ones in The Hunger Games? The Hunger Games universe presents that the wealthier districts have special training and volunteers for their tributes ("Careers"). While it certainly seems reasonable that the poorer districts could not support such an effort, it also seems reasonable that they would develop some tactic or strategy to combat such dominance of the wealthier districts.
One plausible method for the disadvantaged defeating the advantaged is through absolute numbers, which also makes sense on an individual level. If you are disadvantaged and want to have any hope of survival, wouldn't you prefer to fight a weaker opponent? Thus defeating the strongest opponents is most beneficial to all weaker opponents.
I have only seen the first three installments of the movies and have not read the books, but it is not clear to me why this strategy was not employed, other than to enhance the story-telling.

A: To be honest, most of the time it doesn't seem to make sense.

*

*You don't usually gain major advantage in allying with people unless you either have:

*

*Advantage in combat. But to have advantage in the kind of melee combat that the Arena offers, one needs to be trained in teamwork - two untrained people with knives or swords against a trained fighter don't really present much of a bigger challenge
To top that off, Careers seem to frequently team up in the first place, in which case even piling up a bunch of weaker contestants against a single career hoping to overwhelm him/her is not feasible - you will be dealing with a Career pack, and we are back to Careers actually knowing how to fight in a group vs. those who don't.

*access to resources to be pooled (and weaker tributes tend to have very scant resources, since Cornucopia is largely off limits unless they wish to be killed by Careers from the get-go)
Any instances of non-careers teaming up seem to be unique to a situation, or totally useless:

*

*Katniss had a very specific plan involving getting Career pack away from the supplies; so Rue was helpful merely by being able to be in a different place as a diversion (to light fires)

*Katniss and Peeta were both well-trained (especially Katniss) and opposing a single Career fighter at the end, in a very special situation (dogs attacking). Please note that prior to that, Peeta was pretty well useless to Katniss as ally, his purely accidental killing of Foxface being just that, an accident.

*75th games saw people with a grand strategy and tactics arranged well before the games started.

A: The Hunger Games are designed so that there is only one survivor. Alliances must be temporary. In the end, the last survivor must betray his or her friends. (You might note that Heavensbee makes just that point in the design of the 75th games.)
Assume that a dozen non-Careers gang up on half a dozen Careers and defeat them. What next? The winners of the fight, already injured, would have to turn on each other. For an individual who wants to survive, it would be much smarter to let the others take the risks, and to stay at the sidelines of the fight. Either by running away during the initial bloodbath, or at least by holding back during the frantic melee.

A: Occasionally this does happen:

*

*in the 74th Hunger Games, Katniss and Rue team up, followed by Katniss and Peeta later on

*in the 75th, weaker tributes such as Mags, Wiress, and Beetee team up with fighters such as Katniss, Finnick, and Johanna.

But all these alliances are special in some way: in the 74th, both alliances were made in the middle of the Games rather than being prearranged; and in the 75th, there were all sorts of motives going on as most of the tributes were old friends and quite a few of them were in on the plan for rebellion.
Alliances are usually arranged beforehand, by the tributes' mentors. From each individual tribute's point of view, it would make more sense to team up with stronger tributes such as the Career pack than weaker ones. Who'd request an alliance with a weakling when they could have an alliance with some brute from District 2? And when they don't manage to get in with the Careers, another weakling to join up with wouldn't make much difference. Sure, it would be good for them if ten weaklings teamed up, but someone has to make the first step, and just two is hardly better than one.
And if you're thinking about alliances made in the arena, such as Katniss's two alliances in her first Games, remember the Cornucopia bloodbath. It's fairly normal for around half the tributes to die in the first hour or two of the Games. That leaves six Career tributes (Districts 1, 2, and 4 are all Careers in the books, and they all tend to survive the bloodbath due to their training) and about the same number of other tributes surviving. Even if all the rest managed to trust each other to team up at that stage, they'd still be weaker than the Careers.


text:
Q: How to sum values from all Sheet dynamically in Google Sheets I have a list of sheets in my workbook (Sheet1, Sheet2, Sheet3) and I want to sum the values of a specic cell (A1) from all those sheets.
I could do =Sum('Sheet1'!A1;'Sheet2'!A1;'Sheet2'!A1). The catch is that i'll be adding multiple sheets as needed (e.g every new customers) and similar formulas will be used throughout the whole workbook, so editing the formula by hand every time is not an option.
I want to do that dynamically.
I'm toying with the idea of having a list of names of all the sheets and referecing with the INDIRECT(ADDRESS(...) formula, but that's not elegant and it also lacks the ability of changing the structure of the sheets (say, adding a new line).
Any ideia on how to do that? Preferably using only formulas.

A: Try this:
function sumA1(){
  var ss= SpreadsheetApp.getActive();
  const shts = ["Sheet0","Sheet1","Sheet2"];
  let s = ss.getSheets().filter(sh => ~shts.indexOf(sh.getName())).reduce((a,sh) =>  {a+=sh.getRange("A1").getValue();return a},0)
  Logger.log(s);
  return s;
}


text:
Q: Assembly, hello world question I'm learning asm on Linux (noobuntu 10.04)
I got the following code off of: http://asm.sourceforge.net/intro/hello.html
section .text
global _start ;must be declared for linker (ld)

_start: ;tell linker entry point

mov edx,len ;message length
mov ecx,msg ;message to write
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel

mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel

section .data

msg db 'Hello, world!',0xa ;our dear string
len equ $ - msg ;length of our dear string

It's a simple hello world. Runs on Linux + calls the kernel directly (apparently).
Can anyone please explain what is really going on here? I think it reads the integers in the eax & ebx processor registers & ecx, edx data and that defines the system call when the kernel is called.  If so,  do different combinations of integers define different system calls when int 0x80 is called?
I'm not good with man pages, but have read every related one I can find, does any man page tell me what combinations define what syscalls?
ANY help is appreciated. A line by line explanation would be amazing...
-Thanks in advance
Jeremy

A: When you call int 0x80, the kernel looks at the value of the eax register to determine the function you want to call (this is the "syscall number"). Depending on that number, the rest of the registers are interpreted to mean specific things. The sys_write call expects the registers to be set up as follows:

*

*eax contains 4

*ebx contains the file descriptor

*ecx contains the address of the data to write

*edx contains the number of bytes

For further extensive information, see Linux System Calls.

A: section .text
global _start ;must be declared for linker (ld)

This is just header material, the "text" section of an assembly program is just the machine instructions (versus the data, read-only data, and BSS sections).  The global line is akin to saying that the _start function is "public."
_start: ;tell linker entry point

mov edx,len ;message length
mov ecx,msg ;message to write
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel

From the comments we know that we are looking at the sys_write function, so we can man 2 write to get the details.  The C prototype gives the following parameters: fd, *buf, and count.  Starting with %ebx we see that those match (%ebx = fd, %ecx = string to write, and %edx = length of string).  Then, since we are a user process, we must ask the kernel to perform the output.  This is done through the SYSCALL interface, and the write() function is (apparently) given the number 4.  INT 0x80 is a software interrupt that calls the Linux kernel's SYSCALL routine.
You can find the actual numbers of all the syscalls in the Linux header files (assuming you have them installed).  On my system, I checked /usr/include/sys/syscall.h leading to /usr/include/asm/unistd.h and then onto /usr/include/asm-i386/unistd.h.  Where (I see), #define __NR_write 4.
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel

As with the last two lines of the previous segment, this just loads the syscall id and does the software interrupt to exit the program (remove it's memory mapping and cleanup).
section .data

msg db 'Hello, world!',0xa ;our dear string
len equ $ - msg ;length of our dear string

This is the data section, it just describes variables we used in our program.

A: There are too many system calls for there to be a different assembly-language instruction for each one.
Instead, you call the TRAP instruction.  The value of eax determines which system call will be invoked.  The other registers are the arguments to the system call.
The system calls are listed inside the kernel.


text:
Q: Which problem is the Diamond Problem exactly? I see at least 2 separate problems related to the diamond class hierarchy (note the example code below is in C++ but I believe my question is language-agnostic):
class A
{
public:
    virtual ~A() = default;
    virtual void f()
    {}
};

class B : public A
{
public:
    void f()
    {
        std::cout << "B" << std::endl;
    }
};

class C : public A
{
public:
    void f()
    {
        std::cout << "C" << std::endl;
    }
};

class D : public B, public C
{
};

D d;
d.f();

Problem 1: Do B and C share one common instance of A or do they both have a separate instance? (Yes, I know how it's resolved in C++ but the general problem remains.)
Problem 2: Call to d.f() is ambiguous.
My question is - when people talk about the Diamond Problem which problem do they actually mean? 1 or 2? Or possibly both?

A: Says Wikipedia:

The "diamond problem" (sometimes referred to as the "Deadly Diamond of Death"[6]) is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?

That's your "problem 2".

A: When people talk about the diamond problem, they usually don't distinguish between these two problems.  But sometimes they do, especially if they're explaining a mitigating feature of some particular language.
"Diamond problem" is a colloquial expression that doesn't have a universally accepted formal definition.  You can interpret it as "the problem of multiple inheritance nets"... for which there are various solutions.


text:
Q: Setting a MapView's center coordinate does not take into account full size of MapView (off-screen portion) The Problem
I have a view that includes a full-screen MKMapView. The bottom half of the MapView is covered with a TableView that has translucent cells so that the map shows through.

When I center on an annotation coordinate, the current location for example, the annotation view is blocked by the TableView.
- (void)centerOnCurrentLocation
{
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(self.locationManager.location.coordinate, 50000, 50000);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}

Attempted Solution
I first tried to programmatically shift the map to offset the center, shifting the annotation up. This approach works if I turn off animation, though it's not a simple solution. Nor do I want to turn off animation.
Instead I thought that if I extend the MapView off the top of the screen by the same height as the TableView the center of the MapView would be exactly where I want it. It doesn't work! When I set the center coordinate on the larger MapView the annotation still appears in the center of the screen, not in the center of the larger MapView. It seems like MKMapView is using the view's visible region when calculating its center.

This is what I would expect to see when I center on current location using the enlarged MapView.

If only MKMapView had a centerOffset property that allowed you to shift the center by some CGPoint.
Does anybody have a simple, elegant solution to offset a MapView's center?

A: Just to clarify on my comment, you can use setVisibleMapRect: edgePadding: to create the offset you want. You will need to put it in the mapView delegate method regionDidChangeAnimated: this will fire anytime the region changes on your map so you need to wrap your code with a flag to know when to apply the offset or it can be applied multiple times.  Here is what you need to do:
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{

    if (!self.mapInsetsSet) {
        self.mapInsetsSet=TRUE;
        [self.myMapView setVisibleMapRect:self.myMapView.visibleMapRect edgePadding:UIEdgeInsetsMake(10, 0, 0, 0) animated:YES];
    }

}

In the above code, mapInsetsSet is just a bool that you can set elsewhere to control when to apply the offset. Also, you will need to adjust the UIEdgeInsetsMake to the desired offset.


text:
Q: Android: Internet connection cannot be established on my app with some devices ich have written an app for android which has to download data from a website. All in all it works pretty well but i heard from some users that they the internet connection doesn't work when they use internet access via mobile internet. With the WLAN there are no problems and on my mobile phone it even works with mobile internet. I already ensured myself that the users who has got these problems do have internet access on other apps with their mobile internet...
Here is the source code, where I establish the connection.
String urlString = "http://google.com";
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "ISO-8859-"));
String line = "";
while((line = reader.readLine()) != null){
    line //do sthg with line
}

I hope that i gave enough information to you guys the help me to solve that problem
Regards

A: Maybe you could delete those
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);


text:
Q: Is there a Unity equivalent of the GNOME panel 'show desktop' applet?
Possible Duplicate:
How to add a "Show desktop" icon to the launcher?

I miss the symbol to show the desktop with just one click when using Unity instead of the classic desktop.
Is there a possibility to get the "Show Desktop" applet or an equivalent?  There is a bug report on:

*

*Bug #681348 ("Add 'show me the desktop' keyboard or Unity dock shortcut")
Can people suggest any workarounds in the mean-time?


text:
Q: How to use mashape with python request library? Unirest is not compatible with python3 and that's the library that mashape APIs' use on python projects.
I've decided to use python request library to make a POST request, but I'm getting a 400 HTTP error. Everything looks good to me, but I can't figure out what I'm doing wrong.
url = "https://japerk-text-processing.p.mashape.com/sentiment/"

myHeaders={
  "X-Mashape-Key": mashape_key,
  "Content-Type": "application/x-www-form-urlencoded",
  "Accept": "application/json"
}

myParams={
  "language": "english",
  "text": tweet_text
}

r = requests.post(url, headers=myHeaders, params=myParams)
print(r)

A: According to the docs, UNIREST takes the argument:

params - Request Body as an associative array or object

However, requests, per its own documentation, uses params to supply URL query parameters, not the request body.
Try using the data parameter to pass an actual request body instead; see the docs again. You will probably have to keep double-checking parameter names in the two sets of documentation to ensure you're passing the right thing.


text:
Q: Value of UIBackgroundTaskInvalid is? I read from the header file (UIApplication.h):
typedef NSUInteger UIBackgroundTaskIdentifier;
UIKIT_EXTERN const UIBackgroundTaskIdentifier UIBackgroundTaskInvalid  __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0);

It seems that UIBackgroundTaskInvalid is just an ordinary NSUInteger with a given value. Now that I'm writing code that has to be compatible with jailbreaking iOS 3.1.3 (where UIBackgroundTaskInvalid is not defined yet). I might need the real value behind it. Anyone can help?
Thanks in advance.
Di

A: You can check it with
#if !defined UIBackgroundTaskIdentifier
   // Pre iOS 4 Fallback
#endif

The sample above only checks the value on compile time. If you need these kind of checks on run-time you can check this great article.


text:
Q: How do you add an attribute to your CSS selector to specify specific pagination link? I just got into Scrapy & I'm aware this is a Noob question but How do I add an attribute to specify specific pagination link?
here is the html with the element I'm targeting.
`

            1

            2

            3

            4

            …

            50

I Need to follow the link in this line

Here is my scrapy code
            next_page = response.css('div.pagination a::attr(href)').extract_first()
    if next_page is not None:
        yield response.follow(next_page, callback=self.parse)

What's happening is its following this link instead of the other one because it is the first one in the class "pagination"

I can see 2 differences between the attributes of the 2 links, both in the class "pagination"

*

*Rel attribute is different, I need the one with "next"

*Class attribute is different, I need "fa fa-chevron-right next pagination-icon"

I'm pretty sure I can get the correct link by specifying one of the 2 attributes listed above in my css selector. I tried using the following CSS selectors but none worked.

*

*div.pagination a.fa fa-chevron-right next pagination-icon a::attr(href) does not work

*a.fa fa-chevron-right next pagination-icon a::attr(href) does not work

*a.fa fa-chevron-right next pagination-icon::attr(href) does not work

How can I achieve my goal? Why do none of the CSS selectors I tried work?

A: You can't select multiple classes with a single dot. Either combine each of them with dots or go for this syntax "[class='fa fa-chevron-right next pagination-icon']". However, if any class out of them is generated dynamically then the selector will break.
Then try with this to see what happens.
response.css('div.pagination a[rel="next"]::attr(href)').extract_first()


text:
Q: How to solve: Why is coreData(NSFetchedResultsController) sorting differently in iOS5 and iOS4 i have a tableview which is populated with NSFetchedResultsController.
On didSelectRowAtIndexPathi am updating the current row. The sorting here should not change. The difference in the selected row is, that i mark it as read. No title changes or something.
In iOS4 the row gets updated and still leave on his current place, it does not move to the end of section. Thats the right way.
in iOS5 the row gets also updated but it moves to the end of the Section. I want to prevent that. How can i do that? And why is that happening?
See my code:
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil)
{
    return __fetchedResultsController;
}

NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntitySetsCardsInbox" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSPredicate *inboxPred = [NSPredicate predicateWithFormat:@"archived == 0 AND cardId != 0"];
[fetchRequest setPredicate:inboxPred];

if (sortString == nil) {
    //sortString = [[NSString alloc] initWithString:@"sortingOrder"];
    sortString = [[NSString alloc] initWithString:@"colorOrder"];
    sortAsc = NO;
}

if ([sortString isEqualToString:@"cardTitle"]) {
    NSSortDescriptor *sortDescriptor2 = [[[NSSortDescriptor alloc] initWithKey:sortString ascending:sortAsc selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
    NSArray *sortDescriptors = [[[NSArray alloc] initWithObjects:sortDescriptor2, nil] autorelease];
    [fetchRequest setSortDescriptors:sortDescriptors];

    XLog(@"sortDescriptors: %@", sortDescriptors);
} else {
    NSSortDescriptor *sortDescriptor2 = [[[NSSortDescriptor alloc] initWithKey:sortString ascending:sortAsc] autorelease];
    NSArray *sortDescriptors = [[[NSArray alloc] initWithObjects:sortDescriptor2, nil] autorelease];
    [fetchRequest setSortDescriptors:sortDescriptors];

    XLog(@"sortDescriptors: %@", sortDescriptors);
}

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;

    [...]
}

A: i think your sortdescriptor is changing when you updating your rows. add one more sortdescriptor to fix the list with it and check it again. in my case i have a very similar issue and it solved my problem. maybe yours, too.


text:
Q: Merge two rows by conditional variable Suppose I have a Dataframe like the following:
a <- data.frame(A = c("01.01.2000", "02.01.2000", "03.01.2000", "01.01.2000.1", "04.01.2000", "04.01.2000.1"),
            B = c(1, NA, 2, 1, 4, NA ),
            C= c(NA, NA, 4, NA, NA, 1))

Now I want to merge all rows, where the ".1" is at the end, to its "counterpart" without the .1. So in this example I want to join 01.01.2000.1 to 01.01.2000 and 04.01.2000.1 to 04.01.2000 (it's always with this pattern .1 at the end).
If there are two values, they should be comma separated and if one is NA it shall take the other one.
The desired output is:
b <-  data.frame(A = c("01.01.2000", "02.01.2000", "03.01.2000", "01.01.2000.1", "04.01.2000"),
                      B = c("1,1", NA, 2, 1, 4 ),
                      C= c(NA, NA, 4, NA, 1))


text:
Q: Customize getting data from SugarCRM Custom Module by Query parameter in rest api Hi I'm trying to get data from SugarCRM by REST api. It's fine with default module, but with custom module, I got a issue.
I used this example
And getting data from Contacts module which has last name = "abc" is ok with these code:
$get_entry_list_parameters = array(
     'session' => $session_id,
     'module_name' => 'Contacts',
     'query' => "contacts.last_name='abc'",
     'order_by' => "",
     'offset' => '0',
     'select_fields' => array(
          'id'
     ),
     'link_name_to_fields_array' => array(
     ),
     'max_results' => '1',
     'deleted' => '0',
     'Favorites' => false,
);

When I tried to get data from our custom module (eg: Event Session inside Event package), so it's ok as well without Query param like these code
$get_entry_list_parameters = array(
     'session' => $session_id,
     'module_name' => 'event_event_session',
     'order_by' => "",
     'offset' => '0',
     'select_fields' => array(
          'id',
          'name'
     ),
     'link_name_to_fields_array' => array(
     ),
     'max_results' => '3',
     'deleted' => '0',
     'Favorites' => false,
);

But after that I put Query param, I got no record
$get_entry_list_parameters = array(
     'session' => $session_id,
     'module_name' => 'event_event_session',
     'query' => "event_event_session.name='def'",
     'order_by' => "",
     'offset' => '0',
     'select_fields' => array(
          'id',
          'name'
     ),
     'link_name_to_fields_array' => array(
     ),
     'max_results' => '3',
     'deleted' => '0',
     'Favorites' => false,
);

I think the way I used to get data from custom module is not correct.
Anyone can help me resolve this issue. Thank you!
Johnny

A: Are you sure the table name for the custom module is "event_event_session"?

A: When we create any new custom module using module builder then it is asking for key name. So our module will become as key_modulename. So make sure you are passing the key name along with module name. So that way you can access the data of custom new module.


text:
Q: Select Only first two line of a text block I have a VARCHAR column where data is in this format:
John
Smit
Big Street 26
London
England

This in one column, not  5, so I need to select only first two lines:
John
Smit

How can I do this?

A: Find the substring up to the second newline character:
SELECT SUBSTR(address, 1, INSTR(address, CHR(10), 1, 2) - 1) AS name
FROM   table_name;

Which, for the sample data:
CREATE TABLE table_name (address) AS
SELECT 'John
Smit
Big Street 26
London
England' FROM DUAL;

Outputs:

NAME

John Smit

A: You can use REGEXP_SUBSTR:
SELECT
     REGEXP_SUBSTR ( YOURCOLUMN, '(\S*)(\s)'  , 1 , 1 ) || REGEXP_SUBSTR ( YOURCOLUMN, '(\S*)(\s)' , 1 , 2 ) as result
FROM YOURTABLE;

You can check the result here:


text:
Q: TCP connections bottleneck over the internet(SSL handshakes) I've got up some server-client pair that uses epoll, 5 ips with about 100 ports to listen on each.The system is some spawning processes that spawn about 100 server daemons and about 100 connection_maker daemons.
This build can take up to 3-4000 SSL handshakes per second on LAN and only 40 over the internet(under 200ms round-trip), i've tried a lot of things but i just can't see where the bottleneck is. Any hint could be useful(The socket FDs are blocking now but making them nonblocking helps nothing since the degree of parallelism is way bigger than 40 connections per second anyway).

A: Increment your "ulimit" value , if you are using linux.
Thanks,
Justin


text:
Q: Fatal error: Call to a member function prepare() on null in on line 28 This is my first project on PHP and first time encounter this bug which really can't solve after struggle one day.
Can any expert and kind soul here advise how to resolve this error please? My PHP version is 5.6.
Thank you so much,
After I submit my form, it shows below error

Fatal error: Call to a member function prepare() on null in on line 28

My DB connection coding is
<?php
 $DSN= 'mysql:host = localhost; dbname=cms4.2.1';
 $ConnectingDB = new PDO($DSN, 'root', '');

 ?>

Category page that shows line 28 got error on the POD function "prepare"
 if(empty($Category))
{
 $SESSION["ErrorMessage"] = "All fields must be filled out";
 Redirect_to("Categories.php");
 } elseif (strlen($Category)<3) {
 $SESSION["ErrorMessage"] = "Category Title should be greater than 3
 characters";
 Redirect_to("Categories.php");
 } elseif (strlen($Category)>49) {
 $_SESSION["ErrorMessage"] = "Category Title should be less than 50
 characters";
 Redirect_to("Categories.php");
  } else {
 global $ConnectingDB;
 $sql = "INSERT INTO category(title,author,datetime)";
 $sql .="VALUES(:categoryName,:adminName,:dateTime)";
 $stmt = $ConnectingDB->prepare($sql); // - > means PDO object rotation -
 Line 28
 $stmt->bindValue(':categoryName',$Category);
 $stmt->bindValue(':adminName',$Admin);
 $stmt->bindValue(':dateTime',$DateTime);
 $Execute=$stmt->execute();

Please assist. Thank you so much.

A: You may need to remove spaces here: mysql:host = localhost; dbname=cms4.2.1 would be mysql:host=localhost;dbname=cms4.2.1
Also, wrap the connecting statement in a try-catch block to see if you connect correctly.
try {
    $DSN = 'mysql:host=localhost;dbname=cms4.2.1';
    $ConnectingDB = new PDO($DSN, 'root', '');
    $ConnectingDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo 'Connected to Database<br/>';
}
catch(PDOException $e){
    echo $e->getMessage();
}


text:
Q: Get active navigation page in blackberry 10 app I'm making an app with QML/c++ first page with navigation pane is created with qml.
Then the second page is also qml.
On a button press of first page a c++ function is invoked and parsed the second page and have to push to navigation page.
what I'm doing in button press is mentioned below.
QmlDocument *qml = QmlDocument::create("asset:///home.qml");
    if (!qml->hasErrors()) {
        Page *homepage = qml->createRootObject<Page>();
        if (homepage) {
            qDebug() <<"created a homepage";
            navPane->push(homepage);
        }}

But when pushing is done application terminates automatically giving an error.
console output is (created a homepage
Process 304619722 (Sampleapp2) terminated SIGSEGV code=1 fltno=11 ip=78f0a210(/base/usr/lib/libbbcascades.so.1@_ZNK2bb8cascades14NavigationPane7indexOfEPNS0_4PageE+0x707) mapaddr=0010a210. ref=00000010
)
I'm parsing the navigation page pointer to the second c++ file constructor and assigning it to a this->navpange variable.
Should I make navigation pane public in first c++ file header? if so how to do it?
Is there anyway I can get active navigation pane of running app from second c++ file without parsing it?
Thanks in advance :-)
Do I have to make the navigation

A: From the code given, I assume that homepage is unitialized.

A: Zemy from blackberry forums answered me. Credit goes to him.
I think easiest is to pass the NavigationPane as a parameter from QML:
Q_INVOKABLE void function(NavigationPane *pane);
...
pane->push(homepage);

In QML:
_app.function(navPaneId)

But this got an error. Zemy again fixed it.
I've tried to reproduce this and also got the same error message. It seems NavigationPane isn't properly registered in Cascades.
Adding qmlRegisterType() fixed it:
ApplicationUI::ApplicationUI(bb::cascades::Application *app) :
        QObject(app)
{
    // prepare the localization
    m_pTranslator = new QTranslator(this);
    m_pLocaleHandler = new LocaleHandler(this);
    if(!QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged()))) {
        // This is an abnormal situation! Something went wrong!
        // Add own code to recover here
        qWarning() << "Recovering from a failed connect()";
    }
    // initial load
    onSystemLanguageChanged();

    //--------------------------------------
    qmlRegisterType<NavigationPane>(); <---------------- ADDED
    //--------------------------------------

    // Create scene document from main.qml asset, the parent is set
    // to ensure the document gets destroyed properly at shut down.
    QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    qml->setContextProperty("_app", this);

    // Create root object for the UI
    AbstractPane *root = qml->createRootObject<AbstractPane>();

    // Set created root object as the application scene
    app->setScene(root);
}


text:
Q: What does the line with nz do? This is the code for an indicator named Trend Regularity Adaptive Moving Average on trading view.
study("Trend Regularity Adaptive Moving Average","TRAMA [LuxAlgo]",overlay=true)
length=input(99),src = input(close)
//----
ama = 0.
hh = max(sign(change(highest(length))),0)
ll = max(sign(change(lowest(length))*-1),0)
tc = pow(sma(hh or ll ? 1 : 0,length),2)
ama := nz(ama[1]+tc*(src-ama[1]),src)
plot(ama,"Plot",#ff1100,2)

What does the line ama := nz(ama[1]+tc*(src-ama[1]),src) do?
Can you explain in terms of a python code?