text:
Q: How to get pseudo-random uniformly distributed integers in C good enough for statistical simulation? I'm writing a Monte Carlo simulation and am going to need a lot of random bits for generating integers uniformly distributed over {1,2,...,N} where N<40. The problem with using the C rand function is that I'd waste a lot of perfectly good bits using the standard rand % N technique. What's a better way for generating the integers?
I don't need cryptographically secure random numbers, but I don't want them to skew my results. Also, I don't consider downloading a batch of bits from random.org a solution.

A: rand % N does not work; it skews your results unless RAND_MAX + 1 is a multiple of N.
A correct approach is to figure out the largest multiple of N that's smaller than RAND_MAX, and then generate random numbers until it's less than that value.  Only then should you do the modulo operation.  This gives you a worst-case rejection ratio of 50%.

A: in addition to oli's answer:
if you're desperately concerned about bits then you can manage a queue of bits by hand, only retrieving as many as are necessary for the next number (ie upper(log2(n))).
but you should make sure that your generator is good enough.  simple linear congruential (sp?)  generators are better in the higher bits than the lower (see comments) so your current modular division approach makes more sense there.
numerical recipes has a really good section on all this and is very easy to read (not sure it mentions saving bits, but as a general ref).
update if you're unsure whether it's needed or not, i would not worry about this for now (unless you have better advice from someone who understands your particular context).

A: Represent rand in base40 and take the digits as numbers. Drop any incomplete digits, that is, drop the first digit if it doesn't have the full range [0..39] and drop the whole random number if the first digit takes its highest-possible value (e.g. if RAND_MAX is base40 is 21 23 05 06, drop all numbers having the highest base-40 digit 21).


text:
Q: Searching multiple fields with Lucene I'm having some trouble with a search I'm trying to implement.  I need for a user to be able to enter a search query into a web interface and for the back-end Java to search for the query in a number of fields.  An example of this might be best:
Say I have a List containing "Person" objects.  Say each object holds two String fields about the person:
FirstName:  Jack
Surname:    Smith

FirstName   Mary
Surname:    Jackson

If a user enters, "jack", I need the search to match both objects, the first on Surname, and the second on FirstName.
I've been looking at using a MultiFieldQueryParser but can't get the fields set up right.  Any help on this or pointing to a good tutorial would be greatly appreciated.

A: MultiFieldQueryParser is what you want, as you say.
Make sure:

*

*The field names are always used consistently

*The same Analyzer is used on both  fields, and also on the query parser

*You won't find partial words by default, so if you search for jack you won't find jackson. (You can search for jack* in that case.)

Regarding field name, I always set up an enum for my field names, then use e.g. MyFieldEnum.firstname.name() when passing field names to Lucene, so that if I make a spelling mistake the compiler can catch it, and it's also a good place to put Javadoc so you can see what the fields are for, and also a place where you can see the complete list of fields you wish to support in your Lucene documents.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Verifying JWT from Azure Active Directory I have followed the instructions here to obtain an access token for a web API.
https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx
I have this working but the documentation is vague when it comes to figuring out how to validate the token in PHP.

You can use the access token that is returned in the response to authenticate to a protected resources, such as a web API. Typically, the token is presented to the web API in an HTTP request using the Bearer scheme, which is described in RFC 6750. This specification explains how to use bearer tokens in HTTP requests to access protected resources.
When the web API receives and validates the token, it gives the native client application access to the web API.

How do I validate the JWT in  application? I have a PHP framework which is using PHP openssl_verify() function with the token, signiture, key and algorithm but I receive error of when I use the private key from Azure with the SHA256 algorithm:
openssl_verify(): supplied key param cannot be coerced into a public key

This leads me to believe that the key I am using in PHP to validate is not correct. At the moment, I am using the private key I generated for the Active Directory Application, which happens to also be the same value I am using for the "client_secret" parameter when hitting the oauth2/token url (any other value causes no token to be generated so this is probably correct).
The key is similar to (BUT IT NOT ACTUALLY):
cLDQWERTYUI12asdqwezxctlkjpoiAn7yhjeutl8jsP=

Where I beleive openssl needs to have a certificate... if so I can't seem to find where this certificate is in the Azure portal.
What am I missing here? What is the key I should be using with openssl_verify() to verify the JWT and where do I find it in Azure?
Thanks
--
UPDATE:
I have found the public keys here: https://login.windows.net/common/discovery/keys
However I still cannot use the X5C provided to verify the signature. How do you do this in PHP?
--
UPDATE 2:
I used a converted to create a .pem file for the public key using both the 'e' and 'n' parameters. This received a public key.
Now I get OPEN SSL errors when decrypting with it:
error:0906D06C:PEM routines:PEM_read_bio:no start line

A: Closing this question as I have moved on from the origional issue. Updated my question with comments showing how I have progressed.
Created a new question for the new specific issue: How do I verify a JSON Web Token using a Public RSA key?
--
Just in case it helps anyone else:
For further information on a solution to obtaining a public key from Microsoft in PHP I did the following:
$string_microsoftPublicKeyURL = 'https://login.windows.net/common/discovery/keys';

$array_publicKeysWithKIDasArrayKey = loadKeysFromAzure($string_microsoftPublicKeyURL);

function loadKeysFromAzure($string_microsoftPublicKeyURL) {
    $array_keys = array();

    $jsonString_microsoftPublicKeys = file_get_contents($string_microsoftPublicKeyURL);
    $array_microsoftPublicKeys = json_decode($jsonString_microsoftPublicKeys, true);

    foreach($array_microsoftPublicKeys['keys'] as $array_publicKey) {
        $string_certText = "-----BEGIN CERTIFICATE-----\r\n".chunk_split($array_publicKey['x5c'][0],64)."-----END CERTIFICATE-----\r\n";
        $array_keys[$array_publicKey['kid']] = getPublicKeyFromX5C($string_certText);
    }

    return $array_keys;
}

function getPublicKeyFromX5C($string_certText) {
    $object_cert = openssl_x509_read($string_certText);
    $object_pubkey = openssl_pkey_get_public($object_cert);
    $array_publicKey = openssl_pkey_get_details($object_pubkey);
    return $array_publicKey['key'];
}

Its better however to cache these to disk so your not loading these them every time, but this is just a simple example of how to do this.
Then, using the array of public keys, check the JWT header for the 'kid' value to find the correct public cert to verify against and use this in parameter 3 within openssl_verify(). I used the JWT class to deal with this for me.
Using this public key array created above and the JWT class should allow you to validate microsoft JWTs.
Link to JWT class from firebase: https://github.com/firebase/php-jwt
Call JWT::Decode with param 1 of your JWT, param 2 of this public key array and param three of an array of just 'RS256'.
JWT::decode($string_JSONWebToken, $array_publicKeysWithKIDasArrayKey, array('RS256'));

This will throw an exception if the JWT is invalid or return a decrypted JWT for you to use (and check the claims).

A: If you want to verify the jwt then go to jwt.io
This will allow you to paste the JWT and it will then verify the header, claims, and if you add the Public key or private key (depending how the server verifies the signature) it will also verify the signature of the JWT.


text:
Q: Is there a way to use iOS Size Classes without interface builder(programatically)? I have been using Interface Builder with the new xcode 6 and using the Size Classes for interface design. For past projects I just code all the interface and the constraints. This works great since my team can just pull/push/merge the code easily.
Is there a way to continue just using only code and use Size Classes?
I have found several references to Size Classes, but they all mention only the use with Interface Builder:

*

*http://carpeaqua.com/2014/06/14/thinking-in-terms-of-ios-8-size-classes/

*http://mathewsanders.com/designing-adaptive-layouts-for-iphone-6-plus
Edit:
In particular, how to set constraints for different Size Classes by code

A: All IB is doing here is implementing traitCollectionDidChange:. It isn't doing anything you can't do in code by switching on the traitCollection and its horizontalSizeClass and verticalSizeClass, and in fact code might be clearer (and more flexible).


text:
Q: Magento2 store and store view I want to get the names(and the other info ofc.) of all the stores where I have the Magento2 Installation. I do the following:
use Magento\Store\Model\StoreFactory;
...
$this->_storeFactory = $storeFactory->create();
....
$this->_storeFactory->getCollection()->toArray();

And I get the collection into the array. However, the problem is that in the ['name'] column of each item I don't have the name of the Store, but I get the name of the Store View. I've created 3 different stores with 4 Store views - one Store hase 2 Store views, the other 2 stores have only one store view, which makes total of 4, which is the number of the items in the collection. Why is this happening, aren't store and store view to completely different things? This is kind of confusing. How can I get information for a Store like
["store_id"]=> string(1) "The id of the store, not the id of the store view"
["code"]=> string(2) "The code of the store, not the Store view"
["website_id"]=> string(1) "The website Id that the store belongs to"
["group_id"]=> string(1) "1"
["name"]=> string(7) "The actual name of the store, not the name of the view"

A: Never mind, I found it. It is actually the group_id that plays the role of the store_id. So group_id is what should be store_id (and the current store_id should be called something like store_view_id or something) and store_groups is the table where you can find the information about the store. This is so weird in my opinion, but who am I, right ? :)


text:
Q: on focus input button and login button colliding in html i have a login form, whose code is  lie below:

.samaraveera {
  box-sizing: border-box;
  padding-right: 22%;
  padding-bottom: 3%;
  padding-top: 3%;
  display: block;
  margin: 4%;
  padding-left: 17%;

}
.samaraveera:focus + .errspan {display: none;}

