text:
Q: Ошибка при загрузке картинки в vue-cropperjs Есть картинка
<img :src="vacancyLogo" ref='vLogo'/>

data () {
  vacancyLogo: 'https://s3-eu-west-1.amazonaws.com/test.new.vcv.ru/test5-new.vcv.ru/vacancies/4185/logo_2018-11-23T09%3A17%3A10.277Z'
}

Используется vue-cropperjs, передаю этот src
this.$refs.cropper.replace(this.vacancyLogo)

Возвращается ошибка

Access to image at 'https://s3-eu-west-1.amazonaws.com/test.new.vcv.ru/test5-new.vcv.ru/vacancies/4185/logo_2018-11-23T09%3A17%3A10.277Z?timestamp=1542966387614' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Почему возникает такая ошибка?
Или я не так передаю url?

A: Ошибка возникает потому что вы грузите картинку с другого хоста. Нужно чтобы этот хост возвращал заголовок Access-Control-Allow-Origin, в котором указано каким хостам можно это делать. Для этого в nginx можно сделать вот так
add_header Access-Control-Allow-Origin http://your-front-host.lh;

Тут описано подробнее https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work


text:
Q: How do I use a WHERE clause with a CASE inside a SUM? I've got two tables, one is a list of tasks. Each task (row) is specified by a unique pair of story_id and pos_id (point of sale ID), and includes the date last_completed. The other table is a list of POSes with a priority number.
This is what I need: I'll call for each task x the quantity consisting of the time since last completion divided by the priority number for its POS. I need the sum of all the x's for each story over all that story's POSes.
On top of that some of the tasks have never been completed, so last_completed is NULL; for those tasks, I want to set x to 10.
This is what I tried, but I get an error on the WHERE:
SELECT t.story_id, SUM(
  CASE
    WHEN t.last_completed IS NULL THEN 10
    ELSE DATEDIFF(NOW(), t.last_completed)/p.priority
  END
WHERE t.pos_id = p.id) AS weeks
FROM test_task t, test_pos p
GROUP BY story_id;

I also tried the WHERE clause on the same line as the ELSE, but that didn't work either.
Can anyone tell me how I can correlate the priority with the last_completed date inside a CASE inside a SUM?

A: Presumably, this is the query you want:
SELECT t.story_id,
       SUM(CASE WHEN t.last_completed IS NULL THEN 10
                ELSE DATEDIFF(NOW(), t.last_completed)/p.priority
           END) as weeks
FROM test_task t JOIN
     test_pos p
     ON t.pos_id = p.id
GROUP BY story_id;

Your condition should be in the on clause for an explicit join.  This has nothing to do with a case expression in the select clause.

A: You have misordered your clauses - from should come before where. Additionally, you need to close the sum's brackets:
SELECT t.story_id, SUM(
  CASE
    WHEN t.last_completed IS NULL THEN 10
    ELSE DATEDIFF(NOW(), t.last_completed)/p.priority
  END) AS weeks
FROM test_task t, test_pos p
WHERE t.pos_id = p.id
GROUP BY story_id;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Associativity of Relativistic Oblique Velocity Addition I've encountered some information in the Wikipedia page on Lorentz transformation (https://en.m.wikipedia.org/wiki/Lorentz_transformation) that I am having difficulty reconciling with other information that I found on the page (https://en.m.wikipedia.org/wiki/Wigner_rotation) on Wigner rotation. In the Lorentz Transformation page, it says that the oblique (non-collinear) Lorentz transformation is given by a matrix $$\begin{pmatrix}\gamma&-\gamma\beta n_x&-\gamma\beta n_y&-\gamma\beta n_z\\-\gamma\beta n_x&1+(\gamma-1)n_x^2&(\gamma-1)n_x n_y&(\gamma-1)n_z n_x\\-\gamma\beta n_y&(\gamma-1)n_x n_y&1+(\gamma-1)n_y^2&(\gamma-1)n_y n_z\\-\gamma\beta n_z&(\gamma-1)n_z n_x&(\gamma-1)n_y n_z2&1+(\gamma-1)n_z^2\end{pmatrix}$$ with the $n_q$ ($q\in\{x,y,z\}$) being the components of the unit vector along the direction-of-motion of the moving frame. And in the Wigner Rotation page, there is given the formula for oblique velocity addition that is derived from successive application of two such transformations $$\overrightarrow{\beta}_u\oplus\overrightarrow{\beta}_v=\frac{1}{1+\overrightarrow{\beta}_u.\overrightarrow{\beta}_v}\left[\left(1+\frac{\gamma_u\overrightarrow{\beta}_u.\overrightarrow{\beta}_v}{1+\gamma_u}\right)\overrightarrow{\beta}_u+\frac{\overline{\beta}_v}{\gamma_u}\right]$$$$\gamma_{\overrightarrow{\beta}_u\oplus\overrightarrow{\beta}_v}=\gamma_u\gamma_v(1+\overrightarrow{\beta}_u.\overrightarrow{\beta}_v) .$$ But then it goes on to say that in addition to being non-commutative (which I can well-accomodate), this recipe is also non-associative!:
"Although velocity addition is nonlinear, non-associative, and non-commutative, the result of the operation correctly obtains a velocity with a magnitude less than $c$.".
Now since the addition of velocities is derived from the application of successive transformations taking the mathematical form of matrices, which are certainly associative, how then  does the non -associativity of the addition of velocities come-about? For three consecutive Lorentz transformations would have result not contingent upon the association of the matrices - and the resultant velocity is derived from this product of three matrices ... so how can it come-about that the velocity addition be non-associative?

A: I think I might have solved this.
Say you have four frames of reference labelled 0 to 3, the zeroth frame being the 'base' one, if you will; and let $Q_{ab}$ be the value of $Q$ - with Q being $\gamma$ or $\beta$ (or any other quantity, for that matter) - of frame $b$ relative to frame $a$, with $a\in\{0\dots3\}$ & $b\in\{0\dots3\}$. This way, $\beta_{01}$,  $\beta_{12}$ & $\beta_{23}$ - & therefore $\gamma_{01}$,  $\gamma_{12}$ & $\gamma_{23}$ are the givens. If you apply the formula first to find the velocity of frame 3 relative to frame 1, you would use the addition-of-velocity formula as given with $\gamma_u=\gamma_{12}$, $\beta_u=\beta_{12}$, & $\beta_v=\beta_{23}$, and the result would be $\beta_{13}$. Then to find the velocity of frame 3 relative to frame 0, you would simply iterate the formula with $\gamma_u=\gamma_{12}$, $\beta_u=\beta_{12}$, & $\beta_v=\beta_{23}$, and the result would be $\beta_{03}$ - the result sought. However, associating the calculation (the calculation that is! ... not the formula itself, as will shortly be apparent), you would first calculate $\beta_{02}$ by substituting $\gamma_u=\gamma_{01}$, $\beta_u=\beta_{01}$, & $\beta_v=\beta_{12}$. But then to calculate $\beta_{03}$ you would need to substitute $\gamma_u=\gamma_{02}$, $\beta_u=\beta_{02}$, & $\beta_v=\beta_{23}$. Note that in this association of the calculation $\gamma_{02}$ appears - which must be calculated apart using the ancilliary formula for composition of  the Lorentz factor.
So I think essentially what is being said in the Wikipedia article is that the formula is not associative as it stands, and is only applicable as it stands which is to say without invoking the ancilliary formula for composition of Lorentz factors, if the order of association is strictly from the uttermost-observed frame to the base-frame: that all other associations give the wrong result.
That's what I'm surmising, anyway. I haven't got symbolic algebra computation handy just at the moment; and I'm not crunching through all those substitutions using pencil & paper, & I haven't got the mental calibre necessary for doing it in my head. Oblique Lorentz transformations are notorious for the the sheer algeba-load of them being formidable! I'll report back when I've investigated the matter using a symbolic algebra package. But I think I probably do have the explanation here - I think my argument is logically robust.


text:
Q: XSL - Grouping by list item column with multiple entries I am attempting to utilize XSL to format results pulled from a document library, but unfortunately this is my first stab at XSL ever.
The columns in the document library are fairly standard - Title, Description - but also contain a custom column which contains a lookup to another list and it can contain multiple values (separated by semi-colons):
DOCUMENT LIBRARY
Image:

The "Role" column is something I would like to use to 'group' the results.  Problem is, I am not sure how to query the document library in a fashion that if a document is part of multiple roles, then that document should appear under that 'heading'.
An example output I wish to attain:

Is this possible using XSL?  If so, what method would you recommend?  I can educate myself if I know what to search for :)  So if anyone knows of some keywords I should be googling for, please let me know!
Thanks

A: This article on EndUserSharePoint explains how:
https://www.nothingbutsharepoint.com/sites/eusp/pages/sharepoint-group-by-a-column-with-multiple-values.aspx
You basically need to create a linked data source to the lookup list and the main list with the join option.


text:
Q: Simulate mouse click using PostMessage More recently, simulating a click using PostMessage has begun to activate the window. Previously, this was not and the click was performed in an inactive window without focus.
int coords = (y << 16) + x;
IntPtr lParam = new IntPtr(coords);
PostMessage(hwnd, WM_LBUTTONDOWN, IntPtr.Zero, lParam);
PostMessage(hwnd, WM_LBUTTONUP, IntPtr.Zero, lParam);

[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

const Int32 WM_LBUTTONDOWN = 0x201;
const Int32 WM_LBUTTONUP = 0x202;


text:
Q: Error Running f2py, Symbol table not found I have been trying to get f2py to work on my windows 10 64-bit machine. I am using mingw32 and gnu95 compiler. When I run this command in command prompt
python f2py.py -c -m Test2 Test2.f95 --fcompiler=gnu95 --compiler=mingw32

I get the following message produced
running build
running config_cc
unifing config_cc, config, build_clib, build_ext, build commands --compiler options
running config_fc
unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
running build_src
build_src
building extension "Test2" sources
f2py options: []
f2py:> C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6\Test2module.c
creating C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6
Reading fortran codes...
        Reading file 'Test2.f95' (format:free)
Post-processing...
        Block: Test2
                        Block: test
Post-processing (stage 2)...
Building modules...
        Building module "Test2"...
        Wrote C/API module "Test2" to file "C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6\Test2module.c"
  adding 'C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6\fortranobject.c' to sources.
  adding 'C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6' to include_dirs.
copying C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\f2py\src\fortranobject.c -> C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6
copying C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\f2py\src\fortranobject.h -> C:\Users\heele\AppData\Local\Temp\tmp410mc40f\src.win-amd64-3.6
build_src: building npy-pkg config files
running build_ext
Building msvcr library: "C:\Users\heele\AppData\Local\Programs\Python\Python36\libs\libvcruntime140.a" (from C:\Users\heele\AppData\Local\Programs\Python\Python36\vcruntime140.dll)
objdump.exe: C:\Users\heele\AppData\Local\Programs\Python\Python36\vcruntime140.dll: File format not recognized
Traceback (most recent call last):
  File "f2py.py", line 28, in <module>
    main()
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\f2py\f2py2e.py", line 648, in main
    run_compile()
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\f2py\f2py2e.py", line 633, in run_compile
    setup(ext_modules=[ext])
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\distutils\core.py", line 169, in setup
    return old_setup(**new_attr)
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\distutils\dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\distutils\command\build.py", line 47, in run
    old_build.run(self)
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\distutils\command\build.py", line 135, in run
    self.run_command(cmd_name)
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\distutils\cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\distutils\command\build_ext.py", line 117, in run
    force=self.force)
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\distutils\ccompiler.py", line 733, in new_compiler
    compiler = klass(None, dry_run, force)
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\distutils\mingw32ccompiler.py", line 107, in __init__
    msvcr_success = build_msvcr_library()
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\distutils\mingw32ccompiler.py", line 399, in build_msvcr_library
    generate_def(dll_file, def_file)
  File "C:\Users\heele\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\distutils\mingw32ccompiler.py", line 302, in generate_def
    raise ValueError("Symbol table not found")
ValueError: Symbol table not found

If there is anything that can be done that would be amazing. So far I have tried looking for 64 bit compilers, and also trying to reinstall everything. I also read somewhere that there is nothing to be done.


text:
Q: Zend Framework HTTPS URL Is there any more or less standard way to specify a route that would create URL's with explicitly specified scheme?
I've tried the solution specified here but it's not excellent for me for several reasons:

*

*It doesn't support base url request property. Actually rewrite router ignores it when URL scheme is specified explicitly.

*It's needed to specify separate static route for each scheme-dependent URL (it's not possible to chain module route with hostname route because of base url is ignored).

*It's needed to determine HTTP_HOST manually upon router initialization in bootstrap as long as request object is not present within FrontController yet.

A: Use a combination of the ServerUrl and Url view helpers to construct your URLs, eg (view context)
<?php $this->getHelper('ServerUrl')->setScheme('https') ?>
...
<a href="<?php echo $this->serverUrl($this->url(array(
    'url' => 'params'), 'route', $reset, $encode)) ?>">My Link

A: You can write your own custom View helper for composing an URL. Take a look at the http://www.evilprofessor.co.uk/239-creating-url-in-zend-custom-view-helper/
<?php

class Pro_View_Helper_LinksUrl
    extends Zend_View_Helper_Abstract
{
    /**
     * Returns link category URL
     *
     * @param  string          $https
     * @param  string          $module
     * @param  string          $controller
     * @param  string          $action
     * @return string Url-FQDN
     */
    public function linksUrl($https = false, $module = 'www',
        $controller = 'links', $action = 'index')
    {
        $router = Zend_Controller_Front::getInstance()->getRouter();

        $urlParts = $router->assemble(array(
            'module'     => $module,
            'controller' => $controller,
            'action'     => $action,
        ), 'www-index');

        $FQDN = (($https) ? "https://" : "http://") . $_SERVER["HTTP_HOST"] . $urlParts;

        return $FQDN;
    }
}


text:
Q: Azure Active Directory - how to map User/Group/App Registrations for JWT generation I have an Azure Function App (API) linked to an App Registration in Azure Active Directory (AAD), that exposes some custom Roles via the Manifest.
A client App Registration in AAD can add the API and select from its custom Roles as permissions. This allows the client app to call AAD to obtain
a JWT that includes these custom Roles, which can then be checked by the downstream Function App during JWT validation.

*

*I would like the client App Registration to also include other API's custom Roles as part of a company's 'Product Group' (eg. Product Group may be Sales, Service, Finance etc.).

*I want to create AAD Users representing each B2B consumer system, and link them to a Group that aligns to a company 'Product Group'.
Therefore, a User (B2B consumer system) should be able to request a JWT that includes custom Roles for all API's in the Product Group.
I need the JWT to include information of the consumer system, as it needs to be available to the downstream Function App.
What's the best way to achieve this?

A: The best we could come up with is to create App Registrations with custom Roles in the manifest to represent each Product Group. These App Registrations are completely independent of any specific Function App (API) implementation.
Then we have a client App Registration for each B2B consumer system, that imports the required custom Roles from its parent  Product Group App Registration.
The downstream Function Apps (API's) then perform processing based on the Roles extracted from the JWT.


text:
Q: Recommended SMTP Relay Service I've got a legacy application that needs an smtp server to relay emails. Each client has various control over their IT infrastructures (from little to none at all), so I can't necessarily install an smtp server on each of their machines.
Can anyone recommend a basic SMTP Relay Service?
Its literally only for sending a couple of emails a day to a list of about 20 users per client.  The application only allows for the smtp server and to/from addresses to be specified. I'm assuming its using the default port.
Thanks!

A: As many others are saying, such a server would essentially already be on every blacklist known to man, as it would be used by any spammer worth his salt, so it would be pointless for you to use it - half the mails you sent would never arrive.
If this is an application you're planning to deploy in a lot of (ie, >3) places, it may make sense for you to put up a central mail server to handle all the relaying.  Configure the central server to allow relaying from authenticated users, and require SMTP TLS before authentication is done.  Configure the app on each individual server to relay off localhost, and sendmail on each individual server to relay off this central server, authenticating with a username and password specific to the individual server (to allow one machine to be de-authorised without affecting all the others).
Or for that matter, just configure sendmail on each local server to do final delivery itself.  I re-read your question after writing most of the above and realised I couldn't see a good reason to have a central server at all, though there may be one.

A: There are many issues you'll run into when having people sending email out over SMTP ports like port 25, from their network.  A couple:

*

*Many IT admins block outgoing traffic from port 25 from all computers on the network other than the email servers (to mitigate issues with virus-infected computers on the network spewing spam).

*Lots of antivirus and "endpoint security" software will block unknown programs from sending out traffic on port 25 (Ian Ringrose mentions above).  So you may be dealing with supporting 20 different antivirus programs and telling people how to add exceptions (if their IT admins even allow them to).

I think it's going to be a constant battle for you.  But if it's not an app you made, then it doesn't sound like you can modify the functionality.
If you can only specify to/from addresses and a server name, then I think you may be out of luck using a third party external SMTP relay.  An SMTP relay that allows anyone to connect without authenticating is going to be used by spammers immediately and be on every blacklist.  If you can specify SMTP server authentication details, then a service like SendGrid would likely work for you.  If you can't use SMTP authentication, then you'll probably need to setup your own SMTP server to accept email from the clients (maybe lock it down somewhat with IP allow/deny lists?).
The downside to the latter is that you then become a service provider and you open a whole can of worms regarding email server uptime, scaling, making sure your email server isn't blacklisted, are you going to provide this service forever, are you going to charge for it, etc.
EDIT:  One other option would be to run some small SMTP server in the background on the local machine that does allow for SMTP authentication.  Have the app use localhost as the SMTP server, then have the localhost SMTP server set to forward all mail to a service like SendGrid.  It's an additional layer of something to go wrong, but it sounds like you're short on options.

A: Install post cast server at your site, and relay through messagelabs / postini, or some other service that's trusted.
Then you have all your clients connect to your smtp server and the only thing you have to do is only open it for the IP's of your clients.


text:
Q: Maintain the order with searching I have a table of location, that have more than 150 locations with area and zipcode columns. I am using query "Select area from locations where area like %n%", then i am getting results Nigdi
Nigdi
Nigdi
Chinchwad
Chinchwad
Nasik
Here why i am getting Nasik in last, even my first search keyword is 'n'. And Nasik has the 'n' at first location. Can Somebody help please.

A: If you want to order by the position of "n" in the area, then you need to specify that.  Remember, a SQL query returns an unordered set unless you explicitly include order by.  So:
Select area
from locations
where area like '%n%'
order by instr(area, 'n'), area;

A: Your question isn't very clear but I'm guessin that you want one of the following:
SELECT area FROM locations WHERE area LIKE '%n%' ORDER BY area

or
SELECT area FROM locations WHERE area LIKE 'n%' ORDER BY area


text:
Q: how to find my android application's storing path of apk file I want to make an application that could send itself (apk file) by bluetooth. but i have trouble with finding the apk file path. i tried this code:
final PackageManager pm = this.getPackageManager();
    List<PackageInfo> packages =  pm.getInstalledPackages(PackageManager.GET_META_DATA);
    String st = null;
    for (PackageInfo packageInfo : packages) {
        if(packageInfo.packageName.contains("testbutton"))
        st=packageInfo.packageName;
    }

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");

    String uri = "/data/app/";
    uri+=st;
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(uri)));
    startActivity(intent);

but st returns null value.
please help me with this. thanks in advance

A: finally i'd found the right answer that works in this purpose, thanks to @Kanak for her help :)
PackageManager pm = getPackageManager();
    String uri = null;
    for (ApplicationInfo app : pm.getInstalledApplications(0)) {
        if(!((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1))
            if(!((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1)){
                uri=app.sourceDir;
                  if(uri.contains("com.example.test"))
                  break;
            }
    }

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(uri)));
    startActivity(intent);

A: There is no need to iteration. Getting the application itself APK file uri is as easy as this:
String appUri = getApplicationInfo().publicSourceDir;

Also note that doc says this about publicSourceDir:

Full path to the publicly available parts of sourceDir,
   including resources and manifest. This may be different from
   sourceDir if an application is forward locked.