.container-login100-form-btn {
  width: 97%;
  margin-top: 2%;
  margin-left: 1%;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.login100-form-btn {
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 20px;
  width: 100%;
  height: 35px;
  border-radius: 3px;
  background: #f2136e;

  font-family: Montserrat-Bold;
  font-size: 12px;
  color: #fff;
  line-height: 1.2;
  text-transform: uppercase;
  letter-spacing: 1px;

  -webkit-transition: all 0.4s;
  -o-transition: all 0.4s;
  -moz-transition: all 0.4s;
  transition: all 0.4s;
}

.login100-form-btn:hover {
  background: #0cc3eb;
}
<input class="samaraveera" type="text" placeholder="Phone Number">

  <input class="samaraveera" placeholder="Password" type="password" name="pass">

  <button class="login100-form-btn">
       Sign in
      </button>

when the input box is focused for entering values, its moving. And the password input box is colliding with login button like below image:

I have one more issue with this input box, when the page loads it loads with the correct width, when I enter some value or focus the input box then the width of the box increases a bit. can anyone please tell me what could be the problem here, thanks in advance

A: First try to use container aligned in center of screen I think. After that your inputs needs to be in certain width to block them from moving.

.container {
  position: fixed;
  width: 300px;
  height: 300px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
}

.form-title {
  width: 300px;
  height: auto;
  padding: 10px;
}

.form-item {
  width: 100%;
  height: 30px;
  border: 1px solid #929292;
  border-radius: 5px;
  display: flex;
  flex-direction: row;
  align-items: center;
  transition: all .3s;
  margin-bottom: 10px;
}

.form-item:focus-within {
  border: 1px solid #ffffff;
}

.icon {
  width: 10%;
  height: 30px;
  background-color: #f2136e;
}

.form-item [type=text], [type=password] {
  width: 90%;
  background-color: transparent;
  border: none;
}

.form-links {
  text-align: center;
  margin-bottom: 20px;
}

.form-links a {
  text-align: center;
  text-decoration: none;
  color: #f2136e;
  font-size: 14px;
}

.form-btn {
  width: 100%;
  height: 40px;
}

.form-btn [type=button]{
  width: 100%;
  height: 40px;
  background-color: #f2136e;
  border: none;
  color: #fff;
  border-radius: 5px;
}

.form-register{
  width: 100%;
  height: 40px;
}

.form-register [type=button]{
  width: 40%;
  height: 40px;
  background-color: transparent;
  border: 2px solid #f2136e;
  color: #f2136e;
  border-radius: 5px;
}

 LOG IN

    <input type="text" name="phone-number" placeholder="Phone number">

    <input type="password" name="phone-number" placeholder="Password">

    <input type="button" name="submit" value="Sign in">

    RESET PASSWORD | LOGIN WITH OPT

    <input type="button" name="register" value="SIGN UP HERE">
     NEW USER?


text:
Q: Prestashop : modify the order of appearance of payment modules in backoffice order I'm trying to customize (with override) the AdminOrdersController.php in prestashop to simplify the life of my sales guys.
When they create an order in the Backoffice, I want to have a specific payment method selected in the lis by default.
For the moment, I just modified the file _select_payment.tpl by adding a array_reverse because my favourite payment method is the latest in the list, but I'm not satisfied with that.
    <select name="payment_module_name" id="payment_module_name">
  {if !$PS_CATALOG_MODE}
    {foreach from=array_reverse($payment_modules) item='module'}
      <option value="{$module->name}" {if isset($smarty.post.payment_module_name) && $module->name == $smarty.post.payment_module_name}selected="selected"{/if}>{$module->displayName}</option>
    {/foreach}
  {else}
      <option value="{l s='Back office order'}">{l s='Back office order'}</option>
  {/if}
</select>

How can I implement the "selected" option in the list on the chosen element ?
(I want to do it also in another list, the order state one)
Thanks for your ideas !


text:
Q: Python - Request being blocked by Cloudflare I am trying to log into a website. When I look at print(g.text) I am not getting back the web page I expect but instead a cloudflare page that says 'Checking your browser before accessing'
import requests
import time

s = requests.Session()
s.get('https://www.off---white.com/en/GB/')

headers = {'Referer': 'https://www.off---white.com/en/GB/login'}

payload = {
    'utf8':'✓',
    'authenticity_token':'',
    'spree_user[email]': 'EMAIL@gmail.com',
    'spree_user[password]': 'PASSWORD',
    'spree_user[remember_me]': '0',
    'commit': 'Login'
}

r = s.post('https://www.off---white.com/en/GB/login', data=payload, headers=headers)

print(r.status_code)

g = s.get('https://www.off---white.com/en/GB/account')

print(g.status_code)
print(g.text)

Why is this occurring when I have set the session?

A: You might want to try this:
import cloudscraper

scraper = cloudscraper.create_scraper()  # returns a CloudScraper instance
# Or: scraper = cloudscraper.CloudScraper()  # CloudScraper inherits from requests.Session
print scraper.get("http://somesite.com").text  # => "<!DOCTYPE html><html><head>..."

It does not require Node.js dependency.
All credits go to this pypi page

A: I had the same problem because they implemented cloudfare in the api, I solved it this way
import cloudscraper
import json
scraper = cloudscraper.create_scraper()
r = scraper.get("MY API").text
y = json.loads(r)
print (y)

A: You can scrape any Cloudflare protected page by using this tool. Node.js is mandatory in order for the code to work correctly.
Download Node from this link https://nodejs.org/en/
import cfscrape #pip install cfscrape

scraper = cfscrape.create_scraper()
res = scraper.get("https://www.example.com").text
print(res)

A: curl and hx avoid this problem. But how?
I found, they work by default with HTTP/2. But requests library used only HTTP/1.1.
So, for tests I installed httpx with h2 python library to support HTTP/2 requests) and it works if I do: httpx --http2 'https://some.url'.
So, the solution is to use a library that supports http2. For example httpx with h2
It's not a complete solution, since it won't help to solve Cloudflare's anti-bot ("I'm Under Attack Mode", or IUAM) challenge

A: This is due to the fact that the page uses Cloudflare's anti-bot page (or IUAM).
Bypassing this check is quite difficult to solve on your own, since Cloudflare changes their techniques periodically. Currently, they check if the client supports JavaScript, which can be spoofed.
I would recommend using the cfscrape module for bypassing this. To install it, use pip install cfscrape. You'll also need to install Node.js.
You can pass a requests session into create_scraper() like so:
session = requests.Session()
session.headers = ...
scraper = cfscrape.create_scraper(sess=session)


text:
Q: OpenGL pixel doubling on an NSOpenGLView I have a 480x320 NSOpenGLView that I'd like to scale up to 960x640, but in a way that pixels appear as twice the size (and sharp).
If I call
[myglview setFrame:CGRectMake(0,0,960,640)];

the view scales up to the desired size, but the pixels rendered by OpenGL calls are still at the native resolution.
How can I scale up the GL view, pixels' size included?

A: You render into a 480x320 FBO, and use this FBO as a texture on a screen-aligned quad with NEAREST filtering in a second pass.


text:
Q: Converting shapefile to .osm.pbf I am trying to convert a GIS LINE shapefile into a .osm.pbf file on Windows.
I've done some research on the topic and some tools that kept coming out are:

*

*Merkaator

*shp2osm - which deals mostly with point shapefile

*shape2osm.py - which keeps bringing up an error with importing * elementtree.SimpleXMLWriter

But nothing seems to be working.

A: According to https://wiki.openstreetmap.org/wiki/Shapefiles you can try JOSM with the OpenData plugin to open a Shapefile.
https://wiki.openstreetmap.org/wiki/Software_comparison/Import_a_shapefile#Advanced:_Conversion_tools lists various other tools for converting a shapefile to OSM data:

There are multiple tools for converting shapefiles into .osm format
  suitable for importing. These include:

*

*Merkaartor — simply import the shp, export the osm.xml.

*shp2osm (and polyshp2osm) — require some programming skill, but very flexible

*shp-to-osm.jar — less flexible, but requires only a simple configuration file

*shape2osm — a Python script that will convert a POINT shapefile to OSM XML

*PostGIS

*

*convert shp to osm using grass and gpsbabel

*Load the shapefile into PostGIS first, using shp2pgsql (feature of PostGIS) May be helpful as first conversion step

*ogr2osm (ogr2osm) — a new script to convert any OGR supported vector format into .osm format, with emphasis in converting polygon
  boundaries into relations

*Using QGIS & GPX Editor to convert to GPX

*

*1) Menu "Plugins/ Manage Plugins..." enable ,,GPS Tools".

*2) Menu "Plugins/GPS Tools/Create new GPS layer"

*3) Select feature(s) in the default layer. Copy, paste into a GPS tracks layer, save the changed layer.

*4) In GPX Editor open the gpx file. Menu "Edit/ OpenStreetMap Tools/ Anonymize time".

*MapCreator-Toolset: ShapeToOsmTool — This C#-OpenSource tool converts a set of shape files to an osm file, applying specific
  conversion rules defined in a dedicated XML conversion rule file.

*

*The tool is simple and flexible.

*The tool can convert many layers (represented by many shape files) to one OSM output file.

*The tool supports the following geometries: Polygon, LineString and Point. A Polygon will be mapped to a Closed OSM Way, a LineString
  to a OSM Way and a Point to a OSM Node.

*With certain limits the tool can convert geometry types (Polygon to Point, LineString to Point), if so wanted.

*The tool supports a flexible Tag generation. The Tag values can be constant or read out of the shape file fields.

*SHPtoOSMBoundaries python script. If the SHP contains Administrative Boundaries and you want to transform them into OSM in
  order to autogenerate and join the multiple boundary relations before
  importing.

Please don't forget that you are not allowed to import a shapefile directly into OSM! See the Import Guidelines for details.

A: I just faced the problem and solved using JOSM and two different plugins:
JOSM -> https://josm.openstreetmap.de/
OpenData -> https://wiki.openstreetmap.org/wiki/JOSM/Plugins/OpenData
PBF -> https://wiki.openstreetmap.org/wiki/JOSM/Plugins/PBF
With this three pices you will be able to convert a .shp file into a .osm.pbf (and probably others formats).


text:
Q: How to make sure a file is selected before uploading Hi I am using codeigniter for file uploading  and I am using this code
echo form_open_multipart('controller_a');
echo form_upload('userfile');
echo form_submit('Upload','upload');
echo form_close();

I store the pointer to the uploaded file in the database,
My question is how do I make sure that the user has selected a file before clicking on upload button because as of now the code submits even if the user clicks directly on upload without selecting a file

A: Along with client side verification, you should use server side verification, too. Currently, CodeIgniter does not provide a function, so one can use native PHP function is_uploaded_file:
if (is_uploaded_file($_FILES['myfile']['tmp_name']))
{
    $this->load->library('upload');

    $this->upload->do_upload('myfile');
}

A: You can't, not in CodeIgniter at least. You'll need to have JS overwrite the onsubmit property of the form and then test the userfile input's value.

A: use JS
very basic code, but it works.
<script type="text/javascript">

<!--

function validate_form ( )
{
    valid = true;

        if ( document.upload_form.something.value == "" )
        {
                alert ( "Please select a file before clicking upload ! " );
                valid = false;
        }

        return valid;
}

//-->

</script>

and use onsubmit even in the form
onSubmit="return validate_form ( );"

when a user click on upload button without selecting any file, it will alert the user .

A: Your best bet is to use a jQuery plugin like the following:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
This will allow you to select what input values will need to be selected, and customize a message to inform the user what field(s) they are missing.


text:
Q: When do we create multiple instances of the same app?
A runtime instance of the Java virtual machine has a clear mission in
  life: to run one Java application. When a Java application starts, a
  runtime instance is born. When the application completes, the instance
  dies. If you start three Java applications at the same time, on the
  same computer, using the same concrete implementation, you'll get
  three Java virtual machine instances. Each Java application runs
  inside its own Java virtual machine.