And also note that to send an APK file, you need to set the type to application/vnd.android.package-archive instead of image/*
So the complete snippet would be:
String appUri = getApplicationInfo().publicSourceDir;
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("application/vnd.android.package-archive");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(appUri)));
startActivity(Intent.createChooser(sharingIntent, "Share via"));


text:
Q: Stop OpenLayers featureselected event listener blocking map drag event When trying to drag the map, if the user clicks on a vector feature the featureselected event is triggered and the map dragging does not happen. Please try to drag the map starting from any feature in the example below.
http://openlayers.org/dev/examples/select-feature-multilayer.html
Is it possible to disable the featureselected event so the map can be dragged?
Solution
i found this FAQ http://trac.osgeo.org/openlayers/wiki/SelectFeatureControlMapDragIssues
It works.

A: The example you provided specifically demonstrates the ability to select features from different layers. In order to do this it includes an OpenLayers.Control.SelectFeature that is setup to capture featureselected events on the two different vector layers. Removing (or deactivating) the OpenLayers.Control.SelectFeature control will revert to default behaviour, that is to say the feature does not capture the mouse event and instead the map does, allowing it to be dragged.
The example given by simo does not include the OpenLayers.Control.SelectFeature control and therefore demonstrates the map can dragged regardless of whether a feature or the underlying map is clicked on.
If you need the ability to select the feature as well as being able to drag the map when a feature is initially clicked then you will need to look at extending the event so that fallThrough is set to true - which allows the event to fall through after it has been handled. This might then allow the map to pick up the click and drag event. I've not tried that so don't know if it would work.


text:
Q: Export google doc to PNG and send it on email script I need a simple way to export - saveAs or getAs, a google document to PNG or JPG and send it on email.
I was able to get it as pdf with 'application/pdf' with this: Class Blob
But wasn't able to use 'image/png' with the same code. The code I use to get .pdf is:
var pdf = DriveApp.getFileById("docID").getAs("application/pdf");

Should I change the code to function for PNG?

A: The documentation says:

For most blobs, 'application/pdf' is the only valid option. For images in BMP, GIF, JPEG, or PNG format, any of 'image/bmp', 'image/gif', 'image/jpeg', or 'image/png' are also valid.

A Google Document is not an image, so the only type offered is PDF.
What you can do is to save any images embedded in a document as PNG, like this.
var doc = DocumentApp.openByUrl('...');
var image = doc.getBody().getImages()[0];   // first image in document
var file = DriveApp.createFile(image.getBlob().setName('my image.png'));


text:
Q: Was Neo's prime program given to him by the machines, or self generated? What I mean by that is Neo wasn't the only one to have the potential to become the One. In The Matrix, we see that some children already possess powers.
And if the machines need this prime program at a precise moment, why give it to a human to carry and then disseminate? Why not just keep it on a hard drive and use the program when it is time to reset the Matrix?
That is why it is my general belief that Neo's prime program is self-generated by his life experience and the amount of knowledge and elements he learns through his journey.
It even makes sense, given the fact that all the other Ones chose the door to the Source; they basically repeated the cycle, because their experience toward humanity and LOVE was very generalistic. Neo's experience, as the Architect so elegantly put it, is "far more specific vis-à-vis love". That is what separates him from the others; it is what makes him choose the other door.
Then there is the dissemination of the code, which is also different.
The arrival of an enemy like Smith, which threatens the machines and the humans. Neo can break a truce, even a peace accord, should he defeat Smith.
Now there are two elements that need to be taken into account for this last part:

*

*Neo, when first destroying Smith, left an impression on him, quite literally (see Smith's speech in The Matrix Reloaded, before the fight between him and Neo, after Neo talked to the Oracle).

*At the time of the last fight, Smith had absorbed everyone in the Matrix.
Hence the ending. Neo let himself be absorbed, i.e. his code joined the network created by Smith, which in this case equalled everyone in the Matrix. Hence the dissemination of Neo's prime program, which is different from others due to love, changing the usual reset of the Matrix for two reasons: the prime program is different, and Neo broke a peace accord right before.
None of that would make any sense if Neo's prime program was a static code, or a program given to him by the machines. I mean, the biggest plot hole would be why give him the code in the first place? Why not just keep it and use it when needed?

A:
What I mean by that is Neo wasn't the only one to have the potential to become the One. In The Matrix, we see that some children already possess powers.

It's clear that they exhibit powers, and that the hackers aren't sure whether they are The One or not--but I'm not aware of anything that unambiguously clarifies that any of these children can be The One.
I'm not not sure I disagree, but I'm also not sure how we can distinguish between someone ~randomly becoming The Anomaly, and The Anomaly always being the same person.

And if the machines need this prime program at a precise moment, why give it to a human to carry and then disseminate? Why not just keep it on a hard drive and use the program when it is time to reset the Matrix?

I doubt there's a satisfying answer to this, but I don't think there is a specific moment where the machines need the prime program. I read the films as suggesting this as circling back to the problems of choice, and of subconscious consent. Choice is the problem--and for it to exist, someone has to be able to make the choice the machines are engineering against.
In the timeline we're shown the machines do need Neo, but that's because of Smith--and Smith only exists in his current condition ~because of what happens to his program after Neo "destroys him in the first film. (I'm basing this somewhat on the scene after Neo's fight with the "upgrades" earlier in the second film, where Smith tells himself that it's happening just as before--with a knowing look that signals that the Smith copy is the exception. Also on the fact that the machines have no apparent countermeasure for this happening to Smith.) There is presumably still the "escalating probability" problem, but I don't recall anything that clarifies when/where/why that would finally become a problem for the machines.

That is why it is my general belief that Neo's prime program is self-generated by his life experience and the amount of knowledge and elements he learns through his journey.

I don't think there's anything to unambiguously decide this one way or another. My personal inclination is to say that we have to "trust" the monitors that the architect shows us--that when the previous-Neos respond, he is showing us past-realities and not a metaphorical abstraction to make sure Neo is smrt enough to recognize "himself". This isn't the same as thinking it's implausible that it's working this way. Just that I see that as being on the other side of a decision razor based on what the Wachowskis elected to actually show us...

It even makes sense, given the fact that all the other Ones chose the door to the Source; they basically repeated the cycle, because their experience toward humanity and LOVE was very generalistic. Neo's experience, as the Architect so elegantly put it, is "far more specific vis-à-vis love". That is what separates him from the others; it is what makes him choose the other door.

Note that the Oracle plays a role in this. She tells Trinity that she'll fall in love with The One. Given this, I'm not sure there's any clear evidence that the distinction between iterations must lie outside of the Matrix.

Then there is the dissemination of the code which is also different. The arrival of an enemy like Smith, which threatens the machines and the humans neo can break a truce even a peace accord should he defeat Smith.

Now there is two-element that needs to be taken in account for this last part:

Neo, when first destroying Smith, left an impression on him, quite literally (see the speech of smith in The Matrix reloaded, before the fight between him and Neo, after Neo talked to the Oracle.)
At the time of the last fight, Smith has absorbed everyone in the Matrix.
Hence the ending; Neo let himself be absorbed, i.e. his code joined the network created by Smith, which in this case equalled everyone in the Matrix, hence the dissemination of Neo's prime program, which is different from others due to love, changing the usual reset of the Matrix for two reasons: the prime program is different, and Neo broke a peace accord right before.

I'm not sure this holds (or is the difference). This Neo chose to return to the Matrix instead of to the source. It isn't a given that Smith absorbing him is the same as disseminating his prime program. It's also not a given that his prime program is at all changed by love. (And I guess this clarifies that either Neo's prime program does not actually prescribe the whole "choose 23..." bit, or that this doesn't trigger its dissemination).

None of that would make any sense if Neo's prime program was a static code, or a program given to him by the machines.

I've weighed this a bit, but I'm not really sure. "A static code" very much fits how most people thought of code when the movies were released, but the oracle does ambiguously refer to programs "breaking down", which implies that either their code, storage, or hardware is subject to some kind of change or entropy. I've never quite known what to make of this statement in context. I've assumed it's vaguely metaphorical, but I'm also unhappy with that as a conclusion.

I mean, the biggest plot whole would be why give him the code in the first place; why not just keep it and use it when needed?

Not that this isn't a fair question, or that I personally find this answer satisfying, but in-universe I think it is: they give it because Neo has to make a choice.

A: I don't like the language - unnecessarily pretentious - but it is rather clear what The Architect said in the conversation he and Neo had.
Basically, Neo is THE Anomaly of the Matrix, the other side of the equation. He, as The One, is the necessary part of the core of the operating system. If I understand the logic, he's the "materialization" of the choice of every blue-pilled human in the Matrix (something along the line of Humanity's Champion). Since it is his main function, he's one of the fundamental parts of The Core of The Matrix. Again - he's the "remainder of an unbalanced equation". As the name implies, the equation must balance itself, somewhere along those lines:
The One + Zion + Humanity Enslaved in Matrix = The Machines + The Matrix Code + Programs (Agents, etc)
The problem with Neo as The One is that he is not the COMPLETE anomaly. In his specific instance it goes like this:
(Neo+Trinity) + Zion + HEiM = TM + TMC + P
Now, the question is: does Neo BECOME The One, or he IS The One? In my opinion, Neo is The One, which means that his experiences are the result of him being The Anomaly. It then follows that he's either chosen on random or it is linked to his genome in some way? Latter would explain why previous iterations of The One are looking like Neo, but then again, it is not definitive.
So, to answer your question: Neo's code is self-generated, but it is so due to him being designated The One. Neo is a definite "improvement" over "his predecessors", as acknowledged by VIP(rogram)s like the Merovingian or the Architect, which in turn means that he can go outside the basic parameters, so to speak.
For a full breakdown of the mentioned scene see, for example, here.


text:
Q: Is there a command to get model/driver/ppd of existing printers for use with `lpadmin -m`? I'm setting up CUPS of one server to have the same set of printers as another CUPS server. I generally live in the CLI and it's a long list of printers, so I was wondering how simple this could be made. Looking through the commands' docs, I see that I can add printers like this:
lpadmin -p $printer_name -E -v $printer_location -m $printer_model

I can get the $printer_names and $printer_locations with:
lpstat -v

but I can't seem to find a command that will tell me the $printer_model of each printer. I'm tempted to just hack it by scraping http://localhost:631 with curl to get the human-readable models then matching with lpinfo -m to get something suitable for lpadmin -m, but I hope there's something more conventional.

A: You might be able to grep something from the ppd files in /etc/cups/ppd/ and the (protected) file /etc/cups/printers.conf, but there is a Python interface pycups to the cups library which can talk to the server for information. For example,
#!/usr/bin/python3
import cups
conn = cups.Connection()
printers = conn.getPrinters()
for printer in printers:
    p = printers[printer]
    print(printer, p['printer-make-and-model'])

The returned printer dict has entries: printer-make-and-model
printer-is-shared printer-type device-uri printer-location
printer-uri-supported printer-state-message printer-info
printer-state-reasons printer-state.
I found pycups in the rpm package python3-cups.

A: There's no conventional command for getting the driver of an installed printer.
Here's a solution for listing lpadmin -m acceptable ppd specs (relative paths,drv:/// and/or gutenprint*:// URI's) based on meuh's suggestion to use a library:
# hpcups and gutenprint put their version in the model names. That means
# that if you install a printer then update the drivers, the model of the
# printer won't match with those available listed by `lpinfo -m`. So, we'll
# strip the version.
strip_versions() {
  sed -E 's/(, hpcups|- CUPS\+Gutenprint).*//'
}

# Using @ as a custom field delimiter since model names have whitespace.
# `join` is to match the printers' model names with those of the available
# drivers.
join -t@ -j2 -o 1.1,2.1 \
  <(
    ruby -r cupsffi -e '
      CupsPrinter.get_all_printer_attrs.each do |name, attrs|
        puts "#{name}@#{attrs["printer-make-and-model"]}"
      end
    ' | strip_versions | sort -t@ -k2
  ) \
  <(lpinfo -m | sed 's/ /@/' | strip_versions | sort -t@ -k2) |
# We may get multiple ppd specs per printer. For a few printers, I'm
# getting a relative path from the system model directory and either a
# drv:/// uri or a gutenprint.5.3:// URI. We'll filter out all but the
# first per printer.
awk -F@ '!a[$1]++' |
# Change the @ column delimiter for whitespace and align columns.
column -ts@

cupsffi is a ruby gem that can be installed with gem install cupsffi.


text:
Q: Adding subdomain for different user types I am pretty new to Rails and most of my knowledge depends on tutorials :)
So, I followed this http://www.railstutorial.org tutorial and created really good site but now I run into a problem. For my users I have a special column in my database which shows which type of user he is. For example I have column 'student' which is 'true' if user is student and 'false' if he's not.
Now I would like to create a subdomain for students. So, when student wants to sign up or sign in he would be transferred to www.student.mysite.com instead of www.mysite.com.
How can I accomplish that?
Thank you :)

A: There are a number of ways to do this, specifically you'll be interested in looking up multi-tenancy in respect to rails
--
Multi Tenancy
Whilst multi tenancy is typically the definition of having multiple databases / assets (one for each user), however, as it's ridiculously difficult to get this working in rails (something we're currently working on), you can use the principle with a single stack of data
There are several tutorials on how to achieve this with Rails here:

*

*Basecamp-style subdomains by DHH (although looks like the post is down)

*Multitenancy with PostgreSQL (Railscasts)

*Apartment Gem (achieving multi tenancy on Rails)

Although this is not directly related to your question, most of the "multi tenancy" questions
are typically based on "how do I create different subdomains for my users"
--
Subdomains
The basis of subdomains on Rails is to capture the request, and route it to the correct controller. We've managed to achieve that using the following setup:
#config/routes.rb
constraints Subdomain do #-> lib/subdomain.rb & http://railscasts.com/episodes/221-subdomains-in-rails-3

    #Account
    namespace :accounts, path: "" do #=> http://[account].domain.com/....

        #Index
        root to: "application#show"

    end
end

#lib/subdomain.rb
class Subdomain
  def self.matches?(request)
    request.subdomain.present? && request.subdomain != 'www'
  end
end

This will give you the ability to do the following:
#app/controllers/accounts/application_controller.rb
class Account::ApplicationController < ActionController::Base
   before_action :set_account

   def show
      #@account set before_action. If not found, raises "not found" exception ;)
   end

   private

   #Params from Subdomain
   def set_account
        params[:id] ||= request.subdomains.first unless request.subdomains.blank?
        @account = Account.find params[:id]
   end
end

Ideally, we'd love to handle this in the middleware, but as it stands, this is what we've got!
This will give you the ability to call the data you need from the @account variable:
#app/views/accounts/application/show.html.erb
<%= @account.name %>


text:
Q: Matplotlib Colormap with two parameter I am trying to represent two variables x and y on a map using colours.
So far the best I can acheive is using color for one variable and transparancy for another.
plt.Polygon(shape.points, fill=False, color=cmap(y), alpha=x)
Is it possible to create a 2D colormap in matplotlib that takes two variables?

A: In general colormaps in matplotlib are 1D, i.e. they map a scalar to a color.
In order to obtain a 2D colormap one would need to somehow invent a mapping of two scalars to a color. While this is in principle possible, it's not as convenient as the usual colormaps.
An example is below, where we map two parameters to the red and blue RGB color channel respectively and thereby create a 2D colormap.
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.set_aspect("equal")

x = [1,1,2,2,3,3] # xdata
y = [1,2,3,1,2,3] # ydata
p1 = [0.2,0.4,.6,.8,.6,.1] # parameter 1
p2 = [0.4,0.5,.7,.1,.3,.7] # parameter 2

# create a very simple colormap,
#  mapping parameter 1 to the red channel and
#          parameter 2 to the blue channel
cmap = lambda p1,p2 : (p1, 0, p2)

# put shapes at positions (x[i], y[i]) and colorize them with our
# cmap according to their respective parameters
for i in range(len(x)):
    circle = plt.Circle((x[i], y[i]), 0.5, color=cmap(p1[i],p2[i]))
    ax.add_artist(circle)
    tx="p1: {}\np2: {}".format(p1[i],p2[i]) # create a label
    ax.text(x[i], y[i], tx, ha="center", color="w", va="center")

ax.set_xlim(0,4)
ax.set_ylim(0,4)
ax.set_xlabel("x")
ax.set_ylabel("y")

# create the legend:

plt.subplots_adjust(left=0.1, right=0.65, top=0.85)
cax = fig.add_axes([0.7,0.55,0.3,0.3])
cp1 = np.linspace(0,1)
cp2 = np.linspace(0,1)
Cp1, Cp2 = np.meshgrid(cp1,cp2)
C0 = np.zeros_like(Cp1)
# make RGB image, p1 to red channel, p2 to blue channel
Legend = np.dstack((Cp1, C0, Cp2))
# parameters range between 0 and 1
cax.imshow(Legend, origin="lower", extent=[0,1,0,1])
cax.set_xlabel("p1")
cax.set_ylabel("p2")
cax.set_title("2D cmap legend", fontsize=10)

plt.show()

This scheme can of course be extended to other (more complicated) colormappings and also to imshow or pcolormesh plots. Also, the use of the HSV colorscheme may be beneficial compared to the RGB, so matplotlib.colors.hsv_to_rgb(hsv) might be helpful.

A: There is a Javascript plugin for 2D colormaps available here.
A quick translation of this to Python could be something like this:
# Based on: https://github.com/dominikjaeckle/Color2D

import matplotlib.pyplot as plt
import numpy as np

COLORMAP_FILE = "./bremm.png"

class ColorMap2D:
    def __init__(self, filename=None):
        self._colormap_file = filename or COLORMAP_FILE
        self._img = plt.imread(self._colormap_file)

        self._width = len(self._img[0])
        self._height = len(self._img)

        self._range_x = (0, 1)
        self._range_y = (0, 1)

    def _scale(self, u: float, u_min: float, u_max: float) -> float:
        return ((u + 1) - (u_min + 1)) / ((u_max + 1) - (u_min + 1))

    def _scale_x(self, x: float) -> int:
        val = self._scale(x, self._range_x[0], self._range_x[1])
        return int(val * (self._width - 1))

    def _scale_y(self, y: float) -> int:
        val = self._scale(y, self._range_y[0], self._range_y[1])
        return int(val * (self._height - 1))

    def __call__(self, X):
        assert len(X.shape) == 2

        self._range_x = (X[:, 0].min(), X[:, 0].max())
        self._range_y = (X[:, 1].min(), X[:, 1].max())

        output = np.zeros((X.shape[0], 3))
        for i in range(X.shape[0]):
            x, y = X[i, :]
            xp = self._scale_x(x)
            yp = self._scale_y(y)
            output[i, :] = self._img[xp, yp]
        return output

which expects the bremm.png file in the same directory.
This can be used in the same way as any other Matplotlib colormap:
cmap = ColorMap2D()
colors = cmap(array)

where array is an N x 2 matrix of (x, y) coordinates.


text:
Q: Homestead 2.0 giving issues on Yosemite I have this strange problem. Let me describe it:

*

*The mapping on the .yaml doesn't work. forum.app will just open up a Google search.

*The debug is set to true for local, yet, errors aren't presented in browser. They're logged though.

I am using Homestead 2.0, Laravel 4 (everything is latest) on a Yosemite (updated today). The code is here:
YAML file

---
ip: "192.168.10.10"
memory: 2048
cpus: 1

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: /Users/aligajani/Dropbox/Work/Code
      to: /home/vagrant/Code

sites:
    - map: forum.app
      to: /home/vagrant/Code/CommunityFT/forum/public

databases:
    - homestead

variables:
    - key: APP_ENV
      value: local

HOSTS file

#Added by XAMPP Control
127.0.0.1 Alis-MacBook-Pro.local
192.168.10.10  forum.app

A: In order to get forum.app to be a valid domain that works with Homestead, you'll need to point it to your local computer in your hosts file.
You can do this by opening up terminal, and typing vim /etc/hosts, then add the line:
127.0.0.1 forum.app

Your browser may fail to look up the forum.app domain too, so remember to try adding a forward slash teh first time you visit it, so forum.app/, this will prevent the browser trying to google it.
Errors not being presented to the browser may be something to do with this pull request:
https://github.com/laravel/homestead/pull/140
Which is an Nginx configuration issue.
Hope this helps!


text:
Q: How can i rotate the particular view landscape or portrait programatically in android? how can rotate the particular view in Landscape or portrait mode in dynamically in android. i am using the this method
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
but it total layout going to landscapmode .but i want particular view in landscape mode.
so,please tell me anyone known .Advance thanks to all

A: Following is code which i used to display your activity into landscape mode
<activity android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden"
android:name="yourActivty"/>

Change it according to your need


text:
Q: How to determine a git branch source or find a merge commit I have 3 main branches: PROD, TEST, and DEVELOP and developers work in feature branches that are created from the PROD branch. And then the feature branch is merged into the environment branches at the respective point in its lifecycle.
I am now seeing commits in PROD and FEATURE branch that should only exist in the TEST branch. I don't know if the FEATURE branch was incorrectly created from the TEST branch (and then merged into PROD), or if the TEST branch was merged into the FEATURE branch before the FEATURE branch was merged back into the PROD branch. Or possibly the TEST branch was incorrectly merged into the PROD branch before the FEATURE branch was created.
I've tried using gitk on both the PROD and FEATURE branches, which is how I'm seeing the TEST branch commits in those branches, but how can I determine when, who, and how this was messed up?

A: To see a nice pretty line graph between all your branches that you can scroll back in time to see what got merged where, use:
git log --graph --oneline --decorate --all

If you want to investigate those fishy commits on the PROD branch, then you can just look at it's graph history which will include branch paths that were merged into it with:
git log PROD --graph --oneline --decorate

A: git log will show author, date, time, and commit message, if any

A: git log --graph

will show the author and date of the commits/merges