I was going through this article on run-time instance, i was just not clear about the lines above.
public class Test1 {
    public static void main(String args[]) {
        if (args.length > 0) {
            try {
                for (int i = 0; i < args.length; i++) {
                    System.out.println("Args" + args[i]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

When i run the above class, a runtime instance is born. Once it completes it operation, the runtime-instance dies off.

*

*Let's take stackoverflow.com is hosted some where on the web, does one runtime-instance of the app is enough to serve the people or depending on the load and traffic do we create different instance of the same app on different servers/computers. How and when do you decide we need to create different instances of the same app?

*What does the same concrete implementation mean here? How about different concrete implementations.
I am sorry if my questions are quite vague in any manner, i am learning java but purely working on HTML/CSS and JS.
http://www.artima.com/insidejvm/ed2/jvm.html

A: quite vague: right and so is the answer
2 concrete implementation is a class which has implementation for all of its method (unlike abstract class/ interface)
1 You could stretch your app horizontally if required in cloud based deployment

A: Java machines for personal computers are programs like Word or Internet Explorer or Adobe Reader.
The way they are designed is that if you run three Java programs at the same time, each program has its own JVM started to handle it, as opposed to having multiple tabs open in a single browser windows).
The word instance refers to the operating system considering them as running programs and not just files on your harddisk with a lot of bytes that happen to be named EXE.
Concrete implementation refers to a given installation of Java in e.g. C:\Programs\Java\Java-7.1.2.3\bin\java.exe.  If you run this program three times, you will have three running instances and not just only one.

A: 1:
   How and when would you decide to create different instances of the same app?
If, for example you wanted an app that would be located close to the user, then you could deploy one of them on a server in Asia, one in EMEA, and on in the USA. When your user tries to access it, you route them to the server closest to you and they get the most responsive user experience possible.
Now - this is not possible in all instances, as if you are sharing data (for example, if you were a bank), then you would have to manage the data in a way that makes it consistent across the three instances of your application. That though is perhaps a topic for a different question.
2: Same concrete implementation. This is typically used when you are referring to an abstract class, and choose to have a specific implementation of a class. For example - if you have the abstract class "Car" and have a concrete implementation that implements if of "Ferrari".
In this case, it is using the same terminology, but in a way that is not that common. When the text refers to the concrete implementaiton in this context, it is saying that it is the same program. i.e. you copy and paste the ".exe" and run it again. In Java terms, you would copy the same ".jar" files, and execute it.
However in this case, you could be doing it on different machines, or as stated, you could run them on the same computer, and if you looked in memory you would see three separate java processes.


text:
Q: How to print a string value in single line using Perl My problem is simple one...
My perl code is like below...
 $todaydate = `date +%Y-%m-%d-%H%M%S`;
 $output_file = "my_data_$todaydate".".csv";
 print "SQL query output file name : $output_file\n";

But the Output file name is printing as like below...
SQL query output file name : my_data_2017-10-03-062227
.csv

If you can observe, the .csv is coming in new line.
I have also tried the below join for string conactantion. but still no luck.
$output_file = join "", "my_data_", $todaydate, ".csv";

due to this issue, while i am passing the output_file name to a sql query, its creating a file my_data_2017-10-03-062227 without .csv extension.
Any suggestion please...

A: There are several reasons why you might not want to use external programs unnecessarily.

*

*The external program might not be available (or might work differently) on some systems where you want to run your program. You are therefore making your code less portable.

*Starting a new shell and invoking an external program takes longer than just using a Perl feature to achieve the same result.

*The value returned from an external problem will probably have a newline character at the end - and you might forget to remove it.

Getting a date is a task that people commonly want to use an external program for. And I don't understand why, because Perl has pretty good built-in time and date handling. For example, your code can be written like this:
use Time::Piece;

$todaydate = localtime->strftime('%Y-%m-%d-%H%M%S');
$output_file = "my_data_$todaydate.csv";
print "SQL query output file name : $output_file\n";

Time::Piece has been included with all versions of Perl since 2007. It changes the behaviour of localtime() so it returns an object. And the object has many useful methods - here we use strftime().
If you're stuck with an older version of Perl (pre-5.10) then you can still do this easily without calling an external program.
use POSIX 'strftime';

$todaydate = strftime('%Y-%m-%d-%H%M%S', localtime);
$output_file = "my_data_$todaydate.csv";
print "SQL query output file name : $output_file\n";

A: use chomp in your $todaydate variable.
my $todaydate = `date +%Y-%m-%d-%H%M%S`;
chomp $todaydate;
my $output_file = "my_data_$todaydate.csv";

Always put use warnings; and use strict; in top of the program.

A: Its because of new line character at the end of $todaydate. Use below to fix it:
$todaydate =~ s/\n|\r//g;

The above code will remove any occurrence of \n or \r.


text:
Q: how to install open cv wheel package using pip in python? I have installed the wheels package and have the latest update of pip but when I try running pip install opencv.whl it says "opencv.whl is not a valid wheel filename". I made sure that I'm in the same directory where opencv.whl is present.
I also tried installing the .exe file of opencv but it says:
Could not find a version that satisfies the requirement opencv3 from versions:
No matching distributions found for opencv3


text:
Q: Detect if a block device is a local disk or a removable usb disk There's any way to detect if a block device, like /dev/sda or /dev/sdc, is related to a local disk (scsi or sata I mean) or to a removable USB disk?
I'm writing a shell script that have to detect ONLY local disks block devices, excluding any removable disks.
Thanks!

A: You can use udev, the Linux device manager.
Querying for each block device will show several informations about it, including the bus, which you can use in order to discern if the device is a removable USB one.
This is the script:
for device in /sys/block/sd*; do
  device_info="$(udevadm info --query=property --path=$device)"

  device_name=$(echo "$device_info" | perl -ne 'print "$1" if /^DEVNAME=(.*)/')
  device_bus=$(echo "$device_info" | perl -ne 'print "$1" if /^ID_BUS=(.*)/')

  echo "Device $device_name bus: $device_bus"
done

and this is a sample result:
Device /dev/sda bus: ata
Device /dev/sdb bus: ata
Device /dev/sdc bus: usb

A: Use lshw:
lshw -class disk -class storage

and look for the bus info string.


text:
Q: How do I POST data to a remote URL in Classic ASP? I need to POST data to a url in the middle of a script.

*

*User fills out form:

*Form submits to process.asp: I need to POST data to a 3rd Party integration at this point.

*process.asp finishes and directs user to thank you page.

A: Most form action pages accept data as a POST.
Function postFormData(url, data)
    Dim xhr : Set xhr = Server.CreateObject("MSXML2.ServerXMLHTTP.3.0")
    xhr.open "POST", url, false
    xhr.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    xhr.send Data
    If xhr.Status = 200 Then
       postFormData = xhr.ResponseText
    Else
        Err.Raise 1001, "postFormData", "Post to " & url & " failed with " & xhr.Status
    End If
End Function

When creating the data url encoding is needed on the data values.  Since ASPs Server.URLEncode method only does path encoding and not component encoding you need to replace out / characters with %2F
Function URLEncodeComponent(value)
    URLEncodeComponent = Server.URLEncode(value)
    URLEncodeComponent = Replace(URLEncodeComponent, "/", "%2F")
End Function

A: I'm not sure why everybody else is posting ASP.Net solutions when you specifically said you're using ASP "classic."
Something like this should work.  I didn't write the code; I found it elsewhere.  But the MSXML2.ServerXMLHTTP object is what you want to use if you don't want to purchase something commercial.
function getHTML (strUrl)
    Set xmlHttp = Server.Createobject("MSXML2.ServerXMLHTTP")
    xmlHttp.Open "GET", strUrl, False
    xmlHttp.setRequestHeader "User-Agent", "asp httprequest"
    xmlHttp.setRequestHeader "content-type", "application/x-www-form-urlencoded"
    xmlHttp.Send
    getHTML = xmlHttp.responseText
    xmlHttp.abort()
    set xmlHttp = Nothing
end function

You might need to add some error-handling code to that for use in a production environment.  I believe that object throws errors if it gets a 404 or timeout error.  You'll need to "trap" them ASP-style (yuck) by setting On Error Resume Next before the .Send and then examine the ASP error object to see if there was a problem.
Good luck!

A: In .Net it's System.Net.WebClient or System.Net.HttpWebRequest.
Classic ASP has a completely different api- I'm not sure what you would use instead there.
[edit]
I suspect that if classic asp has any built in support for this, it's in a Scripting object, like so: CreateObject("Scripting.????")

A: If you're stuck with class ASP, you can do it with the commercial ASPHTTP library here:
http://www.serverobjects.com/comp/asphttp3.htm

A: In ASP.NET, it's pretty simple:
HttpWebRequest r =
  (HttpWebRequest)WebRequest.Create("http://www.google.com");
r.Method = "POST";
using (Stream stream = myRequest.GetRequestStream()) {
    // Write data to stream
}
WebResponse resp = r.GetResponse();
// Do soemthing with the resp

A: OK all the answers were very complicated and I know you already selected a solution - but I feel like the simple Server.Transfer() command could have done exactly what you need.
At the end of your script instead of Response.Redirect(url) to the new page - just do a Server.Transfer(url) and it will pass your entire Request collection across to the next page.
Read about it here (support.microsoft.com).
There are some catches (i.e. it keeps the same URL on the browser so it can play tricks with the back button and such) but otherwise it's pretty simple.

A: Use the class described here. This is a pretty good method and I use it all the time:
http://www.jigar.net/articles/viewhtmlcontent78.aspx
public class  RemotePost{
     private  System.Collections.Specialized.NameValueCollection Inputs
     = new  System.Collections.Specialized.NameValueCollection() ;

    public string  Url  =  "" ;
    public string  Method  =  "post" ;
    public string  FormName  =  "form1" ;

    public void  Add( string  name, string value ){
        Inputs.Add(name, value ) ;
     }

     public void  Post(){
        System.Web.HttpContext.Current.Response.Clear() ;

         System.Web.HttpContext.Current.Response.Write( "" ) ;

         System.Web.HttpContext.Current.Response.Write( string .Format( "" ,FormName)) ;

         System.Web.HttpContext.Current.Response.Write( string .Format( "<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >" ,

        FormName,Method,Url)) ;
            for ( int  i = 0 ; i< Inputs.Keys.Count ; i++){
            System.Web.HttpContext.Current.Response.Write( string .Format( "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">" ,Inputs.Keys[i],Inputs[Inputs.Keys[i]])) ;
         }
        System.Web.HttpContext.Current.Response.Write( "</form>" ) ;
         System.Web.HttpContext.Current.Response.Write( "" ) ;
         System.Web.HttpContext.Current.Response.End() ;
     }
}

Use it like:
RemotePost myremotepost  =  new  RemotePost() ;
myremotepost.Url  =  "http://www.jigar.net/demo/HttpRequestDemoServer.aspx" ;
myremotepost.Add( "field1" , "Huckleberry" ) ;
myremotepost.Add( "field2" , "Finn" ) ;
myremotepost.Post() ;

A: You can do it by many way. With  WebClient
 WebClient Client = new WebClient ();
 Client.DownloadFile("http://www.stackoverflow.com/myfile.html", "myfile.html");

Or you can put the data in a stream to use it in your program:
WebClient Client = new WebClient ();
Stream strm = Client.OpenRead ("http://www.stackoverflow.com/myfile.htm");

But I do prefer use HttpWebRequest:
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("http://www.stackoverflow.com/myfile.html");
StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream());

I prefer the second one because you can have more option for POST/GET or for Cookie.


text:
Q: Selecting a value from output of ps -eaf Suppose i want to select 6547 from this output of "ps -eaf"
command, how do i do it? I want to select that value and give it to "kill" command to kill that process.
root      6547     1  0 Aug07 ?        00:00:00
root     14805     2  0 Aug07 ?        00:00:00
root     17443 30043  0 16:21 pts/0    00:00:00

A: You may have to write a small shell script - which will basically contain below option -
    pidList=`ps -eaf | awk ' print $2'`
    for pid in pidList
    cmd="kill -9 $pid"
    `$cmd`

Now based on your critieria (like process name, user etc) you can take action for that specific process. So the jist here is to use awk command to get your exact column.


text:
Q: SQLite pagination in a dynamic table I have an SQLite table that changes very often, many times per minute. It is easily thinkable as a table of torrents, where new torrents are appended to the end of the table, and old ones (completed) are removed from the beginning.
This is presenting a logical headache for me to implement pagination, where there could be 100s of torrents in the table, but the table is changing rapidly. I am writing this in C++, with a GUI written in Javascript/HTML. Here is my logic so far. I think I know what I need to do, but I don't know how.

Given:

*

*The UI will always ask for a list of rows based on the page #, not SQL Ids

*The UI will always set the number of rows per page (10 in this eg)

*The app will always return to the UI the # of pages and the current page

On initialization, the UI will ask for Page 1 of data, limited to 10 rows . The application logic then is as follows

*

*Get the number of rows in the table. (100)

*Get the number of pages in the table (100 / 10) = 10

*Get the first 10 rows. This can be done many ways, such as simply using LIMIT set to 10

The application function I have available looks something like this
GetDbRows( startId, limit );
So the UI (currently) must know the row ID to start at. If this is a static table, this is easy. The application returns the last ID to the UI. But it is a dynamic table, so this ID is meaningless. The last ID could actually be gone by the time the next page is requested.
So, using application logic, how can I properly split the DB into pages, and ask for page 2, for example? Can I do this without having to literally get all row IDs and split them? Is there any SQL syntax to do this for me? Such as GET id at page 3

A: From Richard Critten

Will LIMIT followed by OFFSET do what you want eg SELECT * FROM mytable LIMIT 10 OFFSET 20? See: sqlite.org/lang_select.html This would give you the 3rd page

enter image description here
LIMIT
The LIMIT clause is used to place an upper bound on the number of rows returned by the entire SELECT statement.
In a compound SELECT, only the last or right-most simple SELECT may contain a LIMIT clause. In a compound SELECT, the LIMIT clause applies to the entire compound, not just the final SELECT. If the right-most simple SELECT is a VALUES clause then no LIMIT clause is allowed.
OFFSET
Instead of a separate OFFSET clause, the LIMIT clause may specify two scalar expressions separated by a comma. In this case, the first expression is used as the OFFSET expression and the second as the LIMIT expression. This is counter-intuitive, as when using the OFFSET clause the second of the two expressions is the OFFSET and the first the LIMIT. This reversal of the offset and limit is intentional - it maximizes compatibility with other SQL database systems. However, to avoid confusion, programmers are strongly encouraged to use the form of the LIMIT clause that uses the "OFFSET" keyword and avoid using a LIMIT clause with a comma-separated offset.


text:
Q: How to have a drop-down menu that updates itself after submission? Here is my drop-down form. I have searched and still do not understand how to have a selected drop-down value remain after the cart is updated. Maybe it is because of the PHP in the name value? I would greatly appreciate any help. I believe this has to be done with javascript, but again I am unsure.
<select id="quantity" name='.$cart[$x]['ASIN'].'>
<option value=1>1</option>;
<option value=2>2</option>;
<option value=3>3</option>;
</select></td>';

Thanks,
Eric

A: As I understand it, you want the selected item to remain selected after the form is submitted and the page is refreshed... in this case you will need to do something like this:
<select name='mySelect'>
    <option value=1 <?=(isset($_POST['mySelect'])&&$_POST['mySelect']==1?'selected':'')?>>1</option>

Basically for each option you need to check if that select has a value, and if that value matches the current option ... if so, echo 'selected' which will set that option to the current displayed choice.
Unless, you have a situation where you're on like a profile page or something, and you want the user to be able to see his current setting, and still be able to change it... then you would need to do something similar but replace $_POST['mySelect'] with the data from the database. So if you have an array of user data, $data, and one of those values is 'quantity' that corresponds with the select, then you would need:
<option value=1 <?=($data['quantity']==1?'selected':'')?>>1</option>


text:
Q: Honorary gifts? Is it correct to use the phrase honorary gifts to describe gifts that are given to honor someone? The normal usage of honorary is "given as an honor without the normal duties" (as in an honorary degree), which conveys quite a different implication.

A: The word honoraria is used to convey gifts or payments made in this sense:

a payment in recognition of acts or professional services for which
  custom or propriety forbids a price to be set

However, if you actually mean that you are giving a gift in their honor, then "honorary gift" is a perfectly acceptable term. See, for example, the Metropolitan Opera's page on Memory & Honorary Gifts, or the results from this search term.

A: dictionary.reference.com's entry for honorary includes the following definition:

5. given, made, or serving as a token of honor: an honorary gift.

While I have not come across the term (or received one, for that matter) myself, Google's search results suggest that it is in use. Google Books also provides some examples of its usage.
According to the University of Colorado Foundation:

Honorary gifts are a meaningful way to pay tribute to a living person. It may honor a special occasion or achievement, or merely acknowledge the honoree's importance in your life.
Any type of gift can be designated as an honorary gift.

The School of Public Health at UCB states:

Honorary gifts commemorate a significant event or someone who is still living.

Therefore, it appears to be perfectly acceptable to honour someone with an honorary gift.

A: I think OP would be unwise to use the expression "honorary gifts" for his intended sense. It's not a well-established term with a clear-cut meaning, but here's one site's take...

A memorial gift can help perpetuate the values and ideals that defined a loved one's life. Honorary gifts commemorate a significant event or an exceptional person who is still living.

I see many sites making a similar distinction between memorial and honorary gifts. My guess is they don't normally mean the honorary gift actually goes to the person being honoured. More likely you're making a gift/bequest to a "trust fund". Perhaps a trust set up by the person being honoured,  who is still alive; perhaps in honour of a sick relative who's about to die but hasn't yet.

A: You could try "honorific gifts".
Honorific:

Showing or conferring honour and respect.

That may not be ideal either, I tend to think of "honorific" as a title, e.g. Lord Lieutenant kurkevan.

A: Honorary gifts is an uncommon and potentially confusing usage.   More typically you will find them dubbed Honor Gifts, Gifts in Honor Of, or In Honor Gifts.
See, for example:

*

*American Kidney Foundation ("Gifts In Honor Of" / "Honor Gifts")

*American Lung Association ("Honor Gift")

*American Health Assistance Foundation ("In Honor Gift")

A: While "token of appreciation" is often used for a small gesture that is meant to honor the person receiving the gift, "gift of appreciation" can also be used (11,500 hits on Google Books vs. 76,000 hits for "token of appreciation").


text:
Q: InvalidIndexError error mapping dask series This mapping works when calling head on the first 100 rows:
ddf['val'] = ddf['myid'].map( val['val'] , meta=pd.Series(float) )
But when I try to save to parquet:
ddf.to_parquet('myfile.parquet',
               compression='snappy',
               write_index=False,
               compute_kwargs={'scheduler':'threads'}
              )

I am getting an error: InvalidIndexError: Reindexing only valid with uniquely valued Index objects.
But checking my index (after converting to pandas series), it is unique: val.index.duplicated().any() is False.  Also, the index is the same set as the dataframe column it is being mapped to: myid.  There are no nulls, nans, or Nones in the index.  The index is int64.
Update: curiously, if I load each parquet file for the original ddf one at a time, this does not error.  If I load more than one at a time, it errors out.

A: This could be a bug in the fastparquet engine.  I saved the underlying dataframes with pyarrow and used to_parquet with engine='pyarrow' and things are working now:
ddf.to_parquet('myfile.parquet',
               engine='pyarrow',
               compression='snappy',
               write_index=False,
               compute_kwargs={'scheduler':'threads'}
              )


text:
Q: Backpropagation algorithm in neural networks (NN) with logistic activation function In this Coursera course by Geoffrey Hinton, the backpropagation algorithm is described starting at min 8 of this video, and when completed it looks like this:

The slides can be found here.
Now, the critical value to assess is $\color{blue}{\frac{\partial E}{\partial w_{ij}}}$, which relates the changes in the error in the training set $(E)$ to the set of weights $(w_{ij})$.
Working through the equations, $\color{blue}{\frac{\partial E}{\partial w_{ij}}}$ depends on $\color{red}{\frac{\partial E}{\partial z_j}}$:
$$\color{blue}{\frac{\partial E}{\partial w_{ij}}}= y_i\,\color{red}{\frac{\partial E}{\partial z_j}}$$
We find $\color{red}{\frac{\partial E}{\partial z_j}}$ in the first equation:
$$\color{red}{\frac{\partial E}{\partial z_j}}=y_j\,(1-y_j)\,\color{orange}{\frac{\partial E}{\partial y_j}}.$$
Unfortunately, it feels as though we get into a loop on the second equation, where this latter partial of $E$, the expression $\color{orange}{\frac{\partial E}{\partial y_j}}$ seems to recursively refer us back to $\color{red}{\frac{\partial E}{\partial z_j}}:$
$$\color{orange}{\frac{\partial E}{\partial y_j}}=\sum_j w_{ij}\color{red}{\frac{\partial E}{\partial z_j}}$$
What am I missing? What is the right way of walking though the three equations on the posted image?

EDIT:
After the comment regarding the last layer being simply the partial derivative of the loss function, is it as follows:
$$\frac{\partial E}{\partial y_i}=\frac{\partial \frac{1}{2}(y-y_i)^2}{\partial y_i}=y_i-y$$
?

A: Yes you got it right.
Just to add (sorry for being nitpicky :), when you write $\frac{\partial E}{\partial y_i}$ it is implied that the output is a vector, so maybe writing
$$\frac{\partial\frac{1}{2}\sum_i(t_i - y_i)^2}{\partial y_i} = \frac{\partial\frac{1}{2}(t_i - y_i)^2}{\partial y_i} =  y_i - t_i$$
would be more clear, for $T = (t_1, \dots, t_n)^T$ being the correct output.


text:
Q: jsf spring integration error i want to integrate jsf with spring. when i insert application tag in  faces config files and use the context loader listener in web.xml file, it is showing "The requested resource (/SampleWeb/faces/registration.xhtml) is not available."
here is my faces config file:
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">

    <application>
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    </application>

    <managed-bean>
        <managed-bean-name>empbean</managed-bean-name>
        <managed-bean-class>com.java.EmployeeBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
        <managed-property>
            <property-name>employeeBo</property-name>
            <value>#{employeeBo}</value>
        </managed-property>
    </managed-bean>

    <managed-bean>
        <managed-bean-name>employeeBo</managed-bean-name>
        <managed-bean-class>com.java.EmployeeBOImpl</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
        <managed-property>
            <property-name>employeeDto</property-name>
            <value>#{employeeDto}</value>
        </managed-property>
    </managed-bean>

    <navigation-rule>
        <display-name>registration.xhtml</display-name>
        <from-view-id>/registration.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>register</from-outcome>
            <to-view-id>/welcome.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>

</faces-config>

here is the web.xml file:
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>

  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>

  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>

A: Need to add RequestContextListener as listener whenever you are trying to integrate Spring with either JSF or Struts
<listener>
  <listener-class>
     org.springframework.web.context.request.RequestContextListener
  </listener-class>
</listener>


text:
Q: Test the convergence of the series $\sum \sin [\pi(\sqrt5+2)^n]$ I have just approached the following series
$$\sum_{n=1}^\infty \sin [\pi(\sqrt5+2)^n]$$
And I already have a question. The $\lim_{n \to \infty}\pi(\sqrt5+2)^n=+\infty$. And the $\lim_{n\to \infty} \sin[\pi(\sqrt5+2)^n]$ does not exist.
Can $\sum a_n$ converge if $\lim_{n\to \infty}a_n$ does not exist? I guess the answer is yes because I know that $\sum a_n$ cannot converge if $\lim_{n\to \infty}a_n\neq 0$. Am I right?
The second part of my question concerns the strategy to use to test convergence of such a series. I can test convergence of series with standard tests. But it seems I need to develop a more sophisticated approach in order to successfully deal with series like this. For example, here, should I use some sort of expansion? If yes, what kind of expansion?
Thank you for your help.

A: As $n$ increases, $(2+\sqrt{5})^n$ gets closer and closer to an integer, since:
$$ (2+\sqrt{5})^n + (2-\sqrt{5})^n \in \mathbb{Z}. $$
If $[x]$ is the distance of $x$ from the closest integer, we have:
$$ [(2+\sqrt{5})^n] = (\sqrt{5}-2)^n =\frac{1}{(2+\sqrt{5})^n}<\frac{1}{4^n},$$
hence:
$$ |\sin(\pi(2+\sqrt{5})^n)| \leq \frac{\pi}{4^n}, $$
giving that the original series is convergent.


text:
Q: How can we split a string without removing any characters from the string in Java? I have a string like this:
String str = "How {$can} {$we} split this {$string}?";

I have to split it into several chunks:
["How ","{$can}"," ","{$we}"," split this ","{$string}","?"]

A: You can use this split:
String str = "How {$can} {$we} split this {$string}?";

String[] arr = str.split("(?=\\{)|(?<=\\})");

RegEx Demo
RegEx Breakup:
(?=\\{)   # if next char is {
|         # regex alternation
(?<=\\})  # if previous char is }

Read about look arounds in regex


text:
Q: How to calculate the intersection point of a vector and a plane defined as a point and normal vector? I've read through some of the questions on line-plane intersection but I'm struggling because many define the plane in a format like:
$4x-2y+5z-9=0$,
but my plane is defined as a point ($x_p, y_p, z_p$) and the unit vector normal to the plane ($i_p, j_p, k_p$).
My line is defined by a point ($x_v, y_v, z_v$) and a unit vector in the direction of the line ($i_v, j_v, k_v$),
I can't figure out how to apply what I've read in other questions to my scenario, which I will need to implement in some generic VB.NET code.

A: Let $P_p=(x_p,y_p,z_p)$, $P_v=(x_v,y_v,z_v)$, $\vec{v_v}=(i_v,j_v,k_v)$ and $\vec{v_p}=(i_p,j_p,k_p)$. Then
$$P_{intersection} = P_v + \frac{(P_p-P_v)\cdot\vec{v_p}}{\vec{v_v}\cdot\vec{v_p}} \ \vec{v_v}$$
I assume you already know the basics of operations with vectors and points...

EDIT: This formula can be easily derived from the vectorial definition of planes and lines. A point $P$ belongs to the plane defined by $P_p$ and $\vec{v_p}$ if $(P-P_p)\cdot\vec{v_p}=0$. Moreover, points of the line defined by $P_v$ and $\vec{v_v}$ are of the form $P_v+\lambda \vec{v_v}$. Note that the intersection point has to satisfy both conditions, so it is enouh to plug in the line form into the plane equation and solve:
$$(P_v+\lambda \vec{v_v}-P_p)\cdot\vec{v_p}=0 \iff \lambda =\frac{(P_p-P_v)\cdot\vec{v_p}}{\vec{v_v}\cdot\vec{v_p}}$$
Of course, if $\vec{v_v}\cdot\vec{v_p}=0$, both elements would be parallel, so there would not be any intersection point.

Edit: the originally stated formula was incorrect. This has now been fixed.

A: If $\vec P=(x,y,z)$ is some point of the plane that is given by point $\vec A$ and a normal $\vec n$, then by definition of normal the vector $\vec{AP}=\vec P -\vec A$ is perpendicular to $\vec n$, so the scalar product $\vec{AP}\cdot\vec n=0$.
By writing this in coordinate form, you will get the plane equation:
$$
(x-x_v)i_v+(y-y_v)j_v+(z-z_v)k_v = 0,\\
i_vx+j_vy+k_vz-(i_vx_v+j_vy_v+k_vz_v)=0
$$


text:
Q: Moving the back ground screen as well as maintaning the tragetory path of a ball in Iphone Game apps I have game application (cocos2d) in which, a ball is to be shooted from a cannon, this ball travels through a trajectory path and land on a building. Now the problem is that according to the requirement I have to increase the size of the background image due to which my building image is not visible on first view and with the ball traveling i have to drag the background image with out disturbing the trajectory path of the ball. Can some one help me out in this regards. To clarify question bit more I am also attaching a image. Thanks in advance.

A: In cocos2d the easiest way to accomplish this is to move your entire layer.  If you're doing things in the normal cocos2d way, you have a class that subclasses CCLayer.
Within that class you can simply change its position and you'll get the desired effect.
In your example, since you want to move the "camera" to the right, you can simply move the layer to the left.  for example:
-(void) centerOnBuilding {
    CGPoint distanceToMove = ccp(-120, 0);
    self.position = ccpAdd(distanceToMove, self.position);
}

That function, in a CCLayer, will have the effect of centering the camera 120 pixels to the right of where it was before.  If you want to have a scrolling effect, do the same thing but run a MoveTo or MoveBy action in the layer.

A: what you have are two different coordinate spaces that should be independent from each other.
The ball should move in the "world" coordinate space, independently from the "screen" coordinate space. Of course that the "world" must be displayed on the "screen", so you must convert the "world" coordinate space to "screen" coordinate space, which in you case is a simple translation that can be done by adding an offset.
On iPhone, you can simply put all the "world objects" inside a UIView and move that 'UIView' left and right, while the world objects move relatively to the "world" inside that view, and the conversion from "world coordinate space" (the view coordinate space) to the screen coordinate space will be done for you when the view is drawn on screen.


text:
Q: How can I make std::make_pair usable with std::bind*? I'd like to use std::make_pair usable with e.g. std::bind2nd so that I get an unary function object which I could use with e.g. std::transform.
Right now I'm using
template <typename T, typename U>
struct pair_creator : std::binary_function<T, U, std::pair<T, U> >
{
    std::pair<T, U> operator()( T arg1, U arg2 ) const {
        return std::make_pair( arg1, arg2 );
    }
};

// ...

std::transform( start1, end2, start2, std::bind2nd( pair_creator<int, bool>(), true ) );

but I wonder - is there an easier way to make std::make_pair (or potentially any other binary function) usable with the binders except by writing little wrapper classes like pair_creator by hand?
I'd need a C++03 solution (for some obscure reason, stackoverflow always rewrites my c++0x tag to c++11 when saving the post...).

A: You need std::ptr_fun, which turns a plain function pointer into an adaptable binary function object (or a unary function object, if you pass it a one-arg function):
#include <functional>
#include <utility>
#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> intvec;
    intvec.push_back(0);
    intvec.push_back(1);
    std::vector<std::pair<int,bool> > pairvec(intvec.size());
    std::transform(
        intvec.begin(),
        intvec.end(),
        pairvec.begin(),
        // this is the significant line
        std::bind2nd(std::ptr_fun(std::make_pair<int, bool>), true)
    );
    std::cout << pairvec[1].first << " " << pairvec[1].second << "\n";
}

ptr_fun is declared:
template <class Arg1, class Arg2, class Result>
pointer_to_binary_function<Arg1,Arg2,Result>
ptr_fun(Result (*)(Arg1,Arg2));

And for the unary version:
template <class Arg, class Result>
pointer_to_unary_function<Arg,Result>
ptr_fun(Result (*)(Arg));

A: Use lambda don't need to use bind adaptor.
    std::vector<int> start1 = list_of(1)(2)(3)(4)(5);
    std::vector<int> start2 = list_of(10)(20)(30)(40)(50);
    std::vector<Pair> w_vecofpair; // vector of pair
    w_vofpair.reserve(start1.size());
    // create pair using lambda
    std::transform( std::begin(start1), std::end(start1), std::begin(start2), // ranges
        std::back_inserter(w_vecofpair),  // result
        [](int a,int b) { return std::make_pair(a,b);}); // pair creator

    for (auto& pairInt : w_vecofpair)
    {
        std::cout << pairInt << "\n";
    }

    // bind 2nd arg to some value, say 2
    std::transform( std::begin(start1), std::end(start1), std::begin(start2),
        std::back_inserter(w_vecofpair), [](int a, int b) { return std::make_pair(a,2);});

    for (auto& second : w_vecofpair | map_values)
    {
        std::cout << "The second value of our bind 2nd is: " << second << "\n";
        assert(second==2);
    }


text:
Q: Django passing Polish characters to Angular in init causes lexer error Here's the problem - I would like to pass from Django to Angular data using init. I would do that in the following way:

Which seems fine, right? However, it fails once the variable {{supervision.supervisor}}contains characters like 'ż' with Lexer Error: Unexpected next character.
Is there a smart way to deal with the problem on Django side without the need to wider the range of characters allowed in Angular?

A: You need to put the value in quotes.

A: Here's what I ended up doing:
I've added a function to the controller scope:
$scope.initialize = function(data){
    $scope.supervisor = data;
};

and then I did this in my html template:
ng-init="initialize( '{{supervision.supervisor}}');

And now it works. Hope it help you if you have the same problem!


text:
Q: WP-CLI How to generate a list of posts with corresponding meta values I created this SQL query to generate a list of posts (which I will use for a CSV Sheet)
SELECT p.ID, p.post_content, p.post_title, pm1.meta_value as 'Amazon.com', pm2.meta_value as 'Amazon.co.uk'

FROM wp_posts p

LEFT JOIN wp_postmeta pm1 ON p.ID = pm1.post_id AND pm1.meta_key = 'Amazon.com'
LEFT JOIN wp_postmeta pm2 ON p.ID = pm2.post_id AND pm2.meta_key = 'Amazon.co.uk'

WHERE post_type = 'post' AND post_status = 'publish'

I'm trying to accomplish the same using WP-CLI, using 'wp list' and such, but I haven't been able to find a way list all posts with their meta fields in one row.
How can I accomplish this using WP-CLI ?

A: Just figured it out.  This isn't clearly or explicitly documented at https://developer.wordpress.org/cli/commands/post/list/ or elsewhere.
wp  post list --fields=ID,post_title,Amazon.com,Amazon.co.uk --meta_key=Amazon.com --meta_key=Amazon.co.uk


text:
Q: How do I set up a wireless router as a repeater? I have two Buffalo WZR-HP-G300NH routers.  They are both running DD-WRT v24SP2-EU-US (08/19/10) std - build 14998 firmware.
I would like to set them up so that one is a wireless repeater of the other.  I would like to run WPA2 Personal Mixed (TKIP+AES) encryption on them.  I'd prefer them to be on the same subnet.  Is this possible?  How do I configure this?  I have tried following the directions at the DD-WRT site, but I can't seem to make it work.

A: I read this, and came accross the answer on page 8:

WDS Station is the client in a WDS-AP <-> WDS
  station bridge. This is a special wireless
  networking mode that offers better
  flexibility and security than the classical
  MAC address based WDS.

Would a WDS network fit your requirements?


text:
Q: Is there a version of NeoJSON that works in Pharo 1.1? Is there a version of NeoJSON that works in Pharo 1.1?  If so, how do I access this version?  Is there a better place or way to ask this question, other than StackOverflow?

A: NeoJSON is newer than Pharo 1.1, so there probably is no version designated for it. What happens if you just try loading the newest version? The pharo users mailing list is the right place for this kind of question. If it does not load, it is easiest to load the latest version in the latest Pharo, and make a version that can load in Pharo 1.1 there


text:
Q: Amused to, by, with: Which one? How should I use "amuse" with prepositions in phrases? Is following examples correct?

*

*Amused by something: Being entertained by something

*Amused with something: Being entertained with something

*This part is from a music album named "Amused to Death". Does it mean being entertained so much with something that you can't pay attention to anything else? Put it another way, does it mean extremely amused?

A: "Amused by" is common, and "amused at", "amused with" are both used.
You sometimes see "She was amused to hear that ..." But here "to" isn't a preposition (it is forming the infinitive of the verb), but otherwise "amused to" isn't common.
There is another pattern "... to death". You can say "He was shot to death" or "She was loved to death". It means "He was shot, and it killed him"  (loved to death is a figurative use of the expression). The album title "Amused to death" follows this pattern, but it is deliberately an odd expression. People don't say "amused to death". Album titles often take a common expression and change part of it to create something original.


text:
Q: ROS download unable to locate package error I have Ubuntu 20.04 LTS and I want to download ROS Melodic
I have followed this instruction from here.
After sudo apt install ros-melodic-desktop-full command terminal is showing:
Unable to locate package ros-melodic-desktop-full

A: *

*Make sure to configure your Ubuntu repositories to allow restricted, universe, and multiverse. See this for a guide on how to do that.

*Issue the following command into terminal to setup your computer to accept software from packages.ros.org
sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list'

*Setup your keys by issuing the following into terminal:
curl -sSL 'http://keyserver.ubuntu.com/pks/lookupop=get&search=0xC1CF6E31E6BADE8868B172B4F42ED6FBAB17C654' | sudo apt-key add -

*Update your packages
sudo apt update

*Now install:
sudo apt install ros-melodic-desktop-full


text:
Q: Express Mongoose use Dot Notated Field as Field to Update I am trying to use Express to update my Mongoose model fields dynamically.
The data sent to the route handler from the ajax call looks like this:
{ value: true, name: 'settings.follow.state' }

As you can see the value is a "dot notated string?" and I would like to use that as the field selector to update my Mongoose model.
So my client ajax call looks like this:
$("[name='settings.follow.state']").on("change",function () {
   $.ajax({
       url : window.location.pathname +"/update",
       type : "POST",
       contentType: "application/json",
       data : JSON.stringify({
           value : $(this).is(":checked"),
           name : "settings.follow.state"
       }),
       success:function (response) {
           console.log(response);
       }
   });
});

Also, do I need to JSON.stringify my data when using express?
This is my Express route handler:
router.post("/:id/update",[
    oneOf([
        check("value","Field cannot be empty.").isBoolean(),
        check("value","Field cannot be empty.").not().isEmpty()
    ]),
    check("name","Missing name field.").not().isEmpty(),
],function (req,res,next) {
    let errors = validationResult(req);
    if(!errors.isEmpty()){
        return res.status(400).send(errors.array()[0].msg);
    }

    Profile.findOne({_id:req.params.id,user:req.user._id}, function (err,doc) {
        if(err) return next(err);
        if(doc !== null){
            TwitterSettings.findOne({_id:doc.settings},function (err,doc) {
                if(err) next(err);
                if(doc !== null){
                    //HERE is where I would like to update the dynamic fields/values
                    doc.set(req.body.name,req.body.value);
                    //Tried with no avail :-(
                    // doc.set([req.body.name],req.body.value);
                    // doc.set(`${req.body.name}`,req.body.value);
                    doc.save(function (err,doc) {
                        if(err) return next(err);
                        if(doc !== null){
                            return res.status(200).json(doc);
                        }
                        return res.status(400).send("Could not update profile.");
                    });
                }else{
                    return res.status(400).send("Could find profile settings to update.");
                }
            });

            // TRIED findOneAndUpdate too
            // TwitterSettings.findOneAndUpdate({_id:doc.settings},{$set:{[req.body.name] : req.body.value}},{"new":true},function (err,doc) {
            //     if(err) return next(err);
            //     if(doc !== null){
            //         return res.status(200).json(doc);
            //     }else{
            //         return res.status(400).send("Could not update profile.");
            //     }
            // });
        }else{
            return res.status(400).send("Could find profile to update.");
        }
    });
});

My Mongoose mode schema (just incase you need it):
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
    followers : {type:Number,default:0},
    followings : {type:Number,default:0},
    follow:{
        state : {type:Boolean,default:false},

    },
    un_follow:{
        state : {type:Boolean,default:false}

    },
    follow_back:{
        state : {type:Boolean,default:false}

    },

});
const model = mongoose.model('TwitterSettings', schema);
module.exports = model;

I am sure there is someone that is smarter than me that can point me in the right direction.
Thanks
Carl

A: Okay, so you have a collection named TwitterSettings and you want to update the value at the follow.state path.
I would usually use the nessy module for that.
const nessy = require( "nessy" );

...

Profile.findOne({_id:req.params.id,user:req.user._id}, function (err,doc) {
   ...
   TwitterSettings.findOne({_id:doc.settings},function (err,doc) {
       ...
       nessy( req.body.name, req.body.value, doc );
       doc.save( function( err, doc ) {
           ...
       } );
       ...
   } );
   ...
} );

What you should keep in mind that is that req.body.name actually contains settings.follow.state, so you should remove that from the req.body.name :
nessy( req.body.name.replace(/^settings\./, ""), req.body.value, doc );

EDIT
Actually based on the comment you can simply use model.set() and the dot notation without settings. part in it.


text:
Q: Multiply two 2D array using Recursive methods? I am trying to multiply two 2D arrays using a recursive method. I wrote this code
   public static int mul(int i, int j, int[][]A, int[][] B){
    if(i>(A.length-1) && j>(A[i].length-1)) return 0;
    int x = A[i][j]*B[i][j];
    System.out.println(x);
    return mul(++i, ++j, A, B);

}

  public static void main(String[] args){
    Scanner k= new Scanner(System.in);
    int[][] A = new int[2][2];
    int[][] B = new int[2][2];

    for(int i=0;i<A.length;i++){
        for (int j=0;j<(A[0].length); j++){
            A[i][j]=k.nextInt();

        }

    }
    for(int i=0;i<B.length;i++){
        for (int j=0;j<(B[0].length); j++){
            B[i][j]=k.nextInt();

        }

    }

    mul(0, 0, A, B);
    }

But I got this error message:
java.lang.ArrayIndexOutOfBoundsException: 2
at recursive.mul(recursive.java:5)
at recursive.mul(recursive.java:7)
at recursive.mul(recursive.java:7)
at recursive.main(recursive.java:32)
Thank you so much!

A:
First check if multiplication between matrices is possible or not. For this, check if number of columns of first matrix is equal to number of rows of second matrix or not. If both are equal than proceed further otherwise generate output "Not Possible".
In Recursive Matrix Multiplication, we implement three loops of Iteration through recursive calls. The inner most Recursive call of multiplyMatrix() is to iterate k (col1 or row2). The second recursive call of multiplyMatrix() is to change the columns and the outermost recursive call is to change rows.
Below is Recursive Matrix Multiplication code.

CODE:
// Java recursive code for Matrix Multiplication

class GFG
{
    public static int MAX = 100;

    // Note that below variables are static
    // i and j are used to know current cell of
    // result matrix C[][]. k is used to know
    // current column number of A[][] and row
    // number of B[][] to be multiplied
    public static int i = 0, j = 0, k = 0;

    static void multiplyMatrixRec(int row1, int col1, int A[][],
                       int row2, int col2, int B[][],
                       int C[][])
    {
        // If all rows traversed
        if (i >= row1)
            return;

        // If i < row1
        if (j < col2)
        {
            if (k < col1)
            {
                C[i][j] += A[i][k] * B[k][j];
                k++;

                multiplyMatrixRec(row1, col1, A, row2, col2, B, C);
            }

            k = 0;
            j++;
            multiplyMatrixRec(row1, col1, A, row2, col2, B, C);
        }

        j = 0;
        i++;
        multiplyMatrixRec(row1, col1, A, row2, col2, B, C);
    }

    // Function to multiply two matrices A[][] and B[][]
    static void multiplyMatrix(int row1, int col1, int A[][],
                    int row2, int col2, int B[][])
    {
        if (row2 != col1)
        {
            System.out.println("Not Possible\n");
            return;
        }

        int[][] C = new int[MAX][MAX];

        multiplyMatrixRec(row1, col1, A, row2, col2, B, C);

        // Print the result
        for (int i = 0; i < row1; i++)
        {
            for (int j = 0; j < col2; j++)
                System.out.print(C[i][j]+" ");

            System.out.println();
        }
    }

    // driver program
    public static void main (String[] args)
    {
        int row1 = 3, col1 = 3, row2 = 3, col2 = 3;
        int A[][] = { {1, 2, 3},
                      {4, 5, 6},
                      {7, 8, 9}};

        int B[][] = { {1, 2, 3},
                      {4, 5, 6},
                      {7, 8, 9} };

        multiplyMatrix(row1, col1, A, row2, col2, B);
    }
}

Source:
https://www.geeksforgeeks.org/matrix-multiplication-recursive/


text:
Q: Extraer datos de una cadena de caracteres Tengo esta cadena de caracteres:
"Tel:1234567890 Email:example93@hotmail.com"

y quisiera que la salida fuera:
1234567890
example93@hotmail.com

Es decir, extraer esos datos para luego utilizarlos.
Probé hacer un doble split para obtener dos conjuntos de datos, pero no me estaría funcionando.

A: string cadena = "Tel:1234567890 Email:example93@hotmail.com";

string telefono = cadena.split(" ")[0].split(":")[1]; // "1234567890"
string email = cadena.split(" ")[1].split(":")[1]; // "example93@hotmail.com"

No se bien si te referías a eso por que al no ver tu código no te puedo ayudar bien pero creo que la respuesta es esa ya que split hace lo siguiente:
del string
string cadena = "hola que tal";

Si se le hace cadena.split(" ") nos va a quedar un array con los valores {"hola", "que", "tal"}
Al igual que si se le hiciese un cadena.split("a") obtendríamos {"hol", " que t", "l"}


text:
Q: Split a string with Backslash I'm trying to split a long string with a lot of data in it. The data come with a separator character '\r', I wanted to place each row into a List<> and carry out a string.split(). When I use the backslash as separator this doesn't work. I have read the below thread but it doesn't help me cause it still won't separate the data into rows. The idea was to crate a list and place later all info in a datagridview. Therefore I need to split all separate information
Split string with backslash
This is the code I have tried (next to many other things)
 private void ExtractMeasurements (string Data)
    {
        int TotalMeasurements = frmMain.MeasTotal;
        List<string> Measurements = new List<string>();
        Measurements.AddRange(Data.Split('\\'));
    }

This is how the raw string looks like:

And here the result when I try to split the string

Am I making somewhere a silly mistake or is my strategy completely wrong?

A: Adopted from this answer: How to convert from ascii code to split character C# and @Johnny Mopp's comments on the OP's questions.
This could be an approach that works for you. This uses the actual ASCII code as the value to split on. Being that ASCII code 13 is the Carriage Return.
Measurements.AddRange(Data.Split((char)13));

A: Ok the issue was solved easily (with something I wanted to do from the start).
private void ExtractMeasurements (string Data)
    {

        int TotalMeasurements = frmMain.MeasTotal;

        List<string> Measurements = new List<string>();

        Measurements.AddRange(Data.Split('\r'));

    }

This gives me the following result:


text:
Q: Capistrano first deploy error with PG migration The application works well in local. To be used, I have to seed it first.
Trying to deploy, I got the following:
 INFO [b83023c5] Running ~/.rvm/bin/rvm default do bundle exec rake assets:precompile as deploy@51.254.129.78
 DEBUG [b83023c5] Command: cd /home/deploy/guialocal/releases/20180714191701 && ( export RAILS_ENV="production" RAILS_GROUPS="" ; ~/.rvm/bin/rvm default do bundle exec rake assets:precompile )
 DEBUG [b83023c5]   rake aborted!
 DEBUG [b83023c5]   ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "configs" does not exist
LINE 1: SELECT  "configs".* FROM "configs" ORDER BY "configs"."id" A...
                                 ^
: SELECT  "configs".* FROM "configs" ORDER BY "configs"."id" ASC LIMIT $1
 DEBUG [b83023c5]   /home/deploy/guialocal/shared/bundle/ruby/2.4.0/gems/activerecord-5.0.7/lib/active_record/connection_adapters/postgresql_adapter.rb:659:in `prepare'

The config table is a table with just 1 record that I use via initializers to load info in global vars that I use in each VPS deployed instances and across all the application.
db/migrate/20180531033550_create_configs.rb
class CreateConfigs < ActiveRecord::Migration[5.0]
  def change
    create_table :configs do |t|
      t.integer :city

      t.timestamps
    end
  end
end

db/seeds.rb
Config.create!(
  city: "city_name"
)

config/initializers/instance_configs.rb
$current_city = Config.try(:first).try(:city)

A: The problem is that in initializers, you cannot do BD operations (Is not yet workable). In mi case, I removed the assignation used a helper_method mo get the info once everything in fully loaded.


text:
Q: Spring Data JPA : Stored Procedure with Schema Name Please if anyone has experienced calling oracle stored procedure from spring data specifying schema, package and procedure name.
I have the following entity :
@Entity
@Table(name = "ENTITY", schema = "SCHEMA_ENTITY")
@NamedStoredProcedureQueries({
@NamedStoredProcedureQuery(name = "name1",
    procedureName = "packageName.procName",
    parameters = {
        @StoredProcedureParameter(mode = ParameterMode.IN, name = "param1", type = String.class),
        @StoredProcedureParameter(mode = ParameterMode.OUT, name = "return_value", type = BigDecimal.class)
    })})

public class EntityExp {

     @Id
    private Long keyId;
    ...
}

Repository :
 public interface EntityRepository extends JpaRepository<EntityExp, Long> {

   @Procedure(name = "name1")
   BigDecimal test(@Param("param1") String param1);
}

In the service implemetation, after autowiring it, I call the procedure like :
BigDecimal returnVal = entityRepository.test(param1);

The oracle stored proc definition is :
create or replace PACKAGE packageName as
          function procName(param1 IN VARCHAR)
               RETURN NUMBER;
END packageName;
create or replace PACKAGE BODY packageName
        IS
        function procName (param1 IN VARCHAR)
        RETURN NUMBER
        IS
        BEGIN
        return 1;
        END;
        END;

The procedure works fine if I call it using PL/Sql..
And I got the following error :
PLS-00201: identifier 'package.procName' must be declared

I also tested many configs, like specifying the schema in the procedure:
@Procedure(name = "SCHEMA_ENTITY.name1")
BigDecimal test(@Param("param1") String param1);

But still fails...
I can't find any example using schema + package + procedureName while calling the stored procedure...
Any suggestions ?

A: I'm not quite sure that understood your issue completely, but I'll try to share some information since I had a related issue recently.
The first item is related to the way you call the stored procedure. It looks like the returned type of the stored procedure is not currently supported by Spring-data. For more info link. However, with void it is working fine.
I resolved that by creating a separate Repository where I call the procedures which return result through the entityManager. An example which illustrates that link.
The second item is about schema name. I believe when you resolve the first item you could use this question to try to resolve it. In a nutshell, I set the schema name in the procedureName annotation attribute name.
@NamedStoredProcedureQuery(
        name="procName",
        procedureName="<schema_name>.proc_name"
)
@Entity
@Table
public class User {
...
}

Hope it helps.


text:
Q: Issue with SharePoint masterpage and CssRegistration I created a stylesheet for an imagemap and wanted to add it to the masterpage. I did so by adding
<SharePoint:CssRegistration name="/Style Library/CSS/imagemap.css" runat="server"/>

to the masterpage's header. I load a site but can't see the imagemap, I check the HTML source and when I use the link the stylesheet uses I can see it in a new browser window. I also tried with the full URL in the masterpage but still no imagemap.
I checked with FireBug and it loads the stylesheet but when I select it I get "no rules applied" (or similar) even though the stylesheet is not empty. I try with adding after="corev4.css". Same result.
I then do:
<link rel="stylesheet" type="text/css" href="/Style%20Library/CSS/imagemap.css" />

instead of CssRegistration and it works fine. What am I doing wrong/missing with my first attempt above to load the css?
Thanks in advance.

A: You should also have <Sharepoint:CssLink runat="server" />
Sharepoint:CssLink is the control that actually renders the styles. So, for every style defined by a SharePoint:CssRegistration, SharePoint:CssLink will process all of the runtime tokens like ~language and render the CSS files.


text:
Q: Hide a FormIo Radio option based on condition? Is it possible to hide a radio option value based on the answer to a previous question?
For example:
Question 1 (radio): Red or Blue?
Question 2 (radio): 10 ( red only), 20(red only), (30 blue only), 40(blue only)
I don't want to show 10 and 20 if the user selects blue.
I am unable to split the second question into two because the API property needs to be the same.

A: Since formiojs@4 (available through https://next.form.io) components have the option to define specific logics.  Thus, you may change the component itself based on different conditions (such as events or custom javascript).
Basically, you will want to trigger the logic whenever the color component has a value (so it does not triggers unnecessary on every change).  On this change, you may update the component values depending on the value of the color.  Also, clear the component's value if the new options does not includes its current value.
You could have the following action for example:
var values = [];

if (data.color === 'red') {
  values.push(10, 20);
} else if (data.color === 'blue') {
  values.push(30, 40);
}

if (!values.includes(data.option)) {
  delete data.option;
}

schema = {
  values: values.map((value) => ({ label: value.toString(), value })),
};

Check the following jsfiddle for a working example: https://jsfiddle.net/airarrazaval/btpyfjm8/


text:
Q: Segmentation fault when w/ readdir in recursive function So i get an segmentation error in C, while runtime (no compiling Error or Warnings with -Wall). I found a solution but do not understand why the error occurred in first place. If someone could explain this to me it would be nice. I'm learning C right now and want to understand it not just have a solution.
void read_dir (const char *path){
  DIR *dir;
  struct dirent *object;

  dir = opendir(path);
  if (dir == NULL) return;

  object = readdir(dir);

  while (object != NULL) {
    char *name = object->d_name;
    char fullPath[300];
    sprintf(fullPath, "%s/%s", path, name);
    object = readdir(dir);  //put it here **error** placement 1

    if (object->d_type == DT_DIR && strcmp(name,".") && strcmp(name,".."))
      read_dir (fullPath);

    object = readdir(dir);// put it here **no error** placement 2
}
    closedir(dir);
  }

code is running in main like this
int main (){
  read_dir("..");
  return 0;
}

from what i understand seg err/core dump is when reading trying to read memory that does not belong to the program.
And from what i understand about recusion it creates and let my var alive as long as the function does not return so why does that simple change of order changes so much.
Output for placement 1:
../.
../a.out
../scripts
../b.class
../b.java
../..
Segmentation fault (core dumped)

Output for placement 2:
../.
../a.out
../scripts
../scripts/a.c
../scripts/b.c
../scripts/a.txt
../scripts/dir.c
../scripts/.
../scripts/a.out
../scripts/makefile
../scripts/c.c
../scripts/a.class
../scripts/char.c
../scripts/conf.h
../scripts/a.java
../scripts/..
../scripts/dir.backup
../b.class
../b.java
../..```

A: object = readdir(dir);  //put it here **error**

if (object->d_type == DT_DIR && strcmp(name,".") && strcmp(name,".."))
  read_dir (fullPath);

If this call to readdir returns NULL, you still dereference the NULL by trying to test object->d_type which will segfault. You can't change object while you still need to access what it points to.


text:
Q: Thunar - can I change the sorting method for one specific folder?
*

*Xubuntu 13.10

*Thunar 1.6.3
Is it possible to change the sorting method for one specific folder only?

A: I can't find a current official link indicating that it is not possible to sort one folder differently than the rest but a similar feature was requested quite a while back: http://mail.xfce.org/pipermail/thunar-dev/2006-September/003425.html.


text:
Q: |Solved| How to store JSX in variable in TypeScript? I have a Requirement in which i need to store JSX/TSX
For Example:

Hello {name}

in a variable, like this:
const Ele = <>
Hello {name}
</>
to export for another component in React.
Well in normal Javascript it works fines! Everything.
But Problem is TypeScript isn't allowing me to store this even after declaring it to varName:any
(NOTE: For my requirement creating a React Functional Component won't Work!!! It must be normal variable in .ts file)
If anyone can help me?
Thanks in advance! ;)
I tried it with :any and different JSX matching types which is provided by default, but no luck :(

A: You want a React component, which is a function that returns JSX:
const Ele = () => <>
Hello {name}
</>;

A: You should use React.ReactNode type for your React node element

const name: React.ReactNode = Ele


text:
Q: Как скачать сайт? Как скачать сайт с помощью f12 без какого-либо вспомогательного софта/сайта?
учусь верстке и хотелось бы просто посмотреть главные файлы сайта как они написаны index.html и style.css

A: В гугл хроме или яндекс браузере нажимаете ctrl + s или правой кнопкой мыши "и сохранить страницу как", выбираете путь и вам скачается html файл и папка с js b css, а вообще не понимаю зачем скачивать, если вам нужно просто посмотреть.


text:
Q: css button not showing up in any version of IE I've been having an issue where in Chrome, Firefox, and Safari my website displays css buttons I made at the top.  However, in both IE 9 and 11, the button isn't there and only the link is.  I've added redundancies in the CSS to the best of my ability, but I must be missing something.  The full code for the buttons is fairly long, but I've pinpointed the problem to the following few lines.
.button {
/* effects */
    border-top: 1px solid rgba(255,255,255,0.8);
    border-bottom: 1px solid rgba(0,0,0,0.1);
    background-image: -webkit-radial-gradient(top, ellipse cover, rgba(255,255,255,0.7) 0%, rgba(255,255,255,0) 100%), url(http://iwantaneff.in/t/http://iwantaneff.in/t/noise.png);
    background-image: -moz-radial-gradient(top, ellipse cover, rgba(255,255,255,0.7) 0%, rgba(255,255,255,0) 100%), url(http://iwantaneff.in/t/http://iwantaneff.in/t/noise.png);
    background-image: -ms-radial-gradient(farthest-corner ellipse at top, rgba(255,255,255,0.7) 0%, rgba(255,255,255,0) 100%), url(http://iwantaneff.in/t/http://iwantaneff.in/t/noise.png);
    background-image: radial-gradient(farthest-corner ellipse at top, rgba(255,255,255,0.7) 0%, rgba(255,255,255,0) 100%), url(http://iwantaneff.in/t/http://iwantaneff.in/t/noise.png);
    -webkit-transition: background .2s ease-in-out;
    transition: background .2s ease-in-out;
}

And this is the html for the buttons.  The classes of round and blue are defined in the stylesheet also, but I've tested the buttons without those additions and they still don't work.
Home
Software
Support
Consulting Services
What's New
Our Clients
About Us
Contact Us

Any recommendations will be appreciated, as I just don't understand why this isn't working in both IE 9 and 11.

A: Looks like RGBA property with opacity values not working in IE. I just modified your code with removing rgba and assigning two different color. Also i have added display property with height and padding. After that it was working fine for me.
 .button {
/* effects */
border-top: 1px solid rgba(255,255,255,0.8);
border-bottom: 1px solid rgba(0,0,0,0.1);
background-image: -webkit-radial-gradient(top, ellipse cover, rgba(255,255,255,0.7) 0%, rgba(255,255,255,0) 100%), url(http://iwantaneff.in/t/http://iwantaneff.in/t/noise.png);
background-image: -moz-radial-gradient(top, ellipse cover, rgba(255,255,255,0.7) 0%, rgba(255,255,255,0) 100%), url(http://iwantaneff.in/t/http://iwantaneff.in/t/noise.png);
background-image: -ms-radial-gradient(farthest-corner ellipse  at top, #ff00ff 0%, #000fff 100%);
background-image: radial-gradient(farthest-corner ellipse  at top, #ff00ff 0%, #000fff 100%);
-webkit-transition: background .2s ease-in-out;
transition: background .2s ease-in-out;
display:inline-block;
height:50px;
padding:0px 30px;
}

If you want to overcome this issue you need to do some trick. In Stack Overflow already they have discussed about this like how to overcome this. Go through the following url CSS background opacity with rgba not working in IE 8
JSFIDDLE DEMO


text:
Q: Use correct offset when binding a buffer to a memory I have a big chunk of device memory and multiple uniform buffers which I want to bind. Obviously, I need an offset. Let's see what the documentation for vkBindBufferMemory says:

memoryOffset is the start offset of the region of memory which is to
  be bound to the buffer...
memoryOffset must be an integer multiple of the alignment member of
  the VkMemoryRequirements structure returned from a call to
  vkGetBufferMemoryRequirements with buffer

Ok, that's clear - I have multiple uniform buffers created with the same flags so I can use the same alignment for all of them. But wait, there's another usage note for vkBindBufferMemory in specs:

If buffer was created with the VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
  memoryOffset must be a multiple of
  VkPhysicalDeviceLimits::minUniformBufferOffsetAlignment

That's confuing. Can I safely use VkPhysicalDeviceLimits::minUniformBufferOffsetAlignment for my case or should I compare it with VkMemoryRequirements::alignment and choose the lowest?

A: First, a quick note: if You want to compare VkPhysicalDeviceLimits::minUniformBufferOffsetAlignment with VkMemoryRequirements::alignment then You should choose the largest of these two values, not the lowest (smallest) value.
But in the spec we can also read:

The implementation guarantees certain properties about the memory
  requirements returned by vkGetBufferMemoryRequirements and
  vkGetImageMemoryRequirements:

*

*The alignment member is identical for all VkBuffer objects created with the same combination of values for the usage and flags members in the VkBufferCreateInfo structure passed to vkCreateBuffer.

*The alignment member satisfies the buffer descriptor offset alignment requirements associated with the VkBuffer's usage:

*

*If usage included VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT or VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, alignment must be an integer multiple of VkPhysicalDeviceLimits::minTexelBufferOffsetAlignment.

*If usage included VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, alignment must be an integer multiple of VkPhysicalDeviceLimits::minUniformBufferOffsetAlignment.

*If usage included VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, alignment must be an integer multiple of VkPhysicalDeviceLimits::minStorageBufferOffsetAlignment.

So You don't have to compare them but only take the (multiple of the) alignment value returned by the vkGetBufferMemoryRequirements() function in the VkMemoryRequirements structure.
Based on the above information, I think that VkPhysicalDeviceLimits::minUniformBufferOffsetAlignment value is more important when using dynamic uniform buffers as the offset value provided during the vkCmdBindDescriptorSets() function call must also be a multiple of the above value.


text:
Q: ES6 class setter as a function I'm trying to submit the setter function of a class as a parameter.
Let's asume there is:
class A {
    set foo(foo) {
        this._foo = foo
    }
}

However, if I'm calling the function f(setter) { setter(); } like this f(obj.foo), of course the value of obj.foo will be submitted calling the getter.
I was thinking about using an arrow function (foo) => obj.foo = foo and it works. But there must be a shorter way, something like f(obj.setFoo) to get the setter function.
Ideas are welcome.

A:
But there must be a shorter way, something like f(obj.setFoo) to get the setter function.

Nope.  There's a longer way,
var setFoo = Object.getOwnPropertyDescriptor(obj, 'foo').set;
setFoo.call(obj, 'bar');

Accessor functions are stored in the internal property attributes and are not accessible without using reflection.  Stick with your arrow function solution or define getter/setter functions (instead of an accessor property) on the class.

A: You can always define a getter which returns the setter:

class A {
  get foo() {
    return Object.getOwnPropertyDescriptor(A.prototype, 'foo').set;
  }
  set foo(foo) {
    this._foo = foo;
  }
}
var obj = new A();
(function(setter) {
  setter.call(obj, 123);
  console.log(obj._foo); // 123
})(obj.foo);


text:
Q: Restoring lost icons I recently installed Yosemite on my MacBook Air. I note that my Reading List items no longer display the icon/logo from the web pages. They were very handy for quickly locating the item I was looking for without having to read through all the text. Is there a way to restore them?

A: Lets try following to restore your old reading list:
Quit Safari. In the Finder, hold down the option key and select

Go > Library

from the menu bar.
The reading list is stored in the file Safari/Bookmarks.plist in the Library folder.
You have two choices:
Restore the file from a backup that predates the issue; or
Move the file to the Desktop, relaunch Safari, and import from the old bookmarks file (File > Import Bookmarks...).


text:
Q: How to approach developing a Chat Bot in C# I'm creating a chat bot in C# for a uni project and I'm currently unsure as to how best to go about it. I'm new to OO programming and C#.
The basis of how the chat bot has to work is that it is meant to learn, the more it interacts with the user. It achieves this by parsing all user input sentences and counts how many times a certain word follows each word.
The program takes a random word from the sentence and uses the word graph to generate a reply.
So, for example, the following quote could be split into:
"I wandered lonely as a cloud that floats on high ore vales and hills when all at one I saw a crowd a host of golden daffodils"
I: wandered (1) saw (1)
wandered: lonely(1)
lonely: as(1)
as: a(1)
a: cloud (1)crowd (1)host(1)
cloud: that(1)
etc...
So far, I have the idea to use a followingWord class which holds a following word and a count of how many times that has followed the Main word.
The MainWord class holds the word and a list of type FollowingWord which holds the following words and their counts.
class FollowingWord
{
string word; //the following word
int count;  //the amount of times word has followed the main word.
}

class MainWord
{
string word;        //the main word
List<FollowWord> following = new List<FollowWord>();    //a list of type FollowWord which holds all the following words and their counts.

}

Am I on the right track here? Because I haven't been able to think of any other way to approach this.

A: I know this question is 4 years old and you probably already finished university.
Well the subject is Natural Language Processing and there is a series of video's from Stanford which has a lot of the theory you are after.
NPL Open Course Online
I did watch them and there is a way to tell how likely a word is given the previous word. That is how the suggested words work when typing on a mobile phone.