text:
Q: How to calculate degree of freedom for pooled variance? 05/08/2017 update - more on background: Each lab contributes multiple test results for that same sample, all collected by the same operator on a single instrument. Then for each lab, I calculate the sample variance of the multiple test results (just the square of the standard deviation of all the data, not concerned about sampling distribution of the mean), and I use this sample variance to represent the variability of the data submitted by this lab.
Background: I'm estimating variability of test results submitted by different labs on the same sample. For each lab I can obtain a variance estimate, so for the network that consists of all those labs, I have the pooled variance. Then I need to construct confidence intervals from the pooled variance, and this is why I need to have the degree of freedom.
Question: For pooled variance, I've seen some say the degree of freedom is just the denominator of the pooled variance, and others say we need to use Welch–Satterthwaite equation to calculate dof for the pooled variance. Which is correct?


text:
Q: yii2 create view to display model I'am trying to implement the demos.krajee.com/grid-demo in a project but i am getting stuck creating the grid for the detail view.
It is a grid and when use the expandRow functionality of the extention I need to get all the related records from another table base in the id (master - detail scenario)
In the controller i have this function that it is working fine to get all records for an specific id:
    public function actionDetail() {
    $searchModel = new AttendanceSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    if (isset($_POST['expandRowKey'])) {
        $IDcustomers = Yii::$app->request->post('expandRowKey');

    $model = Attendance::find()
            ->where(['IDcustomers' => $IDcustomers])
            ->all();
        return $this->renderPartial('_attendance-details', ['model'=>$model]);

    } else {
        return '
No data found
';
    }
}

The problem now is how to create the view (_attendance-details) from the $model and get all the records display in a grid.
if i use DetailView with the first element of $model works fine:
        <?= DetailView::widget([
    'model' => $model[0],
    'attributes' => [
        'IDattendance',
        'IDcustomers',
        'date',
        'doctor',
        'lawyer',
    ],
]) ?>

But when i try to use grid i need the dataprovider and i can't make it work with the $model i am passing.
I am very new to yii so any guide will be much appreciated.

I tried vitalik and work perfect

A: In controller set:
public function actionDetail()
{
    if (isset($_POST['expandRowKey'])) {
        $IDcustomers = Yii::$app->request->post('expandRowKey');

        $model = Attendance::find()
            ->where(['IDcustomers' => $IDcustomers]);
        $dataProvider = new ActiveDataProvider([
            'query' => $model,
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        return $this->renderPartial('_attendance-details', ['dataProvider' => $dataProvider]);

    } else {
        return '
No data found
';
    }
}

In view:
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'IDattendance',
        'IDcustomers',
        'date',
        'doctor',
        'lawyer',
    ],
]);?>


text:
Q: Access Debug IIS Server From Virtual Machine (VS Express 2013 for Web) I'm developing a web site with Visual Studio 2013 Express for Web on Windows 7, and I need to ensure compatibility with IE8, so I installed Windows Virtual Machine/XP Mode, and set up network bridging to that the VM uses the same network adapter as the main machine.
Ideally, I would like to be able to connect IE8 running in the VM to the debug IIS server started by Visual Studio on the W7 machine, since having to deploy the site to the actual server every time I want to test a minor fix to the formatting would be a hassle.
The VM network bridging seems to be successful, since I can access domain-only web sites and ping the W7 machine from the VM, but pointing a browser to the site address and substituting the W7 IP for "localhost" comes back with a connection problem, I suspect because IIS is refusing the connection.
Is there a way to configure the IIS process that Visual Studio uses for debugging so that I can connect to it from a virtual machine?


text:
Q: Unable to send ALT + Insert using sendkeys in vba I would like to send ALT+Insert in VBA. Its not working please suggest.
SendKeys "%[INSERT]" // its work only insert.

A: Use Application.sendkeys
Sub Test1()
    Application.SendKeys ("%{INSERT}")
    DoEvents
End Sub


text:
Q: How to connect Preferences with Activities? Pretty new to Android Studio, and I'm having a problem connecting my CheckBoxs' in my preferences.xml with all my other activities so they act as settings for the application. I have set up everything just as the official page (https://developer.android.com/guide/topics/ui/settings.html) had said, but I still can't get everything to work properly.
Here's my Settings class:
public class Settings extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }
}

and my SettingsFragment class:
public class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
     }
}

What I'm trying to do is to switch music or sfx either on if checked or off if unchecked around the app, here is my preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <CheckBoxPreference
        android:key="music check box"
        android:title="Music"
        android:defaultValue="true"
        android:id="@+id/checkMusic"/>

    <CheckBoxPreference
        android:key="sfx check box"
        android:title="SFX"
        android:defaultValue="true"
        android:id="@+id/checkSfx"/>

    <CheckBoxPreference
        android:key="notifications check box"
        android:title="Notifications"
        android:defaultValue="true"
        android:id="@+id/checkNotif"/>

</PreferenceScreen>

Now my MediaPlayer is located in an Application class so it would go around every activity. How do I go about all of this?

A:
Now my MediaPlayer is located in an Application class so it would go around every activity

That may not be the correct pattern.

How do I go about all of this?

Have the component managing your MediaPlayer (Application as it stands, possibly a Service sometime later) call registerOnSharedPreferenceChangeListener() on the SharedPreferences to find out about changes. Then, react to those changes as needed.


text:
Q: Import Excel data to SQL Server table using VB.Net application I found several articles on this topic but the issues are different. I'm trying to import data from an Excel 2016 file into SQL Server 2017 using a VB.net application, so that the end-users need not to have SQL Server installed on their machines. I ran the application in debug mode to identify the issue.
Again I read articles on various instances related to the following error:

The 'Microsoft.ACE.OLEDB.15.0' provider is not registered on the local machine

My code:
Dim TheData As DataTable = GetExcelData(OpenFileDialog1)

Private Function GetExcelData(File As OpenFileDialog) As DataTable
    Dim oleDbConnection As New OleDbConnection

    Try
        OpenOLEDBConnections(oleDbConnection, "Provider=Microsoft.ACE.OLEDB.15.0;Data Source=" & File.InitialDirectory & _
        File.FileName & "; ;Extended Properties=""Excel 12.0 XML;HDR=YES;""")

        Dim oleDbDataAdapter As OleDbDataAdapter = New OleDbDataAdapter("Select '' as ID, 'AL' as Supplier, LTRIM(RTRIM(GRADE)) AS GRADE, [ship date] as shipdate, LTRIM(RTRIM(coil)) AS coil, L15*1000 AS L15, H15*1000 AS H15 FROM [sheet1$] where COIL is not null group by GRADE, [SHIP DATE], COIL, L15, H15", oleDbConnection)
        Dim dataTable As DataTable = New DataTable()
        oleDbDataAdapter.Fill(dataTable)
        oleDbConnection.Close()

        Return dataTable
    Catch ex As Exception
        oleDbConnection.Close()

        Return Nothing
    End Try

End Function

Private Sub OpenOLEDBConnections(ByRef cnData As OleDbConnection, cnDataConstr As String)

    If Not cnData.State = ConnectionState.Closed Then cnData.Close()
    If cnData.State = ConnectionState.Closed Then
        cnData.ConnectionString = cnDataConstr
        cnData.Open()
    End If

End Sub

A: Not that this is the silver bullet, but i dont like the look of your connection string. There appears to be a ";" out of place. Try this one
Dim XLSFile As String = "C:\DATA\test.xlsx"
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;" &
    "Data Source=" & XLSFile & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;"""

A: Try installing ACE provider from the following link
https://www.microsoft.com/en-us/download/confirmation.aspx?id=13255
How to import Excel into SQL Server, check out on
https://www.red-gate.com/simple-talk/dotnet/c-programming/office-development-in-visual-studio/
Or try using this snippet
Imports System
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Runtime.InteropServices
Imports Excel = Microsoft.Office.Interop.Excel

Public Module Program
    Public Sub Main()
        Dim officeType = Type.GetTypeFromProgID("Excel.Application")

        If officeType Is Nothing Then
            Console.WriteLine("Sorry, Excel must be installed!")
            Console.WriteLine("Press any key to exit")
            Console.ReadLine()
            Return
        End If

        Const fileToRead As String = "C:\TMP\FirstTest.xlsx"
        Dim xlApp As Excel.Application = Nothing
        Dim workbooks As Excel.Workbooks = Nothing
        Dim xlWorkBook As Excel.Workbook = Nothing
        Dim sheets As Excel.Sheets = Nothing
        Dim t1 As Excel.Worksheet = Nothing

        Try
            xlApp = New Excel.Application()
            Console.WriteLine($"Trying to open file {fileToRead}")
            workbooks = xlApp.Workbooks
            xlWorkBook = workbooks.Open(fileToRead, 0, True, 5, "", "", True, Origin:=Excel.XlPlatform.xlWindows, Delimiter:=vbTab, Editable:=False, Notify:=False, Converter:=0, AddToMru:=True, Local:=1, CorruptLoad:=0)
            sheets = xlApp.ActiveWorkbook.Sheets
            Dim dic = New List(Of String)()

            For Each mSheet In sheets

                dic.Add($"[{t1.Name}$]")
            Next

            Using myConnection = New OleDbConnection($"Provider=Microsoft.Ace.OLEDB.12.0;Data Source={fileToRead};Extended Properties='Excel 12.0 Xml;HDR = YES;'")

                Using dtSet = New DataSet()

                    For Each s In dic
                        Console.WriteLine($" Processing {s} table")
                        Dim myCommand = New OleDbDataAdapter($"select * from {s};", myConnection)
                        myCommand.TableMappings.Add("Table", s)
                        myCommand.Fill(dtSet)
                    Next

                    For Each t As DataTable In dtSet.Tables
                        Console.WriteLine($" Table {t.TableName} has {t.Rows.Count} records")
                    Next
                End Using
            End Using

            dic = Nothing
            Console.WriteLine("Successfully imported!")
            Console.WriteLine("After closing Console Windows start Task Manager and be sure that Excel instance is not there!")
            Console.WriteLine("Press any key to exit")
            Console.ReadLine()
        Catch e As Exception
            Console.WriteLine($"Error importing from Excel : {e.Message}")
            Console.ReadLine()
        Finally
            GC.Collect()
            GC.WaitForPendingFinalizers()

            If sheets IsNot Nothing Then
                Marshal.FinalReleaseComObject(sheets)
                sheets = Nothing
            End If

            xlWorkBook.Close()

            If xlWorkBook IsNot Nothing Then
                Marshal.FinalReleaseComObject(xlWorkBook)
                xlWorkBook = Nothing
            End If

            xlApp.Quit()

            If xlApp IsNot Nothing Then
                Marshal.FinalReleaseComObject(xlApp)
                xlApp = Nothing
            End If

            GC.Collect()
            GC.WaitForPendingFinalizers()
        End Try
    End Sub

End Module

A: After I spent a day and half, I somehow managed to resolve the issue by going through the following link and tried the option mentioned by Manju K Gowda Monday, May 14, 2012 12:14 PM
Microsoft.ACE.OLEDB.15.0 and also modified my connection string provider from OLEDB 15.0 to 12.0.
To be precise, while building the solution either in Debug or release mode, keep the Configuration Manager to x86 instead of AnyCPU


text:
Q: How can I get a definite child of div without class/id How can I use second/third div in JS/JQuery without using class or id on this element?

And also is there any possibility to find out what child element by number(order) it is? Like:

$('.hey').click(function(){
// what element by number is that?
});

A: Use :eq()
var secondInnerDiv = $('div div:eq(1)');
var thirdInnerDiv = $('div div:eq(2)');

$('div div:eq(1), div div:eq(2)').css('background', 'green');

1

2

3

4

Or :lt()/gt()
var secondAndThirdInnerDiv = $('div div:gt(0):lt(2)');

$('div div:gt(0):lt(2)').css('background', 'green');

1

2

3

4

Update
Use index()
$(this).index()

$('div div').click(function(){
  console.log($(this).index());
  });

1

2

3

4

A: you can work with this I quess:
https://api.jquery.com/nth-child-selector/

A: This is what I'd use for example:
div > div:first-child {
    background-color:yellow;
}

Here is a JSFiddle demo
Note that div > div selects all the immediate div childrens. For the demo I made it highlight only the first child using :first-child

A: Here is the code that gives a hint on one of the approaches
var allDivs = $(".parentcontainer > div");
var secondDiv = $(allDivs.get(1));
var thirdDiv = $(allDivs.get(2));

A: You can use the slice() method:
var secondAndThirdDiv = $("div div").slice(1,3);

You basically specify the range of elements you want (0 index based of course).

A: http://jsfiddle.net/k4pm1fxw/
// return position
$('.parentcontainer').on('click', '.hey', function(){
    alert($(this).index());
});
// select nth with eq
$('.parentcontainer').find('.hey').eq(2).css('background', 'red');


text:
Q: How to arrange Windows in a specific order using Windows.Arrange? I have opened more Excel Windows and I will arrange them with macros.
How could I decide the arrange of the windows?
At the moment the arrange of the windows is random.
If I make the arrange a second time, the windows will be arrange in an other order.
I used this script:
Windows.Arrange ArrangeStyle:=xlVertical


text:
Q: What is the best book about generalized linear models for novices? I'm still pretty new to generalized linear models, and I struggle with a lot of the notation in most of the GLM texts I've picked up. Are there extremely popular GLM books that lend themselves better to readability?

A: For a new practitioner, I like Gelman and Hill.
Data Analysis Using Regression and Multilevel/Hierarchical Models
Ostensibly the book is about Hierarchical Generalized Linear Models, a more advanced topic than GLMs; the first section, though, is a wonderful practitioners guide to GLMs.
The book is light on theory, heavy on disciplined statistical practice, overflowing with case studies and practical R code, all told in a pleasant, friendly voice.

A: I am a big fan of Agresti's Categorical Data Analysis.
I have read Agresti's Intro book but found it missing key interpretations for how generalized linear model is built and how it works. For example, you may not need to know how the binomial distribution and logit link work if you only want to fit a logistic regression. However it is annoying when you have read the chapter and started to wonder about it but couldn't find it in the book.
The McCullagh and Nelder GLM book is hard to read. It contains everything you need to know but lacks the derivation for the key results.
Luckily Agresti's Categorical Data Analysis presents a good balance.

A: As a complete beginner myself, I found Foundations of Linear and Generalized Linear Models by the celebrated author of Categorical Data Analysis Alan Agresti to be helpful. Language is fluid, though some exposure to Linear Algebra is assumed.

A: I really liked Mixed Effects Models with Extensions in R - Zuur, et. al. It's a followup to their older book Analysing Ecological Data (2007). They do a good job of motivating the models, along with plenty of visual examples to explain what GLMs look like. They also strike a good balance between, theory, application and discussion. Plus they have all codes and datasets on their website, so you can immediately apply what you've learned.


text:
Q: Why check did_load_filetypes in custom filetype files? From vim wiki:

Custom filetype.vim files should always have the following structure:

if exists("did_load_filetypes")
  finish
endif

augroup filetypedetect
  " au! commands to set the filetype go here
augroup END

I am wondering why is the if...endif part necessary?
I think this basically means that if filetypes are already loaded, then skip loading this script. But in that case what's the point of creating a custom filetype file?

A: This is just an include guard, to avoid that your custom filetype is accidentally sourced multiple times.
If all goes well, this indeed looks superfluous, but with all the variations in user configuration, plugin managers, etc., it's better to be safe. And it saves Vim from re-processing the potentially large list of definitions, speeding up startup.
What happens when this is actually sourced twice?
If you use :autocmd instead of :autocmd!, all your detections would be defined twice. (Note that an initial :autocmd! cannot be used here to clear all previous definitions, because multiple filetype.vim files are involved, and each only adds to the existing ones.)


text:
Q: Bot will not disconnect from VC but won't raise any errors [Discord.py] My bot should disconnect from a Voice Channel when someone runs the disconnect command.

My bot does not disconnect from the Voice Channel

But it also does not raise any errors

My code:
@client.command()
async def disconnect(ctx):
    vc = ctx.voice_client

    if not vc:
        await ctx.send("I am not in a voice channel.")
        return

    await vc.disconnect()
    await ctx.send("I have left the voice channel!")

This code is the code that another StackeOverflow user showed me, yet it doesn't work.

When no one is in the Voice Channel it sends the if not in vc message, so the channel clearly has been found

When someone is in the vc, it sends the: "I have left the voice channel!" message yet it never actually left

Does anyone know why it doesn't work and how could I fix this.
Thanks!

A: You need to save the voice_client of the voice channel when the bot connected to this voice channel, so you cannot disconnect the bot if you don't have it.
Look in your code where you used channel.connect() and this returns the voice_client which you need to use it in disconnect.
You're wrong when you want to use ctx, it used for who wrote the command and not the bot.


text:
Q: 'Unable to get value from JSON object in node js I have a jsp file that returns a json object using the following code:
    JSONObject object = new JSONObject();

    object.put("name","domain");
    object.put("email","domain.com");

    response.setContentType("application/json");
    response.getWriter().write(object.toString());

The output is: {"name":"domain","email":"domain.com"}
I trying to get the values from this JSON using following code in node.js:
        var endpoint = // contains the address of the above jsp file;

        var body = ""
        http.get(endpoint, (response) => {
          response.on('data', (chunk) => { body += chunk })
          response.on('end', () => {
            console.log("Body: "+body);
            console.log("Body name: "+body.name);
          })
        })

In the above snippet I get following output for console.log -
Body: {"name":"domain","email":"domain.com"}
Body name: undefined
I don't know why "body.name" is not working.
Could any body please help in getting the values from the json object. Since, body itself is json object so I don't need to do JSON.parse

A: Try this. You have to parse the JSON string to assign it to a js object.
    var endpoint = // contains the address of the above jsp file;

    var body = {}
    http.get(endpoint, (response) => {
      response.on('data', (chunk) => { body = JSON.parse(chunk) })
      response.on('end', () => {
        console.log("Body: "+body);
        console.log("Body name: "+body.name);
      })
    })

A: body object is string. Because of that when you try to write it in console:
console.log("Body: "+body);

You get this:
Body: {"name":"domain","email":"domain.com"}

But since body is string you cannot get its property name. String doesn't have proerty name. You should firstly parse string to JSON
    var endpoint = // contains the address of the above jsp file;

    var body = ""
    http.get(endpoint, (response) => {
      response.on('data', (chunk) => { body += chunk })
      response.on('end', () => {
        console.log("Body: "+ body);
        var parsedBody = JSON.parse(body);
        console.log("Body name: "+ parsedBody .name);
      })
    })


text:
Q: How to generate the newid when there is change in column value in sql server Consider below example
ID| RecordUID                          |   Person |Value
1 |49D62793-989B-4135-9873-21572D511297|   Test   |10
2 |49D62793-989B-4135-9873-21572D511297|   Test   |11
3 |DDB40B89-2BB4-4536-9847-32B9F53C0196|   Test1  |21

how to generate the above new id(RecordUID(NewID())) when there is a change in the value of a person column?
I need for a select query like
Select ID,NewID() when a change in Person, value from Table A

Thanks In Advance!!!

A: I suppose you're looking for an AFTER UPDATE TRIGGER as the following
CREATE TRIGGER MyTrig
ON Data
AFTER UPDATE
AS

   UPDATE D
   SET RecordUID = NEWID()
   FROM Data D
   JOIN (
          SELECT I.Id
          FROM INSERTED I
          JOIN DELETED D ON I.Id = D.Id AND I.Person <> D.Person
        ) T ON D.Id = T.Id;

Here is a db<>fiddle where you can see how it's working online.


text:
Q: Как перерисовать MediaView, после выбора нового медиафайла? В программе предусмотрена возможность открывать другие медиафайлы, но после выбора следующего файла и его запуска появляется только звук, а видеокартинка не обновляется, как это реализовать в JavaFX?
public class MediaPlayerMain extends Application {

static Stage stage;

@Override
public void start(Stage stage) {
    try {
        MediaPlayerMain.stage = stage;
        URL url = getClass().getResource("/application/MediaPlayerView.fxml");
        BorderPane pane = FXMLLoader.load(url);
        Scene scene = new Scene(pane);
        stage.setTitle("Media Player");
        stage.setScene(scene);
        stage.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static Stage getStage(){
    return stage;
}

public static void main(String[] args) {
    launch(args);
}
}

public class MediaPlayerController implements Initializable {
@FXML
ToolBar toolBar;

@FXML
CheckBox checkBox;

@FXML
Slider slider;

@FXML
Button btnPlay, btnPause, btnStop, btnOpen;

@FXML
BorderPane borderPane;

private Media media;
private MediaPlayer mediaPlayer;
private MediaView mediaView;

public void initialize(URL location, ResourceBundle resources) {
    borderPane.setCenter(createMediaView());
    toolBar = new ToolBar(btnPlay, btnPause, btnStop, btnOpen, slider, checkBox);
    borderPane.setBottom(toolBar);
    MyEvent event = new MyEvent();
    btnPlay.setOnAction(event);
    btnPause.setOnAction(event);
    btnStop.setOnAction(event);
    btnOpen.setOnAction(event);
}

public String getPath(){
    FileChooser fc = new FileChooser();
    fc.getExtensionFilters().add(new ExtensionFilter("Media files","*.flv", "*.mp4", "*.mpeg"));
    File file = fc.showOpenDialog(null);
    String path = file.getAbsolutePath();
    path = path.replace("\\", "/");
    return path;
}

public MediaView createMediaView(){
    media = new Media(new File(getPath()).toURI().toString());
    mediaPlayer = new MediaPlayer(media);
    mediaView = new MediaView(mediaPlayer);
    mediaPlayer.setAutoPlay(true);
    return mediaView;
}

public void fullScreen(ActionEvent event){
    if(checkBox.isSelected()){
        MediaPlayerMain.getStage().setFullScreen(true);
        System.out.println("Fullscreen true");
    }else{
        MediaPlayerMain.getStage().setFullScreen(false);
        System.out.println("Fullscreen false");
    }
}

class MyEvent implements EventHandler<ActionEvent> {

    public void handle(ActionEvent event) {
        Button btn = (Button) event.getSource();
        if (btn.equals(btnPlay)) {
            mediaPlayer.play();
        } else if (btn.equals(btnPause)) {
            mediaPlayer.pause();
        } else if (btn.equals(btnStop)) {
            mediaPlayer.stop();
        } else if (btn.equals(btnOpen)){
            if(mediaPlayer.getStatus().equals(Status.PLAYING)){
                mediaPlayer.pause();
                createMediaView().setMediaPlayer(new MediaPlayer(media));
            }
        }
        System.out.println(btn.getText());
    }

}
}

A: Т.к. никто не подсказал, нашел собственное решение. Код немного изменил, где-то добавил метод, где-то объединил. Класс MediaPlayerMain не поменялся, изменения были добавлены только в класс MediaPlayerController.
public class MediaPlayerController implements Initializable {
@FXML
ToolBar toolBar;

@FXML
CheckBox checkBox;

@FXML
Slider slider;

@FXML
Button btnPlay, btnPause, btnStop, btnOpen;

@FXML
BorderPane borderPane;

private Media media;
private MediaPlayer mediaPlayer;
private MediaView mediaView;

public void initialize(URL location, ResourceBundle resources) {
    borderPane.setCenter(createMediaView());
    createToolbar();
    MyEvent event = new MyEvent();
    btnPlay.setOnAction(event);
    btnPause.setOnAction(event);
    btnStop.setOnAction(event);
    btnOpen.setOnAction(event);
}

public void createToolbar() {
    toolBar = new ToolBar(btnPlay, btnPause, btnStop, btnOpen, slider, checkBox);
    borderPane.setBottom(toolBar);
}

public MediaView createMediaView() {
    FileChooser fc = new FileChooser();
    fc.getExtensionFilters().add(new ExtensionFilter("Media files", "*.flv", "*.mp4", "*.mpeg"));
    File file = fc.showOpenDialog(null);
    String path = file.getAbsolutePath();
    path = path.replace("\\", "/");
    media = new Media(new File(path).toURI().toString());
    mediaPlayer = new MediaPlayer(media);
    mediaView = new MediaView(mediaPlayer);
    mediaPlayer.setAutoPlay(true);
    return mediaView;
}

public void fullScreen(ActionEvent event) {
    if (checkBox.isSelected()) {
        MediaPlayerMain.getStage().setFullScreen(true);
        System.out.println("Fullscreen true");
    } else {
        MediaPlayerMain.getStage().setFullScreen(false);
        System.out.println("Fullscreen false");
    }
}

class MyEvent implements EventHandler<ActionEvent> {

    public void handle(ActionEvent event) {
        Button btn = (Button) event.getSource();
        if (btn.equals(btnPlay)) {
            mediaPlayer.play();
        } else if (btn.equals(btnPause)) {
            mediaPlayer.pause();
        } else if (btn.equals(btnStop)) {
            mediaPlayer.stop();
        } else if (btn.equals(btnOpen)) {
            if (mediaPlayer.getStatus().equals(Status.PLAYING)) {
                mediaPlayer.pause();
                borderPane.setCenter(createMediaView());
                createToolbar();
            }
        }
        System.out.println(btn.getText());
    }

}
}


text:
Q: How to provide two values in query string in LzBrowser.loadURL in openlaszlo How can i pass two values in a query string using LzBrowser.loadURL() in openlaszlo.
My sample code:
LzBrowser.loadURL("../modules/Index.jsp?base="+ canvas.base +" id=" + canvas.Id,"fraMain");

I am getting number Format exception:
java.lang.NumberFormatException: For input string: "1 base=1"]
Please help in solving this.
Thanks,
Raj

A: You should add & between two query parameters . You should write like this
LzBrowser.loadURL("../modules/Index.jsp?base="+ canvas.base +"&id=" + canvas.Id,"fraMain");

A: We have to provide & amp; instead of &. It worked for me.

A: The number format exception means, that at some point in your code the browser tries to parse a string into a number. Which version of OpenLaszlo did you use, and which runtime?
Based on the use of LzBrowser (starting with OpenLaszlo 4.1 you have to use lz.Browser instead) it seems that you are using either a 3.x or the 4.0 release of OpenLaszlo.
If you want to use the ampersand "&" within methods containing JavaScript code, the XML entity rules apply (everything which starts with an & will be treated as an XML entitity). Adding  sections in your methods will let you use the & as you'd do in normal JavaScript or ActionScript code, e.g.
<canvas debug="true">

  <button text="Open URL" onclick="canvas.loadUrl()" />

  <attribute name="base" type="number" value="99" />

  <attribute name="iD" type="number" value="10" />

  <method name="loadUrl"><![CDATA[
    lz.Browser.loadURL("http://www.google.com?base=" + canvas.base + "&iD=" + canvas.iD, "_blank");
  ]]></method>

</canvas>

Without the CDATA section, the following compiler error will be thrown:

loadurl.lzx:10:71: The reference to entity "iD" must end with the ';'
  delimiter. Look for a misplaced or unescaped ampersand ('&') character
  in your source code.

The described workaround of using "&" instead of "&" and no CDATA section is of course a valid option - although it reduced the readability of the JavaScript code in my eyes.

A: Actually there are two ways to do this, both of the following are correct:
1) Escape the special HTML characters (in this case &) by surrounding the internal code with <![CDATA[ and ]]> tags:
<method name="loadUrl">
<![CDATA[
    lz.Browser.loadURL("http://www.google.com?base=" + canvas.base + "&iD=" + canvas.iD, "_blank");
]]>
</method>

2) HTML-entity encode the & character to &
<method name="loadUrl">
    lz.Browser.loadURL("http://www.google.com?base=" + canvas.base + "&iD=" + canvas.iD, "_blank");
</method>

Which method you choose is up to your own preference.


text:
Q: How to locate to a method in IDEA quickly in the outline by paste method name? In eclipse, we can press ctrl + o to popup a outline view, and paste some text (copied from somewhere previously) and locate the corresponding method.
But in IDEA, althought there is a similar view (by press ctrl + F12), but it doesn't support pasting, that I have to type the method name manually.
I wonder is it possible to locate the method declaration by pasting in IDEA?

A: Use ctrl + F12 to open the dialog. Start typing a (for example) to enter the search, then delete it, and paste.
It's kind of awkward, but it works, and once you get used to it, it really isn't an issue.


text:
Q: Fluent validation, set the minimum value in case property has value less then I'm using fluent validation in order to validate certain model.
public class CarModelValidator : AbstractValidator<CarModel>
{
    public CarModelValidator ()
    {
        RuleFor(x => x.Name).NotEmpty();
        // RuleFor(x => x.NrOfDoors)....
    }
}

is it possible to validate CarModel and it's property NrOfDoors, and if its less than 2 to set the value to be 2. Or fluent validation is not meant for that? Is it just for validate the model and informing the user and not for setting the values?

A: Best practice is that validation via any class library or tools do only the validation task and It is based on Separation_of_concerns pattern.
But if you need to make sure NrOfDoors property has maximum value by 2 you can use full property like this:
public class CarModel
{
    private int nrOfDoors;

    public int NrOfDoors
    {
        get { return nrOfDoors; }
        set
        {
            if (value > 2)
                nrOfDoors = 2;
            else
                nrOfDoors = value;
        }
    }
}

A: I think RuleFor(x => x.NrOfDoors).GreaterThanOrEqualTo(2) should do the trick

A: I think the real answer is:  It is not meant for that. Validation is an intermediate step to deny a value change and inform the user if the rule(s) would be broken.


text:
Q: Azure Media Encoder Standard Unknown Error I am trying to run some video encoding using Azure Media Encoder Standard. However, the process runs and then errors out with this vague error coming from the Task object in the state changed event:
Error code: Unknown
Error message: The given key was not present in the dictionary.

The code that queues the encoding is roughly this:
IMediaProcessor mediaProcessor = GetLatestMediaProcessorByName(context, "Media Encoder Standard");

var jobName = this._inputAsset.Name + "_EncodingJob";
var job = context.Jobs.Create(jobName);
ITask encodingTask = job.Tasks.AddNew(
this._inputAsset.Name + "_EncodingTask",
    mediaProcessor,
    "H264 Adaptive Bitrate MP4 Set 720p",
    TaskOptions.ProtectedConfiguration);
encodingTask.InputAssets.Add(this._inputAsset);
encodingTask.OutputAssets.AddNew(this._inputAsset.Name + "_EncodingOutput", AssetCreationOptions.None);

job.StateChanged += job_StateChanged;

The video I'm trying to encode is already an MP4 and the asset is created with the video blob in its container before the above code executes.

A: I think that you are trying to use a Azure Media Encoder preset with Media Encoder Standard. The lists of supported presets are not the same between the two encoders.
You'll find the presets for Media Encoder Standard on this page : https://msdn.microsoft.com/en-us/library/azure/mt269960.aspx
And the presets for Azure Media Encoder on this page : https://msdn.microsoft.com/en-us/library/azure/dn619392.aspx
Hope this helps,
Julien


text:
Q: What is the best way to create a form in asp.net mvc 5 for conditional inputs. Using the divs and render partial or Ajax I have a form in which I want the user to select using the radio button if its a company or individual user. Based on the selection I want to show and hide certain input fields like BirthDate, Gender etc (which is applicable for an individual user but not a company). I have tried different approach but each one has some or the other problem.
Using Html.Partial in the View

        @Html.Partial("Company")

        @Html.Partial("Individual")

The radio button change event:
$("[name=IsIndividual]").on('change', function(){
                var $radio = $(this);

                var $individual = $radio.val();
                if ($individual == "True") {
                    $('.companyDiv').hide();
                   // $('.companyDiv').prop('disabled', true);
                    $('.individualDiv').show();
                  //  $('.individualDiv').prop('disabled', false);

                }
                else {
                    $('.individualDiv').hide();
                  //  $('.individualDiv').prop('disabled', true);
                    $('.companyDiv').show();
                 //   $('.companyDiv').prop('disabled', false);

                }
            });

Using this approach everything loads fine in the View but when I post it the fields which are present in both the partials become null in the controller. The reason to have the same fields in both partial is because I want to use same field in different way. Example - I have a firstName field which I use for first name in case of individual user but in case of company I want to use it to capture name with different labels and validations in both cases.
Using Ajax approach
Main Page

    $(function(){
        $("[name=IsIndividual]").on('change', function(){
            var $radio = $(this);
            $.ajax({
                url:'@Url.Action("GetType", "Customers")',
                data: { IsIndividual: $radio.val() },
                type: 'GET',
                success: function(data){
                    $("#loadpartial").html(data);
                }
            });

        });
    });

Controller
    [HttpGet]
    public ActionResult GetType(bool IsIndividual)
    {
        if (IsIndividual)
        {
            return PartialView("Individual");
        }
        else
        {
            return PartialView("Company");
        }
    }

Partial
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/plugins/select2")
    @Scripts.Render("~/plugins/dataPicker")

}

But in this case the controls like datepicker doesnt work. I am not sure what I am doing wrong here since I tried moving the script from main page to the partial.
Also since I am very new to this I am not sure what is the best practice to achieve this. Either of the 2 approach or something else altogether.

A: When using partial views, the issue is most likely that the element 'name' attributes are not being set with the correct prefix. Check the rendered html to see if the names being rendered from the partial are correct according to elements that are not part of the partial. If they don't match what the model binder expects then they will be null in the controller.
For the Ajax approach, the issue is that you are dynamically loading your elements so they are added to the DOM after the datepicker function has been called so it is not applied to them. You should call the datepicker function in the success function of your Ajax call rather than the document.ready function. The datepicker should then work.
And to actually answer your question, in this particular situation, I would recommend the ajax route as you will only be loading the content the user selects. But either approach is fine.


text:
Q: How to close a video after it ends in a batch script? How can a .bat file open a .avi, .wmv,.mp4 or .mov file and make it close when the video ends?
Is it possible? If not, is there an alternative way to do that?

A: Timeout command should do the deed for you if you know the fixed values of the vidoes your running.
Ex.
start video.mp4
timeout 10 >nul
TASKKILL VLC.exe


text:
Q: Error with creating new folder Hello right now Im trying to download some files on my server to my phone with my app. I'm trying to write it on my storage but not on my sdcard!
I have the necessary permissions on my device in the manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

This is my code from the DownloaderClass to create new folder. I get the return Download complete... and in the debugger it is showing me the path it is saving it in exactly where I want it, but if I look there .... the folder the Folder should be in is empty.
        //File new_Folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "MY DOWNLOADED FILES");
        String intStorageDirectory = context.getFilesDir().toString();
        File new_Folder = new File(intStorageDirectory, "MY DOWNLOADED FILES");
        if (!new_Folder.exists()) {
            if (!new_Folder.mkdir()) {
                return "ERROR: mkdirs() failed for directory" + new_Folder.getAbsolutePath();
            }

        } else {
            Log.i("Info:", "Folder already exists");
        }

        /**
         * Create an output file to store the file for download
         */

        inputoutput_file = new File(new_Folder, "downloaded_files.jpg");

        InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
        //this will read the information in 1 KB
        byte[] data = new byte[1024];
        int total = 0;
        int count;

        OutputStream outputStream = new FileOutputStream(inputoutput_file);

        while ((count = inputStream.read(data))!= -1){
            total+=count;

            if (file_length>0) {
                int progress = total * 100 / file_length;
                publishProgress(progress);
                outputStream.write(data, 0, count);
                Log.i("Info:", "Progress: " + Integer.toString(progress));
            }
        }

        inputStream.close();
        outputStream.close();

        return "Download Complete...";

    } catch (MalformedURLException e) {
        e.printStackTrace();
        return "ERROR MalformedURLException" + e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return "ERROR IOException" + e.getMessage();
    }

}

A: Go on your device to the Settings for your app and switch the Permission toggle for Storage to On.

A: SOLVED: just change your folder path to
"/sdcard/insertyourpreferredfoldername/"

and it creates the folder internal. Adjust the
downloaded_file.jpg

variable to your filename you get from the server and it will save the files seperately!
EDIT: Thanks to greenapps
 for leading me the right way!


text:
Q: what is the optimal Multithreading scenario for processing a long file lines? I have a big file and i want to read and also [process] all lines (even lines) of the file with multi threads.
One suggests to read the whole file and break it to multiple files (same count as threads), then let every thread process a specific file. as this idea will read the whole file, write it again and read multiple files it seems to be slow (3x I/O) and i think there must be better scenarios,
I myself though this could be a better scenario:
One thread will read the file and put the data on a global variable and other threads will read the data from that variable and process. more detailed:
One thread will read the main file with running func1 function and put each even line on a Buffer: line1Buffer of a max size MAX_BUFFER_SIZE and other threads will pop their data from the Buffer and process it with running func2 function. in code:
Global variables:
#define MAX_BUFFER_SIZE 100
vector<string> line1Buffer;
bool continue = true;// to end thread 2 to last thread by setting to false
string file = "reads.fq";

Function func1 : (thread 1)
void func1(){
 ifstream ifstr(file.c_str());
 for (long long i = 0; i < numberOfReads; i++) { // 2 lines per read
    getline(ifstr,ReadSeq);
    getline(ifstr,ReadSeq);// reading even lines
    while( line1Buffer.size() == MAX_BUFFER_SIZE )
        ; // to delay when the buffer is full
    line1Buffer.push_back(ReadSeq);
 }
 continue = false;
 return;
}

And function func2 : (other threads)
void func2(){
 string ReadSeq;
 while(continue){
    if(line2Buffer.size() > 0 ){
        ReadSeq  = line1Buffer.pop_back();
        // do the proccessing....
    }
 }
}

About the speed:
If the reading part is slower so the total time will be equal to reading the file for just one time(and the buffer may just contain 1 file at each time and hence just 1 another thread will be able to work with thread 1). and if the processing part is slower then the total time will be equal to the time for the whole processing with numberOfThreads - 1 threads. both cases is faster than reading the file and writing in multiple files with 1 thread and then read the files with multi threads and process...
and so there is 2 question:
1- how to call the functions by threads the way thread 1 runs func1 and others run func2 ?
2- is there any faster scenario?
3-[Deleted] anyone can extend this idea to M threads for reading and N threads for processing? obviously we know :M+N==umberOfThreads is true
Edit: the 3rd question is not right as multiple threads can't help in reading a single file
Thanks All

A: What is your bottleneck?  Hard disk or processing time?
If it's the hard disk, then you're probably not going to get any more performance out as you've hit the limits of the hardware.  Concurrent reads are by far faster than trying to jump around the file.  Having multiple threads trying to read your file will almost certainly reduce the overall speed as it will increase disk thrashing.
A single thread reading the file and a thread pool (or just 1 other thread) to deal with the contents is probably as good as you can get.

Global variables:

This is a bad habit to get into.

A: An other approach could be interleaved thread.
Reading is done by every thread, but only 1 at once.
Because of the waiting in the very first iteration, the
threads will be interleaved.
But this is only an scaleable option, if work() is the bottleneck
(then every non-parallel execution would be better)
Thread:
while (!end) {
    // should be fair!
    lock();
    read();
    unlock();

    work();
}

basic example: (you should probably add some error-handling)
void thread_exec(ifstream* file,std::mutex* mutex,int* global_line_counter) {
    std::string line;
    std::vector<std::string> data;
    int i;
    do {
        i = 0;
        // only 1 concurrent reader
        mutex->lock();
        // try to read the maximum number of lines
        while(i < MAX_NUMBER_OF_LINES_PER_ITERATION && getline(*file,line)) {
            // only the even lines we want to process
            if (*global_line_counter % 2 == 0) {
                data.push_back(line);
                i++;
            }
            (*global_line_counter)++;

        }
        mutex->unlock();

        // execute work for every line
        for (int j=0; j < data.size(); j++) {
            work(data[j]);
        }

        // free old data
        data.clear();
     //until EOF was not reached
   } while(i == MAX_NUMBER_OF_LINES_PER_ITERATION);

}

void process_data(std::string file) {
     // counter for checking if line is even
     int global_line_counter = 0;
     // open file
     ifstream ifstr(file.c_str());
     // mutex for synchronization
     // maybe a fair-lock would be a better solution
     std::mutex mutex;
     // create threads and start them with thread_exec(&ifstr, &mutex, &global_line_counter);
     std::vector<std::thread> threads(NUM_THREADS);
     for (int i=0; i < NUM_THREADS; i++) {
         threads[i] = std::thread(thread_exec, &ifstr, &mutex, &global_line_counter);
     }
     // wait until all threads have finished
     for (int i=0; i < NUM_THREADS; i++) {
         threads[i].join();
     }
}

A: Assume having #p treads, two scenarios mentioned in the post and answers:
1) Reading with 'a' thread and processing with other threads, in this case #p-1 thread will process in comparison with only one thread reading. assume the time for full operation is jobTime and time for processing with n threads is pTime(n) so:
worst case occurs when reading time is very slower than processing and  jobTime = pTime(1)+readTime and the best case is when the processing is slower than reading in which jobTime is equal to pTime(#p-1)+readTime
2) read and process with all #p threads. in this scenario every thread needs to do two steps. first step is to read a part of the file with size MAX_BUFFER_SIZE which is sequential; means no two threads can read at one time. but the second part is processing the read data which can be parallel. this way in the worst case jobTime is pTime(1)+readTime as before (but*), but the best optimized case is pTime(#p)+readTime which is better than previous.
*: in 2nd approach's worst case, however reading is slower but you can find a optimized MAX_BUFFER_SIZE in which (in the worst case) some reading with one thread will overlaps with some processing with another thread. with this optimized MAX_BUFFER_SIZE the jobTime will be less than pTime(1)+readTime and could diverge to readTime

A: First off, reading a file is a slow operation so unless you are doing some superheavy processing, the file reading will be limiting.
If you do decide to go the multithreaded route a queue is the right approach. Just make sure you push in front an pop out back. An stl::deque should work well. Also you will need to lock the queue with a mutex and sychronize it with a conditional variable.
One last thing is you will need to limit the size if the queue for the scenario where we are pushing faster than we are popping.